texts:
I have written a simplified version of the Mars Rover challenge in Ruby. Please review it for best coding practices.

A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.
In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.

class Rover
  def initialize(x, y, direction)
    @x = x
    @y = y
    @direction = direction
  end

  def instruction(position)
    position.each do |input|
      if input == 'L'
        left
      elsif input == 'R'
        right
      else
        move
      end
    end
      puts "this is where the rover should be: x= #{@x} y= #{@y} facing= #{@direction}"
  end

  def right
    if @direction == 'S'
        puts "the rover is facing West."
      @direction = 'W'
    elsif @direction == 'N'
        puts "the rover is facting East"
      @direction = 'E'
    elsif @direction == 'W'
        puts "the rover is facting North"
      @direction = 'N'
    else
      puts "the rover is facing South"
      @direction = 'S'
    end
  end

  def left
    if @direction == 'N'
        puts "the rover is facing North."
      @direction = 'W'
    elsif @direction == 'W'
        puts "the rover is facting West"
      @direction = 'S'
    elsif @direction == 'E'
        puts "the rover is facting East"
      @direction = 'N'
    else
      puts "the rover is facing South"
      @direction = 'E'
    end
  end

  def move
    if @direction == 'N'
      @y += 1
    elsif @direction == 'E'
      @x += 1
    elsif @direction == 'S'
      @y -= 1
    else
      @x -= 1
    end
  end
end

#instance of our rovers with direction x, y, direction facing N, E, S, or W
mars_rover_a = Rover.new(0,0,'N')
# mars_rover_a.move()
mars_rover_b = Rover.new(1,1,'E')

#call the instruction for each instance of the object rover
mars_rover_a.instruction(['L','M','R','M','L','M','R','R','M'])
mars_rover_b.instruction(['R','M','M','L','M','L','L','M'])


texts: Check if a string is a permutation of a palindrome

texts:
I see a couple of these on codereview but I was hoping my way hasn't yet been encountered:

def is_palindrome_permutation(strng):
    cache = set()
    for char in strng.lower():
        if not char.isalpha():
            continue
        if char in cache:
            cache.remove(char)
        else:
            cache.add(char)

    return len(cache) <= 1

Instead of maintaining any counts of characters to check for oddness or evenness, simply add and remove characters from a set. A character repeated an even number of times will be removed from the set; a character repeated an odd number of times will remain in the set. If the final set has a length less than or equal to one, it is a permutation of a palindrome.


texts: Convenience function for writing files in CSV, JSON, etc

texts:
The McCabe code complexity of the following function is 19 as found by pytest --mccabe test.py (from my toy-project mpu). While I agree that this function is length and likely will become longer in future, I don't know how to improve the situation.

What it does

The code mpu.io.write(filepath) is a convenience function for writing a few common file formats.

Code

This code should work in Python 2 and 3.

def write(filepath, data, **kwargs):
    """
    Write a file.
    Supported formats:
    * CSV
    * JSON, JSONL
    * pickle
    Parameters
    ----------
    filepath : str
        Path to the file that should be read. This methods action depends
        mainly on the file extension.
    data : dict or list
        Content that should be written
    kwargs : dict
        Any keywords for the specific file format.
    Returns
    -------
    data : str or bytes
    """
    if filepath.lower().endswith('.csv'):
        kwargs_open = {'newline': ''}
        mode = 'w'
        if sys.version_info < (3, 0):
            kwargs_open.pop('newline', None)
            mode = 'wb'
        with open(filepath, mode, **kwargs_open) as fp:
            if 'delimiter' not in kwargs:
                kwargs['delimiter'] = ','
            if 'quotechar' not in kwargs:
                kwargs['quotechar'] = '"'
            with open(filepath, 'w') as fp:
                writer = csv.writer(fp, **kwargs)
                writer.writerows(data)
        return data
    elif filepath.lower().endswith('.json'):
        with io_stl.open(filepath, 'w', encoding='utf8') as outfile:
            if 'indent' not in kwargs:
                kwargs['indent'] = 4
            if 'sort_keys' not in kwargs:
                kwargs['sort_keys'] = True
            if 'separators' not in kwargs:
                kwargs['separators'] = (',', ': ')
            if 'ensure_ascii' not in kwargs:
                kwargs['ensure_ascii'] = False
            str_ = json.dumps(data, **kwargs)
            outfile.write(to_unicode(str_))
    elif filepath.lower().endswith('.jsonl'):
        print(filepath)
        with io_stl.open(filepath, 'w', encoding='utf8') as outfile:
            kwargs['indent'] = None  # JSON has to be on one line!
            if 'sort_keys' not in kwargs:
                kwargs['sort_keys'] = True
            if 'separators' not in kwargs:
                kwargs['separators'] = (',', ': ')
            if 'ensure_ascii' not in kwargs:
                kwargs['ensure_ascii'] = False
            for line in data:
                str_ = json.dumps(line, **kwargs)
                outfile.write(to_unicode(str_))
                outfile.write(u'\n')
    elif filepath.lower().endswith('.pickle'):
        if 'protocol' not in kwargs:
            kwargs['protocol'] = pickle.HIGHEST_PROTOCOL
        with open(filepath, 'wb') as handle:
            pickle.dump(data, handle, **kwargs)
    elif (filepath.lower().endswith('.yml') or
          filepath.lower().endswith('.yaml')):
        raise NotImplementedError('YAML is not supported, because you need '
                                  'PyYAML in Python3. '
                                  'See '
                                  'https://stackoverflow.com/a/42054860/562769'
                                  ' as a guide how to use it.')
    elif (filepath.lower().endswith('.h5') or
          filepath.lower().endswith('.hdf5')):
        raise NotImplementedError('HDF5 is not supported. See '
                                  'https://stackoverflow.com/a/41586571/562769'
                                  ' as a guide how to use it.')
    else:
        raise NotImplementedError('File \'{}\' is not known.'.format(filepath))


texts: Creating multiple new child forms from a single form

texts:
I have a simple application reading IO and plotting chart on UI. There is one instance that I need to plot three graphs at a time, and to make this easier, I made a graph form where I declared all non-fixed chart settings during form load and load it to chart as settings when the graph form is called as a new child form on the main/parent form.

Here is my code to call out graph form on parent form:

    System.Windows.Forms.Integration.WindowsFormsHost DemoTabContentMiniGraph1 = new System.Windows.Forms.Integration.WindowsFormsHost();
    System.Windows.Forms.Integration.WindowsFormsHost DemoTabContentMiniGraph2 = new System.Windows.Forms.Integration.WindowsFormsHost();
    System.Windows.Forms.Integration.WindowsFormsHost DemoTabContentMiniGraph3 = new System.Windows.Forms.Integration.WindowsFormsHost();

    // Create the window control.
    F_CWndw_Graph FormMiniGraph1 = new F_CWndw_Graph(true, false, false, false, 0.5, 100, 0.5, 10, "Time (s)", 20, 100, 100, "Flow Rate (l/s)", 2, true, "DEMO");
    F_CWndw_Graph FormMiniGraph2 = new F_CWndw_Graph(false, true, true, false, 0.5, 10, 0.5, 10, "Time (s)", 50, 250, 250, "Height (mm)", 3);
    F_CWndw_Graph FormMiniGraph3 = new F_CWndw_Graph(false, false, false, true, 0.5, 10, 0.5, 10, "Time (s)", 400, 2000, 2000, "Height (mm)", 4);

   // Assign the grid control as the host control's child.
   DemoTabContentMiniGraph1.Child = FormMiniGraph1;
   DemoTabContentMiniGraph2.Child = FormMiniGraph2;
   DemoTabContentMiniGraph3.Child = FormMiniGraph3;

   // Add the interop host control to the Grid
   Grid_miniGraph1.Children.Add(DemoTabContentMiniGraph1);
   Grid_miniGraph2.Children.Add(DemoTabContentMiniGraph2);
   Grid_miniGraph3.Children.Add(DemoTabContentMiniGraph3);

Will this be a good and safe way with UI programming, knowing that each of these graphs will run a timer ticking at 500ms to do the plotting of data?

And will those private variables inside the new child forms I created out of one layout form be totally separate/independent from each other?


texts: Create a collection of binaries with random set positions

texts:
I would like to create a collection of binaries with n set bits and total length should be between n and 31; also those set bits should be randomly positioned. For example if n = 3, then [1;0;1;0;1], [1;0;0;1;1;] and [1;1;1;0;0] should all be possible with equal chance.
Below is my implementation and any feedback is welcome.

/// <summary>
/// Create a random collection of binaries, between n and 31 elements, with n bits are set.
/// The set positions should be random too.
/// </summary>
/// <param name="n">The number of set bits in the collection; must be positive and less than 32</param>
let createRandomBinary (n : int) =
    if n > 31 || n < 0 then ArgumentException("invalid input: must be positive and less than 32", "n") |> raise
    let ran = new Random()
    let mutable totalLength = ran.Next(n, 32) // [n, 32)
    match totalLength with
    | x when x = n -> Array.init n (fun _-> 1) // all bits are set case
    | _ ->  let res : int array = Array.zeroCreate totalLength // initialise a result with all 0s.
            let indices = ResizeArray(seq{0..totalLength - 1})
            let mutable counter = n
            let rec shuffle = function
                            | 0 ->  res // all n 1s have been set randomly so return the result
                            | _ ->  counter <- counter - 1
                                    let i = ran.Next(0, totalLength) // randomly pick an index and set to 1
                                    res.[indices.[i]] <- 1
                                    indices.RemoveAt(i) // remove the chosen index so it won't be set twice
                                    totalLength <- totalLength - 1 // decrease the length for next random index pick
                                    shuffle counter
            shuffle counter


texts:
This solves Sudoku by using backtracking. Accepts one grid where 0 represents a missing number. Here are some examples: http://norvig.com/easy50.txt

The program is quite slow. Input is stdin.

import Data.Char (isDigit)
import Data.List (intersperse, delete)

printGrid [] = []
printGrid x = (intersperse ' ' $ take 9 x) ++ "\n" ++ (printGrid $ drop 9 x)

solve x = if isSolved x then x
          else
                firstSolved cands
             where
                firstSolved [] = []
                firstSolved (c:cs) = if isSolved trial then trial else firstSolved cs
                        where
                            trial = solve c
                cands = candidates x

isSolved x = (length x == 81) && (not $ elem '0' x) && (isValidCandidate x)

candidates x = filter isValidCandidate [(takeWhile (/='0') x) ++ z ++ (tail $ dropWhile (/='0') x) | z <- map show [1..9]]

isValidCandidate x = not $ any (isInvalidCand x) [0..80]

isInvalidCand x i = (x !! i /= '0') &&
                    any (elem ic) [row, col, unit]
    where
        ix = mod i 9
        iy = quot i 9
        ic = x !! i
        row = [x !! a | a <- [9*iy..(9*iy + 8)], a /= i]
        col = [x !! a | a <- [ix, (ix + 9)..(ix + 72)], a /= i]
        icx = (quot ix 3) * 3
        icy = (quot iy 3) * 3
        si = (9*icy) + icx
        unit = map (x !!) (delete i [si, si + 1, si + 2, si + 9, si + 10, si + 11, si + 18, si + 19, si + 20])

