texts:
I'm writing up a game server on which thread-safety is very important, basically for this approach I've decided to move my entire server in a single brain loop which handles everything in a single thread, connections are ran separately in their own separate thread, whenever a packet is received, the brain loop is signaled so it doesn't have to wait for the entire interval.

This is truly the best approach I could come up with, given my server is filled with pointers everywhere, and invalidation would kill my player base.

#define GAME_BEAT 50

void Game::brain() {
    int64_t connectionsTimeCounter = 0;
    int64_t decayTimeCounter = 0;
    int64_t releasePointersCounter = 0;
    int64_t creaturesTimeCounter = 0;
    int64_t roundNr = getServerMilliseconds();

    while (isGameRunning() || isGameStarting()) {
        gameSignal.wait(GAME_BEAT);

        int64_t delay = getServerMilliseconds() - roundNr;
        roundNr = getServerMilliseconds();

        // Receive packets from connections with data available to be read (non-blocking)
        // when data is available to be read, the connection which was previously ran in a different thread
        // will be signaled to read packet data and store it in a variable
        // say, a packet for "player talk" was sent, then the function below "moveCreatures" would handle this action
        g_server.receiveData();

        connectionsTimeCounter += delay;
        if (connectionsTimeCounter >= 1000) {
            // This function closes invalid connections/closed connections
            g_server.processConnections();
        }

        decayTimeCounter += delay;
        if (connectionsTimeCounter >= 1500) {
            decayItems(delay);
        }

        releasePointersCounter += delay;
        if (releasePointersCounter >= 1000) {
            // This function simply calls a "delete" to removed objects from the game
            releaseObjects();
        }

        creaturesTimeCounter += delay;
        if (creaturesTimeCounter >= 1000) {
            // Processes creatures idle status
            processCreatures(delay);
        }

        // Moves creatures, players, talking, moving, etc ...
        moveCreatures();

        // Sends all pending packets to be sent to active connections
        g_server.sendAllData();
    }
}

That is pretty much the only way I found for my server to be thread-safe, since I did experienced a few crashes because when connections sent a particular packet (say player move item), it would invalidate other connections from doing so


texts: Speeding up the process of obtaining data

texts:
I created this script to obtain data from graphs online, from monavisaxmldata. I were wondering if there was a way to obtain the data faster. The program which uses this data gets presented in a presentation which takes roughly 5 minutes. But the data already takes 1.5 minutes to load. Which is quiet a bite in such a short time period.

Is the WebClient() optimized in speed or should I approach the handling of the information differently?

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Web;

public class PVPanels_Actueel : MonoBehaviour
{
    private static WebClient myWebClient = new WebClient();
    private List<KeyValuePair<string, List<MonavisaXmlData>>> DataList = new List<KeyValuePair<string, List<MonavisaXmlData>>>();
    private List<MonavisaGraphData> graphReadyData = new List<MonavisaGraphData>();
    public event System.Action<List<MonavisaGraphData>> PVPanelsActDataParsed = delegate { };

private void Start()
{
    myWebClient.DownloadStringCompleted += onDownloadComplete;
}
public static void StartDownload(int day, int month, int year)
{
    string dateAndTime = string.Format("{0}-{1}-{2}+23:00", day, month, year);
    MonavisaRequestForm myRequest = new MonavisaRequestForm
        (
            "foo",
            "bar",
            string.Format("http://www.monavisa.info/CreateGraphData?graphs=1&graph[0]=1226&todate={0}&period=1&step=0&b_id=194&inter=1&other_graph=true", dateAndTime),
            ref myWebClient
            );
    MonavisaFetch.instance.getData(ref myRequest);
}

private void onDownloadComplete(object sender, DownloadStringCompletedEventArgs e)
{
    DataList.Clear();
    DataList = MonavisaParse.Parse(e.Result);
    graphReadyData.Clear();

    float totalKwh = 0;
    float totalMw2 = 0;
    string latestDate = "";
    for (int i = 0; i < DataList[1].Value.Count; i++)
    {
        float f0 = float.Parse(DataList[0].Value[i].value);
        float f1 = float.Parse(DataList[1].Value[i].value);
        float f2 = float.Parse(DataList[2].Value[i].value);
        float f3 = float.Parse(DataList[3].Value[i].value);

        if (f0 > 0)
        {
            totalMw2 += f0;
            latestDate = DataList[0].Value[i].date;
        }

        if (f1 > 0 || f2 > 0 || f3 > 0)
        {
            totalKwh += f1 + f2 + f3;
        }
    }

    graphReadyData.Add(new MonavisaGraphData { date = latestDate, value = totalMw2 });
    graphReadyData.Add(new MonavisaGraphData { date = latestDate, value = totalKwh });
    PVPanelsActDataParsed.Invoke(graphReadyData);
}
}

The data is stored on a dutch site. you can go to this link use the log in info DWA-demo and password = welkom (this is a sample login given by the site itself) to see how the data structure is stored. What I currently request is a bit of a different graph, which is stored in a XML file. This file contains the values

Period where:

HOUR = 0;
DAY = 1;
WEEK = 2;
MONTH = 3;
TWO_MONTHS = 4;
THREE_MONTHS = 5;
SIX_MONTHS = 6;
YEAR = 7;
FIVE_YEAR = 8;

and a step where

HOUR = 0;
DAY = 1;
WEEK = 2;
MONTH = 3;
TWO_MONTHS = 4;
THREE_MONTHS = 5;
SIX_MONTHS = 6;
YEAR = 7;
FIVE_YEAR = 8;

And currently I am listing graph1&graph[0] which is 1 day per hour of dateAndTime, which today and the last round hour.

string.Format("http://www.monavisa.info/CreateGraphData?graphs=1&graph[0]=1226&todate={0}&period=1&step=0&b_id=194&inter=1&other_graph=true", dateAndTime),

This situation should be repeatable by putting a XML on a server/site where you first have to login, and then grab the data from the XML through requests.


texts: Min Heap implementation with Dijkstra's algorithm

texts:
I am implementing Dijkstra's Algorithm using Min Heap to speed up the code.

For a small number of nodes, the code is really running very fast. But for a large number of nodes, my code is throwing java.lang.OutOfMemoryError: Java heap space exception. My Min heap implementation is based on the code, given here in C++. I changed this code into Java.

Below is my min heap code (I am not putting Dijkstra's algorithm code, as it is same as described in the above link).

public class Heap {
    private static int[] data;
    private static int[] index;
    public static int[] cost;
    public static boolean[] eval;
    private static int size;

    public Heap(int s) {
        data = new int[s];
        index = new int[s];
        cost = new int[s];
        eval = new boolean[s];
    }

    public void init(int s) {
        for (int i = 0; i < s; i++) {
            index[i] = -1;
            eval[i] = false;
        }
        size = 0;
    }

    public boolean isEmpty() {
        return (size == 0);
    }

    private void shiftUp(int i) {
        int j;
        while (i > 0) {
            j = (i - 1) / 2;
            if (cost[data[i]] < cost[data[j]]) {

                int temp = index[data[i]];
                index[data[i]] = index[data[j]];
                index[data[j]] = temp;

                temp = data[i];
                data[i] = data[j];
                data[j] = temp;
                i = j;
            } else
                break;
        }
    }

    private void shiftDown(int i) {
        int j, k;
        while (2 * i + 1 < size) {
            j = 2 * i + 1;
            k = j + 1;
            if (k < size && cost[data[k]] < cost[data[j]]
                    && cost[data[k]] < cost[data[i]]) {

                int temp = index[data[k]];
                index[data[k]] = index[data[i]];
                index[data[i]] = temp;

                temp = data[k];
                data[k] = data[i];
                data[i] = temp;

                i = k;
            } else if (cost[data[j]] < cost[data[i]]) {

                int temp = index[data[j]];
                index[data[j]] = index[data[i]];
                index[data[i]] = temp;

                temp = data[j];
                data[j] = data[i];
                data[i] = temp;

                i = j;
            } else
                break;
        }
    }

    public int pop() {
        int res = data[0];
        data[0] = data[size - 1];
        index[data[0]] = 0;
        size--;
        shiftDown(0);
        return res;
    }

    public void push(int x, int c) {
        if (index[x] == -1) {
            cost[x] = c;
            data[size] = x;
            index[x] = size;
            size++;
            shiftUp(index[x]);
        } else {
            if (c < cost[x]) {
                cost[x] = c;
                shiftUp(index[x]);
                shiftDown(index[x]);
            }
        }
    }
}

As far as the code is concerned, it is working fine for small s. How can I optimize this code for a large value of nodes?


texts:
I have the need to programatically create a context menu using names for the menu items which aren't known until the program loads user data.

Here's how I have implemented it.  I'm not happy with the cast to get the menu item text to find out which item they have clicked on. Is there a better way that I'm missing?

public partial class Form1 : Form
{
    private readonly string[] cards = new string[] {"HBOS", "EGG", "RBOS"};

    ContextMenu mnuContextMenu = new ContextMenu();

    private void Form1_Load(object sender, EventArgs e)
    {
        ContextMenu = mnuContextMenu;

        SetupRightClickmenu();
    }

    private void SetupRightClickmenu()
    {
        MenuItem bank1MenuItem = new MenuItem(BankNames.Bank1);
        MenuItem bank2MenuItem = new MenuItem(BankNames.Bank2);
        MenuItem bank3MenuItem = new MenuItem(BankNames.Bank3);
        MenuItem cashMenuItem = new MenuItem("Cash");
        MenuItem creditCardMenuItem = new MenuItem("Credit Card");

        bank1MenuItem.Click += bank1MenuItem_Click;
        bank2MenuItem.Click += bank2MenuItem_Click;
        bank3MenuItem.Click += bank3MenuItem_Click;
        cashMenuItem.Click += cashMenuItem_Click;

        mnuContextMenu.MenuItems.Add(bank1MenuItem);
        mnuContextMenu.MenuItems.Add(bank2MenuItem);
        mnuContextMenu.MenuItems.Add(bank3MenuItem);
        mnuContextMenu.MenuItems.Add(cashMenuItem);
        mnuContextMenu.MenuItems.Add(creditCardMenuItem);

        MenuItem creditCardSubMenuItem;

        foreach(string card in cards)
        {
            creditCardSubMenuItem = new MenuItem();
            creditCardSubMenuItem.Text = card;
            creditCardMenuItem.MenuItems.Add(creditCardSubMenuItem);
            creditCardSubMenuItem.Click += creditCardSubMenuItem_Click;
        }
    }

    void creditCardSubMenuItem_Click(object sender, EventArgs e)
    {
        MenuItem menuItem = (MenuItem) sender;

        MessageBox.Show("You clicked on " + menuItem.Text);
    }

    void cashMenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked on cash");
    }

    void bank3MenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked on bank 3");
    }

    void bank2MenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked on bank 2");
    }

    void bank1MenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked on bank 1");
    }
}

In the actual version the cards array is received from the users data.


texts:
Looking around for modern Crypto libraries.
Could not find anything good.
I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:

Hashing
Hashed Key
Password Key
Salted Challenge Response

This review is for an implementation of pbkdf2 implementation. This is a way of using HMAC that allows you to make incrementally more expensive to create the hash on failures. The idea is that you can slow down attacks by making it harder to make lots of guesses.
The data structures and implementation presented in these questions are based on RFC2104 and this post on codeproject.
Usage Example
Digest<Pbkdf2<HMac<Sha1>>>    digest;
Pbkdf2<HMac<Sha1>>            pbkdf2;

