texts: WPF: Model to View Model data binding to implement Two Step View

texts:
I am trying to use Two Step View pattern in WPF. The problem is about keeping things in sync – I need a way to data-bind models to view models. Are there any good existing solutions? My approach is to introduce Property<T> to be used this way:

public abstract class TextField : ObservableObject
{
    public Property<bool> IsEnabled { get; set; } = true;
    public Property<string> Text { get; set; } = false;
    // etc.
}

Where property supports databinding updates:

public class Property<T> : ObservableObject
{
    public static implicit operator Property<T>(T value) => new Property<T>(() => value);
    public static implicit operator T(Property<T> property) => property.Value;

    public Property(Func<T> getter, params INotifyPropertyChanged[] dataSources)
        : this(getter, v => { throw new NotSupportedException(); }, dataSources)
    {
    }

    public Property(Func<T> getter, Action<T> setter, params INotifyPropertyChanged[] dataSources)
    {
        Getter = getter;
        Setter = setter;
        foreach (var dataSource in dataSources)
            dataSource.PropertyChanged += (s, e) => RaisePropertyChanged("Value");
    }

    public T Value
    {
        get { return Getter(); }
        set { Setter(value); }
    }

    Func<T> Getter { get; }
    Action<T> Setter { get; }
}

I use helper method Bind in the following way for view model construction:

        var model = new DocumentModel();
        var viewModel = new TextField
        {
           Text = model.Bind(m => m.FullName),
           IsEnabled = model.Bind(m => m.FullName != "")
        };

Where bind defined as:

public static class Binding
{
    public static Property<TTarget> Bind<TSource, TTarget>(this TSource source, Expression<Func<TSource, TTarget>> mapper)
        where TSource : INotifyPropertyChanged
    {
        Mapping<TSource, TTarget> mapping = mapper;
        return new Property<TTarget>(() => mapping[source], v => mapping[source] = v, source);
    }
}

Where Mapping compiles getter and setter from the expression:

class Mapping<TSource, TTarget>
{
    public static implicit operator Mapping<TSource, TTarget>(Expression<Func<TSource, TTarget>> mapping) =>
        new Mapping<TSource, TTarget>(mapping);

    [DebuggerHidden]
    public Mapping(Expression<Func<TSource, TTarget>> mapper)
    {
        Field = mapper.Parameters[0].Name;
        Getter = mapper.Compile().Invoke;

        try
        {
            var newValue = Expression.Parameter(mapper.Body.Type);
            var assign = Expression.Lambda<Action<TSource, TTarget>>(
                Expression.Assign(mapper.Body, newValue),
                mapper.Parameters[0], newValue);

            Setter = assign.Compile().Invoke;
        }
        catch(ArgumentException)
        {
        }
    }

    public string Field { get; }

    public TTarget this[TSource source]
    {
        get { return Getter(source); }
        set { Setter(source, value); }
    }

    Func<TSource, TTarget> Getter { get; }
    Action<TSource, TTarget> Setter { get; }
}

It works somehow:

 <DataTemplate DataType="{x:Type f:TextField}">
    <TextBox
        Text="{Binding Path=Text.Value, UpdateSourceTrigger=PropertyChanged}"
        IsEnabled="{Binding Path=IsEnabled.Value}"/>
 </DataTemplate>

Does it look ugly? Two Step View helps me a lot…


texts:
I hate to have to write a custom exists promise every time I need to know if a file exists, so I came up with this. Thoughts?

var Promise = require("bluebird")
var fs = Promise.promisifyAll(require("fs"))

function fsExists(_path){
  return fs.lstatAsync(_path)
  .then(function(){ return true })
  .catch(function(){ return false })
}

module.exports = fsExists


texts:
Basically I have a 2d list containing movies. Movies are specified by name, version and description. For example

['Jaws', 1, 'Movie about sharks']  - where Jaws = name, 1 = version and Movie about sharks = description.

My result is a dictionary which contains a map between name and description. But name should be updated to contain the version for e.g

['Jaws', 2, 'Movie about more sharks'] - should now be :

{'JawsV2': 'Movie about more sharks'}

Is there a more pythonic way to do this?

def movie_version_map():
    movies =  [['Jaws', 1, 'Movie about sharks'],
               ['Jaws', 2, 'Movie about more sharks'],
               ['HarryPotter', 1, 'Movie about magic'],
               ['HarryPotter', 4, 'Movie about more magic']]
    for movie in movies:
        if movie[1] != 1:
            movie[0] = ''.join([movie[0], 'V',str(movie[1])])

    newversion = dict([(movie[0],movie[2]) for movie in movies])
    return newversion

Output

{'Jaws': 'Movie about sharks', 'HarryPotter': 'Movie about magic', 'HarryPotterV4': 'Movie about more magic', 'JawsV2': 'Movie about more sharks'}


texts: List of integer factorization into n terms

texts:
I want the fastest way in Mathematica 7 to generate a list of the factors (not prime factors) of an integer into a specified number of terms, with each factor greater than one.

For example, 240 into three terms:

{{2,2,60}, {2,3,40}, {2,4,30}, {2,5,24}, {2,6,20}, {2,8,15}, {2,10,12},
 {3,4,20}, {3,5,16}, {3,8,10}, {4,4,15}, {4,5,12}, {4,6,10}, {5,6,8}}

My starting code is based on a recursive method the source of which I have forgotten, but probably someone on projecteuler.net:

f[n_, 1, ___] := {{n}}

