texts: A geometry Sector Solver, Value finder for my calculator's micropython

texts:
I made a program for my calculator for A levels that acquires the value of the angle and radius of a sector and gives:

Area of Sector
Area of inner Triangle
Arc Length
Chord Area
Chord Length
Sector Perimeter

I need some advice on compacting and making it more efficient, it would be also nice to have some coding tricks.

Disclaimer: my calculator uses micropython which lacks alot of functions, and modules however some functions from math work, check the documentary about it to confirm.

from math import pi, sin

def input_pi_replacer(prompt):
    return float(eval(input(prompt).replace("pi", str(pi))))

def stopper():
    stop_or_continue = input("Stop?: ")
    if stop_or_continue == "x":
        raise SystemExit

print("Sector Quantities\nCalculator:\n")
C_Factor = 0
Area = 0
B = 0
while True:
    C_Factor = 0
    Area = 0

    Unit = ""
    # + = degrees , - = radians
    while Unit not in ['+', '-']:
        Unit = input("For Deg, enter '+',\nFor Rad, enter '-'\n: ")
        if Unit == "+":
            C_Factor = pi/180
            break
        elif Unit == "-":
            C_Factor = 180/pi
            break
        elif Unit == ".":
            raise SystemExit
    # R = Radius, A = theta/angle in deg/rads, C_Angle = Converted Angle, C_Factor = Conversion Factor of Angle

    R = input_pi_replacer("\nEnter Radius: ")
    A = input_pi_replacer("Enter Theta/Angle: ")

    if Unit == "+":
        C_Angle = A * C_Factor
        Angle_In_Deg = A
    elif Unit == "-":
        C_Angle = A
        Angle_In_Deg = A * C_Factor

    print()
    Sector_Area = 1/2 * (R**2) * C_Angle
    Triangle_Area = 1/2 * (R**2) * sin(C_Angle)
    Arc_Length = R * C_Angle
    Chord_Area = Sector_Area - Triangle_Area
    Chord_Length = 2 * R * sin(C_Angle/2)
    Perimeter_Sector = 2 * R + Arc_Length
    print("Area of Sector\n= ", Sector_Area)
    print("Area of inner Triangle\n= ", Triangle_Area)
    print("Arc Length\n= ", Arc_Length)
    print("Chord Area\n= ", Chord_Area)
    print("Chord Length\n= ", Chord_Length)
    print("Sector Perimeter\n= ", Perimeter_Sector)
    print()
    stopper()


texts: Make multiple conditions in if expression more readable

texts:
My logic has to be written in this way, but I think the if expression is too long to read.

How can I make it more readable?

  if @tool_cvt_video_info_test.save and check_and_update_firmware_model_and_version(params["camera_ip"]) and save_uploaded(params[:videos])

    format.html { redirect_to @tool_cvt_video_info_test, notice: 'Video info test was successfully created.' }
    format.json { render action: 'show', status: :created, location: @tool_cvt_video_info_test }
  else
    format.html { render action: 'new' }
    format.json { render json: @tool_cvt_video_info_test.errors, status: :unprocessable_entity }
  end


texts: How do I clean up these Python decorators?

texts:
I wrote some type checking decorators for Python. One checks the type that a function returns, the other checks the type that a function accepts.

import functools

