texts:
I have server-client communication architecture where there is one server and 150 clients.

The server-client communication happens via Java NIO where all the clients send some or the other data every 10 seconds.
Previously we used to queue all the process messages and process all those in a single thread, as the number of clients are more so as the messages, server is not able to process all the messages instantly and there is a delay in processing in turn data loss.
So I have thought of implementing CachecThreadPool to process the tasks simultaneously as soon as they come, picked CachedThreadPool over FixedThreadPool because the tasks are short lived and many in number, below is the code for that.
The thread which receives messages from client calls ProcessorClass.processData(message) as soon as it receives the message.

public class ProcessorClass{

    private static final Logger LOGGER = Logger.getLogger(ProcessorClass.class);
    static ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    public static void processData(StringBuffer message) {
        Runnable task = new Runnable() {
            @Override
            public void run() {
                try {
                    LOGGER.info("Queue size:"+executor.getQueue().size());
                    if (message != null){
                        processMessage(message);
                    }
                }
                catch(Exception e) {
                    LOGGER.error("Error happened in run() method" + e.getMessage());
                }

            }
        };
        executor.execute(task);
    }
    public static void processMessage(StringBuffer message){
        // all the processing of message such as DB operations goes here.
    }
}

Doubts:

How CachedThreadPool stores the message in the queue because i haven't defined any explicitly.
Should i chose FixedThreadPool over this?
Should i make my processMessage() method synchronized?

All the suggestions and review comments are welcome.


texts:
Challenge:

  Return the length of the longest word in the provided sentence.

I've made a solution that works but it is kinda bad since the time complexity is \$O(n \log n)\$ and it involves mutation.

function findLongestWordLength(str) {
  let strSplit = str.split(" ");
  let wordLengthArray = [];
  for(let i = 0; i < strSplit.length; i++)
  {
    wordLengthArray.push(strSplit[i].length);
  }
  wordLengthArray.sort(function(a , b){return a - b});
  return wordLengthArray[wordLengthArray.length - 1];
}

I basically split the string, pushed all the word lengths in an empty array, then used the ascending sort function. After that I returned the last index of the new array which is the longest length.

Test Cases:

findLongestWordLength("The quick brown fox jumped over the lazy dog") should return 6.
findLongestWordLength("May the force be with you") should return 5.
findLongestWordLength("Google do a barrel roll") should return 6.
findLongestWordLength("What is the average airspeed velocity of an unladen swallow") should return 8.
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19.

I would appreciate some hints/tips on a better algorithm.


texts: Prompting the user for employment information

texts:
I have created a simple program in which the user is prompted for various details about their employment. In my Employee.java file, I have all the methods.

Employee.java:

import javax.swing.JOptionPane;

public class Employee {

    private static String name;
    private static String jobTitle;
    private static int age;
    private static int salary;
    private static int taxAmount;
    private static int salaryPostTax;

    public static int getSalary() {
        try {
            String inputSalary = JOptionPane.showInputDialog("Enter your salary:");
            salary = Integer.parseInt(inputSalary);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "ERROR! That's NOT a numeric value.");
        }
        return salary;
    }

    public static String getName() {
        name = JOptionPane.showInputDialog("Enter your name:");
        return name;
    }

    public static String getJobTitle() {
        jobTitle = JOptionPane.showInputDialog("Enter your Job Title:");
        return jobTitle;
    }

    public static int getAge() {
        try {
            String inputAge = JOptionPane.showInputDialog("Enter your age:");
            age = Integer.parseInt(inputAge);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "ERROR! That's NOT a numeric value.");
        }
        return age;
    }

    public static int calcTaxAmount () {

        if (salary < 10_000)
            taxAmount = 0;

        if ((salary >= 10_000) && (salary < 30_000))
            taxAmount = 28;

        if ((salary >= 30_000) && (salary < 80_000))
            taxAmount = 38;

        if (salary >= 80_000)
            taxAmount = 48;

        return taxAmount;
    }

    public static int calcSalary () {
        salaryPostTax = salary - taxAmount;

        return salaryPostTax;
    }

    public static void showPayment() {
        if (inputValid() == true) {

            JOptionPane.showMessageDialog(null, "Pay to the order of " + name + " (" + jobTitle +
                    ") the sum of £"+ salaryPostTax);
        } else {
            JOptionPane.showMessageDialog(null, "ERROR! Please fill in ALL the required fields correclty.");
        }
    }

    public static boolean inputValid() {
        if (
                (name != null) &&
                (jobTitle != null) &&
                (!(salary <= 0)) &&
                (!(salaryPostTax <= 0)) &&
                (!(age <= 0))) {
            return true;

        } else {
            return false;
        }
    }
}

I have a file (UseIt.java) in which I use the class. My question though, is: Is it a good programming practice to either:

1. Put all your methods into one method, and simply call that one method rather than calling them all individually, which becomes tiresome?

Employee.java: (Example 1)

//Collate ALL Employee details into ONE method
public static void getAllDetails() {
    Employee.getName();
    Employee.getAge();
    Employee.getJobTitle();
    Employee.getSalary();
    Employee.calcTaxAmount();
    Employee.calcSalary();
    Employee.showPayment();
}

UseIt.java: (Example 1)

public class UseIt {

    static Employee foo = new Employee();

    public static void main(String[] args) {
        foo.getAllDetails(); //Calling ONE method, rather than all of them.
    }
}

2. Put all the methods into the constructor, so that the methods run automatically upon the creation of the instance?

Employee.java (Example 2)

//Collate ALL Employee details into the constructor
public Employee() {
    Employee.getName();
    Employee.getAge();
    Employee.getJobTitle();
    Employee.getSalary();
    Employee.calcTaxAmount();
    Employee.calcSalary();
    Employee.showPayment();
}

UseIt.java (Example 2)

public class UseIt {

    public static void main(String[] args) {
        Employee foo = new Employee();
    }
}


texts:
I'm new to F# and functional programming in general (coming from an object oriented background). I just wanted to get some criticism on an algorithm for assigning jobs to crew members. I want to be as functional as possible and avoid loops and mutable state. Here is what I've come up with.

let rec AssignJobs crewMembers jobs jobAssignments =
    let AssignJob job crewMembers =
        let bestCrewMember = crewMembers |> Seq.sortWith crewMemberComparison
                                         |> Seq.head
        {CrewMember = bestCrewMember; Job = job}

    match jobs with
    | job :: remainingJobs ->
        let jobAssignment = AssignJob job crewMembers
        let remainingCrewMembers = crewMembers |> Seq.filter ((<>)jobAssignment.CrewMember)
        AssignJobs remainingCrewMembers remainingJobs (jobAssignments @ [jobAssignment])
    | [] -> jobAssignments

Assume that crewMemberComparison is working for this review. I'm more concerned about whether I have a good approach to managing the crewMembers, jobs and jobAssignments sequences.

I don't like how I have to invoke this with an empty list i.e.

let assignedJobs = AssignJobs crewMembers jobs []