pbkdf2.hash("The password", "A Salt", 2048, digest);

pbkdf2.h
#ifndef THORS_ANVIL_CRYPTO_PBKDF2_H
#define THORS_ANVIL_CRYPTO_PBKDF2_H

#include "hmac.h"
#include <string>

// RFC-2898 PKCS #5: Password-Based Cryptography Specification Version 2.0

namespace ThorsAnvil::Crypto
{

// Look in hmac.h for good examples of PRF
// ThorsAnvil::Crypto::HMac
template<typename PRF>
struct Pbkdf2
{
    static constexpr std::size_t digestSize = PRF::digestSize;
    using DigestStore    = typename PRF::DigestStore;

    void hash(std::string const& password, std::string const& salt, long iter, DigestStore& digest)
    {
#pragma vera-pushoff
        using namespace std::string_literals;
#pragma vera-pop
        PRF             prf;
        DigestStore     tmp;

        prf.hash(password, salt + "\x00\x00\x00\x01"s, tmp);
        std::copy(std::begin(tmp), std::end(tmp), std::begin(digest));

        for (int loop = 1; loop < iter; ++loop)
        {
            prf.hash(password, tmp.view(), tmp);
            for (std::size_t loop = 0; loop < digestSize; ++loop)
            {
                digest[loop] = digest[loop] ^ tmp[loop];
            }
        }
    }
};

}

#endif


texts:
Suppose You have two kind of response like one for success and one for failure

Success response model will looks like

struct UserLogin: Codable {
    let status: Bool?
    let accessToken: String?
    let data: [UserLoginData]?
   ....
}

Failure Model will looks like

struct FailedResponse: Codable {
    let status: Bool?
    let error: ErrorResponse?

}

How I handle this two responses

struct FailableResponse <T:Codable,E:Codable> : Codable {

    var success:T?
    var failure:E?

    public init(from decoder:Decoder) throws {

        let singleValue = try decoder.singleValueContainer()

        success = try singleValue.decode(T.self)
        failure = try singleValue.decode(E.self)

    }
}

And How I use FailableResponse

  APIClient.login(userName: self.loginViewModel.userName, password: self.loginViewModel.password) { (response:FailableResponse<UserLogin,FailedResponse>? , error) in

   }

// METHOD OF API CLIENT
// API CALLING
static func login<T:Codable>(userName:String,password:String,completion:@escaping completionResponse<T>) {
        self.performRequest(request: APIRouterUserModule.login(email: userName, password: password)) {(model) in

            self.handleResponseCallCompletion(result: model, completion: completion)
        }
  }
 // Parsing
 private static func handleResponseCallCompletion<T:Codable>(result:Result<Any>,completion:@escaping completionResponse<T>) {
        let object = CodableHelper<T>().decode(json: result)
        completion(object.object,object.error)
    }

I think It can be more better

Any suggestion Please :)


texts:
In mobile phones technologies, a SectorId is a 128-bit value broadcast by a 1xEV-DO BTS system.

That is a 16 bytes data.

I made a structure to store them:

using System;
using System.Globalization;
using System.Linq;
using System.Text;

public struct SectorId
{
    readonly byte[] id;

    SectorId(byte[] id)
    {
        this.id = new byte[16];
        Array.Copy(id, this.id, 16);
    }

    public override bool Equals(object obj)
    {
        if (obj is SectorId)
        {
            return Equals((SectorId)obj);
        }

        return false;
    }

    public bool Equals(SectorId other)
    {
        return id.SequenceEqual(other.id);
    }

    public override int GetHashCode()
    {
        int hash = 0;
        unchecked
        {
            foreach (var b in id)
            {
                hash *= 397;
                hash += b;
            }
        }
        return hash;
    }

    public static SectorId Parse(string s)
    {
        Throw.IfArgumentIsNull("s", s);

        SectorId result;
        if (TryParse(s, out result))
        {
            return result;
        }

        throw new FormatException();
    }

    public override string ToString()
    {
        var sb = new StringBuilder();
        foreach (var b in id)
        {
            sb.AppendFormat("{0:X2}", b);
        }
        return sb.ToString();
    }

    public static bool TryParse(string s, out SectorId result)
    {
        if (s == null)
        {
            goto Fail;
        }

        if (s.Length > 32)
        {
            goto Fail;
        }

        if (s.Length < 32)
        {
            s = s.PadRight(32, '0');
        }

        var bytes = new byte[16];

        for (var i = 0; i < 16; i++)
        {
            var substring = s.Substring(i * 2, 2);
            if (!byte.TryParse(substring, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out bytes[i]))
            {
                goto Fail;
            }
        }

        result = new SectorId(bytes);
        return true;

        Fail:
        result = default(SectorId);
        return false;
    }
}

The TryParse part is the worse for me. I would like to avoid gotos.


texts:
We are always told to call GPIO.cleanup() before we exit our Pi programs. I've seen people using try ... catch ... finally to achieve this. But hey, we are doing python here, an elegant programming language. Do you guys think this is a more elegant solution?

# SafeGPIO.py

from RPi import GPIO

class SafeGPIO(object):
    def __enter__(self):
        return GPIO

    def __exit__(self, *args, **kwargs):
        GPIO.cleanup()

Use like this:

from SafeGPIO import SafeGPIO
import time

with SafeGPIO() as GPIO:
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(7, GPIO.OUT)
    GPIO.output(7, True)
    GPIO.setup(8, GPIO.OUT)
    GPIO.output(8, True)

    val = 0
    for i in xrange(10):
        val = (val + 1) % 2
        active_pin = 7 + val
        inactive_pin = 7 + (val + 1) % 2
        GPIO.output(active_pin,True)
        GPIO.output(inactive_pin,False)
        time.sleep(2)


texts: Insert a node at a specific position in a Linked List

texts:
This code is built to insert a Node into a specific position of a linked-list. It passes all the test cases for the interview, but I was wondering about the coding style regarding techniques, and especially variable naming, and any other best-practices you can help with.

Node* InsertNth(Node *head, int data, int position)
{
    // Complete this method only
    // Do not write main function.
    Node * sentinel = new Node();
    sentinel->data = -1;
    sentinel->next = head;
    Node* node = sentinel;
    int i = 0;
    while (node->next && i < position) {
        node = node->next;
        i++;
    }

    Node* preNext = node->next;
    Node* newNode = new Node();
    newNode->data = data;
    newNode->next = preNext;
    node->next = newNode;
    head = sentinel->next;
    delete sentinel;

    return head;

}


texts: Calculator for magic item creation in RPG

texts:
I have created a simple calculator that will assist in creating magic items from the tabletop RPG Pathfinder. Here are the full requirements, and if you want a more concise version, here is a player generated summary of the process.

I have been trying to get into F# and functional programming in general. I come from a strong object-oriented background and it has been difficult in ignoring those habits. Please focus on whether or not this is idiomatic F#. I would love to hear if there is a better way to write any of it. And, if you find bug, I'd be happy to know that too.

Questions

A couple of things specifically that I feel could be better would be the DC calculation. I wasn't sure how to approach applying the rush function only if the item was rushed. I also tried finding a place where I could apply functional composition, but I think I needed all the intermediate steps that I stop on.

Code

let baseDC casterLevel =
    5 + casterLevel

let rush dc =
    dc + 5

let ignoreRequirements requirements dc =
    dc + (5 * requirements)

let getBuildPrice basePrice =
    basePrice * 0.5

let getTime basePrice =
    floor (8.0 * basePrice / 1000.0)

let getMinBonusForNoCursed dc =
    dc - 6

let buildDaysWhileAdventuring isRushed buildTime =
    let adventuringBuildTime = buildTime / 4.0
    floor (if isRushed then adventuringBuildTime else adventuringBuildTime * 2.0)

[<EntryPoint>]
let main argv =
    printfn "%A" argv

    let isRushed = true
    let casterLevel = 1
    let requirementsIgnored = 1

    let basePrice = 5000.0
    let buildPrice = getBuildPrice basePrice

    let buildTime = getTime basePrice
    let daysAdventuring = buildDaysWhileAdventuring isRushed buildTime

    let DC =
        match isRushed with
        | false -> baseDC casterLevel |> ignoreRequirements requirementsIgnored
        | true -> baseDC casterLevel |> ignoreRequirements requirementsIgnored |> rush

    let minDC = getMinBonusForNoCursed DC

    printfn "Min/DC: %i/%i Cost: %.2f Days/Hours: %.1f/%.1f" minDC DC
        buildPrice daysAdventuring buildTime

    0 // Return code


texts:
Trying to write fast non dependency IP4 string validator for embedded system, It should counts leading zeros, values over 255 and other corrupted strings. Not sure if I missed something. Сan you guys take a look:

// Return 0 on error, store result to segs, if segs != 0.
int is_valid_ip4(const char *str, unsigned char* segs)
{
    int dots = 0;   // Dot count.
    int chcnt = 0;  // Character count within segment.
    int accum = 0;  // Accumulator for segment.

    // Catch NULL pointer.
    if (str == 0)
        return 0;

    // Process every character in string.
    for (;;)
    {
        // Check numeric.
        if (*str < '0' || *str > '9')
            return 0;

        // Prevent leading zeros.
        if (chcnt > 0 && accum == 0)
            return 0;

        // Accumulate and check segment.
        accum = accum * 10 + *str - '0';
        if (accum > 255)
            return 0;

        // Store result.
        if (segs)
            segs[dots] = (unsigned char)accum;

        // Advance other segment specific stuff.
        ++chcnt;
        ++str;

        // Finish at the end of the string when 3 points are found.
        if (*str == '\0' && dots == 3)
            return 1;

        // Segment changeover.
        if (*str == '.')
        {
            // Limit number of segments.
            ++dots;
            if (dots == 4)
                return 0;

            // Reset segment values.
            chcnt = 0;
            accum = 0;
            ++str;
        }
    }
}


texts:
I've made this to pick the LQR parameters for my self balancing robots simulation. So to break down what I have done,
Randomly Create Population

I create a random population. The population is a list of lists having 4 parameters each of which is randomly generated. But I have applied bounds for them using the values I got from my manual tuning for my simulation.
 def population_create(p_size,geno_size,bounds):

 p = [ random_param(geno_size,bounds) for i in range(p_size)]
 return p

def random_param(g,b):
     return [random.uniform(b[i][0],b[i][1]) for i in range(g)]

Try it on Robot and Evaluate
2.Then I evaluate each parameter to see how much the wheels have rotated and how much the robot is inclined after one minute.
fitness = encoder_readings + tilt
So the closer the fitness is to zero the better the robot balances.
This is done for the whole population
Create next generation
3.Then I make the next generation with Mutation, Crossover and passing healthy individuals directly.
def population_reproduce(p,fitness):

    size_p = len(p)
    new_p = []

    dataframe = pd.DataFrame({"Param":p,"Fitness":fitness})
    dataframe = dataframe.sort_values(['Fitness'])
    dataframe = dataframe.reset_index(drop=True)

    sorted_p = dataframe['Param'].tolist()

    elite_part = round(ELITE_PART*size_p)
    new_p = new_p + sorted_p[:elite_part]

    for i in range(size_p-elite_part):
        mom = p[random.randint(0,size_p-1)]
        dad = p[random.randint(0,size_p-1)]
        child = crossover(mom,dad)
        child = mutate(child)
        new_p.append(child)

    return new_p