def returns(t):
""" Calls a function, and if it returns something of the wrong type,
    throws a TypeError
"""
    def outer(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            output = func(*args, **kwargs)
            if not isinstance(output, t):
                message = "function {} returned an invalid type: {} is a {}"
                raise TypeError(message.format(func.__name__,
                                               output,
                                               type(output)))
            else:
                return output
        return wrapper
    return outer

class accepts:
    def __init__(self, *artypes, **kwtypes):
        """ Pass it a list consisting of types or tuples of types.
        in other words, pass it things that will be valid second
        arguments to the isinstance(arg, type) method.
        """
        self.artypes = artypes
        self.kwtypes = kwtypes

    def checkTypes(self, args, kwargs):
        """ Checks each arg and kwarg for type validity, and if
            they fail, then it throws a TypeError. Not very descriptive,
            but it's just an example.
        """
        type_zip = zip(args, self.artypes)
        for arg, type_ in type_zip:
            if not isinstance(arg, type_):
                raise ValueError()

        for key, value in kwargs.items():
            if not isinstance(value, self.kwtypes[key]):
                raise ValueError()

    def __call__(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            self.checkTypes(args, kwargs)
            return func(*args, **kwargs)
        return wrapper

@accepts(int)
def hitimes(times=1):
    return "hello " * times

@accepts(int, word=str)
def byetimes(times, word="bye"):
    return " ".join([word] * times)

print(hitimes(2)) # works
print(byetimes(5)) # works
print(byetimes(3, word="adios")) # works as expected
print(byetimes(3, word=[])) # fails as expected

For returns, I used nested functions, and for accepts I used the class style of decorator. But both of them get pretty unwieldy with respect to indentation levels. What can I do to make these cleaner?

Note that the wrappers are themselves pretty pointless.


texts:
My goal was to get my hands dirty in OOP by designing and using classes and getting started with inheritance and other OOP concepts.

I have written a very small code to play a card Game called "War". The rules are simple. Each person playing the game is given 1 card. The person with the highest card wins. I am not worrying too much about Ties right now. My code does work but I wanted feedback on my OOP usage.

import itertools
import random
class Cards:
    def __init__(self):
        self.suits = ['Spades','Hearts','Diamonds','Clubs']
        self.values = range(1,14)
        self.ActualCards = [] #Empty List to Append
        for Card in itertools.product(self.suits,self.values):
            self.ActualCards.append(Card) #Cartesian Product to Create Deck
    def GetRandomCard(self):
        RandomNumber = random.randint(0,51)
        CardToBeReturned = self.ActualCards[RandomNumber] #Generates Random Card
    return(CardToBeReturned)

class Player:
    def __init__(self,ID,Card):
        self.PlayerID = ID
        self.CardForPlayer = Card

class Game:
    def __init__(self,NameOfGame):
        self.name = NameOfGame

class SimpleWar(Game):
    def __init__(self,NumberOfPlayers):
        self.NumberOfPlayers = NumberOfPlayers
        self.PlayerList = []
    def StartGame(self):
        DeckOfCards = Cards()
        for playerID in range(0,self.NumberOfPlayers):
            CardForPlayer = DeckOfCards.GetRandomCard() #Deal Card to Player
            NewPlayer = Player(playerID,CardForPlayer) #Save Player ID and Card
            self.PlayerList.append(NewPlayer)
        self.DecideWinner()
    def DecideWinner(self):
        WinningID = self.PlayerList[0] #Choose Player 0 as Potential Winner
        for playerID in self.PlayerList:
            if(playerID.CardForPlayer[1]>WinningID.CardForPlayer[1]):
                WinningID = playerID #Find the Player with Highest Card
        print "Winner is Player "+str(WinningID.PlayerID)
        print "Her Card was "+ str(WinningID.CardForPlayer[1]) + " of " + str(WinningID.CardForPlayer[0])

if __name__=="__main__":
    NewGame = SimpleWar(2)
    NewGame.StartGame()


texts:
I'm looking for a function to take a list of generic classes, and map it to different layout of datatable.

That means, I can't just directly map my class property names and values to grid, I need to convert it to the new values.

The solution that I came up with works, but it feels ... sloppy. Can anyone recommend a better way of doing it?

class Program
{
    static void Main(string[] args)
    {
        var list = new List<InputClass>()
        {
            new InputClass {SomeField = "A", OtherField = 1},
            new InputClass {SomeField = "B", OtherField = 2},
            new InputClass {SomeField = "C", OtherField = 3},
            new InputClass {SomeField = "D", OtherField = 4}
        };

        var dict = new Dictionary<string, Func<InputClass, object>>()
        {
            {"ColA", (f) => $"{f.SomeField}ABCD"},
            {"ColB", (f) => DateTime.Now}
        };

        var dt = ToDataTable(list, dict);
        Console.ReadKey();
    }

    public static DataTable ToDataTable<T>(List<T> list, Dictionary<string, Func<T, object>> columns) where T : class
    {
        var dt = new DataTable();

        foreach (var key in columns.Keys)
        {
            var func = columns[key];
            Type[] funcParams = (func.GetType()).GenericTypeArguments;
            dt.Columns.Add(key, funcParams[1]);
        }

        foreach (var record in list)
        {
            var objects = new List<object>();
            foreach (var key in columns.Keys)
            {
                objects.Add(columns[key](record));
            }

            dt.Rows.Add(objects.ToArray());
        }

        return dt;
    }
}

class InputClass
{
    public string SomeField { get; set; }

    public int OtherField { get; set; }
}


texts: Summing some datum for requests in each domain that fall in a date range

texts:
I have a LINQ query which works fine. I am however very interested to understand if this can be written in a more optimum way...

var query = (from r in Results.All.AsEnumerable()
                       where r.RequestType.Id == Id &&
                             r.DateFrom >= sDate &&
                             r.DateTo <= eDate
                       group r by new {r.Data_1} into g
                       select new {data = g.Key.Data_1,
                                    sum = g.Sum(s => int.Parse(s.Data_2))}).ToList();

I am trying to sum Data_2 (stored as a string) by a unique list of Data_1 all by a given date range.

I have provided some sample data below:

For example: facebook.com = 51, m.facebook.com = 94 etc.


texts:
I'm looking for feedback on improving the structure of this code. Also, I could not find the command line executable for Chrome.

General feedback is also requested.

#
#
#
# Divider - configures bash, git, grunt, sublime and chrome
#
#
#

user1=foo

config_bash() {
    rm ~/.bash_profile
    ln -s ~/root/config/bash/login.sh ~/.bash_profile
    source ~/.bash_profile
    echo "Bash configured."
}
config_git() {
    local a="$1"
    if [ $# -eq 0 ]
    then
        a="default"
    fi
    if [ $# -eq 1 ]
    then
        git config --global user.name "$a"
        git config --global user.email "$a@$a.com"
    fi
    git config --global push.default matching
    git config --global core.editor "subl"

    git remote add godaddy $user1@foo.com:~/root.git
    git remote add heroku https://git.heroku.com/frozen-dusk-2587.git
    echo "Git configured."
}
config_grunt() {
    sudo npm install -g grunt-cli
    mkdir ~/root_install/grunt
    ln -s ~/root/config/grunt/package.json ~/root_install/grunt/package.json
    ln -s ~/root/config/grunt/Gruntfile.js ~/root_install/grunt/Gruntfile.js
    cd ~/root_install/grunt
    npm install
    cd ~/root
    echo "Grunt configured."
}
config_sublime_2() {
    ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
    rm  -rf ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/User
    ln -s ~/root/config/sublime ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/User
    echo "Sublime configured."
}
reset_sublime_2() {
    rm -rf ~/Library/Application\ Support/Sublime\ Text\ 2
}
config_chrome(){
    chmod 0444 ~/Library/Application\ Support/Google/Chrome/Default/History
    echo "Chrome configured."
}
config_all() {
    config_bash
    config_git
    config_grunt
    config_sublime_2
    config_chrome
    list
}
list(){
    local a=$(which bash) b=$(which git) c=$(which grunt) d=$(which subl)
    local g=$(which node)  i=$(which heroku)
    echo "****"
    echo "Your bash executble is here: $a."
    echo "Your git executble is here: $b."
    echo "Your grunt executble is here: $c."
    echo "Your sublime executble is here: $d."
    echo "Your node executble is here: $g."
    echo "Your heroku executble is here: $i."
    echo "****"
}


texts:
I'm trying to write terse Perl code to calculate the average of each column in a file. The file can have >= 1 columns.

use strict;
use warnings;
use List::Util qw/sum/;

my @aoc = ();
while (<DATA>) {
  my $c = 0;
  push @{ $aoc[$c++] }, $_ foreach (split);
}
print join (" ", map { sum(@$_)/@$_ } @aoc), $/;

#output: 2.66666666666667 26.6666666666667 266.666666666667

__DATA__
1 10 100
3 30 300
4 40 400

Can this code be any terser? I tried to remove while (<DATA>) by replacing split with map { $c = 0; split } <DATA> but this does not reset $c to 0 for each loop.

Any ideas on how to reduce this code further?


texts:
I created my first Ruby program. Even though it works, I wondered whether I could do something different/better?

#!/usr/bin/ruby

class LuhnyBinChecker
  def initialize(number)
    @number = number
  end

  def check
    createNumberArray
    doubleSecond
    sumNumbers
    getResult
  end

  def createNumberArray
    @numberArray = @number.scan(/\d/).map { |c| c.to_i }
  end

  def doubleSecond
    puts "Checker: doubling every second number from the right.."
    i = @numberArray.length - 1
    pos = 0
    while i >= 0
      if pos.modulo(2) == 1
        @numberArray[i] = @numberArray[i] * 2
      end
      i = i - 1
      pos = pos + 1
    end
  end

  def sumNumbers
    puts "Checker: calculating the sum.."
    @sum = 0
    @numberArray.each do |i|
      if i > 9
        @sum = @sum + splittedSum(i) # treat numbers >= 10 individually
                                     # e.g. 12 -> 1 + 2 = 3
      else
        @sum = @sum + i
      end
    end
  end

  def splittedSum(number)
    numberAsString = number.to_s()
    splittedNumbers = numberAsString.scan(/\d/).map { |c| c.to_i }
    splittedSum = 0
    splittedNumbers.each do |n|
      splittedSum = splittedSum + n
    end
    return splittedSum
  end

  def getResult
    if @sum.modulo(10) == 0
      puts "Credit card number is valid"
    else
      puts "Credit card number is not valid"
    end
  end
end

class CreditCard
  def setCardNumber(number)
    @cardNumber = number
  end

  def getCardNumber
    if @cardNumber!= nil
      @cardNumber
    end
  end

  def verify
    puts "Verifying card number now..."
    checker = LuhnyBinChecker.new(@cardNumber)
    checker.check
  end
end

if __FILE__ == $0
  card = CreditCard.new

  puts "Please enter the credit card number to check:"
  gets              # input card number
  input = $_
  if input.match(/[a-z]/i) != nil || input.match(/\d/) == nil
    puts "Please enter only numbers."
    exit
  end

  card.setCardNumber(input)
  puts "You entered: " + card.getCardNumber
  card.verify
end

Edit: here are two input/output examples:

michael@michael-linlap /media/Data/development/private/scripts $ ruby LuhnyBin.rb
Please enter the credit card number to check:
1111 1111 1111 1111 1111
You entered: 1111 1111 1111 1111 1111
Verifying card number now...
Checker: doubling every second number from the right..
Checker: calculating the sum..
Credit card number is valid

michael@michael-linlap /media/Data/development/private/scripts $ ruby LuhnyBin.rb
Please enter the credit card number to check:
fooobar1111
Please enter only numbers.


texts: Adding more responsibility to this endgame-analyzer class

texts:
I have written a Tic-Tac-Toe game.  I have a class called GameEndAnalyzer that will check if the game has already ended or not.

Would it violate the Single Responsibility Principle if I will add more responsibilities to this class to not only decide if someone has won the game, but who has won (X or O)?  What is the best way to add responsibility to this?

public interface IGameEndAnalyzer
{
    bool IsGameEnd(IBoard board);
}
public class GameEndAnalyzer : IGameEndAnalyzer
{
    public bool IsGameEnd(IBoard board)
    {
        return IsAnyRowHasAllSameValue(board) ||
               IsAnyColumnHasAllSameValue(board) ||
               IsLeftDiagonalHasAllSameValue(board) ||
               IsRightDiagonalHasAllSameValue(board);
    }

    private bool IsAnyRowHasAllSameValue(IBoard board)
    {
        for (int rowIndex = Board.Row.Top; rowIndex <= Board.Row.Bottom; rowIndex++)
        {
            var isSameValue = board
                       .Cells
                       .WhereInRow(rowIndex)
                       .AllCellIs_O_Or_X();

            if (isSameValue)
            {
                return true;
            }
        }

        return false;
    }

    private bool IsAnyColumnHasAllSameValue(IBoard board)
    {
        for (int columnIndex = Board.Column.Left; columnIndex <= Board.Column.Right; columnIndex++)
        {
            var isSameValue = board
                       .Cells
                       .WhereInRow(columnIndex)
                       .AllCellIs_O_Or_X();

            if (isSameValue)
            {
                return true;
            }
        }

        return false;
    }

    private bool IsLeftDiagonalHasAllSameValue(IBoard board)
    {
        var isSameValue = board
                          .Cells
                          .WhereInDiagonalLeft()
                          .AllCellIs_O_Or_X();

        return isSameValue;
    }

    private bool IsRightDiagonalHasAllSameValue(IBoard board)
    {
        var isSameValue = board
                          .Cells
                          .WhereInDiagonalRight()
                          .AllCellIs_O_Or_X();

        return isSameValue;
    }
}


texts: Checking if website exists and adding +1

texts:
I am trying to find if a subwebsite exists in sharepoint, and if it does, then add +1.

I think the loop can be improved.

// subsiteName will be like "FruitCrateOfCompanyX"

public static string FormatMyHomieURL(string subsiteName, string mainSite)
{
    if (!mainSite.EndsWith("/"))
        mainSite = mainSite + "/";

    string temp = mainSite + subsiteName;
    int i = 0;

    while (SubwebExists(temp))
    {
        i++;
        temp = mainSite + subsiteName + i;

    }

    return subsiteName + i;    // I only need to return subSiteName which will be used later on by web services to create a unique subweb
}

public static bool SubwebExists(string url)
{
    bool exists = false;
    Uri u = new Uri(url);
    using (SPSite site = new SPSite(url))
    using (SPWeb web = site.OpenWeb(u.AbsolutePath.ToString(), true))
    {
        exists = web.Exists;
    }

    return exists;
}


texts: Simple Prefix Matching Library in Haskell

texts:
For some context, I'm trying to write a streaming tokenizer in Haskell and noticed that I was writing a lot of functions with the type signature String -> Maybe Int that attempted to consume "the longest possible token matching a particular pattern" from the input stream. The pattern might be something like a quoted string literal in JSON.

I tried using Parsec for a while to get a "prefix matcher", but I kept getting tripped up over what the appropriate userstate is supposed, and what the m argument in ParsecT means. Parsec is probably a strict superset of the functionality that this little library exposes.

A "Matcher" is anything with the type String -> Maybe Int. Matchers are supposed to be greedy and produce the longest prefix that they possibly can. There's also an unenforced property that, in cases where the match is a proper prefix of the input string, adding more characters to the end of a string doesn't extend the prefix. The library also encourages / permits users to write sloppy grammars (for instance using symOrExn) that fail in ugly ways.

I could use some helping figuring out how to generalize String -> Maybe Int. I don't know what class I should insist on for the input Eq a => [a] is the first thing that comes to mind, but it might be possible to make something more general than that. As for the output type maybe a type that's constrained to be a monoid or a group? I really just need a notion of zero and the ability to increment for the index. ... although it might also be possible to generalize the notion of a "prefix" to tree-like structures.

I'm hoping to structure this library eventually as a collection of really concrete implementations for a handful of commonly-used text-like types, as well as a generic implementation that can be used in other circumstances. Advice on how to generalize the library is much appreciated.

module Text.PrefixMatcher.String where
import Data.List

-- A simple non-generic prefix matching library
-- with a few simple combinators
--
-- a Matcher has type (String -> Maybe Int)
--
-- It takes a String and returns a number corresponding
-- to the length of the matched prefix.
--
-- The intended use case here is to provide a simple utility
-- to help in converting a string to a stream of tokens.
--
-- makeMatcher -- make a matcher for a constant string
--

type Matcher = String -> Maybe Int

identityMatcher :: Matcher
identityMatcher str = Just 0

makeMatcher :: String -> Matcher
makeMatcher spec str = case isPrefixOf spec str of
    True -> Just (length spec)
    False -> Nothing

andThen :: Matcher -> Matcher -> Matcher
andThen m1 m2 str = ltotal where
    l1 = m1 str
    ltotal = case l1 of
        Nothing -> Nothing
        (Just l1) ->
            let rest = drop l1 str in
            let l2 = m2 str in
            case l2 of
                Nothing -> Nothing
                (Just l2) -> Just (l1 + l2)

symOrExn :: Matcher -> Matcher -> Matcher
symOrExn m1 m2 str = res where
    l1 = m1 str
    l2 = m2 str
    res = case (l1, l2) of
        -- good cases
        (Just l1, Nothing) -> Just l1
        (Nothing, Just l2) -> Just l2
        -- bad cases
        (Nothing, Nothing) -> Nothing
        -- if you reach this case, the grammar was
        -- constructed badly
        (Just l1, Just l2) -> error "ambiguous match"

leftOr :: Matcher -> Matcher -> Matcher
leftOr m1 m2 str = result where
    l1 = m1 str
    l2 = m2 str

    result = case (l1, l2) of
        (Just l1, _) -> Just l1
        (Nothing, Just l2) -> Just l2
        (Nothing, Nothing) -> Nothing

andThenList :: [Matcher] -> Matcher
andThenList [] = identityMatcher
andThenList [x] = x
andThenList (x:xs) = andThen x (andThenList xs)

leftOrList :: [Matcher] -> Matcher
leftOrList [] = identityMatcher
leftOrList [x] = x
leftOrList (x:xs) = leftOr x (leftOrList xs)


texts:
This is my first time using classes objects and functions. What can I improve on?

#include <iostream>
#include <conio.h>
using namespace std;

class functions{
public:
    void Body(){
        cout << " :: Welcome to Taylor's CALCULATOR! ::" << endl;
    }
    int Addition(int x, int y){
        int ans = x + y;
        return ans;
    }
    int Subtraction(int x, int y){
        int ans = x - y;
        return ans;
    }
    int Multiplication(int x, int y){
        int ans = x * y;
        return ans;
    }
    int Division(int x, int y){
        int ans = x / y;
        return ans;
    }
};

int main(){
int func;
int x, y;

functions key; //Object
key.Body(); //Object

cout << "What function do you want to use? " << endl;
cout << "1 - Addition " << endl;
cout << "2 - Subtraction " << endl;
cout << "3 - Multiplication " << endl;
cout << "4 - Division " << endl;
cout << "Input: " << endl;

cin >> func;
cout << endl;

switch(func){

    case 1: //Addition
        cout << "**ADDITION**" << endl;
        cout << "Please enter first number: " << endl;
        cin >> x;
        cout << "Please enter second number: " << endl;
        cin >> y;
        cout << x << " + " << y << " = ";
        cout << key.Addition(x, y);
        break;
    case 2: //Subtraction
        cout << "**SUBTRACTION**" << endl;
        cout << "Please enter first number: " << endl;
        cin >> x;
        cout << "Please enter second number: " << endl;
        cin >> y;
        cout << x << " - " << y << " = ";
        cout << key.Subtraction(x, y);
        break;
    case 3: //Multiplication
        cout << "**MULTIPLICATION**" << endl;
        cout << "Please enter first number: " << endl;
        cin >> x;
        cout << "Please enter second number: " << endl;
        cin >> y;
        cout << x << " x " << y << " = ";
        cout << key.Multiplication(x, y);
        break;
    case 4: //Division
        cout << "**DIVISION**" << endl;
        cout << "Please enter first number: " << endl;
        cin >> x;
        cout << "Please enter second number: " << endl;
        cin >> y;
        cout << x << " / " << y << " = ";
        cout << key.Division(x, y);
        break;
    default:
        cout << "Invalid Input...";
        break;
}

}


texts:
I have an ASP.NET MVC project wherein I need to follow the open closed principles.

The project converts a .csv file to a model from a database, but in the future we might also have to convert Excel files to the same model from the database.

Now, I have this code in the Convertor class:

public class Convertor
{
    private static ICompanyRepository companyRepository;

    /// <summary>
    /// converts the uploaded csv data to Company model
    /// </summary>
    /// <param name="filePath">the csv data</param>
    /// <returns>a list of Compamy model</returns>
    public List<Company> ConvertCsvToCompanyModel(string filePath)
    {
        companyRepository = new CompanyRepository(new ImportContext());
        List<Company> companies = new List<Company>();

        //Read the contents of CSV file.
        string csvData = System.IO.File.ReadAllText(filePath);

        //we skip the first row, because it contain the header
        var csvLines = csvData.Split('\n').Skip(1);

        //Execute a loop over the rows.
        foreach (string row in csvLines)
        {
            if (!string.IsNullOrEmpty(row))
            {
                if (!companyRepository.CompanyExist(row.Split(',')[0]))//check if already contains the ExternalId
                {
                    companies.Add(new Company
                    {
                        //CounterPartId
                        ExternalId = row.Split(',')[0],
                        //Name
                        TradingName = row.Split(',')[1],
                        //IsBuyer
                        IsForwarder = Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), row.Split(',')[2])),
                        //IsSeller
                        IsCarrier = Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), row.Split(',')[3])),
                        //Phone
                        Phone = row.Split(',')[4],
                        //Fax
                        Fax = row.Split(',')[5]
                    });
                }
            }
        }
        return companies;
    }
}