Is there another way? Is recursion the best solution at all (presuming I'm not allowed to loop)?

Thanks in advance!


texts:
I've made a function to print all paths from root to all leaves in a binary search tree. I already have an insert function, which I haven't included in the code here as I felt it was irrelevant to the question. However, assume that it works. The code provided does produce the correct results. However, is it optimal? Is there room for improvement? Also, am I correct in thinking that the time complexity of this function is \$O(n)\$?

public static void printPaths(Node node,ArrayList<Integer> path) {

    if(node == null) {

        return;
    }

    path.add(node.value);

    if(node.leftChild == null && node.rightChild == null) {

        System.out.println(path);
        return;

    } else {

        printPaths(node.leftChild,new ArrayList<Integer>(path));
        printPaths(node.rightChild,new ArrayList<Integer>(path));
    }
}

public static void main(String[] args) {

    BST tree = new BST();

    tree.insertNode(20);
    tree.insertNode(8);
    tree.insertNode(22);
    tree.insertNode(12);
    tree.insertNode(10);
    tree.insertNode(14);
    tree.insertNode(4);

    ArrayList<Integer> path = new ArrayList<Integer>();

    printPaths(tree.root, path);


texts: Reliably setting the system clipboard in a spawned thread and having the spawner wait

texts:
Checklist from FAQ for proper posting.

Does my question contain code?
   - YES
Did I write that code?
   - YES
Is it actual code from a project rather than pseudo-code or example code?
   - Strait from actual code, minus a few functions that do not apply to the Q
To the best of my knowledge, does the code work?
   - To the best of my knowledge it works most of the time, other times it
     fails to do what I ask of it but produces no runtime errors.
Do I want feedback about any or all facets of the code?
   - Just about how to reliably wait for the clipboard to be set and
     reliably set it while I am waiting.

I am trying to reliably set the system clipboard text in my program but keep coming back with confusing results. Those results being it sometimes setting the text and sometimes not setting it. Here is where I create a thread of type ClipSetThread and tell it to set the system clipboard and also set a global variable called waitForMe in the main Application.

public void setClip(String arg) // Starts a clip setting thread
{
    CLUtilCompact.waitForMe = true;
    ClipSetThread set = new ClipSetThread(theApp);
    set.arg = arg;
    set.start();
    while(CLUtilCompact.waitForMe){}
}

And here is the class ClipSetThread

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

public class ClipSetThread extends Thread
{
String arg = "";
Clipboard sysClip = null;
CLUtilCompact theApp = null;
public ClipSetThread(CLUtilCompact app)
{
    theApp = app;
    theApp.updateOutput("Set Clip ID:" + this.getId() + "|CREATED");
    sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
}
public void run()
{
    setClip2(arg);
    CLUtilCompact.waitForMe = false;
    return;
}
public void setClip2(String arg)
{
    while(true)
    {
        try
        {
            sysClip.setContents(new StringSelection(arg), null);
        }
        catch(Exception e)
        {
            try {Thread.sleep(20);} catch (InterruptedException e1) {}
            continue;
        }
        break;
    }
    return;
}
}

It seems that even with the while loop to wait for the waitForMe flag the setClip function will return and allow the application to try and continue what it is doing even though the clipboard is not set.

After the clipboard is set I almost always try to paste what is there; I usually call Thread.sleep(1000) between a call to setClip and my call to paste(). (Paste simply simulates ctrl+V with the java Robot class)


texts:
I am trying to make a scrolling game in Tkinter. However, with all my for loops and functions it is extremely slow.

I am reading the tutorial from Khan Academy's advanced JS. In their JS game everything is fine, so is it just a problem of python is slow or am I doing things inefficiently.

import tkinter as tk
import random
import time
win = tk.Tk()
win.title("Beaver Game")
win.wm_attributes("-topmost", 1)#Makes it stay on top of other windows
canvas = tk.Canvas(win, width=300, height=300, bg='#97FEFF', bd = 0, highlightthickness = 0)
canvas.pack()
canvas.create_rectangle(0, 270,300, 300, fill = "brown")
win.update()

class Beaver:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = self.canvas.create_rectangle(150,150, 100, 100, fill = color)
        self.y = 0
        self.canvas_height = self.canvas.winfo_height()
        self.canvas_width = self.canvas.winfo_width()
        self.canvas.bind_all('<KeyPress-Up>', self.turn_left)
        self.canvas.bind_all('<KeyPress-Down>', self.turn_right)
        self.sticks = 0
    def draw(self):
        self.canvas.move(self.id, 0, self.y)
        pos = self.canvas.coords(self.id)
        if pos[1] <= 0:
            self.y = 0
        if pos[3] >= self.canvas_height:
            self.y = 0
    def turn_left(self, evt):
        self.y = -3
    def turn_right(self,evt):
        self.y = 3
class Stick:
    def __init__(self, canvas, color, x, y):
        self.canvas = canvas
        self.color = color
        self.x = x
        self.y = y
    def draw(self):
        canvas.create_rectangle(self.x, self.y, 5, 40, fill = self.color)
beaver = Beaver(canvas, "pink")

grassXs = []
for i in range(25):
     grassXs.append(i * 25)

sticks = []
for i in range(40):
    sticks.append(Stick(canvas, "black", i * 4 + 100, random.randint(20, 26)))

while 1:
   for i in range(len(grassXs)):
      canvas.create_rectangle(grassXs[i], 250, 270, 270, fill = "green")
      grassXs[i] -= 1
      if (grassXs[i] <= -20):
         grassXs[i] = canvas.winfo_width()
   for i in range(len(sticks)):
       sticks[i].draw()
       sticks[i].x -= 1
   beaver.draw()
   win.update_idletasks()
   win.update()


texts:
Im am currently wrapping all OpenGL ressources (which are simply a GLuint) into classes that own and manage the deletion of them, to make it possible to use OpenGL in an object oriented fassion. Since these classes manage a ressource that get's destroyed in their destructor i know the rule of five is something to think about. This is how my Shader classes look like:

Shader.h :

#pragma once

#include <glad/glad.h>
#include <string>

class Shader
{
public:

    Shader(GLuint type, const std::string& shaderPath);
    virtual ~Shader();

    Shader(const Shader& s) = delete;
    Shader& operator = (const Shader& s) = delete;

    Shader(Shader&&) = default;
    Shader& operator = (Shader&&) = default;

private:

    /*
        The Shader objects are passed to the constructor
        of ShaderProgram that compiles the glShaderProgram -> needs id
    */
    friend class ShaderProgram; //

    GLuint id = 0;
};

class FragmentShader : public Shader
{
public:

    FragmentShader(const std::string& shaderPath) : Shader(GL_FRAGMENT_SHADER, shaderPath) {};
};

class VertexShader : public Shader
{
public:

    VertexShader(const std::string& shaderPath) : Shader(GL_VERTEX_SHADER, shaderPath) {};
};

Shader.cpp :

Shader::Shader(GLuint type, const std::string& shaderPath)
{
    std::ifstream fstram;
    std::stringstream sstream;

    fstram.exceptions (std::ifstream::failbit | std::ifstream::badbit);

    fstram.open(shaderPath);
    sstream << fstram.rdbuf();
    fstram.close();

    id = glCreateShader(type);

    auto data = sstream.str();
    const char* dataPtr = data.c_str();

    glShaderSource(id, 1, &dataPtr, NULL);
    glCompileShader(id);

    int result = 0;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);

    if(result == 0)
    {
        char infolog[1024];
        glGetShaderInfoLog(id, 1024, NULL, infolog);

        throw std::runtime_error(infolog);
    }
}

Shader::~Shader()
{
    glDeleteShader(id);
}

Use them like this:

try
{
    VertexShader vs("Path to file");
    FragmentShader fs("Path to file");
}
catch(const std::exception& e)
{
    std::cerr << e.what() << std::endl;
}

Because i am planning to implement classes for the ofther OpenGL ressources like buffers, textures, etc  in a similar fassion i would like some feedback. Any insight on mistakes that i made or how to improve my code are very appreciated. And do i need to declare move assignment and move constructor in the derived shader classes too?


texts:
I'm learning Python, and found a fun little video on YouTube called "Learn Python through public data hacking".  In essence it uses the CTA unofficial API to do some parsing of XML data.  In taking things further than inline code, I'm chunking behaviors into modules and classes to further understand how Python works.

The XML from the API looks something like this:

<buses rt="22">
<time>1:40 AM</time>
    <bus>
        <id>4194</id>
        <rt>22</rt>
        <d>East Bound</d>

Northbound

        <dn>E</dn>
        <lat>41.88327006970422</lat>
        <lon>-87.62828115689553</lon>
        <pid>5421</pid>
        <pd>Northbound</pd>
        <run>P238</run>
        <fs>Howard</fs>
        <op>49875</op>
        <dip>5314</dip>
        <bid>7323287</bid>
        <wid1>0P</wid1>
        <wid2>238</wid2>
    </bus>

</buses>

I'm using the python-requests module for the HTTP side, and once the XML is downloaded, I parse each <bus> node into a Bus class, assign each of the child nodes into a dictionary, and make that visible with a get(prop) statement, so I can just call bus.get('lat') to retrieve the latitude, etc.  However, in order to do the correct calculations on it (i.e. arithmetic) each node's value needs to be returned as the correct type.  By default, they're all read as strings.

Considering that Python doesn't have a "switch" statement like most other languages, someone at SO said to use a dictionary. Is this the/a correct way of doing something like this? Or is there some nifty builtin that I don't know of?

def dyncast(value):
    _type = type(value)
    types = {
        "FloatType": (r'^[\d]{2}\.[\d]+$', lambda f : float(f)),
        "IntType" : (r'^[\d]+$', lambda i : int(i)),
        "StrType" : (r'^[a-zA-z]+$', lambda s : str(s))
    }
    for typeval in types:
        pattern = types[typeval][0]
        fn = types[typeval][1]
        match = re.match(pattern, value)

        # if it matches a regex and has a group(), return the
        # lambda calculation (typecast)
        if match and match.group():
            return fn(value)

    # return straight up if no matches
    return value

# Called via:
for elm in node:
    self._data[elm.tag] = dyncast(elm.text)
# where node is the bus node, and elm are the child nodes

It seems to work well, as I get returns such as:

# print bus.get('fs'), type(bus.get('fs'))
Harrison <type 'str'>

# print bus.get('lat'), type(bus.get('lat'))
41.9027030677 <type 'float'>


texts: Is there a better way of showing multiple NSDictionaries?

texts:
I have a method that contains a bunch of NSDictionaries (in fact, the only reason I have that method is to create those NSDictionaries).  While I don't believe there are enough NSDictionaries initialized to visibly slow the code down as of yet, that is a good possibility in the future.  I am currently just creating all the NSDictionaries separately, but is there a better way to do it while keeping its readability?

- (void)items {

    NSDictionary *item1 = @{
    @"label"     : @"item1",
    @"icon"      : [UIImage imageNamed:@"item1-Icon"],
    @"identifier": @"item1"};

    NSDictionary *item2 = @{
    @"label"     : @"item2",
    @"icon"      : [UIImage imageNamed:@"item2-Icon"],
    @"identifier": @"item2"};

    NSDictionary *item3 = @{
    @"label"     : @"item3",
    @"icon"      : [UIImage imageNamed:@"item3-Icon"],
    @"identifier": @"item3"};

    NSDictionary *item4 = @{
    @"label"     : @"item4",
    @"icon"      : [UIImage imageNamed:@"item4-Icon"],
    @"identifier": @"item4"};

    items = [ @[item1, item2, item3, item4] mutableCopy];

}


texts: This is a Monoid instance I wrote for a Tree data type. Is this the most terse way to express mappend?

texts:
Here's my type:

data Tree a = Empty | Node a (Tree a) (Tree a)

Here's the instance declaration for Monoid:

instance (Monoid a) => Monoid (Tree a) where
    mempty = Empty
    mappend Empty Empty = Empty
    mappend Empty t = t
    mappend t Empty = t
    mappend (Node val ta tb) (Node val' ta' tb') = (Node (mappend val val') (mappend ta ta') (mappend tb tb'))

This compiles, but it was tedious to write and very repetitive. Is there a better way of doing this?


texts: Finding the length of the longest streak of ones in any array

texts:
I need help reviewing my code snippet copied below.
The below code counts the number of continuous ones in a given array of Size 11.

#define size 11
#define ONE 1
using namespace std;

#include <iostream>
#include "stdio.h"

    int arr[11] = {1, 0, 1, -1, 0, 0, 1, 1,0, 1, 1};
        int sequence_count = 0;
        int loop_count;
        bool continuity = true;
        for(loop_count = 0; loop_count<size; loop_count++)
        {
            if((arr[loop_count]&ONE) == ONE)
            {
                if(continuity)
                    sequence_count++;
                else
                {
                    continuity = true;
                    sequence_count++;
                }
            }
            else
            {
                continuity = false;
                sequence_count = 0;
            }
        }
        cout << sequence_count << endl;


texts:
My code works; I am just seeing if there's an optimized way to write these methods or even better perhaps combine them (since majority of their contents look similar).

public class IntegerUtils {

    public static int getMaxValue(int[] array) {
        int value = Integer.MIN_VALUE;

        if (array.length <= 0) {
            throw new IllegalArgumentException("Array is empty.");
        }

        for (int i = 0; i < array.length; i++) {
            if (array[i] > value) {
                value = array[i];
            }
        }
        return value;
    }

    public static int getMinValue(int[] array) {
        int value = Integer.MAX_VALUE;

        if (array.length <= 0) {
            throw new IllegalArgumentException("Array is empty.");
        }

        for (int i=0; i < array.length; i++) {
            if (array[i] < value) {
                value = array[i];
            }
        }
        return value;
    }
}

Here's my unit test (which works as well):

import org.junit.Test;

public class IntegerUtilsTest {

    int[] array = new int[] {1, 2, 3, 58, 47, 229, 40};

    @Test
    public void shouldBeMaxValue() {
        int maxValue = IntegerUtils.getMaxValue(array);
        assert(maxValue == 229);
    }