main :: IO ()
main = interact $ printGrid . solve . filter isDigit


texts:
This Connect 4 game will be used for implementing game-playing AI. Sample players are supplied. One takes user input, and the other plays randomly. Right now it's set for a human player to play against a randomly playing agent, but in the future I plan to try out algorithms such as Minimax and have AI agents play against themselves.

Some more features (such as notifying the players when the game is over, instead of just printing to stdout) need to be added for later work, but I'm showing this simply as a working base. I'm not so much looking for feature suggestions, since those will come later. I will be adding docstrings and comments, but for now it should be straight forward.

I'm looking for tips on: program correctness, code structure, and best practices (whether specific to Python or not).

(Python 3.2.3)

#!/usr/bin/env python

import numpy as np
from copy import copy
from abc import ABCMeta, abstractmethod

class Connect4Game():
    def __init__(self, player1, player2):
        self.player1 = player1
        self.player2 = player2
        self.player_names = {player1 : "Player1", player2 : "Player2"}
        self.board = np.zeros((6, 7), dtype=np.int8)
        self.turn = player1
        self.last_move = ()
        self.winner = None

    def gameover(self):
        if self.last_move == ():
            return False

        rind, cind = self.last_move

        row = self.board[rind, :]
        col = self.board[:, cind]
        diag1 = np.diagonal(self.board, cind - rind)
        diag2 = np.diagonal(np.fliplr(self.board), -(cind + rind - 6))

        for line in [row, col, diag1, diag2]:
            if line.shape[0] < 4:
                continue

            for four in [line[i:i+4] for i in range(len(line)-3)]:
                if sum(four == 1) == 4:
                    self.winner = self.player1
                    return True
                elif sum(four == 2) == 4:
                    self.winner = self.player2
                    return True

        if sum(self.board[0] == 0) == 0:
            return True

        return False

    def move(self, cind):
        free_index = sum(self.board[:, cind] == 0) - 1
        if free_index == -1:
            return False

        if self.turn is self.player1:
            self.board[free_index, cind] = 1
            self.turn = self.player2
        else:
            self.board[free_index, cind] = 2
            self.turn = self.player1

        self.last_move = (free_index, cind)
        return True

    def play(self):
        while not self.gameover():
            print(self.board)
            print(self.player_names[self.turn]+"'s turn.")

            self.move(self.turn.get_move(copy(self.board)))

        print(self.board)

        if self.winner is self.player1:
            print("Winner: player1")
        elif self.winner is self.player2:
            print("Winner: player2")
        else:
            print("Tie")

class BasePlayer(metaclass=ABCMeta):
    @abstractmethod
    def __init__(self, empty, me, opponent):
        pass

    @abstractmethod
    def get_move(self, board):
        pass

class HumanPlayer(BasePlayer):
    def __init__(self, empty, me, opponent):
        pass

    def get_move(self, board):
        col = input("Your move (0-6): ")
        return int(col)

class RandomPlayer(BasePlayer):
    def __init__(self, empty, me, opponent):
        pass

    def get_move(self, board):
        free_columns = np.where(board[0] == 0)[0]
        return np.random.choice(free_columns)

def main():
    player1 = HumanPlayer(0, 1, 2)
    player2 = RandomPlayer(0, 2, 1)

    game = Connect4Game(player1, player2)
    game.play()

if __name__ == "__main__":
    main()


texts: Different neural network activation functions and gradient descent

texts:
I've implemented a bunch of activation functions for neural networks, and I just want have validation that they work correctly mathematically. I implemented sigmoid, tanh, relu, arctan, step function, squash, and gaussian and I use their implicit derivative (in terms of the output) for backpropagation.

import numpy as np

def sigmoid(x, derivative=False):
    if (derivative == True):
        return x * (1 - x)
    return 1 / (1 + np.exp(-x))

def tanh(x, derivative=False):
    if (derivative == True):
        return (1 - (x ** 2))
    return np.tanh(x)

def relu(x, derivative=False):
    if (derivative == True):
        for i in range(0, len(x)):
            for k in range(len(x[i])):
                if x[i][k] > 0:
                    x[i][k] = 1
                else:
                    x[i][k] = 0
        return x
    for i in range(0, len(x)):
        for k in range(0, len(x[i])):
            if x[i][k] > 0:
                pass  # do nothing since it would be effectively replacing x with x
            else:
                x[i][k] = 0
    return x

def arctan(x, derivative=False):
    if (derivative == True):
        return (np.cos(x) ** 2)
    return np.arctan(x)

def step(x, derivative=False):
    if (derivative == True):
        for i in range(0, len(x)):
            for k in range(len(x[i])):
                if x[i][k] > 0:
                    x[i][k] = 0
        return x
    for i in range(0, len(x)):
        for k in range(0, len(x[i])):
            if x[i][k] > 0:
                x[i][k] = 1
            else:
                x[i][k] = 0
    return x

def squash(x, derivative=False):
    if (derivative == True):
        for i in range(0, len(x)):
            for k in range(0, len(x[i])):
                if x[i][k] > 0:
                    x[i][k] = (x[i][k]) / (1 + x[i][k])
                else:
                    x[i][k] = (x[i][k]) / (1 - x[i][k])
        return x
    for i in range(0, len(x)):
        for k in range(0, len(x[i])):
            x[i][k] = (x[i][k]) / (1 + abs(x[i][k]))
    return x

def gaussian(x, derivative=False):
    if (derivative == True):
        for i in range(0, len(x)):
            for k in range(0, len(x[i])):
                x[i][k] = -2* x[i][k] * np.exp(-x[i][k] ** 2)
    for i in range(0, len(x)):
        for k in range(0, len(x[i])):
            x[i][k] = np.exp(-x[i][k] ** 2)
    return x

The input x is the result of the output matrix of the previous layer multiplied by the weight matrix. The output x is the resultant of the activation function on the matrix to be used for the next layer.

Did I implement them in the way that it was intended to be used, or do some of these not give the intended results?

Here is the gradient descent algorithm I implemented:

import numpy as np
from Neural_Network import Activation_Function as af

def GD(layers, weights, proper, acti):
    deltas = []
    llayerError = layers[-1] - proper
    llayerDelta = llayerError * acti(layers[-1], True)
    deltas.append(llayerDelta)
    for i in range(-1, -len(layers), -1):
        layerError = deltas[abs((i + 1))].dot(weights[i].T)
        layerDelta = layerError * acti(layers[i-1], True)
        deltas.append(layerDelta)

    return deltas


texts: Filtering parent and children elements of list of dictionaries

texts:
I have a list of dictionaries and its elements has id and parent_id fields.

Main purposes:

If the parent_id field of an element is defined, it should be returning the rest of elements except itself.
If the parent_id field of element is not defined, it should be returning the rest of elements. In other words, its all child elements. Because it is parent element.

I'll be sharing my implementation below. But I need more concise and Pythonic way.

products = [
    {"id": 5, "counter": 10, "parent_id": None},
    {"id": 6, "counter": 10, "parent_id": 5},
    {"id": 7, "counter": 10, "parent_id": 5},
]

def get_by_id(product_id):
    product = list(filter(lambda p: p["id"] == product_id, products))
    return product[0] if product else False

def get_by_product(product):
    p = []
    for i in products:
        if product["parent_id"]:
            if i["id"] == product["parent_id"] or i["id"] != product["id"]:
                p.append(i)
        else:
            if i["parent_id"] == product["id"]:
                p.append(i)
    return p

p = get_by_id(7)
g = get_by_product(p)
print(g) # [{'id': 5, 'counter': 10, 'parent_id': None}, {'id': 6, 'counter': 10, 'parent_id': 5}]

p = get_by_id(5)
g = get_by_product(p)
print(g) # [{'id': 6, 'counter': 10, 'parent_id': 5}, {'id': 7, 'counter': 10, 'parent_id': 5}]

I have changed ridiculous if statements above like this:

def get_by_product(product):
    p = []
    for i in products:
        if product["parent_id"] and i["id"] == product["parent_id"] or i["id"] != product["id"] or i["parent_id"] == product["id"]:
            p.append(i)
    return p


texts:
I created this class to keep track of a user's role:

class UserRoleHelper extends AppHelper
{
    public $helpers = array('Session');

    private $role = NULL;

    const CUSTOMER  = 'customer';
    const ASSOCIATE = 'associate';
    const MANAGER   = 'manager';
    const ADMIN     = 'admin';
    const DEVELOPER = 'developer';

    private $score = array(
        self::CUSTOMER  => 0,
        self::ASSOCIATE => 1,
        self::MANAGER   => 2,
        self::ADMIN     => 3,
        self::DEVELOPER => 4,
    );

    public function role()
    {
        if($this->role == NULL)
        {
            $this->role = strtolower($this->Session->read('Auth.User.role')) ?: 'customer';
        }
        return $this->role;
    }

    private function is($role)
    {
       return $this->score[$this->role()] >= $this->score[$role];
    }

    public function admin()
    {
        return $this->is(self::ADMIN);
    }

    public function manager()
    {
        return $this->is(self::MANAGER);
    }

    public function associate()
    {
        return $this->is(self::ASSOCIATE);
    }

}

The idea is to be able to have an expression like:

if($this->UserRole->manager())
{
    //do something
}

And have it evaluate true if you are a manager or higher (admin, developer).

I also tried to design it so if there is ever the need to add a level like GENERAL_MANGER = 3 which would shift the values of ADMIN and DEVELOPER up one, it won't effect anything.

I originally had the keys in the $score array as strings, but it seemed redundant when I had constants already defined with the same values. I have never seen an array definition with constants for keys in a class body before. I know variables are not allowed but it seems to work with constants. Still don't know if that is bad or not though.

Is there anything I have missed or can do to make this better?


texts:
I am trying to solve the warning, which avoids the call of a virtual method, I have seen different answers, but none of them seems to solve my doubt, I understand why this warning appears and is one of the ones you should not suppress. My code gets data from Matlab and uses a method to configure the limits in a usercontrol. Should I build another class to call from there the method?
abstract public class MatlabData:eSoundMaster
{
    //[sdon] changed to override from derived class
    public bool EQAMAvail = false;
    public readonly int numTonspuren = 32;
    public readonly int numSubgroups = 8;
    public readonly int numStandardTS = 22;
    public readonly int numPremiumTS = 10;
    public readonly int numOutputs = 2;
    public readonly int numSoundtrackLUTs = 124;

    public MatlabData(int nTonspuren, int nIntermediateMixerChannels, int nStandardTS, int nPremiumTS, int LimiterNumSettings)

    {
        //Override predefined vars with values from child class
        this.numTonspuren = nTonspuren;
        this.numSubgroups = nIntermediateMixerChannels;
        this.numStandardTS = nStandardTS;
        this.numPremiumTS = nPremiumTS;
        //this.ProjectType = ProjectType;
        this.LimiterNumSettings = LimiterNumSettings;
        ConfigLimiter();
    }

    public bool isEQAMAvailable()
    {
        return EQAMAvail;
    }

    public virtual void ConfigLimiter()
    {
        //Overwrite from derived class
    }
}