Can you please give me some hints how to change this code in order to follow the open closed principle? In the future, as I mentioned, it is possible to need a converter for Excel files, too.


texts: Formatting XML strings in JavaScript for readability

texts:
I've created a vanilla JS function to indent XML strings so they can be more easily read. It uses some pretty nasty regex...yes, I know it's a cardinal sin for XML/HTML, but it works. For instance, this string...

<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><ns:getCourseResponse xmlns:ns="http://course.ws.blackboard" xmlns:ax212="http://course.ws.blackboard/xsd" xmlns:ax211="http://ws.platform.blackboard/xsd" /></soapenv:Body></soapenv:Envelope>

...would look like this after being passed through the function:

<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <ns:getCourseResponse xmlns:ns="http://course.ws.blackboard" xmlns:ax212="http://course.ws.blackboard/xsd" xmlns:ax211="http://ws.platform.blackboard/xsd" />
    </soapenv:Body>
</soapenv:Envelope>

Here's the function itself. What can I do to simplify it?

function formatXML(input) {

    // PART 1: Add \n where necessary
    // A) add \n between sets of angled brackets without content between them
    // B) remove \n between opening and closing tags of the same node if no content is between them
    // C) add \n between a self-closing set of angled brackets and the next set
    // D) split it into an array

    xmlString = input.trim()
        .replace(/>\s*</g,'>\n<')
        .replace(/(<[^\/>].*>)\n(<[\/])/g,'$1$2')
        .replace(/(<\/[^>]+>|<[^>]+\/>)(<[^>]+>)/g,'$1\n$2');
    xmlArr = xmlString.split('\n');

    // PART 2: indent each line appropriately

    var tabs = '';          //store the current indentation
    var start = 0;          //starting line
    if (/^<[?]xml/.test(xmlArr[0])) start++;    //if the first line is a header, ignore it

    for (var i = start; i < xmlArr.length; i++) { //for each line
        var line = xmlArr[i].trim();    //trim it just in case
        if (/^<[/]/.test(line)) { // if the line is a closing tag
            // remove one tab from the store
            // add the tabs at the beginning of the line
            tabs = tabs.replace(/.$/, '');
            xmlArr[i] = tabs + line;
        } else if (/<.*>.*<\/.*>|<.*[^>]\/>/.test(line)) { // if the line contains an entire node
            // leave the store as is
            // add the tabs at the beginning of the line
            xmlArr[i] = tabs + line;
        } else { // if the line starts with an opening tag and does not contain an entire node
            // add the tabs at the beginning of the line
            // and add one tab to the store
            xmlArr[i] = tabs + line;
            tabs += '\t';
        }
    }

    //rejoin the array to a string and return it
    return xmlArr.join('\n');
}


texts: Simplify Google places autocomplete address for loop

texts:
I am using the following code to format an address retrieved using the Google Places API. According to Googles docs they recommend looping through the response based on what you list in the componentForm array. Is there a way to optimize this code and simplify it without having to specify the individual if statements?

var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    postal_code: 'short_name'
};

var place = searchaddress.getPlace();

for (var i = 0; i < place.address_components.length; i++) {

    var addressType = place.address_components[i].types[0];

    if (componentForm[addressType]) {

        if (addressType == 'street_number') {
            var streetNumber = place.address_components[i][componentForm[addressType]];
        }

        if (addressType == 'route') {
            var route = place.address_components[i][componentForm[addressType]];
        }

        if (addressType == 'locality') {
            var locality = place.address_components[i][componentForm[addressType]];
        }

        if (addressType == 'administrative_area_level_1') {
            var state = place.address_components[i][componentForm[addressType]];
        }

        if (addressType == 'postal_code') {
            var zipcode = place.address_components[i][componentForm[addressType]];
        }

    }

}

document.getElementById('fullAddress').value = streetNumber + ' ' + route + ', ' + locality + ', ' + state + ' ' + zipcode;


texts:
Wouldn't it be better to always pass parameters by reference to avoid creating unnecessary copies?

#include <iostream>

void deliver(const std::string& message){
    std::cout << message;
}

void say(const std::string message){
    std::cout << message;
}

int main(){

    std::string message = "Hello World";

    deliver(message);
    /* VS */
    say(message);

    return 0;
}

If not, why not?

Because I'm really starting to think references and pointers are useless.

I've been coding in C++ for a year and a half and never even once had to use a reference or pointer.

I've made countless programs and just finished making my biggest one ever, a 5000 lines game, divided in 28 separate files without using any of them.


texts:
My goal is to parse defines in Objective-C code:

#define wowFont [UIFont fontWithName:(DEV)?@"one":@"two" size:(DEV? 10: 12)]
#define wowColor [UIColor colorWithRed:(DEV?240/255.0f:255.0f) green:((DEV)? 230.0f / 255.0f) blue: 10.0f]

I try to write grammar for it:

grammar Defines::Grammar {
    token TOP {
        \s*<define_expression>\n
    }
    token define_expression {

        ^^ #define $<keyword>=\w+ \s+ $<value> = <general_expression>
    }

    token general_expression{
        # here, determine parenthes
        <simple_expression>|[(]<general_expression>[)]|<value_expression>
    }

    token simple_expression{
        # here, determine ?: behaviour
        \s*<general_expression>\s*[?]\s*<general_expression>\s*[:]\s*<general_expression>\s*
    }

    token value_expression {
        # stop here, need to determine ?: operator here
        <numeric_expression>|<string_expression>|<function_invocation_expression>|<bareword_expression>
    }

    token function_invocation_expression {
        [\[] (<class>|<bareword_expression>) \s+ <function_body>\s* [\]]
    }

    token function_body {
        <bareword_expression>|<bareword_expression> \s* [:] <general_expression>
    }

    token bareword_expression {
        [\w_]+
    }

    token string_expression {
        \@["][^"]["]
    }

    token numeric_expression {
        # we could +-*/ numeric expressions, also we can put lead sigil [-]. put parentheses and it could be a <number>
        <numeric_expression> [*/+-] <numeric_expression> | [-+]<numberic_expression> | [(] <numeric_expression> [)] | <number>
    }

    token number {
        # number expression here, ok
        # not needed legal sign here, numeric_expression already have it
        \d+ [\.] \d+
    }
}

Could anybody help to improve it?

P.S: As a part of answer (I hope that somebody will find this documents helpful) I place here a link to Perl 6 book (I found out that Grammars section is good enough for beginning). Perl 6 Book


texts:
This code uses a ReaderWriterLockSlim to store data (on a disk or wherever), so that only one thread can write and many threads can read.

All writers should be finished before reading, and the write should not block the caller.

Basically my solution would work, but it doesn't look and feel natural to .NET since 4.0 the Task Parallel Library (TPL) was introduced...

class JsonApplicationContainerDAO : IApplicationContainerDAO
{

    private static volatile IApplicationContainerDAO instance;
    private static object syncRoot = new Object();

    private readonly BlockingCollection<ICollection<IApplicationConfiguration>> itemsToSave = new BlockingCollection<ICollection<IApplicationConfiguration>>();
    private readonly Thread writerThread ;
    private readonly ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim();

    public static IApplicationContainerDAO Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new JsonApplicationContainerDAO();
                }
            }
            return instance;
        }
    }

    private JsonApplicationContainerDAO()
    {
        writerThread =  new Thread(WriteItems);
        writerThread.Start();
    }

    private void WriteItems(object obj)
    {
        ICollection<IApplicationConfiguration> item = null;
        while((item = itemsToSave.Take()) != null){
            try
            {
                readerWriterLock.EnterWriteLock();
                //do stream stuff here
            }
            finally
            {
                readerWriterLock.ExitWriteLock();
            }
        }
    }

    public ICollection<IApplicationConfiguration> LoadAll()
    {
        try
        {
            readerWriterLock.EnterReadLock();
            //do stream stuff here
        }
        finally
        {
            readerWriterLock.ExitReadLock();
        }

        return null;
    }

    public void Persist(ICollection<IApplicationConfiguration> items)
    {
        itemsToSave.Add(items);
    }
}