f[n_, k_, x_: 2] :=
 Join @@ Table[
   If[q < x, {}, {q, ##} & @@@ f[n/q, k - 1, q]],
   {q, # ~Take~ ⌈Length@#/k⌉ & @ Divisors @ n}
 ]

f[240, 3]

Memoization can be applied in several places.  In the case of large integers this is much faster, at the expense of memory usage of course.  Here, with memoization at three points:

Clear[f, div]

div@n_ := div@n = Divisors@n

div[n_, k_] := div[n, k] = # ~Take~ ⌈Length@#/k⌉ & @ div @ n

f[n_, 1, ___] := {{n}}

f[n_, k_, x_: 2] := f[n, k, x] =
 Join @@ Table[
   If[q < x, {}, {q, ##} & @@@ f[n/q, k - 1, q]],
   {q, n~div~k}
  ]

Compared to Sasha's code on a large composite integer:

f[10080^2, 5] // Length // Timing

   {0.891, 103245}

FactorIntoFixedTerms[10080^2, 5] // Length // Timing

   {25.594, 103245}

Can this be further improved?


texts:
I have a library function that returns a pair of two numbers like this

def library_function(x0, x1):
    return x0**2 + x1**2, 10*x0*x1 + 1

(Actually, it is a function that returns predicted probabilities of two classes for some object, but it doesn't matter, so I created an artificial one.) I want to draw contours where the difference between two numbers returned by library_function is zero. To do so, I have to create a two-dimensional list (or array) with the differences.

I have the following possibilities:

X0 = np.linspace(-10, 10, 200)
X1 = np.linspace(-10, 10, 200)

results = [[(lambda u: u[0]-u[1])(library_function(x0, x1))
            for x0 in X0] for x1 in X1]
plt.contour(X0, X1, results, [0])

This approach is concise but I have to introduce lambda which seem to be considered not so Pythonic.

Another way:

values = [[library_function(x0, x1) for x0 in X0] for x1 in X1]
results = [[a-b for a, b in row] for row in values]

I have to introduce temporary two-dimensional list and this approach is longer.

Are there any ideas how to do it better (more concise and readable)?


texts: Calling synchronous code in asynchronous method

texts:
I'm implementing an interface with the async method Execute. In this I need to call some synchronous code. (removing an item from a dictionary). What would be the best way to go about this?

Alternative 1.

internal class ClearClaimByClaimIdCache : IListenTo<ClaimStatusChangedEvent>
{
        private readonly ICache<Guid, Claim> _cache;

        public ClearClaimByClaimIdCache(ICacheFactory cacheFactory)
        {
            _cache = cacheFactory.GetOrCreateCache<Guid, Claim>("ClaimByClaimId");
        }

        public Task Execute(ClaimStatusChangedEvent @event)
        {
            _cache.Remove(@event.ClaimId);
            return Task.CompletedTask;
        }
}

Alternative 2.

public Task Execute(ClaimStatusChangedEvent @event)
{
    return Task.Run(() => _cache.Remove(@event.ClaimId));
}

Alternative 3.

public async Task Execute(ClaimStatusChangedEvent @event)
{
    await Task.Run(() => _cache.Remove(@event.ClaimId));
}

Or any better way?


texts: Parse YAML file with nested parameters as a Python class object

texts:
I would like to use a YAML file to store parameters used by computational models developed in Python. An example of such a file is below:

params.yaml

reactor:
  diameter_inner: 2.89 cm
  temperature: 773 kelvin
  gas_mass_flow: 1.89 kg/s

biomass:
  diameter: 2.5 mm                # mean Sauter diameter (1)
  density: 540 kg/m^3             # source unknown
  sphericity: 0.89 unitless       # assumed value
  thermal_conductivity: 1.4 W/mK  # based on value for pine (2)

catalyst:
  density: 1200 kg/m^3                            # from MSDS sheet
  sphericity: 0.65 unitless                       # assumed value
  diameters: [[86.1, 124, 159.03, 201], microns]  # sieve screen diameters
  surface_areas:
    values:
      - 12.9
      - 15
      - 18
      - 24.01
      - 31.8
      - 38.51
      - 42.6
    units: square micron

Parameters for the Python model are organized based on the type of computations they apply to. For example, parameters used by the reactor model are listed in the reactor section. Units are important for the calculations so the YAML file needs to convey that information too.

I'm using the PyYAML package to read the YAML file into a Python dictionary. To allow easier access to the nested parameters, I use an intermediate Python class to parse the dictionary values into class attributes. The class attributers are then used to obtain the values associated with the parameters. Below is an example of how I envision using the approach for a much larger project:

params.py

import yaml

class Reactor:

    def __init__(self, rdict):
        self.diameter_inner = float(rdict['diameter_inner'].split()[0])
        self.temperature = float(rdict['temperature'].split()[0])
        self.gas_mass_flow = float(rdict['gas_mass_flow'].split()[0])

class Biomass:

    def __init__(self, bdict):
        self.diameter = float(bdict['diameter'].split()[0])
        self.density = float(bdict['density'].split()[0])
        self.sphericity = float(bdict['sphericity'].split()[0])

class Catalyst:

    def __init__(self, cdict):
        self.diameters = cdict['diameters'][0]
        self.density = float(cdict['density'].split()[0])
        self.sphericity = float(cdict['sphericity'].split()[0])
        self.surface_areas = cdict['surface_areas']['values']

class Parameters:

    def __init__(self, file):

        with open(file, 'r') as f:
            params = yaml.safe_load(f)

        # reactor parameters
        rdict = params['reactor']
        self.reactor = Reactor(rdict)

        # biomass parameters
        bdict = params['biomass']
        self.biomass = Biomass(bdict)

        # catalyst parameters
        cdict = params['catalyst']
        self.catalyst = Catalyst(cdict)

example.py

from params import Parameters

pm = Parameters('params.yaml')

# reactor
d_inner = pm.reactor.diameter_inner
temp = pm.reactor.temperature
mf_gas = pm.reactor.gas_mass_flow

# biomass
d_bio = pm.biomass.diameter
rho_bio = pm.biomass.density

# catalyst
rho_cat = pm.catalyst.density
sp_cat = pm.catalyst.sphericity
d_cat = pm.catalyst.diameters
sa_cat = pm.catalyst.surface_areas

print('\n--- Reactor Parameters ---')
print(f'd_inner = {d_inner}')
print(f'temp = {temp}')
print(f'mf_gas = {mf_gas}')

print('\n--- Biomass Parameters ---')
print(f'd_bio = {d_bio}')
print(f'rho_bio = {rho_bio}')

print('\n--- Catalyst Parameters ---')
print(f'rho_cat = {rho_cat}')
print(f'sp_cat = {sp_cat}')
print(f'd_cat = {d_cat}')
print(f'sa_cat = {sa_cat}')

This approach works fine but when more parameters are added to the YAML file it requires additional code to be added to the class objects. I could just use the dictionary returned from the YAML package but I find it easier and cleaner to get the parameter values with a class interface.

So I would like to know if there is a better approach that I should use to parse the YAML file? Or should I organize the YAML file with a different structure to more easily parse it?


texts: Simple Caesar cipher cryptanalysis in Ruby

texts:
I really like Ruby and want to get better at it. Any input is appreciated.

Description

This program prompts the user for a string which is ciphertext resulting from a Caesar cipher given (English) plaintext and a key on the range [0, 25]. The program then uses a table of character frequencies of the English language to perform simple cryptanalysis to determine the top 5 most probable shift keys, and displays the resulting plaintext when these keys are used to decrypt the ciphertext.

It should also be noted that the only input expected is letters and whitespace, but I think it works with most punctuation.

Code:

class Cryptanalysis
  def initialize
    @alphabet = ('A'..'Z').to_a.join

    @english_frequency = { :A => 0.080, :B => 0.015, :C => 0.030,
                           :D => 0.040, :E => 0.130, :F => 0.020,
                           :G => 0.015, :H => 0.060, :I => 0.065,
                           :J => 0.005, :K => 0.005, :L => 0.035,
                           :M => 0.030, :N => 0.070, :O => 0.080,
                           :P => 0.020, :Q => 0.002, :R => 0.065,
                           :S => 0.060, :T => 0.090, :U => 0.030,
                           :V => 0.010, :W => 0.015, :X => 0.005,
                           :Y => 0.020, :Z => 0.002 }
  end

  def decrypt_caesar(ciphertext, shift)
    i = shift % @alphabet.size
    decrypt = @alphabet
    encrypt = @alphabet[i..-1] + @alphabet[0...i]

    ciphertext.tr(encrypt, decrypt)
  end

  def analyze(ciphertext)
    chars = ciphertext.gsub(/[^A-Z]/i, '').split(//)
    ciphertext_frequency = character_frequency(chars)

    correlation_of_frequency = Hash.new

    alphabet = @alphabet.split(//)
    (0..25).each { |i|
      sum = 0.0
      alphabet.each { |c|
        e = alphabet.index(c)
        sum += ciphertext_frequency[c.to_sym] * @english_frequency[alphabet[(26 + e - i) % 26].to_sym]
      }
      correlation_of_frequency[i] = sum
    }

    correlation_of_frequency.sort_by { |_, v| -v }.take(5).to_h
  end

  def character_frequency(chars)
    frequency = Hash.new
    inc = 1.0 / chars.size

    @alphabet.each_char { |c| frequency[c.to_sym] = 0.0  }
    chars.each          { |c| frequency[c.to_sym] += inc }

    frequency
  end
end

crypt = Cryptanalysis.new

puts 'Enter a string to analyze'
text = gets.chomp.upcase
result = crypt.analyze(text)

puts 'Top 5 possible shifts: '
choice = 1

result.each do |k, v|
  puts '%10s) Shift amount: %2s Correlation: %%%.4f Result: %s' % [choice, k, v, crypt.decrypt_caesar(text, k)]
  choice += 1
end


texts: Different versions of the Operate method

texts:
I have code that basically is the same, but depending on the number of arguments you provide (up to 5), it will operate with them in a very repetitive way. I have the feeling that this can be optimized in some way, since maintaining and creating all the overloads by hand is a tedious and error-prone task.
The code is 5 versions (overloads) of the Operate method. As you can see, it increasingly deal with 2, 3, 4 and 5 arguments (each one is of a given type), so it can adapt from 2 to 5 type arguments.
public static Either<ErrorList, TResult> Operate<T1, T2, TResult>(Either<ErrorList, T1> a, Either<ErrorList, T2> b,
    Func<T1, T2, Either<ErrorList, TResult>> onSuccess)
{
    var success = from av in a.RightValue
                  from bv in b.RightValue
                  select onSuccess(av, bv);
    var errorList = new[]
        {
            a.LeftValue,
            b.LeftValue,
        }
        .SelectMany(x => x.ToEnumerable())
        .Aggregate((x, y) => new ErrorList(x.Concat(y)));

    return success.ValueOr(() => errorList);
}

public static Either<ErrorList, TResult> Operate<T1, T2, T3, TResult>(Either<ErrorList, T1> a,
    Either<ErrorList, T2> b, Either<ErrorList, T3> c,
    Func<T1, T2, T3, Either<ErrorList, TResult>> onSuccess)
{
    var success =
        from av in a.RightValue
        from bv in b.RightValue
        from cv in c.RightValue
        select onSuccess(av, bv, cv);

    var errorList = new[]
        {
            a.LeftValue,
            b.LeftValue,
            c.LeftValue,
        }
        .SelectMany(x => x.ToEnumerable())
        .Aggregate((x, y) => new ErrorList(x.Concat(y)));

    return success.ValueOr(() => errorList);
}

public static Either<ErrorList, TResult> Operate<T1, T2, T3, T4, TResult>(Either<ErrorList, T1> a, Either<ErrorList, T2> b, Either<ErrorList, T3> c, Either<ErrorList, T4> d,
    Func<T1, T2, T3, T4, Either<ErrorList, TResult>> onSuccess)
{
    var success = from av in a.RightValue
                  from bv in b.RightValue
                  from cv in c.RightValue
                  from dv in d.RightValue
                  select onSuccess(av, bv, cv, dv);

    var errorList = new[]
        {
            a.LeftValue,
            b.LeftValue,
            c.LeftValue,
            d.LeftValue,
        }
        .SelectMany(x => x.ToEnumerable())
        .Aggregate((x, y) => new ErrorList(x.Concat(y)));

    return success.ValueOr(() => errorList);
}

public static Either<ErrorList, TResult> Operate<T1, T2, T3, T4, T5, TResult>(
    Either<ErrorList, T1> a,
    Either<ErrorList, T2> b,
    Either<ErrorList, T3> c,
    Either<ErrorList, T4> d,
    Either<ErrorList, T5> e,
    Func<T1, T2, T3, T4, T5, Either<ErrorList, TResult>> onSuccess)
{
    var success = from av in a.RightValue
        from bv in b.RightValue
        from cv in c.RightValue
        from dv in d.RightValue
        from ev in e.RightValue
        select onSuccess(av, bv, cv, dv, ev);

    var errorList = new[]
        {
            a.LeftValue,
            b.LeftValue,
            c.LeftValue,
            d.LeftValue,
            e.LeftValue,
        }
        .SelectMany(x => x.ToEnumerable())
        .Aggregate((x, y) => new ErrorList(x.Concat(y)));

    return success.ValueOr(() => errorList);
}

Is there a better way to do this without repeating almost the same code? Imagine that I would like to create another overload for 6, 7, 8... arguments. It can be really tricky and sub-optimal.


texts:
I'm dynamically selecting elements in jQuery, how can I make it more resilient?

$('[data-example="' + exampleData + '"]').each(...);

I'm concerned that the data might contain special characters.


texts:
I have a method within a class that validates all proxy addresses are valid on initialization. I've tried to refactor this a bit, but this seems to be the best I can do. Any suggestions and/or tips as to how I can possibly improve this method?

def valid?(proxies)
  return false if !proxies.is_a?(Array) || proxies.empty?
  ipv4_address = /^((\d{1,3}[\.]){3}\d{1,3}:\d+)$/
  proxies.each do |proxy|
    return false if proxy !~ ipv4_address
    octets = proxy.scan(/\d+/).map(&:to_i).first(4)
    return false unless octets.all? { |octet| octet.between?(0, 255) }
  end
  true
end


texts: Test to see if installed and if not, install it

texts:
Okay all you Linux/shell folks out there. This is my first shell script (2nd if you count "Hello World") and would appreciate some feedback.

Basically, I need to test whether htop is installed; if it is, then move on; if it is not, then install it. If the user is root then just do it, and if not, sudo and install it. I have "borrowed" code from here to stitch this together. It works in my test environment. I would like to know:

What did I miss? What other variables do I need to account for? Are there better ways to go about this?

if ! [ -x "$(command -v htop)" ]; then
    # set the var SUDO to "" (blank)
    SUDO=""
        # if the user ID is not 0 (root is 0)
        if [ $EUID != "0" ] ; then
        # set the var SUDO to "sudo"
        SUDO="sudo"
        fi
    # Let the user know it is not installed & then install it, using sudo if not root
    echo 'Error: htop is not installed.' && $SUDO apt install htop >&1
    # exit the script
    exit 0
fi


texts: Calculating distance and angle between two points, C# program

texts:
I like to think I'm an intermediate programmer, but I learned to code with the Unity engine so I'm still getting used to not using it, and I've never had someone review my code before. I don't know any other programmers, most people in my town don't even have a computer. I'd appreciate it greatly if you'd be so kind and tell me what you think of my little script here. Rather, be brutal if you want.

My script works fine, but I have some concerns, like the readability of calling a Boolean method with a bunch of parameters in the condition of a while loop for example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Course_Assignment
{
class DistanceCalculator
{
    /// <summary>
    /// This class calculates the distance between two points and the angle of the slope.
    /// </summary>

    static void Main(string[] args)
    {
        float point1X = 0;
        float point1Y = 0;
        float point2X = 0;
        float point2Y = 0;

        float deltaX = 0;
        float deltaY = 0;

        double distance = 0;
        double angle;

        Console.WriteLine("Welcome. This program calculates the distance \nbetween two points as well as their angle.\nPlease type the prompted values.");

        //GetPoints() defines all the point coordinates via user input and
        //returns true if the data entered was invalid.
        NewPoints : while (GetPoints(ref point1X, ref point1Y, ref point2X, ref point2Y))
        {
            Console.WriteLine("Invalid data has been entered. Try again.");
        }

        //Getting the change in x and y from point 1 to 2.
        deltaX = point2X - point1X;
        deltaY = point2Y - point1Y;

        //Calc() uses the Pythagorean Theorem to calculate and return
        //distance, and calculates angle in degrees by multiplying the
        //tangent of deltaX and deltaY.
        distance = Calc(deltaX, deltaY, out angle);

        //Displaying calculations
        Console.WriteLine("\nDistance: {0:N3}\nAngle: {1:N3} degrees\nWould you like to calculate new points? (y,n)", distance, angle);

        //User decides whether or not to do new calculations.
        string newCalc = Console.ReadLine().ToLower();

        if (newCalc.Equals("y") || newCalc.Equals("yes"))
        {
            goto NewPoints;
        }
        else return;
    }

    static bool GetPoints(ref float newPoint1X, ref float newPoint1Y, ref float newPoint2X, ref float newPoint2Y)
    {

        bool invalid = false;

        //Prompts user for coordinates and sets the cursor in front of the
        //prompt for neatness, then checks validity of user input
        Console.WriteLine("\nPoint 1\nX Coordinate: ");
        Console.SetCursorPosition(14, Console.CursorTop - 1);
        if (!float.TryParse(Console.ReadLine(), out newPoint1X))
        {
            invalid =  true;
            return invalid;
        }
        Console.WriteLine("Y Coordinate: ");
        Console.SetCursorPosition(14, Console.CursorTop - 1);
        if (!float.TryParse(Console.ReadLine(), out newPoint1Y))
        {
            invalid = true;
            return invalid;
        }

        Console.WriteLine("Point 2\nX Coordinate: ");
        Console.SetCursorPosition(14, Console.CursorTop - 1);
        if (!float.TryParse(Console.ReadLine(), out newPoint2X))
        {
            invalid = true;
            return invalid;
        }
        Console.WriteLine("Y Coordinate: ");
        Console.SetCursorPosition(14, Console.CursorTop - 1);
        if (!float.TryParse(Console.ReadLine(), out newPoint2Y))
        {
            invalid = true;
            return invalid;
        }

        return invalid;
    }

    static double Calc(float deltaX, float deltaY, out double angle)
    {
        double newDistance = Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
        angle = (Math.Atan2(deltaY, deltaX)) * (180 / Math.PI);
        return newDistance;
    }
}
}


texts: Store nested json repsonses in relational database

texts:
The goal is to collect market data from a free rest api. The response is in json and size per response is above 1MB. I want to get at least updated data once per minute which means about 24h * 60min * 1MB ~ 1.5GB per day of json data. Since i have to collect data over a few weeks in order to start analysing market patterns i have to store the json responses in a space efficient way --> SQLite is my idea so far. Now the ugly part is dealing with nested (4 levels) json and insert it into a relational database.

json example:

{
    'country-id': 1,
    'name': 'USA',
    'states': [
    {
        'country-id': 1,
        'name': 'Alaska',
        'state-id': 11,
        'cities': [
        {
            'state-id': 11,
            'name': 'Anchorage',
            'city-id': 111,
            'streets':
            [
                {
                    'city-id': 111,
                    'name': 'Ingra St.',
                    'street-id': 1111
                }
            ]
        },
        {
            'state-id': 11,
            'name': 'Fairbanks',
            'city-id': 112,
            'streets':
            [
                {
                    'city-id': 112,
                    'name': 'Johansen Expy',
                    'street-id': 1121
                }
            ]
        }
        ]
    },
    ]
}

My approach:

from dataclasses import dataclass
from typing import List

@dataclass
class Country:
    def __init__(self, country_json):
        self.country_id: int = country_json['country-id']
        self.name: str = country_json['name']
        self.states: List(State) = [State(state) for state in country_json['states']]

@dataclass
class State:
    def __init__(self, state_json):
        self.country_id: int = state_json['country_id']
        self.name: str = state_json['name']
        self.state_id: int = state_json['state_id']
        self.cities: List(City) = [City(city) for city in state_json['cities']]

@dataclass
class City:
    def __init__(self, city_json):
        self.state_id: int = city_json['state-id']
        self.name: str = city_json['name']
        self.city_id: int = city_json['city-id']
        self.streets: List(Street) = [Street(street) for street in city_json['street']]

@dataclass
class Street:
    def __init__(self, street_json):
        self.city_id: int = street_json['city-id']
        self.name: str = street_json['name']
        self.street_id: int = street_json['street-id']

Next steps would be to add functions to each dataclass that store the values in a SQlite DB. I am really not sure if my general approach is efficient or if there is a better solution for this kind of problem. My idea in general was that if i build it like this i can easily add other steps e.g. data validation.


texts:
I've made a program that works, but i want to make it reusable. This code reads in a dictionary object created in another class (that i made), as well as read in a text file to put in said dictionary object. The code then loads in another text file, compares it with the dictionary, updates its frequency values and outputs to a vector. Everything works, but as i said i'm looking to make it reusable. What i mean by this is once the values have been stored in the vector, i'd like the dictionaries frequency values to reset back to 0, ready for the next text document to be compared with the dictionary, then output that to a different vector - this process will be repeated 10-12 times.

String Counter

public class StringCounter {

private LinkedList<Integer> list = new LinkedList<>();

public StringCounter(LinkedList<Integer> list) {
    this.list = list;
}

public static void main(String[] args) {

    HashMap<String, Integer> dictionary = new HashMap<String, Integer>();

    List<String> textFileList = Arrays.asList("Test.txt", "Test2.txt");

    try {

        Dictionary reader = new Dictionary(dictionary);

        for (String text : textFileList) {
            reader.fileScanner(text);
        }

        Scanner textFile = new Scanner(new File("Test4.txt"));
        ArrayList<String> file = new ArrayList<String>();

        while(textFile.hasNext()) {
            file.add(textFile.next().trim().toLowerCase());
        }

        for(String word : file) {
            Integer dict = dictionary.get(word);
            if (!dictionary.containsKey(word)) {
                    dictionary.put(word, 1);
            } else {
                    dictionary.put(word, dict + 1);
            }
        }

        textFile.close();

        } catch(FileNotFoundException e){
            e.printStackTrace();
        }

    Vector<Integer> vec1 = new Vector<>(dictionary.values());

    for (Integer count : vec1) {
        System.out.println(count);
    }
}
}

Dictionary

public class Dictionary {
    // Declare set in a higher scope (making it a property within the object)
    private HashMap<String, Integer> dictionary = new HashMap<String, Integer>();

    // Assigns the value of the parameter to the field of the same name
    public Dictionary(HashMap<String, Integer> dictionary) {
        this.dictionary = dictionary;
    }

    // Gets input text file, removes white spaces and adds to dictionary object
    public void fileScanner(String textFileName) {
        try {

            Scanner textFile = new Scanner(new File(textFileName));

            while (textFile.hasNext()) {
                 dictionary.put(textFile.next().trim(), 0);
            }

            textFile.close();

        } catch (FileNotFoundException e) {
             e.printStackTrace();
        }
    }

    public void printDict(HashMap<String, Integer> dictionary) {
        System.out.println(dictionary.keySet());
    }
}


texts:
I've been trying to deal with a lot of duplicate code in the first web pages I've been working on and have been playing around with the prototype model, which I think is the 'right' way to go about it.

What I'm not sure about however is if this is the right way to re-use event handlers. For example:

function GeneralPageHandler(args) {
  this.args = args;

  this.eventHandlers();
}

GeneralPageHandler.prototype.eventHandlers = function() {
    $('#OK').click(function() {
      //Do something
    });
}

function SpecificPageHandler(args) {
  this.args = args;
  this.prototype = Object.create(GeneralPageHandler.prototype);
  this.prototype.constructor = GeneralPageHandler;

  GeneralPageHandler.call(this, this.args);
}

SpecificPageHandler.prototype.eventHandlers = function() {
  GeneralPageHandler.eventHandlers.call(this);

  $('#Select').change(function() {
    //Do something
  });
  $('#OK').click(function() {
    //Do something that might be different to the previous click handler
  }
}

For the most part this allows me to re-use event handlers for common page elements, but I have found I end up with multiple handlers being defined for the same elements, depending on the specific page's purpose.
I also find that I'm sometimes 'inheriting' event handlers which I don't particularly need on a specific page, but I think this might be more my misuse of the prototype model than anything else.

Does this seem a sensible way to go about re-using event handlers? Are there any ways that I could make this pattern more robust?


texts: Singly Linked List "Strange sorting" exercise

texts:
I'm currently working through "Algorithms in java" by Robert Sedgewick (3rd edition, german version) on my own and am trying to solve one of the exercises there.

One of these involves taking a singly linked list (type not specified) and rearranging the nodes. The sorting involves first having all nodes appear that were at "even" positions in the prior linked list and after that having all nodes appear that were at "uneven" positions in the prior linked list. All this while every node should keep their relative position. I chose to write this for a linked list with a null reference at its tail and a true node as head.

So short example: a list of values 4-5-7-3-2-1-null should rearrange to
4-7-2-5-3-1-null.

I wrote some code that worked (the strangeSort (Node x) method) but can't think of it as an elegant solution. I am convinced that there must be a way out there to make this neater, especially the for-loop in the strangeSort method. Base idea behind it was to make the original linked list basically 2 linked lists with different head nodes and then attaching one linked list at the end of the other.

The code:

public class Test {
    static class Node
    {
        int val; Node next;
        Node(int v){val=v;}
    }

    public static void main (String[] args)
    {
        /*Create Linked list of length N*/
        int N=Integer.parseInt(args[0]);
        Node head = new Node(0);
        Node x = head, x2;
        for (int i=1; i<N; i++, x = x2)
        {
            x2 = new Node(i);
            x.next = x2;
        }

        /*Prints out linked list for checking purposes*/
        for (Node t = head; t!=null; t=t.next)
        {
            System.out.print(t.val+" -> ");
        }

        /*Rearrange Linked list*/
        strangeSort(head);

        /*Prints out linked list after sorting for checking purposes*/
        System.out.println();
        for (Node t = head; t!=null; t=t.next)
        {
            System.out.print(t.val+" -> ");
        }

    }

    public static void strangeSort (Node x)
    {
        Node headu = x, heade = x.next;
        Node t,s;
        for (t=headu, s=heade ; t!=null && s!=null ; t=t.next , s=s.next)
        {
            if (t.next==null){break;}
            t.next = t.next.next;
            if (s.next ==null){break;}
            s.next = s.next.next;
        }
        if (t==null){t=heade;}
        else if (t.next==null){t.next = heade;}
    }
}

As you can see, the forloop of strangeSort contains a fairly inelegant way to make sure I don't get a NullPointerException in the end through the fact that I am traversing 2 nodes every iteration of the loop.


texts:
I've created a program where the user is, at first, presented with a window with a yellow circle (random size, random coordinates) and a Start button. Once the user presses Start, the circle, when hovered over, will turn red in color and when it is clicked, another circle (random size, random coordinates) will be generated and this process is repeated (without the Start button).

The circle is generated with a random size of minimum 10 and maximum 100. The circle will be fully visible in the JFrame.

Is there any room for improvement?

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Color;

import java.awt.geom.Ellipse2D;

import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.util.Random;

public class ClickGame {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                    System.exit(-1);
                }

                JFrame frame = new JFrame("Game - Click the circle!");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new Panel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setResizable(false);
                frame.setVisible(true);
            }
        });
    }
}

class Panel extends JPanel {   /* Main panel of Click game */

    Ellipse2D.Double circle;

    boolean hover = false;

    int randomSize = 0;
    int randomPositionX = 0;
    int randomPositionY = 0;

    public final static int MAX_SIZE = 100;
    public final static int MIN_SIZE = 10;

    public final static int WIDTH    = 500;
    public final static int HEIGHT   = 500;

    private Random rand = new Random();

    public Panel() {
        init();
        generateRandom();
    }

    public void init() {
        final JButton start = new JButton("Start");
        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                addMouseMotionListener(new MouseAdapter(){
                    public void mouseMoved(MouseEvent e) {
                        if(circle.contains(e.getPoint()))
                            hover = true;
                        else
                            hover = false;
                        repaint();
                    }
                });

                addMouseListener(new MouseAdapter(){
                    public void mouseClicked(MouseEvent e) {
                        if(circle.contains(e.getPoint()))
                            generateRandom();
                    }
                });
                remove(start);
                repaint();
            }
        });
        add(start);
    }

    public void generateRandom() {
        hover = false;
        randomSize = MIN_SIZE + (rand.nextInt(MAX_SIZE - MIN_SIZE) + 1);

        randomPositionX = rand.nextInt(WIDTH - randomSize);
        randomPositionY = rand.nextInt(HEIGHT - randomSize);
        circle = new Ellipse2D.Double(randomPositionY, randomPositionX, randomSize, randomSize);

        repaint();
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(WIDTH, HEIGHT);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(hover)
            g.setColor(Color.RED);
        else
            g.setColor(Color.YELLOW);
        g.fillOval(randomPositionY, randomPositionX, randomSize, randomSize);
    }

}


texts: Is returning promise form angular service bad?

texts:
What is the problem when I return a promise from angular service instead of Observable?
If it's a matter of any manipulation or side-effect, that I can easily do inside angular service itself. Then why I shouldn't return a promise over observable?

Here's my code for service class

public async getCountriesAsync(filter: PaginateFilter): Promise<Paginate<IdNameTypeModel>> {
return await this.http.get<Paginate<IdNameTypeModel>>(`/api/{version}/Types/{lang}/Countries${filter.url()}`)
  .pipe(map(response => {
    return response == null ? new Paginate<IdNameTypeModel>() : response;
  })).toPromise();
}

Using inside component

async loadCountries() {
  const filter = new PaginateFilter(this.data.pageIndex, this.data.pageSize);
  this.countries = await this.dldTypesService.getCountriesAsync(filter);
}


texts:
I have a registration form. Step 1 user creates an account. As user creates an account I need to authenticate user with the created account.

in my account.service.ts I have following.

Is this the best way to handle this? and how can improve this to handle errors from 2 different http calls?

  public createAccount(reg: CreateUserRequestModel): Observable<any> {
    return this.apiService.post('api/register/account', reg)
      .flatMap(()=>{
        return this.authenticationService.authenticate(reg.emailAddress, reg.password)
      }).map((response)=>{
        return response.json()
      })
      .catch((error: any) => {
        return Observable.throw(error.json());
      });
  }


texts:
I have completed my homework with directions as follows:

  Declare and implement a class named Binary. This class will have a
  method named printB(int n) that prints all binary strings of length n.
  For n = 3, it will print

000
001
010
011
100
101
110
111

  in this order.

Here is my code:

import java.util.Scanner;
class Binary
{

    String B;
    int temp;

    void printB(int n)
    {
        for(int i = 0; i < Math.pow(2,n); i++)
        {
            B = "";
            int temp = i;
            for (int j = 0; j < n; j++)
            {
                if (temp%2 == 1)
                    B = '1'+B;
                else
                    B = '0'+B;
                    temp = temp/2;
            }
            System.out.println(B);
         }
    }
}

class Runner
{
    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter n:");
        int n = in.nextInt();

        Binary myB = new Binary();

        myB.printB(n);
    }
}

