texts: Basic Color class for both Delphi and Lazarus

texts:
Intro
If you want to know, then about 10+ years ago, I started a journey on the (best in my country) color picker for WinXP, later Win7. Since now it is hardly compatible with Win10 and HiDPI (work in progress), and in no way compilable in Linux using Lazarus, it would take quite an effort to create a decent desktop color picker with zoom and everything on Linux. But first things first - in this question I would like to start with basic color class, i.e. class capable of holding single color, and providing easy access to each color component, except for hue sat lum, which I'm not able to program, and am not asking you to point me to any direction. At the bottom I attached this code to existing color picker for windows just to show what it is doing. I want to start from scratch and maybe re-invent the wheel just to practice my brain.

TBasicColor class
unit basic_color;

interface

uses
    Graphics;

type
    TBasicColor = class
    strict private
        FColorRef: TColor;
    protected
        function GetColorRef: Integer;
        function GetRed: Byte;
        function GetGreen: Byte;
        function GetBlue: Byte;
        function GetCyan: Byte;
        function GetMagenta: Byte;
        function GetYellow: Byte;
    public
        constructor Create; reintroduce;
        constructor CreateRandom;
        constructor CreateColorUsingRGB(const ARed, AGreen, ABlue: Byte);
        constructor CreateColorUsingCMY(const ACyan, AMagenta, AYellow: Byte);
        property ColorRef: Integer read GetColorRef;
        property Red: Byte read GetRed;
        property Green: Byte read GetGreen;
        property Blue: Byte read GetBlue;
        property Cyan: Byte read GetCyan;
        property Magenta: Byte read GetMagenta;
        property Yellow: Byte read GetYellow;
    end;

implementation

constructor TBasicColor.Create;
begin
    inherited Create;
    // implicitly initialize to white color
    CreateColorUsingRGB(255, 255, 255);
end;

constructor TBasicColor.CreateRandom;
begin
    inherited Create;
    FColorRef := Random($FFFFFF + 1);
end;

constructor TBasicColor.CreateColorUsingRGB(const ARed, AGreen, ABlue: Byte);
begin
    inherited Create;
    FColorRef := ARed or (AGreen shl 8) or (ABlue shl 16);
end;

constructor TBasicColor.CreateColorUsingCMY(const ACyan, AMagenta, AYellow: Byte);
begin
    CreateColorUsingRGB(255 - ACyan, 255 - AMagenta, 255 - AYellow);
end;

function TBasicColor.GetColorRef: Integer;
begin
    Result := Integer(FColorRef);
end;

function TBasicColor.GetRed: Byte;
begin
    Result := Byte(FColorRef);
end;

function TBasicColor.GetGreen: Byte;
begin
    Result := Byte(FColorRef shr 8);
end;

function TBasicColor.GetBlue: Byte;
begin
    Result := Byte(FColorRef shr 16);
end;

function TBasicColor.GetCyan: Byte;
begin
    Result := 255 - GetRed;
end;

function TBasicColor.GetMagenta: Byte;
begin
    Result := 255 - GetGreen;
end;

function TBasicColor.GetYellow: Byte;
begin
    Result := 255 - GetBlue;
end;

end.

Screenshot from Windows

Whatever you answer, I value all input. Thank you.


texts: Optimizing Python code for Project Euler #5 (LCM of all numbers from 1 to 20)

texts:
This is my solution for the 5th problem of Project Euler, which asks for the least common multiples of the numbers from 1 to 20 (inclusive). Is there any way to improve the while loop conditional instead of using the sum?

table = range(1, 21)
result = 1
pf = 2
while sum(table) > len(table):
   flag = False
   for x, y in enumerate(table):
      if y % pf == 0:
         table[x] = y/pf
         flag = True
   if flag:
      result *= pf
   else:
      pf += 1
print result


texts: Does this intersection algorithm work like it's supposed to?

texts:
and can I make it more efficient? It's to test the collision between a ray and a sphere.

float BoundingSphere::Intersects(Ray ray)
{
D3DXVECTOR3 direction = ray.Direction();
D3DXVECTOR3 vec = D3DXVECTOR3();
D3DXVECTOR3 cToO = ray.Origin() - centre;
float rSquared = radius * radius;
float vSquared = 0;

if(D3DXVec3Dot(&cToO, &cToO) <= rSquared)
{
    return 0;
}
else if(D3DXVec3Dot(&cToO, &direction) <= 0)
{
    vec = cToO - direction * D3DXVec3Dot(&cToO, &direction);
    vSquared = D3DXVec3Dot(&vec, &vec);

    if(vSquared <= rSquared)
    {
        D3DXVECTOR3 normDir = *D3DXVec3Normalize(&direction, &direction);
        float mul = sqrt(rSquared - vSquared);

        return D3DXVec3Length(
            &(ray.Origin() -
            (centre + vec - D3DXVECTOR3(normDir.x *= mul, normDir.y *= mul, normDir.z *= mul))));
    }
    else
    {
        return -1;
    }
}
else
{
    return -1;
}
}

it should return -1 if there is no collision, 0 if the origin of the ray is inside the sphere. Otherwise it should return a float of the distance from the ray's origin to the first point of collision.


texts: Scrape HTML into separate files for each chapter

texts:
I have written a program to read HTML file, find particular text, write text from that particular text to next particular text in a newly opened file. I am interested in code review. I am very new PHP.

<?php

$FILE = "testing.html";
$count = 0;
$directoryName = explode('.',$FILE)[0];
$TAG = "/x-berschrift-1--nur-f-r-Header-/";

function readingFile($FILE)
{
    //Creates a directory on the file name to store segmeted chapters from $FILE
    global $directoryName;
    mkdir($directoryName);
    $file_handle = fopen($FILE, "r");
    chdir($directoryName);
    $matchTag = False;
    while (!feof($file_handle))
     {
           $line = fgets($file_handle);
           if(checkingMatchTag($line))
           {
                if($matchTag){
                    closeWriteFile($writeHandle);
                    incrementCounter();
                }
                else
                {
                    $matchTag = True;
                }
                $writeHandle = openWriteFile();
                segmentContent($writeHandle, $line);
           }
           elseif($matchTag)
           {
               segmentContent($writeHandle, $line);
           }
     }
}

function checkingMatchTag($line)
{
    global $TAG;
    if(preg_match($TAG, $line))
    {
        return True;
    }
    return False;
}

function openWriteFile()
{
    global $directoryName, $count, $FILE;
    $writingFile = fopen($directoryName.$count.'.'.explode('.',$FILE)[1], 'w');
    return $writingFile;
}

function segmentContent($writeFileHandle, $line)
{
   fwrite($writeFileHandle, $line);
}

function closeWriteFile($file)
{
    fclose($file);
}

function incrementCounter()
{
    global $count;
    $count++;
}

readingFile($FILE);


texts:
I started learning Python just yesterday, and so I am aware of my lack of knowledge regarding the language. Below is a program I wrote to simulate a guessing game. I ended up creating a lot of ad hoc patches for some possible errors, and suspect that there are more elegant ways to write the program. I'd like pointers/assistance/an example of a "best practices" version of the program I write below:

import random, sys

sys.setrecursionlimit(10000)    #I expect any troll who's trying to fuck with the program to give up before they reach 10,000.
control = True    #global variable to control the behaviour of the 'guessNumber()' function.
errors = 0    #To store the number of errors a user triggers.

def guessNumber(maxx):
    global errors
    global control
    try:
        maxx = float(maxx)    #Incase a cheeky user decided to submit floating point numbers.
        if int(maxx) != maxx:     #If they submitted a floating point number instead of an integer.
            print("Input whole numbers only.")
            errors += 1
            guessNumber(input('Input the Maximum number: \t'))  #Call a new instance of 'guessNumber()'
        else:   #If they indeed submitted a whole number.
            maxx = int(maxx)
    except ValueError:  #They didn't submit a whole number.
        print("Input whole numbers only.")
        errors += 1
        guessNumber(input('Input the Maximum number: \t'))  #Call a new instance of 'guessNumber()'

    if not control:    #control variable. If the program has already properly evaluated, it should terminate.
        return None

    print('I am thinking of a whole number between 1 and ' + str(maxx) + ' (both inclusive).')
    num = random.randint(1, maxx)
    count = 0
    check = True
    var = None

    while check:
        print("Guess the number.")
        try:
            var = float(input())    #Incase a cheeky user decided to submit floating point numbers.
            if int(var) != var:     #If they submitted a floating point number instead of an integer.
                print("Input whole numbers only.")
                errors += 1
                continue
            else:   #If they indeed submitted a whole number.
                var = int(var)
        except ValueError:  #They didn't submit a whole number.
            print("Input whole numbers only.")
            errors += 1
            continue
        count +=  1
        if var == num:  #If they guess the number right.
            check = False
        elif var > num:
            print('Too high! \nTry a little lower.')
        elif var < num:
            print('Too low! \nTry a little higher.')

    print('Congratulations!!!\nYou guessed the number after ' + str(count) + " tries and triggering " + str(errors) + " errors.")
    control = False     #After every completed execution, we set control to false so that if the function was called from another instance of itself it terminates and doesn't cause errors.
    return None

guessNumber(input('Input the Maximum number (integers only): \t'))

I am particularly worried about the memory cost, due to using recursion to deal with errors.


texts:
I wrote a C# tool that make a recursive search. I need the file size and the size on disc. I am using a function that give me the size on disc but it is very slow.

Is there any other way to do it except the following code?