texts: Is it OK to use while ((line = r.readLine()) != null) construct?

texts:
I want to refactor the following code because I don't feel comfortable about using assignment inside comparison operator. It looks like pretty idiomatic C, but do you think this is a good practice in Java?

private void demoA(BufferedReader reader) throws IOException {
    String line = null;
    while ((line = reader.readLine()) != null) {
        doSomething(line);
    }
}

Here is an alternative.

private void demoB(BufferedReader reader) throws IOException {
    String line = reader.readLine();
    while (line != null) {
        doSomething(line);
        line = reader.readLine();
    }
}

UPDATE: I've stumbled across a similar question asked couple years ago. It seems that opinions on whether it's OK or not are divided. However, both Guava and Commons IO provide alternative solutions for this issue. If I had any of these libs in the current project, I'd probably use them instead.


texts:
I have to swap the characters in a string before sending said string to a device to show the information sent through a LCD, the method I developed is as follows:

private string StringSwap(string stringToSwap)
{
    if ((stringToSwap.Length % 2).Equals(1))
    {
        stringToSwap += " ";
    }

    char[] array = stringToSwap.ToCharArray();

    for (int i = 0; i < array.Length; i += 2)
    {
        char temp = array[i];
        array[i] = array[i + 1];
        array[i + 1] = temp;
    }
    return new string(array);
}

I want to know if there are any implementations that do this already (I feel like I am reinventing the wheel here) or, in case there is not, know how to optimize and make this code more resilient, while also making it more readable.

Also, should I make this an extension for the string class instead of a method?


texts: TypeScript, checking for keys and subkeys and its variants

texts:
How to reduce code size?

  getAlreadySaved(goal: GoalModel): number {

        if (goal.status && goal.status.investedAmount && !goal.status.pendingIncoming && !goal.status.pendingOutgoing) {
            return goal.status.investedAmount;

        } else if (goal.status && goal.status.investedAmount && goal.status.pendingIncoming && !goal.status.pendingOutgoing) {
            return goal.status.investedAmount + goal.status.pendingIncoming;

        } else if (goal.status && goal.status.investedAmount && !goal.status.pendingIncoming && goal.status.pendingOutgoing) {
            return goal.status.investedAmount - goal.status.pendingOutgoing;

        } else if (goal.status && goal.status.investedAmount && goal.status.pendingIncoming && goal.status.pendingOutgoing) {
            return goal.status.investedAmount + goal.status.pendingIncoming - goal.status.pendingOutgoing;

        } else {
            return 0;
        }

    }


texts:
I am rather new in GUI programming and multi-threading apps. It is just a serial port monitor which plot serial data via pyqtgraph. There are two curves on the first plot (a and b) and one curve on the second plot (c which is (a-a_prevous)/(b-b_prevous)). How can I improve this code in general? I use Python3.5.

from PyQt4 import QtGui
from PyQt4.QtCore import QObject, pyqtSignal
import sys
import serial
import pyqtgraph
import threading
import ui_main
import numpy as np

class GraphPlotter(QtGui.QMainWindow, ui_main.Ui_GraphPlotter):

    def __init__(self):
        super().__init__()
        pyqtgraph.setConfigOption('background', 'w')
        self.a = []
        self.b = []
        self.c = [0]
        self.flag = 'a'
        self.setupUi(self)
        self.plotAB.plotItem.showGrid(True, True, 0.7)
        self.plotC.plotItem.showGrid(True, True, 0.7)
        self.monitor = SerialMonitor()
        self.monitor.bufferUpdated.connect(self.update)
        self.startButton.clicked.connect(self.monitor.start)
        self.stopButton.clicked.connect(self.monitor.stop)
        self.clearBufferButton.clicked.connect(self.clear)

    def update(self, msg):
        if self.flag == 'a':
            self.a.append(msg)
            self.flag = 'b'

        elif self.flag == 'b':
            self.b.append(msg)
            c = pyqtgraph.hsvColor(0.2, alpha=.5)
            pen2 = pyqtgraph.mkPen(color=c, width=3)
            try:
                print((self.a[-1] - self.a[-2]), (self.b[-1] - self.b[-2]))
                self.c.append((self.a[-1] - self.a[-2]) / (self.b[-1] - self.b[-2]))
                self.plotC.plot(np.arange(len(self.c)), self.c, pen=pen2, clear=True)
            except ZeroDivisionError:
                print('Division by zero')
                self.c.append(0)
            except IndexError:
                print('C is not ready')
            finally:
                self.flag = 'a'

            for y, pen in [(self.a, (255, 0, 0)), (self.b, (0, 255, 0))]:
                self.plotAB.plot(np.arange(len(y)), y, pen=pen)

    def clear(self):
        self.a = []
        self.b = []
        self.c = [0]

        self.plotAB.clear()
        self.plotC.clear()

class SerialMonitor(QObject):
    bufferUpdated = pyqtSignal(int)

    def __init__(self):
        super(SerialMonitor, self).__init__()
        self.running = False
        self.thread = threading.Thread(target=self.serial_monitor_thread)

    def start(self):
        self.running = True
        self.thread.start()

    def stop(self):
        self.running = False

    def serial_monitor_thread(self):
        while self.running is True:
            ser = serial.Serial('/dev/ttyS0', 115200)
            msg = ser.readline()
            if msg:
                try:
                    self.bufferUpdated.emit(int(msg))
                except ValueError:
                    print('Wrong data')
            else:
                pass
            ser.close()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    plot = GraphPlotter()
    plot.show()
    app.exec_()


texts:
What would be the most performant way to get the last 2 digits of a string?

For example: getLastTwoDigits("a1b2cd3e4ghi5jk") must return "45";

I had already asked how to get the first two digits of a string. But now I need a performant way to get the last two digits.

I've adapted the answer I received in the other question and I could make it work using the code below. However, I know that I've defeated the purpose of StringBuilder when I used sb.insert(0, char).

private static String getLastTwoDigits(String s) {
    if(s==null)
        return null;

    StringBuilder sb = new StringBuilder(2);

    char charArray[] = s.toCharArray();
    for (int i = charArray.length-1; i>=0; i--) {
        if (Character.isDigit(charArray[i])) {
            sb.insert(0, charArray[i]);
            if (sb.length() == 2)
                break;
        }
    }

    return sb.toString();
}

I imagine that StringBuider is not the right tool for this case. So what would be the most performant solution?


texts:
This question refers to this problem on lintcode. I have a working solution, but it takes too long for the huge testcase. I am wondering how can it  be improved? Maybe I can decrease the number of comparisons I make in the outer loop.

class Solution:
    # @param strs: A list of strings
    # @return: A list of strings
    def anagrams(self, strs):
        # write your code here
        ret=set()
        for i in range(0,len(strs)):
            for j in range(i+1,len(strs)):
                if i in ret and j in ret:
                    continue
                if Solution.isanagram(strs[i],strs[j]):
                    ret.add(i)
                    ret.add(j)

        return [strs[i] for i in list(ret)]

    @staticmethod
    def isanagram(s, t):
        if len(s)!=len(t):
            return False
        chars={}
        for i in s:
            if i in chars:
                chars[i]+=1
            else:
                chars[i]=1

        for i in t:
            if i not in chars:
                return False
            else:
                chars[i]-=1
                if chars[i]<0:
                    return False

        for i in chars:
            if chars[i]!=0:
                return False
        return True


texts: Three ways to read a number for a BitInputStream

texts:
I'm trying to learn how to write more readable code without introducing easily avoidable performance killers.

This is part of a BitInputStream Java class I'm experimenting with. There are code parts before and after this provided segment to read less than 8 bits from iBuffer if data is not aligned to bytes - that's why aNumberOfBits is needed to know how many bits have to be read later on.

I think variant 3 below is best when implemented in Java, but variant 1 may be worth the more complex formula for slightly better (theoretical) performance in C for realtime applications.

Variant 1:

int i = aNumberOfBits / 8;
aNumberOfBits -= i * 8;
for (; i > 0; --i) {
   iBuffer = iIs.read();
   if (iBuffer == -1) {
      throw new EOFException();
   }
   value = (value << 8) | iBuffer;
}

Variant 2 (obviously worse performant on most CPUs?):

for (int i = aNumberOfBits / 8; i > 0; --i) {
   iBuffer = iIs.read();
   if (iBuffer == -1) {
      throw new EOFException();
   }
   value <<= 8;
   value |= iBuffer;
   aNumberOfBits -= 8;
}

Variant 3:

for (int i = aNumberOfBits / 8; i > 0; --i) {
   iBuffer = iIs.read();
   if (iBuffer == -1) {
      throw new EOFException();
   }
   value = (value << 8) | iBuffer;
}
aNumberOfBits %= 8;

Now what about variant 2: should aNumberOfBits be decremented by 8 in the loop for a better understanding why it is decremented? (And isn't shifting value and then ORing the next part of data even more complicated to read than doing it in one step?)


texts: Differ returned web link from app scheme

texts:
I have a WebView, which loads the returned from a request url. The thing is, the url might be a scheme to my app, and if that's the case I need to handle it properly, rather than open it in a WebView. I am not sure if this is the best way to implement that check:

In WebViewClient:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

        String appScheme = getResources().getString(R.string.app_scheme);
        if (url.startsWith("http://" + appScheme + "//checkout")) {
            url = url.substring(7);
            url = new StringBuilder(url).insert(appScheme.length(), ":").toString();
        } else if (url.startsWith("https://" + appScheme + "//checkout")) {
            url = url.substring(8);
            url = new StringBuilder(url).insert(appScheme.length(), ":").toString();
        }

        if (url.startsWith("http:") || url.startsWith("https:")) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        // Otherwise allow the OS to handle things.
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity( intent );
            close();
            return true;
   }

I should also note, that the returned scheme sometimes looks like this:

http://myAppScheme//checkout

when my app can read only this template:

myAppScheme://checkout

I have no control over how the scheme is returned, because this happens from the payment provider I am working with. This is why I need to convert it in the proper template when it's returned in a wrong one.


texts:
For a server-side Java application I want to have a random number generator. I'm using the ISAAC algorithm from Apache Commons Math 3 because it is both cryptographically strong and fast. I have written the following code to initialise the generator:

public class ThreadLocalRandomGenerator {
    private static ThreadLocal<RandomGenerator> instances = new ThreadLocal<>();