def crossover(p1,p2):

    crossover = []
    locii = [random.randint(0,8) for _ in range(len(p1))]

    for i in range(len(p1)):
        if locii[i]>4:
            crossover.append(p2[i])
        else:
            crossover.append(p1[i])

    return crossover

def mutate(c):
    size = len(c)
    for i in range(size):
        if random.random()< MUTATION_PROBABILITY:
            c[i] += random.gauss(c[i]/50,MUTATION_DEVIATION)

    return c

This continues for some generations.
These are the links to the full codes.
Genetic Algorithm Supervisor
Population Script
Robot Controller
I would very much appreciate if you could take a look and let me know if this is a correct implementation of a genetic algorithm.
One observation I made is that the fitness doesn't converge to a lower value after each iteration. It randomly goes up and down. Could this be because of some inconsistency in my stimulation on Webots or is it a mistake in my code thats causing this?


texts:
I wanted to test the performance of concurrent http request in Go against node.js:

package main

import (
  "fmt"
  "time"
  "strconv"
  "net/http"
)

var responseCounter = 0
var requestCounter = 0
var count=0
var ch = make(chan int)

func sendRequest(){
    go func() {
        requestCounter++
        url := "https://www.google.co.in/#q=search_" +strconv.Itoa(requestCounter)
        resp, err := http.Get(url)
        if err != nil {
            fmt.Printf("\nError",err)
        }
        defer resp.Body.Close()
        count++
        ch <- count
        sendRequest()
    }()
}

func main() {

    for i := 1; i<100; i++{
        sendRequest()
    }

    for {
        select {
            case r := <-ch:
                fmt.Printf("\nChannel ",r)
            case <-time.After(50 * time.Millisecond):
                //sendRequest()
        }
    }
}

When I run this code the CPU usage goes very high (around 90%). Is there something wrong with this code? Have I used the Goroutines correctly?


texts: Is this a correct way to use Factory Pattern?

texts:
I have an abstract class which implements the IDataCreator interface:

public interface IDataCreator
{
    public String getDataString();
}

public abstract class AbstractCreator implements IDataCreator
{
    protected IProject p;

    public AbstractCreator(IProject p) {
       this.p = p;
    }

    public abstract String getDataString();
}

Then I have 5 concrete classes which extend AbstractCreator and implement the getDataString() method:

public class ProjectManagerCreator extends AbstractCreator
{
    public ProjectManagerCreator(IProject p) {
       super(p);
    }

    @Override
    public String getDataString() {
       if(p.getLead() != null) {
           String lead = p.getLead().getName();
           return lead;
       }
       return "";
    }
}

Factory class is implemented like this:

public class ProjectDataCreatorFactory
{
    IProject p = null;

    public ProjectDataCreatorFactory(IProject p) {
       this.p = p;
    }

    /**
     * Factory method which constructs a object from a given string value.
     *
     * @param column string of the column name TODO: Implement a interface which maps the strings into static variables
     * @return object which implements the {@link IDataCreator} interface
     */
    public IDataCreator createFromString(String column) {
        IDataCreator creator = null;
        if(column.equals("name")) {
           return new URLCreator(p);
        } else if(column.equals("status")) {
           return new ProjectStatusCreator(p);
        } else if(column.equals("manager")) {
           return new ProjectManagerCreator(p);
        } else if(column.equals("setupdate")) {
           return new ProjectDateCreator(p, ProjectDateCreator.CREATION);
        } else if(column.equals("updatedate")) {
           return new ProjectDateCreator(p, ProjectDateCreator.UPDATED);
        }
        return creator;
    }
}

The factory class is called like this:

ProjectDataCreatorFactory factory = new ProjectDataCreatorFactory(p);
String s = factory.createFromString("name").getDataString();

Question

Is this the (or a) correct way to use the Factory Pattern? Is the approach with an interface and an abstract class a good design?


texts: Set the entitlement of a case based on record type

texts:
This is my first salesforce code. It seems to me there is too much data lookup but I don't know enough about saleforce apex coding to say.

The purpose of the code is to set the entitlement based on the record type when inserting a new Case record.

The business reason for this code is the proper assignment of Entitlements (SLAs) for the various Case types.

The code runs before the record is inserted into the table. It enforces the relationship between Case type and Entitlement type.

trigger SetCaseEntitlementOnInsert on Case (before insert) {
    System.debug('SetCaseEntitlementOnInsert executed');

    // 1) Loop through the Case(s) to be inserted.
    // 2) Get the Entitlement for each based on the RecordType.
    // 3) Retrieve the Entitlement.
    // 4) Assign the Entitlement to the Case

    for(Case c : Trigger.New) {
        RecordType recordType = [SELECT Id, Name FROM RecordType WHERE Id =: c.RecordTypeId];
        String recordTypeName = recordType.Name;

        if(recordTypeName == 'Trouble Tickets') {
            Entitlement entitlement = [SELECT Id, Name FROM Entitlement WHERE Name = 'Priority 1'];
            c.EntitlementId = entitlement.Id;
        } else if (recordTypeName == 'Access Request/New Hire') {
            Entitlement entitlement = [SELECT Id, Name FROM Entitlement WHERE Name = 'Priority 2'];
            c.EntitlementId = entitlement.Id;
        } else if (recordTypeName == 'Purchase Order') {
            Entitlement entitlement = [SELECT Id, Name FROM Entitlement WHERE Name = 'Priority 3'];
            c.EntitlementId = entitlement.Id;
        } else {
            // Termination
            Entitlement entitlement = [SELECT Id, Name FROM Entitlement WHERE Name = 'Priority 4'];
            c.EntitlementId = entitlement.Id;
        }
    }
}


texts:
I am repeating this code at lot of places:

public class ProductTypeService : IProductTypeService
{
    public async Task<IList<ProductType>> GetAllAsync(int sectionId = -1)
    {
        string key = "ProductTypeService_" + "GetAllAsync" + sectionId;
        var list = _memoryCacheService.Get<IList<ProductType>>(key);
        if (list == null)
        {
            list = await _repository.GetAllAsync(sectionId);
            _memoryCacheService.Save(key, list);
        }
        return list;
    }

public class VendorService : IVendorService
{
    public async Task<IList<Vendor>> GetAllAsync()
    {
        string key = "VendorService_" + "GetAllAsync";
        var list = _memoryCacheService.Get<IList<Vendor>>(key);
        if (list == null)
        {
            list = await _repository.GetAllAsync();
            _memoryCacheService.Save(key, list);
        }
        return list;
    }

The key is the combination of class + method + parameter. The only change is _repository.XX(XX, XX, ...........). How can I make it DRY?


texts:
Given an unsorted array. The task is to find all the star and super
  star elements in the array. Star are those elements which are strictly
  greater than all the elements on its right side. Super star are those
  elements which are strictly greater than all the elements on its left
  and right side.

  Note: Assume first element (A[0]) is greater than all the elements on
  its left side, And last element (A[n-1]) is greater than all the
  elements on its right side.

  Input: The first line of input contains an integer T denoting the
  number of test cases. Then T test cases follow. Each test case
  consists of two lines. First line of each test case contains an
  Integer N denoting size of array and the second line contains N space
  separated elements.

  Output: For each test case, print the space separated star elements
  and then in new line print super star elements. If no super star
  element present in array then print "-1".

  Constraints: 1<=T<=200 1<=N<=106 1<=A[i]<=106

  Example: Input:

2
6
4 2 5 7 2 1
3 8 6 5

  Output:

7 2 1
7
8 6 5
8

My approach:

/*package whatever //do not write package name here */

import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.Collections;
import java.util.Set;
import java.util.*;

class GFG {

    private static void findElems (int [] arr)
        {
            int len = arr.length;

            HashMap<Integer,Integer> stars = new HashMap<>();

            stars.put(arr[len-1],len - 1);

            int maxRight = arr[len - 1];

            for (int i = len - 2; i >=0; i--)
                {
                    if (arr[i] > maxRight)
                    {
                         stars.put(arr[i],i);
                         maxRight = arr[i];
                    }
                }

           int maxStar = Collections.max(stars.keySet());

           int maxStarInd = (Integer)stars.get(maxStar);
           int flag = 0;

           for (int i = 0; i < len;i++)
            {
                if  (i != maxStarInd)
                    {
                        if (arr[i] == maxStar)
                            {
                                flag = 1;
                                break;
                            }
                    }
            }

            Set <Integer> starSet = stars.keySet();

            //Integer [] starKeys = starSet.toArray (new Integer[stars.size()]);
            LinkedList <Integer> revSet = new LinkedList<>(starSet);
            Collections.sort(revSet, Collections.reverseOrder());

            Iterator<Integer> iter = revSet.iterator();

            while (iter.hasNext())
                {
                    System.out.print(iter.next() + " ");
                }

            System.out.println();
         /*   for (int i = starKeys.length - 1; i >= 0; i--)
                {
                    System.out.println(starKeys[i]);
                }
        */
            if (flag == 0)
                {
                    System.out.println(maxStar);
                }
            else
                {
                   System.out.println(-1);
                }

        }

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

        int numTests = sc.nextInt();

        for (int i = 0; i < numTests; i++)
            {
                int size = sc.nextInt();
                int [] arr = new int[size];

                for (int j = 0; j < size; j++)
                    {
                        arr[j] = sc.nextInt();
                    }

                findElems(arr);
            }

    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?
Is my code very redundant?

Reference


texts: Dynamically create array with nested objects/array

texts:
I need help to dynamically create an array with nested objects holding again an array of objects each. The structure is as follows:

tiles=[
     { "row": [{isChecked: true, src: ''}, {isChecked: true, src: ''}, {isChecked: true, src: ''}] },
     { "row": [{isChecked: true, src: ''}, {isChecked: true, src: ''}, {isChecked: true, src: ''}] },
     { "row": [{isChecked: true, src: ''}, {isChecked: true, src: ''}, {isChecked: true, src: ''}] },
     { "row": [{isChecked: true, src: ''}, {isChecked: true, src: ''}, {isChecked: true, src: ''}] }
  ];

However, the amount of row objects and amount of rows is dynamic. In the example above, it's 3 x 4.

My current approach is a simple nested loop:

updateTileEditor(x: number, y: number) {
  this.tiles = [];
  for (var i = 0; i < y; i++) {
    let helperArray = [];
    for (var j = 0; j < x; j++) {
      helperArray.push({ isChecked: true, src: '' });
    }
    this.tiles.push({ "row": helperArray });
  }
}

Could you perhaps propose a more feasable approach to this?

Be aware that every nested object of the nested array must be a different object. In other words, the objects can not point to the same reference.

Thanks in advance!


texts:
I've started learning C++ recently and want from what I've gathered smart pointers are the way to go when storing stuff on the free store. I want to make sure I've got the basic hang of C++(11) correctly. I've implemented a very basic vector class (a mathematical vector) and would greatly appreciate if anyone would point out if I'm doing something wrong or that could be done better.

Vector.h

#ifndef VECTOR
#define VECTOR

#include <memory>

class Vector {
private:
    int x;
    int y;
    int z;

public:
    Vector(int x, int y, int z);
    ~Vector();

    std::unique_ptr<Vector> operator + (Vector* vector);