public void RecursiveSearch(string path)
{
    try
    {
        foreach (string dir in Directory.GetDirectories(path))
        {
            foreach (string file in Directory.GetFiles(dir))
            {
                FileInfo fi = new FileInfo(file);

                Application.DoEvents();
                lblPfad.Text = fi.FullName;

                long FileLength = fi.Length;
                long FileLengthOnHarddisc = GetFileSizeOnDisk(file,fi);

                if ((FileLength == FileLengthOnHarddisc && FileLength == 4096) || FileLength >= FileLengthOnHarddisc)
                {
                    myStreamWriter.WriteLine(file + " - Größe - " + FileLength.ToString() + " - Größe auf Datenträger - " + FileLengthOnHarddisc.ToString());
                }

            }

            RecursiveSearch(dir);

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Here is the function for getting the size on disc:

  public static long GetFileSizeOnDisk(string file,FileInfo info)
        {
            uint dummy, sectorsPerCluster, bytesPerSector;

            int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy);
            if (result == 0) throw new Win32Exception();
            uint clusterSize = sectorsPerCluster * bytesPerSector;

            uint hosize;
            uint losize = GetCompressedFileSizeW(file, out hosize);
            long size;
            size = (long)hosize << 32 | losize;
            return ((size + clusterSize - 1) / clusterSize) * clusterSize;
        }

        [DllImport("kernel32.dll")]
        static extern uint GetCompressedFileSizeW([In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
           [Out, MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh);

        [DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)]
        static extern int GetDiskFreeSpaceW([In, MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName,
           out uint lpSectorsPerCluster, out uint lpBytesPerSector, out uint lpNumberOfFreeClusters,
           out uint lpTotalNumberOfClusters);


texts: Array choice based on template specialization

texts:
I've got these two template functions responsible of adding/removing actors in-game in GameEngine.h:

template<typename T>
void add(T actor);
template<typename T>
void remove(T actor);

And these arrays:

std::set<std::shared_ptr<Tickable>> tickables;
std::set<std::shared_ptr<Hitbox>> hitboxes;
std::set<std::shared_ptr<sf::Drawable>> drawables;
std::set<std::shared_ptr<EventCatch>> eventCatchers;

Currently, the way i fill these is really... horrible, here's GameEngine.cpp:

template<>
void GameEngine::add<std::shared_ptr<sf::Drawable>>(std::shared_ptr<sf::Drawable> actor)
{
    drawables.insert(actor);
}

template<>
void GameEngine::add<std::shared_ptr<Hitbox>>(std::shared_ptr<Hitbox> actor)
{
    hitboxes.insert(actor);
}

template<>
void GameEngine::add<std::shared_ptr<Tickable>>(std::shared_ptr<Tickable> actor)
{
    tickables.insert(actor);
}

template<>
void GameEngine::add<std::shared_ptr<EventCatch>>(std::shared_ptr<EventCatch> actor)
{
    eventCatchers.insert(actor);
}

template<>
void GameEngine::remove<std::shared_ptr<sf::Drawable>>(std::shared_ptr<sf::Drawable> actor)
{
    drawables.erase(actor);
}

template<>
void GameEngine::remove<std::shared_ptr<Hitbox>>(std::shared_ptr<Hitbox> actor)
{
    hitboxes.erase(actor);
}

template<>
void GameEngine::remove<std::shared_ptr<Tickable>>(std::shared_ptr<Tickable> actor)
{
    tickables.erase(actor);
}

template<>
void GameEngine::remove<std::shared_ptr<EventCatch>>(std::shared_ptr<EventCatch> actor)
{
    eventCatchers.erase(actor);
}

My knowledge about template / smart pointer is limited(yet), is there a better way to do this?
Even if that modifies the arrays, as long as i can call everything is the Loop:

The game loop looks like that in GameEngine.cpp:

void GameEngine::GameLoop()
{
    sf::Clock timer;
    sf::Time tickRate;
    bool run = true;
    Level level(this);

    while (run) {

        clear();

        for (std::shared_ptr<sf::Drawable> drawable : drawables)
            draw(*drawable);

        display();

        sf::Event event;
        while (pollEvent(event))
        {
            switch (event.type) {
            case sf::Event::Closed:
                close();
                run = false;
                break;
            default:
                for (std::shared_ptr<EventCatch> evt : eventCatchers)
                    evt->onEvent(event);
                break;
            }
        }

        for (std::shared_ptr<Tickable> tick : tickables)
            tick->onTick(tickRate.asMicroseconds());

        tickRate = timer.restart();
    }
}


texts:
I developed a simple deck shuffle and drawing system, as a test on how to use collections and learn from it.

However, I think my code is a bit wonky, and I think here is the best place to get new tips on what to improve.

Public deck As New Collection
Public face As New Collection
Public symbols As New Collection

Sub atomic()

face.Add "A"
For i = 2 To 10
    face.Add i
Next i
face.Add "J"
face.Add "Q"
face.Add "K"
symbols.Add ChrW(9826)
symbols.Add ChrW(9828)
symbols.Add ChrW(9825)
symbols.Add ChrW(9831)

End Sub

Sub lime()

Set deck = Nothing
Set face = Nothing
Set symbols = Nothing
Dim i As Long

For i = 1 To 52
deck.Add i
Next i

atomic

End Sub

Sub versive(draw As Long)
Dim randc As Long
Dim ub As Long
Dim cardnumber As Long
Dim actualcard As String
Dim actualcard2 As String
Dim i As Long
Dim lastrow As Long
lastrow = Cells(Rows.count, 14).End(xlUp).row
For i = 1 To draw

    ub = deck.count
    If ub = 0 Then
        MsgBox "Out of cards"
    Exit Sub
    End If
    randc = Int((ub - 1 + 1) * Rnd() + 1)
    If randc > ub Then
       randc = ub
    End If
    cardnumber = deck.Item(randc)
    deck.Remove (randc)
    actualcard = face.Item(cardnumber - (WorksheetFunction.RoundUp(cardnumber / 13, 0) - 1) * 13) & symbols.Item(WorksheetFunction.RoundUp(cardnumber / 13, 0))
    lastrow = lastrow + 1
    Cells(lastrow, 14).Value = actualcard
Next i
End Sub

Private Sub CommandButton1_Click()
versive (51)
End Sub

Private Sub CommandButton2_Click()
lime
End Sub

If it matters, it is developed on Excel VBA.

The atomic sub calls for the definition of the cards names, because it was not just numbers (Like 1 is actually "A") and the definition for the symbols (Hearts, diamonds, etc).

The lime sub basically restarts everything. It runs the atomic sub, so lime actually needs to run first. It also defines that the deck will have 52 cards.

The versive sub actually draws cards. So after it gets a random number from 1 to the amount of cards left in the deck, it converts the number to the actual value and symbols of cards, doing some math to convert it in such a way that number 1 becomes Ace of Diamonds and number 52 becomes King of Clubs. Versive sub also allows multiple cards drawn at once.


texts: Subtraction in a spreadsheet column numbering scheme

texts:
The idea of the algorithm is to decrease a number from a word.

Is there a better way to write this algorithm?

limitiation:

it is important to decrease with a limit, if BB is the word we
decrease from, after decreasing by 1 the result will be BA, but
after decreasing by 2, we expect logically for the result to be AZ,
but no, we want to stay with our word limit, so the result will be
AB, the next word will be AA.
tought it supports decreasing only it can be changed easily to
support increasing.
though it supports only UPPER CASE letters, it can be changed easily
by changing the A_IN_ASCII code.

Usage:

one usage that was needed, was to create a matrix based on a start cell and an end cell - the start cell is AA and the end cell is BB, so we will need those cells : (AA, AB, BA, BB), to get them we need to decrease from BB by an increasing index 0

Examples:

 - getWordDecreasedByNumber('C', 2) = 'A' (just like doing 3 - 2 = 1)
 - getWordDecreasedByNumber('AB', 1) = 'AA' ('AB' - 1)
 - getWordDecreasedByNumber('BB', 3) = 'AA' ('BB' - 3)
 - getWordDecreasedByNumber('ZZ', 26*26-1) = 'AA' ('ZZ' - 675)
 - getWordDecreasedByNumber('ZZZZ', 25) = 'ZZZA' ('ZZZZ' - 25)
 - getWordDecreasedByNumber('ZZZZ', 26) = 'ZZYZ' ('ZZZZ' - 26)
 - getWordDecreasedByNumber('BB', 1) = 'BA'
 - getWordDecreasedByNumber('BB', 2) = 'AB'
 - getWordDecreasedByNumber('BB', 3) = 'AA'

Code:

String.prototype.replaceAt=function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
}

function getWordDecreasedByNumber(word, n) {
            var A_IN_ASCII = 64;
            var decreasedWord = word;
            for (var i = word.length - 1; i >= 0; i--) {
                var limit = (word.charCodeAt(i) - A_IN_ASCII);
                var reduce = n % limit;
                var newCode = word.charCodeAt(i) - reduce;
                var newChar = String.fromCharCode(newCode);
                decreasedWord = decreasedWord.replaceAt(i, newChar);
                n = Math.floor((n - reduce) / limit);
            }

            return decreasedWord;
   }

 console.info(getWordDecreasedByNumber('C', 2)) // 'A'
 console.info(getWordDecreasedByNumber('AB', 1)) // 'AA'
 console.info(getWordDecreasedByNumber('BB', 3)) //'AA'
 console.info(getWordDecreasedByNumber('ZZ', 26*26-1)) //'AA' ('ZZ' - 675)
 console.info(getWordDecreasedByNumber('ZZZZ', 25)) //'ZZZA'
 console.info(getWordDecreasedByNumber('ZZZZ', 26)) //'ZZYZ'
 console.info(getWordDecreasedByNumber('BB', 1)) // 'BA'
 console.info(getWordDecreasedByNumber('BB', 2)) // 'AB'
 console.info(getWordDecreasedByNumber('BB', 3)) // 'AA'


texts:
I am looking for some useful feedback on my programming. I'm only three days in and trying to improve.

Here is the code:

#include <iostream>
using namespace std;
const double SECT_A_TICKPRICE = 20;
const double SECT_B_TICKPRICE = 15;
const double SECT_C_TICKPRICE = 10;

double getSeatsA();
double getSeatsB();
double getSeatsC();
double calcIncomeA(double);
double calcIncomeB(double);
double calcIncomeC(double);
void showIncome(double, double, double);

int main()
{
    double aSeats;
    double bSeats;
    double cSeats;
    double incomeSectA;
    double incomeSectB;
    double incomeSectC;

    aSeats = getSeatsA();

    bSeats = getSeatsB();

    cSeats = getSeatsC();

    incomeSectA = calcIncomeA(aSeats);

    incomeSectB = calcIncomeB(bSeats);

    incomeSectC = calcIncomeC(cSeats);

    showIncome(incomeSectA, incomeSectB, incomeSectC);

    return 0;

}

double geatSeatsA()
{
    double totalSeatsA;

    cout << "How many tickets were sold in Section A?" << endl;

    cin >> totalSeatsA;

        while (totalSeatsA < 0 && totalSeatsA > 300)
        {
            cout << "Enter a value between 0 and 300" << endl;

            cin >> totalSeatsA;
        }

    return totalSeatsA;
}

double geatSeatsB()
{
    double totalSeatsB;

    cout << "How many tickets were sold in Section B?" << endl;

    cin >> totalSeatsB;

        while (totalSeatsB < 0 && totalSeatsB > 500)
        {
            cout << "Enter a value between 0 and 500" << endl;

            cin >> totalSeatsB;
        }

    return totalSeatsB;
}

double geatSeatsC()
{
    double totalSeatsC;

    cout << "How many tickets were sold in Section C?" << endl;

    cin >> totalSeatsC;

        while (totalSeatsC < 0 && totalSeatsC > 200)
        {
            cout << "Enter a value between 0 and 200" << endl;

            cin >> totalSeatsC;
        }

    return totalSeatsC;
}

double calcIncomeA(double aSeats)
{
    double incomeA;

    incomeA = aSeats * SECT_A_TICKPRICE;

    return incomeA;
}

double calcIncomeB(double bSeats)
{
    double incomeB;

    incomeB = bSeats * SECT_B_TICKPRICE;

    return incomeB;
}

double calcIncomeC(double cSeats)
{
    double incomeC;

    incomeC = cSeats * SECT_C_TICKPRICE;

    return incomeC;
}

void showIncome(double incomeSectA, double incomeSectB, double incomeSectC)
{
    double allincome;

    allincome = incomeSectA + incomeSectB + incomeSectC;

    cout << "The income for Section A is ";

    cout << incomeSectA << endl;

    cout << "The income for Section B is ";

    cout << incomeSectB << endl;

    cout << "The income for Section C is ";

    cout << incomeSectC << endl;

    cout << "The total amount made from ticket sales is ";

    cout << allincome;

}


texts:
Last week I was challenged in a technical interview with a code challenge about threads and efficiency.
The challenged required to create a service to detect whether an ID had been already seen or not.
The requirements were simple:

Return true or false if a given id was already seen or not
Duplicates are not allowed, this is critical
False positives can be tolerated at a maximum error rate of less than 1%
Must be thread safe to call
No 3rd party packages can be used
create the implementation as efficiently as possible in both locking, memory usage, and cpu usage

I was provided with the following code:
public interface IDuplicateDetectionService
{
    bool Seen(int id);
}

public class Service : IDuplicateDetectionService
{
    public bool Seen(int id)
    {
        if (id < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(id));
        }
    }
}

My solution was this:
public class Service : IDuplicateDetectionService
{
    private readonly HashSet<int> _itemsSeen = new HashSet<int>();
    private readonly object _lock = new object();

    public bool Seen(int id)
    {
        if (id < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(id));
        }

        if (_itemsSeen.Contains(id))
        {
            return true;
        }

        lock(_lock)
        {
            return _itemsSeen.Add(id) == false;
        }
    }
}

And the test code this:
private void Test()
{
    //Arrange
    var maxDegreeOfParalellism = 1000;
    var idCount = 1000000;
    var successfulCalls = 0;
    var failedCalls = 0;
    var ids = Enumerable.Range(1, idCount);

    var servie = new Service();
    var testService = new Action<int>(id =>
    {
        var seen= service.Seen(id);
        if (seen == false)
        {
            Interlocked.Increment(ref successfulCalls);
        }
        else
        {
            Interlocked.Increment(ref failedCalls);
        }
    });

    // Act
    Parallel.ForEach(
        ids,
        new ParallelOptions
        {
            MaxDegreeOfParallelism = maxDegreeOfParalellism
        },
        currentId => testService(currentId));

    // Assert
    Assert.Equal(idCount, successfulCalls);
    Assert.Equal(0, failedCalls);
}

The code worked and the test passed, however, I don't think I matched the expectations.
To begin with, I don't understand the requirement stating error rate of less than 1%, on the other hand, I don't know how to refactor that code so that it satisfies the conditions.
I didn't get possitive feedback, which is fine, but I didn't get what a possible solution would be, which I would have liked to get.
I would like to learn how that case could be solved following the given requirements.
Thanks.


texts:
I've done the shakesort algorithm win \$O(N^2)\$ but it doesn't seem that \$O(N^2)\$ is correct because it takes 6-9 steps in the while loop for a list of 4 integers and \$4^2\$ is 8. ~1975 steps for 80 entries. I think that should be original. Do you have any tips and improvements for me?

# -*- coding: utf-8 -*-
"""
Created on Nov 25 20:02:33 2016
Shakesort Algorithm

@author: frye
"""
import random

def shakesort(workList):
    listLength = len(workList)
    listIndexDecr = listLength - 1
    listIndexIncr = 0
    xChanged = True
    step = 0

    if(listLength <= 1):
        return workList, 1
    # This will loop n times throught the whole list till the
    # list got looped without a change of number or sort
    while (True):
        step = step + 1 # For counting purpose
        # Init a new loop
        if(listIndexDecr <= 0):
            listIndexIncr = 0
            listIndexDecr = listLength - 1
            # Stop if the last loop had no sort!
            if(xChanged == False):
                break
            # Set it False again
            xChanged = False

        # Walk Forward
        if(workList[listIndexIncr] > workList[listIndexIncr+1]):
            tvar = workList[listIndexIncr+1]
            workList[listIndexIncr+1] = workList[listIndexIncr]
            workList[listIndexIncr] = tvar
            xChanged = True
        listIndexIncr = listIndexIncr + 1

        # Walk back
        if(workList[listIndexDecr-1] > workList[listIndexDecr]):
            tvar = workList[listIndexDecr-1]
            workList[listIndexDecr-1] = workList[listIndexDecr]
            workList[listIndexDecr] = tvar
            xChanged = True
        listIndexDecr = listIndexDecr - 1

    # Return sorted list and stats
    return workList, step

#myList = [21,2,43,4,4,2,4,7,87,65,0,0,0,4,3,2,1212,21,212,32,433]
myList = random.sample(range(32), 4)
print("> "+str(myList))
myNewList,x = shakesort(myList)
print("< " + str(myNewList))
print("Finished in "+str(x-1)+" steps! List length was: "+str(len(myList)))


texts: Graph implementation in c++ using adjacency matrix

texts:
Here is my code for implementing Graph using adjacency matrix. The code should be Object-oriented and there is a method isPath() checking if there is a connection between two nodes. Some advice?

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

class Graph
{
protected:
    int value;
    int **graphm;

public:
    Graph(int value)
    {
        this->value = value;
        graphm = new int*[value];
        int k, j;
        for (k = 0; k < value; k++)
        {
            graphm[k] = new int[value];
            for (j = 0; j < value; j++)
            {
                graphm[k][j] = 0;
            }
        }
    }

    void newEdge(int head, int end)
    {
        if (head > value || end > value || head < 0 || end < 0)
        {
            cout << "Invalid edge!\n";
        }
        else
        {
            graphm[head - 1][end - 1] = 1;
            graphm[end - 1][head - 1] = 1;
        }
    }

    void display()
    {
        int i, p;

        for (i = 0; i < value; i++)
        {
            for (p = 0; p < value; p++)
            {
                cout << graphm[i][p] << "   ";
            }
            cout << endl;
        }
    }

    void isPath(int head, int end)
    {
        int k, o;
        ofstream fullstore("Test.txt");

        cout << graphm[head - 1][end - 1];
        cout << endl;
        if (!fullstore.is_open())
        {
            cout << "File can't be open";
        }

        if (graphm[head - 1][end - 1] == 1)
        {
            cout << "There is an edge between " << head << " and " << end << "\n";
            fullstore << head << ", " << end;
            fullstore.close();
        }
        else
        {
            cout << "Edge not found\n";
        }
    }
};

int main()
{
    int vertex, numberOfEdges, i, head, end;
    cout << "Enter number of nodes: ";
    cin >> vertex;
    numberOfEdges = vertex * (vertex - 1);
    Graph g1(vertex);
    for (int i = 0; i < numberOfEdges; i++)
    {
        cout << "Enter edge ex.1 2 (-1 -1 to exit): \n";
        cin >> head >> end;
        if ((head == -1) && (end == -1))
        {
            break;
        }
        g1.newEdge(head, end);
    }
    g1.display();
    cout << endl;
    g1.isPath(1, 3);

    return 0;
}


texts:
I am working on the Google Maps API, doing a reverse geocoding with the following code snippet.

What I am using are:

Spring
Jackson Parser
Google Maps API

It is working fine but it gives results a bit slowly. Can I improve my code in terms of performance?

package com.addressparser.api;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class GeocodeAddressParser {
    public String getLocationInfo( String lat, String lng) throws JsonProcessingException, IOException {

        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=false");

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
            } catch (IOException e) {
        }

        ObjectMapper mapper = new ObjectMapper();
        JsonNode array =  mapper.readValue(stringBuilder.toString(), JsonNode.class);
        JsonNode object = array.get("results").get(0);
        String reportKey = object.get("formatted_address").textValue();
        System.out.println(reportKey);//just printing it on the console for testing at the moment
        return reportKey;

    }

    public static void main(String[] args) throws JsonProcessingException, IOException{
        GeocodeAddressParser ref = new GeocodeAddressParser();

        ref.getLocationInfo("31.338451","75.554183");
    }
}