class MatlabData_MLBevo : MatlabData
{
    public new const int numTonspuren = 32;
    public new const int numSubgroups = 8;
    public new const int numStandardTS = 22;
    public new const int numPremiumTS = 10;
    public new const int LimiterNumSettings = 7;

    public MatlabData_MLBevo()
        :base(numTonspuren, numSubgroups, numStandardTS, numPremiumTS, LimiterNumSettings)
    {
        EQAMAvail = false;
    }

    //ConfigLimiter method in this class override method in base class automatically
    //parts of the label already configured in matlabconstants region of this class
    public override void ConfigLimiter()
    {
        LabelText = new string[LimiterNumSettings];
        LabelText[0] = "Threshold (dB)";
        LabelText[1] = "Out Gain (dB)";
        LabelText[2] = "Knee Depth (dB)";
        LabelText[3] = "Ratio (dB)";
        LabelText[4] = "Attack Time (ms)";
        LabelText[5] = "Decay Time (ms)";
        LabelText[6] = "Post Limiter Gain";

        LabelName = new string[LimiterNumSettings + 2];
        LabelName[0] = "LimiterCore1.threshold";
        LabelName[1] = "LimiterCore1.outputGain";
        LabelName[2] = "LimiterCore1.kneeDepth";
        LabelName[3] = "LimiterCore1.ratio";
        LabelName[4] = "LimiterCore1.attackTime";
        LabelName[5] = "LimiterCore1.decayTime";
        LabelName[6] = "PostLimGain.gainDB";
        LabelName[7] = "gsys.SYS.";
        LabelName[8] = "Limiter_Stereo.Limiter_CH";

        LabelMinimum = new double[LimiterNumSettings];
        LabelMinimum[0] = -60;
        LabelMinimum[1] = 0;
        LabelMinimum[2] = 0.1;
        LabelMinimum[3] = 1;
        LabelMinimum[4] = 0.009;
        LabelMinimum[5] = 0.01;
        LabelMinimum[6] = -100;

        LabelMaximum = new double[LimiterNumSettings];
        LabelMaximum[0] = 0;
        LabelMaximum[1] = 100;
        LabelMaximum[2] = 60;
        LabelMaximum[3] = 100;
        LabelMaximum[4] = 1000;
        LabelMaximum[5] = 1000;
        LabelMaximum[6] = 20;
    }
}


texts:
I have the following class in Typescript (using the Aurelia SPA-framework).

import { inject } from "aurelia-framework";
import {Apiclient} from "../services/apiclient";
import * as gravatarUrl from "gravatar-url";

// Dialogs
import {DialogService} from "aurelia-dialog";
import {RedigerBruker} from "./dialogs/rediger-bruker";

@inject(Apiclient, DialogService)
export class Brukere {
    users;
    lastFetchSuccess:boolean = true;

    constructor(private api:Apiclient, private dialog:DialogService) {

    }

    gravatar(email) {
        return gravatarUrl(email, { size: 48, default: "mm" });
    }

    activate() {
        return this.api.getUsers().then(
            res => {
                if(res.status == 200) {
                    res.resultObject.then(json => this.users = json);
                    this.lastFetchSuccess = true;
                } else {
                    this.lastFetchSuccess = false;
                };
            });
    }

    editUser(userId) {
        this.api.getUser(userId).then(
            res => {
                if(res.status == 200) {
                    res.resultObject.then(json => {
                        this.dialog.open({ viewModel: RedigerBruker, model: json })
                            .then(response => {
                                if (!response.wasCancelled) {
                                    console.log("MKS: Good - " + response.output);
                                } else {
                                    console.log("MKS: Bad");
                                }

                            });
                    });
                } else {
                    console.log(`MKS: Error retrieving user ${userId}: ${res.status} - ${res.statusText}`);
                }
            });
    }
}

This code works. The API-client is just a simple wrapper around the fetch-client that returns simplified objects with status, statustext and the JSON-result promise. If you look at the editUser function. This function takes a user-id, passes it to the api-client which fetches the data from the server, and then returns the result-object. This code looks like the usual callback-pyramid-of-doom. Which makes me think I'm not using promises correctly.

Am I completely fumbling the use of promises, or is this just the way it works and I have to deal with it? Maybe there is some other way to code this?


texts:
I have the following code in a VIEW:

<select name="selected_budget_mode" class="" onchange="OnBudgetModeChanged(this)">
<option value="0"
        <% if params[:current_budget_mode].to_i == 0 %>selected
        <% end %>><%= show_budget_mode(0) %></option>
<option value="1"
        <% if params[:current_budget_mode].to_i == 1 %>selected
        <% end %>><%= show_budget_mode(1) %></option>
<option value="2"
        <% if params[:current_budget_mode].to_i == 2 %>selected
        <% end %>><%= show_budget_mode(2) %></option>
</select>

I am aware of the select_tag and the options_for_select form helpers, but that implies that I need to create a list with the options and then pass it to the options_for_select.

The budgets_mode are not dynamic. They don't come from calling a service or other function, there are only 3 modes.

What would be the best approach to simplify this code and make it as readable as possible?


texts:
I have a simple Java model Class called Person which have a constructor that receives a JSONObject. In that constructor I get the values from the JSONObject and put in my instance variables. This is just a simple question but which way is best?

public Person(JSONObject personJsonObject) {
    // Without setter
    this.name = personJsonObject.getString("name");
    // With setter passing String
    setName(personJsonObject.getString("name"));
    // With setter passing JSONObject
    setName(personJsonObject);
}

And when my setter isn't just a simple attribution but a evaluation, which one should I use?

public Person(JSONObject personJsonObject) {
    // Without setter
    this.fullName = personJsonObject.getString("name") + personJsonObject.getString("lastName");
    // With setter passing String
    setFullName(personJsonObject.getString("name"), personJsonObject.getString("lastName"));
    // With setter passing JSONObject
    setFullName(personJsonObject);
    // Or should I put this logic in the getFullName method? The caveat is if there is a huge calculation in the getter method. It wouldn't be efficient.
}

Thanks for your answer.


texts: Finding the sum of all numeric palindromes that are less than N

texts:
I wrote a function that finds the sum of all numeric palindromes lesser than N.

const sumOfPalindromes = (n) => {
    let x = 0;
    for (let i = 0; i <= n; i++) {
      x += i == (''+i).split('').reverse().join('') ? i : 0;
    }
    return x;
}

console.log(sumOfPalindromes(10000));
console.log(sumOfPalindromes(24));

Are there shorter, more-concise alternatives to the above approach (preferably without using a for loop)?


texts: Speeding up nested for-loop analysis code

texts:
I have two matrices, the first one is mat 2000*500, the second one is 6000*500 tep
I did this code for some analysis to get another matrix that has a specific elements.

Problem is :
This code is very very slow, I need to make faster.Any suggestion to do so is welcome

mat=matrix(sample(c(0,1,2),200,replace =T),nrow=500,ncol=2000)
tep =matrix(rnorm(200,5,2),nrow=500,ncol=6000)`

The code is trying to create one matrix (500 row by 2000 col). Its elements depend on the following :
Let the new matrix is A .

if mat[1,1] = 0 then A[1,1]=tep[1,1]/(sum(tep[1,1:3]))
if mat[1,1] = 1 then A[1,1]=tep[1,2]/(sum(tep[1,1:3]))
if mat[1,1] = 2 then A[1,1]=tep[1,3]/(sum(tep[1,1:3]))
if mat[1,2] = 0 then A[1,2]=tep[1,4]/(sum(tep[1,4:6]))
if mat[1,2] = 1 then A[1,2]=tep[1,5]/(sum(tep[1,4:6]))
if mat[1,2] = 2 then A[1,2]=tep[1,6]/(sum(tep[1,4:6]))`
......

and so on..
 The one column in mat is corresponding to three columns in tep.
Every three values in three columns in matrix tep at a j row is a group we calculate from each group there will be one value according to the example above, so we will end up with a 500 row by 2000 column matrix.

allele=c(0,1,2)
A=matrix(nrow=500,ncol=2000)
 start=seq(1,6000,3)
for(k in 1:500){
for(i in 1:2000){
for(j in start){
  temp.z= mat[k,i]
  temp.pl=tep[k,j:(j+2)]
  loc=which(allele==temp.z)
  temp.pl=temp.pl[loc]/(sum(temp.pl))
  A[k,i]=temp.pl
  rm(temp.pl,temp.z,loc)

      }
   }
}


texts:
I've written a method to round a MySQL Time to two decimal places. Here's some examples:

Input           -> Output

13:04:27.127930 -> 13:04:27.13
00:00:14.000000 -> 00:00:14.00
02:19:03.300000 -> 02:19:03.30
07:13:00.954639 -> 07:13:00.96

My current code works, but seems a bit difficult to follow. How could I improve the readability of the code? Performance isn't too much of a concern.

<?php
public function mysql_time_to_human($mysql_time)
    {
        //how many decimal places it should show
        (defined('DECIMAL_PLACES')) ?: define('DECIMAL_PLACES', 2);

        //Separate the sting on the decimal place
        $time_parts = explode('.', $mysql_time);

        //Add a 0 prefix so it can properly round the decimal part
        $time_parts[1] = '0.' . $time_parts[1];

        //Round the number to two decimal places
        $rounded_part = round($time_parts[1], DECIMAL_PLACES);

        //Ensure the part is always two decimal places, including zeroes
        $time_parts[1] = sprintf('%.2f', $rounded_part);

        //Remove the 0 prefix added earlier
        $time_parts[1] = substr($time_parts[1], 2);

        //Glue the parts back together
        $time = implode('.', $time_parts);

        return $time;
    }

While writing this question I've realized a case which my current method won't accurately work for:

Input           -> Desired Output -> My Output
00:00:00.995000 -> 00:00:01.00    -> 00:00:00.00


texts: Dynamically inserting html from external file and updating the database

texts:
I need some suggestions on how to approach this. I want to allow users to create sections of website. The code so far is working but since I am new to back-end I feel like there is better, more elegant way to approach this. I am open to any approaches, as long as the code is kept as concise as possible.

  The user clicks "add section" button (there would be different types of sections to choose from), the html of each section will be stored in an external file
  The id of the section should be inserted into the database (alongside some other details such as user uniqid)
  The section should be inserted inside a div

At the moment this is how I have approached it:

if (isset($_POST["add_section"])) {
    $section_id = $_POST["add_section"];
    $stmt = $conn->prepare('INSERT INTO sections (user_id, section_id) VALUES (?, ?)');
    $stmt->bind_param('ss', $row['user_id'], $section_id);
    $stmt->execute();
}

The value of the button is the id of the section passed to the database.

<form method="post">
    <button class="button_1" value="navigation_ht" name="add_section>Seleccionar</button>
</form>

I want to allow the user to be able to include up to 3 sections.

$sql = "SELECT * FROM sections WHERE user_id = '{$row['user_id']}'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        include('shared/'.$row['section_id'].'.php');
    }
}

I was considering to do the following, but if the section is not created, there is error message:

$sql = "SELECT * FROM sections WHERE user_id = '{$row['user_id']}'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
    include('shared/'.$row['section_id'].'.php');
    include('shared/'.$row['section_id'].'.php');
    include('shared/'.$row['section_id'].'.php');
}