My question is...is there anyway to make this shorter or more efficient?


texts:
I've created a MovingAverage class, but it is not optimized for performance at all. I care about performance a little bit because I'm using this class in trading (I collocate on exchange and so on and so on; let's talk about performance of this particular class).

How would you improve it for better performance?

interface Indicator
{
    double? Value { get; }
}

public class Candle
{

    public Candle(double value)
    {
        Minimum = value;
        Maximum = value;
    }

    public void ValueUpdated(double value)
    {
        if (value < Minimum)
        {
            Minimum = value;
        }
        if (value > Maximum)
        {
            Maximum = value;
        }
    }

    public double Maximum { get; private set; }
    public double Minimum { get; private set; }

    public double Median
    {
        get { return (Maximum + Minimum) / 2; }
    }
}

public class MovingAverage : Indicator
{
    private int _length;
    public Queue<Candle> _candles;
    private Candle _newestCandle;
    private double _sumExceptNewest;

    /**
     * only median supported now
     */
    public MovingAverage(int length)
    {
        _length = length;
        _candles = new Queue<Candle>(length);
    }

    public void Add(double val)
    {
        if (_candles.Count == _length)
        {
            _sumExceptNewest -= _candles.Dequeue().Median;
        }
        if (_candles.Count > 0)
        {
            _sumExceptNewest += _newestCandle.Median;
        }
        // TODO: avoid new
        _newestCandle = new Candle(val);
        _candles.Enqueue(_newestCandle);
        RecalculateValue();
    }

    public void Modify(double val)
    {
        if (_newestCandle == null)
        {
            Add(val);
        }
        else
        {
            _newestCandle.ValueUpdated(val);
            RecalculateValue();
        }
    }

    private void RecalculateValue()
    {
        Value = (_sumExceptNewest + _newestCandle.Median)/_candles.Count;
    }

    public double? Value { get; private set; }

    public void CheckValueAndPrintDelta()
    {
        double result = 0;
        foreach (var candle in _candles)
        {
            result += candle.Median;
        }
        result /= _candles.Count;
        Console.WriteLine("checked MA Value = " + Value + " Should be = " + result +
            " delta (1 = 100%) = " + (Value - result) / result);
    }

}


texts: Best way to construct a semantic HTML table?


texts:
I've made a small skeleton for a larger project that will include cross-platform multithreading (by using Boost) and thread-safe random numbers (by using GNU scientific libraries and mutexes).  My goal is to run a simulation (probably over 100,000 loops) in which each thread will utilize a random number and read from a library that the threads will not change the value of (thus, I don't bother putting the library in a mutex)!