    int GetX() { return x; }
    int GetY() { return y; }
    int GetZ() { return z; }

    void SetX(int x) { this->x = x; }
    void SetY(int y) { this->y = y; }
    void SetZ(int z) { this->z = z; }
};

#endif

Vector.cpp

#include <memory>
#include <iostream>
#include "Vector.h"

Vector::Vector(int x, int y, int z) : x(x), y(y), z(z) {
    std::cout << "Constructed a Vector instance with elements ( " << x << ", " << y << "," << z << " )." << std::endl;
};

Vector::~Vector() {
    std::cout << "Destructed a Vector instance with elements ( " << x << ", " << y << "," << z << " )." << std::endl;
}

std::unique_ptr<Vector> Vector::operator + (Vector* vector) {
    std::unique_ptr<Vector> result = std::make_unique<Vector>(0, 0, 0);

    result->SetX(this->x + vector->GetX());
    result->SetY(this->y + vector->GetY());
    result->SetZ(this->z + vector->GetZ());

    return result;
};

Usage

#include <iostream>
#include <memory>
#include "Vector.h"

int main() {
    std::unique_ptr<Vector> v1 = std::make_unique<Vector>(1, 2, 3);
    std::unique_ptr<Vector> v2 = std::make_unique<Vector>(3, 2, 1);
    std::unique_ptr<Vector> vr = *(v1.get()) + v2.get();
}

When using the overloaded operator (+) it looks a bit ugly but it's the way I found that worked when using unique_ptr<T>. One thing I'm doubting if I'm doing "correctly" is returning a unique_ptr<T>. Should I return a value instead and then create a unique_ptr<T> from that instead?


texts: Finding suggested flight destinations from database in Golang

texts:
This is my first Go project. Coming from a Java developer background, this code just smells very bad. But, cannot figure out better way to do this.

It's a small app to find suggested flight destinations based on one or more origins (by their airport-codes, called codesbelow).
Basically finding flights that have the same destination and about the same arrival times.

// SuggestDestinations takes a list of origin airport codes, an earliest arrival time and a latest arrival time and
// returns a map, where the destination is the key, and the suggested flights.
func (service *FlightService) SuggestDestinations(codes []string, earliestArrival, latestArrival time.Time) (destinationMap map[string][]internal.Flight, err error) {
    rows, err := service.db.Query(selectFlightsSQL, pq.Array(codes), earliestArrival, latestArrival)
    if err != nil {
        return nil, err
    }
    defer rows.Close()
    var m map[string][]internal.Flight
    m = make(map[string][]internal.Flight)
    for rows.Next() {
        var a internal.Flight
        var origin, destination, airline string
        if e := rows.Scan(&origin, &destination, &airline, &a.Departure, &a.Arrival); err != nil {
            return nil, e
        }
        a.Origin, err = service.GetAirport(origin)
        a.Destination, err = service.GetAirport(destination)
        a.Airline, err = service.GetAirline(airline)
        // Filter out destinations which is one of the origins
        if !contains(codes, a.Destination.Code) {
            m[a.Destination.Code] = append(m[a.Destination.Code], a)
        }
    }

    // Delete destinations for which there are not flights from every given origin
    for k := range m {
        if !containsAllCodes(m[k], codes) {
            delete(m, k)
        }
    }

    return m, nil
}

Where containsAllCodes looks like this:

func containsAllCodes(flights []internal.Flight, codes []string) bool {
containsAllOrigin := true
for _, c := range codes {
    containsOrigin := false
    for _, f := range flights {
        containsOrigin = containsOrigin || f.Origin.Code == c
    }
    containsAllOrigin = containsAllOrigin && containsOrigin
    }
    return containsAllOrigin
}


texts:
This game allows one to either pick their own lottery numbers or have them generated and checks them with the most recent numbers, jackpot, and multiplier. I use concepts such as random, for loops, raw_input, and logic. I would it appreciated if it were reviewed by someone more experienced.

import random
choice = raw_input("Do you want to randomly generate numbers, or pick them? (Enter 'R' for random, 'P' for pick.")
if choice == ('R'):
  one = random.randint(1,69)
  two = random.randint(1,69)
  three = random.randint(1,69)
  four = random.randint(1,69)
  five = random.randint(1,69)
  pball = random.randint(1,26)
elif choice == ('P'):
  one = int(raw_input("Please pick your 1st number, between 1 and 69."))
  two = int(raw_input("Please pick your 2nd number, between 1 and 69."))
  three = int(raw_input("Please pick your 3rd number, between 1 and 69."))
  four = int(raw_input("Please pick your 4th number, between 1 and 69."))
  five = int(raw_input("Please pick your 5th number, between 1 and 69."))
  pball = int(raw_input("Please pick your Powerball number, between 1 and 26."))
  if ((one or two or three or four or five) > 69) or pball > 26 or ((one or two or three or four or five or pball) < 1): #In case the entered numbers are too high or too low.
    print "Please choose a number between 1 and 69."
elif choice != ('R' or 'P'): #In case invalid input is given.
  print "Please enter either 'R' for random or 'P' for picking."
human = [one, two, three, four, five, pball]
print human
#August 15, 2018 Powerball
real = [12,15,28,47,48,16]
jackpot = 40000000
multiplier = 2
def powerball(human,real,jackpot,multiplier):
  x = raw_input("Do you want to buy the multiplier for $1? ('Y' or 'N')")
  if x == 'Y':
    pass
  elif x == 'N':
    multiplier = 1
  p = 0 #Prize
  i = 0 #Index
  m = 0 #Matches
  if human[5] == real[5]: #If you only get the powerball right.
    p = 4
  for i in range(0,5): #If you only get normal numbers, no powerball.
    if human[i] in real:
      m += 1
    i += 1
    if m == 3:
      p = 7
    elif m == 4:
      p = 100
    elif m == 5:
      p = 1000000
  m = 0
  for i in range(0,5): #If you get normal numbers along with the powerball.
    if (human[i] in real) and (human[5] == real[5]):
      m += 1
    i += 1
    if m == 1:
      p = 4
    elif m == 2:
      p = 7
    elif m == 3:
      p = 100
    elif m == 4:
      p = 50000
    elif m == 5:
      p = jackpot
  p *= multiplier
  if p > 0:
    return "Congratulations, you won $%s!" % (p)
  elif p == 0:
    return "Sorry, you didn't win anything, try again next time."
print powerball(human, real, jackpot, multiplier)


texts: The answer to life, the universe, and Project Euler

texts:
I've never did a real Project Euler in my life, so I figured it was about to do one.
And what better Project Euler to start with than Problem 42?
Project description from Project Euler:

By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt, a 16K text file containing nearly two-thousand common English words, how many are triangle words?

I realized quite quickly that to determine if a number is triangular, you can solve a quadratic equation.
The part that I'm the least proud of is how the words are read from the URL. Reading the whole line into memory (the whole text file is essentially one whole line) feels unnecessary, just to then split it into words, cut off the quotation marks, and read it.
Even though I could keep the quotation marks and add a filter in wordValue, it feels like it makes more sense to change the string before passing it there.
I considered using StreamTokenizer to read the words, but that class felt old and ugly and not Java 8-ish at all.
The project euler assignment only asks to print the count of triangular numbers, I figured that it doesn't hurt to also write them and their word values - this can be easily disabled by removing the .peek(System.out::println) lines.
public class ProjEuler42 {

    public static int wordValue(String str) {
        return str.toUpperCase().chars().map(ch -> ch - 'A' + 1).sum();
    }

    public static boolean isTriangular(int number) {
        // The Nth triangular number, T(n), is n*(n+1)/2,
        // by doing T(n) - number = 0 we get a quadratic equation.
        // If the solution to this equation is an integer, it is a triangular number
        double n = Math.round(-0.5 + Math.sqrt(0.25 + 2 * number));
        return 0.5 * n * (n + 1) == number;
    }

    public static void main(String[] args) throws IOException {
        URL url = new URL("https://projecteuler.net/project/resources/p042_words.txt");
        InputStream in = url.openStream();
        try (BufferedReader reader = new BufferedReader(
          new InputStreamReader(in, StandardCharsets.UTF_8))) {
            long count = reader.lines()
                    .flatMap(line -> Arrays.stream(line.split(",")))
                    .map(str -> str.substring(1, str.length() - 1))
                    .filter(str -> isTriangular(wordValue(str)))
                    .peek(System.out::println)
                    .mapToInt(ProjEuler42::wordValue)
                    .peek(System.out::println)
                    .count();
            System.out.println("There are a total of " + count + " triangular words");
        }
    }
}

From a Project Euler perspective, and from a Java 8 perspective, is there anything to improve?


texts:
I've been writing this data structure for a few days, and now I'm really curious about what it actually is, and to get some critique on my logic.

A branch, based on this usage, exists when a HEAD node contains at least one node of the same type referenced.

The purpose of the structure is to have branches that are arranged by type. Each node on the branch has a reference to the next node on the branch (always of the same type) and an entry point to a Subdata branch. Subdata in this case being an instance of a class that inherits from the AchievementNode. When subdata is added and it is the first of it's kind on that branch it has the HEAD tag applied to it, additionally, it also has a tag that contains the metadata of the type of data contained (to bypass the typeof calls).

Implementation:

public abstract class AchievementNode : ScriptableObject
{
    public enum NodeTypes
    {
        NONE   = 0x0,
        HEAD   = 0x1,
        TAIL   = 0x2,
        TYPE   = 0x4,
        DATA   = 0x8,
        LEVEL  = 0x16,
        GLOBAL = 0x32
    }

    public NodeTypes nodeType;

    public AchievementNode nextOfType;

    public AchievementNode headOfSubnode;

    public void OnEnable ()
    {
        hideFlags = HideFlags.HideAndDontSave;
    }

    public virtual void Init(NodeTypes type, int enumData)
    {
        nodeType = type;
    }

    protected void AddNode(NodeTypes type, AchievementNode originNode, AchievementNode newNode)
    {
        //Create SubNode branch notch when types mismatch.
        if((originNode.nodeType & type) != type)
        {
            //If Has subNode Data Run to the end and assign new node
            if(originNode.headOfSubnode!=null)
            {
                newNode.nodeType = type | NodeTypes.TAIL;
                AppendToTail(type,GetEndOfBranch(originNode.headOfSubnode),newNode);
            }//Search for proper SubNodeTypes then add. Wicked Recursion warning here...
            else if((originNode.headOfSubnode.nodeType & type) != type)
            {
                Debug.LogError("Do Gnarly Search To Find!");
                return;
            }//Doesn't have subnode... add new Subnode.
            else
            {
                newNode.nodeType = type | NodeTypes.HEAD | NodeTypes.TAIL;
                originNode.headOfSubnode = newNode;
            }
        }
        else
        {
            //Add to the current branch
            newNode.nodeType = type | NodeTypes.TAIL;
            AppendToTail(type,GetEndOfBranch(originNode),newNode);
        }
    }

    private void AppendToTail(NodeTypes type,AchievementNode tailNode, AchievementNode newNode)
    {
        if((tailNode.nodeType & NodeTypes.HEAD) == NodeTypes.HEAD)
        {
            tailNode.nodeType = tailNode.nodeType | type;
        }
        else
        {
            tailNode.nodeType = type;
        }
        tailNode.nextOfType = newNode;
    }