texts:
I'm learning about how to create a good and clean code. I just need to review something like that, and I really not sure how can I fix this code into a clean code.
bool isValidUserName(const std::string& username)
{
    bool valid = false;

    if (username.length() >= MIN_NAME_LENGTH)
    {
        if (username.length() <= MAX_NAME_LENGTH)
        {
            if (isalpha(username[0]))
            {
                bool foundNotValidChar = std::find_if(username.begin(), username.end(), isNotValid) != username.end();
                if (!foundNotValidChar)
                {
                    valid = true;
                }
            }
        }
    }

    return valid;
}


texts:
Is there any way I can DRY up this Rails 4 routes.rb code?

  match '/oauth/apps/' => 'oauth/applications#index', :as => :oauth_applications, :via => :get
  match '/oauth/apps/new/' => 'oauth/applications#new', :as => :new_oauth_application, :via => :get
  match '/oauth/apps/new/' => 'oauth/applications#create', :via => :post
  match '/oauth/apps/:id/' => 'oauth/applications#show', :as => :oauth_application, :via => :get
  match '/oauth/apps/:id/edit/' => 'oauth/applications#edit', :as => :edit_oauth_application, :via => :get
  match '/oauth/apps/:id/edit/' => 'oauth/applications#update', :via => :post
  match '/oauth/apps/:id/destroy/' => 'oauth/applications#destroy', :as => :destroy_oauth_application, :via => :delete


texts: Python exception handler to recommend package

texts:
Consider this python 3 snippet, where when an import exception is raised, a string 'e' is created that says: "No module named ' packageName'".

The goal is to simply say on exit, that the import error can perhaps be solved by installing a package of the same name. I came up with this, and it works but I'd like to make it better, if anyone has some tips.

except ImportError as e:
     e = e.replace("No module named '", "")
     e = e.replace("'", "")
     sys.exit("'Error: Try sudo pip install %s'" % e)

Example output:

  Error: Try sudo pip install Crypto


texts: Finding nearest points and points within a radius

texts:
I have implemented the following two methods which are described in 1. and 2..

Is there another better simpler way to implements those methods?

  A static method, nearestPoint , accepts an array of points (objects of type Point ) and one point (an object of type Point),
  and returns that point in the array which is closest to the given
  point. Create that method.
  A circle in the plane, with radius \$r\$ and midpoint at the origin, is given by the following equation: \$x^2 + y^2 = r^2\$

  A static method, internalPoints , accepts an array of points (objects
  of type Point) and the radius of a circle, and returns those points
  (in an array) that are inside the given circle. Create that method.
  Create an array of points (objects of type Point) and a point (an object of type Point). Establish also the radius of the circle.
  Use the method nearestPoint to determine the point in the array that
  is closest to the given point. Then use the method internalPoints to
  determine the points that are inside the circle.

public class Point {
// the coordinates of the point
private double x;
private double y;

public Point(double x, double y) {
    this.x = x;
    this.y = y;
}

public double getX() {
    return this.x;
}

public double getY() {
    return this.y;
}

// distance returns the distance between this point and a given point
public double distance(Point p) {
    return Math.sqrt((p.x - this.x) * (p.x - this.x) +
            (p.y - this.y) * (p.y - this.y));
}

public String toString() {
    String s = "";
    //for (int i = 0; i < s.length(); i++) {
    s = "(" + this.getX() + "," + this.getY() + ")";

    return s;
}

public static Point nearestPoint(Point[] points, Point point) {
    Point p = points[0];
    for (int i = 0; i < points.length; i++) {
        if (points[i].distance(point) < p.distance(point)) {
            p = points[i];
        }
    }
    return p;
}

public static Point[] internalPoints(Point[] points, double radius) {

    int countPoints = 0;
    for (int i = 0; i < points.length; i++) {
        double xp = points[i].getX();
        double yp = points[i].getY();
        // points are inside the circle if d^2 <= r^2
        // d^2 = (Xp-Xc)^2 + (Yp-Yc)^2
        // Xp and Yp is the point that should be checked
        // Xc and Xc is the point center (orgin)
        // Xc and Yc are 0 you end up with d^2 = (Xp-Xc)^2 + (Yp-Yc)^2
        if (xp * xp + yp * yp <= radius * radius) {
            countPoints++;
        }
    }
    int companionVar = 0;
    Point[] pointsInside = new Point[countPoints];
    for (int j = 0; j < countPoints; j++) {
        pointsInside[companionVar] = points[j];
        companionVar++;
    }
    return pointsInside;

}

public static void main(String[] args) {
    Point[] points = {new Point(1, 2),
            new Point(2, 3),
            new Point(5, 2)};
    new Point(12, 13); // points outside the circle
    Point point = new Point(1, 1);
    double r = 7;
    Point nearestPoint = nearestPoint(points, point);
    Point[] internalPoints = internalPoints(points, 7);

    System.out.println(nearestPoint + "   " + Arrays.toString(internalPoints));
}

}