Is this code alright?

#include <stdio.h> // Standard in out for c
#include <vector> // Vectors
#include <boost/thread.hpp> // Boost threads
#include <boost/signals2/mutex.hpp> // Boost mutexes
#include <gsl/gsl_rng.h> // Gnu Scientific Library, thread safe rand

const gsl_rng_type * T = gsl_rng_default; // Select random generator
gsl_rng * r = gsl_rng_alloc (T); // Allocate the range
boost::mutex mtx; // Create a mutex
std::vector<unsigned long> data; // Create a vector

int count=23; // Have a total number of threadFunctions you want to loop through
int CORES = static_cast<int>(boost::thread::hardware_concurrency());

void threadFunction(int id);

int main()
{
    printf("Number of cores = %d\n-------------------\n\n",CORES);
    gsl_rng_env_setup(); // Setup the random variable environment
    gsl_rng_set (r,time(NULL)); // Seed the r generator
    std::vector<boost::thread *> t; // Create vector of boost::thread pointers
    while(count>0){ // While you are looping
        for(int i=0;i<((CORES>count?count:CORES));i++) // Create 4 threads if more than 4 loops are left, else create the appropriate number of threads
            t.push_back(new boost::thread(threadFunction,i)); // Push threads objects back
        for(int i=0;i<t.size();i++){ // Loop through all threads
            t[i]->join(); // Wait to join.  Note, these are pointers so use -> instead of .
            count--; // Reduce count by 1
        }
        t.resize(0); // Empty the array
    }

    printf("\nEnd of threads...");
    FILE *out = fopen("RandomNumbers.txt","w+"); // Create a file to hold values
    for(int i=0;i<data.size();i++) // Print out values
        fprintf(out,"%lu\n",data[i]);
    fclose(out); // Close file
    printf("\nPress Enter to exit...");
    getchar();
    return 0;
}

void threadFunction(int id)
{
    { // By scoping in, the lock_guard can destroy itself upon exit
        boost::lock_guard<boost::mutex> ownlock(mtx); // Create lock_guard
        data.push_back(gsl_rng_get(r)); // Put a random number in data
    }
    printf("Working on %d...\n",id);
}


texts: Best practice to initialize instance variables for a POJO when values are null

texts:
I am using Java 8. I haven't found another question that fits mine exactly, and I've come across some conflicting information on best practices with what I'm trying to do.

I'm creating a POJO which is essentially a business object - to be returned by my API - that will have its fields initialized from another object.

I'm using the @Data lombok annotation to generate the getters/setters/toString.

I'm wondering which of the following options would align with best practices:

Note: It is guaranteed that authUser will be not null when calling the User constructor.

1. Null-checks with if-statements and default field values

@Data
public class User {
    private String userId = "";
    private String fullName = "";
    private String email = "";
    private Set<String> roles = Collections.emptySet();

    public User(AuthUser authUser, Set<String> roles) {
        if (authUser.getUserId() != null) {
            this.userId = authUser.getUserId();
        }

        if (authUser.getFullName() != null) {
            this.fullName = authUser.getFullName();
        }

        if (authUser.getEmail() != null) {
            this.email = authUser.getEmail();
        }

        if (roles != null) {
            this.roles = roles;
        }
    }
}

I feel like this is a safe/generic way to do this, and I could store the values retrieved from the getters to local variables so the get calls aren't redundant.

2. Null-checks using ternaries with redundant get calls

@Data
public class User {
    private String userId;
    private String fullName;
    private String email;
    private Set<String> roles;

    public User(AuthUser authUser, Set<String> roles) {
        this.userId = authUser.getUserId() == null ? "" : authUser.getUserId();
        this.fullName = authUser.getFullName() == null ? "" : authUser.getFullName();
        this.email = authUser.getEmail() == null ? "" : authUser.getEmail();
        this.roles = roles == null ? Collections.emptySet() : roles;
    }
}

The purpose of this is to reduce code-cluttering, but I believe Clean Code argues against ternaries, so I'd probably not prefer this option for the sake of readability.

3. Null-checks with Optionals without redundant get calls