    @Test
    public void shouldBeMinValue() {
        int minValue = IntegerUtils.getMinValue(array);
        assert(minValue == 1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldBeIllegalArgumentException() {
        int[] emptyArray = new int[] {};
        int maxValue = IntegerUtils.getMaxValue(emptyArray);
        int minValue = IntegerUtils.getMinValue(emptyArray);
    }
}

Just seeking feedback regarding optimization and / or code elegance.


texts: Calculating min and max with if-statements within a for-loop

texts:
This code section is from the main method of my Annual Fuel Use class. The program projects my annual fuel usage based on at least three fill ups of my car.
Here, I am calculating the max and min for distance (which is miles traveled), MPG, and price per gallon.  I'd like a general review.

//initialization of array of objects
AnnualFuelUse[] fillUps = {new AnnualFuelUse (1, 1, 6500, 6800, 9.70, 3.11),
                          new AnnualFuelUse (2, 10, 6800, 7052, 8.10, 3.08),
                          new AnnualFuelUse (3, 20, 7052, 7349, 9.20, 3.15)};

//calculate Min and Max for distance, MPG, and price per gallon
double minDist = 0, maxDist = 0;
double minMPG = 0.0, maxMPG = 0.0, minPrice = 0.0, maxPrice = 0.0;

Double dMin = Double.MAX_VALUE;
Double dMax = Double.MIN_VALUE;
Double mpgMin = Double.MAX_VALUE;
Double mpgMax = Double.MIN_VALUE;
Double priceMin = Double.MAX_VALUE;
Double priceMax = Double.MIN_VALUE;

for (int i = 0; i < fillUps.length; i++) {
    if (fillUps[i].getDist() < dMin){
        dMin = fillUps[i].getDist();
        minDist = dMin;
    }
    if (fillUps[i].getDist() > dMax) {
        dMax = fillUps[i].getDist();
        maxDist = dMax;
    }
    if (fillUps[i].getMilesPerGallon() < mpgMin) {
        mpgMin = fillUps[i].getMilesPerGallon();
        minMPG = mpgMin;
    }
    if (fillUps[i].getMilesPerGallon() > mpgMax) {
        mpgMax = fillUps[i].getMilesPerGallon();
        maxMPG = mpgMax;
    }
    if (fillUps[i].getPrice() < priceMin) {
        priceMin = fillUps[i].getPrice();
        minPrice = priceMin;
    }
    if (fillUps[i].getPrice() > priceMax) {
        priceMax = fillUps[i].getPrice();
        maxPrice = priceMax;
    }
}


texts: Calculation of the Distance Matrix in the K-Means Algorithm in MATLAB

texts:
Purpose of the code :

To assign the corresponding label of the centroids to the points which are close to it. Below is a graphical (2D) example.

Variable X is a matrix, rows represent the points, columns collectively represent the coordinates
idx is the list of centroids assigned to every example

Inefficient MATLAB code to find and assign nearest Centroids
sd2=size(X,2);
t2=[];
for a=1:K
    t1=[];
    for b=1:sd2
        temp=(X(:,b)-centroids(a,b)).^2;
        t1=[t1 temp];
    end
    dmat=sum(t1,2);
    t2=[t2 dmat];
end
[~,idx]=min(t2,[],2);

supposedly faster MATLAB code which worked on a small dataset:
[~,idx]=min(sum(((repmat(X,1,1,K)-reshape(centroids,1,n,K)).^2),2),[],3);

My Question:

Is my second implementation correct? If yes, why doesn't it work on a 300 x 2 matrix X , in the sense that the final array idx produced is not correct. If no, where is the problem (because I tested it with a small sample code just to be sure that I am finding (x-x1)2+ (y-y1)2 correctly).
speculation:

MATLAB is erroneous because of a multidimensional matrix.


texts:
I am trying to get acquainted with C++11/14, so please tell me if the code below could be written in a more "modern" way. Or, of course, if it could be improved in any way.

The function buildInput reads the content of a file and builds a matrix with it.

std::vector<std::vector<int>> buildInput(std::string fileName) {
    auto rows = 0, cols = 0;
    auto objectsCount = 0;

    std::ifstream in(fileName);

    // Throw exceptions in case any i/o operation fails.
    in.exceptions(std::ifstream::failbit | std::ifstream::badbit);

    in >> rows >> cols >> objectsCount;
    std::vector<std::vector<int>> input(rows, std::vector<int>(cols, 0));

    for(int i = 0; i < objectsCount; ++i) {
        auto type = 0, row = 0, col = 0;
        in >> type >> row >> col;
        input[row][col] = type;
    }

    return input;
}

The function builds the input for a Sokoban game from a file. Basically, it builds a "map" (a matrix) with several types of objects placed on it.

The file has the following format:

rows_count columns_count objects_count
[object_type object_row_number object_column_number](objects_count times)

For example, for the following file content:

4 4 6
1 0 3
2 1 2
3 1 3
1 2 3
4 3 1
1 3 3

the code would build the matrix

0 0 0 1
0 0 2 3
0 0 0 1
0 4 0 1


texts: A semaphore implmentation with Peterson's N process algorithm

texts:
I need feedback on my code for following statement, am I on right path?

Problem statement:

Implement a semaphore class that has a private int and three public methods: init, wait and signal. The wait and signal methods should behave as expected from a semaphore and must use Peterson's N process algorithm in their implementation.
Write a program that creates 5 threads that concurrently update the value of a shared integer and use an object of semaphore class created in part a) to ensure the correctness of the concurrent updates.

Here is my working program:

#include <iostream>
#include <pthread.h>

using namespace std;

pthread_mutex_t mid;                   //muted id
int shared=0;                           //global shared variable
class semaphore {
   int counter;
public:
   semaphore(){
   }
   void init(){
       counter=1;                     //initialise counter 1 to get first thread access
   }
   void wait(){
       pthread_mutex_lock(&mid);         //lock the mutex here
       while(1){
           if(counter>0){             //check for counter value
               counter--;             //decrement counter
               break;                   //break the loop
           }

       }
       pthread_mutex_unlock(&mid);       //unlock mutex here
   }
   void signal(){
       pthread_mutex_lock(&mid);       //lock the mutex here
           counter++;                   //increment counter
           pthread_mutex_unlock(&mid);   //unlock mutex here
       }

};
semaphore sm;
void* fun(void* id)
{
   sm.wait();                           //call semaphore wait
   shared++;                           //increment shared variable
   cout<<"Inside thread "<<shared<<endl;
   sm.signal();                       //call signal to semaphore
}

int main() {

   pthread_t id[5];                   //thread ids for 5 threads
   sm.init();
   int i;
   for(i=0;i<5;i++)                   //create 5 threads
   pthread_create(&id[i],NULL,fun,NULL);
   for(i=0;i<5;i++)
   pthread_join(id[i],NULL);           //join 5 threads to complete their task
   cout<<"Outside thread "<<shared<<endl;//final value of shared variable
   return 0;
}


texts: Printing out prime numbers from an array given a max number

texts:
Is there a shorter or maybe a cleaner way of doing:

  Using your is_prime? method, write a new method, primes that takes a (non-negative, integer) number max and returns an array of all prime numbers less than max.

def is_prime?(max)
  i = 2
  while i < max
    is_divisible = ((max % i) == 0)
    if is_divisible
      # divisor found; stop and return false!
      return false
    end

    i += 1
  end

  # no divisors found
  true
end
def primes(max)
  primes_arr = []

  i = 2
  while i < max
    if is_prime?(i)
      # i is prime; add it to the array
      primes_arr << i
    end

    i += 1
  end

  # return primes_arr
  primes_arr
end


texts:
I made a little program to parse data from an API.
I do not have experience with Pandas. It is working but I would like to know how to do that better and more efficiently.

class Albion_data():
    def __init__(self,item):
        self.location = f'Bridgewatch,Thetford,FortSterling,Martlock,Bridgewatch,Lymhurst'
        self.item = item
    @property
    def get_data(self):
        url = f"https://www.albion-online-data.com/api/v1/stats/Prices/{self.item}?locations={self.location}"
        response = (requests.get(url).text)
        response_json = json.loads(response)
        if response_json != []:
            response_json = pd.DataFrame(response_json)[["item_id", "city", "sell_price_min"]]
            max = response_json.loc[response_json["sell_price_min"].idxmax()]
            min = response_json.loc[response_json["sell_price_min"].idxmin()]
            gain = max[2] - min[2]
            data = pd.DataFrame(
                [[max[0], max[1], min[1], min[2], max[2], gain]],
                columns=["ITEM", "CITY max ", "CITY min", "MIN_PRICE", "MAX PRICE", "GAIN"])