    protected AchievementNode GetEndOfBranch(AchievementNode currentNode)
    {
        //Special Case where Node is HEAD and TAIL.
        if((currentNode.nextOfType.nodeType & NodeTypes.TAIL) != NodeTypes.TAIL)
        {
            return GetEndOfBranch(currentNode.nextOfType);
        }
        else
        {
            return currentNode;
        }
    }

    protected void SetType(NodeTypes type)
    {
        nodeType = type;
    }

    protected virtual AchievementNode FindInHierarchy(NodeTypes nodeCheck, AchievementNode currentNode)
    {
        if(currentNode == null)
        {
            return null;
        }
        else if((currentNode.nodeType & nodeCheck) == nodeCheck)
        {
            return currentNode;
        }
        else
        {
            return FindInHierarchy(nodeCheck,currentNode.nextOfType);
        }
    }
}


texts:
I need to map a sequence of bits that represents a float into a sequence of bytes by this rule: the value 1 maps to the value 255 and the value 0 maps to the value 0.

This is the code I have now:

int FloatToBit(int *buffer, int startIndex, float value) {
  int fl = *(int*)&value;
  int i = 0;
  for (; i < sizeof(float) * 8; ++i) {
    buffer[startIndex + i] = ((1 << i) & fl) != 0 ? 255 : 0;
  }
  return i;
}

The code above is working, still I need something faster. Is it possible to improve its performance?

Edit 1:
I have created an online benchmark for this function.

Edit 2:
Using buffer[startIndex+i] = (unsigned char)-((fl>>i)&1) as @matt-timmermans suggested in the original question. Looks like there is no evident performance improvement.
Online benchmark.

Edit 3:
This benchmark shows that the approach suggested by @greybeard is ~29 times faster than the original implementation.

Edit 4:
Created a benchmark that measures all the suggested approaches.


texts: Phone Number Extracting using RegEx And HtmlAgilityPack

texts:
I've written this whole code to extract cell numbers from a website. It is extracting numbers perfectly but very slowly, and it's also hanging my Form while Extracting.

Imports HtmlAgilityPack
Imports System.Text.RegularExpressions
Public Class Extractor

Shared doc As New HtmlAgilityPack.HtmlDocument()

Public Shared Function ScrapLinks(TextBox1 As TextBox, ListBox1 As ListBox, lbllinks As Label)
Dim hw As New HtmlWeb()
Try
    doc = hw.Load(TextBox1.Text)
    doc.LoadHtml(doc.DocumentNode.SelectSingleNode("//*[@id='ad_list']").InnerHtml())

    For Each link As HtmlNode In doc.DocumentNode.SelectNodes("//a[@href]")

        Dim hrefValue As String = link.GetAttributeValue("href", String.Empty)

        If hrefValue.Contains("/detail/") Then
            If Not ListBox1.Items.Contains(hrefValue) Then
                ListBox1.Items.Add(hrefValue)
            End If
        End If
    Next

Catch ex As Exception
    MsgBox("Error " + ex.Message)

End Try
Return Nothing

End Function

Public Shared Function Scrapnums(lstbox As ListBox,lstnum As ListBox)
Try

    Dim hw As New HtmlWeb()
    doc = hw.Load(lstbox.SelectedItem)

    Dim data = doc.DocumentNode.SelectSingleNode("//*[@class='det_ad f_left']").InnerText

    Dim m As Match = Regex.Match(data, "(\+92|0092)-?\d{3}-?\d{7}|\d{11}|\d{4}-\d{7}")

    If Not lstnum.Items.Contains(m.Value) Then

        lstnum.Items.Add(m.Value)