@Data
public class User {
    private String userId;
    private String fullName;
    private String email;
    private Set<String> roles;

    public User(AuthUser authUser, Set<String> roles) {
        this.userId = Optional.ofNullable(authUser.getUserId()).orElse("");
        this.fullName = Optional.ofNullable(authUser.getFullName()).orElse("");
        this.email = Optional.ofNullable(authUser.getEmail()).orElse("");
        this.roles = Optional.ofNullable(roles).orElse(Collections.emptySet());
    }
}

The purpose of this is to reduce code-cluttering and redundant get calls without creating local variables in order to remove that redundancy. I think this is preferable to ternaries but am not sure.

4. Null-checks with Apache StringUtils.defaultString and CollectionUtils.emptyIfNull

@Data
public class User {
    private String userId;
    private String fullName;
    private String email;
    private Set<String> roles;

    public User(AuthUser authUser, Set<String> roles) {
        this.userId = StringUtils.defaultString(authUser.getUserId());
        this.fullName = StringUtils.defaultString(authUser.getFullName());
        this.email = StringUtils.defaultString(authUser.getEmail());
        this.roles = CollectionUtils.emptyIfNull(roles);
    }
}

This a little shorter than using Optionals, but I feel like using native Java is preferable to third-party libraries (ApacheUtils is already included as a dependency).


texts: Good way to write extend method of a contructor?

texts:
I've been following along a blog post on JavaScript inheritance. I wanted to slightly adapt this and try to write something more like I've seen in Backbone (extend method). See I set about it, and run into problems. Then I came across this SO post. It was so much simpler. So after some minor tweaks to that I set about writing a way each extended constructor could have their own extend method (inherited from Base). This is what I have:

var Base = function(name){
    this.name = name;
}
Base.prototype.extend = function(new_constructor){
    //new_constructor.prototype = new this.constructor();
    new_constructor.prototype = Object.create(this.constructor.prototype);
    new_constructor.prototype.constructor = new_constructor;

    return new_constructor;
}

var Robot = Base.prototype.extend(function(name, material){
    Base.call(this, name)
    this.material = material
    this.type = 'robot';
});

var T1000 = Robot.prototype.extend(function(options){
    Robot.call(this, options.name, options.material)
    this.guns = options.guns;
    this.type = 'killer robot';
});

robot = new Robot("Boutros", "metal");
t1000 = new T1000({name: "Arnie", material:"flesh/metal", guns:3});

console.log(robot)
console.log(t1000)

Anyway seems to work, but I'm a little new to this. Can anyone suggest any limitations with this approach. Also, I'd like to move the [Constructor].call out of the new constructor function and into the extend function so this is handled automatically, not sure if I can. Would appreciate your feedback.

Btw, here is my jsFiddle


texts:
The model takes a long time to run. I have tried to vectorise it as far as I can, but it's still taking about a day to compute. I'm wondering if it's possible to speed it up.

Maybe the problem isn't even with the code, but with the model being improper/bad priors/...? Or maybe the data set is simply very large and supposed to take hours to compute. Either way, for now, I dread adding another predictor.

# data is in wide format, one row with one outcome and a range of predictors

set_cppo(mode = "fast")

code ="                     // the model itself
data        {
       int<lower=1> nrow;   // 72000 (3 items per W*N*R)
       int W;               // n words; 24
       int N;               // n subjects; 100
       int R;               // n raters; 10
       int<lower=1,upper=nrow> ind[nrow]; // this vector is used to index fields per row
       int<lower=0,upper=1> responses[nrow];  // outcomes
       int subjects[nrow];
       int words[nrow];
       int sex[nrow];
       int languages[nrow];
       int raters[nrow];
}

parameters  {
real intercept;               // "fixed"
real beta_language;
real beta_sex;
real interaction_s_l;
real beta_rater[R];           // "random"
real beta_word[W];
real beta_subject[N];
}

model       {
real theta[nrow];

 beta_word ~ normal(0,100);         // priors
 beta_subject ~ normal(0,100);
 beta_language ~ normal(0,100);
 beta_sex ~ normal(0,100);
 interaction_s_l ~ normal(0,100);

for (i in 1:nrow){                    // for each row, construct theta
theta[i] <- intercept
          + beta_sex * sex[ind[i]]
          + beta_language * languages[ind[i]]
          + interaction_s_l * languages[ind[i]] * sex[ind[i]]
          + beta_subject[subjects[ind[i]]]
          + beta_rater[raters[ind[i]]];}

responses ~ bernoulli_logit(theta);   // sample
}

generated quantities {               // get odds ratios
real odds_intercept;
real odds_sex;
real odds_language;
real odds_interaction;

odds_intercept <- exp(intercept);
odds_sex <- exp(beta_sex);
odds_language <- exp(beta_language);
odds_interaction <- exp(interaction_s_l);
}
"

fit <- stan(model_code = code, data = dat,     // run the model
            iter = 4000, chains = 3)


texts:
I have a form that displays a list of days in a given month that looks like so:

All the text boxes are set as readonly, which is the desired functionality.
While setting enabled to false works, it gives the control a blurred out look, which is difficult to override. In order to complete them, I want to keep the user from being able to select any text.

I have bound the KeyUp and MouseUp events in the following code:

private void dateDisplay_MouseUp(object sender, MouseEventArgs e)
{
    this.dateDisplay.SelectionStart = this.dateDisplay.Text.Length;
}

private void dateDisplay_KeyUp(object sender, KeyEventArgs e)
{
    this.dateDisplay.SelectionStart = this.dateDisplay.Text.Length;
}

where dateDisplay is the left textbox.

And this what the other textbox looks like with text selected, without being wired up to any events:

This code prevents the user from selecting any text inside the text boxes by forcing the cursor to end of the text box. Is there a better way of doing this?


texts: Finding consecutive days in an array of dates

texts:
The problem:

How to get the largest number of consecutive days from an array of unknown number of Date objects, by taking into account days only like 4th of April, 5th of April and so on.

Example input data:

let calendar = Calendar.current
let x1 = Date()
let x2 = calendar.date(byAdding: .day, value: 1, to: x1)!
let x3 = calendar.date(byAdding: .day, value: 1, to: x2)!
let x4 = calendar.date(byAdding: .day, value: 1, to: x3)!
let x5 = calendar.date(byAdding: .day, value: 1, to: x4)!
let x6 = calendar.date(byAdding: .day, value: 1, to: x5)!

let x7 = calendar.date(byAdding: .hour, value: 1, to: x4)!
let x8 = calendar.date(byAdding: .hour, value: 2, to: x4)!
let x9 = calendar.date(byAdding: .hour, value: 3, to: x2)!
let x10 = calendar.date(byAdding: .hour, value: 4, to: x2)!

var dates = [Date]()
dates.append(x1)
dates.append(x5)
dates.append(x2)
dates.append(x3)
dates.append(x4)
dates.append(x6)

dates.append(x7)
dates.append(x8)
dates.append(x9)
dates.append(x10)

Expected result from the sample data: 6 consecutive days

How this solution could be improved?

Solution:

dates.sort(by: < )

// extract only unique days
var dateIndex = 0
var nextDateIndex = 1

repeat {
    let date = dates[dateIndex]
    let nextDate = dates[nextDateIndex]
    if calendar.isDate(nextDate, inSameDayAs: date) {
        dates.remove(at: nextDateIndex)
    } else {
        dateIndex += 1
        nextDateIndex += 1
    }
} while (dateIndex < dates.count - 1)

print(dates)

let aDayInSeconds: TimeInterval = 86_400
let twoDaysInSeconds: TimeInterval = 172_800

var consecutiveDaysCount = 1
dateIndex = 0
nextDateIndex = 1

// count consecutive days
repeat {
    guard (i + 1 < dates.count) else { break }
    let date = dates[dateIndex]
    let nextDate = dates[nextDateIndex]

    if nextDate.timeIntervalSince(date) >= aDayInSeconds && nextDate.timeIntervalSince(date) < twoDaysInSeconds {
        dateIndex += 1
        nextDateIndex += 1
        consecutiveDaysCount += 1
    } else {
        break
    }
} while (i < newDates.count - 1)

print(consecutiveDaysCount)


texts:
I have 4 CSV files that i need to process (filter out Part segment and then merge them) but the problem is that they do not fit in my memory. So I decided to: [open - filter - write out] each one of theses 4 files and merge them after reopening the filtered version.
I learned that it was good practice to decouple the functionality (filter functionality, merge functionality, write out functionality) but in this case splitting filter and dumping out functionality seem silly, it would be like wrapping an existing function  from pandas library.
But merging the 2 functionality make me also uncomfortable since I have heard that it is not good practice to write functions that return and have side effect (as writing out a CSV) as follow:
def exclude_segm_part(f):
    """ Filter out "Part client" on credit selection and write it on disk

    Args:
        f (string): filepath of the credit base (csv)
    """
    df = pd.read_csv(f,sep=';',encoding="latin")
    df_filter = df[df.LIB_SEGM_SR_ET!="PARTICULIERS"]
    filename = "{base}.txt".format(base=os.path.basename(f).split(".txt")[0])
    df_filter.to_csv(filename,index=False,sep=';')
    return df_filter

What would be your suggestion? (Hope my question is clear enough, I want to get the good practice of coding in data science environment)


texts:
This is my function for determining the Longest Substring between two strings in Java.

public class Main {
    public static String longestSubstring(String str1, String str2){
        int row = str1.length();
        int col = str2.length();

        int[][] checker = new int[row][col];

        int max = 0;
        int r = 0;
        int c = 0;
        for(int i=0; i < row; i++){
            for(int j=0; j < col; j++){
                if(str1.charAt(i) == str2.charAt(j)){
                    if((i -1 > 0) && (j -1 >0)){
                        checker[i][j] = checker[i-1][j-1] +1;

                    }else{
                        checker[i][j]++;
                    }
                    max = checker[i][j];
                    r = i;
                    c = j;

                }else continue;
            }
        }
        StringBuilder sb = new StringBuilder();
        while(true){
            if(checker[r][c] == 0) break;
            sb.append(str1.charAt(r));
            r--;
            c--;
        }
        return sb.reverse().toString();

    }

    public static void main(String[] args) {
    // write your code here
        String str1 = "adedfrgyu";
        String str2 = "arvbfrgykset";

       String str3 = "aaaaaaatyuieo";
       String str4 = "aaaaaklui";

        System.out.println(longestSubstring(str1, str2));
    }
}

The code compiles, but wondering is the algorithm is correct. It passes all the test cases that I could make up.