texts: Maximum product of 3 integers in an int array

texts:
I want to find the maximum product that can be obtained from any 3 integers in an integer array. The optimal solution has time complexity of \$O(n)\$ and space complexity of \$O(1)\$. I managed to write up as solution in Java that only traverses the array twice (so my time complexity is \$O(n)\$) and my space complexity is \$O(1)\$. I do not believe the solution can be any cleaner than this but would still like to see what other people think.

The \$O(n)\$ solution is obtained by keeping track of the max three integers and the min two integers. The max product will either be  (min_one * min_two * max_one) or (max_one * max_two * max_three).

// Assume input array is of at least length 3.

public int max_prod_three(int[] A){

    int len = A.length;

    // Base case
    if (len == 3) return A[0]*A[1]*A[2];

    int max = A[0], min = A[0], max_index = 0, min_index = 0;

    for (int i = 0; i < len; i++) {

        if (A[i] > max) {

            max = A[i];
            max_index = i;
        }
        else if (A[i] < min) {

            min = A[i];
            min_index = i;
        }
    }

    int max_sec = min, max_third = min , min_sec = max;

    for (int i = 0; i < len; i++) {

        if (i == max_index || i == min_index) continue;

        if (A[i] > max_sec) {

            max_third = max_sec;
            max_sec = A[i];
        }
        else if (A[i] > max_third) {
            max_third = A[i];
        }

        if (A[i] < min_sec) min_sec = A[i];

    }

    int prod_one = max * max_sec * max_third ;
    int prod_two = min * min_sec * max ;

    if (prod_one > prod_two) return prod_one ;
    return prod_two;
}

You can iterate through the array only once and get the max product but I found that the solution gets a bit too messy (with a lot more if else statements). But if anyone can do it cleanly, I would like to know.


texts:
I'm currently in the process of redesigning and coding my website, for which I'm wanting to use paper.js to draw on canvas. Currently the only project page I have is using a basic random ball generator on canvas with paper. I've set up a debounced resize function however the calculations seem to be taking a long time to be applied, which in turn breaks the canvas and the balls appear momentarily out of their containers.

HTML:

        <canvas id="canvas" resize></canvas>

JS/Paperscript:

$(document).ready( function() {

    var halfImg = $('.project-image-half'),
        palette = ["#F4E664", "#EF6767", "#2089F8", "#3D9FF8", "#DBDCE0", "#F7F7F7"];

    function canvasSizer() {
        var heroW = $('.project-hero').width(),
            heroH = $('.project-hero').height();

        canvas.width = heroW;
        canvas.height = heroH;

        view.viewSize = new Size(heroW, heroH);
    }

    var imageObj = {
        heightSizer: function() {

            var imgWidth = halfImg.width();

            halfImg.css({
                height: function() {
                    return imgWidth * 0.716292135 + "px";
                }
            });
        }
    };

    function Ball(r, p) {
        this.path = new Path.Circle({
            fillColor: palette[Math.floor(Math.random()*palette.length)],
            center: p,
            radius: r
        });
    };

    var balls = [];
    var numBalls = 18;
    for (var i = 0; i < numBalls; i++) {
        var position = Point.random() * view.size;
        var radius = Math.random() * 40 + 50;
        balls.push(new Ball(radius, position));
    }

    function init() {
        canvasSizer();
        imageObj.heightSizer();
    }

    function debounce(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

    var debouncedFunctions = debounce(function() {
        imageObj.heightSizer();
        canvasSizer();
    }, 50);

    window.addEventListener('resize', debouncedFunctions);

    init();
});

I can't see any reason why it's taking so long. I'm wondering if it's possibly because I'm viewing it on a Retina Display Macbook Pro so the canvas is rendering twice as large?


texts:
I am attempting to write a Python code to simulate many particles in a confined box. These particles behave in such a way that they move in the box in straight lines with a slight angular noise (small changes in the direction of the particle path). They should interact by acknowledging the other particle and 'shuffle/squeeze' past each other and continue on their intended path, much like humans on a busy street. Eventually, the particles should cluster together when the density of particles (or packing fraction) reaches a certain value.
However, I have a feeling there are parts of the code that are inefficient or which could be either sped up or written more conveniently.
If anyone has any improvements for the code speed or ideas which may help with the interactions and/or angular noise that would be much appreciated. I will also leave an example of an animation which is my aim: https://warwick.ac.uk/fac/sci/physics/staff/research/cwhitfield/abpsimulations
The above link shows the animation I am looking for, although I don't need the sliders, just the box, and moving particles. The whole code is shown below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def set_initial_coordinates():
    x_co = [np.random.uniform(0, 2) for i in range(n_particles)]
    y_co = [np.random.uniform(0, 2) for i in range(n_particles)]
    return x_co, y_co

def set_initial_velocities():
    x_vel = np.array([np.random.uniform(-1, 1) for i in range(n_particles)])
    y_vel = np.array([np.random.uniform(-1, 1) for i in range(n_particles)])
    return x_vel, y_vel

def init():
    ax.set_xlim(-0.05, 2.05)
    ax.set_ylim(-0.07, 2.07)
    return ln,

def update(dt):
    xdata = initialx + vx * dt
    ydata = initialy + vy * dt
    fx = np.abs((xdata + 2) % 4 - 2)
    fy = np.abs((ydata + 2) % 4 - 2)

    for i in range(n_particles):
        for j in range(n_particles):
            if i == j:
                continue

            dx = fx[j] - fx[i]  # distance in x direction
            dy = fy[j] - fy[i]  # distance in y direction
            dr = np.sqrt((dx ** 2) + (dy ** 2))  # distance between x

            if dr <= r:
                force = k * ((2 * r) - dr)  # size of the force if distance is less than or equal to radius

                # Imagine a unit vector going from i to j
                x_comp = dx / dr  # x component of force
                y_comp = dy / dr  # y component of force

                fx[i] += -x_comp * force  # x force
                fy[i] += -y_comp * force  # y force
    ln.set_data(fx, fy)
    return ln,

# theta = np.random.uniform(0, 2) for i in range(n_particles)
n_particles = 10
initialx, initialy = set_initial_coordinates()
vx, vy = set_initial_velocities()
fig, ax = plt.subplots()
x_co, y_co = [], []
ln, = plt.plot([], [], 'bo', markersize=15)  # radius 0.05
plt.xlim(0, 2)
plt.ylim(0, 2)

k = 1
r = 0.1
t = np.linspace(0, 10, 1000)

ani = FuncAnimation(fig, update, t, init_func=init, blit=True, repeat=False)
plt.show()


texts: Writing a product() function analogous to sum

texts:
Exercise 1.31

  a.  The sum
  procedure is only the simplest of a
  vast number of similar abstractions
  that can be captured as higher-order
  procedures.51 Write an analogous
  procedure called product that returns
  the product of the values of a
  function at points over a given range.
  Show how to define factorial in terms
  of product. Also use product to
  compute approximations to  using the
  pi / 4 = (2/3) * (4/3) * (4/5) * (6/5)
  * (6/7) * (8/7) ...

  b.  If your product procedure
  generates a recursive process, write
  one that generates an iterative
  process. If it generates an iterative
  process, write one that generates a
  recursive process.

I wrote the following:

Recursive:

(define (product term a next b)
  (cond
    ((> a b) 1)
    (else (* (term a) (product term (next a) next b)))))

Iterative:

(define (i-product term a next b)
  (cond ((> a b) null)
      (else
       (define (iter a result)
         (cond ((> a b) result)
               (else (iter (next a) (* (term a) result)))))
       (iter a 1))))

Multiply-integers [test - does (product ...) work?]

(define (identity x) x)
(define (inc x) (+ 1 x))
(define (multiply-integers a b) (i-product identity a inc b))

Compute pi:

(define (square x) (* x x))
(define (compute-pi steps)
  (define (next n) (+ n 2.0))
  (* 8.0 (* steps 2) (/ (i-product square 4.0 next (* (- steps 1) 2))
              (i-product square 3.0 next (* steps 2)))))

Factorial:

(define (factorial n)
  (define (next n) (+ n 1))
  (i-product identity 1 next n))

What do you think of my solution?


texts: Password Generator with injected password model

texts:
I'm getting started with Python and one of the beginner projects to learn the language was a password generator (one of the dozens already in CodeReview). I have a C# and JS background so I want to make sure I'm doing things the Python way.
Technically the include_punctuation and include_digits properties could be omitted and the exclusion list would be a custom concat of strings.digits+strings.punctuation.
The reasoning behind the PasswordModel is that any component that has an API of charset and length is a valid model. That would mean we could create a MemorablePasswordModel for passwords such as "apple truck butterfly postcard" with a clean and separate model.
from random import choice
from string import digits, ascii_letters, punctuation

def filter_exclusions(items, exclusions):
    result = []
    for i in items:
        if i not in exclusions:
            result.append(i)

    return result

class PasswordModel:
    def __init__(self, length=8, include_symbols=True, include_digits=True, exclusion_list=""):
        self.exclusion_list = list(exclusion_list)
        self.length = length
        self.include_symbols = include_symbols
        self.include_digits = include_digits

    def charset(self) -> str:
        chars = [ascii_letters]

        if self.include_symbols:
            chars.append(punctuation)
        if self.include_digits:
            chars.append(digits)

        return "".join(filter_exclusions("".join(chars), self.exclusion_list))

class PasswordGenerator:
    def __init__(self, password_model=PasswordModel()):
        self.model = password_model

    def generate(self) -> str:
        charset = self.model.charset()
        return "".join(choice(charset) for _ in range(self.model.length))

# Test it out
model = PasswordModel(length=24, exclusion_list="\\/@%")
gen = PasswordGenerator()

print(gen.generate())

Questions

Is there a cleaner way to "include" symbols and digits, I just appended them to a list.
Is there anything built-in to exclude one list from another?


texts: Parsing MWNumericArray to C# code optimization

texts:
This is my function returning matrices from Matlab.  This code run very slowly.
I was trying to use Parallel.For in-order to run it in parallel threads but I got different results than running it on one thread.

Am I iterating the matrix in a wrong order? Row, col vs col, row?
Can you please review this code any suggest some performance boost tips?

public static SerializableMatrix ParseNumericMatrix(MWNumericArray matrix)
{
    SerializableMatrix resultMatrix;
    int[] dimensions = matrix.Dimensions;

    if (dimensions.Length > 3 || dimensions.Length < 2)
    {
        throw new ArgumentException("Input matrix dimensions are too long", "Three is the max dimensions");
    }
    var height = dimensions[0];
    var width = dimensions[1];
    resultMatrix = new SerializableMatrix() { Width = width, Height = height, Data = new List<double[]>() };

    if (dimensions.Length == 2)
    {
        var dataArray = new double[width * height];
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                dataArray[i * width + j] = (double)matrix[i, j];
            }
        }
        resultMatrix.Data.Add(dataArray);
        return resultMatrix;
    }
    if (dimensions.Length == 3)
    {
        int depth = dimensions[2];
        for (int depthIndex = 0; depthIndex < depth; depthIndex++)
        {
            var dataArray = new double[width * height];
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    // matlab indices start at 1 , not 0!!!
                    dataArray[i * width + j] = (double)matrix[i + 1, j + 1, depthIndex + 1];
                }
            }
            resultMatrix.Data.Add(dataArray);
        }
    }
    return resultMatrix;
}