    End If

Catch ex As Exception

End Try
Return Nothing

End Function

End Class


texts:
I decided to not use heap in my program and create a custom memory manager to retrieve memory chunks from a big global array of uint8_t(u8). I chose u8 since 8 bits is a byte. The very big MEMORY_BLOCK_SIZE is not a problem since in Release builds the compiler will remove the unused bytes. I keep track of free memory chunks with something i call "lookups".
#include <assert.h>

// NOTE: null is a redefinition of NULL
// NOTE: u8 = uint8_t
// NOTE: u64 = uint64_t

#define MEMORY_BLOCK_SIZE 8388608
#define MEMORY_LOOKUPS 8

static u8 memoryBlock[ MEMORY_BLOCK_SIZE ];
static u8* memoryLookups[ MEMORY_LOOKUPS ];
static u64 memoryLookupsSizes[ MEMORY_LOOKUPS ];

void memoryInit( void )
{
     memoryLookups[ 0 ] = memoryBlock;
     memoryLookupsSizes[ 0 ] = MEMORY_BLOCK_SIZE;
}

u8* requestMemoryChunk( u64 size )
{
     assert( size );

     u8* usablePtr = null;
     u64 ptrPosition;

     for( u64 i = MEMORY_LOOKUPS; i >= 0; --i )
     {
          if( ( !( memoryLookups[ i ] ) ) &&
                ( memoryLookupsSizes[ i ] >= size ) )
          {
                usablePtr = memoryLookups[ i ];
                ptrPosition = i;
                break;
          }
     }

     assert( usablePtr );

     u8* block = usablePtr;

     memoryLookupsSizes[ ptrPosition ] -= size;

     if( !( memoryLookupsSizes[ ptrPosition ] ) )
          memoryLookups[ ptrPosition ] = null;
     else
          memoryLookups[ ptrPosition ] = usablePtr + size;

     return block;
}

void freeMemoryChunk( u64 size, u8* block )
{
     assert( block && size );

     for( u64 i = 0; i < MEMORY_LOOKUPS; ++i )
     {
          if( ! ( memoryLookups[ i ] ) )
          {
                memoryLookups[ i ] = block;
                memoryLookupsSizes[ i ] = size;

                break;
          }
     }
}
```


texts: Different templates for various resource representations in Marionette

texts:
I'm making a Backbone-Marionette app with a file structure that matches restful verbs as much as possible. It looks something like this:

+ backbone
  + apps
    + student
      + show
      + list
      + new
    + lesson
      + show
      + new
      + edit

If, for example, the student show controller wanted to display a lesson, I simply execute a command that sends which lesson I want and the region in which it should be inserted like so:

App.execute( "show:lesson", lesson, someRegion );

This has mostly worked well, but now I need to create an email preview that contains a lesson. This representation of lesson show shouldn't look exactly like the existing lessons show - for example, it doesn't need edit and delete links.

What I'm doing now is adding a config object to my command above that looks like this...

App.execute( "show:lesson", lesson, someRegion, { template: "email" } );

... then I unpack that object in my Marionette controller and set it on the model. Now that it's piggy backed on the model, I use it to conditionally get the correct template in my view like so:

Show.Lesson = Backbone.Marionette.ItemView.extend({
  getTemplate: function() {
    if( this.model.get( "config" ).template === "email" ) {
      return "lessons/show/lesson_email";
    } else {
      return "lessons/show/lesson";
    }
  }
});

This feels a little weird to me, plus it doesn't quite work when getting templates for Marionette.CompositeViews. Should I be making completely new Marionette views for these email preview versions of my resource representations? Would it make more sense for my file structure to look like this?

+ backbone
  + apps
    + lesson
      + show
      + show_email
      + new
      + edit


texts: Viewmodel has lots of properties which bind to view

texts:
I created a configuration View. so it binds a lot of properties in Viewmodel. But I have a another class People and I want to assign properties of viewmodel to class People.

class Viewmodel
{
   public string name {get;set;}
   public int age {get;set;}
   public string nationality {get;set;}
   public string hobby {get;set;}
   …………

}

class People
{
   public string name {get;set;}
   public int age {get;set;}
   public string nationality {get;set;}
   public string hobby {get;set;}
   public People[] friends {get;set;}
   …………
   public void AddFriend(People people)
   {
    //add friend to this
   }
}

I have to write a function:

void Assign()
{
  People.name = Viewmodel.name;
  People.age= Viewmodel.age;
  …………
}

How could I refactor this function? I usually will define more than 10 properties in viewmodel.


texts: strategy pattern, good practices on how to switch between classes

texts:
i'm using an external API that posts products and orders into a marketplace, and it provides a class that in each request i have to specify an endpoint, user and password (token), it's something like this:

if($env == 'testing') {
    $endpoint = 'testing';
    $user = 'testing';
    $pass = 'testing';
} else {
    $endpoint = 'production';
    $user = 'production';
    $pass = 'production';
}

$itemSender = new ItemSender($endpoint, $user, $pass);
$orderSender = new OrderSender($endpoint, $user, $pass);

my first thought was to use the strategy pattern so i can have both testing and production environment, or even others environments, implementing an interface, i built something lie this:

interface EnviromentInterface () {

    function getEndpoint();
    function getUser();
    function getPassword();
}

class TestingEnvironment implements EnviromentInterface {

    private $endpoint;
    private $user;
    private $password;

    function getEndpoint() {
        return $this->endpoint;
        // return getFromConfigFile('API_ENDPOINT_TESTING');
    }

    function getUser() {
        return $this->user;
    }

    function getPassword() {
        return $this->password;
    }

}

class ProductionEnviroment implements EnviromentInterface {

    private $endpoint;
    private $user;
    private $password;

    function getEndpoint() {
        return $this->endpoint;
        // return getFromConfigFile('API_ENDPOINT_PRODUCTION');
    }

    function getUser() {
        return $this->user;
    }

    function getPassword() {
        return $this->password;
    }

}

and i would overwrite the parent's class construct to use the environment object, something like this:

class CustomItemSender extends ItemSender
{

    function __construct(EnviromentInterface $env)
    {
        parent::__construct($env->getEndpoint(), $env->getUser(), $env->getPassword());
    }
}

the problem is: how can i switch between these environment objects? i thought about using a switch/case, but if i need to implement more environments i have to add another if to the switch/case statment.

what would be a good aproach in this case?

important: all info/credentials about the testing and production environments are inside a config file, that in this case is an .env file


texts:
HTTP request is made, and a JSON string is returned, which needs to be parsed.
Example response:

{"urlkey": "com,practicingruby)/", "timestamp": "20150420004437", "status": "200", "url": "https://practicingruby.com/", "filename": "common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246644200.21/warc/CC-MAIN-20150417045724-00242-ip-10-235-10-82.ec2.internal.warc.gz", "length": "9219", "mime": "text/html", "offset": "986953615", "digest": "DOGJXRGCHRUNDTKKJMLYW2UY2BSWCSHX"}
{"urlkey": "com,practicingruby)/", "timestamp": "20150425001851", "status": "200", "url": "https://practicingruby.com/", "filename": "common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246645538.5/warc/CC-MAIN-20150417045725-00242-ip-10-235-10-82.ec2.internal.warc.gz", "length": "9218", "mime": "text/html", "offset": "935932558", "digest": "LJKP47MYZ2KEEAYWZ4HICSVIHDG7CARQ"}
{"urlkey": "com,practicingruby)/articles/ant-colony-simulation?u=5c7a967f21", "timestamp": "20150421081357", "status": "200", "url": "https://practicingruby.com/articles/ant-colony-simulation?u=5c7a967f21", "filename": "common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246641054.14/warc/CC-MAIN-20150417045721-00029-ip-10-235-10-82.ec2.internal.warc.gz", "length": "10013", "mime": "text/html", "offset": "966385301", "digest": "AWIR7EJQJCGJYUBWCQBC5UFHCJ2ZNWPQ"}

My code:

result = Net::HTTP.get(URI("http://index.commoncrawl.org/CC-MAIN-2015-18-index?url=#{url}&output=json")).split("}")

result.each do |res|
    break if res == "\n"
    #need to add back braces because we used it to split the various json hashes from the http request
    res << "}"
    to_crawl = JSON.parse(res)
    puts to_crawl
end

It works, but I'm sure there is a much better way to do it, or at least a better way to write the code.


texts:
I did the following Excercise:

  simulate single inheritance in C. Let each "base
     class" contain a pointer to an array of pointers to functions (to simulate
     virtual functions as freestanding functions taking a pointer to a "base
     class" object as their first argument). Implement "derivation" by
     making the "base class" the type of the first member of the derived class.

  For each class, initialize the array of "virtual functions" appropriately. To test the ideas, implement a version of "the old Shape example" with the base
  and derived draw() just printing out the name of their class. Use only
  language features and library facilities available in standard C.

I wonder if my approach is good? And as a side question: Is OOP relevant in practice with using c?

Edit: the goal is to simulate c++ like OOP constructs with the limited features of c.

#include <stdio.h>

typedef void(*pfct)(struct Shape*);

typedef struct {
    pfct draw;
}Vtable;

typedef struct{                 // "Base class"
    Vtable* pvtable;
}Shape;

typedef struct{                 // "Derived" from Shape
    Shape shape;
    int radius;
}Circle;

void draw(Shape* this)          // "Virtual function"
{
    (this->pvtable->draw)(this);
}

void draw_shape(Shape* this)
{
    printf("Drawing Shape\n");
}

void draw_circle(Shape* this)
{
    Circle* pcircle = (Circle*)this;
    printf("Drawing Circle with radius = %i\n",pcircle->radius);
}

Shape* init_shape()
{
    Shape* pshape = malloc(sizeof(Shape));
    Vtable* pvtable = malloc(sizeof(Vtable));
    pvtable->draw = &draw_shape;
    pshape->pvtable = pvtable;
    return pshape;
}

Circle* init_circle(int radius)
{
    Circle* pcircle = malloc(sizeof(Circle));
    pcircle->shape = *init_shape();
    pcircle->shape.pvtable->draw = &draw_circle;
    pcircle->radius = radius;
    return pcircle;
}

int main()
{
    Shape* myshape = init_shape();
    Circle* mycircle = init_circle(5);
    draw(myshape);
    draw(mycircle);

    getchar();
    return 0;
}


texts: Does my classes contain right destructors

texts:
Every Account has its owner who is Person The bank has list of owners. I am not sure if my destructors are right and delete bank will delete all elements of list<Account*>* v nad the list itself. Please help.

#include <iostream>
#include <vector>
#include <list>
using namespace std;
class Person{
public:
    char* name;
    int age;

    Person(char* name, int age){
        this->name = name;
        this->age = age;
    }
    ~Person(){
    }

    void show(){
        cout<<name<<" "<<age<<" yo";
    }
};

class Account{
public:
    Person& owner;
    double money;
    Account(Person* owner, double money):
        owner(*owner) , // this->owner = *owner;
        money(money)  { //Uninitialized reference member
    }

     void show(){
        cout<<"\n-------------\n";
        owner.show();
        cout<<endl;
        cout<<money<<"USD\n-------------";
    }
      ~Account(){
    }
};

class Bank{
public:
    list<Account*>* v;
    Bank(){
        v = new list<Account*>();
    }
    Account* openNewAccount(Person* client, double money){
        Account* r = new Account(client, money);
        v->push_back(r);
        return r;
    }
    void zmienWlasciciela(Person& o, Account* r){

        r->owner = o;
    }
    void usunRachunek(Account* r){
        cout<<"\n\n\nUSUNALEM"<<endl;
       v->remove(r);
       delete r;
    }
    void show(){
    for (list<Account*>::iterator it = v->begin(); it != v->end(); ++it){
        (*it)->show();
    }
    }
    ~Bank(){
        delete v;
    }
};

int main(){
    Bank* bank = new Bank();
    Person* thomas = new Person("thomas", 34);
    Account* r1 =  bank->openNewAccount(thomas, 64363.32);
    Account* r2 =  bank->openNewAccount(thomas, 41251.54);
    Account* r3 =  bank->openNewAccount(thomas, 3232.32);
    bank->show();

    Person* margaret = new Person("Margaret", 23);
    bank->zmienWlasciciela(*margaret, r2);
    cout<<"I have changed owner of account r2"<<endl;
    bank->show();
    cout<<"I have deleted account r3"<<endl;
    bank->usunRachunek(r3);
    bank->show();

    delete bank;
    return 0;
}


texts:
Since I've looked far and wide for a good example of this to no avail, I have created my own using the JSONArray and JSONObject classes. It took me a while to realize that the push method for JSONObject overwrites everything previously pushed.

public static JSONArray getJSON(String url) throws IOException, JSONException, URISyntaxException, TransformerException{
        HttpClient httpClient = new DefaultHttpClient();
        JSONArray jArray = new JSONArray();
        Object[] q = null;
        Deque<String> queue = new ArrayDeque<String>();

        try{
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            int responseCode = response.getStatusLine().getStatusCode();
            logger.info("Response Code : " + responseCode);
            if (responseCode != 404){
                logger.info("Response" + response.getEntity().getContent());
                try(BufferedReader reader = new BufferedReader(
                       new InputStreamReader(
                               response.getEntity().getContent()))) {

                 if(reader != null){
                     String aux = "";
                     while ((aux = reader.readLine()) != null) {
                         queue.add(aux);
                     }
                     q = queue.toArray();

                     for(int i = 0; i < q.length; i++){

                         String[] row = q[i].toString().split(",");

                            JSONObject json = new JSONObject();
                            json.put("col0", row[0]);
                            json.put("col1", row[1]);
                            json.put("col2", row[2]);
                            json.put("col3", row[3]);
                            json.put("col4", row[4]);
                            json.put("col5", row[5]);

                            jArray.put(json);

                     }
                 }
                }

             }
                }
                return null;

             }
             return jArray;
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
    }


texts: A Simple Unix Filter in Racket - Learning the Racket Way

texts:
I've written the following simple filter in Racket as my first Racket program and am wondering if I am writing it in an "idiomatic Racket style".

#! /usr/bin/env racket
#lang racket

(require racket/cmdline)

(define a-prolog-mode? (make-parameter #f))

;; parses the options passed on the command-line
(command-line
 #:program "patoms"
 #:once-any
 [("-a" "--aprolog") "output as A-Prolog code"
                     (a-prolog-mode? #t)])

;; dlv-input? : string -> boolean
;; Returns True if the given text corresponds to the output of DLV
;; and False otherwise. DLV's output is prefixed by one of the following
;; strings: "DLV", "{", or "Best model".
(define (dlv-input? text)
  (regexp-match? #rx"^DLV|^{|^Best model" text))

;; text->answer-sets : string -> list of strings
;; Returns a list comprised of all of the answer sets in the given text.
(define (text->answer-sets text)
  (cond
    [(dlv-input? text) (regexp-match* #rx"{(.*?)}" text #:match-select cadr)]
    [else null]))

;; write-as-code : string
;; Writes the given answer set in plain text form to standard output.
(define (write-as-text answer-set)
  (let ([literals (map string-trim (string-split answer-set ","))])
    (cond
      [(empty? literals) (printf "~a~n" "{}")]
      [else (for-each (λ (literal) (printf "~a~n" literal)) literals)])
    (printf "~a~n" "::endmodel")))

;; write-as-code : string
;; Writes the given answer set as A-Prolog code to standard output.
(define (write-as-code answer-set)
  (let ([literals (map string-trim (string-split answer-set ","))])
    (for-each (λ (literal) (printf "~a.~n" literal)) literals)
    (printf "~a~n" "%%endmodel")))

;; main
;; Serves as the main function of the program. If a-prolog-mode is specified
;; by the user via the command-line, all of the answer sets that may be parsed
;; from standard input are written to standard output as A-Prolog. Otherwise
;; the answer sets are written in a plain text format.
(define (main)
  (let* ([text (port->string (current-input-port))]
         [answer-sets (text->answer-sets text)])
    (cond
      [(a-prolog-mode?) (for-each write-as-code answer-sets)]
      [else (for-each write-as-code answer-sets)])))

(main)

In general, any and all feedback would be very much appreciated given that this is my first foray into Racket.

Thank you kindly in advance.


texts:
Apart from general JavaScript knowledge, this snippets requires someone who knows how to properly use Google Analytics API.

To log errors on my site, I use this code:

try {
  window.addEventListener("error", function(e) {
    var file = e.filename.substr(e.filename.lastIndexOf("/")+1);
    // for some reason, filename sometimes contained path, sometimes just name
    if(file.length==0)
      file = e.filename;
    var msg = file+":"+e.lineno+":"+e.colno+" \""+e.message+"\" Browser: "+navigator.userAgent;

    if(typeof ga=="function") {
      ga('send', 'event', 'jserror', 'click', msg, {'transport': 'beacon'});
    }
    else {
      // This is executed when google analytic is not loaded
      // which happens in debug mode
      console.error(msg);
    }
  });
}
catch(e) {
  console.warn("Failed to add error callback.");
}

I'm especially interested to know whether I'm using the google analytics API correctly. Maybe I could log the data about error in multiple columns?

I'm new to google analytics so feedback is very valuable for me.


texts: PHP MYSQL loop to check if LicenseID Values are contained in mysql DB

texts:
I have some troubles to find the right loop to check if some values are contained in mysql DB. I'm making a software and I want to add license ID. Each user has x keys to use.

Now when the user start the client, it invokes a PHP page that check if the Key sent in the POST method is stored in DB or not.

If that key isn't store than I need to check the number of his keys. If it's > than X I'll ban him otherwise i add the new keys in the DB.

I'm new with PHP and MYSQL. I wrote this code and I would know if I can improve it.

<?php

$user = POST METHOD
$licenseID = POST METHOD

$resultLic= mysql_query("SELECT  id , idUser , idLicense FROM license WHERE idUser = '$user'") or die(mysql_error());
$resultNumber = mysql_num_rows($resultLic);
$keyFound = '0'; // If keyfound is 1 the key is stored in DB

while ($rows = mysql_fetch_array($resultLic,MYSQL_BOTH)) {
   //this loop check if the $licenseID is stored in DB or not
    for($i=0; $i< $resultNumber ; i++) {
        if($rows['idLicense'] === $licenseID) {
            //Just for the debug
            echo("License Found");
            $keyFound = '1';
            break;
    }
    //If key isn't in DB and there are less than 3 keys the new key will be store in DB

    if($keyfound == '0' && $resultNumber < 3) {
        mysql_query( Update users set ...Store $licenseID in Table)
    }

    // Else mean that the user want user another generated key (from the client) in the DB and i will be ban (It's wrote in TOS terms that they cant use the software on more than 3 different station)
    else {
        mysql_query( update users set ban ='1'.....etc );
    }
}

?>

I know that this code seems really bad so i would know how i can improve it. Someone Could give me any advice?

I choose to have 2 tables: users where all information about the users is, with fields id, username, password and another table license with fields id, idUsername, idLicense (the last one store license that the software generate)


texts:
Here is a lazy dictionary with test cases.

"""
A dictionary whose values are only evaluated on access.
"""
from functools import partial

from UserDict import IterableUserDict

class LazyDict(IterableUserDict, object):
    """
    A lazy dictionary implementation which will try
    to evaluate all values on access and cache the
    result for later access.
    """

    def set_lazy(self, key, item, *args, **kwargs):
        """
        Allow the setting of a callable and arguments
        as value of dictionary.
        """
        if callable(item):
            item = partial(item, *args, **kwargs)
        super(LazyDict, self).__setitem__(key, item)

    def __getitem__(self, key):
        item = super(LazyDict, self).__getitem__(key)
        try:
            self[key] = item = item()
        except TypeError:
            pass
        return item

def test_lazy_dict():
    """
    Simple test cases for `LazyDict`.
    """

    lazy_dict = LazyDict({1: 1, 2: lambda: 2})
    assert lazy_dict[2] == 2
    lazy_dict[3] = 3
    assert lazy_dict[3] == 3

    def joiner(*args, **kwargs):
        sep = kwargs.pop('sep', ' ')
        kwargs = [
            '%s=%s' % (k, v)
            for k, v in sorted(kwargs.iteritems())]
        return sep.join(list(args) + kwargs)

    lazy_dict.set_lazy(
        4, joiner, 'foo', 'bar', name='test', other='muah', sep=' ')
    assert lazy_dict[4] == 'foo bar name=test other=muah'

    assert lazy_dict.get('5') is None

    # Test caching functionality.
    def call_at_max(count):
        counter = [0]

        def inner():
            counter[0] += 1
            if counter[0] > count:
                raise AssertionError('Called more than once')
            return 'happy'
        return inner

    call_once = call_at_max(1)
    lazy_dict[5] = call_once
    assert lazy_dict[5] == 'happy'
    assert lazy_dict[5] == 'happy'

    # Test for helper function.
    try:
        call_once()
    except AssertionError:
        assert True


texts:
I've started learning C++ and I wanted to ask you to take a look at my linked list implementation and give comments what's wrong with. It compiles and runs fine, but I am curious about const correctness, proper use of pointers/references, etc., so feel free to go super tough on me!

I've read about these concepts online but this doesn't get me far without an experienced C++ programmer's opinion.

Node:

#include <iostream>

#pragma once
template <typename T>
class Node
{
const char * const _key;
Node *_next;
T _value;

public:
Node(const char * const key, const T &value) : _key(key), _value(value), _next(nullptr) {}

const char * const getKey()
{
    return _key;
}

Node *getNext()
{
    return _next;
}

void setNext(Node *next)
{
    _next = next;
}

T &getValue()
{
    return _value;
}
};

Linked List:

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

#pragma once

template <typename T>

class LinkedList
{
int _count;
Node<T> *_first;

public:
LinkedList() : _count(0), _first(nullptr) {}

Node<T> *add(const char * const key, const T &value)
{
    Node<T> *first = new Node<T>(key, value);
    first->setNext(_first);
    _first = first;
    _count++;
    return _first;
}

void remove(const char * const key)
{
    Node<T> *next = _first;
    Node<T> *previous = nullptr;

    while (next)
    {
        if (next->getKey() == key)
        {
            if (next == _first)
                _first = next->getNext();
            else
                previous->setNext(next->getNext());
            _count--;
            return;
        }
        previous = next;
        next = next->getNext();
    }
}

int getCount()
{
    return _count;
}

Node<T> * const getFirst()
{
    return _first;
}
};

I am not too certain how to properly define value inside Node class, because I want to support both primitive types and objects.

This actually worked for me, although this is probably not correct?

if (next->getKey() == key)


texts: X86_64 implementation of STRCHR using NASM

texts:
As this will eventually become part of an operating system I'm developing, there is no specific adherence to any particular ABI, even though this is being developed and tested on Ubuntu 16.04. My OS will however adopt a SYSTEM V paradigm insomuch as passing values by register, but they will be passed in the one most suitable to the algorithm.
One of my methodologies is to utilize as many bits of the register as possible, especially when 16 or less are significant. I have found too, that in a lot of cases this can simplify calling process. It does however complicate things a little ie:
    mov     rdi, Pointer_to_String
    mov     ecx, 784 << 8 | '.'
    call    strlen

This would traverse the buffer pointed to by RDI for the first occurence of period for a maximum of 784 characters. This snippet had evolved from just scanning for NULL for a maximum of FFFFFFFFH bytes, to scanning for any of the values (0 - FF), to traversing buffer for specified number of bytes.
Question
Do you think I've achived the maximum utility with the least amount of code.
 ; Determine length, including terminating character EOS. Result may include
 ; VT100 escape sequences.

 ;        ENTER: RDI = Pointer to ASCII string.
 ;               RCX   Bits 31 - 08 = Max chars to scan (1 - 1.67e7)
 ;                          07 - 00 = Terminating character (0 - FF)

 ;        LEAVE: RAX = Pointer to next string (optional).

 ;        FLAGS:  ZF = Terminating character found, NZ otherwise (overrun).
 ;                DF = Unmodified incase it was already set.

strlen:  pushf                       ; Preserve DF (Direction flag)
         push    rcx                 ; Preserve registers used by proc so
         push    rdi                 ; its non-destructive except for RAX.

         mov      al, cl             ; Byte to scan for in AL.
         shr     ecx, 8              ; Shift max count into bits 23 - 00

         std                         ; Auto decrement.
         repnz   scasb               ; Scan for AL or until ECX = 0
         mov     rax, rdi            ; Return pointer to EOS + 1

         pop     rdi                 ; Original pointer from proglogue
         jz      .exit               ; ZF indicates EOS was found
         mov     rax, rdi            ; RAX = RDI, NULL string

    .exit:
         pop     rcx
         popf                        ; Restore direction flag.
         ret


texts: Removing nested for loops to hasten API call response time

texts:
I've got an MVC APU project that I'm working on to feed data to some JavaScript charts. This beast below takes nearly 1 second of server time to process before it is served to the chart. I know that it's because of the nested for loops.

The chart is a line. By default it shows one data point per month for the last 5 years (one line per year, up to 12 points per line).

The only way I can think to do this is to say for each year, for each month add a point.

Is there a more efficient way to get this done? The resulting JSON looks like this:

{"YearLabel":2011,"MonthProduction":7505.83,"MonthNumber":1}

public string DealsPerMonth(int? BrokerID, int NumberOfYears, int? StartingYear)
    {
        DBNAME db = new DBNAME();

        List<NumberOfDealsPerMonth> dealsPerMonth = new List<NumberOfDealsPerMonth>();

        StartingYear = StartingYear ?? DateTime.Now.Year;

        for (var i = NumberOfYears; i > 0; i--)
        {
            var year = StartingYear - (i - 1);

            var deals = db.VDealParticipations.Where(w => w.IsPrimaryParticipant && w.EffectiveDate.Value.Year == year);

            if (BrokerID != null)
                deals = deals.Where(w => w.BrokerID == BrokerID);

            for (var month = 1; month <= 12; month++)
            {
                if (!(year == DateTime.Now.Year && month > DateTime.Now.Month))
                {
                    var dealCount = deals.Count(w => w.EffectiveDate.Value.Month == month);
                    dealsPerMonth.Add(new NumberOfDealsPerMonth
                    {
                        YearLabel = (int) year,
                        DealCount = dealCount,
                        MonthNumber = month
                    });
                }
            }
        }
        var serializer = new JavaScriptSerializer();
        var value = serializer.Serialize(dealsPerMonth.ToArray());
        return value;
    }

The class that's being used is as follows, although I am probably going to delete it as I found out about anonymous return types and so instead of

select(s => new NumberOfDealsPerMonth {blah = s.bleh}

I can do

select(s => new {blah = s.bleh}

and it does the same thing. But I want to include it anyway just for the sake of more information.

public class NumberOfDealsPerMonth
{
    public int YearLabel { get; set; }
    public int DealCount { get; set; }
    public int MonthNumber { get; set; }
}


texts:
I've recently started to look into React. I feel like I'm understanding it, but I want to make sure I'm doing the best practices before I make too many bad habits.

I'm using the react-rails gem, and my data structure is as follows:

GolfCourse:

has_many :holes

Hole:

belongs_to :golf_course
has_many :yardages

Yardage:

belongs_to :tee_box

I load the component using:

<%= react_component('Scorecard', teeBoxes: TeeBox.all, holes: @course.holes, yardages: @yardages) %>

The idea behind the component is: The user has loaded the page to enter their recent golfing score, the page loads the scorecard for the current course they have selected. The user then changes the dropdown to select which tee box they played off.

The scorecard yardage/par/stroke_index will change depending on which tee colour they have chosen.

Scorecard Component

var Scorecard = React.createClass({

  getInitialState: function() {
    return {
      yardages: {}
    };
  },

  changeYardage: function(teeBoxId) {
    this.setState({
      yardages: _.filter(this.props.yardages, function(yardage){ return yardage.tee_box_id == teeBoxId; })
    });
  },

  renderHoles: function() {
    var state = this.state;
    return this.props.holes.map(function(option) {
      yardage = _.find(state.yardages, function(yardage) { return yardage.hole_id == option.id; });

      return (

          {option.number}
          {option.name}
          {typeof(yardage) !== "undefined" ? yardage.yards : ""}
          {typeof(yardage) !== "undefined" ? yardage.par : ""}
          {typeof(yardage) !== "undefined" ? yardage.stroke_index: ""}

      );
    });
  },

  render: function() {
    return (

        <TeeBoxSelect teeBoxes={this.props.teeBoxes} changeYardage={this.changeYardage} />

              Hole
              Yards
              Par
              Stroke Index
              Score

            {this.renderHoles()}

    );
  }
});

Tee box select component

var TeeBoxSelect = React.createClass({
  getInitialState: function() {
    return {
      selected: 0
    }
  },

  handleChange: function() {
    this.props.changeYardage(this.refs.teeBox.value);
  },

  optionNodes: function() {
    return this.props.teeBoxes.map(function(option) {
      return <option key={option.id} value={option.id}>{option.colour}</option>;
    });
  },

  render: function() {
    return (
      <select ref="teeBox" value={this.state.selected} onChange={this.handleChange}>
        <option value="0">-- Select your tee box --</option>
        {this.optionNodes()}
      </select>
    );
  }
});

How did I do? My main concerns are where I'm rendering the multiple elements (holes
 in scorecard component, tee box options in the teebox component.), and the way I handle state (yardages) in the Scorecard component.


texts: SQL Sub-query with running total optimization

texts:
The codes below get the rows of data until it reaches the total running quantity limit.

Notice that the SQL uses sub-query. select *, sum(Quantity) over (order by id) as RunningQty from #PurchaseOrderProducts. I'm worried that the sub-query would get all the data from the table. Is there a way to improve the performance?

CREATE TABLE #PurchaseOrderProducts
(
    Id int,
    Product varchar(10),
    Quantity int
)

INSERT INTO #PurchaseOrderProducts VALUES (1, 'Item A', 5)
INSERT INTO #PurchaseOrderProducts VALUES (2, 'Item B', 1)
INSERT INTO #PurchaseOrderProducts VALUES (3, 'Item C', 8)
INSERT INTO #PurchaseOrderProducts VALUES (4, 'Item D', 2)
INSERT INTO #PurchaseOrderProducts VALUES (5, 'Item E', 1)

SELECT P.*
FROM (select *, sum(Quantity) over (order by id) as RunningQty
      from #PurchaseOrderProducts
     ) P
WHERE P.RunningQty - Quantity < 12;


texts:
I have the next bilinear resizing algorithm, and even though I use fixed point is still quite slow for my requirements. In the past I tried to cache some values in tables but the improvement was of a few not noticeable milliseconds.

Is any other way I can improve the speed? As this is intended for ARM processors, I know I could write it with NEON instructions, but unfortunately I don't have the knowledge for such task.

void resize_bilinear(const unsigned int *input, unsigned int *output, const unsigned int sourceWidth, const unsigned int sourceHeight, const unsigned int targetWidth, const unsigned int targetHeight)
{
    unsigned int widthCoefficient, heightCoefficient, x, y;
    unsigned int pixel1, pixel2, pixel3, pixel4;
    unsigned int hc1, hc2, wc1, wc2, offsetX, offsetY;
    unsigned int r, g, b, a;

    const unsigned int wStepFixed16b = ((sourceWidth - 1) << 16)  / ((unsigned int)(targetWidth - 1));
    const unsigned int hStepFixed16b = ((sourceHeight - 1) << 16) / ((unsigned int)(targetHeight - 1));

    heightCoefficient = 0;

    int offsetPixelY;
    int offsetPixelY1;
    int offsetX1;

    for (y = 0; y < targetHeight; y++)
    {
        offsetY = (heightCoefficient >> 16);
        hc2 = (heightCoefficient >> 9) & (unsigned char)127;
        hc1 = 128 - hc2;

        widthCoefficient = 0;

        offsetPixelY  = offsetY * sourceWidth;
        offsetPixelY1 = (offsetY + 1) * sourceWidth;

        for (x = 0; x < targetWidth; x++)
        {
            offsetX = (widthCoefficient >> 16);
            wc2 = (widthCoefficient >> 9) & (unsigned char)127;
            wc1 = 128 - wc2;

            offsetX1 = offsetX + 1;

            pixel1 = *(input + (offsetPixelY  + offsetX));
            pixel2 = *(input + (offsetPixelY1 + offsetX));
            pixel3 = *(input + (offsetPixelY  + offsetX1));
            pixel4 = *(input + (offsetPixelY1 + offsetX1));

            a = ((((pixel1 >> 24) & 0xff) * hc1 + ((pixel2 >> 24) & 0xff) * hc2) * wc1 +
                (((pixel3  >> 24) & 0xff) * hc1 + ((pixel4 >> 24) & 0xff) * hc2) * wc2) >> 14;

            r = ((((pixel1 >> 16) & 0xff) * hc1 + ((pixel2 >> 16) & 0xff) * hc2) * wc1 +
                (((pixel3  >> 16) & 0xff) * hc1 + ((pixel4 >> 16) & 0xff) * hc2) * wc2) >> 14;

            g = ((((pixel1 >> 8) & 0xff) * hc1 + ((pixel2 >> 8) & 0xff) * hc2) * wc1 +
                (((pixel3  >> 8) & 0xff) * hc1 + ((pixel4 >> 8) & 0xff) * hc2) * wc2) >> 14;

            b = ((((pixel1) & 0xff) * hc1 + ((pixel2) & 0xff) * hc2) * wc1 +
                (((pixel3)  & 0xff) * hc1 + ((pixel4) & 0xff) * hc2) * wc2) >> 14;

            *output++ = (a << 24) | (r << 16) | (g << 8) | b;

            widthCoefficient += wStepFixed16b;
        }

        heightCoefficient += hStepFixed16b;
    }
}


texts:
I Have written this program to add workers into a list and print them. I'd like a review of this. I'm especially concerned if the method Addworker should be inside the class or in the main program.

Person:

class Person
{
    public uint NumberId;
    public string Name;
    public string LastName;
    public uint Age; // Age Should Be Beetween 18 And 40

    public uint numberId
    {
        set { this.NumberId = value; }
        get { return this.NumberId; }
    }

    public string name
    {
        set { this.Name = value; }
        get { return this.Name; }
    }

    public string lastName
    {
        set { this.LastName = value; }
        get { return this.LastName; }
    }

    public uint age
    {
        set
        {
            if (value < 18 || value > 40)
            {
                throw new ArgumentOutOfRangeException();
            }
            this.Age = value;
        }

        get { return this.Age; }
    }
}

Worker:

class Worker:Person
{
    private uint WageHour;
    private uint Total_Hours;

    public uint wageHour
    {
        set { this.WageHour = value; }
        get { return this.WageHour; }
    }

    public uint total_Hours
    {
        set { this.Total_Hours = value; }
        get { return this.Total_Hours; }
    }

    public double SalaryCalcul()
    {
        return this.wageHour * this.total_Hours;
    }

    public override string ToString()
    {
        return string.Format("Name : {0} Last Name : {1} Age : {2} WageHour : {3} Total Hours : {4} Salary : {5}",
                          this.name,this.lastName,this.age,this.wageHour,this.total_Hours,this.SalaryCalcul().ToString());

     }
}

Main program:

class Program
{
    static List<Worker> WorkersList = new List<Worker>();

    static void Main(string[] args)
    {
        do
        {
            Console.Clear();

            Console.WriteLine("1 - Add A Worker .");
            Console.WriteLine("2 - Print List .");

            int Choice = int.Parse(Console.ReadLine());

            switch (Choice)
            {
                case 1:
                    {
                        AddWorker();
                        break;
                    }

                case 2:
                    {
                        Console.Clear();

                        foreach (Worker W in WorkersList)
                        {
                            Console.WriteLine(W.ToString());
                        }

                        Console.ReadKey();

                        break;
                    }
            }
        }
        while (true);

    }

    static void AddWorker()
    {
        Worker W = new Worker();

        Console.WriteLine("Enter ID : ");
        W.numberId = uint.Parse(Console.ReadLine());

        Console.WriteLine("Enter Name : ");
        W.name = Console.ReadLine();

        Console.WriteLine("Enter Last Name : ");
        W.lastName = Console.ReadLine();

        try
        {
            Console.WriteLine("Enter Age : ");
            W.age = uint.Parse(Console.ReadLine());
        }
        catch (Exception)
        {
            Console.WriteLine("Age Should Be Between 18 and 40 ");
        }

        Console.WriteLine("Enter Hour Wage : ");
        W.wageHour = uint.Parse(Console.ReadLine());

        Console.WriteLine("Enter Total Hours : ");
        W.total_Hours = uint.Parse(Console.ReadLine());

        WorkersList.Add(W);
    }
}


texts:
I am learning to use Java Swing and have made a simple animation that makes a small shape bounce around the predetermined borders of a panel. The program works well, but I am looking for feedback in terms of quality and any improvements or alternative methods that could be used in such an application.

import javax.swing.*;
import java.awt.*;

final public class Tester {

    JFrame frame;
    DrawPanel drawPanel;

    private int oneX = 7;
    private int oneY = 7;

    boolean up = false;
    boolean down = true;
    boolean left = false;
    boolean right = true;

    public static void main(String[] args) {
        new Tester().go();
    }

    private void go() {
        frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        drawPanel = new DrawPanel();

        frame.getContentPane().add(BorderLayout.CENTER, drawPanel);

        frame.setVisible(true);
        frame.setResizable(false);
        frame.setSize(300, 300);
        frame.setLocation(375, 55);
        moveIt();
    }

    class DrawPanel extends JPanel {
        public void paintComponent(Graphics g) {
            g.setColor(Color.BLUE);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            g.setColor(Color.RED);
            g.fillRect(3, 3, this.getWidth()-6, this.getHeight()-6);
            g.setColor(Color.WHITE);
            g.fillRect(6, 6, this.getWidth()-12, this.getHeight()-12);
            g.setColor(Color.BLACK);
            g.fillRect(oneX, oneY, 6, 6);
        }
    }

    private void moveIt() {
        while(true){
            if(oneX >= 283){
                right = false;
                left = true;
            }
            if(oneX <= 7){
                right = true;
                left = false;
            }
            if(oneY >= 259){
                up = true;
                down = false;
            }
            if(oneY <= 7){
                up = false;
                down = true;
            }
            if(up){
                oneY--;
            }
            if(down){
                oneY++;
            }
            if(left){
                oneX--;
            }
            if(right){
                oneX++;
            }
            try{
                Thread.sleep(10);
            } catch (Exception exc){}
            frame.repaint();
        }
    }
}


texts: Function that takes an array of integers and returns that array rotated to the right N components

texts:
Example:
  if \$N=2\$, given the input array \${[1, 2, 3, 4, 5, 6]}\$ the function should return \${[5, 6, 1, 2, 3, 4]}\$

Here is my code:

def copyDigit(list,index,item):

        """
                Copy the item to the indexed location in the given list
        """
        list[index] = item
        return list

def rotateList(noListToRorate,timesRotate):

        """
                Rotate List to right
        """
        print "Function received {0},{1}".format(noListToRorate,timesRotate)
        for rotate in range(N):
            lastItemInList = noListToRorate[-1]
            for i in range(len(noListToRorate)-2,-1,-1):
                itemToShift = noListToRorate[i]
                noListToRorate = copyDigit(noListToRorate,i+1,itemToShift)
            noListToRorate[0] = lastItemInList
        print "Rotate once: {0}".format(noListToRorate)
        return noListToRorate

if __name__ == '__main__':

        """
           This program will rorate right the given list N no of times
        """

        arrayList = [1,2,3,4,5,6]
        N = 2
        print "Rotate an array: " ,(arrayList), "No of times: ", N
        finalList = rotateList(arrayList,N)
        print "Rotated List: ", finalList


texts: Booking appointments with MySQLi and PHP

texts:
The following code books one appointment for one or more slots. I have never used database before, but have seen so many warnings regarding SQL injections. Since it has never affected me I have not paid attention.

<?php

    include('php/connect.php');

    if(isset($_POST['slots_booked'])) $slots_booked = mysqli_real_escape_string($link, $_POST['slots_booked']);
    if(isset($_POST['name'])) $name = mysqli_real_escape_string($link, $_POST['name']);
    if(isset($_POST['akeri'])) $akeri = mysqli_real_escape_string($link, $_POST['akeri']);
    if(isset($_POST['email'])) $email = mysqli_real_escape_string($link, $_POST['email']);
    if(isset($_POST['phone'])) $phone = mysqli_real_escape_string($link, $_POST['phone']);
    if(isset($_POST['typ'])) $typ = mysqli_real_escape_string($link, $_POST['typ']);
    if(isset($_POST['fri'])) $fri = mysqli_real_escape_string($link, $_POST['fri']);
    if(isset($_POST['booking_date'])) $booking_date = mysqli_real_escape_string($link, $_POST['booking_date']);

    $booking_array = array(
            "slots_booked" => $slots_booked,
            "booking_date" => $booking_date,
            "name" => $name,
            "email" => $email,
            "Åkeri" => $akeri,
            "phone" => $phone,
            "typ" => $typ,
            "fri" => $fri
    );

    $explode = explode('|', $slots_booked);

    foreach($explode as $slot) {

        if(strlen($slot) > 0) {

            $stmt = $link->prepare("INSERT INTO bookings (date, start, name, email, phone, typ, fri) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param('sssssss', $booking_date, $slot, $name, $email, $phone, $typ, $fri);
            $stmt->execute();

        } // Close if

     } // Close foreach

    header("location: Done.html");
    exit;
?>