texts: Can this list comprehension be made more pythonic?

texts:
Quite a specific question can the below code be made more clearer / pythonic in any way.

Essentially based on the condition of the string x((len(x) / 3) - 1), I use this to extract out parts of the string.

def split_string(x):
    splitted_string = [x[counter*3:(counter*3)+3] for counter in range ((len(x) /3) - 1)]
    return splitted_string

>>> split_string('ABCDEFGHI')
['ABC', 'DEF']


texts:
Below is a python script that generates the sequence ['a', 'b' .. 'z', 'aa', 'ab' .. 'az', 'ba', 'bb' .. 'zz', 'aaa', 'aab', ..]

This is essentially counting in base 27, replacing every digit with the n-th letter of the alphabet, but skipping any number that would have a '0'.

import string

def gen_labels():
    i = 0
    n = len(string.ascii_lowercase) + 1
    while True:
        i += 1
        j = i
        result = ''
        while True:
            c = j % n
            if not c:
                break
            result = string.ascii_lowercase[c-1] + result
            if j < n:
                break
            j = j // n
        if c:
            yield result

print(list(zip(gen_labels(), range(1000))))

However, the code seems overly long to me for generating such a straightforward series and it's doing a lot of work to break down values that would have a '0' in them in base 27.

What is a more efficient way of generating the exact same (infinite) series?

Note that I'm not worried that much about speed, but mainly about the brevity / simplicity of the algorithm - it seems overly complicated, but I don't really see my way to an efficient realisation.


texts: Menu of triggers reveal corresponding dialog elements

texts:
So I have this code that for the most part, does what it needs to do, but I'm having trouble making it more concise and elegant.

Codepen

Intended functionality:

If you click a trigger, it's corresponding element must display
If you click another trigger, that trigger's element displays and the other closes
If you click the trigger whilst it is open, it simply closes the element

Any ideas on how to make this cleaner?

var trigger = ".trigger";
var recipient = ".target";
var not_trigger = $(".trigger").not(this);

$(trigger).click(function(e) {
  e.stopPropagation();
  recipient = '#' + $(this).attr('data-target-id');
  var not_recipient = $(".target").not(recipient);

  if($(trigger).hasClass("active")){
    $(trigger).not(this).removeClass("active");
  }
  $(this).toggleClass("active") ;

  if($(".target").hasClass("open")){
    $(not_recipient).removeClass("open");
    TweenMax.to($(".target"), .3, {display:'none', y:'0%', autoAlpha:0});

    if($(recipient).hasClass("open")){
      $(recipient).removeClass("open");
      TweenMax.to(recipient, .3, {display:'none', y:'0%', autoAlpha:0});
    }else{
      $(recipient).addClass("open");
      TweenMax.to(recipient, .3, {display:'block', y:'100%', autoAlpha:1});
    }
  }else {
    $(recipient).addClass("open");
    TweenMax.to(recipient, .3, {display:'block', y:'100%', autoAlpha:1});
  }

});


texts: Asynchronous task on every element of an array

texts:
Here is some synchronous code:

let barsClient = [{
    id: 1,
    name: "The Shindig",
    goingTonight: []
  },
  {
    id: 2,
    name: "Steakapolis",
    goingTonight: []
  },
  {
    id: 3,
    name: "Booty Town",
    goingTonight: []
  }
];

let barsDB = [{
  id: 2,
  name: "Steakapolis",
  goingTonight: ["Joe", "Jim", "Joey"]
}];

function findById(bar) {
  return barsDB.find((dbBar) => {
    return dbBar.id === bar.id;
  });
}

// Check to see if bar is present in barsDB
for (let bar of barsClient) {
  let result = findById(bar);
  // If bar is not in barsDB, add it
  if (!result) {
    barsDB.push(bar);
    // If it is present, update its goingTonight property
  } else {
    bar.goingTonight = result.goingTonight;
  }
}

// Both barsClient and barsDB should contain the same data, albeit not necessarily in the same order
console.log("barsClient:", barsClient);
console.log("barsDB:", barsDB);

Now, imagine that the findById function was asynchronous? It took me about six hours of Googling, reading and fiddling to finally figure this one out and I'm pretty happy with myself. I'm just wondering if my solution is in accordance with best practices. Here is the code to review:

let barsClient = [{
    id: 1,
    name: "The Shindig",
    goingTonight: []
  },
  {
    id: 2,
    name: "Steakapolis",
    goingTonight: []
  },
  {
    id: 3,
    name: "Booty Town",
    goingTonight: []
  }
];

let barsDB = [{
  id: 2,
  name: "Steakapolis",
  goingTonight: ["Joe", "Jim", "Joey"]
}];

function findById(bar) {
  return barsDB.find((dbBar) => {
    return dbBar.id === bar.id;
  });
}

function findByIdAsync(bar) {
  var promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(findById(bar));
    }, 3000);
  });
  return promise;
}

Promise.all(barsClient.map((bar, i) => {
    return findByIdAsync(bar)
      .then(function(result) {
        if (!result) {
          barsDB.push(bar);
        } else {
          bar.goingTonight = result.goingTonight;
        }
      });
  }))
  .then(() => {
    console.log("barsClient:", barsClient);
    console.log("barsDB", barsDB);
  });


texts: Converting a string to a list of key-value pairs

texts:
I'm trying to convert a string (here after called input) into a vector of key-value pairs, all in C++03 (cannot use C++11, cannot use Boost libs).

The string in question can contain whitespaces. A comma (,) delimits key-value pairs and the equals sign (=) separates the key from the value.
A sample string (also in the code could be: "ab=xy z,time a=1s". Notice the lack of a final ,.

Any improvement is most welcome.

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>

struct Flag_name_value {
    std::string name;
    std::string value;
};

std::istringstream& operator>>(std::istringstream& iss, Flag_name_value& fnv)
{
    char ch;
    std::ostringstream oss;

    while (iss >> std::noskipws >> ch) {
        std::cout << ch << "\n";
        switch(ch) {
            case('='):
                fnv.name = oss.str();
                oss.str("");
                break;
            case(','):
                fnv.value = oss.str();
                oss.str("");
                break;
            default:
                oss << ch;
                break;
        }

        if (!fnv.name.empty() && !fnv.value.empty())
        {
            return iss;
        }
    }

    // We end here if the string didn't end with ','
    fnv.value = oss.str();
    return iss;
}

int main () {

    std::string input("ab=xy z,time a=1s");

    std::istringstream iss(input);

    std::vector<Flag_name_value> flags;
    while (true) {
        Flag_name_value f;
        iss >> f;
        flags.push_back(f);
        if (!iss) break;
    }

    return 0;

}


texts:
This is quite plain vanilla, but I'm hoping for Objective-C specific feedback. Also I'd be interested in what folks think about sorting in Objective-C vs. doing all sorting in C or C++ (and which?) even in an app.

- (NSMutableArray *) quickSort: (NSMutableArray *)toSort{

    for(NSNumber *arrayMember in toSort){
        if(![arrayMember respondsToSelector:@selector(doubleValue)]){
                NSLog(@"incorrect types in input array, returning nil");
                return nil;
            }
    }

    int intLength = toSort.count;
    if (intLength == 0){
        return toSort;
    }
    else if (intLength == 1){
        return toSort;
    }else if (intLength==2){
        if ([toSort[0] doubleValue] <= [toSort[1] doubleValue]) {
            return toSort;
    }else{
        NSNumber *temp = [toSort objectAtIndex:0];
        [toSort replaceObjectAtIndex:0 withObject:[toSort objectAtIndex:1]];
        [toSort replaceObjectAtIndex:1 withObject:temp];
        return toSort;
        }
    }

    int r = arc4random_uniform(intLength);
    double pivot = [[toSort objectAtIndex:r] doubleValue];

    NSMutableArray *lowArray = [NSMutableArray array];
    NSMutableArray *highArray = [NSMutableArray array];
    NSMutableArray *equalArray = [NSMutableArray array];
    for(int i = 0; i < intLength; i++){
        double arrayMember = [[toSort objectAtIndex:i] doubleValue];
        if (arrayMember < pivot) {
            [lowArray addObject:[NSNumber numberWithDouble:arrayMember]];
        }else if (arrayMember > pivot){
            [highArray addObject:[NSNumber numberWithDouble:arrayMember]];
        }else{
            [equalArray addObject:[NSNumber numberWithDouble:arrayMember]];
        }
    }

    NSMutableArray *returnLeft = [self quickSort:lowArray];
    NSMutableArray *returnRight = [self quickSort:highArray];

    NSMutableArray *returnArray = returnLeft;
    [returnArray addObjectsFromArray:equalArray];
    [returnArray addObjectsFromArray:returnRight];

    return returnArray;

}

This function is written to sort NSNumbers formed from doubles. Here's a sample call:

NSNumber *number3 = [NSNumber numberWithDouble:92.3];
NSNumber *number1 = [NSNumber numberWithDouble:2.3];
NSNumber *number2 = [NSNumber numberWithDouble:4.3];
NSNumber *number5 = [NSNumber numberWithDouble:5.3];
NSNumber *number4 = [NSNumber numberWithDouble:-5.3];

NSMutableArray *toSort = @[number1, number2, number3, number4, number5];
NSMutableArray *sorted = [self quickSort:toSort];
NSLog(@"here's sorted array: %@", sorted);


texts:
I wrote a function to resolve the full path to the current Bash script, and I'm wondering if it's SOLID:

#!/usr/bin/env bash

scriptpath()
{
    result=${BASH_SOURCE[0]}

    # unfortunately readlink -f isn't available on Macs,
    # so resolve the symlinks manually
    while [ -h "$result" ]
    do
        symdir=$(dirname "$result")
        cd -P "$symdir"
        result=$(readlink "$result")
    done

    echo "$result"
}

echo "The path to the current script is: $(scriptpath)"

Is there anything I may have looked over in the function? I'm not sure because my answer seems quite different than the solutions listed here or here, and I'm pretty fuzzy on symlinks.

I basically want to know if my function (scriptpath) is any different than this on a Linux system:

readlink -f "${BASH_SOURCE[0]}" | xargs -0 dirname


texts: Rate limit a method by generating particular load on demand in C#

texts:
I am working on a project where I want to generate random throughput on a particular method so that I can do some performance testing on it. This way I can test my method by generating random throughputs and see how my method works under all those scenarios.

For example: I need to call my doIOStuff method at an approximate rate of x requests per second from multiple threads where x will be less than 2000 mostly but it really doesn't matter in this case. It doesn't have to be accurate so there is some room for an error but the overall idea is I need to make sure that my method doIOStuff is executed no more than x times in a sliding window of y seconds.

Assuming we start n threads and want a maximum of m calls per second. We can achieve this by having each thread generate a random number between 0 and 1, k times per second and call  doIOStuff method only if the generated number is less than m / n / k.

Below is the code I got which uses global variables and it does the job but I think it can be improved a lot where I can use some cancellation tokens as well and make it more efficient and clean.

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

namespace ConsoleApp
{
    class Program
    {
        const int m_threads = 100;
        const int n_throughput = 2000;
        const int k_toss_per_second = 2000; // Note that k_toss_per_second x  m_threads >= n_throughput

        static void Main(string[] args)
        {
            var tasks = new List<Task>();

            for (int i = 0; i < m_threads; i++)
                tasks.Add(Task.Factory.StartNew(() => doIOStuff()));

            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("All threads complete");
        }

        static void callDoIOStuff()
        {
           int sleep_time = (int) (1000 * 1.0d / k_toss_per_second);
           double threshold = (double) n_throughput / m_threads / k_toss_per_second;
           Random random = new Random();
           while (true) {
                Thread.Sleep(sleep_time);
                if (random.NextDouble() < threshold)
                    doIOStuff();
            }
        }

        static void doIOStuff()
        {
            // do some IO work
        }
    }
}

I wanted to see what can we do here to make it more efficient and clean so that it can used in production testing for generating random throughput load. Also I should keep an eye to the completion of the tasks that are started otherwise number of pending tasks would keep increasing every second? Right.


texts: Iterate through all the photo library in iOS

texts:
This function is supposed to return a map of all unique local identifiers of images that are on the iPhone using the IOS Photos Framework.

(it is a map so nSnull or (any object can be mapped to it) and retrieved in O(1))

I was never sure if in this way I am iterating every photos or am i missing something.

 - (NSDictionary*) getAllPhotos
        {
            PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
            if (status == PHAuthorizationStatusAuthorized)
            {
                //initialize empty local state
                __block NSMutableDictionary* currentImageState = [NSMutableDictionary dictionaryWithCapacity:0];
                @autoreleasepool
                {
                    PHFetchOptions *userAlbumsOptions = [PHFetchOptions new];
                    userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"];

                    //fetch all the albums

                    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:userAlbumsOptions];
                    PHFetchOptions *onlyImagesOptions = [PHFetchOptions new];
                    onlyImagesOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage];
                    onlyImagesOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
                    [userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
                    PHFetchResult *collectionResult = [PHAsset fetchAssetsInAssetCollection:collection options:onlyImagesOptions];

                    [collectionResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
                            [currentImageState setObject:[NSNull null] forKey:asset.localIdentifier];
                        }];
                    }];

                    PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];

                    [allPhotosResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
                         [currentImageState setObject:[NSNull null] forKey:asset.localIdentifier];
                     }];
                }
                return [currentImageState copy];
            }
            return 0;
        }