texts:
I'm trying to create my own service, $hR.  This service uses XMLHTTPrequest to get data from a URL with promise.

;(function(global){

    var http = function(){
        var self = {}
        self.get = function (url){

            var ajax = new XMLHttpRequest();
            ajax.open('GET',url,true)
            ajax.send()
            var p = new Promise(function(resolve, reject){
                ajax.onreadystatechange = function (){
                    if(ajax.readyState == 4){
                        var obj = JSON.parse(ajax.responseText)
                        resolve(obj)
                    }
                }
            })
            return p;
           }//Get Methood
        return self;
        }
    global.$hR = http();
}(window));

It works great for me, but I created this service only to study and learn.  I want to improve my code.

Can someone give me a more expert way to this same service?


texts: Implementation of KeyEventDispatcher in Java

texts:
This is my first test at making a key event dispatcher. Some of the code is unnecessary if one is interested in separating lower and upper cases, however I want to treat them as the same. Hence my wonderfully named method keyToLowerCaseIfUpperCase(char c). I also want to lock the key if it has been pressed untill it is released by the user. To run an event twice the user first needs to release the key.

First of it checks if the key is in [A...Z], if so it returns the corresponding lower key. If not it will keep the key intact. Then I check whetever a key was pressed or not pressed, if it was pressed it will check if that specific key actually can be pressed (using my lock). If it was a key release it will simply release the lock of that key.

import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;

import java.util.HashMap;

public class KeyBindManager implements KeyEventDispatcher
{
    private HashMap<String, Boolean> keyPresses = new HashMap<>();

    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        String pressed = keyToLowerCaseIfUpperCase(e.getKeyChar())+"";

        if (e.getID() == KeyEvent.KEY_PRESSED) {

            if (keyPresses.get(pressed) != null && keyPresses.get(pressed).booleanValue()) {
                return false;
            }
            keyPresses.put(pressed, new Boolean(true));

            switch (keyToLowerCaseIfUpperCase(e.getKeyChar())) {
                case 'a': System.out.println("D"); break; // these are just two test cases
                case 'b': System.out.println("E"); break;
                default: break;
            }

        } else if (e.getID() == KeyEvent.KEY_RELEASED){
            keyPresses.put(pressed, new Boolean(false));
        }
        return false;
    }

    private char keyToLowerCaseIfUpperCase (char c) {
        if (c >= 'A' && c <= 'Z') {
            c = Character.toLowerCase(c);
        }

        return c;
    }
}

Please tell me this can be done in a more clean approach than what I've accomplished. I don't like the looks of my code very much at all. For now, it gets the job done.

To emphasize, it is the first draft for it. Every criticism is welcome.


texts:
I'm curious if there is another way to code this. Could it be done with a while loop for instance?

public static int numUnique(double[] list) {
    int uniques = 0;
    if(list.length == 0){return 0;}
    for(int i = 0; i < list.length; i++){
        int dups = 0;
        for(int j = i + 1; j < list.length; j++){
            if(list[i] == list[j]){
                dups = dups + 1;
            }
        }
        if(dups == 0){
            uniques = uniques + 1;
        }
    }
    return uniques;
}


texts:
I have created this directive in Angular. The idea is to calculate width of height and height of specific element via style function attached to ng-style on the same element.

The directive uses underscore for debounce, and $routeScope to receive  called from the element, $window to get full height and width of it.

How can I improve this code to make it more testable, more readable?

(function (ng, _) {
ng.module('mixbank.app').directive('tableResize', [
    '$window',
    '$rootScope',
    function ($window, $rootScope) {
        return function (scope, element, attrs) {
            var w = ng.element($window);
            var topOffsetCalculate = function () {
                return {
                    total: ng.element("nav.navbar-fixed-top").height() +
                    ng.element("nav.navbar-business").height() +
                    ng.element(".table-business-rules thead").height()
                }
            };
            var topOffset = topOffsetCalculate().total;
            var leftOffset = ng.element(".left-business-rules-view").outerWidth();
            var rowHeight = 58;
            var expandedRowHeight = 175;

            scope.getWindowDimensions = function () {
                return {
                    'h': w.height(),
                    'w': w.width(),
                    'th': attrs.totalRows * rowHeight + topOffset
                };
            };

            function doLayout(expandedRule) {
                var newValue = scope.getWindowDimensions();
                var possibleHeight = expandedRule ? newValue.th + expandedRowHeight : newValue.th;
                scope.style = function () {
                    var h = Math.min(possibleHeight, newValue.h);
                    return {
                        height: (h - topOffset) + 'px',
                        width: (newValue.w - leftOffset) + 'px'
                    }
                };
            }

            var resizeHandler = _.debounce(function () {
                doLayout();
                scope.$apply();
            }, 300);

            $rootScope.$on('expandRow', function (event, data) {
                typeof data != 'undefined' ? doLayout(true) : doLayout();
            });

            scope.$watch(function () {
                return attrs.totalRows;
            }, function () {
                doLayout();
            });

            scope.$on('$destroy', function () {
                w.off('resize', resizeHandler);
            });
            w.on('resize', resizeHandler);
        }
    }
])
;}(window.angular, _));


texts:
import java.math.BigInteger;
import java.util.Random;
public class Primetest {

    private static int size=15;
    private static Random r=new Random();
    private static BigInteger two=new BigInteger("2");
    private static BigInteger three=new BigInteger("3");
    public static void main(String[] args) {

        while(true)
        {
            BigInteger p=new BigInteger(size,r);
            if(isprime(p)==true)
            {
                System.out.println("prime="+p);
                break;
            }
        }
    }

    public static boolean isprime(BigInteger n)
        {
             if(n.compareTo(BigInteger.ONE)==0 || n.compareTo(two)==0)
            {
                return true;
            }
          BigInteger half=n.divide(two);

           for(BigInteger i=three; i.compareTo(half)<=0;i=i.add(two))
            {

                if(n.mod(i).equals(BigInteger.ZERO))
                {
                  return false;
                }

            }
             return true;

        }
 }

This code selects a random prime BigInteger number. I want a 2048 bit BigInteger prime number, but it only works with 15 bit. Can anybody help me?


texts: Is this Java small pubsub memory implementation correct and effective?

texts:
We want to provide a simple Redis pub/sub alternative in memory for our software. So we implemented this :
public class MemoryDataBus implements DataBus {
    private final Map<Consumer<Message>, MessageListener> subscribers = new ConcurrentHashMap<>();

    @Override
    public void publish(final Channel channel, final Message message) {
        Message nonNullMessage = requireNonNull(message, "cannot publish a null message");
        subscribers.values().stream().filter(l -> l.hasSubscribedTo(channel)).forEach(l -> l.accept(nonNullMessage));
    }

    @Override
    public void subscribe(final Consumer<Message> subscriber, final Channel... channels) throws InterruptedException {
        MessageListener listener = new MessageListener(subscriber, channels);
        subscribers.put(subscriber, listener);
        listener.loopUntilShutdown();
    }

    @Override
    public void unsubscribe(Consumer<Message> subscriber) {
        ofNullable(subscribers.remove(subscriber)).ifPresent(l -> {
            l.accept(new ShutdownMessage());
        });
    }

    private static class MessageListener implements Consumer<Message> {
        private final Consumer<Message> subscriber;
        private final LinkedHashSet<Channel> channels;
        final AtomicReference<Message> message = new AtomicReference<>();

        public MessageListener(Consumer<Message> subscriber, Channel... channels) {
            this.subscriber = subscriber;
            this.channels = asSet(channels);
        }

        boolean hasSubscribedTo(Channel channel) {
            return channels.contains(channel);
        }

        @Override
        public void accept(Message message) {
            subscriber.accept(message);
            synchronized (this.message) {
                this.message.set(message);
                this.message.notify();
            }
        }

        boolean shutdownAsked() {
            Message message = this.message.get();
            return message != null && message.type == Message.Type.SHUTDOWN;
        }

        void loopUntilShutdown() throws InterruptedException {
            synchronized (message) {
                while (!shutdownAsked()) {
                    message.wait();
                }
            }
        }
    }
}

I've removed unnecessary code that brings some noise (logs, couters) the source code is here.
Our unit tests are green, and manual testing shows no regression compared to redis. But as we also know how difficult it is to make a correct thread safe implementation we want to verify with threading experts :

the correctness of it (for example the value returned by shutdownAsked)
if the contention could be improved
if there could be a better implementation of it

PS : must add that the question has been originally posted on SO.


texts:
I am new to repository pattern. If I want to join two tables, where should I implement the logic? I have implemented it as shown below. Is there any better way to achieve the same?

This is my UserRepository class:

public class UserRepository : Repository<UserMaster>, IUserRepository
{
    public UserRepository(DbContext context)
        : base(context)
    {

    }
    public UserMaster GetById(int id)
    {
        return FindBy(x => x.Userid == id).FirstOrDefault();
    }

}

This is the Service layer from which I am implementing data access functions:

 public class UserService : EntityService<UserMaster>, IUserService
{
    IUnitOfWork _unitOfWork;
    IUserRepository _userRepo;
    IRolePrivilegeMapRepository _rolePrevilegeMapRepo;
    IUserRoleMapRepository _userRoleMapRepo;

    public UserService(IUnitOfWork unitOfWork, IUserRepository userRepo, IRolePrivilegeMapRepository rolePrevilegeMapRepo,IUserRoleMapRepository userRoleMapRepo)
        : base(unitOfWork, userRepo)
    {
        _unitOfWork = unitOfWork;
        _userRepo = userRepo;
        _rolePrevilegeMapRepo = rolePrevilegeMapRepo;
        _userRoleMapRepo = userRoleMapRepo;
    }

    public List<int> GetUserPrevileges(string UserName)
    {
        var rolePrevilegeMap = _rolePrevilegeMapRepo.GetAll();
        var userRoleMap = _userRoleMapRepo.GetAll();
        var userMaster = _userRepo.GetAll();

        var Privs = (from  rpm in rolePrevilegeMap
                     join urm in userRoleMap on rpm.RoleId equals urm.Roleid
                     join um in userMaster on urm.Userid equals um.Userid
                     where um.Username.Equals(UserName) && rpm.IsDeleted == false && urm.IsDeleted == false
                     select rpm.PrivilegedId).Distinct();

        if (Privs.Any())
        {
            return Privs.ToList();
        }
        else
        {
            return null;
        }

    }

}