texts:
Hello everyone!
Here is the thing. So I wanted at first to create Robot class, I want him to move around some board. Maybe 10x10 or something like that, then i wanted to invent a Robot fights class, I want to add class players (becuase i want to play between player 1 and player 2) but here it is what I have so much.
Lets focus on this code because I want it to make it much better then start to create robot fights!
class Robot:

    def __init__(self, name, place, start = (0,0), power = 9):
        self.name = name
        self.start = start
        self.place = place
        self.power = power

    def get_name(self):
        return self.name

    def get_start(self):
        return self.start

    def get_place(self):
        return self.place

    def get_power(self):
        return self.power

    def set_name(self, x):
        if isinstance(x, str):
            self.name = x
        else:
            raise TypeError("must be a string")

    def set_start(self, x):
        if isinstance(x, tuple):
            self.start = x
        else:
            raise TypeError("must be a tuple")

    def set_place(self, x):
        if isinstance(x, list):
            self.place = x
        else:
            raise TypeError("must be a list")

    def set_power(self, x):
        if isinstance(x, int):
            self.power = x
        else:
            raise TypeError("must a int")

    def check_power(self):
        if self.power <= 0:
            raise ValueError("No power")

    def left(self, value):
        self.check_power()

        self.power -= value

        if self.place[0] - value < 0:
            self.place[0] = self.place[0] - value + 8

        else:
            self.place[0] = self.place[0] - value

    def up(self, value):
        self.check_power()

        self.power -= value

        if self.place[1] + value > 7:
            self.place[1] = self.place[1] + value - 8

        else:
            self.place[1] = self.place[1] + value

        if self.place[1] == 5:
            self.power += 2

    def __str__(self):
        return self.name, self.place, self.power

Also want I want to make better in this one. Well power will be important in the Robot fights, because if some robot from player 1 will be near to robot from player 2 I want them to you know, fight, so the power will be pretty good right there, if they will be near to each other the power will decrease until the robot is destroyed. But lets focus on above code to make it better.
Any tips how to make this SHORTER and more neat, closer to a advanced or just better solution will be definitely on point.
Have a great day!


texts:
I am working on a small script for a mobile site.
Is there any way to improve on the regex here? or remove it completely?

function fn_page_change(event) {
    event.preventDefault();
    var activePage = $(".ui-active");
    var newPage = $(event.target.getAttribute("href"));
    activePage.className = activePage.className.replace(/(?:^|\s)ui-active(?!\S)/, " ui-inactive ");
    newPage.className = newPage.className.replace(/(?:^|\s)ui-inactive(?!\S)/, " ui-active");
}

I'm not using jQuery, the $ is myown

function $(selector, el) {
    if (!el) {
        el = document;
    }
    var tmp = el.querySelectorAll(selector);
    if (tmp.length === 1) {
        return tmp[0];
    }
    return tmp;
}

Here is an example


texts: Class for working with users and passwords in a PHP CMS

texts:
I'm working on CMS in PHP just for fun. Right now I'm trying to implement class for working with users/passwords. I had been reading lot of articles about hashing and as far as I understood crypt() function are the best(most secure) for now.

class Users {
    private static $key, $table, $logtable;

    public static function init($key) {
        self::$key = $key;
        self::$table = DBPREFIX.$key.'s';
        self::$logtable = self::$table.'_access_log';
    }