texts:
I would like to make the search faster as it takes a long time to retrieve the data that I require. Is there a faster method to do this? I have written the code below to allow me to search through a data table and retrieve data, which currently is fully functional. It's the nested for loops which I am using and wondering if there is another method of completing the tasks that the for loops get?

 DataTable sqlData = GetConfiguration();

       // var q = sqlData.AsEnumerable().Where(data=> data.Field<String>("slideNo")=="5");

        var w = sqlData.AsEnumerable().Where(data => data.Field<String>("slideNo") == "5")
            .Select(data => data.Field<String>("QuestionStartText")).Distinct();

        List<String> queryResult = new List<String>();
        foreach (var item in w.ToArray<string>())
        {
            if (item != null)
            {
                String queryString = item;
                //queryResult.Clear();
                for (int i = 0; i < excelDataTable.Columns.Count; i++)
                {
                    for (int k = 2; k < excelDataTable.Rows.Count; k++)
                    {
                       String row = "";
                       bool check = excelDataTable.Rows[k][0].ToString().StartsWith(queryString);
                       if (check)
                       {
                           for (int j = 0; j < excelDataTable.Columns.Count; j++)
                           {
                               string value = excelDataTable.Rows[k][j].ToString()+":";
                               row += value;
                           }
                           if (!queryResult.Contains(row))
                           {
                               queryResult.Add(row);
                           }
                       }
                    }
                }
            }
        }


texts: The best way to handle many, different requests with custom query params

texts:
I have a list of products, I would like to filter that products e.g. by number, price, type etc. using checkboxes, selects and inputs. I get my data from REST API - using query params in GET method. My code is working but I'm wondering how to make it better and cleaner.
First, function in my component which connects with a service
  getMethod(): void {
    this.listService
      .getFilter(
        this.FullName,
        this.LastName,
        this.IP,
        this.price,
        this.age,
        this.dateTo,
        this.dateFrom,
        this.male,
        this.female,
        this.kid,
        this.group
      )
      .subscribe(
        (data) => {
          this.items = data;
        },
        (error) => (this.errorMsg = error)
      );
  }