I have injected IRolePrivilegeMapRepository, IUserRoleMapRepository, and IUserRepository using Autofac to the UserService class for joining the tables.

    var rolePrevilegeMap = _rolePrevilegeMapRepo.GetAll();
    var userRoleMap = _userRoleMapRepo.GetAll();
    var userMaster = _userRepo.GetAll();

The GetAll method is of return type IQueryable. After that, using that result, I have done the join. Is this the right way to approach? Or Is there any better way to implement the same?


texts: Project Euler #45 - Triangular, pentagonal, and hexagonal

texts:
Project Euler Problem 45

  Triangle, pentagonal, and hexagonal numbers are generated by the
  following formulae:

  Triangle      Tn=n(n+1)/2     1, 3, 6, 10, 15, ... Pentagonal
    Pn=n(3n−1)/2        1, 5, 12, 22, 35, ... Hexagonal     Hn=n(2n−1)      1, 6,
  15, 28, 45, ... It can be verified that T285 = P165 = H143 = 40755.

  Find the next triangle number that is also pentagonal and hexagonal.

My Implementation:

I used a HashSet for fast searching. I got the right answer after experimenting with the size of the HashSet. 100000 worked for me.

void Main()
{
    var pen = Pentagonals(100000);
    var hex = Hexagonals(100000);

    foreach(var n in Triangles()){
        if(pen.Contains(n) && hex.Contains(n) && n > 40755){
            Console.WriteLine(n);
            return;
        }
    }
}

IEnumerable<BigInteger> Triangles()
{
    for(BigInteger n = 1;;n++)
    {
        yield return (n * (n + 1) / 2);
    }
}

HashSet<BigInteger> Pentagonals(int limit)
{
    HashSet<BigInteger> set = new HashSet<BigInteger>();
    for(BigInteger n = 1;n <= limit;n++)
    {
        set.Add(n * (3 *n - 1) / 2);
    }
    return set;
}

HashSet<BigInteger> Hexagonals(int limit)
{
    HashSet<BigInteger> set = new HashSet<BigInteger>();
    for(BigInteger n = 1;n <= limit;n++)
    {
        set.Add(n * (2*n - 1));
    }
    return set;
}

How can I improve this?


texts: Dynamic loading of Javascript dependency graph

texts:
I have JavaScript module for loading dynamically script files by dependency graph:

var module = {};

module.loadScript = function (url, callback) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.async = true;
    script.charset = 'utf-8';
    document.body.appendChild(script);
    console.time(script.src + ' Load');

    module.addEvent(script, 'load', function () {
        console.timeEnd(this.src + ' Load');
        document.body.removeChild(this);

        if (typeof callback === "function") {
            callback();
        }
    });
};

module.loadJsTree = function (tree, callback) {
    _loadJsTreeInternal(tree, callback, 0, 0);
};

function _loadJsTreeInternal (tree, callback, _totalCount, _loadedCount) {
    tree = tree || {};

    var branches = Object.keys(tree);
    _totalCount += branches.length;

    branches.forEach(function (branch, index) {
        console.log("Start load ", branch, tree[branch]);

        module.loadScript(branch, function () {
            _loadedCount++;

            if (tree[branch] !== null && typeof tree[branch] === 'object') {
                _loadJsTreeInternal(tree[branch], callback, _totalCount, _loadedCount);
            }
            else if (_loadedCount == _totalCount) {
                if (typeof callback === "function") {
                    callback();
                }
            }
        });
    });
}

//RUN SCRIPT

var scripts = {
    '/script1.js': null,
    '/script2.js': {
        '/script2.plugin1.js': {
            '/script2.plugin1.plugin1.js': null
        },
        '/script2.plugin2.js': null
    }
};

module.loadJsTree(scripts, function () { alert("ALL SCRIPTS READY!") });

Do you see any other improvements / issues?


texts: OAuth2 Client for Reddit, written using Tornado

texts:
I have a written some code which helps me to get OAuth Access Code from Reddit. Reddit uses standard OAuth2, so like any other OAuther server, here's are the steps to perform:

The client/app sends app key, app secret and redirect URL to browser.
User authorizes it and gives permission.
Reddit sends request back, with code to earlier given redirect URL.
The code can be used for further access.

The way my script works:

I am using praw. I first create a praw object and pass this to server code with required info like app key, app secret and redirect URL:

oauthserver = PrawOAuth2Server(reddit_client=reddit_client,
                               app_key=app_key,
                               app_secret=app_secret,
                               state=user_agent)

Start the server. This opens the URL in browser and prompts user for authorization. Most of the magic happens at this stage. This not only starts the server (to handle redirect_url request), but also receives the code:

oauthserver.start()

Then later I can get the access code, refresh token using one of Praw's method:

oauthserver.get_access_codes()

Example usage code:

import praw
from PrawOauth2Server import PrawOAuth2Server

user_agent = '...'
app_key = '...'
app_secret = '...'
scopes = ['identity', 'submit']

reddit_client = praw.Reddit(user_agent=user_agent)
oauth_server = PrawOAuth2Server(reddit_client,
                                app_key=app_key,
                                app_secret=app_secret,
                                state=user_agent)
oauth_server.start()
print(oauth_server.get_access_codes())

Finally, here is the code I want to be reviewed:

import webbrowser

import tornado.ioloop
import tornado.web

REDIRECT_URL = 'http://127.0.0.1:65010/authorize_callback'
SCOPES = ['identity']
REFRESHABLE = True
CODE = None

class AuthorizationHandler(tornado.web.RequestHandler):

    def get(self):
        global CODE
        CODE = self.get_argument('code')
        tornado.ioloop.IOLoop.current().stop()

class PrawOAuth2Server:

    def __init__(self, reddit_client, app_key, app_secret,
                 state, redirect_url=REDIRECT_URL, scopes=SCOPES,
                 refreshable=REFRESHABLE):
        self.reddit_client = reddit_client
        self.app_key = app_key
        self.app_secret = app_secret
        self.state = state
        self.redirect_url = redirect_url
        self.scopes = set(scopes)
        self.refreshable = refreshable
        self.code = None

        self._set_app_info()

    def _set_app_info(self):
        self.reddit_client.set_oauth_app_info(self.app_key, self.app_secret,
                                              self.redirect_url)

    def get_auth_url(self):
        return self.reddit_client.get_authorize_url(self.state,
                                                    self.scopes,
                                                    self.refreshable)

    def start(self):
        global CODE
        url = self.get_auth_url()
        webbrowser.open(url)
        tornado.ioloop.IOLoop.current().start()
        self.code = CODE

    def get_access_codes(self):
        return self.reddit_client.get_access_information(self.code)

application = tornado.web.Application([
    (r'/authorize_callback', AuthorizationHandler),
])
application.listen(65010)

I want any general suggestion/advice related to above code
I really want to change the way I am handling CODE (fetching it from request object, using it as global variable etc). I am not able to find way to make this better.


texts:
I've created an Ajax login for my website but I feel like I can optimize it, but I'm not sure how and where.

Questions:

How can I optimize my code?
Is the code secure? Any ways to break it (injection, etc)?

Also, when I attempt to log in, it currently takes about 1 second to process the login (on localhost). Is this long?

Here's my Ajax call:

$(document).ready(function() {
  $(document).on("submit", "form", function(event) {
    event.preventDefault();
    $.ajax({
      url: 'assets/php/login_script.php',
      type: 'POST',
      data: $(this).serialize(),
      success: function(data) {
        if (data == true) {
          window.location.href = "index.php";
        } else {
          $("input[name=password_field]").focus();
          $(".error").html(data);
        }
      }
    });
  });
});

Here's the PHP script:

<?php

  include_once("access.php");

  $cxn = mysqli_connect($host, $user, $pass, $db) or die ("Couldn't connect to the server. Please try again.");

  $username = $_POST["username"];
  $password = $_POST["password"];
  $date = date('Y-m-d h:i:s', time());
  $ip_address = get_ip_address();
  $expire = time() + 86400 * 365;

  $options = array('cost' => 12);
  $hash_password = password_hash($password, PASSWORD_BCRYPT, $options);

  /* Log the login request. */
  $stmt = $cxn->prepare("INSERT INTO login_logs (log_id, username, password, datetime, ip_address) VALUES ('', ?, ?, ?, ?)");
  $stmt->bind_param('ssss', $username, $hash_password, $date, $ip_address);
  $stmt->execute();

  /* Get user information from database. */
  $stmt = $cxn->prepare('SELECT * FROM users WHERE username = ?');
  $stmt->bind_param('s', $username);
  $stmt->execute();
  $result = $stmt->get_result();

  /* If a result exists, continue. */
  if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
      $db_username = $row['username'];
      $db_password = $row['password'];
      $random_hash = password_hash(time() . $db_username . time(), PASSWORD_BCRYPT, $options);

      /* Password matches. */
      if (password_verify($password, $db_password)) {

        /* Get user's cookie information in database. */
        $stmt2 = $cxn->prepare("SELECT * FROM cookies WHERE username = ?");
        $stmt2->bind_param('s', $db_username);
        $stmt2->execute();
        $result2 = $stmt2->get_result();

        /* If a result exists, update the cookie. */
        if ($result2->num_rows > 0) {
          $stmt = $cxn->prepare("UPDATE cookies SET hash = ? WHERE username = ?");
          $stmt->bind_param('ss', $random_hash, $db_username);
          $stmt->execute();

          setcookie("user", $db_username, $expire, "/");
          setcookie("hash", $random_hash, $expire, "/");
        } else {
          $stmt = $cxn->prepare("INSERT INTO cookies (cookie_id, username, hash) VALUES ('', ?, ?)");
          $stmt->bind_param('ss', $db_username, $random_hash);
          $stmt->execute();

          setcookie("user", $db_username, $expire, "/");
          setcookie("hash", $random_hash, $expire, "/");
        }

        echo true;
      } else {
        echo "Incorrect credentials.";
      }
    }
  } else {
    echo "Incorrect credentials.";
  }

  function get_ip_address() {
    $ip_address = '';
    if (getenv('HTTP_CLIENT_IP'))
      $ip_address = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
      $ip_address = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
      $ip_address = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
      $ip_address = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
      $ip_address = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
      $ip_address = getenv('REMOTE_ADDR');
    else
      $ip_address = 'UNKNOWN';

    return $ip_address;
  }

?>

How can I optimize my script to look better, be faster, etc?


texts: Generic implementation of SiftUp/Down operations on binary heap

texts:
Binary heap construction and maintenance boil down to the two basic operations: sift up and sift down. Following are generic template implementations of the two operations. Any comments are welcome. I'm preparing for an interview, and I hope my code will appeal to the interviewer :-)

/// Compile with `-std=c++14`.
#include <cassert>
#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
#include <iterator>
#include <utility>

template <class RandIt, class Less = std::less<void>>
void SiftDown(RandIt first, RandIt last, Less&& less = Less{}) {
  auto n = static_cast<unsigned>(last - first);
  if (n < 2) return;
  auto child = 1u;
  if (2 < n && less(first[1], first[2])) ++child;
  if (less(first[0], first[child])) {
    typename std::iterator_traits<RandIt>::value_type val =
      std::move(first[0]);
    first[0] = std::move(first[child]);
    while (true) {
      first += child;
      n = static_cast<unsigned>(last - first);
      if (n < 2) break;
      child = 1u;
      if (2 < n && less(first[1], first[2])) ++child;
      if (! less(val, first[child])) break;
      first[0] = std::move(first[child]);
    }
    first[0] = std::move(val);
  }
}