    public static function isLogged() {
        if(isset($_SESSION[self::$key])) {
            if(isset($_SESSION[self::$key]['uid'])) {
                $uid = intval($_SESSION[self::$key]['uid']);
                $user = DB::select()->from(self::$table)->where('id', '=', $uid)->execute()->object();
                if(count($user) > 0) {
                    return true;
                }
                else {
                    return false;
                }

            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    }

    public static function userExist($login) {
        $user = DB::select()->from(self::$table)->where('login', '=', $login)->execute()->object();
        if(count($user) > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    public static function getUser($login) {
        $user = DB::select()->from(self::$table)->where('login', '=', $login)->execute()->object();
        if(count($user) > 0) {
            return $user[0];
        }
        else {
            return false;
        }
    }

    public static function generateHash($password) {
        $salt = self::generateSalt();
        $hashedPassword = crypt($password, $salt);
        return array('hashed_password' => $hashedPassword, 'salt' => $salt);
    }

    private static function generateSalt() {
        $blowfishPre = '$2y$10$';
        $blowfishEnd = '$';
        $allowedChars ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./';
        $charsLength = strlen($allowedChars);
        $saltLength = 20;
        $salt = "";
        for($i=0; $i < $saltLength; $i++)
        {
            $salt .= $allowedChars[mt_rand(0,$charsLength)];
        }
        $bcrypt_salt = $blowfishPre . $salt . $blowfishEnd;
        return $bcrypt_salt;
    }

    public static function comparePasswords($input, $uid) {
        $user = DB::select()->from(self::$table)->where('id', '=', $uid)->execute()->object();
        if(count($user) > 0) {
            $user = $user[0];
            $password = $user->password;
            return crypt($input, $password) === $password;
        }
        else {
            return false;
        }
    }

    public static function userExit() {
        if(isset($_SESSION[self::$key])) {
            unset($_SESSION[self::$key]);
        }
    }

    public static function changePassword($password, $uid) {
        $newPassword = self::generateHash($password);
        if(isset($newPassword['hashed_password']) && isset($newPassword['salt'])) {
            DB::update(self::$table)->set(array('password' => $newPassword['hashed_password'], 'salt' => $newPassword['salt']))->where('id', '=', $uid)->execute();
        }
    }

    public static function updateTime($uid) {
        DB::update(self::$table)->set(array('last_login' => time()))->where('id', '=', $uid)->execute();
    }

    public static function writeAccessLog($uid, $success) {
        if($success) {
            DB::insert(self::$logtable)->set(array('admin_id' => $uid, 'date' => time(), 'success' => '1'))->execute();
        }
        else if(!$success) {
            DB::insert(self::$logtable)->set(array('admin_id' => $uid, 'date' => time(), 'success' => '0'))->execute();
        }
    }
}

Please, take a look and let me know if I doing something wrong.


texts: Splitting a long string based on its graphical presentation

texts:
I got a long string, let's call it Story.
I fetch this story from a database so I don't know how long it is.

I want to display this story in a view, but what if the story is too long so it doesn't fit in one view?

I don't want to adjust the font size because it may be a very long story and making the font size smaller is not a good solution.

Therefore I want to split the Story into more than one view.
By passing the story and getting a separated story as an array of String every item in the array can fit in one view.

This is the code, it hopefully gives you a hint what I'm trying to achieve exactly:

extension String {

    /// - returns: The height that will fit Self
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
        return ceil(boundingBox.height)
    }

    #warning("it's so slow that i can't handle it in main thread , ( 21 second for 15 items in array )")
    /// complition contains the separated string as array of string
    func splitToFitSize(_ size : CGSize = UIScreen.main.bounds.size ,font : UIFont = UIFont.systemFont(ofSize: 17) , complition : @escaping (([String]) -> Void) )  {
        DispatchQueue.global(qos: .background).async {

            // contents contains all the words as Array of String
            var contents = self.components(separatedBy: .whitespaces)

            var values : [String] = []
            for content in contents {
                // if one word can't fit the size -> remove it , which it's not good, but i don't know what to do with it
                guard content.isContentFit(size: size , font : font) else {contents.removeFirst(); continue;}
                if values.count > 0 {
                    for (i , value) in values.enumerated() {
                        var newValue = value
                        newValue += " \(content)"
                        if newValue.isContentFit(size: size, font: font) {
                            values[i] = newValue
                            contents.removeFirst()
                            break;
                        }else if i == values.count - 1 {
                            values.append(content)
                            contents.removeFirst()
                            break;
                        }
                    }
                }else {
                    values.append(content)
                    contents.removeFirst()
                }
            }
            complition(values)
        }
    }

    /// - returns: if Self can fit the passing size
    private func isContentFit(size : CGSize, font : UIFont) -> Bool{
        return self.height(withConstrainedWidth: size.width, font: font) < size.height
    }
}

This code is working, but it takes very long.
If I want to split a story to 15 views it takes 20 seconds or even longer.

How can I optimize this so it runs faster?


texts: Function to toggle between two values of an enum

texts:
I have this code, but it looks a bit verbose:

enum MonitoringMode
{
    Seek,
    Destroy
}

void ToggleMonitoringMode()
{
    if (_monitoringMode == MonitoringMode.Seek)
        _monitoringMode = MonitoringMode.Destroy;
    else
    if (_monitoringMode == MonitoringMode.Destroy)
        _monitoringMode = MonitoringMode.Seek;
}

There are some well known idioms to toggle between two values, like:

bitwiseBoolean ^= bitwiseBoolean; // bit toggle
boolean = !boolean;               // boolean toggle
oneOrZero = 1 - oneOrZero;        // numeric toggle

Is there a similar, less verbose way to get the same result? I am not sure using the int value of enums would be safe or even "elegant" in C#.


texts: Performance of object-to-string conversion

texts:
Using an OR/M I map a lot of rows from database to array of objects (~300k). In these objects some properties are marked with special attribute [Signed]. Row-by-row I combine them in string, calculate salted MD5 of string and compare to hash I received from database.

Everything was working pretty okay for a long time, but now my website started to work quite slow and I run a profiler. It says the slowest method of whole website is ValueToString. I optimized it as much as I can. Is it possible to optimize it more? I want to mention I do not need exact string representation so feel free to change formatters.

Another question if I will redesign everything from string to byte[] - will it speed up the process, what do you think?

static string ValueToString(object value)
{
    if (value == null)
        return "";

    string value_string = value as string;
    if (value_string != null)
        return value_string;

    int value_int;
    if (value is Enum) {
        value_int = (int)value;
        if (value_int >= 0 && value_int <= 255)
            return hexStringTable[((int)value)];
        if (value_int == -1)
            return "FFFFFFFF";
        // Actually, we are never here.
        return value_int.ToString("X");
    }

    decimal value_decimal;
    if (TryCast(value, out value_decimal))
        return value_decimal.ToString().TrimEnd('0');

    if (TryCast(value, out value_int))
        return value_int.ToString("X");

    DateTime value_DateTime;
    if (TryCast(value, out value_DateTime))
        return value_DateTime.Ticks.ToString("X");

    // We are never here for slow table.
    return Convert.ToString(value,
        CultureInfo.InvariantCulture);
}

static bool TryCast<T>(object o, out T r)
{
    if (o is T) {
        r = (T)o;
        return true;
    }

    r = default(T);
    return false;
}

static readonly string[] hexStringTable = new string[]
{
    "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
    "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
    "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
    "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
    "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
    "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
    "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
    "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
    "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
    "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
    "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
    "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
    "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
    "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
    "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
    "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"
};


texts: Assigning parallel workers to predict from keras model using concurrent.futures

texts:
I am working on a Reinforcement learning project, where I have to gather a lot of data using a TensorFlow model. During the data gathering, the weights of the model do not change. So, I am using concurrent.futures.ProcessPoolExecutor to parallelize this work-flow. The following is an MWE of my implementation.
import tensorflow as tf
from tensorflow import keras

import numpy as np
import concurrent.futures
import time

def simple_model():
    model = keras.models.Sequential([
        keras.layers.Dense(units = 10, input_shape = [1]),
        keras.layers.Dense(units = 1, activation = 'sigmoid')
    ])
    model.compile(optimizer = 'sgd', loss = 'mean_squared_error')
    return model

def clone_model(model):
    model_clone = tf.keras.models.clone_model(model)
    model_clone.set_weights(model.get_weights())
    return model_clone

def work(model_path, seq):
    # model = clone_model(model)# model_list[model_id]
    # print(model)
    # import tensorflow as tf
    model = tf.keras.models.load_model(model_path)
    return model.predict(seq)

def workers(model, num_of_seq = 4):
    seqences = np.arange(0,num_of_seq*10).reshape(num_of_seq, -1)
    model_savepath = './simple_model.h5'
    model.save(model_savepath)
    path_list = [model_savepath for _ in range(num_of_seq)]

    with concurrent.futures.ProcessPoolExecutor(max_workers=None) as executor:
        t0 = time.perf_counter()
        # model_list = [clone_model(model) for _ in range(num_of_seq)]
        index_list = np.arange(1, num_of_seq)
        # [clone_model(model) for _ in range(num_of_seq)]
        # print(model_list)
        future_to_samples = {executor.submit(work, path, seq): seq for path, seq in zip(path_list,seqences)}
    Seq_out = []
    for future in concurrent.futures.as_completed(future_to_samples):
        out = future.result()
        Seq_out.append(out)
    t1 = time.perf_counter()
    print(t1-t0)
    return np.reshape(Seq_out, (-1, )), t1-t0

if __name__ == '__main__':
    model = simple_model()
    num_of_seq = 400
    out = workers(model, num_of_seq=num_of_seq)
    print(out)

Are there any better approaches to this problem?


texts: 3 last distinct values of a list taken from a list of dictionaries

texts:
I have a list of orders (each order is a dict) which looks like this (simplified version) :

[{'name' : XXX,
  'id' : { 'order_id_local' : 'xxx_001'}},
 {'name' : XXX,
  'id' : { 'order_id_local' : 'xxx_002'}},
 {'name' : XXX,
  'id' : {}},
 {'name' : XXX,
  'id' : { 'order_id_local' : 'xxx_002'}},
 {'name' : XXX,
  'id' : { 'order_id_local' : 'xxx_003'}},
  ...]

As you can see there could be duplicate for the key 'order_id_local' but also nothing.
What I would like to do is to get the last distinct 3 'order_id_local' in a list, beginning from the last one.
Here it will be ['xxx_0003', 'xxx_002', 'xxx_001'].

What i did is :

 id_orders = [x['id']['order_id_local'] for x in order_list if 'order_id_local' in x['id']]
 id_orders = [x for x in id_orders if x is not None]
 id_orders = list(reversed(sorted(set(id_orders))[-3:]))

It works but when i see this id_orders three times and those nested functions, i'm wondering if there is no a more efficient and pythonic way to do this.


texts: Generating row and column of a given nonogram-like table

texts:
What are nonogram tables?

  Nonograms, also known as Hanjie, Picross or Griddlers, are picture logic puzzles in which cells in a grid must be colored or left blank according to numbers at the side of the grid to reveal a hidden picture.

There are two kind of nonogram tables, ones with only one row and column, and kinds with multiple rows and columns. For simplicity's sake, I have assumed that nonogram table given has only one row and one column, and 5x5 only. That is why my table is only nonogram-like, a true nonogram table gives out two columns if a row is as if colored-blank-blank-blank-colored. But in my code if the nonogram table is like that, the column will be 2 instead of 1 1.

Anyways, the code, in which I have assumed that blank spaces are 0 and painted spaces are asterisk. Keep in mind that blank space can be any character.

def nono_descriptor(given_string):
    number_of_lines = given_string.count('\n') #number of line breaks
    length_of_string = len(given_string) #length of the given string

    if number_of_lines != 4 and length_of_string != 29:
        raise Exception("You need exactly four line breaks and 25 characters!") #throw exception if conditions don't match

    rows_split = [] #list that contains each line split
    columns_list = [] #list that contains columns
    rows_list = [] #list that contains rows

    list_of_lines = given_string.split('\n') #split the string by line break

    for each_line in list_of_lines:
        rows_split.append(list(each_line)) #populate rows list with split up characters
        columns_list.append(each_line.count('*')) #populate columns list with the number of asterisks in each column

    for i in range(5):
        temp_list = [row[i] for row in rows_split]
        rows_list.append(temp_list.count('*'))

    print (columns_list, rows_list)

nono_descriptor('0*0*0\n***00\n****0\n*0*0*\n****0')

Would love to hear your opinions.

Again, don't mistake this code as a nonogram table generator. It only generates a table similar to that of a nonogram.


texts:
(define (merge-sort lst (lt? <))
  (define (truthy=? a b)
    (eq? (not a) (not b)))

  (let sort ((lst lst)
             (size (length lst))
             (flip #f))
    (define (merge l r (res '()))
      (cond ((null? l) (append-reverse r res))
            ((null? r) (append-reverse l res))
            ((truthy=? (lt? (car r) (car l)) flip)
             (merge l (cdr r) (cons (car r) res)))
            (else
             (merge (cdr l) r (cons (car l) res)))))

    (if (<= size 1) lst
        (let*-values (((mid) (quotient size 2))
                      ((l r) (split-at lst mid)))
          (merge (sort l mid (not flip))
                 (sort r (- size mid) (not flip)))))))

Tested with Racket and Guile; requires SRFIs 1 and 11. (If you want to use this for Guile, you will need to adjust the syntax used for optional arguments.)

This version is tailored for Scheme in a number of ways:

The length of the list is calculated only once, at the beginning. At each split, the length of the split parts is passed to each recursive call.
The merge step uses a right-unfold rather than a left-unfold, to be tail-recursive. This results in a reversed list at each step.
Rather than reverse the list at each merge, I just keep a flag saying whether the lists are reversed. The merging step takes this flag into account and then does the right kind of merge to maintain sort stability.


texts: Sort a strings collection by a search term

texts:
I'm trying to implement a search bar in which the user sends a search term and the search bar displays the results.

I have a naive solution which separates the original list into three sublists:
a list with all the exact matches, a list with all the phrases containing the search term and a list with all the phrases that doesn't match. Later on I sort the unmatched list using Edit Distance algorithm.

Is this the right way to do it or should I concern a different approach such as suffix trees, etc. ?

public static <T> List<T> sortListByName(final String name, final List<T> itemsList,
      final Function<T, String> itemNameExtractor, int limit) {
    List<T> res = new LinkedList<>();
    List<T> containedList = new LinkedList<>();
    List<T> unmatchedList = new LinkedList<>();

    // First, separates the list into sublists which have exact word match; the search term is a
    // substring; the search term doesn't appear at all.

    for (T item : itemsList) {
      String currItemName = itemNameExtractor.apply(item);
      if (currItemName.contains(name)) {
        boolean isExactMatch = false;
        for (String term : currItemName.split(" ")) {
          if (term.equals(name)) {
            res.add(item);
            isExactMatch = true;
            break;
          }
        }
        if (!isExactMatch) {
          containedList.add(item);
        }
      } else {
        unmatchedList.add(item);
      }
    }
    Comparator<T> comparator = new Comparator<T>() {
      @Override
      public int compare(final T t1, final T t2) {
        Integer n1Length = itemNameExtractor.apply(t1).length();
        Integer n2Length = itemNameExtractor.apply(t2).length();
        return n1Length.compareTo(n2Length);
      }
    };

    Collections.sort(res, comparator);
    Collections.sort(containedList, comparator);
    res.addAll(containedList);

    if (res.size() >= limit) {
      return res.subList(0, limit);
    }

    // Sort unmatched items by their edit distance rank and concatenate them to the contained
    // matches list.
    List<T> editDistList = EditDist.sortList(name, unmatchedList, itemNameExtractor);

    res.addAll(editDistList);
    if (res.size() > limit) {
      return res.subList(0, limit);
    }

    return res;
  }


texts: Computing the sum of all measures for a certain group type

texts:
I have a method that receives 2 params:

first one is an array of objects of type { group1: string, group2: string, measure: number, ... }
second one is a string

I also have an enum GroupColumns
enum GroupColumns {
  ColumnTypeX = 'Column Type X',
  ColumnTypeY = 'Column Type Y',
  ColumnTypeZ = 'Column Type Z'
}

This method computes the sum of all the measures for a certain group type when the second parameter matches the second group and the first group is equal to any group found in GroupColumns enum.
    private ComputeSpecificColumnMeasure(data: Array<IDynamic<any>>, groupType: String): number {
        let measure: number = 0;
        data.forEach(el => {
            if (el.group2 === groupType && (el.group1 === GroupColumns.ColumnTypeX || el.group1 === GroupColumns.ColumnTypeY || el.group1 === GroupColumns.ColumnTypeZ )) {
                measure += el.measure;
            }
        });

        return measure;
    }

I do not like the verifications inside the if. If I somehow want to add more columns(unlikely) I would need to expand it, or create another method only to check if group1 is equal to any GroupColumns.
Any opinions?
How can I make this code scalable and optimized


texts:
I started learning Python these days and made my first code. Guess_The_Number and I would like some comments to improve or if I am on the right track. Thank you very much in advance
P.s: I am trying to create my own function.
def guess_number (answer):
    trys = 0

    while trys < 5:
        guessing = int(input("Your guessing is? "))
        if guessing == answer:
            print ("Yes!! it's Right!!")
            break
        elif guessing < answer:
            print ("Big")
        elif guessing > answer:
            print ("smaller")
        trys = trys+1

    if trys == 5:
        print("WoW, your trys are over  , try again!!")
        print("The number was ", answer)

print("Welcome to guess the number!!")
print("You have 5 trys to guess the number")
print("Good Luck!!")
print("I'm thiking in a number from 0 to 100")
print('')
import random
num_right = random.randint(0,100)
guess_number(num_right)


texts:
I request you to provide insightful suggestions to improve the following code as well as an alternative algorithm to solve it.
Problem Specification:

We'll say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the largest mirror section found in the given array.
maxMirror({1, 2, 3, 8, 9, 3, 2, 1}) → 3
maxMirror({1, 2, 1, 4}) → 3
maxMirror({7, 1, 2, 9, 7, 2, 1}) → 2

Solution:
public class MaxMirror {
    public static void main(String[] args) {
        MaxMirror max = new MaxMirror();
        int[] nums = { 1, 2, 1, 4 };
        System.out.println("The maximum length of the mirror is "
                + max.maxMirror(nums));
    }

    public int maxMirror(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        // Reverse order of the array
        int[] revNums = new int[nums.length];
        for (int numIndex = nums.length - 1, revIndex = 0; numIndex >= 0; numIndex--, revIndex++) {
            revNums[revIndex] = nums[numIndex];
        }
        // Hope the sub array of maximum length is the array itself
        int subArraysToBeChecked = 1;
        for (int len = nums.length; len > 1; len--) {
            if (mirrorOfLengthLenExists(nums, revNums, len,
                    subArraysToBeChecked)) {
                return len;
            }
            // Increase the number of sub-arrays to be checked
            subArraysToBeChecked++;
        }
        // In the worst case return 1
        return 1;
    }

    // Choose start and end i.e. sub-arrays to be checked
    public boolean mirrorOfLengthLenExists(int[] nums, int[] revNums, int len,
            int subArraysToBeChecked) {
        int start = 0;
        int end = len - 1;
        for (int i = len; i <= nums.length; i++) {
            if (mirrorExistsFromStartToEnd(nums, revNums, start, end,
                    subArraysToBeChecked)) {
                return true;
            }
            start++;
            end++;
        }
        return false;
    }

    // Check from start to end whether mirrored in the revNums
    public boolean mirrorExistsFromStartToEnd(int[] nums, int[] revNums,
            int start, int end, int subArraysToBeChecked) {
        int revStart = 0;
        for (int subArraysChecked = 1; subArraysChecked <= subArraysToBeChecked; subArraysChecked++) {
            int noOfElementsEqual = 0;
            for (int numIndex = start, revIndex = revStart; numIndex <= end; numIndex++, revIndex++) {
                if (revNums[revIndex] != nums[numIndex]) {
                    break;
                } else {
                    ++noOfElementsEqual;
                }
            }
            if (noOfElementsEqual == (end - start + 1)) {
                return true;
            }
            revStart++;
        }
        return false;
    }
}


texts:
I am trying to resolve below question in order to prepare for an interview xD

An XOR linked list is a more memory efficient doubly linked list.
Instead of each node holding next and prev fields, it holds a field
named both, which is an XOR of the next node and the previous node.
Implement an XOR linked list; it has an add(element) which adds the
element to the end, and a get(index) which returns the node at
index.

Please suggest how this implementation can be improved. Thank you in prior.
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int value;
    long both;

} StNode;
typedef StNode *pStNode;

pStNode add(pStNode lastNode, int value)
{
    pStNode newNode = (StNode *) malloc(sizeof(StNode));
    newNode->value = value;

    //[both]=value of previous node pointer if it is last node
    newNode->both = (long)lastNode;

    //calculating previous node [both] value
    lastNode->both = (long)newNode ^ lastNode->both;

    return newNode;
}

pStNode get(pStNode headNode, int index)
{
    pStNode prevNode;
    pStNode currNode;
    long tmp;

    //special handling
    //case: cur=1, prev=0
    //we have set previous node of head node value to be 0 manually
    currNode = (StNode *) ((headNode->both) ^ 0);
    prevNode = headNode;

    //skim through linked list
    for(int i=2; i<=index; i++)
    {
        tmp = (long)prevNode;
        prevNode = currNode;
        currNode = (StNode *)(currNode->both ^ tmp);
    }

    return currNode;
}

int main() {

    //I named first node as headNode, and last node as tailNode
    //create head node with both=0 since there is no previous node to it
    pStNode headNode = (StNode *) malloc(sizeof(StNode));
    headNode->both = 0;
    headNode->value = 2;

    //assign pointers
    pStNode tailNode = headNode;

    //lets add 10 nodes after head, and assign values
    for(int i=3; i<13; i++)
    {
        tailNode = add(tailNode, i);
    }

    //get node value where index=3
    pStNode iNode = get(headNode, 3);
    printf( "result: %d\n",  iNode->value);

    return 0;
}


texts: Iterating through one map and one multimap and printing the vlaue of common keys

texts:
I've got one multimap: mm1 and a map: mm2. The size of mm1 is usually expected to be smaller than mm2. So I begin by iterating through mm1, and for each key in mm1 that also exists in mm2, will print the values of them. e.g. in the following example, first I come up with 2 in mm1, which also exists in mm2; therefor I print "aa" and "bb" from mm1 and "b" from mm2. If we encounter any key in mm1 that cannot be found in mm2, the whole process will be stopped. Example:

(in each pair, number is key, string is value)

mm1:

  2, "aa"
  2, "bb"
  4, "cc"
  4, "dd"
  5, "ee"

mm2:

  1, "a"
  2, "b"
  3, "c"
  4, "d"
  6, "e"

output should be:

  aa
  bb
  b
  cc
  dd
  d

For the following input, 4 is not found in the second map and therefore we stop printing values after 2 (even though 5 exists in both of them, it's not printed).

mm1:

  2, "aa"
  2, "bb"
  4, "cc"
  4, "dd"
  5, "ee"

mm2:

  1, "a"
  2, "b"
  3, "c"
  5, "d"

output should be:

  aa
  bb
  b

And here is my code:

#include <map>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    multimap<int,string> mm1;
    mm1.insert(make_pair(2, "aa"));
    mm1.insert(make_pair(2, "bb"));
    mm1.insert(make_pair(4, "cc"));
    mm1.insert(make_pair(4, "dd"));
    mm1.insert(make_pair(5, "ee"));

    map<int,string> mm2;
    mm2.insert(make_pair(1, "a"));
    mm2.insert(make_pair(2, "b"));
    mm2.insert(make_pair(3, "c"));
    mm2.insert(make_pair(4, "d"));
    mm2.insert(make_pair(5, "e"));

    typedef multimap<int,string>::iterator Iter;

    pair<Iter, Iter> range1(mm1.begin(), mm1.begin());
    Iter next1 = mm1.begin();
    map<int,string>::iterator next2 = mm2.begin();

    range1 = mm1.equal_range(next1->first);
    while (!(range1.first == mm1.end() && range1.second == mm1.end()))
    {
        next2 = mm2.find(next1->first);
        if(next2 == mm2.end()) break;
        for (Iter itr = range1.first;itr!=range1.second;itr++)
        {
            cout << itr->second << endl;
        }
        cout << next2->second << endl;
        next1 = range1.second;
        next2++;
        if(next1 == mm1.end() || next2 == mm2.end())
            break;
        range1 = mm1.equal_range(next1->first);
    }
    return 0;
}

My intention was to iterate over each map only once. Any advice on improving the performance and size of this program would be appreciated!


texts:
I want to handle input like the following

ls -al | awk '{print $1}'

Now to parse it I couldn't tokenize at whitespace because of the quotations and I had to make a special case for awk instead. The code below successfully parses the command-line input. Is there a better way?

int handleToken(int awk, char *token, char *params[100], int i) {
    while (token != NULL) {
        if (awk == 1) {
            params[i++] = token;
            token = strtok(NULL, " ");
            awk = 0;
            continue;
        }
        if (strcmp(token, "awk") == 0) {
            params[i++] = token;
            awk = 1;
            token = strtok(NULL, "\'");
            continue;
        }
        params[i++] = token;
        token = strtok(NULL, " ");
    }
    params[i] = NULL;
    return i;
}


texts:
I've the following code which check for duplicate property and provide and warning when the key is exist and provide error if the key and the value have the same values.
The code have done some iteration and its working
my question is there is a way to avoid the if's statement's  ?

      Map<String, Object> existProp = requires.get(reqidx).getProperties();
        Optional<Map.Entry<String, Object>> foundProperty = properties.entrySet().stream().filter(property -> existProp.containsKey(property.getKey())).findFirst();
        if (foundProperty.isPresent()) {
            // Same key already exists
            LOG.warn("Property with key {} already exists in requires {}", foundProperty.get().getKey(), requires.get(reqidx).getName());
            // in case the existing property has the same value (check only for value of type String)
            if (foundProperty.get().getValue() instanceof String
                    && existProp.get(foundProperty.get().getKey()) instanceof String
                    && (foundProperty.get().getValue()).equals(existProp.get(foundProperty.get().getKey()))) {
                throw new Exception("Property " + foundProperty.get().getKey() + "  exists already with value " + foundProperty.get().getValue() + " in requires " + requiresName);
            }
        }
        return reqidx;
    }


texts:
I wrote a simple C++ template meta function for filtering out types from a list not matching a predicate. This is similar to Filtering variadic template arguments but does pattern matching instead of std::conditional with the aim of being faster. To that end no empty typelists are concatenated which should incur less instantiations and be faster according to https://blog.galowicz.de/2016/06/25/cpp_template_type_list_performance

The below code works for all my test cases. Any hints how to make it faster (less template instantiations), smaller, better, ...? (Note: Assume appropriate *_t using-templates)

template <typename... Ts>
struct typelist;

template <typename... TLists>
struct concat;
template <typename... Args1, typename... Args2>
struct concat<typelist<Args1...>, typelist<Args2...>>
{
    using type = typelist<Args1..., Args2...>;
};
template <class Seq1, class Seq2, class... Seqs>
struct concat<Seq1, Seq2, Seqs...> : concat<Seq1, concat_t<Seq2, Seqs...>>
{
};

template <class TList, template <typename> class Cond>
struct filter;
template<bool matches, template <typename> class Cond, typename...>
struct filter_helper;

template<template <typename> class Cond, typename T, typename... Ts>
struct filter_helper<true, Cond, T, Ts...>
{
    using type = concat_t<typelist<T>, filter_t<typelist<Ts...>, Cond>>;
};

template<template <typename> class Cond, typename T, typename... Ts>
struct filter_helper<false, Cond, T, Ts...>
{
    using type = filter_t<typelist<Ts...>, Cond>;
};

template<template <typename> class Cond, typename T, typename... Ts>
struct filter<typelist<T, Ts...>, Cond>
{
    using type = typename filter_helper<Cond<T>::value, Cond, T, Ts...>::type;
};

template<template <typename> class Cond>
struct filter<typelist<>, Cond>
{
    using type = typelist<>;
};

Some tests (TMP_ASSERT is like static_assert):

using list1 = tmp::typelist<int, double>;
using list2 = tmp::typelist<float>;
using list3 = tmp::typelist<double>;
using list4 = tmp::typelist<float, double, double>;
using list5 = tmp::typelist<double, float, double>;
using list6 = tmp::typelist<double, double, float>;
using empty = tmp::typelist<>;

template<typename T>
struct is_not_double: std::true_type{};
template<>
struct is_not_double<double>: std::false_type{};

TMP_ASSERT_SAME((tmp::filter_t<list1, is_not_double>), (tmp::typelist<int>));
TMP_ASSERT_SAME((tmp::filter_t<list2, is_not_double>), (tmp::typelist<float>));
TMP_ASSERT_SAME((tmp::filter_t<list3, is_not_double>), (tmp::typelist<>));
TMP_ASSERT_SAME((tmp::filter_t<list4, is_not_double>), (tmp::typelist<float>));
TMP_ASSERT_SAME((tmp::filter_t<list5, is_not_double>), (tmp::typelist<float>));
TMP_ASSERT_SAME((tmp::filter_t<list6, is_not_double>), (tmp::typelist<float>));
TMP_ASSERT_SAME((tmp::filter_t<empty, is_not_double>), (tmp::typelist<>));

Note: Code is from a library licensed under BSD 3-Clause.