Next, my service. First I check if all values have some content/set to true etc. Then I put all variables as params and at the end I delete empty variables.
  getFilterList(
    FullName: string,
    LastName: string,
    IP: number,
    Price: number,
    Age: number,
    DateTo: string,
    DateFrom: string,
    Male: boolean,
    Female: boolean,
    Kid: boolean,
    Group: boolean,

  ): Observable<ClientsAllData> {

    let isMale = '';
    if (Male=== true) {
      isMale= '0';
    }

    let isFemale= '';
    if (Female=== true) {
      isFemale = '0';
    }

    let isKid= '';
    if (Kid=== true) {
      isKid = '0';
    }

    {...}

    let params = new HttpParams()
      .set('FullName', FullName)
      .set('LastName', LastName)
      .set('IP', IP)

    {...}

    params = params.delete('FullName', '');
    params = params.delete('LastName', '');
    params = params.delete('IP', '');

    {...}

    return this.http.get<any>(
      MY_API,
      { params }
    );

Basically that code looks bad, this is my side learning angular project and I couldn't find better way to do it. Could anyone show me how to write it cleaner or maybe better approach for that topic or just send some links, examples? What's the best way to handle query params if there are many of them.


texts: Performing add/delete/count operations on a list

texts:
Problem Statement (HackerRank)

  You have a list of integers, initially the list is empty.

  You have to process Q operations of three kinds:

  add s: Add integer s to your list, note that an integer can exist more
  than one time in the list
  del s: Delete one copy of integer s from the list, it's guaranteed
  that at least one copy of s will exist in the list.
  cnt s: Count how many integers a are there in the list such that a AND
  s = a, where AND is bitwise AND operator

  Input Format

  First line contains an integer Q.  Each of the following Q lines
  contains an operation type string T and an integer s.

  Constraints

  \$1 \le Q \le 200000\$
  \$0 \le s \lt 2^{16}\$

  Output Format

  For each cnt s operation, output the answer in a new line.

  Sample Input

7
add 11
cnt 15
add 4
add 0
cnt 6
del 4
cnt 15

  Sample Output

1
2
2

  Explanation

  For first line, we have 15 AND 11 = 11 so the answer is 1

  For second line, 6 AND 0 = 0 and 6 AND 4 = 4 so the answer is 2

  For third line, 4 has been deleted and we have 15 AND 11 = 11 and 15
  AND 0 = 0 so the answer is 2

My working code:

operations = int(raw_input())
current = 1
lst = []
while current <= operations:
    count = 0
    input_ = raw_input().split()
    operation = input_[0]
    num = int(input_[1])
    if operation == 'add':
        lst.append(num)
    elif operation == 'cnt':
        for number in lst:
            if number & num == number:
                count += 1
        print(count)
    elif operation == 'del':
        lst.remove(num)
    current += 1


texts: Extending Sieve of Eratosthenes beyond a billion - follow-up

texts:
Follow up form Extending Sieve of Eratosthenes beyond a billion

Taking suggestions from the comments on the previous post:

Updated Code: This takes about 22 seconds for MAX as \$10^9\$ to reach "done". This is a significant improvement.

void sieve_of_eratosthenes(){
    bool* a;
    a = (bool*)malloc(MAX * sizeof(bool));
    memset(a, true, MAX);
    unsigned long int i = 1;
    while (i < ceil(sqrt(MAX))){
        while (((++i)<MAX) && (!a[i]));

        if (2 * i >= MAX)//I am keeping this test. Can't Figure out if it is still relevant
            break;

        for (unsigned long int k = i * i; k < MAX; k += i)
            if (a[k])
                a[k] = false;
    }
    std::cout << "done\n";
    for (unsigned long int i = 2; i < MAX; i++)
        if (a[i])
            std::cout << i << "\n";
    free(a);
    getchar();
    getchar();
}

Further improved:

This takes about 24 seconds for MAX as \$10^9\$ to reach "done". This is a very strange behavior as I am processing only odd numbers now. So this should take less time(must be less than 22 seconds). Also, it prints from \$3\$ to \$2*MAX + 1\$ but even that isn't such a big margin. Good thing is with \$10^9\$ array size, I am able to find primes up to \$2*10^9 + 1\$.

void sieve_of_eratosthenes(){
    bool* a;
    a = (bool*)malloc(MAX * sizeof(bool));
    memset(a, true, MAX);
    unsigned long int i = 0;
    while (i < ceil(sqrt(MAX))){

        while (((++i)<MAX) && (!a[i]));

        //if ((2 * i+1) >= MAX)//This test isn't going to be relevant anymore.
            //break;
        int j = 2 * i + 1;

        //std::cout << "element is " << 2*i+1 << "\n";

        for (unsigned long int k = i + j; k < MAX; k += j)

            if (a[k])
                //Open the following comment very carefully
                //std::cout << "removes " << 2 * k + 1 << "\n";
                a[k] = false;
    }
    std::cout << "done\n";
    for (unsigned long int i = 1; i < MAX; i++)
        if (a[i])
            std::cout << (2*i+1) << "\n";

    free(a);
    getchar();
    getchar();
}

Why is the strange behavior in time? Is there a limit to how much a malloc can allocate? Going beyond a billion for MAX still gives me error. How can I further improve this?


texts: Mockable clock meeting std::chrono TrivialClock requirement and interface

texts:
I'm using the time for e.g. ping and timeout calculation as well as animations in a game. So my (big) codebase uses std::chrono::steady_clock::now() in many places. For testing I'd like to test those without having to resort to sleep and friends (timeout of >=5mins will be hard to test this way...)

For this I created a custom Clock class that uses a singleton-like instance which can be changed to provide a custom clock. A default of steady_clock is used for production code. This Clock can be used as a drop-in replacement of  std::chrono::steady_clock and can be mocked in test code.

I'd like a review with suggestions how to improve this or if it has any flaws. Pointers to similar/better implementations are also welcome. I'm mostly concerned about the multiple indirections (and related performance penalties) this causes: Lookup of a "constructed" flag, the impl and the vtable (3 pointers) although I only have 1 function. See godbold

#include <chrono>
#include <memory>

struct BaseClock
{
    using Clock = std::chrono::steady_clock;
    using time_point = Clock::time_point;
    virtual ~BaseClock() = default;
    virtual time_point now(){ return std::chrono::steady_clock::now(); }
};

class Clock
{
    static std::unique_ptr<BaseClock>& inst(){
        static std::unique_ptr<BaseClock> clock(new BaseClock);
        return clock;
    }
public:
    using rep = BaseClock::Clock::rep;
    using duration = BaseClock::Clock::duration;
    using time_point = std::chrono::time_point<Clock>;

    static time_point now(){ return time_point(inst()->now().time_since_epoch()); }
    static void set(std::unique_ptr<BaseClock> clock){inst() = std::move(clock);}
};

int main()
{
    return Clock::now().time_since_epoch().count();
}

Example usage in test code:

struct MockClock: public BaseClock{
    static time_point current;
    time_point now() override { return current; }
};

void test_method(){
    Clock::set(new MockClock);
    MockClock::current = MockClock::time_point(100);
    testClass.methodUsingClock();
    MockClock::current += std::chrono::seconds(10);
    REQUIRE(testClass.checkTimeout());
}


texts:
My task was to write a function in C where a string such as {2210090,34566,87234,564676} would be given as input and the function had to find out the count of numbers separated by comma whose average of single digits is greater than or equal to 5.

In the below example, the average of 2210090 is 2, the average of 34566 is 4.8, the average of 87234 is 4.8 and the average of 564676 is 5.6, hence the count is 1.

void GetCount(int n,char* input2)
{
    int sum=0;
    n=0;
    h:
    *input2++;
    if((*input2) && !isdigit(*input2))
    {
        if(sum>n<<2)
            output1++;
        sum=0;
        n=0;
        goto h;
    }
    else if(*input2!='\0')
    {
        sum+=*input2-'0';
        n++;
        goto h;
    }
}

The first parameter n is the total count of number.  The program is working fine and I just wanted to know if anyone could give input on improving the time complexity of the program.  I would also appreciate a better way of solving this problem, reducing the number of ifs and gotos or completely eliminating the need of if or goto.


texts:
I have the following code but it's a bit messy and hard to look at. I could include a function to host a game so that block of code isn't repeating, but could this be optimized any further?

server.em.addListener('hostGame', function(settings)
{
    if (Object.keys(hostingGames).length != 0) //If nobody is hosting a game
        {
            for (i in hostingGames) //If there is more than 1 game being hosted, scroll through each one
            {
                if(hostingGames[i].userId === settings.userId) //Check if any of them are by the current user
                {
                    break; //if there is, dont let them host a new one
                }
                else
                {
                    var hostGame = new HostGame(); //If the player isnt hosting a game, host a new game for them

                    hostGame.initialise(settings.userId, settings.userName, settings.boardSize, settings.gameMode, settings.gameNote);
                    hostingGames[settings.userId] = hostGame;
                    server.consoleLog('APP', settings.userName + ' is hosting a game. ID: ' + settings.userId);
                    server.updateGamesList(hostingGames);
                }
            }
        }
        else //If there is no games being hosted, the user must not be hosting any, so let them host a new game
        {
            var hostGame = new HostGame();

            hostGame.initialise(settings.userId, settings.userName, settings.boardSize, settings.gameMode, settings.gameNote);
            hostingGames[settings.userId] = hostGame;
            server.consoleLog('APP', settings.userName + ' is hosting a game. ID: ' + settings.userId);
            server.updateGamesList(hostingGames);
        }
});


texts: TextRenderer class for rendering text with OpenGL

texts:
I'm writing a class called TextRenderer to render text with OpenGL.

Here's my TextRenderer.hpp file

class TextRenderer
{
public:
    void renderText(std::string text, int x, int y);
private:
    void setup();
    GLuint program;
};

Here's my TextRenderer.cpp file:

#include "TextRenderer.hpp"
#include <string>
#include <GL/glew.h>

void TextRenderer::setup()
{

}

Here's my main file:

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include "TextRenderer.hpp"

int main()
{
    //Init GLFW
    glfwInit();
    //Set OpenGL version to 3.2
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    //Make window un-resizable
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    //Create GLFW window in fullscreen mode
    GLFWwindow* window = glfwCreateWindow(800, 600, "MOBA", glfwGetPrimaryMonitor(), nullptr);
    glfwMakeContextCurrent(window);

    //Init FreeType
    FT_Library ft;
    if (FT_Init_FreeType(&ft)) {
        fprintf(stderr, "FATAL: Could not init FreeType");
        return 1;
    }
    //Init Arial FreeType Face
    FT_Face arial;
    if (FT_New_Face(ft, "Arial", 0, &arial))
    {
        fprintf(stderr, "FATAL: Could not init font \"Arial\"");
        return 1;
    }

    //Main loop
    while (!glfwWindowShouldClose(window))
    {
        glfwSwapBuffers(window);
        glfwPollEvents();

        //Close on Esc key press
        //TODO: Bring up quit dialog
        if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        {
            glfwSetWindowShouldClose(window, GL_TRUE);
        }
    }
    //Terminate GLFW
    glfwTerminate();
    return 0;
}

Notice how I have a private GLuint, program. To do this I have to #include <GL/glew.h> (in TextRenderer.cpp), and I already have GL/glew.h included in my main.cpp file. What's the best way to do this?


texts: Split string by list of separators and return used separator in the correct order

texts:
I have built a function that splits a string by an list of separators and returns the used separator in order of usage.

This is the header of the function:

vector<string>* split(const string* value, const string* seperators, string* split_by)

The function is used like the following:

const string value_to_split = "000-000:000-000";
const string seperators = "-:";
string split_by;

auto parts = split(&value_to_split, &seperators, &split_by);
delete parts;

  Example:

  Input

  value => 000-000:000-000
  seperators => "-:"

  Output

  return value => [ '000', '000', '000', '000' ]
  split_by => "-:-"

This is the functions body:

#include <string>
#include <vector>

using std::string;
using std::vector;

vector<string>* split(const string* value, const string* seperators, string* split_by) {
    vector<string>* splited_string = new vector<string>;
    string current_item = "";
    for (int charIndex = 0; charIndex < value->length(); charIndex++) {
        auto current_char = (*value)[charIndex];
        auto seperator_search = seperators->find(current_char);
        if (seperator_search != string::npos) {
            auto current_seperator = (*seperators)[seperator_search];
            splited_string->push_back(current_item);
            *split_by += current_seperator;
            current_item = "";
        }
        else {
            current_item += current_char;
        }
    }
    splited_string->push_back(current_item);
    return splited_string;
};

I mainly want to know if I'm using the language correctly (I'm a C# developer learning C++). But pleace also dont hestitate to tell me about anything that you would do different.


texts:
I just started learning the basics to Swift 3 about 2 days ago. Since then, I've decided to make a simple calculator that can only do one operation at a time.

I was wondering how efficient this was and what I could possibly do to make it more efficient. Any type of criticism would be helpful too

import UIKit

class ViewController: UIViewController {

    @IBOutlet var buttonResponseLabel: UILabel!
    var userIsCurrentlyTyping: Bool = false
    var storedValue: Int = 0;
    var currentOperation = 0
    var currentNumberInLabel = ""

    @IBAction func buttonAppend(_ sender: UIButton)
    {
        let buttonTitle = sender.currentTitle!

        switch buttonTitle
        {
            case "+":
            currentOperation = 1
            storedValue = Int(currentNumberInLabel)!
            buttonResponseLabel.text = ""
            case "-":
            currentOperation = 2
            storedValue = Int(currentNumberInLabel)!
            buttonResponseLabel.text = ""
            case "*":
            currentOperation = 3
            storedValue = Int(currentNumberInLabel)!
            buttonResponseLabel.text = ""
            case "/":
            currentOperation = 4
            storedValue = Int(currentNumberInLabel)!
            buttonResponseLabel.text = ""
            default:

            if buttonTitle == "="
            {
                var finalValue = 0
                print(currentNumberInLabel)
                let secondStoredValue = Int(currentNumberInLabel)!
                if currentOperation == 1
                {
                    finalValue = storedValue + secondStoredValue
                    buttonResponseLabel.text = ""
                    buttonResponseLabel.text = String(finalValue)
                }
                else if currentOperation == 2
                {
                    finalValue = storedValue - secondStoredValue
                    buttonResponseLabel.text = ""
                    buttonResponseLabel.text = String(finalValue)
                }
                else if currentOperation == 3
                {
                    finalValue = storedValue * secondStoredValue
                    buttonResponseLabel.text = ""
                    buttonResponseLabel.text = String(finalValue)
                }
                else if currentOperation == 4
                {
                    finalValue = storedValue / secondStoredValue
                    buttonResponseLabel.text = ""
                    buttonResponseLabel.text = String(finalValue)
                }
            }
            else
            {
                if userIsCurrentlyTyping
                {
                    currentNumberInLabel = buttonResponseLabel.text! + buttonTitle
                    buttonResponseLabel.text = currentNumberInLabel
                }
                else
                {
                    userIsCurrentlyTyping = true
                    buttonResponseLabel.text = ""
                    buttonResponseLabel.text = buttonTitle
                }

            }

            print("\(currentOperation) \(buttonTitle)")
        }

    }

}


texts:
Here is another example of a moving ball.  I would like to see how to make it more efficient and better. I think that moving the variables to the top of the function would be better but then I tried this and it would not work as good as it did.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH5EX9: Moving In Circle</title>
<script src="modernizr.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
    canvasApp();

}

function canvasApp() {
    var radius = 100;
    var circle = {centerX:250, centerY:250, radius:125, angle:0}
    var ball = {x:0, y:0,speed:.1};

    theCanvas = document.getElementById('canvasOne');
    context = theCanvas.getContext('2d');

  function  drawScreen () {

        context.fillStyle = '#EEEEEE';
        context.fillRect(0, 0, theCanvas.width, theCanvas.height);
        //Box
        context.strokeStyle = '#000000';
        context.strokeRect(1,  1, theCanvas.width-2, theCanvas.height-2);

        ball.x = circle.centerX + Math.cos(circle.angle) * circle.radius;
        ball.y = circle.centerY + Math.sin(circle.angle) * circle.radius;

        circle.angle += ball.speed;

        context.fillStyle = "#000000";
        context.beginPath();
        context.arc(ball.x,ball.y,15,0,Math.PI*2,true);
        context.closePath();
        context.fill();
    }

    function gameLoop() {
            window.setTimeout(gameLoop, 20);
            drawScreen()
        }

    gameLoop();
}

</script>

</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
   <canvas id="canvasOne" width="500" height="500">
    Your browser does not support the HTML 5 Canvas.
   </canvas>
</div>
</body>
</html>


texts:
I have to parse a custom configuration file with this structure:

# Begin with core containers.

ID          = 0 # STX container
Name        = "" # No name is necessary for a STX container.
Flags       = {STX}
Attributes  = {Status=0}

So I've written the following code in order to remove those comments (starting with #) and the inline comments. I don't know if I'm doing it the right way, it just seems (for me, not too much experience) a stupid way of doing it with many while loops.

void NextToken() {
   // Let's begin taking comments away!
   FILE* Source = fopen("defs.dat", "r");
   char* Buffer = calloc(MAXBUFLEN, sizeof(char));
   while (fgets(Buffer, MAXBUFLEN, Source)) {
    // If line starts with '#' it is a comment, so it must be ignored. If it's a newine it just has to be skipped.
    if (Buffer[0] == 35 || Buffer[0] == '\n')
        continue;
    // Now we have to delete inline comments
    int Pos = 0;
    while (Pos < strlen(Buffer)) {
        if(Buffer[Pos] == '#') {
            Pos++;
            while(Buffer[Pos] != '\n')  {
                Pos++;
                continue;
            }
            continue;
        }
        //Cool! now just let's print the output.
        printf("%c", Buffer[Pos++]);
    }
   }
}