template <class RandIt, class Less = std::less<void>>
void SiftUp(RandIt first, RandIt last, Less&& less = Less{}) {
  auto n = static_cast<unsigned>(last - first);
  if (n < 2) return;
  auto parent = n / 2 - 1;
  if (less(first[parent], last[-1])) {
    typename std::iterator_traits<RandIt>::value_type val =
      std::move(last[-1]);
    last[-1] = std::move(first[parent]);
    while (true) {
      last = first + parent + 1;
      n = static_cast<unsigned>(last - first);
      if (n < 2) break;
      parent = n / 2 - 1;
      if (! less(first[parent], val)) break;
      last[-1] = std::move(first[parent]);
    }
    last[-1] = std::move(val);
  }
}

int main() {
  int arr[5] = {2, 1, 5, 4, 3};
  auto it = arr;
  while (true) {
    SiftUp(arr, it);
    if (it == arr + 5) break;
    ++it;
  }
  for (auto i = 0; i < 5; ++i) {
    std::cout << *arr << ' ';
    std::iter_swap(arr, --it);
    SiftDown(arr, it);
  }
}


texts:
I'm currently studying data structures, I have implemented simple single linked list as shown below.

I would like to know how can I improve it?

#include <iostream>
#include <memory>
#include <cassert>

template <typename T>
class List
{
    struct node
    {
        T value;
        std::unique_ptr<node> next;
    };

public:
    List();

    void add(T value);

    T first() const;
    T value(std::size_t position) const;

    std::size_t length() const;
    void clear();

private:
    std::unique_ptr<node>   mFirst;
    std::size_t             mLength;
};

template <class T>
List<T>::List()
    : mFirst(nullptr)
    , mLength()
{
}

template <typename T>
std::size_t List<T>::length() const
{
    return mLength;
}

template <typename T>
T List<T>::first() const
{
    assert(mFirst != nullptr);
    return mFirst->value;
}

template <typename T>
void List<T>::add(T value)
{
    auto next = std::move(mFirst);
    mFirst = std::make_unique<node>();
    mFirst->value = value;
    mFirst->next = std::move(next);
    mLength++;
}

template <class T>
T List<T>::value(std::size_t position) const
{
    assert(mFirst != nullptr);

    auto current = mFirst.get();

    for (auto i = 0u; i < position; ++i)
    {
        current = current->next.get();
    }
    return current->value;
}

template <class T>
void List<T>::clear()
{
    assert(mFirst != nullptr);

    auto length = mLength;

    for (auto i = 0u; i < length; ++i)
    {
        mFirst = std::move(mFirst->next);
        mLength--;
    }
}

int main()
{
    List<int> list;

    for (int i = 0; i < 10; ++i)
        list.add(i);

    for (auto i = 0u; i < list.length(); ++i)
        std::cout << list.value(i) << ' ';

    list.clear();

    std::cout << "\n\n" << list.length() << "\n\n";
}


texts: Commit the working directory to different branch and switch back

texts:
The aim of this script is to snapshot the current working directory of a git repository to another branch. Afterwards, it switches back to the original branch and restores the original state, including the working directory and staged changes.

#!/bin/sh

function git_snapshot() {
  # Usage: SNAPSHOT=$(git_snapshot <backup_branch> "<commit message>")
  set -e

  # Save the current state.
  BEFORE=$(git rev-parse --abbrev-ref HEAD)
  if [[ "$BEFORE" == 'HEAD' ]]; then
    BEFORE=$(git rev-parse HEAD)
  fi
  (>&2 echo "Starting at $BEFORE.")
  git stash push --include-untracked
  (>&2 echo "Stashed changes ($(git rev-parse stash@{0})).")

  # Commit files to other branch.
  git checkout "$1"
  git read-tree -um $BEFORE
  git commit -m "$2"
  (>&2 echo "Saved last commit ($(git rev-parse HEAD)).")
  git stash apply --index stash@{0}
  git add -A
  git commit --amend --no-edit
  (>&2 echo "Amended uncommitted changes ($(git rev-parse HEAD)).")
  SNAPSHOT=$(git rev-parse HEAD)

  # Switch back and restore state.
  git checkout $BEFORE
  git stash apply --index stash@{0}
  (>&2 echo "Restored changes.")

  echo $SNAPSHOT
}


texts:
This code is a Frankenstein. I found ten examples done in ten different ways and my requirements were slightly different so even if they were reliable they weren't a copy and paste solution.

Encrypt takes in a byte[] and password and returns the byte[] encrypted with the password. It has to tack on the length of the original byte[] and the initialization vector used by the encryption algorithm.

Decrypt knows how to read the encrypted byte[] and will return the original message.

Note: One thing about naming conventions - Since a lot of this is copy and paste from different sources I tended to keep the original authors' conventions so that the code would match up. That's why some variables start with caps and some don't. Not looking to have this post turn into a tangent about that low hanging fruit though. But since it's obvious I thought I should point it out.

Encrypt