    public static RandomGenerator get() {
        RandomGenerator generator = instances.get();
        // Initialise new generator if needed.
        if (generator == null) {
            int[] seed = new int[256];
            seed[0] = (int) (System.currentTimeMillis() & 0xffffffffL);
            seed[1] = System.identityHashCode(new Object());
            for (int i=2 ; i<256 ; i++) {
                seed[i] = 0;
                for (int j=0; j<32; j++) {
                    seed[i] |= (int) ((System.nanoTime() & 1L) << j);
                }
            }
            System.out.println("Initialised random seed: " + Arrays.toString(seed));
            // Create generator.
            generator = new ISAACRandom(seed);
            instances.set(generator);
            // Warm up.
            for (int i=0 ; i<1_000 ; i++) {
                generator.nextLong();
            }
        }
        return generator;
    }
}

Basically I'm using a ThreadLocal to keep several generators around for use in threads, and I'm initialising each one using an array of integers generated from the least significant bits of nanoTime(). The reason for using 256 integers is because that's the internal size of the ISAACRandom class.

Does this seem sensible?


texts: Filtering DbContext data dynamically by user input in WPF applications

texts:
I need to filter database data based on filters available to the end user in the form of search term text box, select boxes etc.

I have put together this code and need feedback if this is a good way to do it or if there are any better solutions.

using Multi.Model;
using System;
using System.Linq;
using System.Windows.Controls;

namespace Multi.Pages
{
    /// <summary>
    /// Interaction logic for Page1.xaml
    /// </summary>
    public partial class Page1 : Page
    {

        public Page1()
        {
            InitializeComponent();
            textBoxName.TextChanged += TextBoxName_TextChanged;
            PopulateDataGrid();
        }

        private void PopulateDataGrid()
        {
            using (var db = new optisysEntities())
            {
                var items = db.clients.AsQueryable();
                items = FilterClients(db, items);
                dataGrid.ItemsSource = items.ToList();
            }
        }

        private System.Linq.IQueryable<Multi.Model.clients> FilterClients(optisysEntities db, System.Linq.IQueryable<Multi.Model.clients> clients)
        {

            if (!String.IsNullOrWhiteSpace(textBoxName.Text)) clients = db.clients.Where(c => c.name.Contains(textBoxName.Text)
                                                                                || c.phone.Contains(textBoxName.Text));
            // if (!String.IsNullOrWhiteSpace(search.Email)) clients = clients.Where(u => u.Email.Contains(search.Email));
            // if (search.UsertypeId.HasValue) clients = clients.Where(u => u.UsertypeId == search.UsertypeId.Value);
            return clients;
        }

        private void TextBoxName_TextChanged(object sender, TextChangedEventArgs e)
        {
            PopulateDataGrid();
        }

    }
}


texts: Find indices of two numbers such that they add up to a target

texts:
The task

...is taken from leetcode

  Given an array of integers, return indices of the two numbers such
  that they add up to a specific target.

  You may assume that each input would have exactly one solution, and
  you may not use the same element twice.

  Example:

  Given nums = [2, 7, 11, 15], target = 9,

  Because nums[0] + nums1 = 2 + 7 = 9, return [0, 1].

const lst = [11, 7, 15, 2]
const target = 9;

My imperative solution

function findIndexOfSumPair(lst, trgt) {
  const len = lst.length;
  for (let i = 0; i < len; i++) {
    const found = lst.findIndex(x => trgt - lst[i] === x);
    if (found !== i && found !== -1) {
      return [found, i];
    }
  }
}

console.log(findIndexOfSumPair(lst, target));

My functional solution

const findIndexOfSumPair2 = (lst, trgt) => {
  return lst.reduce((res, x, i) => {
    const j = lst.findIndex(y => target - x === y);
    return j !== -1 ? [i, j] : res;
  });
};

console.log(findIndexOfSumPair2(lst, target));

The disadvantage with my functional solution is that reduce iterates till the end of the array - even though it may have found a solution already. I tried to come up with a functional that stops iterating once it found a solution. I could come up with this. However it is too verbose and relies on side-effects (which doesn't make it functional anymore):

const findIndexOfSumPair3 = (lst, trgt) => {
  let res;

  lst.some((x, i) => -1 !== lst.findIndex((y, j) => {
    if (i !== j && trgt - y === x) {
      res = [j, i];
      return true;
    }
  }));
  return res;
};

console.log(findIndexOfSumPair3(lst, target));

Do you know an elegant and efficient functional solution?


texts: Need Feedback on JUnit test comparing two timestamps

texts:
I am writng a JUnit test case for the below methods :
public final class LoggerService implements ILoggerService {

  private Logger logger;

  private <T> LoggerService(T type){
    logger = LoggerFactory.getLogger((Class<?>) type);
  }

  public static <T> LoggerService getLoggerService(T type){
    return new LoggerService(type);
  }

  @Override
  public Long startTimeFrame() {
    return new Date().getTime();
  }

  @Override
  public Long stopTimeFrame(Long startTimeFrame) {
    return new Date().getTime() - startTimeFrame;
  }

  }

}

The simple JUnit test is :

@Test
public void testStartTimeFrame(){
   LoggerService loggerService = LoggerService.getLoggerService(LoggerServiceTest.class);
   assertEquals(new Date().getTime(), loggerService.startTimeFrame());
}

Is this an efficient test case ? Is there any chance that this test could fail sometimes ?
Please suggest how I can improve this


texts:
I have a routine that can be potentially reduced.

internal ArrayBufferObject GetAccessorArray()
{
    ColladaDocument colladaDocument = GetColladaDocument();
    ColladaArray colladaArray = colladaDocument.GetSpecialElement<ColladaArray>(Source);
    ArrayBufferObject bufferObject;

    if (IsSimpleParamsConfiguration() == false)
        throw new NotSupportedException("complex accessor params not supported");

    string simpleParamsType = Params[0].Type;

    if (simpleParamsType == ArrayTypeFloat) {
        uint cursorOffset = Offset;

        ArrayBufferObject<float> arrayBufferObject = new ArrayBufferObject<float>(BufferObject.Hint.StaticCpuDraw);

        for (uint i = 0; i < Count; i++) {
            foreach (ColladaParam param in Params) {
                if (param.Name != null)
                    arrayBufferObject[cursorOffset - Offset] = (float) colladaArray[cursorOffset];
                cursorOffset++;
            }
            cursorOffset += Stride - (uint)Params.Count;
        }

        bufferObject = arrayBufferObject;

    } else if (simpleParamsType == ArrayTypeInt) {
        uint cursorOffset = Offset;

        ArrayBufferObject<int> arrayBufferObject = new ArrayBufferObject<int>(BufferObject.Hint.StaticCpuDraw);

        for (uint i = 0; i < Count; i++) {
            foreach (ColladaParam param in Params) {
                if (param.Name != null)
                    arrayBufferObject[cursorOffset - Offset] = (int) colladaArray[cursorOffset];
                cursorOffset++;
            }
            cursorOffset += Stride - (uint)Params.Count;
        }

        bufferObject = arrayBufferObject;
    } else
        throw new NotSupportedException(String.Format("simple accessor params type {0} not supported", simpleParamsType));

    return (bufferObject);
}

As you can see, there are two if branches that are the same. Essentially they create a generic class using float and int type.

The class ArrayBufferObject is the base of ArrayBufferObject<T>, but only the latter implements an indexer (strongly typed). It is implemented as following:

public T this[uint index]
{
    get
    {
        if ((MemoryBuffer == null) || (MemoryBuffer.AlignedBuffer == IntPtr.Zero))
            throw new InvalidOperationException("not defined");
        if (index >= ItemCount)
            throw new ArgumentException("index out of bounds", "index");

        return ((T) Marshal.PtrToStructure(new IntPtr(MemoryBuffer.AlignedBuffer.ToInt64() + (index * mItemSize)), typeof(T)));
    }
    set
    {
        if ((MemoryBuffer == null) || (MemoryBuffer.AlignedBuffer == IntPtr.Zero))
            throw new InvalidOperationException("not defined");
        if (index >= ItemCount)
            throw new ArgumentException("index out of bounds", "index");

        Marshal.StructureToPtr(value, new IntPtr(MemoryBuffer.AlignedBuffer.ToInt64() + (index * mItemSize)), false);
    }
}

The source of the assigned item comes from a ColladaArray class, that is an abstract class wrapping an array of values. To resolve the data accessor I've defined in it a generic numeric accessor like the following:

/// <summary>
/// Access this array.
/// </summary>
/// <param name="i">
/// The index of the element to be accessed.
/// </param>
/// <returns>
/// It returns an equivalent <see cref="System.Double"/> of the value accessed.
/// </returns>
public virtual double this[uint i] { get { throw new NotSupportedException("array accessor not implemented"); } }

Which is implemented in each derived class returning the real array value casted to double (all arrays contains numeric data... hopefully).

How would you suggest to remove the GetAccessorArray routine redundancies? Help! Soon it will grow up with all possible numeric types!


texts: Made a simple gui string encrypter, just to obfuscate plaintext

texts:
I realize this won't stop people who know what they're doing, just a project I decided to undertake while I'm trying to learn Python and Tkinter. Would love some input!

import Tkinter
import base64

class crypt_mod(Tkinter.Tk):
    def __init__(self, parent):
        Tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

        plain_label = Tkinter.Label(text='Plain Text:')
        plain_label.grid(column=0, row=0, sticky='E')

        self.ptxt = Tkinter.StringVar()
        self.plain_text = Tkinter.Entry(self, textvariable=self.ptxt, width=50)
        self.plain_text.grid(column=1, row=0, padx=5, pady=5)
        self.plain_text.bind("<Return>", self.encrypt)

        self.enc_button = Tkinter.Button(self, text='Encrypt', command=self.encrypt, relief='groove')
        self.enc_button.grid(column=2, row=0, padx=5, pady=5)

        self.dec_button = Tkinter.Button(self, text='Decrypt', command=self.decrypt, relief='groove')
        self.dec_button.grid(column=2, row=1, padx=5, pady=5)

        plain_label = Tkinter.Label(text='Base64:')
        plain_label.grid(column=0, row=1, sticky='E')

        self.etxt = Tkinter.StringVar()
        self.e_text = Tkinter.Entry(self, textvariable=self.etxt, width=50)
        self.e_text.grid(column=1, row=1, padx=5, pady=5)

        self.clear_button = Tkinter.Button(self, text='Clear Both', command=self.clear_both, relief='groove')
        self.clear_button.grid(column=1, row=2, padx=5, pady=5)

        self.htxt = Tkinter.StringVar()
        self.history = Tkinter.Text(width=50, height=10, wrap='word', spacing1=2, font=('courier',8), state='disabled')
        self.history.grid(column=0, row=3, columnspan=3, padx=5, pady=5)

        self.clear_history_button = Tkinter.Button(self, text='Clear History', command=self.clear_history, relief='groove')
        self.clear_history_button.grid(column=1, row=4, padx=5, pady=5)

    def encrypt(self):
        self.etxt.set(base64.b64encode(str(self.ptxt.get())))
        self.history.config(state='normal')
        self.history.insert(Tkinter.END, 'encrypt:\n' + base64.b64encode(str(self.ptxt.get())) + '\n')
        self.history.config(state='disabled')
        self.history.see(Tkinter.END)
        #print "encrypt click!"

    def decrypt(self):
        self.ptxt.set(base64.b64decode(str(self.etxt.get())))
        self.history.config(state='normal')
        self.history.insert(Tkinter.END, 'decrypt:\n' + base64.b64decode(str(self.etxt.get())) + '\n')
        self.history.config(state='disabled')
        self.history.see(Tkinter.END)
        #print "decrypt click!"

    def clear_both(self):
        self.etxt.set('')
        self.ptxt.set('')

    def clear_history(self):
        self.history.config(state='normal')
        self.history.delete(0.0, Tkinter.END)
        self.history.config(state='disabled')
        pass