The max size of the buffer is 256 characters.


texts:
I have a simple array in PHP like this :
Array
(
    [max_size_video] => 50000
    [max_size_photo] => 8000
    [token_expire] => 100
    [dns] => mydns.fr
    ...
)

I would like to convert this array to multidimensional format with underscore as a separator:
Array
(
    [max] => Array
        (
            [size] => Array
                (
                    [video] => 50000
                    [photo] => 8000
                )
        )
    [token] => Array
        (
            [expire] => 100
        )
    [dns] => mydns.fr
    ...
)

I can do this with the following ugly code :
$item = explode('_', $row);
switch (count($item)) {
  case 1:
    $array[$item[0]] = $value;
  break;
  case 2:
    $array[$item[0]][$item[1]] = $value;
  break;
  case 3:
    $array[$item[0]][$item[1]][$item[2]] = $value;
  break;
  case 3:
    $array[$item[0]][$item[1]][$item[2]][$item[3]] = $value;
  break;
  ...
}

How can I do this with a more elegant function?


texts:
According to https://stackoverflow.com/questions/19608546/optimize-regex-for-maximum-speed
and comments to ask my question here .
Please help me to optimize following regex to best performance . I have read some articles but this problem should solve quickly to decrease cpu usage and delay time so i don't have enough time for try and false .

First one should match for example

http://microsoft.com/test/temp.iso

http://download.microsoft.com/TEMP.iso

http://www.download.microsoft.com/test.aspx?hdwjdhcjdgcjhdc=TEMP.iso

note:

All url should start with http://  so i don't know it is better to put ^http:// at first or not ?
first line and last line have specific rules but lines between them may combined.
These regexp are used in squid configuration.

Any help appreciated .

refresh_pattern -i (.+\.||)(microsoft|windowsupdate).com/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|iso|psf)
refresh_pattern -i (.+\.||)eset.com/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ver|nup)
refresh_pattern -i (.+\.||)avg.com/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)
refresh_pattern -i (.+\.||)grisoft.(com|cz)/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)
refresh_pattern -i (.+\.||)avast.com/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|vpx|vpu|vpa|vpaa|def|stamp)
refresh_pattern -i (.+\.||)(kaspersky-labs|kaspersky).com/.*\.(cab|zip|exe|msi|msp|bz2|avc|kdc|klz|dif|dat|kdz|kdl|kfb)
refresh_pattern -i (.+\.||)nai.com/.*\.(gem|zip|mcs|tar|exe|)
refresh_pattern -i (.+\.||)adobe.com/.*\.(cab|aup|exe|msi|upd|msp)
refresh_pattern -i (.+\.||)symantecliveupdate.com/.*\.(zip|exe|msi)
refresh_pattern -i (.+\.||)(192\.168\.10\.34|mywebsite.com)/.*

After help of Stackoverflow guys i have changed it to this . Any more optimization ?

refresh_pattern -i (.+\.)?(microsoft|windowsupdate)\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|iso|psf)$
refresh_pattern -i (.+\.)?eset\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ver|nup)$
refresh_pattern -i (.+\.)?avg\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)$
refresh_pattern -i (.+\.)?grisoft\.(com|cz)/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)$
refresh_pattern -i (.+\.)?avast\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|vpx|vpu|vpa|vpaa|def|stamp)$
refresh_pattern -i (.+\.)?(kaspersky-labs|kaspersky)\.com/.*?\.(cab|zip|exe|msi|msp|bz2|avc|kdc|klz|dif|dat|kdz|kdl|kfb)$
refresh_pattern -i (.+\.)?nai\.com/.*?\.(gem|zip|mcs|tar|exe|)$
refresh_pattern -i (.+\.)?adobe\.com/.*?\.(cab|aup|exe|msi|upd|msp)$
refresh_pattern -i (.+\.)?symantecliveupdate\.com/.*?\.(zip|exe|msi)$
refresh_pattern -i (.+\.)?(192\.168\.10\.34|mywebsite\.com)/.*?$

Edit: Squid does not accept (?:content) so i removed it . any replacement ?


texts:
In CodeIgniter, I have created function (helper) to populate, store and retrieve checkbox group. I just wonder if I have written code is in proper way and optimized or needs some more finishing?

Function

if ( ! function_exists('checkbox_group') )
{
    function checkbox_group($checkboxes = array(), $name)
    {

    // setting hidden field for null, if no checkbox selected
    echo form_hidden($name.'[]', 'null');

    // start checkbox loop
    foreach($checkboxes as $check => $label_text):

        $checked = FALSE;
        $selects = get_config_row($name);
        if(in_array($check, $selects))
        $checked = TRUE;

        echo '
';
        echo form_label(form_checkbox($name.'[]', $check, $checked, 'id="'.$check.'" class="checkbox"') . $label_text, $check);
        echo '
';
    endforeach;
    }
}

Usage

// checkbox items
$checkboxes = array(
    'noindex'=>'No Index',
    'nofollow'=>'No Follow',
    'noarchive'=>'No Archive',
    'nosnippet'=>'No Snippet'
);

// render checkboxes useing function
checkbox_group($checkboxes, 'indexes');


texts:
This is my solution to the ECOO 2015 contest, problem 1, Fractorials. I'd appreciate any advice to improve readability, style, organization, etc.

def main():
    number = int(input())
    fractorial = {}
    for i in range(2, number + 1):
        prime_factorization = prime_factor(i)
        update_fractorial(prime_factorization, fractorial)

    print(compute_fractorial_value(fractorial))

def prime_factor(number):
    primes = [2, 3, 5, 7, 11, 13, 17, 19]
    dict = {}
    i = 0
    while i < len(primes):
        p = 0
        while number % primes[i] == 0:
            number = number // primes[i]
            p += 1

        if p != 0:
            dict[primes[i]] = p

        i += 1

    return dict

def update_fractorial(prime_factorization, fractorial):
    for key in prime_factorization:
        if key in fractorial:
            if prime_factorization[key] > fractorial[key]:
                fractorial[key] = prime_factorization[key]
        else:
            fractorial[key] = prime_factorization[key]

        # Or should I replace the if/else statements with:
        #
        # if key in fractorial:
        #   if prime_factorization[key] < fractorial[key]:
        #      break
        #
        # fractorial[key] = prime_factorization[key]
        #
        # since it is shorter.

def compute_fractorial_value(fractorial):
    value = 1
    for key in fractorial:
        value *= key ** fractorial[key]

    return value

main()


texts: Python function to strip inline repr'd unicode strings

texts:
I have to write a python function that takes a string that contains raw unicode strings (e.g. "u'hello' there") and transform it into a string that strips the u'' identifiers from it. For example:

strip_inline_unicode("u'hello' there")  # -> 'hello there'

Without getting into too much detail as to why I have to do this, sufficed to say I cannot simply replace the logic that generates these strings, and I have to strip these because it is being returned as human-readable output to a user.

Constraints:

Strings can have "malformed" unicode identifiers which should be handled correctly (e.g. "hello u'there" -> "hello there")
Strings can have empty unicode identifiers (e.g. "hello u''there" -> "hello there")
Strings will never have "nested" unicode identifiers (e.g. 'u"u\'foo\'"')
Quotes will always be single-quotes (so never u"<stuff>")

Here is what I came up with:

def strip_inline_unicode(stupid_string):
    """Takes a string that looks like "u'hello' there" and returns
    "hello there" """

    in_unicode = False
    pos = 0

    new_str = ''

    while (pos < len(stupid_string)):
        if pos + 1 >= len(stupid_string):
            if in_unicode and stupid_string[-1] == "'":
                new_str += stupid_string[pos:-1]
            else:
                new_str += stupid_string[pos:]
            break

        cur = stupid_string[pos]
        nxt = stupid_string[pos + 1]
        if cur == 'u' and nxt == "'" and not in_unicode:
            in_unicode = True
            pos += 1
        elif in_unicode and cur == "'":
            in_unicode = False
        else:
            new_str += cur

        pos += 1

    return new_str

When I plug it into the interpreter it seems to work correctly:

In [12]: strip_inline_unicode("u'hello' there")
Out[12]: 'hello there'

In [14]: strip_inline_unicode("hello there")
Out[14]: 'hello there'

In [15]: strip_inline_unicode("hello u'there")
Out[15]: 'hello there'

In [16]: strip_inline_unicode("hello u''there")
Out[16]: 'hello there'

In [17]: strip_inline_unicode("au'b'")
Out[17]: 'ab'

In [18]: strip_inline_unicode("u'abc'")
Out[18]: 'abc'

However, I am by no means a Python expert, and it seems like I could accomplish something similar in a simpler and more robust manner, perhaps by using regexes. I was hoping to get some feedback on the implementation and maybe simplify it/make it better.


texts: Replacing an F# loop over a mutable variable by an immutable approach

texts:
Consider:

        let mutable m' = m
        while m' % i = 0L do
            m' <- m' / i

I've refactored it into:

        let m' =
            let rec exhaust m =
                if m % i = 0L then exhaust (m/i)
                else m
            exhaust m

but it's pretty obvious to me that the original code was way more concise and clear than this last one. Is there anything simple and clear that I'm missing regarding this refactor?

The full algorithm:

(* Calculates all the prime factors of a given integer *)
let primeFactors x =
    let rec primeFactors' = function
        | (m, _, r) when m = 1L -> r
        | (m, i, r) ->
            let mutable m' = m
            while m' % i = 0L do
                m' <- m' / i
            primeFactors' (m', (i+1L), (if m <> m' then i::r else r))
    List.rev (primeFactors' (x, 2L, []))


texts: Representing historical prices of certain financial instruments

texts:
I have an object which represents historical prices of certain financial instruments as below:

 class DailyPrice
        {
            public DateTime? Date { get; set; }
            public double? Price { get; set; }
        }

This needs to be converted into QuarterlyPrice objects which will have all daily prices aggregated:

class QuarterlyPrice
        {
            public QuarterlyPrice()
            {
                DailyViews = new List<DailyPrice>();
            }
            public DateTime? Date { get; set; }
            public double? Price { get; set; }
            public List<DailyPrice> DailyViews { get; set; }
        }

Now I need to aggregate the daily prices into quarterly prices. I already have the logic of finding the quarters given a date range and the aggregation logic is as follows:

class Aggregater
        {
            public IEnumerable<QuarterlyPrice> GetQuarterlyAggViews(List<DailyPrice> dailyViews)
            {
                var dates = dailyViews.Where(x => x.Date.HasValue).Select(x => x.Date.Value).ToList();
                var dictionary = dailyViews.ToDictionary(x => x.Date.Value, x => x);

                //Will give me quarterly dates from the last to fist.
                var allQuarters = dates.Last().GetAllQuarters(dates.First());

                foreach (var quarter in allQuarters)
                {
                    var quarterlyPrice = new QuarterlyPrice();
                    var daily = dictionary.Where(x => x.Key <= quarter).Select(lx => lx.Value).ToList();
                    quarterlyPrice.DailyPrice.AddRange(daily);
                    quarterlyPrice.Date = quarter;
                    quarterlyPrice.Price = daily.Sum(x => x.Price);
                    yield return quarterlyPrice;
                }
            }
        }

My questions are the following:

My daily prices can spawn 10-20 years and there will be as many daily price object. While aggregating them I'm putting them in the dictionary assuming the lookup would be quicker. Is this the correct thing to do? Is there a way to optimize the look up a bit further?
How can I write a better aggregation logic for converting daily to quarterly price?

Note: The daily price list is sorted using .NET 4.0.


texts: A filled_multi_array Template Function for Boost.MultiArray in C++

texts:
This is a follow-up question for A ones Function for Boost.MultiArray in C++. Thanks to G. Sliepen's answer, the mentioned method which can set various initial value is better in generic purpose usage. However, the previous function specified the input type which must be boost::detail::multi_array::extent_gen<NumDims>. The type issue happened in some cases, an example is as below. The object filled_multi_array1 is created first with filled_multi_array(boost::extents[3][4][2], 1.0). This works well. I want to create a filled_multi_array2 object which size is as same as filled_multi_array1 and the initial value is 2.0. This doesn't work in existed version of filled_multi_array function.
auto filled_multi_array1 = filled_multi_array(boost::extents[3][4][2], 1.0);
auto filled_multi_array2 = filled_multi_array<double, filled_multi_array1.dimensionality>(filled_multi_array1.shape(), 2.0);

for (decltype(filled_multi_array2)::index i = 0; i != 3; ++i)
    for (decltype(filled_multi_array2)::index j = 0; j != 4; ++j)
        for (decltype(filled_multi_array2)::index k = 0; k != 2; ++k)
            std::cout << filled_multi_array2[i][j][k] << std::endl;

Then, I found that the type returned from .shape() function is this one const boost::detail::multi_array::multi_array_base::size_type*. It seems that the another function overloading is needed to handle the above filled_multi_array2 case. The experimental code of the filled_multi_array function with the input type const boost::detail::multi_array::multi_array_base::size_type* is as follows.
template<class T, std::size_t NumDims>
auto filled_multi_array(const boost::detail::multi_array::multi_array_base::size_type* size, const T& value)
{
    boost::multi_array<T, NumDims> output(reinterpret_cast<boost::array<size_t, NumDims> const&>(*size));
    std::fill_n(output.data(), output.num_elements(), value);
    return output;
}

With this overloaded function, filled_multi_array2 object can be generated successfully and the output is like:
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2

The full implementation of filled_multi_array template function:
template<class T, std::size_t NumDims>
auto filled_multi_array(boost::detail::multi_array::extent_gen<NumDims> size, const T& value)
{
    boost::multi_array<T, NumDims> output(size);
    std::fill_n(output.data(), output.num_elements(), value);
    return output;
}

template<class T, std::size_t NumDims>
auto filled_multi_array(const boost::detail::multi_array::multi_array_base::size_type* size, const T& value)
{
    boost::multi_array<T, NumDims> output(reinterpret_cast<boost::array<size_t, NumDims> const&>(*size));
    std::fill_n(output.data(), output.num_elements(), value);
    return output;
}

All suggestions are welcome.
The summary information:

Which question it is a follow-up to?
A ones Function for Boost.MultiArray in C++

What changes has been made in the code since last question?
The another overloaded filled_multi_array function has been added here.

Why a new review is being asked for?
I am trying to handle both cases, including the one with the specified shape directly and the other one with .shape() function (the shape is referenced from another Boost.MultiArray object). If there is any possible improvement, please let me know.


texts: Managing several payment means in my Rails 3.2 app

texts:
I'm trying to manage several means of payment in my Rails 3.2 application.

Let's say I have 2 means : Credit Cards & Bank Transfers (BIC), working with 2 different payment providers. Those means both contain a reference string that will be sent to the payment provider to trigger new payments later.
Each means also contains specific information. This is why I'm thinking about creating 2 models (a CreditCard one and a Bic one). And I would like to link both models to the User model.

A single user can have for example 2 credit cards and 1 BIC so there must be at least a have_many association.
I don't want my user model to have too many different associations, but I want it to have the same behavior for each kind of payment mean. I though about using the Single Table Inheritance but I previously had a bad experience with the combo "STI + associations" and I lost a lot of time.

So, my solution to that problem would be to make an intermediate model PaymentMean that would:

belong to User
be associated to both CreditCard and Bic with a polymorphic "belongs_to" association

as follows:

class User < ActiveRecord::Base
  has_many :payment_means
end

class PaymentMean < ActiveRecord::Base
  belongs_to :user
  belongs_to :payment, polymorphic: true
end

class CreditCard < ActiveRecord::Base
  has_one :payment_mean, as: :payment
end

class Bic < ActiveRecord::Base
  has_one :payment_mean, as: :payment
end

What do you think about it ? Should I try to use STI (if so, HOW ?) or is this model viable ? Or is there any other solution ?


texts: Solution for sum of all fizzbuzz numbers in a given range

texts:
The number fizz buzz is composed of two numbers that are fizz and buzz.

fizz represents the numbers that are divisible by 3 and buzz are the numbers that are divisible by 5.

combining both fizz buzz are the numbers that are divisible by both 3 and 5 both. So how can we get all the fizz buzz numbers sum in a given range?

If we analyze and try to find out the numbers that are divisible by both 3 and 5 we get series like this:

3*5*1, 3*5*2, 3*5*3, .....,3*5*n

analyzing this here is my C# code to find all fizz buzz numbers sum in a given range.

I am looping through the entire range and add all numbers whose remainder with 15 is 0.

int start_range = Convert.ToInt32(Console.ReadLine());
int end_range = Convert.ToInt32(Console.ReadLine());
int sum = 0;
for(int i= start_range; i<= end_range; i++)
{
    if(i%15==0)
    {
        sum = sum + i;
    }
}
Console.WriteLine(sum);
Console.ReadKey();


texts: "Guess a random letter" game with command line interface

texts:
The code below if launched on the command line is a simple guessing game.
A random character 'a', 'b' or 'c' is chosen, and the user is prompted until they guess correctly.
It's arguable that invalid input and a win is not necessarily exceptional.  Should exceptions be used in this manner?
I am not sure what's a sensible way to check for a winning situation and to terminate the game.
<?php

class ABorCException extends Exception {
    const WIN     = 'Win';
    const INVALID = 'Invalid';
}

class ABorC
{
    const CHOICES = ['a', 'b', 'c'];
    public $answer;
    public $turns;

    public function __construct($answer = null)
    {
        $this->answer = $answer ?? self::CHOICES[array_rand(self::CHOICES)];
    }

    public function turn($guess)
    {
        if(!in_array($guess, self::CHOICES))
            throw new ABorCException(ABorCException::INVALID);
        $this->turns[] = $guess;
        if($guess === $this->answer)
            throw new ABorCException(ABorCException::WIN);
    }
}

$game = new ABorC;

while (true) {
    try {
        $input = readline("Enter your guess a, b or c?\n");
        $game->turn($input);
        echo "Wrong!\n", "Guess again.\n";
    } catch (ABorCException $e) {
        if($e->getMessage()===ABorCException::INVALID) {
            echo "Invalid input.\n";
        }
        if($e->getMessage()===ABorCException::WIN) {
            echo "Correct!\n", "You won in ", count($game->turns), " valid attempts.\n";
            exit;
        }
    }
}

Sample game:
$ php aborc.php
Enter your guess a, b or c?a
Wrong!
Guess again.
Enter your guess a, b or c?z
Invalid input.
Enter your guess a, b or c?b
Correct!
You won in 2 valid attempts.


texts: Simple streaming parser to extract columns

texts:
In reply to previous question I rewrote ColumnReader and would like more suggestions

using System;

namespace R2D.IO
{
    public sealed class LineReader
    {
        public string NewLine { get; set; }

        string _buffer = "";

        public void Parse(string text)
        {
            _buffer += text;

            var lastline = _buffer.LastIndexOf(NewLine);
            if (lastline == -1)
                return;

            var lines = _buffer.Substring(0, lastline).Split(NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            _buffer = _buffer.Substring(lastline);

            foreach (var line in lines)
                Receive(line);
        }

        public event Action<string> Receive = (line) => { };
    }

    public sealed class ColumnReader
    {
        public string Delimiter { get; set; }
        public string NewLine
        {
            get { return reader.NewLine; }
            set { reader.NewLine = value; }
        }

        private LineReader reader = new LineReader();

        public ColumnReader()
        {
            reader.Receive += (line) => Receive(line.Split(Delimiter.ToCharArray()));
        }

        public event Action<string[]> Receive = (columns) => { };
    }
}

My main use-case is reading lines from a SerialPort:

var parser = new IO.LineReader { NewLine = port.NewLine };
port.DataReceived += (o, e) => parser.Parse(port.ReadExisting());
parser.Receive += (line) => { };


texts: Implementation of Queue using Linkedlist in Java

texts:
Can someone please review my code? Is it the correct implementation of a queue? If not, please give suggestions on how to implement it using a linked list.

class Queue
{
Node front,rear;

class Node
{
    int data;
    Node next;

    public Node(int d)
    {
        data=d;
        next=null;
    }
}

void enqueue(int new_data)
{
    Node new_node=new Node(new_data);

    if(front==null)
    {
        new_node.next=front;
        front=new_node;
        rear=front;
    }
    else if(rear.next==null)
    {
        rear.next=new_node;
        rear=rear.next;
    }
    System.out.println(rear.data+"\t Enqueued");
}

Node dequeue()
{
 if(front==null && rear==null)
 {
System.out.println("\t Queue is Empty");
  return null;
 }
    else    {
    Node temp=front;
    front=temp.next;
    temp.next=null;
    System.out.println(temp.data+"\t Dequeued");
if(front==null)
    { rear=front; }

    System.out.println(front +" "+ rear);
    return temp;
    }
}

public static void main(String[] args)
{
    Queue q=new Queue();
    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);
    q.enqueue(4);

    q.dequeue();
    q.dequeue();

}
}


texts:
When generating a matrix barcode, it takes 1 minute per 10000 files .That's how to generating a matrix barcode for big quantities in less time.

Here is the library used to encoder data.

My code for button generating:

Class1 CLS = new Class1();
DataTable dt = CLS.ShowalldataSerial(textBox4.Text);

for (int i = 0; i <= Convert.ToInt32(textBox1.Text); i++)
{
    Serial = SRL.Rnd().ToString();
    txt = "UserID" + dt.Rows[0][0] + "FirmName" + dt.Rows[0][1] + "OrderNo" + dt.Rows[0][2] + "BtachNo" + dt.Rows[0][3] + "Quantity" + dt.Rows[0][4] + "ProductName" + dt.Rows[0][5] + "SerialNo" + Serial;

    dm.DM(txt, Color.FromName(comboBox1.SelectedItem.ToString()), Color.White).Save(root + "\\" + Serial + ".emf", System.Drawing.Imaging.ImageFormat.Emf);

}
MessageBox.Show("Records generated success ");

When creating 10000 in textbox1 it take 1 minute. If I write 200000 in textbox1 it takes 20 minutes.

The code is working without any problems and gives me results that I need, but it is slow. Can someone help me speed it up?