            return data

def get_data_frame():
    item_list = pd.read_csv('items.txt', sep=':', names=['nuber', 'item']['item']
    item_price = pd.DataFrame(columns=["ITEM", "CITY max ", "CITY min","MIN_PRICE", "MAX PRICE", "GAIN"])
    for item in item_list:
        item_price = item_price.append(Albion_data(item).get_data)
        item_price.to_csv('data.csv')
    return item_price
```


texts:
This is useful for web scraping and web crawling anything other than that idk. It seems to work as planned.

I'm curious as to how the community thinks about the way I break the code down into simple functions with descriptive names. My reasoning for writing so many trivial functions is that I think it makes the code read more like pseudo code. In my opinion it makes the code self documented and easier to read. It also adds a big reusability factor.

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

def is_string(data):
    return isinstance(data, str)

def is_bytes(data):
    return isinstance(data, bytes)

def encodeable(data):
    return is_string(data) or is_bytes(data)

def encode_decode(data, *args, **kw):
    kw.setdefault('errors', 'ignore')
    return data.encode(*args, **kw).decode(*args, **kw)

def encode(data, encoding='ascii', **kw):
    if not encodeable(data):
        error_msg = ('Invalid data type',
                         'to_ascii can only encode',
                         'bytes, strings, and raw-strings',
                         'not {}'.format(type(data)))
        raise ValueError(error_msg)

    if is_string(data):
        data = encode_decode(data, encoding, **kw)

    elif is_bytes(data):
        data = data.decode(encoding, **kw)

    return data

def test_encode():
    #invalid = to_ascii({})
    s = str('spam')
    r = r'eaggs'
    b = b'slurm'
    print('Before encoding')
    print(s, r, b)
    print(type(s), type(r), type(b), '\n')

    print('After encoding')
    s, r, b = encode(s), encode(r), encode(b)
    print(encode(s), encode(r), encode(b))
    print(type(s), type(r), type(b))

if __name__ == '__main__':
    test_encode()


texts: Creating a Generic Template Interface/Class and injecting into another object

texts:
I would like to create a generic template class for my document processor. Assuming the template has a source file path and a "content", here's what I came up with:

Template

public interface ITemplate<T>
{
    /// <summary>
    /// The filepath of the base document for the template.
    /// </summary>
    String BaseDocumentFilePath { get; }

    /// <summary>
    /// Retrieve the underlying template source.
    /// </summary>
    /// <returns>T</returns>
    T GetContent();
}
public class WordTemplate : ITemplate<XmlDocument>
{
    private string _baseDocumentFilePath;
    private XmlDocument _content;

    public WordTemplate(XmlDocument content, string baseDocumentFilepath)
    {
        _content = content;
        _baseDocumentFilePath = baseDocumentFilepath;
    }

    public string BaseDocumentFilePath { get { return _baseDocumentFilePath;}}

    public XmlDocument GetContent()
    {
        return _content;
    }
}

Ex Doc Generator

public interface IDocumentGenerator
{
    /// <summary>
    /// Generates a document from an instance of <see cref="ITemplate"/>.
    /// </summary>
    /// <param name="template">The template for the document.</param>
    /// <param name="outputDocumentFilepath">The full file path of the result output.</param>
    /// <returns>Returns filepath for generated document.</returns>
    void Generate<T>(ITemplate<T> template, string outputDocumentFilepath);
}

public class WordDocumentGenerator : IDocumentGenerator
{
    public void Generate<T>(ITemplate<T> template, string outputDocumentFilepath)
    {
        XmlDocument xmlDocumentBody = template.GetContent() as XmlDocument;

        // generate doc
    }
}

The template would be created elsewhere and injected into the document generator. My question is, is this a good design? I am casting the generic T into XmlDocument (which is what I need for that specific implementation) and I don't think that's the right way to use generics. I've always been a little lost when it comes to generics.


texts: Faster way to check if number has factor of different primes than given list of primes

texts:
im trying to get the factor prime number(s) for given number if its different than the primes that i have in a list.

The number have to:

dividable with any of the primes in the list
should not have any other factor as primes other than in the list

example:

my_primes = [2, 3, 5]

n = 14 should return [7]

14 has factors [1, 2, 7, 14], can be divided by prime 2 (which is in list and prime) but also have 7 as factor prime and it is not in my list so i want to return that. If number has even 1 prime like this its enough for me so i dont need to check till i find other primes.

The code i have come up with so far:

from rTime import timer

@timer
def solve(n):
    def is_prime(n):
        i = 2
        while i**2 <= n:
            if n % i == 0:
                return False
            i += 1
        return True

    primes = [2, 3, 5]
    listo = []

    if n % 2 != 0 and n % 3 != 0 and n % 5 != 0:
        return False

    for i in range(2, n):
        if n % i == 0 and is_prime(i) and i not in primes:
            listo.append(i)
        if listo:
            break

    return listo

result = solve(1926576016)
print(result)

so my problem is it takes 22.36 seconds to check if 1926576016 has any primes like that at the moment. Is there anything i can improve in my code to make it faster or whole different approach needed to do this task.

Should note that i have been learning python since 4-5 months so i might not be aware of any build-in tools that makes this faster and its my first question here sorry if i did something wrong !

(@timer is a function that i have write to check how long it takes to run a function)


texts: Count the number of discrete values in a slice

texts:
I'm using this right now to count the number of discrete values in a given []string. Is there a faster way to do this?

func CountDiscrete(x []string) int {
    discrete := 0

    for i,xi := range x {
        is_discrete := true
        for j,xj := range x {
            if i != j {
                if xi == xj {
                    is_discrete = false
                    break
                }
            }
        }

        if is_discrete {
            discrete = discrete + 1
        }
    }

    return discrete
}


texts: Remove Duplicates from Sorted List -- LeetCode Solution in C

texts:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
    struct ListNode* deleteDuplicates(struct ListNode* head) {
    }

I have the written the solution for it, but looking for more ideas and suggestions. This solution has passed all the 166 test cases from leetcode.

    /**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteDuplicates(struct ListNode* head) {
 struct ListNode * current = head, *nextNode, *temp;

 //No elements
 if(head == NULL)
 {
     return NULL;
 }

 //Single element linked list
 if(head->next == NULL)
 {
     return head;
 }

     //if the numbers are repeating from the beginning;;
     //then we need to move head;
     while(head !=NULL && head->next !=NULL && head->val == head->next->val){
     if( head->val == head->next->val)
     {
         nextNode = head->next;
         while(nextNode !=NULL  && head->val == nextNode->val){
            temp = nextNode;
        nextNode = nextNode->next;
            free(temp);
         }

         temp = head;
         head = nextNode;
         current = head;
         free(temp);
     }

     }
     //Again a check to see if the list is empty

         if(head == NULL)
         {
             return NULL;
         }

    while(current->next != NULL){

     nextNode = current->next;

        if(nextNode->next !=NULL  && nextNode->val == nextNode->next->val){

         while(nextNode->next !=NULL  && nextNode->val == nextNode->next->val){
            temp = nextNode->next;
        nextNode->next = temp->next;
         }
        current->next = nextNode->next;

        }else {
            current = nextNode;
        }

 }

return head;

}


texts:
I am creating a database to store house points for our school running events. I would like to be able to tally all the points for the houses and it is working fine, however, I think it may be a bit verbose at this point.

Is there a simpler/better way with maybe more efficient code?

Races are stored in a races table (competitorID, raceID, time).

Student data is stored in a competitor table (competitorID, names, house).

The code will query the DB and bring back unique races, and then assign a point value based on their position (calculated by their race time).

import sqlite3
conn = sqlite3.connect('house.db')
conn.row_factory = sqlite3.Row

# House Totals
blueTotal = 0
greenTotal = 0
redTotal = 0
yellowTotal = 0

# Assign points from 1st = 15 through to 10-Last being 1
def points():
    global pointvalue
    if count == 0:
        pointvalue = 15
        places()
    if count == 1:
        pointvalue = 12
        places()
    if count == 2:
        pointvalue = 10
        places()
    if count == 3:
        pointvalue = 8
        places()
    if count == 4:
        pointvalue = 7
        places()
    if count == 5:
        pointvalue = 6
        places()
    if count == 6:
        pointvalue = 5
        places()
    if count == 7:
        pointvalue = 4
        places()
    if count == 8:
        pointvalue = 3
        places()
    if count == 9:
        pointvalue = 2
        places()
    if count > 10:
        pointvalue = 1
        places()

#Add points to houses
def places():
    global blueTotal, greenTotal, redTotal, yellowTotal, pointvalue
    if competitors['house'] == "blueTotal":
        blueTotal += pointvalue
    if competitors['house'] == "redTotal":
        redTotal += pointvalue
    if competitors['house'] == "yellowTotal":
        yellowTotal += pointvalue
    if competitors['house'] == "greenTotal":
        greenTotal += pointvalue

for x in range(1,50):
    competitorDetails = conn.execute('SELECT firstname, surname, house '
                                     'FROM race, competitor '
                                     'WHERE competitor.competitorID = race.competitorID '
                                     'AND race.raceID = ' + str(x))
    count=0
    for competitors in competitorDetails:
        points()
        count += 1

print("blueTotal " + str(blueTotal))
print("greenTotal " + str(greenTotal))
print("redTotal " + str(redTotal))
print("yellowTotal " + str(yellowTotal))


texts:
I'm working on a piece of code for calculating all the possible combinations of numbers that sum to n. For example:

sum_combination(3) = [
  [1,1,1],
  [1,2],
  [3]
]

So my ruby code is this:

class Integer
  SUM_COMBINATION = {
    1 => [[1]],
    2 => [[1,1],[2]],
    3 => [[1,1,1],[1,2],[3]]
  }

  def sum_combination
    SUM_COMBINATION[self] ||= (
      (self-1).downto((self/2.0).ceil).map do |n|
        n.sum_combination.map { |c| (c+[self-n]).sort }
      end.flatten(1).uniq + [[self]]
    )
  end
end

The code works, but it's insanely slow for numbers above 50.


texts: How can I make this CSV Importer code better of any code smell?

texts:
I wrote this method a few years ago in a Ruby on Rails project, which I think I am not proud of. How can I make this code better to show in-depth professionalism in Ruby?
lib/merchant/web_csv_importer.rb
# frozen_string_literal: true

require 'open-uri'
require 'csv'

class WebCsvImporter
  attr_accessor :url

  def initialize(url)
    @url = url
  end

  def call
    data = URI.open(url).read.force_encoding('UTF-8')

    parse_csv(data)
  end

  private

  def parse_csv(data)
    counter = 0
    duplicate_counter = 0

    CSV.parse(data, headers: true, header_converters: :symbol) do |row|
      next unless row[:name].present? && row[:email].present? && row[:status].present?

      role = Role.find_or_create_by(name: 'admin')
      merchant = Merchant.new row.to_h
      merchant.roles << role
      merchant.save

      merchant.persisted? ? counter += 1 : duplicate_counter += 1
      p "Email duplicate record: #{merchant.email} - #{merchant.errors.full_messages.join(',')}" if merchant.errors.any?
    end

    p "Imported #{counter} merchant, #{duplicate_counter} duplicate rows ain't added in total" # dont forget to pluralize this statements
  end
end

lib/tasks/merchant/csv_importer.rake
require 'merchant/web_csv_importer'

namespace :merchant do
  desc "Imports data from a Web CSV into Merchant's table"
  task web_csv_importer: :environment do
    WebCsvImporter.new('http://expample.com/merchant.csv').call
  end
end


texts: Searching an element in a 2D sorted array

texts:
I had to write a code (as an exercise) that receives a 2D row wise and col wise sorted array and an element, and return true is the element exists in the array.

The first thing that came to mind when i heard "sorted" is binary search, but than i realized that the last element in each row isn't necessarily smaller than the first one in the next line.

So, i figured out that the best complexity will be O(n), and wrote the following code:

 public static boolean findN(int[][] a, int x) {
        if (a.length == 0 || a[0].length == 0 || x > a[a.length - 1][a[0].length - 1] || x < a[0][0]) {
            return false;
        }
        int LastRow = a.length - 1, Lastcol = a[0].length - 1, row = 0, col = 0;

        while (row <= LastRow) {
            if (a[row][col] == x) {
                return true;
            } else if (col < Lastcol) {
                col++;
            } else {
                col = 0;
                row++;
            }
        }
        return false;
    }

    array example:

arr = {{1,2,7,30},
      {2,4,18,50},
      {3,6,19,90},
      {4,7,20,91}}

After realizing that the best complexity will be O(n), I googled this problem  so I'm almost certain that I'm right (although some people are claiming that they can do it in O(log(n))), but am I really?
Any other thoughts and improvements are welcomed, thank you all in advance!


texts:
I am trying to see if there is a more efficient way of creating a hash of a file of unknown size (could be gb). My code below works fine but I am sure there is a more efficient way of achieving this.

    private static string GetHash(FileInfo fileInfo, HashAlgorithm algorithm)
    {
        byte[] Block = ArrayPool<byte>.Shared.Rent(8192);
        string hashString = string.Empty;
        try
        {
            using (algorithm)
            {
                using (FileStream stream = fileInfo.OpenRead())
                {
                    int length;
                    while ((length = stream.Read(Block, 0, Block.Length)) > 0)
                    {
                        algorithm.TransformBlock(Block, 0, length, null, 0);
                    }
                    algorithm.TransformFinalBlock(Block, 0, 0);
                    hashString = algorithm.Hash.ToHex();
                    algorithm.Dispose();
                    stream.Flush();
                }
            }
            fileInfo = null;
            return hashString;
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(Block);
        }
    }

    private static string ToHex(this byte[] bytes, bool upperCase = true)
    {
        StringBuilder result = new StringBuilder(bytes.Length * 2);

        foreach (var bit in bytes)
        {
            result.Append(bit.ToString(upperCase ? "X2" : "x2"));
        }
        bytes = null;
        return result.ToString();
    }

And the usage would be:

GetHash(fileInfo, SHA512.Create());


texts: WebApi action that updates entity using stored procedure

texts:
I have ASP.NET WebApi project. Some of controller has method SetAsMain(int id) that get information about people then use stored procedure update people. How can I improve it? Should I do check people.IsMain == true in stored procedure?

        public HttpResponseMessage SetAsMain(int id)
        {
            People people = repository.GetById(id);

            if (people == null)
            {
                return ErrorMsg(HttpStatusCode.NotFound, string.Format("No people with ID = {1}", id));
            }

            if (people.IsMain == true)
            {
                return ErrorMsg(HttpStatusCode.OK, string.Format("{0} is already set as main", people.Houses.ToString()));
            }

            try
            {
                var parameters = new Dictionary<string, string>();
                parameters.Add("PeopleID", id.ToString());

                repository.ExecProcedure("usp_PeopleSetMain", parameters);
                return Request.CreateResponse(HttpStatusCode.OK, repository.GetById(id)); // some problem here
            }
            catch (Exception ex)
            {
                return ErrorMsg(HttpStatusCode.InternalServerError, ex.Message);
            }
        }


texts:
My input consists of a list of lists (not necessary of the same length), like

[
     ['a', 'b', 'c', 'd', 'b'],
     ['a', 'd', 'e', 'b'],
     ['f', 'a', 'g', 'e', 'b', 'h']
]

and I would like to have a matrix / dictionary  that contains the co-occurences. The keys of the dictionary are the elements of the original matrix, while the values would be a counter. So in the previous example, the result would be

{
    'a' : Counter({'b': 4, 'c': 1, 'd': 2, 'e' : 2, 'f' : 1, 'g' : 1, 'h' : 1})
    ...
}

Here is my code:

import collections
def my_func(data):
    result = collections.defaultdict(collections.Counter)
    for l in data:
        for e in l:
            result[e].update([el for el in l if el is not e])
    return result
my_func(data)

This works, except the fact I am not sure it's the smartest way: when updating the Counter, I am relooping over the elements of l.

EDIT: I should probably clarify that the elements in the list are not necessary chars but Python objects. I have used single letters only for faster typing.


texts: String vs List to check if a country is part of a continent

texts:
I simply need to check if a country is part of a particular continent (only one). The continent has around 50 countries. The list is constant and must be initialized at the time of creation. Which one of the solutions below is a better approach from performance point of view?

Having all the counties in a single string and doing simple String.contains()

String countryList = "country1 country2";
boolean isPartOfContinent = countryList.contains("country1");

Creating a List and using contains method

List<String> countryList  = Arrays.asList("country1 ", "country2");
boolean isPartOfContinent = countryList.contains("country1");

I realise the use case is pretty trivial to hamper performance. I feel that List is an overkill for simple stuff like this, whereas my colleague thinks Strings are "meh!" and Java programmers should stick to Lists. What would you use if you had to do this?

The number of countries won't change and is constant so maintainability and performance over a range of countries shouldn't be considered.

To summarise my question: is the use of a comparatively complex data structure than String justifiable when the requirement is so trivial?


texts:
A question on Stack Overflow had me look up the article on bogosort on Wikipedia.

There they describe the bogosort algorithm and the bogobogosort algorithm. They say, about this last algorithm, that:

  bogobogosort was designed not to succeed before the heat death of the universe on any sizable list.

I wrote a program to compare these 2 algorithms and got somewhat conflicting results: bogosort performs worse than bogobogosort for arrays up to 12 elements.

I am more inclined to believe my code is wrong than Wikipedia. Of course it can be that 12 is not a sizable enough list and the difference starts being noticeable with larger arrays.

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void quit(const char *msg) __attribute__((noreturn));
void datainit(int *data, size_t n);
void acopy(int *dst, const int *src, size_t n);
unsigned long bogosort(int *data, size_t n);
unsigned long bogobogosort(int *data, size_t n);
double timedelta(const struct timespec *b, const struct timespec *a);
void shuffle(int *data, size_t n);
int sorted(int *data, size_t n);
int randto(int n);

int main(int argc, char **argv) {
    int data[20], data2[20];
    unsigned long n;
    unsigned long s[2];
    struct timespec t[3];
    char *err;

    if (argc != 2) quit("Specify number of elements.");
    errno = 0;
    n = strtoul(argv[1], &err, 10);
    if (errno || n < 2 || n > 20) quit("number between 2 and 20");

    srand((unsigned)time(0));
    datainit(data2, n);

    clock_gettime(CLOCK_MONOTONIC, t + 0);
    acopy(data, data2, n);
    s[0] = bogosort(data, n);
    clock_gettime(CLOCK_MONOTONIC, t + 1);
    acopy(data, data2, n);
    s[1] = bogobogosort(data, n);
    clock_gettime(CLOCK_MONOTONIC, t + 2);

    printf("    bogosort shuffled %12lu cards in %f seconds.\n", s[0], timedelta(t + 1, t + 0));
    printf("bogobogosort shuffled %12lu cards in %f seconds.\n", s[1], timedelta(t + 2, t + 1));

    return 0;
}

void quit(const char *msg) {
    if (msg) fprintf(stderr, "%s\n", msg);
    exit(EXIT_FAILURE);
}

void datainit(int *data, size_t n) {
    for (size_t i = 0; i < n; i++) data[i] = (int)i;
    shuffle(data, n);
}

void acopy(int *dst, const int *src, size_t n) {
    for (size_t i = 0; i < n; i++) dst[i] = src[i];
}

unsigned long bogosort(int *data, size_t n) {
    unsigned long c = 0;
    while (!sorted(data, n)) {
        c += n;
        shuffle(data, n);
    }
    return c;
}

unsigned long bogobogosort(int *data, size_t n) {
    unsigned long c = 0;
    for (size_t b = 2; b <= n; b++) {
        while (!sorted(data, b)) {
            c += b;
            shuffle(data, b);
            b = 2;
        }
    }
    return c;
}

double timedelta(const struct timespec *b, const struct timespec *a) {
    double aa = a->tv_sec + (a->tv_nsec / 1000000000.0);
    double bb = b->tv_sec + (b->tv_nsec / 1000000000.0);
    return bb - aa;
}

void shuffle(int *data, size_t n) {
    if (n == 1) return;
    int p = randto((int)n);
    int tmp = data[p];
    data[p] = data[n - 1];
    data[n - 1] = tmp;
    shuffle(data, n - 1);
}

int sorted(int *data, size_t n) {
    int r = 1;
    for (size_t i = 1; i < n; i++) {
        if (data[i - 1] > data[i]) {
            r = 0;
            break;
        }
    }
    return r;
}

int randto(int n) {
    int mx = (RAND_MAX / n) * n;
    int p;
    do p = rand(); while (p >= mx);
    return p % n;
}

And this is a possible result for an array with 10 elements

% ./a.out 10
    bogosort shuffled     13816640 cards in 0.400548 seconds.
bogobogosort shuffled      1102233 cards in 0.027740 seconds.

So, unexpectedly bogosort shuffled more cards than bogobogosort and took more time doing it.

Is my bogosort() wrongly implemented?
Is my bogobogosort() wrongly implemented?
Is my shuffle() wrongly implemented? (but it would influence both functions)
Is my randto() wrongly implemented? I believe there's no bias.


texts:
Follow-up posted -> Follow up to Pay Rate Calculator

This little bit of code is just some code that I wrote from a flowchart at the beginning of a programming and logic book that I have added some to. I tried to create it as an object.

I would like a review on what I am doing and if I am doing it right, and what I could do better.  I want you to look at this like I am a novice to intermediate Programmer.  I don't think that I learned as much as I should have while I was in school, and it probably shows.

Main Method

public static void Main (string[] args)
{
    var payCheck = new PayRateCalculator();
    Console.Write ("Please provide the Employees Last Name >>");
    payCheck.lastName = Console.ReadLine();
    Console.Write ("How many hours has employee {0} worked? >>", payCheck.lastName);
    payCheck.hours = Convert.ToInt32 (Console.ReadLine());
    Console.Write ("What is employee {0}'s hourly wage? >>", payCheck.lastName);
    payCheck.payrate = Convert.ToInt32 (Console.ReadLine ());
    Console.WriteLine ("{0}'s Gross pay is ${1}", payCheck.lastName, payCheck.grossPay);
    Console.WriteLine ("{0}'s Net pay is ${1}", payCheck.lastName, payCheck.netPay);
}

Class

class PayRateCalculator
{
    private float _payrate = 8.25f;
    private float _withholdingRate = 0.20F;

    public float hours { get; set; }
    public float grossPay {
        get {
            return hours * _payrate;
        }
    }
    public float netPay {
        get {
            return grossPay - (grossPay * _withholdingRate);
        }
    }
    public float payrate {
        get {
            return _payrate;
        }
        set {
            _payrate = value;
        }
    }
    public string lastName { get; set; }

    public PayRateCalculator (string lastName, float hours, float payRate)
    {
        this.hours = hours;
        this.payrate = payrate;
        this.lastName = lastName;
    }

    public PayRateCalculator ()
    {

    }
}

Just a simple console application. Help me to relearn coding the right way.


texts:
I modified Amit Agarwal's script which checks the uptime of one website so that it now checks several sites. The script runs every 5 minutes, however, I kept receiving mails that a site was down and then 5 mins later that it was up again.

I adapted my code to only log a change if it persisted for two checks, like this:

function siteUptimeCheck(url, row) {
    var response, error;
    var status = "status"+row.toString();         // status1, status2..
    if (!ScriptProperties.getProperty(status))
      ScriptProperties.setProperty(status, 200);
    try {                                         // try, catch, else
        var success = true;
        response = UrlFetchApp.fetch(url);
    } catch(error) {
        success = false;
        insertData(status, url, row, error, response.getResponseCode(), "Site down: ");
        return;
    } if(success) {
        insertData(status, url, row, "Up", response.getResponseCode(), "Site up: ");
    }
}

function insertData(status, url, row, error, code, msg) {
      if (ScriptProperties.getProperty(status) == code) {
          return;                                  // Return if there are no changes
      } else if (ScriptProperties.getProperty(status) == 1) {
          sheet.getRange(row,2).setValue(code);
          if (code != 200) {
            //create newdate log entry
            sheet.getRange(row,3).setValue(newdate +" "+ error);
          }
          ScriptProperties.setProperty(status, code);
          MailApp.sendEmail(email, msg, error);
     } else {
          ScriptProperties.setProperty(status, 1);  // Marker for "something changed"
  }
}

Are there better ways of solving this?


texts: More efficient way to loop through an object

texts:
There's a part in my page where you can add, edit or delete school details, and it wasn't supposed to save entries to the database until the user hits Enter, so I save all data in an object first.

My object looks like this:

schooldetails : {
  "1": {
    "school_ctr":"schoolctr_1",
    "school":"Fiat Lux Academe",
    "course":"",
    "qualification":"High School",
    "date_grad":"06/04/2008",
    "notes":"*graduated with honors",
    "deleted":0
  },
  "2": {
    "school_ctr":"schoolctr_2",
    "school":"College of St. Benilde",
    "course":"Computer Science",
    "qualification":"Bachelor / College",
    "date_grad":"06/05/2012",
    "notes":"",
    "deleted":0
  },
  "3":{
    "school_ctr":"schoolctr_3",
    "school":"Siliman University",
    "course":"Information Technology",
    "qualification":"Post Graduate / Master",
    "date_grad":"06/06/2014",
    "notes":"",
    "deleted":0
  }
}

I passed it through AJAX and I was able to save info through this code:

if(!empty($school_details_new)){
  foreach($school_details_new as $key => $value) {
    foreach($value as $school_data => $data_values) {
      if($school_data == "school")
        $s_name = mysql_real_escape_string($data_values);
      if($school_data == "course")
        $s_degree = mysql_real_escape_string($data_values);
      if($school_data == "qualification")
        $s_type = mysql_real_escape_string($data_values);
      if($school_data == "date_grad")
        $s_enddate = mysql_real_escape_string($data_values);
      if($school_data == "notes")
        $s_notes = mysql_real_escape_string($data_values);
    }
  $sql = "INSERT INTO `SchoolDetails` (`personID`, `School`, `Type`, `End_Date`, `Degree`, `Notes`) VALUES ($id, '$s_name', '$s_type', '$s_enddate', '$s_degree', '$s_notes');";
  $res_sql = mysql_query ($sql);
  }
}

This is actually working fine with me.  I don't have any errors or anything but I do believe there is a more efficient way to do this without having a lot of if statements. Thoughts?


texts:
I'm trying to work around a rule processor so I created the following classes (the interfaces would be straightforward to guess).

public class OrderProcessor : IOrderProcessor
{
    private readonly IRuleEvaluator _ruleEvaluator;

    public OrderProcessor(IRuleEvaluator ruleEvaluator)
    {
        _ruleEvaluator = ruleEvaluator;
    }

    public void Process(Command command)
    {
        var rules = _ruleEvaluator.GetRules(command);
        foreach (var rule in rules)
        {
            rule.Apply(command);
        }
    }
}

public class RuleEvaluator : IRuleEvaluator
{
    private readonly IRuleSet _ruleSet;

    public RuleEvaluator(IRuleSet ruleSet)
    {
        _ruleSet = ruleSet;
    }

    public List<IRule> GetRules(Command command)
    {
        var ruleSet = _ruleSet.GetRules();

        if (!ruleSet.Any())
        {
            return new List<IRule>();
        }

        var rules = from pair in _ruleSet.GetRules()
                    orderby pair.Value descending
                    select pair.Key;

        return rules.Where(r => r.IsApplicable(command)).ToList();
    }
}

public class RuleSet : IRuleSet
{
    private readonly Dictionary<IRule, int> _rules = new Dictionary<IRule, int>();

    public RuleSet(IDependency1 dependency1,
        IDependency2 dependency2)
    {
        _rules.Add(new Rule1(dependency1), 1000);
        _rules.Add(new Rule2(dependency2), 1);
    }

    public Dictionary<IRule, int> GetRules()
    {
        return _rules;
    }
}

I was trying to abstract it in a way that would be easy to add new Rules to the RuleSet, but my issue comes where I see that if the Rules take any dependency I have to add them to RuleSet class. Not sure if this is actually a good practice as I would say it will easily bloat.


texts:
I have more than 1000 items in my GridView. When scrolling though, it appears to make the app 'shutter'. Each time I load images from Picasso GC, it increases.

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

public class BrandsItemAdapter extends BaseAdapter {

    public Activity activity;
    private static LayoutInflater inflater = null;

    public ArrayList<HashMap<String, String>> data;

    public HashMap<String, String> ITEM;

    public BrandsItemAdapter(Activity activity,ArrayList<HashMap<String, String>> data)
    {
        this.activity=activity;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.data = data;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder = null;
        ITEM = new HashMap<String, String>();
        ITEM = data.get(position);

        if(convertView == null)
        {
        convertView  = inflater.inflate(R.layout.department_viewadapter, parent, false);
        holder = new ViewHolder();

        holder.mTitleView = (TextView) convertView.findViewById(R.id.textView1);
        holder.imageView1 = (ImageView) convertView.findViewById(R.id.imageView1);

        convertView.setTag(holder);
        }else
        {
        holder = (ViewHolder) convertView.getTag();
        }

        try
        {
            holder.mTitleView.setText(ITEM.get("name"));
            Picasso.with(activity).load(ITEM.get("image")).placeholder(R.drawable.icon).resize(150, 150).error(R.drawable.icon).into(holder.imageView1);
            System.gc();

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder {
        TextView mTitleView;
        ImageView imageView1;
    }

}


texts: Detecting over-/underflow for uint64+int64

texts:
I am trying to write a function in Go which adds an uint64 value and an int64 value and which detects whether the result can be represented as an uint64.

func addUintInt64(x uint64, y int64) (uint64, bool) {
    if y >= 0 {
        z := x + uint64(y)
        if z < x {
            return 0, false
        }
        return z, true
    } else if y == -(1 << 63) {
        if x < 1<<63 {
            return 0, false
        }
        return x - 1<<63, true
    } else {
        negY := uint64(-y)
        if x < negY {
            return 0, false
        }
        return x - negY, true
    }
}

(Also on the Go Playground)

The second argument indicates whether the result is in the range of an int64.  If this is true, the first argument is the sum of x and y.

My questions:

Is this code correct?  I tested all boundary cases I could think of, but maybe I overlooked something?
Is there a nicer or more obvious looking way to write this code?  The fact that I'm not sure whether the code is correct probably indicates that it is not well written.
Is there a more efficient way to perform this task?  In particular, I would love to get rid of the special case for y == -(1<<63).  Note that I don't care about the first result, in cases where the second result is false.  Maybe this offers some potential for optimisations?


texts:
I just wondered if someone could review this socket class for me.

using Apple.Application.Base.Sockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Apple.Application.Base.Connection
{
    class SocketManager
    {
        private Socket _serverSocket;
        private SocketSettings _settings;

        public SocketManager(SocketSettings settings)
        {
            _settings = settings;
            _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            BeginListen();
            BeginAccept();
        }

        public void BeginListen()
        {
            _serverSocket.Bind(_settings.EndPoint);
            _serverSocket.Listen(_settings.SocketBacklog);
        }

        public void BeginAccept()
        {
            _serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
        }

        public void OnAccept(IAsyncResult AsyncResult)
        {
            try
            {
                _settings._log.Info("New connection was received");
                Apple.GetPlayerManager().RegisterNewPlayer();
            }
            catch (Exception exception)
            {
                _settings._log.Error(exception);
            }
            finally
            {
                BeginAccept();
            }
        }
    }
}

Here is the SocketSettings class:

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

namespace Apple.Application.Base.Sockets
{
    sealed class SocketSettings
    {
        public IPEndPoint EndPoint { get; set; }
        public ushort SocketBacklog { get; set; }
        public ILog _log { get; set; }
    }
}


texts: Reporting success or failure of a child process

texts:
The variable result is an integer representing the exit code of a command line process that was run via Groovy code. An exit code of 0 means the process was successful and an exit code from 1-255 means a failure. Then this line is executed:

println result ? "The command failed." : "The command succeeded."

What's happening here is that result is being coerced to a boolean (nonzero is true, zero is false) and then the ternary operator is used to determine which message to print, telling the user if the command succeeded or failed.

Is this fine in the context of the Groovy language, or is this going a bit too far with implicit magic?


texts:
Input: String : Title; List Tags

Problem statement:

  Need to map title to tags, e.g. title is "china man japan beijing bell" and tags are ["china man" "beijing bell"], output should be ["china man" "japan" "beijing bell"]

What I am doing:

List<String> getTitleSplits(String title, List<String> tags) {
        List<String> titleSplits = title.split(" "));
        List<String> ret = new ArrayList<String>();
        LinkedHashMap<String, Boolean> splitValueMap = new LinkedHashMap<String, Boolean>();
        for(String split : titleSplits) {
            splitValueMap.put(split, FALSE);
        }
        for(String titleSplit : titleSplits) {
                boolean flag = false;
                for(String tag : tags) {
                    if(tag.contains(titleSplit) || tag.contains(titleSplit.toLowerCase())) {
                        List<String> tagSplits = Arrays.asList(tag.split((" ")));
                        List<String> list = new ArrayList<String>();
                        for (String tagSplit : tagSplits) {
                            if (splitValueMap.get(tagSplit) == FALSE &&
                                    titleSplits.contains(tagSplit)) {
                                list.add(tagSplit);
                                splitValueMap.put(tagSplit, TRUE);
                                flag = true;
                            }
                        }
                        if(flag) {
                            ret.add(StringUtils.join(list, " ").trim());
                            splitValueMap.put(titleSplit, TRUE);
                            break;
                        }
                    }
                }
                if(!flag && splitValueMap.get(titleSplit) == FALSE) {
                    ret.add(titleSplit);
                }
            }
        return ret;
}

Please review this.


texts:
I'm working on converting my basic cryptocurrency miner from C# to C++ for performance reasons (I've been told that C++ is faster in many aspects). However, that aside, the focus of this post is to get some feedback for a very basic port of ReadLine, Write and WriteLine as I understand them, from C# to C++. This way, I don't get too far along before learning lessons the hard way.
Console.h
From my understanding, this file is mostly meant for definitions, such as an interface in C# in that implementation should not occur here, though it's not disallowed (unlike C# where it is disallowed):
#pragma once
#include <string>
using namespace std;
class Console
{
public:
    static string ReadLine();
    static void Write(string input);
    static void WriteLine(string input);
};

Console.cpp
The concept of separating definition from implementation is a bit new to me (outside of interfaces and members marked as abstract in C#). The part that threw me off here is that the static keyword is dropped when writing out the function:
#include "Console.h"
#include <iostream>
#include <string>
using namespace std;
string Console::ReadLine() {
    string result;
    cin >> result;
    return result;
}
void Console::Write(string input) { cout << input; }
void Console::WriteLine(string input) { cout << input + "\n"; }

CryptoSandbox.cpp
This is my entry point, I didn't really change much. I simply replaced the original cout << "Hello World" with Console::WriteLine(...), which required inclusion of Console.h to compile, so lesson learned fast there:
#include "Console.h"
#include <string>
using namespace std;
int main() {
    Console::Write("Starting the crypto sandbox. Please tell us your name: ");
    string userName = Console::ReadLine();
    Console::WriteLine("Welcome to the crypto sandbox, " + userName + "!");
}

The goal of this post is to learn what I can simplify, and anything that can be done better. A few questions hitting me hard are:

How does organization not become quickly overwhelming based on how VS Community creates the initial project structure?
Why is static not accepted in the cpp file when the declaration states static void in the h file?

Outside of those two questions (entirely optional, by the way), my primary focus is certainly feedback on my port.


texts: Find max-number div by three to be formed by array elements

texts:
Given an array of non-negative integers, find the largest multiple of 3 that can be formed from array elements.
For example, if the input array is {8, 1, 9}, the output should be "9 8 1", and if the input array is {8, 1, 7, 6, 0}, output should be "8 7 6 0".

Looking for code-review, best-practices and optimizations.
public final class DivThree {

    private DivThree() {}

    public static int divThree(int[] a) {
        final Queue<Integer> queue0 = new LinkedList<Integer>(); // if num % 3 == 0, store num in queue0.
        final Queue<Integer> queue1 = new LinkedList<Integer>(); // if num % 3 == 1, store num in queue1.
        final Queue<Integer> queue2 = new LinkedList<Integer>(); // if num % 3 == 2, store num in queue2.

        Arrays.sort(a);

        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum = sum  + a[i];

            int remainder = a[i] % 3;

            if (remainder == 0) {
                queue0.add(a[i]);
            } else  if (remainder == 1) {
                queue1.add(a[i]);
            } else {
                queue2.add(a[i]);
            }
        }

        if (sum % 3 == 1) {
            if (!queue1.isEmpty()) {
                queue1.remove();
            } else {
                if (!queue2.isEmpty()) {
                    queue2.remove();
                } else {
                    return -1;
                }
                if (!queue2.isEmpty()) {
                    queue2.remove();
                } else {
                    return -1;
                }
            }
        } else if (sum % 3 == 2) {
            if (!queue2.isEmpty()) {
                queue2.remove();
            } else {
                if (!queue1.isEmpty()) {
                    queue1.remove();
                } else {
                    return -1;
                }
                if (!queue1.isEmpty()) {
                    queue1.remove();
                } else {
                    return -1;
                }
            }
        }

        final List<Integer> list = new ArrayList<Integer>();
        list.addAll(queue0);
        list.addAll(queue1);
        list.addAll(queue2);

        Collections.sort(list);

        int result = 0;
        int pow = 1;
        for (int i = 0; i < list.size(); i++) {
            result = result  + pow * list.get(i);
            pow = pow * 10;
        }

        return result;
    }
}

public class DivThreeTest {

    @Test
    public void test1() {
        int[] a1 = {1, 2, 3, 4};
        assertEquals(432, DivThree.divThree(a1));
    }

    @Test
    public void test2() {
        int a2[] = {8, 1, 7, 6, 0};
        assertEquals(8760, DivThree.divThree(a2));
    }

}


texts:
I more or less asked the same questions on stackoverflow.com, but maybe this is more for this forum. I have a hard time getting to grips with how to implement a top navigation (common for the whole site) and a page specific navigation (common for the current controller). I use Colin Williams' Template library.

I have written my own MY_Controller which all page controllers should extend, but I do not know if this is the correct way. The page specific navigation is implemented in the code below.

MY_Controller.php

abstract class MY_Controller extends CI_Controller {
    private $_nav;

    public function __construct() {
        parent::__construct();
    }

    abstract protected function _get_nav();

    protected function _load_nav(array $nav = null) {
        if ($nav === null) {
            $this->_nav = $this->_get_nav();
        } else {
            $this->_nav = $nav;
        }
    }

    protected function _render() {
        if (func_num_args() < 3) {
            return false;
        }

        $args = func_get_args();
        $this->template->write('title', array_shift($args));
        $data = array_pop($args);

        for ($i = 0; $i < count($args); $i++) {
            $this->template->write_view('content', array_shift($args), $data);
        }

        if ($this->_nav === null) {
            $this->_load_nav();
        }

        $this->template->write_view('nav', 'templates/sidebar_nav', array('nav' => $this->_nav));
        $this->template->render();
        return true;
    }
}

collection.php

class Collection extends MY_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('collection_model');
    }

    protected function _get_nav() {
        return $this->config->item('collection_nav');
    }

    public function index() {
        $this->view();
    }

    public function view() {
        $data = array();
        $data['list'] = $this->collection_model->get_list();
        $this->_render('View Collection', 'collection/view', $data);
    }
}

sidebar_nav.php

    <?php foreach ($nav as $item) : ?>
    <?php $class = isset($item['class']) ? ' class="' . $item['class'] . '"' : ''; ?>
    <li<?php echo $class; ?>>
        <a href="<?php echo $item['href']; ?>"><?php echo $item['value']; ?>

    <?php endforeach; ?>

What do you think? Is this the proper way to produce a navigation system?


texts: Retrieve words from dictionary when they meet letter requirements

texts:
I have a set of functions that retrieve words from some arbitrary dictionary based on what letters they have. For example, this function gets words that use only the specified letters:

function getWordsWithOnlySpecifiedLetters(array $dictionary, string $letters)
{
    foreach ($dictionary as $key => $value) {
        if(mb_strlen($value) > mb_strlen($letters)) unset($dictionary[$key]);
    }

    $step = 0;
    $strSplit = preg_split('//u', $letters, null, PREG_SPLIT_NO_EMPTY);
    $result = [];
    foreach ($dictionary as $word) {
        $step++;
        $wordSplit = preg_split('//u', $word, null, PREG_SPLIT_NO_EMPTY);
        sort($wordSplit);
        sort($strSplit);
        if (array_map('mb_strtolower', $wordSplit) === array_map('mb_strtolower', $strSplit)) {
            //echo "All specified letters from $letters are in $word | Step $step
" . PHP_EOL;
            $result[] = $word;
        }
    }

    return $result;
}

Example usage:

$dictionary = ['apple', 'sample', 'api', 'pia', 'тоҷик'];
getWordsWithOnlySpecifiedLetters($dictionary, "aip");

This would return the words api and pia.

getWordsWithOnlySpecifiedLetters($dictionary, "leamps");

This one would return the word sample.

I also have a function that doesn't require that they exclusively use the selected letters, but rather that they use all of the specified letters (and any other letters).

function getWordsWithSpecifiedLetters(array $dictionary, string $letters)
{
    $step = 0;
    mb_internal_encoding("UTF-8");
    $result = [];
    foreach ($dictionary as $word) {
        $step++;
        $wordSplit = preg_split('//u', $word, null, PREG_SPLIT_NO_EMPTY);
        $strSplit = preg_split('//u', $letters, null, PREG_SPLIT_NO_EMPTY);
        $wordSplit = array_filter($wordSplit, function($x) use (&$strSplit) {
            if (in_array(strtolower($x), array_map('strtolower', $strSplit), true)) {
                $pos = array_search(strtolower($x), array_map('strtolower', $strSplit), true);
                unset($strSplit[$pos]);
                return false;
            }
            return true;
        });
        if (count(array_diff($strSplit,$wordSplit)) === 0) {
            //echo "$word contains all letters of $letters | Step $step
" . PHP_EOL;
            $result[] = $word;
        }
    }

    return $result;
}

Example usage:

$dictionary = ['apple', 'sample', 'api', 'pia', 'тоҷик'];
getWordsWithSpecifiedLetters($dictionary, "ple");

This returns the words sample and apple.

I have more 90000 words in my dictionary (UTF-8). This results in a very slow program; if I'm trying to find something from the full dictionary it may take tens of thousands of loops. How can I improve the performance of these functions?

You can download my dictionary from here and testing your code using dictionary words.


texts:
Employee hierarchy in an Organization is classic example of modeling Composite design  pattern. Following are the details that are to be modeled:

There are two type of employees; Manager, and Developer.
A Manager manages a team that can comprise managers, and developer.
A Developer has fixed salary at given point of time and get work from the manager.
The salary of a manager is the sum of salary of all the team members + 10K.
We need to model work distribution, and salary of employees of the organization.

#include <string>
#include <vector>
#include <iostream>

using namespace std;

class Employee {
   private:
      string _name;
   public:
      Employee(string name_) {
         _name = name_;
      }
      string name() {
         return _name;
      }
      void virtual work() = 0;
      float virtual salary() = 0;
};
// Common Interface to interact with Manager, and Developer
class Developer : public Employee {
   private:
      float _salary;
   public:
      Developer(string name_,float salary_) : Employee(name_),_salary(salary_) {}
      void work() {
         cout << "Developer " << name() << " Worked\n";
         // A developer works own.
      }
      float salary() {
         return _salary;
      }
};

class Manager : public Employee {
   private:
      vector<Employee*> _team;
   public:
      Manager(string name_) : Employee(name_) {}
      void add(Employee * emp_) {
          _team.push_back(emp_);
      }
      void work() {
         cout << "Manager " << name() << " Distributed Work\n";
         for(vector<Employee*>::iterator it = _team.begin(); it!=_team.end(); ++it) {
            (*it)->work();
         }
         // A manager distributes work in team members.
      }
      float salary() {
         float salary_ = 0.0;
         for(vector<Employee*>::iterator it = _team.begin(); it!=_team.end(); ++it) {
            salary_ += (*it)->salary()+15000;
         }
         return salary_;
         // Salary of a manager is derived from team members.
      }
};
int main() {
   Developer d1("developer1",10000);
   Developer d2("developer2",15000);
   Manager m1("manager1");
   m1.add(&d1);
   m1.add(&d2);
   Manager m2("manager2");
   m2.add(&m1);
   m2.work();
   return 0;
}


texts: Generic repository accessor in a unit of work

texts:
I'm giving the repository + UoW patterns my first shot on the server side, so bear with me. Also, it's worth mentioning that I haven't used an IoC container on the server side before either, so I'll post its setup too. I'm using simple injector at the moment.

All kinds of feedback is appreciated, especially for UnitOfWork.GetRepository<T>() a bit below, which I'm not very satisfied with.

var container = new Container();

container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

container.Register(typeof(IUnitOfWork), typeof(UnitOfWork), Lifestyle.Scoped);

container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

container.Verify();

GlobalConfiguration.Configuration.DependencyResolver =
                                     new SimpleInjectorWebApiDependencyResolver(container);

public interface IUnitOfWork
{
    DatabaseRepository<T> GetRepository<T>() where T : BaseEntity;
    Task CommitAsync();
}

public class UnitOfWork : IUnitOfWork, IDisposable
{
    private readonly Entities _context = new Entities();
    private readonly IDictionary<Type, object> _repositories = new Dictionary<Type, object>();

    public DatabaseRepository<T> GetRepository<T>() where T : BaseEntity
    {
        var type = typeof(T);

        if (!_repositories.ContainsKey(type))
        {
            var instance = (DatabaseRepository<T>)Activator.CreateInstance(typeof(DatabaseRepository<T>), _context);
            _repositories[type] = instance;
        }

        return _repositories[type] as DatabaseRepository<T>;
    }

    public async Task CommitAsync()
    {
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbEntityValidationException e)
        {
            // todo: handle validation errors...
            throw;
        }
    }

    private bool _disposed;

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        _disposed = true;
    }

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


texts: Implementation of Set data type in Haskell

texts:
I'm an advanced beginner Haskell programmer. I implemented a set data type in Haskell and I wanted to find out if I made correct choices when writing it. Would there be a way to improve some of the algorithms like intersection etc.

data SET a = E | Add(a, SET a) deriving (Eq, Ord, Read, Show)

--test data

setx = listToSet[1,2,3,4]

setx2 = listToSet[3,4,2,1]

sety = listToSet[3,4,5,6]

setys = listToSet[3,4]

listToSet :: [a] -> SET a
listToSet [] = E
listToSet (s:x) = Add(s, listToSet x)

inS :: (Eq a) => a -> SET a -> Bool
inS a E = False
inS a (Add(value, set)) = if (value == a)
                        then True
                        else (inS a set)

nullSET :: (Eq a) => SET a -> Bool
nullSET s = s == E

headSET :: SET a -> a
headSET (Add(v, s)) = v

tailSET :: SET a -> SET a
tailSET (Add(v, s)) = s

addToSet :: (Eq a) => a -> SET a -> SET a
addToSet a (Add(value, set)) = if (inS a (Add(value, set)) == False)
                               then Add(a, Add(value, set))
                               else (Add(value, set))

setFilter :: (Eq a) => (a -> Bool) -> SET a -> SET a
setFilter f s
    | nullSET s    = E
    | f h == False = setFilter f t
    | otherwise    = Add(h, setFilter f t)
        where
            h = headSET s
            t = tailSET s

intersection :: (Eq a) => SET a -> SET a -> SET a
intersection s1 s2 = setFilter (\x -> inS x s1) s2

union :: (Eq a) => SET a -> SET a -> SET a
union set E = set
union set (Add(value2, set2)) = if (inS value2 set == False)
                                then Add(value2, (union set set2))
                                else union set set2

subSet :: (Eq a) => SET a -> SET a -> Bool
subSet set1 set2
    | set1 == E  = True
    | inS h set2 = subSet t set2
    | otherwise  = False
    where
        h = headSET set1
        t = tailSET set1

setEq :: (Eq a) => SET a -> SET a -> Bool
setEq s1 s2 = (subSet s1 s2) == (subSet s2 s1)


texts: A simple list of objects to display and edit with Angular

texts:
I want to create a simple CRUD app using angular on the frontend.

I'm not really happy with the logic here, it seems a bit convoluted for fairly simple functionality.

 {{o.objectId}}

            <input type = "text" ng-model = "o.someContent" class = "col-xs-9" ng-disabled = "!o.isBeingEdit"/>
            <input type = "button" class = "col-xs-2 btn btn-default" ng-click = "editSave(o)" ng-value = "o.isBeingEdit? 'Save' : 'Edit'"/>

$scope.editSave = function(o){
    if (o.isBeingEdit){
        //Save
        BackendService.updateObject(o).then(function(data){
            o.isBeingEdit = false;
        }, function(data){
            o.isBeingEdit = false;
            handleServerError(data);
        });
    }
    else{
        o.isBeingEdit = true;
    }
};

Is there a much much much nicer way of doing this?


texts:
So I wrote this class template for a custom container. Basically, it stores elements and their occurences. When an element is pushed into the container, if it already exists, all it does is increment its counter.

#pragma once

#include <map>
#include <string>

//
// Template class for a tocc, or Thing Occurence Counter Container
//
template <class T>
class tocc
{
public:
    tocc();

    //
    // Increments the count of that item or creates a new pair if it doesn't exist
    //
    void push(const T& item)
    {
        // If no the item isn't found, create new pair with a count of 1
        if(_tocc.find(item) == _tocc.end())
            _tocc.insert(std::pair<T, long int>(item, 1));
        else
            _tocc.at(item)++;
    }

    //
    // Decrements the count of that item and erases it if the count reaches 0
    //
    void pop(const T& item)
    {
        // If the item is found
        if(_tocc.find(item) != _tocc.end())
            (_tocc.at(item) <= 1) ? _tocc.erase(item) : _tocc.at(item)--;

        // Do nothing if the item isn't found
    }

    //
    // Gets the count of a particular item
    // Returns the count if the item exists, 0 otherwise
    //
    long int getCount(const T& item)
    {
        if(_tocc.find(item) == _tocc.end())
            return 0;
        return _tocc.at(item);
    }

    //
    // Returns true if the item is present in the map, false otherwise
    //
    bool contains(const T& item)
    {
        return _tocc.find(item) != _tocc.end();
    }

private:
    std::map<T, long int> _tocc;
};

Here I put all the whole code in a single "file" for simplicity's sake, though I know it is best practice to separate files into headers and source files (which I normally do).

I'd like to know what can be improved about this implementation.


texts: Recursive branch and bound Knapsack solution

texts:
I've got the imperative styled solution working perfectly.
What I'm wondering is how to make a recursive branch and bound.

This is my code below. Evaluate function returns the optimistic estimate, the largest possible value for the set of items which fit into the knapsack (linear relaxation).

For some inputs this outputs an optimal solution, for some it comes really close, for every input it is extremely fast, so it doesn't seem that it hangs anywhere in the search space. So, maybe I'm not branching where I have to or I did something wrong. I'm sure optVal is optimal.

def branch(items: List[Item], taken: List[Item], capacity: Int, eval: Long): (List[Item], Boolean) = items match {
  case x :: xs if x.weight <= capacity => {

    val (bestLeft, opt) = branch(xs, x :: taken, capacity - x.weight, eval)
    if (opt) (bestLeft, opt) // if solution is optimal get out of the tree
    else {
      val evalWithout = evaluate(taken.reverse_:::(xs))

      if (evalWithout < optVal) (bestLeft, opt)
      else branch(xs, taken, capacity, evalWithout)
    }
  }
  case x :: xs => branch(xs, taken, capacity, evaluate(taken.reverse_:::(xs)))

  case Nil => if ((taken map (_.value) sum) == optVal) (taken, true) else (taken, false)
}


texts: Optimizing my solution for problem #23 - project Euler

texts:
The question -

  A perfect number is a number for which the sum of its proper divisors
  is exactly equal to the number. For example, the sum of the proper
  divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28
  is a perfect number.

  A number n is called deficient if the sum of its proper divisors is
  less than n and it is called abundant if this sum exceeds n.

  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the
  smallest number that can be written as the sum of two abundant numbers
  is 24. By mathematical analysis, it can be shown that all integers
  greater than 28123 can be written as the sum of two abundant numbers.
  However, this upper limit cannot be reduced any further by analysis
  even though it is known that the greatest number that cannot be
  expressed as the sum of two abundant numbers is less than this limit.

  Find the sum of all the positive integers which cannot be written as
  the sum of two abundant numbers.

My solution -

public class Problem23 {

    /**
     * A brute force solution -
     * 1. Calculate the abundant numbers till the limit.
     * 2. Check each number if it can be written as a sum of any two
     *    abundant numbers in the pre-calculated set
     *
     * @param args
     */
    public static void main(String[] args) {

        Set<Integer> abundantNumSet = new LinkedHashSet<Integer>(); //sorted set of abundant numbers

        // find all abundant numbers from 13 to 28123, since 12 is the smallest
        // abundant number and greatest number that cannot be expressed as the
        // sum of two abundant numbers is less than 28123
        abundantNumSet.add(12);
        for (int i = 13; i < 28124; ++i) {
            if (isAbundant(i)) {
                abundantNumSet.add(i);
            }
        }

        int total = 276; // sigma 23, since 24 = 12 * 2
        for (int i = 25; i < 28124; ++i) {
            boolean isRep = false;

            for (Integer num : abundantNumSet) {
                // iterating through half of the numbers in the set is enough
                if (abundantNumSet.contains(i - num)) {
                    // the number can be represented as a sum of two
                    isRep = true;
                    break;
                }
                if (i < num) {
                    // the abundant number should less than a given number to
                    // be part of the numbers forming the sum
                    break;
                }
            }

            if (!isRep) {
                // the number cannot be represented as sum of two abundant
                // numbers
                total += i;
            }
        }

        System.out.println(total);
    }

    public static boolean isAbundant(int n) {
        int sum = 1;
        int end = (int) Math.sqrt(n);

        for (int i = 2; i <= end; ++i) {
            if (n % i == 0) {
                int quotient = n / i;

                if (quotient != i) {
                    sum += i + quotient; // add the factors
                } else {
                    // avoid adding twice - factor in case of perfect squares
                    sum += quotient;
                }
            }
        }

        if (sum > n) {
            return true;
        }

        return false;
    }
}

I would like to optimize my solution.
Some pointers at the same would be appreciated.


texts: Is this a good way to catch all 404s in .NET without playing with IIS configuration?

texts:
The situation is that its not always possible to play with the web.config or have access to IIS, that being said I had to come up with a way to catch all 404s in a .NET application, for aspx page extensions its fairly easily and the web is full of ideas... but for non aspx extensions I did the following, looking for advice, is this a good way? are their scenarios where it might fail? does it measure well in performance? thanks for advice

After checking my web.sitemap links and make my rewrites, the "else" block contains the following

string s = context.Server.MapPath(context.Request.AppRelativeCurrentExecutionFilePath);
if (!System.IO.File.Exists(s)){
    throw new HttpException(404, "Page not found");
}

and of course, the rest is handled by the application error handler
notice that all css, js, jpegs and other file types go through this check

edit: two problems seem to be persistent with regular error catch, html and friendly urls, they never seem to fire 404s (guessing there other file types, depends on isapi filters)


texts:
I just finished Project Euler 31: Coin sums, which asks how many ways there are to make £2 using British coins (1p, 2p, 5p, 10p, 20p, 50p, £1, and £2).

When I compared my code and the problem review's algorithms, I found that my code was faster than theirs. Both of them use dynamic programming, but for some unknown reasons, my code meets the recursive limits.

Project Euler  Reference

def problem_31_dynamic_programming(money, coin_index):
    count = 0
    if coin_index <= 0:
        return 1
    m = money
    if memoiz_list[m][coin_index] > 0:
        return memoiz_list[m][coin_index]
    while money >= 0:
        count += problem_31_dynamic_programming(money, coin_index - 1)
        money -= coin_list[coin_index]
    memoiz_list[m][coin_index] = count
    return count

My solution

import time

def problem_31(money, coin_index): #My solution (cannot solve big number such as 10000)
    if coin_index < 0:
        return 0
    if coin_index == 0 or money == 0:
        return 1
    if memoiz_list[money][coin_index] > 0:
        return memoiz_list[money][coin_index]
    if coin_list[coin_index] > money:
        return problem_31(money, coin_index - 1)
    memoiz_list[money][coin_index] = problem_31(money, coin_index-1)+ \
                                     problem_31(money-coin_list[coin_index],coin_index)
    return memoiz_list[money][coin_index]

start = time.time()
coin_list = [1,2,5,10,20,50,100,200]
memoiz_list = [[0,0,0,0,0,0,0,0] for i in range(201)]
print(problem_31_dynamic_programming(200,7)) #Replace problem_31_dynamic_programming() with problem_31
elapsed = time.time() - start
print("Result found in %f seconds"%(elapsed))