if __name__ == "__main__":
    app = crypt_mod(None)
    app.title('Base64 Crypto')
    app.mainloop()


texts:
Is this good or can it be improved? The program should backtrack the two variables until this logic operation is true: a & b.

#include <stdio.h>
#include <stdbool.h>

bool perm(bool, bool);

int main(){

    bool x = false;
    bool y = false;

/*  RECURSIVE SOLUTION  */

    if(perm(x,y) == true){
        puts("DONE\n");
    }

    puts("\n\n");

/* ITERATIVE SOLUTION*/

    for(int cnt = 0; cnt < 2; cnt++){
        x = cnt;
        for(int cnt_2 = 0; cnt_2 < 2; cnt_2++){
            y = cnt_2;
            if( (x & y) == true){
                printf("%d ^ %d =  TRUE\n", x,y);
                puts("DONE");
                return 0;
            }
            printf("%d ^ %d =  FALSE\n", x,y);
        }
    }

    puts("NOTHING");

    return 0;
}

bool perm(bool x, bool y){

    const bool c_x = x;
    const bool c_y = y;

    printf("%d ^ %d  = %d\n", c_x, c_y, c_x&c_y);

    if(x == true){ return x;}
    if(y == true){ return y;}

    perm(y+1,x);

    return ( (x & y) == true) ? true : perm(x+1,y);
}


texts:
My goal is to simulate a Pile shuffle of a vector. It takes 2 optional arguments for the number of piles to use and how many times to perform the shuffle.

As this is my first attempt at clojure code, I'm fairly sure I'm doing something terribly wrong here. I'm concerned with speed, efficiency, and indentation style. I'd also appreciate any pointers that would make this function more generic (maybe not restricting to vectors, but general collections).

(defn pile
  ([cards] (pile cards 3 1))
  ([cards num_piles] (pile cards num_piles 1))
  ([cards num_piles times]
    (loop [i 1
           piles (transient (vec (map (fn [p] []) (range num_piles))))
           the_pile 0]
      (if (<= i (count cards))
        (recur (inc i)
               (assoc!
                 piles
                 the_pile
                 (vec (concat [(nth cards (dec i))]
                               (nth piles the_pile))))
               (rem i num_piles))
        (if (> times 1)
          (pile (reduce into (persistent! piles)) num_piles (dec times) )
          (vec (reduce into (persistent! piles))))))))


texts: How does one handle activity stuff in custom classes in Android?

texts:
This is a question, I'm just not quite sure about:
Every Android development tutorial you find, will put all of the code simply into the MainActivity class (or some other class, that inherits from an Activity class).
But what if you want to put code into your own classes? How do you best access certain Features?
Example for illustration:
I have created a NetworkManager class, that should handle all my connections for the app. Now I need for example the WifiManager in this class. In my MainActivity I would simply get it by using:
getSystemService(Context.WIFI_SERVICE)

To access it in my custom class - as far as I know, at least - I would need either a reference to my MainActivity or to the feature (in this cases the WifiManager) I need, by passing it into the instantiation.
Which is the better way? Are both wrong/right? Passing the main reference around to each class instance of any custom class seems a bit weird to me...


texts:
I was working on teaching myself some Scala and decided to tackle some Project Euler problems.  The first four of these turned out to be one liners.

/* Find the sum of all the multiples of 3 or 5 below 1000 */
object Problem1 extends App {
    println((1 to 999).filter((i: Int) => i % 3 == 0 || i % 5 == 0).sum)
}

/* By considering the terms in the Fibonacci sequence whose values do not
   exceed four million, find the sum of the even-valued terms. */
object Problem2 extends App {
  def fib: Stream[Long] = {
    def tail(h: Long, n: Long): Stream[Long] = h #:: tail(n, h+n)
    tail(0,1)
  }

  println(fib.takeWhile(_ < 4000000).filter(_ % 2 == 0).sum)
}

/* What is the largest prime factor of the number 600851475143? */
object Problem3 extends App {
  val v = BigInt("600851475143")
  val z = BigInt(0)

  println(PrimeSeq.ps.takeWhile{p => v.>(BigInt(p).pow(2))}.filter(v.%(_) == z).max)
}

/* Find the largest palindrome made from the product of two 3-digit numbers. */
object Problem4 extends App {
  def isPalindrome (a:Int) : Boolean = {
    a.toString.equals(a.toString.reverse)
  }

  println((100 to 999).map { rangeIdx => (rangeIdx to 999).map{ i => i * rangeIdx}.map{ x => if(isPalindrome(x)) x else 0}.max }.max)
}

PrimeSeq is in a separate object because I expect that I'll be using it again in the future and is included here for completeness. The code itself is from this StackOverflow question and isn't code I wrote.

object PrimeSeq {
  lazy val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i =>
    ps.takeWhile{j => j * j <= i}.forall{ k => i % k > 0})
}

I am most interested in the idiomatic corrections of the Scala code, though other parts will be of interesting too.


texts: Queue Implementation using a Linked List

texts:
For understanding the concepts, I've implemented the Queue data structures using a linked list. Is there anything to improve?

LinkList.java

public class LinkList {

    private static class Node<T> {

        private final T data;
        private Node next;

        public Node(T data){
            this.data=data;
        }

        public void displayNode(){
            System.out.print(data+ " ");
        }

    }

    private Node first = null;
    private Node last = null;

    public boolean isEmpty() {
        return (first == null);
    }

    public <T> void addLast(T data) {
        Node n = new Node(data);
        if (isEmpty()) {
            n.next = first;
            first = n;
            last = n;
        } else {
            last.next = n;
            last = n;
            last.next = null;
        }

    }

    public void removeFirst() {

            Node temp = first;
            if (first.next == null)
                last = null;
            first = first.next;

        }

    public void displayList() {
        Node current = first;
        while (current != null) {
            current.displayNode();
            current = current.next;
        }
    }

}

LinkListQueue.java

public class LinkListQueue {

    LinkList newLinkList = new LinkList();

    public <T> void enqueue(T data) {
        newLinkList.addLast(data);
    }

    public void dequeue() {
        if(!newLinkList.isEmpty())
            newLinkList.removeFirst();

    }

    public void displayQueue() {
        newLinkList.displayList();
        System.out.println();
    }

    public boolean isEmpty(){
        return newLinkList.isEmpty();
    }

}

LinkListQueueDemo.java

public class LinkListqueueDemo {

    public static void main(String[] args) {

        LinkListQueue queueImpl = new LinkListQueue();

        queueImpl.enqueue("A");
        queueImpl.enqueue("B");
        queueImpl.enqueue("C");
        queueImpl.enqueue("D");
        queueImpl.displayQueue();
        queueImpl.dequeue();
        queueImpl.displayQueue();

    }

}


texts: Optimal Caching - "Farthest in Future" Algorithm

texts:
I'm looking for someone to really tear apart the following code I wrote for my graduate-level algorithms class. The problem was Optimal Caching, and the algorithm I'm implementing is called "Farthest in Future", which looks to see which cache item is either NOT in the request, or one who's first occurrence appears LAST compared to the other items.
I'm looking for ways to get the run-time down. Right now I think it's O(n+k), with n being the length of requests and k being the length of the cache, after the initial data structure (the indices dict) is created. Please let me know if I'm wrong! I'm still learning!
Also looking how I can better organize my code like this in the future.
cache = ['a', 'b', 'c', 'd']
requests = ['e', 'f', 'c', 'g']

def get_items(cache, queue):

  # Handles cache "hits"
  def cache_hit(item):
    print('HIT', cache)
    return item

  def cache_miss(item):
    # evict "farthest in future" item
    fif = get_farthest_in_future(cache, queue)
    cache.remove(fif)
    cache.append(item)
    print('MISS', cache)

  # Predicts which item occurs "farthest in the future"
  def get_farthest_in_future(cache, requests):
    max_index = 0
    for cache_item in cache:
      # next appearance
      if len(indices[cache_item]) > 0:
        next_appearance = indices[cache_item][0]
        if next_appearance > max_index:
          max_index = next_appearance
          fif = requests[max_index]
          break
      else:
        fif = cache_item
        break
    return fif

  #### CREATE DATA STRUCTURES #####
  def get_indices(cache, queue):
    indices = {}

    # ensure that every cache item
    # has an entry in the dict
    for cache_item in cache:
      indices[cache_item] = []

    for i, item in enumerate(queue):
      if item not in indices:
        indices[item] = [i]
      else:
        indices[item].append(i)

    return indices

  indices = get_indices(cache, queue)

  for item in queue:

    print('request:', item)

    # update indices
    indices[item].pop(0)

    if item in cache:
      cache_hit(item)
    else:
      cache_miss(item)

get_items(cache, requests)


texts:
The main problem that I tried to tackle here was trying not to have the erase method to be \$O(n)\$. I kept two data structures: a linked-list of pairs and a map of a key and a pair containing a value and a pointer that points to the node in the linked-list.

Am I on the right track? Right now the code is all rough, ugly and all over the place but I tested it and it works properly.

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

using std::cout;
using std::endl;

template <typename key, typename value>
class table {
    using node = std::pair<key, value>;
    using iterator = typename std::list<std::pair<key, value>>::iterator;
    using value_node = std::pair<value, iterator>;

    std::list<node> list;
    std::map<key, value_node> data;

public:
    table & push(key const & k, value const & v) {
        list.emplace_back(k, v);
        data.emplace(k, value_node {v, std::prev(std::end(list))});
        return *this;
    }

    iterator begin() {
        return std::begin(list);
    }

    iterator end() {
        return std::end(list);
    }

    table & erase(key const & k) {
        list.erase(data[k].second);
        data.erase(k);
        return *this;
    }

    // Just to check if the list items are actually being erased.
    size_t length() const {
        return list.size();
    }

    value & operator [](key const & k) {
        return data[k].first;
    }
};