// https://social.msdn.microsoft.com/Forums/vstudio/en-US/eab7d698-2340-4ba0-a91c-da6fae06963c/aes-encryption-encrypting-byte-array?forum=csharpgeneral
// https://crypto.stackexchange.com/questions/2280/why-is-the-iv-passed-in-the-clear-when-it-can-be-easily-encrypted
public static byte[] Encrypt(byte[] bytesToEncrypt, string password)
{
    byte[] ivSeed = Guid.NewGuid().ToByteArray();

    var rfc = new Rfc2898DeriveBytes(password, ivSeed);
    byte[] Key = rfc.GetBytes(16);
    byte[] IV = rfc.GetBytes(16);

    byte[] encrypted;
    using (MemoryStream mstream = new MemoryStream())
    {
        using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
        {
            using (CryptoStream cryptoStream = new CryptoStream(mstream, aesProvider.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
            {
                cryptoStream.Write(bytesToEncrypt, 0, bytesToEncrypt.Length);
            }
        }
        encrypted = mstream.ToArray();
    }

    var messageLengthAs32Bits = Convert.ToInt32(bytesToEncrypt.Length);
    var messageLength = BitConverter.GetBytes(messageLengthAs32Bits);

    encrypted = encrypted.Prepend(ivSeed);
    encrypted = encrypted.Prepend(messageLength);

    return encrypted;
}

Decrypt

public static byte[] Decrypt(byte[] bytesToDecrypt, string password)
{
    (byte[] messageLengthAs32Bits, byte[] bytesWithIv) = bytesToDecrypt.Shift(4); // get the message length
    (byte[] ivSeed, byte[] encrypted) = bytesWithIv.Shift(16);                    // get the initialization vector

    var length = BitConverter.ToInt32(messageLengthAs32Bits, 0);

    var rfc = new Rfc2898DeriveBytes(password, ivSeed);
    byte[] Key = rfc.GetBytes(16);
    byte[] IV = rfc.GetBytes(16);

    byte[] decrypted;
    using (MemoryStream mStream = new MemoryStream(encrypted))
    {
        using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
        {
            aesProvider.Padding = PaddingMode.None;
            using (CryptoStream cryptoStream = new CryptoStream(mStream,aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
            {
                cryptoStream.Read(encrypted, 0, length);
            }
        }
        decrypted = mStream.ToArray().Take(length).ToArray();
    }
    return decrypted;
}

Relevant Extension Methods (i'm more worried about security than these)

    public static byte[] Prepend(this byte[] bytes, byte[] bytesToPrepend)
    {
        var tmp = new byte[bytes.Length + bytesToPrepend.Length];
        bytesToPrepend.CopyTo(tmp, 0);
        bytes.CopyTo(tmp, bytesToPrepend.Length);
        return tmp;
    }

    public static (byte[] left, byte[] right) Shift(this byte[] bytes, int size)
    {
        var left = new byte[size];
        var right = new byte[bytes.Length - size];

        Array.Copy(bytes, 0, left, 0, left.Length);
        Array.Copy(bytes, left.Length, right, 0, right.Length);

        return (left, right);
    }


texts:
I was wondering if this implementation of bubble sort could be improved. Are there any things that I have done wrong?

template<typename Element>
void bubble_sort(Element arr[], size_t size) {
    auto sorted_elements = 1u;
    bool sorted = false;
    while (!sorted) {
        sorted = true;
        for (auto index = 0u; index < size - sorted_elements; ++index) {
            if (arr[index] > arr[index + 1]) {
                auto temp = arr[index + 1];
                arr[index + 1] = arr[index];
                arr[index] = temp;
                sorted = false;
            }
        }
        ++sorted_elements;
    }
}


texts: Putting array name in variable and shortening code

texts:
I'm a beginner in C# and am doing a simple programming exercise. I would like to put the Item.price and Item.Name into Listbox2.

Is it possible to put the array name into a variable and iterate with a foreach loop?  This is to avoid a very long if, switch, or while loop.  It could also be useful in the future if I have 40 lists.

Example

Array variable = Drinks;
foreach(Product item in variable)
{
    listBox2.Items.Add(item.ProductName + item.Price);
}

PS: I've already tried using a temporary List, where I put the Drinks into the list and call it by Product.Name and/or Product.price.

Could it also be more efficient? I'm very open to new ideas or approaches on how I should make my code shorter and more efficient.

    public partial class Form1 : Form
    {
        List<Product> Drinks = new List<Product>() { new Product("Coca Cola", 1.2F), new Product("Fanta", 2.0F), new Product("Sprite", 1.5F) };
        List<Product> Bread = new List<Product>() { new Product("Brown Bread", 1.2F), new Product("White Bread", 2.0F), new Product("Some otherBread", 1.5F) };
        public Form1()
        {
            InitializeComponent();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
// instead of 40 if loops or a while loop is it possible to change the List Name with a variable and use only 1 foreach loop as the example i showed above?
            if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0)
            {
                foreach (Product item in Drinks)
                {
                    listBox1.Items.Add(item.ProductName);
                }
            }
            else
            {

                foreach (Product item in Bread)
                {
                    listBox1.Items.Add(item.ProductName);
                }
            }
        }

        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // do something here
        }
    }

    public class Product
    {
        private string productName;
        private float price;

        public Product(string productName, float price)
        {
            this.ProductName = productName;
            this.Price = price;
        }

        public string ProductName
        {
            get { return productName; }
            set { productName = value; }
        }

        public float Price
        {
            get { return price; }
            set { price = value; }
        }

    }


texts:
I am learning scheme to get something new from a programming language and this code below is the solution to Project Euler question 21 but the code runs 10x slower than the listed Python code when I use Chibi-Scheme. Can any Scheme craftsman refactor the code into the Scheme idiom for efficiency.

Scheme Code:

(define (sum-of-amicable-pairs n)
  (let ((sums (make-vector n)))
        (for-each
          (lambda (i)
            (vector-set! sums i
                         (reduce + 0
                                 (filter (lambda (j) (= (remainder i j) 0))
                                         (iota (+ 1 (quotient i 2)) 1 1)))))
            (iota n 0 1))

        (let loop ((res (make-vector n 0))
                   (i 0))
          (cond
            ((= i n) (reduce + 0 (vector->list res)))
            ((and (< (vector-ref sums i) n) (not (= (vector-ref sums i) i))
                  (= (vector-ref sums (vector-ref sums i)) i))
             (begin
               (vector-set! res i i)
               (vector-set! res (vector-ref sums i) (vector-ref sums i))
               (loop res (+ 1 i))))
            (else
              (loop res (+ i 1)))))))

(display (sum-of-amicable-pairs 10000))
(newline)

Python code:

def amicable_pairs(n):
    """returns sum of all amicable pairs under n. See project euler for
    definition of an amicable pair"""
    div_sum = [None]*n
    amicable_pairs_set = set()
    for i in range(n):
        div_sum[i] = sum([j for j in range(1, i/2 + 1) if i%j == 0])
    for j in range(n):
        if div_sum[j] < n and div_sum[div_sum[j]] == j and div_sum[j] != j:
            amicable_pairs_set.add(j)
            amicable_pairs_set.add(div_sum[j])
    #print sum(amicable_pairs_set)
    return sum(list(amicable_pairs_set))


texts: Display Tournament League from total Players

texts:
I've created function that will display a league competition from the total team numbers.

For example if we have 4 teams it will display (a vs b) vs (c vs d)
and if we have 5 teams it will diplay ((a vs b) vs c) vs (d vs e) and so on. It will display the competition looks square or equal.

here is the complete code :

public class EqualPlayer {
    private int index=0;

    public static void main(String[] args){
        EqualPlayer equalPlayer = new EqualPlayer();
        System.out.println(equalPlayer.getEqualPlayerID(26));
    }

    private String getEqualPlayerID(int numberPlayers){
        int nPDevided = numberPlayers/2;
        int A = numberPlayers-nPDevided;
        int B = nPDevided;
        String result="";

        if(A>2 || B > 2)
            return "( "+getEqualPlayerID(A)+" )"+" vs "+ "( "+getEqualPlayerID(B)+" )";

        if(A==2)
            if(result.isEmpty()){
                result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
                index+=2;
            }
            else{
                result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
                index+=2;
            }
        else if(A==1)
            if(result.isEmpty()){
                result = ""+getPlayerId(index);
                index+=1;
            }
            else{
                result = result+" vs "+ getPlayerId(index);
                index+=1;
            }

        if(B==2)
            if(result.isEmpty()){
                result = "( "+ getPlayerId(index) +" vs " +getPlayerId(index+1) +" )";
                index+=2;
            }
            else{
                result =  result+" vs ( "+getPlayerId(index)+" vs "+ getPlayerId(index+1) +" )";
                index+=2;
            }
        else if(B ==1)
            if(result.isEmpty()){
                result = ""+getPlayerId(index);
                index+=1;
            }
            else{
                result = result+" vs "+ getPlayerId(index);
                index+=1;
            }

        return result;

    }

    private char getPlayerId(int index){
        char [] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
        return  alphabet[index];
    }

}

Any better idea how to create this function without recursive?

And also the limits of the player is 26 which is the total alphabets, if I want to increase the total player I need to add additional char to getPlayerId method, I would like to know about what are you guys think about that?
Improvement, suggestion, are welcome.


texts: Apache POI and cyclomatic complexity of code

texts:
I have an Excel file, which I am reading using Apache POI APIs; which gives me control over cells/columns in my Excel.

I have around 17 columns in my Excel and these are with different datatypes. I want to populate a model object from these column values. So, I came up with something like below to populate my model object:

private WHTApps populateModel(WHTApps whtApp, int columnIndex, Object cellValue) {
        switch (columnIndex) {
        case 0:
            whtApp.setVendorCode((int) cellValue);
            break;
        case 1:
            whtApp.setVendorName((String) cellValue);
            break;
        case 2:
            whtApp.setCountry((String) cellValue);
            break;
        case 3:
            whtApp.setApplicationReceivedFromUSDate((Date) cellValue);
            break;
        case 4:
            whtApp.setContractNumber((String) cellValue);
            break;
        case 5:
            whtApp.setContractEffectiveDate((Date) cellValue);
            break;
        case 6:
            whtApp.setContractExpirationDate((Date) cellValue);
            break;
        case 7:
            whtApp.setAutomaticRenewal((String) cellValue);
            break;
        case 8:
            whtApp.setReducedRate((int) cellValue);
            break;
        case 9:
            whtApp.setForm17((String) cellValue);
            break;
        case 10:
            whtApp.setResidencyCertIssueDate((Date) cellValue);
            break;
        case 11:
            whtApp.setTaxAuthoritySubmissionDate((Date) cellValue);
            break;
        case 12:
            whtApp.setTaxAuthorityAcceptanceDate((Date) cellValue);
            break;
        case 13:
            whtApp.setStatus((String) cellValue);
            break;
        case 14:
            whtApp.setForm17Expiration((Date) cellValue);
            break;
        case 15:
            whtApp.setComments((String) cellValue);
            break;
        case 16:
            whtApp.setRemarks((String) cellValue);
            break;
        case 17:
            whtApp.setCategory((String) cellValue);
            break;
        default:
        }

        return whtApp;
    }

But, this gives rise to a really high cyclomatic complexity value of 19.

Now how do I reduce the cyclomatic complexity as I have 17 columns which I need to populate in my model object?


texts: Review of a C++ missing characters snippet

texts:
I recently had to write a function to return characters missing from an input string.  Here is the snippet

#include <bitset>
#include <string>

template<class Iterator>
std::string getMissingLetters(Iterator begin, Iterator end) {

    std::bitset<26> letters;

    for (auto it = begin; it != end; ++it) {
        size_t c = tolower(*it) - char('a'); // normalized to start at 'a'
        if (c > 26) continue;
        letters.set(c);
        if (letters.to_ulong() == ((1 << 26) - 1)) break;  // all 26 bits set
    }

    std::string missing;
    for (int i = 0; i < letters.size(); ++i) {
        if (!letters[i]) missing.push_back(char('a' + i));
    }
    return missing;
}

I thought of couple things to improve, for example avoiding branch by clamping characters, eg.

letters.set(std::min(c, 26));

and perhaps blocking the loop s.t. the line

if (letters.to_ulong() == ((1 << 26) - 1)) break;

is executed every N iterations rather than each iteration.

What do you think one could have done better?


texts:
So, we have this "Rubberduck Settings" window, with a number of "tabs" dedicated to each configurable feature. The "root" tab contains the application's "general settings" and, in the next release, we've found something to put there:

The display language! Credits to @SimonAndréForsberg and @Vogel612, for the Swedish and German translations respectively.. I did the French translation myself.

The first thing I tried after Simon's pull request was merged, was of course trying to switch the display language to Swedish... and that blew up with a CultureNotFoundException.

I had to handle the case when a culture wasn't supported/installed on the user's system, so this is how I went about the DisplayLanguageSetting class, which gets serialized into the application's xml configuration file:

namespace Rubberduck.Settings
{
    [XmlType(AnonymousType = true)]
    public class DisplayLanguageSetting
    {
        [XmlAttribute]
        public string Code { get; set; }

        public DisplayLanguageSetting()
        {
            // serialization constructor
        }

        public DisplayLanguageSetting(string code)
        {
            Code = code;

            CultureInfo culture;
            try
            {
                culture = CultureInfo.GetCultureInfo(code);
                _exists = true;
            }
            catch (CultureNotFoundException)
            {
                culture = RubberduckUI.Culture;
                _exists = false;
            }

            _name = RubberduckUI.ResourceManager.GetString("Language_" + Code.Substring(0, 2).ToUpper(), culture);
        }

        private readonly string _name;
        private readonly bool _exists;

        [XmlIgnore]
        public string Name { get { return _name; } }

        [XmlIgnore]
        public bool Exists { get { return _exists; } }

        public override bool Equals(object obj)
        {
            var other = (DisplayLanguageSetting) obj;
            return Code.Equals(other.Code);
        }

        public override int GetHashCode()
        {
            return Code.GetHashCode();
        }
    }
}

So the "general settings" tab is only loading the instances where the Exists getter is returning true. I'm particularly not fond of what I did in the LoadLanguageList method... would there be a better way?

namespace Rubberduck.UI.Settings
{
    public partial class GeneralSettingsControl : UserControl
    {
        private readonly IGeneralConfigService _configService;
        private readonly DisplayLanguageSetting _currentLanguage;

        public GeneralSettingsControl()
        {
            InitializeComponent();
            TitleLabel.Text = RubberduckUI.SettingsCaption_GeneralSettings;
            LanguageLabel.Text = RubberduckUI.Settings_LanguageLabel;

            LoadLanguageList();
        }

        public GeneralSettingsControl(DisplayLanguageSetting displayLanguage, IGeneralConfigService configService)
            : this()
        {
            _configService = configService;
            _currentLanguage = displayLanguage;
            LanguageList.SelectedItem = displayLanguage;
        }

        public DisplayLanguageSetting SelectedLanguage
        {
            get { return (DisplayLanguageSetting)LanguageList.SelectedItem; }
        }

        private void LoadLanguageList()
        {
            var settings = new[]
            {
                new DisplayLanguageSetting("en-US"),
                new DisplayLanguageSetting("fr-CA"),
                new DisplayLanguageSetting("sv-SV")
            };

            LanguageList.Items.AddRange(settings.Where(item => item.Exists).ToArray());
            LanguageList.DisplayMember = "Name";
        }
    }
}


texts:
I'm drawing shapes to OpenGL using the standard commands and function calls to OpenGL. Everything works fine, however since this is a learning process I know sometimes what works in theory and using simple basic examples doesnt always work in real time situations so I wanted to ask if this is correct what I am doing here with my drawing commands.

Everything works fine, and draws correctly as expected but I am just curious is it correct way to do things and could i result in problems when drawing far more objects in a real world rendering scene.

Here is the drawing part of the code:

//raw data
   GLfloat vec[] = {0.0f, 0.0f,
                            1.0f, -1.0f,
                           -1.0f, -1.0f};

   GLfloat vec2[] = {0.0f, 1.0f,
                            1.0f, 0.0f,
                           -1.0f, 0.0f};

   //next step is to upload data to graphics memory

   //generating a buffer from openGL
   GLuint vbo;
   GLuint vao;

   glGenBuffers(1, &vbo);

   glGenVertexArrays(1, &vao);

   //to upload the actual data must make the object active by binding it to a target
   glBindBuffer(GL_ARRAY_BUFFER, vbo);
   //upload the data of active object to memory
   glBufferData(GL_ARRAY_BUFFER, sizeof(vec), vec, GL_STATIC_DRAW);

   //first triangle bind and enable
   glBindVertexArray(vao);

   glEnableVertexAttribArray(0);
   glVertexAttribPointer(0,2,GL_FLOAT, GL_FALSE, 0, NULL);

   glDrawArrays (GL_TRIANGLES, 0, 3);
   glXSwapBuffers ( dpy, glxWin );

   sleep(1);

   glClear(GL_COLOR_BUFFER_BIT);

   glBufferData(GL_ARRAY_BUFFER, sizeof(vec2), vec2, GL_STATIC_DRAW);

   glDrawArrays (GL_TRIANGLES, 0, 3);
   glXSwapBuffers ( dpy, glxWin );

   sleep(1);

So as you can see what i am doing , since the triangles are the same dimensions just different vector positions, i am simply just uploading/transferring the data to the server memory of one object instead of creating whole other object with exactly the same set-up as the first object but different position vectors and i would like to know is this safe to do and practical?