int main() {

    table<std::string, std::string> t;

    t.push("hello", "world");
    t.push("blabla", "hello");

    cout << t["hello"] << endl;
    cout << t["blabla"] << endl;
    cout << t.length() << endl;

    for (auto const & e : t) {
        cout << e.first << " " << e.second << endl;
    }

    t.erase("hello");
    t.erase("blabla");
    cout << t.length() << endl;

    cout << "Size: " << sizeof(table<int, int>) << endl;

    return 0;
}


texts: Split a given number so that their sum adds to another given number

texts:
Task

  You are given a string S containing only decimal digits ('0' through
  '9') and a number N. Your task is to insert an arbitrary number
  (including zero) of plus signs '+' into S in order to form a valid
  expression whose value is equal to N.

  Input

  The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
  The first and only line of each test case contains a string S, followed by a space and an integer N.

  Output

  For each test case, print a single line containing one string — your
  solution, i.e. the expression obtained after inserting some plus signs
  into S. If there are multiple solutions, you may output any one. It is
  guaranteed that at least one solution exists.

My code is not very optimized but gives the correct answer. Help me find an optimized version.

import itertools
case=input("")

for i in range(case):

    text,text2=str(raw_input("")).split()

    text=list(text)
    text1=""
    l=[]
    def break_down(text):
        words = text.split()
        ns = range(1, len(words)) # n = 1..(n-1)
        for n in ns: # split into 2, 3, 4, ..., n parts.
            for idxs in itertools.combinations(ns, n):
                    yield [' '.join(words[i:j]) for i, j in zip((0,) + idxs, idxs + (None,))]

    for i in text:
        #to add whitespace in between so that split() functions separates it correctly
        text1=text1+i
        text1=text1+" "

    for x in break_down(text1):
        #this part calls the generator and sums every iteration
        sum=0
        answer=""

        for i in range(len(x)):
            #removing the whitespaces that were added before
            x[i]=x[i].replace(" ","")
        #converts string to int so that it actually adds number not concatenates them
        x=[int(i) for i in x]

        for i in x:
            #calculating sum
            sum+=i
        if sum==int(text2):

            l=x

        #if the sum is equal to given number then it prints it out in the asked manner
        for i in l:
            i=str(i)
            answer+=i
            answer+="+"
    if int(text1.replace(" ",""))==int(text2):
        print int(text1.replace(" ",""))
    else:
        print answer[:len(answer)-1]

Example Input

4
15112 28
120012 33
123 123
15489001 10549

Example Output

15+11+2
1+20+012
123
1548+9001


texts: Setter use for dependency injection, passing interface through too many layers

texts:
I have an Offers class which is basically a seller which has specific skills, such as law knowledge.
It needs a method isLawyer. Offers has a parent_cat_id column, which references the id of a Category.

Here's Offers :

<?php

namespace App\Models;

use App\Services\CategoryService\AbstractCategory;
use LogicException;

class Offers
{
    /** @var AbstractCategory $category */
    private $categoryService;

    public function isLawyer(): bool
    {
        return $this->getCategoryService()->isLawyer($this->getParentCatId());
    }

    public function setParentCatId(int $catId)
    {
        $this->parent_cat_id = $catId;
    }

    public function getParentCatId(): int
    {
        return (int)$this->parent_cat_id;
    }

    public function setCategoryService(AbstractCategory $categoryService)
    {
        $this->categoryService = $categoryService;
    }

    public function getCategoryService(): AbstractCategory
    {
        if (is_null($this->categoryService)) {
            throw new LogicException('Category service should be set beforehand.');
        }

        return $this->categoryService;
    }
}

AbstractCategory is an abstract class that different categories will extend. I don't care about the implementation of this as of now.

Now in tests, it's all good and fun :

/** @test */
public function is_lawyer_defers_to_category_is_lawyer_method()
{
    $category = Mockery::mock(AbstractCategory::class);
    $category->shouldReceive('isLawyer')->once()->with(1)->andReturn(true);

    $offer = new Offers;
    $offer->setParentCatId(1);
    $offer->setCategoryService($category);

    $this->assertTrue($offer->isLawyer());
}

But as for the real implementation, it gets tricky, as I have 3-4 layers before I'm using $offers->isLawyer().

<?php

namespace App\Models\Product\Chat;

use App\Models\Offers;

class Chat
{
    /** @var Offers $offer */
    private $offer;

    /**
     * @param Offers $offers
     */
    public function setOffer(Offers $offers)
    {
        $this->offer = $offers;
    }

    /**
     * @return Offers
     */
    public function getOffer()
    {
        return $this->offer;
    }

    /**
     * @return bool
     */
    public function byLawyer(): bool
    {
        return $this->getOffer()->isLawyer();
    }
}

Chat uses isLawyer of Offers, but byLawyer is itself called by something else.

I still need to set the AbstractCategory before I use this method.

So, should I pass it through as a parameter to every step ? This sounds ridiculous.

Should I "setup" Offers and set the AbstractCategory even before it's assigned to the Chat ?

Should I give up and instantiate a new Category right in the Offers class ? Setting the abstraction felt like a better design.

Thanks.


texts: How to better process csv file with pandas and further dealing with set

texts:
I have below working code with pandas and python, i'm looking if there is an improvement or simplification which can be done.

Can we Just wrap this up into a definition.

$ cat getcbk_srvlist_1.py
#!/python/v3.6.1/bin/python3
from __future__ import print_function
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
import pandas as pd
import os
##### Python pandas, widen output display to see more columns. ####
pd.set_option('display.height', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('expand_frame_repr', True)
##################### END OF THE Display Settings ###################

################# PANDAS Extraction ###########
df_csv = pd.read_csv(input("Please input the CSV File Name: "), usecols=['Platform ID', 'Target system address']).dropna()
hostData = df_csv[df_csv['Platform ID'].str.startswith("CDS-Unix")]['Target system address']
hostData.to_csv('host_file1', header=None, index=None, sep=' ', mode='a')

with open('host_file1') as f1, open('host_file2') as f2:
    dataset1 = set(f1)
    dataset2 = set(f2)

for i, item in enumerate(sorted(dataset2 - dataset1)):
    print(str(item).strip())

os.unlink("host_file1")

The above code just compares the two files one is processed through pandas ie host_file1 and another is already existing host_file2.


texts: Can this PHP code to settle up payments be improved?

texts:
I've made a function that takes an array of amounts owed by each user_id and works out the best way to square everyone up. The input array would look something like this, but may consist of 1 or more "users" who all owe (or are owed) money between each other:

//the owings should sum to 0.
$owings = array(
    1 => -1.72, //user 1 owes -1.72
    2 => -5.78,
    3 => 7.5,
    );

And here is my function:

/**
* Calculate the most efficient way to settle up a group of payments
*
* @param array $owings
*/
function settleUp($owings){
    $reimbursments = array();
    $payment = 0.11; $i = 1;
    while ( $payment > 0.1 || $payment < -0.1 ){
        $min = 0;
        $max = 0;
        foreach ($owings as $id => $owing){
            if ($owing < $min) {
                $min = $owing;
                $min_id = $id;
            }
            if ($owing > $max) {
                $max = $owing;
                $max_id = $id;
            }
        }
        $payment = -$min > $max ? -$max : $min;

        if ($payment !== 0) {
            $reimbursments[] = array(
                'from'      => $max_id,
                'to'        => $min_id,
                'payment'   => -$payment,
                );

            $owings[$max_id] += $payment;
            $owings[$min_id] -= $payment;
        }
        $i++;
    }
        return $reimbursments;
}

The result looks like this:

//print_r(settleUp($owings));
Array
(
    [0] => Array
        (
            [from] => 3
            [to] => 2
            [payment] => 5.78
        )
    [1] => Array
        (
            [from] => 3
            [to] => 1
            [payment] => 1.72
        )
)

Currently I use a while loop that iterates until the net balance owed is close to 0. Is there a better way of doing this? Perhaps using a recursive function?


texts: MessageFormat.format() with named parameters

texts:
I was looking for how to use MessageFormat.format() in Java with named parameters, as a similar option exists in Python, and found this question. Some functions are presented there, although they use internal cycles and StringBuilder, and apparently they can fall into infinite loops (comments there suggest that, and it makes sense).

Option 1 (potential infinite loop):

public static String format(String str, Map<String, Object> values) {

    StringBuilder builder = new StringBuilder(str);

    for (Entry<String, Object> entry : values.entrySet()) {

        int start;
        String pattern = "%(" + entry.getKey() + ")";
        String value = entry.getValue().toString();

        // Replace every occurence of %(key) with value
        while ((start = builder.indexOf(pattern)) != -1) {
            builder.replace(start, start + pattern.length(), value);
        }
    }

    return builder.toString();
}

Option 2 (infinite loop removed):

public static String dictFormat(String format, Hashtable<String, Object> values) {
    StringBuilder convFormat = new StringBuilder(format);
    Enumeration<String> keys = values.keys();
    ArrayList valueList = new ArrayList();
    int currentPos = 1;
    while (keys.hasMoreElements()) {
        String key = keys.nextElement(),
        formatKey = "%(" + key + ")",
        formatPos = "%" + Integer.toString(currentPos) + "$";
        int index = -1;
        while ((index = convFormat.indexOf(formatKey, index)) != -1) {
            convFormat.replace(index, index + formatKey.length(), formatPos);
            index += formatPos.length();
        }
        valueList.add(values.get(key));
        ++currentPos;
    }
    return String.format(convFormat.toString(), valueList.toArray());
}

And the question is, why not something simpler? Why is there an internal cycle?
Here my option (which probably has some issue I'm not aware of).

public static String format(String str, Map<String, String> values) {

    String finalString = str;

    // validation input string
    if (str == null || str.isEmpty()) {
        return finalString;

    // validate parameters
    } else if (values == null || values.isEmpty()) {
        return str;
    }

    for (Map.Entry<String, String> entry : values.entrySet()) {

        String pattern = "%(" + entry.getKey() + ")";
        String value = entry.getValue();

        // Replace every occurrence of %(key) with value
        finalString = finalString.replace(pattern, value);
    }

    return finalString;
}


texts:
I am writing a backend with Node JS. It is my first Node JS application so I haven't learnt all the principles Node involves. I am writing the code for a media upload mechanism (to handle profile pictures, articles' featured pics, and any other media content that comes from the users to my app).

The current version of my code does not seem easily testable and I don't know if there's a problem with the code itself, or the operation it handles is actually hard(er) to test.

I will leave jsdoc comments in so you can easily understand it and possibly guide me into writing it in a better way.

/**
 * Upload specified files from the exposed ones.
 *
 * @param {IncomingMessage} request Request came from the client.
 * @param {object[]} exposedFiles The files exposed by multiparty.parse
 * @param {string|string[]} files Array of file identifiers to process.
 * If this is not specified, all the request files will be
 * uploaded and indexed.
 * @param {function(err: ?Error, tokens: ?object)} callback
 * @throws {Error} If the callback is not a function.
 */
function upload(request, exposedFiles, files, callback) {
    if (typeof callback !== 'function') {
        throw new Error('Callback must be a function');
    }
    if (typeof files === 'string') {
        files = [ files ];
    }

    let fileTokens = {};
    async.each(files, (id, cb) => {
        if (!exposedFiles[id]) {
            cb(new Error(`File identified by ${id} was not found`));
        }

        const fileInfo = exposedFiles[id];
        const databaseToken = crypto.randomBytes(16).toString('hex');

        async.waterfall([
            (next) => Database.query('INSERT INTO media(id, mimetype) VALUES($1, $2)', [
                databaseToken,
                fileInfo.headers['content-type'],
            ], next),
            (next) => fs.rename(fileInfo.path, path.join(__dirname, Configuration.userData.mediaDir, databaseToken), next),
            (next) => {
                fileTokens[id] = databaseToken;

                next();
            },
        ], cb);
    }, err => {
        if (err) {
            callback(err);
            return;
        }

        callback(undefined, fileTokens);
    });
}


texts:
How can I write this shorter?

$('#pietra_svg #p1_4 polygon#p1').click(function() {
  $('#apla_p1').fadeIn("slow");
  return false;
});
$('#pietra_svg #p1_4 polygon#p2').click(function() {
  $('#apla_p2').fadeIn("slow");
  return false;
});
$('#pietra_svg #p1_4 polygon#p3').click(function() {
  $('#apla_p3').fadeIn("slow");
  return false;
});
$('#pietra_svg #p1_4 polygon#p4').click(function() {
  $('#apla_p4').fadeIn("slow");
  return false;
});
$('#pietra_svg #p5 polygon#a').click(function() {
  $('#apla_p5').fadeIn("slow");
  return false;
});
$('#pietra_svg #p5 polygon#b').click(function() {
  $('#apla_p5').fadeIn("slow");
  return false;
});
$('.close').click(function() {
  $('.apla').fadeOut("slow");
  return false;
});


texts: ActionGroupContext to know an id of the current context

texts:
My services(or services that depend on services) need to know about a current action group id. To add an extra optional parameter to each service for the id was an idea but in my current environment to difficult and ugly because every service would have to take in the parameter only to pass it to other services.

My solution was a class ActionGroupContext which stores the current context in a static ThreadStore or HttpStore.

What I don't like especially with my solution is that even though you are not do web application you have to include a reference to System.Web, but the convenience is great, the user does not need any setup code.

Do you have any improvement ideas?

Demo usage:

public void SomeApplicationMehtod()
{
    using (new ActionGroupContext())
    {
        someService.SomeMehtod();
    }
}

public class SomeService
{
    public void SomeMehtod()
    {
        var id = ActionGroupContext.Id;

        //Do something with the Id.

    }
}

The code:

public class ActionGroupContext : IDisposable
{
    private static readonly GuidStore GuidStore = new GuidStore("Action-Group-Id-Store");

    private readonly Guid? oldId;
    public ActionGroupContext()
    {
        oldId = GuidStore.GetGuid();
        GuidStore.SetGuid(Id ?? Guid.NewGuid());
    }

    public static Guid? Id
    {
        get { return GuidStore.GetGuid(); }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            GuidStore.SetGuid(oldId);
        }
    }
}

public class ThreadStore : IStore
{
    private readonly LocalDataStoreSlot slot;
    public ThreadStore(string storeKey)
    {
        slot = Thread.GetNamedDataSlot(storeKey);
    }

    public object GetData()
    {
        return Thread.GetData(slot);
    }

    public void SetData(object data)
    {
        Thread.SetData(slot, data);
    }
}

public interface IStore
{
    object GetData();
    void SetData(object data);
}

public class ThreadStore : IStore
{
    private readonly LocalDataStoreSlot slot;
    public ThreadStore(string storeKey)
    {
        slot = Thread.GetNamedDataSlot(storeKey);
    }

    public object GetData()
    {
        return Thread.GetData(slot);
    }

    public void SetData(object data)
    {
        Thread.SetData(slot, data);
    }
}

public class HttpStore : IStore
{
    private readonly string storeKey;

    public HttpStore(string storeKey)
    {
        if (!IsContextForStoreAvailable())
        {
            throw new InvalidOperationException("HttpContext is not available");
        }
        this.storeKey = storeKey;
    }

    public object GetData()
    {
        return HttpContext.Current.Items(storeKey);
    }

    public void SetData(object data)
    {
        HttpContext.Current.Items(storeKey) = data;
    }

    public static bool IsContextForStoreAvailable()
    {
        return HttpContext.Current != null;
    }
}


texts: Simple target shooter game using Windows Forms

texts:
Currently, my game is a basic target shooting game.

The targets rise to the top, if the target reaches the top an end screen is shown.
If you shoot a target you get more score, and the speed in which the targets move increases.
If you shoot the fake target, the end screen is shown

If anyone could help me and clean up my code I'd appreciate it greatly.
namespace ProjectProtoypeUI
{
    public partial class gameForm : Form
    {

        bool gameOver;
        int targetSpeed;
        int score;
        Random randomValue = new Random();

        public gameForm()
        {
            InitializeComponent();
            GameRestart();
        }

        private void textScore_Click(object sender, EventArgs e)
        {

        }

        private void MainTimeEvent(object sender, EventArgs e)
        {
            textScore.Text = "Score: " + score;

            if (gameOver == true)
            {
                targetTimer.Stop();
                textScore.Text = "Score :" + score + "Game over, press enter to reset game";
            }

            foreach(Control test in this.Controls)
            {
                if (test is PictureBox)
                {
                    test.Top -= targetSpeed;
                    //test.Left -= targetSpeed;

                    if (test.Top < -100)
                    {
                        test.Top = randomValue.Next(700, 1000);
                        test.Left = randomValue.Next(5, 500);
                    }

                    if ((string)test.Tag == "target")
                    {
                        if (test.Top < -50)
                        {
                            gameOver = true;
                        }
                    }

                    if (gnomeImage.Bounds.IntersectsWith(pictureBox2.Bounds) || gnomeImage.Bounds.IntersectsWith(pictureBox1.Bounds))
                    {
                        test.Top = randomValue.Next(650, 800);
                        test.Left = randomValue.Next(50, 450);
                    }

                    if (pictureBox1.Bounds.IntersectsWith(pictureBox2.Bounds))
                    {
                        test.Top = randomValue.Next(700, 1000);
                        test.Left = randomValue.Next(5, 500);
                    }

                }
            }
        }

        private void shootTarget(object sender, EventArgs e)
        {
            if (gameOver == false)
            {
                var target = (PictureBox)sender;

                target.Top = randomValue.Next(750, 1000);
                target.Left = randomValue.Next(5, 500);

                if (target.Top > 800 && target.Left > 514)
                {
                    target.Top = randomValue.Next(100, 1000);
                    target.Left = randomValue.Next(5, 1000);
                }

                score += 1;
                targetSpeed += 1;

            }

        }

        private void gameLost(object sender, EventArgs e)
        {
            if (gameOver == false)
            {
                gameOver = true;
            }

        }

        private void GameOver(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && gameOver == true)
            {
                GameRestart();
            }
        }

        private void GameRestart()
        {
            targetSpeed = 10;
            score = 0;
            gameOver = false;

            foreach (Control pictures in this.Controls)
            {
                if (pictures is PictureBox)
                {
                    pictures.Top = randomValue.Next(750, 1000);
                    pictures.Left = randomValue.Next(5, 500);
                }
            }

            targetTimer.Start();

        }

    }
}

```


texts:
This is a simple brute force algorithm that I have programmed in C.  All the program does is print out every possible combination of the given alphabet for the given length.

I would prefer suggestions on how to improve the algorithm, or decrease run-time.  Any other suggestions are acceptable though.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static const char alphabet[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";

static const int alphabetSize = sizeof(alphabet) - 1;

void bruteImpl(char* str, int index, int maxDepth)
{
    for (int i = 0; i < alphabetSize; ++i)
    {
        str[index] = alphabet[i];

        if (index == maxDepth - 1) printf("%s\n", str);
        else bruteImpl(str, index + 1, maxDepth);
    }
}

void bruteSequential(int maxLen)
{
    char* buf = malloc(maxLen + 1);

    for (int i = 1; i <= maxLen; ++i)
    {
        memset(buf, 0, maxLen + 1);
        bruteImpl(buf, 0, i);
    }

    free(buf);
}

int main(void)
{
    bruteSequential(3);
    return 0;
}


texts:
I've posted here before and got pretty helpful reviews. How does my code look now? To keep it really helpful, I just copied this from the middle of one of my projects.

 <?php

  function findSimilarityBetweenImages($imagePathA, $imagePathB, $accuracy){

    //if images are png
    $imageA = imagecreatefrompng($imagePathA);
    $imageB = imagecreatefrompng($imagePathB);

    //if images are jpeg
    //$imageA = imagecreatefromjpeg($imagePathA);
    //$imageB = imagecreatefromjpeg($imagePathB);

    //get image resolution
    $imageX = imagesx($imageA);
    $imageY = imagesy($imageA);

    $pointsX = $accuracy*5;
    $pointsY = $accuracy*5;

    $sizeX = round($imageX/$pointsX);
    $sizeY = round($imageY/$pointsY);

    //Compare the color of each point while looping through.
    $y = 0;
    $match = 0;
    $num = 0;
    for ($i=0; $i < $pointsY; $i++) {
      $x = 0;
      for($n=0; $n < $pointsX; $n++){

        $rgba = imagecolorat($imageA, $x, $y);
        $colorsa = imagecolorsforindex($imageA, $rgba);

        $rgbb = imagecolorat($imageB, $x, $y);
        $colorsb = imagecolorsforindex($imageB, $rgbb);

        if(colorComp($colorsa['red'], $colorsb['red']) && colorComp($colorsa['green'], $colorsb['green']) && colorComp($colorsa['blue'], $colorsb['blue'])){

          $match ++; //Match between points.
        }
        $x += $sizeX;
        $num++;
      }
      $y += $sizeY;
    }
    //A similarity or percentage of match between the two images.
    $similarity = $match*(100/$num);
    return $similarity;
  }

  function colorComp($color, $c){
    //To see if the points match
    if($color >= $c-2 && $color <= $c+2)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

?>


texts: Shortest and longest city name and alphabetical order

texts:
Problem

  Query the two cities in STATION with the shortest and longest CITY
  names, as well as their respective lengths (i.e.: number of characters
  in the name). If there is more than one smallest or largest city,
  choose the one that comes first when ordered alphabetically.

  Sample Input

  Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY

  Sample Output

  ABC 3 PQRS 4

Can I get shorter code in MySQL and also an optimal Oracle query? There's no way to have only one sub-query for both min and max, is there?

select city, char_length(city) from STATION
 where city = (select min(city) from STATION
     where char_length(city) = (select min(char_length(city)) from STATION))

 or city = (select min(city) from STATION
     where char_length(city) = (select max(char_length(city)) from STATION));