texts: Can this JavaScript singleton be improved?

texts:
I needed a singleton in JavaScript in order to make a DataManager which is called multiple times, but I just want it to load its data only the first time it is called, then give pieces of the data out view public methods, never loading the initial data again.

I found a number of approaches to building singletons in JavaScript but this one seems to have everything I need.

Does anyone see any kind of problem this singleton is going to have for the uses I need it for?

<!DOCTYPE html>
<html>
    <head>
        <title>test singleton</title>
        <script type="text/javascript">
            var DatapodManager = (function() {
                var instantiated;
                that = this;

                //DEFINE INTERNAL VARIABLES HERE:
                var message = '';

                function init() {

                    //LOAD DATA ONCE HERE:
                    that.message = 'singleton message defined at: ' + getMilliseconds();

                    //ALLOW PUBLIC ACCESS TO SINGLETON DATA HERE:
                    return {
                        getMessage : function() {
                            return that.message;
                        },
                        id : '1234'
                    }
                }

                return {
                    getInstance : function() {
                        if(!instantiated) {
                            instantiated = init();
                        }
                        return instantiated;
                    }
                }
            })()

            function dowait() {
                for( x = 1; x <= 10000000; x++) {
                    var y = 1000;
                    var z = 2000;
                    var b = y * z;
                }
            }

            function getMilliseconds() {
                var d = new Date();
                return d.getMilliseconds();
            }

            window.onload = function() {
                console.log('getting first singleton message at: '+getMilliseconds());
                console.log(DatapodManager.getInstance().getMessage());
                dowait();
                console.log('getting second singleton message at: '+getMilliseconds());
                console.log(DatapodManager.getInstance().getMessage());
                console.log('the static id is '+DatapodManager.getInstance().id);
            };
        </script>
    </head>
    <body></body>

Output:


texts: Does this Actor implementation has synchronization problems?

texts:
As a part of a job test, I wrote following implementation of the Actor execution model:

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Executor;
public abstract class Actor implements Runnable {
  private final Executor executor;

  /** current token */
  private Message message=null;
  /** rest of tokens */
  private Queue<Message> queue = new LinkedList<Message>();

  private boolean isFired=false;

  public Actor(Executor executor) {
    this.executor = executor;
  }

  /**
   * Frontend method which may be called from other Thread or Actor.
   * Saves the message and initiates Actor's execution.
   */
  protected void post(Message message) {
    synchronized(this) {
        if (isFired) {
            queue.add(message);
            return;
        }
        this.message=message;
        isFired=true; // to prevent multiple concurrent firings
    }
    executor.execute(this);
  }

  @Override
  public void run() {
    for (;;) {
        this.message.run();
        synchronized(this) {
            this.message = queue.poll();  // consume token
            if (this.message==null) {
                isFired=false; // allow firing
                return;
            }
        }
    }
  }

  protected abstract class Message {
    protected abstract void run();
 }
}

Reviewers concluded, in particular, that "Actor class have synchronization issues", but did not want to explain why.

Can you see any synchronization problems here?

The code, along with a test, can be downloaded from https://github.com/rfqu/CodeSamples/tree/master/src/simpleactor.


texts:
I wrote this DFS in Python and I was wondering if it correct. Somehow it seems too simple to me.

Each node is a class with attributes:

visited: Boolean
sons: list of nodes linked to the current node.

This code should work both for directed and undirected graphs.

def DFS(node):

    node.visited = True

    if node == None:
        return

    // perform some operation on the node
    do_something(node)

    to_visit = [son in node.sons if not son.visited]
    for son in to_visit:
        DFS(node)


texts:
Is this a proper Count sort implementation?
Code and style improvements?

It does not support negative and that should be improved.  A large input could cause out of memory.

Some of the array index is different as the WIKI is 1 based and these arrays are zero based.

public static void CountSort(int[] arr)
{
    int max = -1;
    foreach(int i in arr)
    {
        if (i < 0)
        {
            throw new IndexOutOfRangeException(" < 0 ");
        }
        max = Math.Max(max, i);
    }

    int n = arr.Length;

    // The output character array that will have sorted arr
    int[] output = new int[n];

    // Create a count array to store count of inidividul
    // characters and initialize count array as 0
    int[] count = new int[max+1];
    for (int i = 0; i <= max; ++i)
        count[i] = 0;

    // store count of each character
    foreach (int i in arr)
        count[i]++;

    // Change count[i] so that count[i] now contains actual
    // position of this character in output array
    for (int i = 1; i <= max; ++i)
        count[i] += count[i - 1];

    // Build the output character array
    for (int i = 0; i < n; ++i)
    {
        output[count[arr[i]] - 1] = arr[i];
        count[arr[i]]--;
    }

    // Copy the output array to arr, so that arr now
    // contains sorted characters
    for (int i = 0; i < n; ++i)
        arr[i] = output[i];
}

//test
int[] ar = new int[] { 0, 0, 0, 0 };
CountSort(ar);
foreach (int i in ar)
    Debug.WriteLine(i);
Debug.WriteLine("");

ar = new int[] { 5, 5, 5, 5 };
CountSort(ar);
foreach (int i in ar)
    Debug.WriteLine(i);
Debug.WriteLine("");

ar = new int[] {};
CountSort(ar);
foreach (int i in ar)
    Debug.WriteLine(i);
Debug.WriteLine("");

ar = new int[] { 90, 90, 71, 82, 93, 75, 81, 0, 12, 54, 36, 13, 102, 99, 34, 103, 78, 196, 52, 5, 215 };
CountSort(ar);
foreach (int i in ar)
    Debug.WriteLine(i);
Debug.WriteLine("");


texts: Return two results from API with an ID set

texts:
I am calling from an API to return a member and their upcoming classes. I would like to show only the next two classes (up to six are available in the API) that have an ID set.

$instructorID = $_GET['InstructorID']; // get member ID from url
$test_member  = new test\api\test_api_call();
$response     = $test_member->get_members_info($instructorID); // get member info from API based on member ID
$member       = $response->body->member;

[...]

$memberClasses = $member->member_locations[0]->upcoming_classes; // get member upcoming classes

[...]

if (is_array($memberClasses)) : // if member has upcoming classes in array
    for ($limitClasses = 0; $limitClasses < 2; $limitClasses++) : // limit to two classes
        $class   = $memberClasses[$limitClasses];
        $classID = $class->id;

        if (empty($classID)) : // check that class has ID set, if not continue loop
            $limitClasses--;
            continue;
        endif;

        [...]

    endfor;
endif;

Is there a better way to set up my loop to return only the next two classes with an ID?

For example, if the first class in the API is missing an ID, the loop will be at -1 on the next pass. This isn't something I've experienced yet, but I'd like to be prepared in the event of a possible future error.


texts: Computing sums in some CSV files horizontally and in other CSV files vertically

texts:
I'd like to eliminate the code duplication in the following two methods by moving the common code into a separate method callable by both. The comments indicate the blocks of code that have a differing implementation in each method.

def compute_totals_h(self, size, bad_codes):
    with open(self._in_file_path, self._FILE_READ_MODE) as f:
        # initialize reader
        reader = csv.reader(f)
        field_names = reader.next()
        for i, code in enumerate(field_names):
            code = code.strip(string.punctuation).upper()
            field_names[i] = code
        for code in field_names:
            if (len(code) <= size) and (code not in bad_codes):
                self._totals[code] = 0

        for row in reader:
            # get totals
            for i, val in enumerate(row):
                code = field_names[i]
                if (code in self._totals):
                    self._totals[code] += string_utils.to_int(val)

    self._write_totals()

def compute_totals_v(self, code_field, est_field):
    with open(self._in_file_path, self._FILE_READ_MODE) as f:
        # initialize reader
        reader = csv.DictReader(f)

        for row in reader:
            # get totals
            code = row[code_field].strip(string.punctuation).upper()
            est = string_utils.to_int(row[est_field])
            if code in self._totals:
                self._totals[code] += est
            else:
                self._totals[code] = est

    self._write_totals()

I'm thinking of a solution that has a common abstract method that can be called from compute_totals_h and compute_totals_v with each method passing functions to handle its implementation. I can't figure out how to do this while passing the arguments for each implementation correctly. It would look something like:

def compute_totals(self, initialize_reader, get_totals):
    with open(self._in_file_path, self._FILE_READ_MODE) as f:
        reader = initialize_reader(f)

        for row in reader:
            get_totals(row)

        self._write_totals()

I'll also appreciate suggestions on a better way of handling this type of code refactoring to eliminate this general class of code duplication problems.


texts:
I need to sort files by the type of the File. To accomplish the task I first wrote the code below:

private static Comparator SortByFileType() {

    return Comparator.comparing((File f) -> {
        String probeContentType = null;
        try {
            probeContentType = Files.probeContentType(f.toPath());
            if (probeContentType ==null) {
                probeContentType = "probeContentTypeIsNull";
            }
        } catch (IOException e) {
        }
        return probeContentType;
    });
}

Then I needed to perform different sorts, so I decided to make an enum of sorts, but I wasn't able to pass the above code to the enum. I instead rewrote the above code as given below:

public enum Sort implements Comparator<File> {

/**
 * Compare files by the name of the File A<->Z
 *
 */
ByFileName {

        },
/**
 * Compare Files by the Type of file
 */
ByFileType {

        @Override
        public int compare(File f1, File f2) {
            String fileType1 = "";
            String fileType2 = "";

            try {
                fileType1 = Files.probeContentType(f1.toPath());
                fileType2 = Files.probeContentType(f2.toPath());
            } catch (IOException ex) {

            }

            if (fileType1 == null) {
                fileType1 = "probeContentTypeIsNull";
            }
            if (fileType2 == null) {
                fileType2 = "probeContentTypeIsNull";
            }

            return fileType1.compareTo(fileType2);
        }

    }
}

Now I need to know two things:

Can we turn the code passed to the ByFileType enum into a lambda?
Can the code passed to the ByFileType be optimized and improved?


texts: Comparing a list of known animals to a master list of animals

texts:
This script works for what I need it to do, but I'm not all that proficient with Python yet, so I was wondering if any of the more seasoned python veterans would go about it differently.

import os
import string
import re

'''This script will take in an input list of strictly stellar IDs, and compare those IDs to a master file
with IDs AND photometric data. It will then write to a file, the lines from the master file that correspond to the known IDs
in the IDs list.'''

def pullIDs(file_input):
    '''Pulls Mon-IDs from input file.'''
    arrayID = []
    with open(file_input,'rU') as user_file:
        for line in user_file:
            arrayID.append(re.findall('Mon\-\d{6}',line))
    return arrayID

def pullLines(file_input):
    '''Creates an array component for each
    line in the input file.'''
    arrayLines = []
    with open(file_input,'rU') as info:
        for item in info:
            item.split
            arrayLines.append(item)
    return arrayLines

def getHeader(file_input):
    '''Assuming the file-header begins with a '#',
    this will pull the header line.'''
    with open(file_input,'rU') as title:
        for line in title:
            if line.startswith('#'):
                header = line
    return header

known_stars = raw_input("Enter your ID list: ")
master_list = raw_input("Enter your master list: ")
results_list = raw_input("Name your output file: ")

with open(results_list,"w+") as output:
    output.write(getHeader(master_list))
    for item in pullIDs(known_stars):
        for items in pullLines(master_list):
            if items[:10] in item:
                output.write(items)

output_fileSIZE = os.stat(results_list).st_size
if output_fileSIZE > 0:
    print "\nYour output file has been written to.\n"
else:
    print "\nThere was an error writing to your file.\n"

This essentially takes a list of known animals, say, cat and dog, and compares that list to a master list of animals and their respective information.

For example:

cat female 2 gray playful
dog male 9 black aggressive
giraffe male 12 tall hungry
elephant male 33 gray lonely
etc.

By creating two arrays for both lists, it searches for an animal that exists in both files and, once found, prints all of the more in-depth results from the 'master list' to a file.

So my file would look like this:

cat female 2 gray playful
dog male 9 black aggressive

because I only had a 'known list' of cats and dogs.

I'm just looking for tips on how to make this script better.  It also prints a header for the column information.


texts: Is this a reasonable algorithm for shuffling cards?

texts:
So I based my "algorithm" on the poke method defined by Persi Diaconis. You start with the card at the bottom of a given deck and then poke the top card into a random position in the deck. At first the probability of this happening is 1/52 but once a card is below the bottom most card it increases to 2/52 since there is now two positions a card could go to move the bottom card up the deck.

He claims it takes about 200 of these pokes to get the bottom card to the top. Then you poke the that bottom card which is now at the top somewhere random in the deck and he claims it is now completely randomized.

My results have held true to that, I haven't calculated mean or standard deviation yet to check but just from initial runs it seems to hold true(he is a mathematician and I am a first year undergrad, of course its true).

public void shuffle()
{
    SecureRandom rnd = new SecureRandom();
    Card bottomCard = deck.get(deck.size() - 1);
    int i = 0;
    while(!deck.get(0).equals(bottomCard))
    {
        Card poke = deck.get(0);
        deck.remove(0);
        deck.add(rnd.nextInt(52), poke);
    }
    deck.remove(bottomCard);
    deck.add(rnd.nextInt(52), bottomCard);
}


texts: Converting an integer to binary, hex, and octal

texts:
I've started caring about standards and the beauty of my code. I doubt whether I've written it correctly and aesthetically. Can you please judge this simple, exemplary program? I want to know of any mistakes I've made. It converts an integer number given in the argument to binary, hexadecimal and octal number. Ignore the "1." prefix.

1.conversion_main.cpp:

//Conversion
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include "1.conversion_header.h"
#include "1.convert.cpp"

int parse(int, char**);

int main(int argc, char *argv[]){
    int number = parse(argc, argv);
    if (number == 0)
      return 0;
    convert converter;
    std::cout << "HEX: " << converter.to_hex(number) << std::endl;
    std::cout << "OCT: " << converter.to_oct(number)  << std::endl;
    std::cout << "BIN: " << converter.to_bin(number)  << std::endl;
    return 0;
}

int parse(int argc, char* argv[]){
    if (argc == 2){
        if ((strcmp(argv[1], "--help") == 0) || (strcmp(argv[1], "-h") == 0)
        || (strcmp(argv[1], "/?")) == 0){
            std::cout << "Usage: a R\\{0}\n";
        }
        else{
            int check;
            std::istringstream in(argv[1]);
            if ((in >> check) && (in.eof()))
                return atoi(argv[1]);
        }
    }
    return 0;
}

1.conversion_header.h:

//Conversion header

class convert{
    public:
          std::string to_hex(int);
          std::string to_oct(int);
          std::string to_bin(int);
  protected:
          std::string int_to_bin(int);
          std::string reverse(std::string);
};

1.convert.cpp:

//Convert definition

#include <string>

std::string convert::int_to_bin(int number){
    static std::string result;
    static int level = 0;
    level++;
    if (number > 0){
        if (number % 2 == 0){
            result.append("0");
        }
        else{
            result.append("1");
        }
        int_to_bin(number / 2);
        level--;
    }
    if (level == 1) return reverse(result);
    return result;
}

std::string convert::reverse(std::string to_reverse){
    std::string result;
    for (int i = to_reverse.length()-1; i >=0 ; i--)
        result += to_reverse[i];
    return result;
}

std::string convert::to_hex(int to_convert){
    std::string result;
    std::stringstream ss;
    ss << std::hex <<to_convert;
    ss >> result;
    return result;
}

std::string convert::to_oct(int to_convert){
    std::string result;
    std::stringstream ss;
    ss << std::oct << to_convert;
    ss >> result;
    return result;
}

std::string convert::to_bin(int to_convert){
    return int_to_bin(to_convert);
}


texts:
This is just a simple class that you can you use to send requests and get the HTML code. I would like to get feedback on this.

For your request you can set:

URL
Request method: GET or POST
Request parameters: if you need to pass parameters
Request cookie

As a response you will get:

HTML
Response cookie

Request

class Request
{
    public string Url { get; set; }
    public string RequestMethod { get; set; }
    public string RequestParameters { get; set; }
    public string RequestCookie { get; set; }
    public string ResponseCookie { get; private set; }

    /// <summary>
    /// Send Request To URL
    /// </summary>
    /// <returns>HTML Text of URL</returns>
    public string SendRequest()
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

            request.Method = RequestMethod;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4";

            if (RequestCookie != null)
            {
                request.Headers["Cookie"] = RequestCookie;
            }

            WebProxy myProxy = new WebProxy("localhost", 8888);
            request.Proxy = myProxy;

            if (RequestParameters != null)
            {
                byte[] bytes = Encoding.UTF8.GetBytes(RequestParameters);
                request.ContentLength = bytes.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            response.Headers["Set-Cookie"] = ResponseCookie;

            StreamReader reader = new StreamReader(response.GetResponseStream());

            return reader.ReadToEnd();
        }
        catch (WebException ex)
        {
            StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream());

            return streamReader.ReadToEnd();
        }
    }
}

Example

static void Main(string[] args)
    {
        Request myRequest = new Request();

        myRequest.Url = "https://google.com";
        myRequest.RequestMethod = "GET";

        string html = myRequest.SendRequest();

        Console.WriteLine("REQUEST DONE !");

        Console.WriteLine(html);

        Console.ReadKey();
    }


texts:
I have the following block of code which adds pins including descriptions and links onto a Google map. How can I refactor it so that I can add pins easier and without so much redundant code?

var map;

function initializeMap() {
var myOptions = {
    zoom: 9,
    center: new google.maps.LatLng(42.2340464046899, -71.0956621170044),
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    scrollwheel: false
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

var marker1 = new google.maps.Marker({
    position: new google.maps.LatLng(42.2340464046899, -71.0956621170044),
    map: map,
    title: "Pin 1",
    url: "#tabs-pin1"
});
google.maps.event.addListener(marker1, 'click', function() {
    $("#tabs").tabs('select', marker1.url);
});
var marker2 = new google.maps.Marker({
    position: new google.maps.LatLng(41.9584457, -70.6672621),
    map: map,
    title: "Pin 2",
    url: "#tabs-pin2"
});
google.maps.event.addListener(marker2, 'click', function() {
    $("#tabs").tabs('select', marker2.url);

var marker9 = new google.maps.Marker({
    position: new google.maps.LatLng(42.445921, -71.2690294),
    map: map,
    title: "Pin 9",
    url: "#tabs-pin9"
});
google.maps.event.addListener(marker9, 'click', function() {
    $("#tabs").tabs('select', marker9.url);

}
google.maps.event.addDomListener(window, 'load', initializeMap);


texts: Is this a correct way to write a convenience constructor?

texts:
I was reading more about the instancetype on Stack Overflow and now my question is:

For every convenience constructor that I write, do I need to have the corresponding one using init?

For example:

RandomItem.h

#import <Foundation/Foundation.h>

@interface RandomItem : NSObject

@property (nonatomic, copy) NSString *aString;

+(instancetype)itemWithString:(NSString *)string;

@end

RandomItem.m

#import "RandomItem.h"

@implementation RandomItem

+(instancetype)itemWithString:(NSString *)string
{
    RandomItem *anItem = [[self alloc] init];
    anItem.aString = string;
    return anItem;
}

@end

And compare this when using an -initWithString: constructor as well:

RandomItem.h

#import <Foundation/Foundation.h>

@interface RandomItem : NSObject

@property (nonatomic, copy) NSString *aString;

-(id)initWithString:(NSString *)string;
+(instancetype)itemWithString:(NSString *)string;

@end

RandomItem.m:

#import "RandomItem.h"

@implementation RandomItem

-(id)initWithString:(NSString *)string
{
    self = [super init];
    if (self)
    {
        self.aString = string;
    }
    return self;
}

+(instancetype)itemWithString:(NSString *)string
{
    return [[self alloc] initWithString:string];
}

@end

I suppose that both cases are fine, but I would like to hear your comments.

Thanks!


texts: Class dedicated to transforming API response to the data I need?

texts:
I have the following code (in php) that calls the open weather api with my credentials, and returns data for me.
Know I'm returning some data I pick from that response, I'm wondering if it's good practice to create a dedicated class for that? Is this something that's commonly used and does it have a name?
try {
    $request = $this->http->get( 'api.openweathermap.org/data/2.5/weather', $options);
    $response = json_decode($request->getBody());

    return [
        'main' => $response->weather[0]->main,
        'temperature' => $response->main->temp,
    ];

} catch (GuzzleException $e) {
    die(var_dump($e->getMessage()));
}
```


texts: Create two vehicles, move them on a grid based on user input

texts:
I have a grid and a class Vehicle, which will have starting point(X, Y on the grid) and direction(one of N,E,S,W) taken from user and there will be commands, L & R turns the vehicle 90 degrees around left and right respectively and M moves the vehicle one unit to faced direction.

  For instance, if the command is M and the current direction is E, the vehicle moves from (x,y) to (x+1,y) and preserve its direction.
  If the command is R, and the current direction is E, vehicle preserves its position but direction changes to S.

  My input consists of 5 lines:

  The first line defines the limits of the grid; X and Y separated by space
  The second line defines the current position and facing direction for the
  first vehicle; X, Y and Dir are separated by space
  The third line defines the commands for the first vehicle, which is a line of string
  The fourth and fifth lines are the same as second and third except they
  are for the second vehicle

  Note: Vehicles are sent sequentially. If the second vehicle attempts to move to the occupied spot of the first vehicle, the command will be skipped. If any move command makes any of the vehicles move out of the grid, that command will be skipped as well. Inputs are always in expected style, so there is no need to validate inputs.

As an example:

Inputs:

6 6
1 3 E
RMLLMRMRM
1 1 N
LMLML

Output:

2 2 S
0 0 E

My code:

directions = ['N','E','S','W']
movement = {'N': (0,1), 'E': (1,0), 'S': (0,-1), 'W':(-1,0)}
commands = {'L': 'turn_left', 'R': 'turn_right', 'M': 'move'}

GRID_MAX_X, GRID_MAX_Y = map(int, raw_input().split())

first_vehicle_x = None
first_vehicle_y = None

class Vehicle():
    def __init__(self, x, y, face):
        self.x = x
        self.y = y
        self.dir = face

    def turn_left(self):
        self.dir = directions[(directions.index(self.dir)-1)%len(directions)]

    def turn_right(self):
        self.dir = directions[(directions.index(self.dir)+1)%len(directions)]

    def move(self):
        new_x = self.x + movement[self.dir][0]
        new_y = self.y + movement[self.dir][1]

        if new_x != first_vehicle_x or new_y != first_vehicle_y:
            if new_x in xrange(GRID_MAX_X+1):
                self.x = new_x
            if new_y in xrange(GRID_MAX_Y+1):
                self.y = new_y

vehicle_one_pos = raw_input().split()
vehicle_one_commands = raw_input()

vehicle_one = Vehicle(int(vehicle_one_pos[0]), int(vehicle_one_pos[1]), vehicle_one_pos[2])
for command in vehicle_one_commands:
    eval("vehicle_one.{0}()".format(commands[command]))

first_vehicle_x = vehicle_one.x
first_vehicle_y = vehicle_one.y

vehicle_two_pos = raw_input().split()
vehicle_two_commands = raw_input()

vehicle_two = Vehicle(int(vehicle_two_pos[0]), int(vehicle_two_pos[1]), vehicle_two_pos[2])
for command in vehicle_two_commands:
    eval("vehicle_two.{0}()".format(commands[command]))

print vehicle_one.x, vehicle_one.y, vehicle_one.dir
print vehicle_two.x, vehicle_two.y, vehicle_two.dir

About my code, it feels like repetition on doing same things for each vehicle but wasnt't sure how to handle without it since I need position of vehicle_one for vehicle_two.

Any comment is always appreciated, thanks in advance.


texts:
The data (news items) comes from a
. I'm using setInterval and setTimeout for the timing aspects, and jQuery animate for the movement to the right. I know that setInterval and setTimeout start acting weirdly when the tab is not active, but that's not a problem for my specific use-case.

I'm looking for any comments, specifically the entire displayItem() function -- is there a better way to do this?

var items = [];
$('.news li').each(function() { //get all items from
 and add to array
  items.push($(this).html());
});

//Ticker
var duration = 5000; //take 5 seconds to show one item
$('.news ul').remove();
$('.news').append('Headlines');

function displayItem(html, i) {
  setTimeout(function() {
    $('.news .item').html(items[i]).animate({
      "left": "+=400px"
    }, {
      duration: duration,
      easing: "linear",
      complete: function() {
        $('.news .item').css('left', '0');
      }
    });
  }, (duration + 75) * i);
}

function loopAndDisplayItems() {
  for (var i = 0; i < items.length; i++) {
    var time = (i + 1) * 1000;
    displayItem(items[i], i);
  }
}

setInterval(loopAndDisplayItems, items.length * duration);
loopAndDisplayItems();
.news {
  border-radius: 7px;
  background-color: lightgray;
  padding: 8px;
  font-size: 12px;
}
.news .title {
  color: red;
}
.news .item {
  margin-left: 5px;
  position: relative;
}

Headline 1

Headline 2


texts:
Recently, I encountered this coding exercise on codility and the idea is

A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.

For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.

  Write a function:

 class Solution { public int[] CyclicRotation(int[] A, int K); }

  that, given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times.

  For example, given array A = [3, 8, 9, 7, 6] and K = 3

  the function should return [9, 7, 6, 3, 8].

Assume that:

  N and K are integers within the range [0..100];
      each element of array A is an integer within the range [−1,000..1,000].

My approach was if the array has zero or 1 element, the array given is returned else thne for loop is executed. I also added the new array to extract a subset of the array which was meant to be shifted and the first element of Array A is swapped with the last element. Finally, a new list is created with aim to achieve the insert the first element A[0] after being swapped.

public static int[] CyclicRotation(int[] A, int K)
    {
        //Rotate an array to the right by a given number of steps.
        // eg k= 1 A = [3, 8, 9, 7, 6] the result is [6, 3, 8, 9, 7]
        // eg k= 3 A = [3, 8, 9, 7, 6] the result is [9, 7, 6, 3, 8]

        if(A.Length== 0 || A.Length ==1)
        {
            return A;
        }
        int lastElement;
        int[] newArray = new int[A.Length];

        List<int> listOfNumbers = new List<int>();

        for (int i = 1; i < K+1; i++)
        {

            lastElement = A[A.Length - 1];
            newArray = A.Take(A.Length - 1).ToArray();
            listOfNumbers = newArray.ToList<int>();
            listOfNumbers.Insert(0, lastElement);

            A = listOfNumbers.ToArray();
            newArray = A;

        }
        return newArray;
    }

I believe there is room for improvements. Any suggestions would be appreciated.


texts:
I wrote a piece of code to benchmark the detection of perfect numbers up to 10000.  The original code is here, in C:

#include <stdio.h>

int isPerfectNumber(int num) {
    if (num == 1) { return 0; }

    int i, c = num - 1;
    for (i = 2; i <= num / 2; ++i) {
        if (num % i == 0) { c -= i; }
    }

    return c == 0;
}

int main(int argc, char* argv[]) {
    int i;
    for (i = 0; i < 10000; ++i) {
        if (isPerfectNumber(i)) {
            printf("%d\n", i);
        }
    }
    return 0;
}

I then wrote the same code in a number of different languages (C, C#, Java, V8 Javascript, Python and Go).

After benchmarking, I got the following results:

C: 92.8 ms
C#: 97.9 ms
Go: 208.85 ms
Java: 130.65 ms
V8 Javascript: 279.15 ms
Python: 1126.35 ms

I expected pretty much exactly this pattern of fastest to slowest, except for Go.  Why is my Go implementation so slow?  I admit I know very little about Go but I was under the impression that since it is a compiled language it is likely to be as fast as at least C# was.

Here is my Go implementation:

package main

import "fmt"

func main() {
    for i := 0; i < 10000; i++ {
        if (isPerfectNumber(i)) {
            fmt.Println(i)
        }
    }
}

func isPerfectNumber(num int) bool {
    if num == 1 { return false }

    c := num - 1
    for i := 2; i <= num / 2; i++ {
        if num % i == 0 { c -= i }
    }

    return c == 0
}

Have I just mucked something up or are the results I am seeing accurate?

FYI: I benchmark by running the code 10 times without timing it, then running another 20 times and take the average of those 20 tests.


texts: Using async / await with dynamic import() for ES6 modules

texts:
I am experimenting with the best way to standardise my dynamic import() expressions when importing javascript modules.

import() returns a promise, so, to handle the asynchronous steps after theimport() expression, I can use either:

.then() syntax; or
async / await syntax

Whilst I am quite familiar with the older XHR2 approach and somewhat familiar with ES2015 .then() syntax, I am less familiar with async / await syntax.

I understand that I can only use await inside a function which has been declared or assigned with async.

But I am trying to understand why Approach 1 works.

Approach 1:

(async () => {

  let myImportedModule = await import('/path/to/my-module.js');

  myImportedModule.myFunction1();
  myImportedModule.myFunction2();

})();

But Approach 2 does not.

Approach 2:

(async () => {

  await import('/path/to/my-module.js');

  myFunction1();
  myFunction2();

})();

Additional Notes:

Clearly I have something wrong, but I thought Approach 2 would be the async / await equivalent of this snippet (using .then() syntax):

import('/path/to/my-module.js')

  .then((myImportedModule) => {

    myImportedModule.myFunction1();
    myImportedModule.myFunction2();

  });

but that it would enable me to access myFunction1 and myFunction2 directly, without needing to give a name to the resolved Promise.


texts: Singly Linked List Implementation in ES6

texts:
This is my Singly Linked List implementation in ES6.

class LinkedList{

    constructor(){
        this.head = null;
        this.size = 0;
    }

    insert(item){
        this.size ++;
        let p = new Node(item);
        if(this.head === null){
            this.head = p;
        }
        else{
           p.next = this.head;
           this.head = p;
        }
    }
    insertAt(item, index){
        if(index > this.size){
            throw "Wrong index";
        }
        let p = new Node(item);
        if(index === 0){
            p.next = this.head;
            this.head = p;
            return;
        }
        let curr = this.head;
        while(curr !== null){
            if(index === 0){
                if(curr.next === null){
                    curr.next = p;
                    return;
                }
                else if(curr.next.next === null){
                    curr.next = p;
                }else{
                    curr.next.next = p.next;
                    curr.next = p;

                }
                return;
            }
            curr = curr.next;
            index --;
        }

    }
    remove(item){
        let curr, prev;
        prev = curr = this.head;
        if(item === curr.val){
            this.head = this.head.next;
            this.size --;
            return;
        }
        while(curr !== null){
            if (curr.val === item){
                prev.next = curr.next;
                this.size --;
                return;
            }
            prev = curr;
            curr = curr.next;

        }
        throw "Item doesn't exist in list."
    }
    length(){
        return this.size;
    }

    is_empty(){
        return this.size === 0;
    }
    printList(){
        let curr = this.head;
        let out = [];
        while(curr !== null){
            if(curr.next === null){
                out.push(curr.val);
            }else{
                out.push(curr.val);
                out.push("->")
            }
            curr = curr.next;
        }
        return out.join("");
    }
}
class Node{
    constructor(val){
        this.val = val;
        this.next = null;
    }
}

const list = new LinkedList();
list.insert(12);
list.insert(9);
list.insert(13);
list.insert(17);
console.log(list.printList());
list.remove(12);
console.log(list.printList());
console.log(list.length());
console.log(list.is_empty());
list.insertAt(21, 2);
console.log(list.printList());

Invite reviews please on all fronts, improvements, modern usage of JS.
Thanks.


texts:
I built my first long running AJAX heavy app and memory leaks are eating me alive.
I don't want to post too much code because it should be my job to fix it all, but I need some help.

Does this code leak? Where? Why? and if you'd be so kind as to suggest a fix.

function list_stuff(data, type, where, order) {
    var items = [];
    $.each(data, function (i, item) {
        items.push(
        //using jquery $data might make this look more readable
        '
 ' + '
' + item.name + '
' + '
' + item.description + '
' + '
' + 'Miles: ' + item.distance + '  People: ' + item.people);

        if (item.privacy != 0) {
            items.push('  (Private group) ');
        }
        if (where == '#thelist') {
            items.push('
' + '<button data-action ="2" type ="button" class ="join_button" onclick="join_group(this)">Join

');
        } else if (where == '#thelist2') {
            items.push('
' + '<button data-action= "4" type ="button" class ="join_button" onclick="join_group(this)">Leave

');
        }
    });

    if (order === 'append') {
        $(where).append(items.join(''));
    } else {
        $(where).prepend(items.join(''));
    }

    scroll.refresh();
}

My AJAX looks like this:

function ajax(send,where) {
    $.ajax({
        url: where,
        type: 'POST',
        dataType: 'json',
        data: send,
        success: function(a) {
            if (a.success===1) {
                list_stuff(a.data, a.type, '#list1','append');
            } else {
                create_group_problem(a.msg);
            }
            if(a.msg.length >1 ) {
                msg_disp(a.msg);
            }
        },
        error: function(err){
            msg_disp('error');
        }
    });
}

I understand (tenuously) that JavaScript gets garbage collected, but doesn't this form a circular reference that may prevent it from being collected? Please correct me if I'm wrong, but here is my reasoning:

list_stuff():

'<button data-action ="2" type ="button" class ="join_button" onclick="join_group(this)">Join

'

JS -> DOM
Generated LI Element:

onclick="join_group(this)"

DOM ->JS

Last question for the sake of learning/understanding: if this is not a circular reference, that will be prevented from being garbage collected, how can I change it to become one?

function join_group(block) {
    var $block = $(block);
    var pass   = 0;
    var c_id   = $block.closest("li").data("id");
    var p      = $block.closest("li").data("privacy");
    var action = $block.data("action");

    if(p !== 0 && action ==3){
        pass = prompt("This group requires a password to join.");
        if (pass === null || pass ==='') {
            return;
        }
    }

    var send ={
        group_id: c_id,
        group_action: action,
        privacy:p,
        password: pass,
    };

    ajax(send, 'group');
}


texts:
I'm working my way through the Rust Book:

Ch.8 Challenge:
Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in the company. For example, “Add Sally to Engineering” or “Add Amir to Sales”. Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

use std::collections::HashMap;
#[derive(Debug)]
enum Command {
    Add(String, String),
    List,
    Unknown
}

fn command_filter(input: String) -> Command {
    let mut command_string = input.split_whitespace();
    match command_string.next() {
        Some("Add") => {
            match (command_string.next(), command_string.last()){
                (Some(name), Some(dept)) => Command::Add(name.to_string(), dept.to_string()),
                _ => Command::Unknown
            }
        },
        Some("List") => Command::List,
        _ => Command::Unknown
    }
}

fn process_command(command: Command, employee_map: &mut HashMap<String, String>) {
    match command {
        Command::Add(name, dept) => {
            employee_map.insert(name, dept);
            ()
            },
        Command::List => {
            for (name, dept) in employee_map {
                println!("Name: {} Dept: {}", name, dept);
            };
        },
        Command::Unknown => println!("Unknown command!"),
    };
}

fn main() {
    let mut employee: HashMap<String, String> = HashMap::new();
    let command = command_filter(String::from("Add John to Eng"));
    process_command(command, &mut employee);

    let command = command_filter(String::from("Add Devon to Bio"));
    process_command(command, &mut employee);

    let command = command_filter(String::from("List"));
    process_command(command, &mut employee);
}

As with most devs starting to learn Rust I am finding difficulty with borrowing. I do not come from a C/C++ background and so I'm also finding pointers versus actual object a little tricky too.
Some specific thoughts:

I am suspicious that match statements inside match statements is not good practice.
The Command::Add branch in process_command feels a little hacky with the () return. Edit: After thinking more about this problem, I think if I wrapped the branch responses in Ok() then I could return a Result from that function.

Do you have any feedback?


texts: Editing  values through a textbox with jquery

texts:
I've written a script that will allow me to enter a serial number for each received product, in-line in a table. First you enter the amount received, which increases the size of the <select> to that amount. Then you can enter new serial numbers through the s/n text box, submitting with TAB or Return.

Additionally, selecting one of the options (empty or filled) will allow you to edit that specific option - otherwise, the next empty line is taken when submitting a serial number. It also checks if the entered serial number already exists, which disallows entering it. This works with multiple products (each tbody is a product "row").

I'm looking for any tips to improve style, best practices and performance. Thanks in advance.

Here's a working JSFiddle (I've translated the comments, but classes etc. are still Dutch):
http://jsfiddle.net/iv00w/7wds214d/

My HTML code:

                Amount: <input type="text" value="0" />

            omschrijving etc.

            Enter s/n:

                <input type="text" />

                <select size="0"></select>

And my Javascript:

$(".AantalOntvangen input").each(function () {
    $(this).keyup(function (event) {
        var aantal = $(this).val();

        // find the select box that holds the s/n
        var serieNrBox = $(this).parent().parent().nextAll().last().find("select");

        // resize it
        serieNrBox.prop("size", aantal);

        // append new options until it matches the size
        while (serieNrBox.children().length < aantal) {
            serieNrBox.append($("<option></option>"));
        }

        // select the first option
        $(serieNrBox).children().first().prop("selected", true);
    });
});

$(".SerieNr input").each(function () {
    $(this).keydown(function (event) {
        if (event.which == 9 || event.which == 13) {
            var serieNrBox = $(this).parent().parent().next().find("select");
            var selected = $("option:selected", serieNrBox);
            var emptyOptions = serieNrBox.find("option")
                .filter(function () {
                return !this.value || $.trim(this.value).length === 0;
            });
            var serienr = $(this).val();
            var exists = false;

            // the s/n has to be unique
            serieNrBox.children().each(function () {
                if ($(this).val() == serienr) {
                    // error
                    exists = true;
                }
            });

            // if it is unique, update the selected, or next empty, option
            if (exists === false) {
                if (selected.val().length > 0) {
                    emptyOptions.first().prop("selected", true);
                } else {
                    emptyOptions.next().first().prop("selected", true);
                }

                selected.text(serienr);
                selected.val(serienr);

                $(this).val("").focus();
            }
        }
    });
});

$(".SerieNr select").each(function () {
    $(this).change(function () {
        // update the textbox
        var selected = $("option:selected", this);
        var serieNr = $(this).parent().parent().prev().find("input");
        serieNr.val(selected.val()).focus().select();
    });
});


texts: Conway life game implementation with scala

texts:
I've tried to create optimal in terms of performance and memmory consumption. But also I've tried to make it functional and scala way. I want to get you comment on how to make it more 'scala'stic

object LifeGame extends App {
    trait Matrix extends Iterable[(Int, Int)] {
        def apply(p: (Int, Int)): Boolean
        def update(p: (Int, Int), b: Boolean): Unit
        def newInstance: Matrix;
    }

    class SparseMapMatrix extends Matrix {
        type Point = (Int, Int)

        private var data = Set[(Int, Int)]()

        def apply(p: Point): Boolean = data.contains(p)

        def update(p: Point, b: Boolean) = if (b) data += p else data -= p

        def newInstance = new SparseMapMatrix()

        def iterator = data.iterator

        override def toString() = {
            val sb = new StringBuilder()
            def best(func: (Int, Int) => Int)(p1: Point, p2: Point) = (func(p1._1, p2._1), func(p1._2, p2._2))
            val minBoundary = ((0, 0) /: iterator)(best(math.min))
            val maxBoundary = ((0, 0) /: iterator)(best(math.max))
            for (i <- minBoundary._1 to maxBoundary._1) {
                sb.append("\n")
                for (j <- minBoundary._2 to maxBoundary._2) {
                    sb.append(if (this((i, j))) "x" else " ")
                }
            }
            sb.append("\nmin=%s, max=%s" format(minBoundary, maxBoundary))
            sb.toString()
        }
    }

    object Engine {
        def apply(input: Matrix): Matrix = {
            val result = input.newInstance
            def block2D(pp: (Int, Int)): Seq[(Int, Int)] =
                for (ii <- block1D(pp._1); jj <- block1D(pp._2)) yield (ii, jj)
            val liveCells = for (p <- input.iterator.flatMap(block2D).toSet[(Int, Int)].par) yield {
                val offsets = block2D(p).filter(_ != p)
                val nn = offsets.map(p => input(p)).count(_ == true)
                case class State(l: Boolean, n: Int)
                val newValue = State(input(p), nn) match {
                    case State(true, n) if n < 2 => false
                    case State(true, 2) | State(true, 3) => true
                    case State(true, n) if n > 3 => false
                    case State(false, 3) => true
                    case State(value, _) => value
                };
                 if(newValue) Some(p) else None
            }
            liveCells.seq.foreach { _ match { case Some(p:Point) => result(p) = true; case _ => ;}}
            result
        }
    }

    def block1D(i: Int) = i - 1 to i + 1

}


texts: Serialize and deserialize n dimensional int array

texts:
I've made two symmetric methods which serialize an int array of any number of dimensions into an OutputStream, and read such an array from an InputStream. I was wondering if there is ways this code could be improved. (I have tested this code and it works correctly.) Thanks!

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;

public class IntArraySerializer {

    private IntArraySerializer() {}

    /**
     * Writes arr, which is assumed to be an n dimensional int array, to out.
     */
    public static void writeIntArr(Object arr, OutputStream out) throws IOException {
        writeInt(dimensions(arr.getClass()), out);
        writeIntArrRaw(arr, out);
    }

    /**
     * Reads an n dimensional int array from in. Symmetrical to writeIntArr.
     */
    public static Object readIntArr(InputStream in) throws IOException {
        int dimensions = readInt(in);
        return readIntArrRaw(in, dimensions - 1);
    }

    private static void writeIntArrRaw(Object obj, OutputStream out) throws IOException {
        if (obj.getClass().isArray()) {
            writeInt(Array.getLength(obj), out);
            for (int i = 0; i < Array.getLength(obj); i++) {
                writeIntArrRaw(Array.get(obj, i), out);
            }
        } else {
            writeInt((Integer) obj, out);
        }
    }

    private static Object readIntArrRaw(InputStream in, int dimensionsRemaining) throws IOException {
        int length = readInt(in);
        Object[] out = new Object[length];
        if (dimensionsRemaining == 0) {
            for (int i = 0; i < length; i++) {
                out[i] = readInt(in);
            }
        } else {
            for (int i = 0; i < length; i++) {
                out[i] = readIntArrRaw(in, dimensionsRemaining - 1);
            }
        }
        return out;
    }

    public static void writeInt(int n, OutputStream out) throws IOException {
        out.write(new byte[] {
                (byte) ((n & 0xFF000000) >> 24),
                (byte) ((n & 0x00FF0000) >> 16),
                (byte) ((n & 0x0000FF00) >> 8),
                (byte) (n & 0x000000FF)
                });
    }

    public static int readInt(InputStream in) throws IOException {
        byte[] buffer = new byte[4];
        in.read(buffer);
        return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
    }

    /**
     * @param clazz a class of array
     * @return how many dimensions clazz represents, or 0 if clazz doesn't represent an array.
     */
    public static int dimensions(Class<?> clazz) {
        if (clazz.isArray())
            return dimensions(clazz.getComponentType()) + 1;
        else
            return 0;
    }

}


texts: Create a structure to store data about a movie

texts:
Below are the instructions for my program and the source code. My program runs and works but I would like second opinions on how to make my program more efficient or if there are any loose ends in my source code.

Using functional decomposition, write a C++ program that will use a structure called MovieData to store the following information.

Title
Director
Year Released
Running time (in minutes)
Production cost
First Year Revenue.

Then use a value returning function called getMovieData() to read data to each
component of a struct variable as stated above. This function must return a
variable of type MovieData.

Also use a void function called printMovieData() to print each member of struct
in a nice format (with appropriate description). This function will accept a
pointer to type MovieData, that is, its prototype will be like this:
void printMovieData(MovieData *);

In your main() program, declare two variable of type MovieData with the following declaration: MovieData m1,m2;

And then call getMovieData() to assign value to each of m1 and m2.

Finally call printMovieData() on each of m1 and m2 to print values in each struct.

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

struct MovieData
{
    string title;
    string director;
    int year_released;
    int running_time;
    int production_cost;
    int first_year_revenue;
};

// Function prototypes
MovieData getMovieData();
void printMovieData(MovieData *);

int main()
{
    // Variables
    MovieData m1, m2;
    MovieData *ptr1, *ptr2;
    ptr1 = &m1;
    ptr2 = &m2;

    // Call getMovieData function to get information for both movies
    m1 = getMovieData();

    m2 = getMovieData();

    // Call printMoviedata function to print information for both movies
    printMovieData(ptr1);

    cout << "\n";

    printMovieData(ptr2);

    system("PAUSE");

    return 0;
}

/**
* Pre-Condition:
* Post-Condition:
*/
MovieData getMovieData()
{
    // Variables
    MovieData temp;

    // Prompt user for information
    cout << "Enter the title of the movie: ";
    getline(cin, temp.title);

    cout << "\n";

    cout << "Enter the name of the movie's director: ";
    getline(cin, temp.director);

    cout << "\n";

    cout << "Enter the year the movie was released: ";
    cin >> temp.year_released;

    cout << "\n";

    cout << "Enter the running time of the movie in minutes: ";
    cin >> temp.running_time;

    cout << "\n";

    cout << "Enter the production cost of the movie: $";
    cin >> temp.production_cost;

    cout << "\n";

    cout << "Enter the movie's first year revenue: $";
    cin >> temp.first_year_revenue;

    cin.ignore();

    cout << "\n";

    return temp;
}

/**
* Pre-Condition:
* Post-Condition:
*/
void printMovieData(MovieData *pointer)
{
    cout << "Title: " << pointer->title << endl;
    cout << "Director: " << pointer->director << endl;
    cout << "Year Released: " << pointer->year_released << endl;
    cout << "Running Time: " << pointer->running_time << endl;
    cout << "Production Cost: " << pointer->production_cost << endl;
    cout << "First Year Revenue: " << pointer->first_year_revenue << endl;
    cout << "\n";
}


texts: Pythonic way to flatten nested dictionarys

texts:
Here's my attempt to write a function that flattens a nested dictionary structure in Python 3.6

This came about because I had a nested dictionary structure of data I wanted to visualize in the library Bokeh.

I didn't like other examples that require a recursive function call. (I find it difficult to reason about, and I believe python has a relative small recursion limit)

Tell me about the styling, ease of (or lack of) understanding and what you would do.

Here's my code:

def flatten_dict(dictionary, delimiter='.'):
    """
    Function to flatten a nested dictionary structure
    :param dictionary: A python dict()
    :param delimiter:  The desired delimiter between 'keys'
    :return: dict()
    """

    #
    # Assign the actual dictionary to the one that will be manipulated
    #
    dictionary_ = dictionary

    def unpack(parent_key, parent_value):
        """
        A function to unpack one level of nesting in a python dictionary
        :param parent_key: The key in the parent dictionary being flattened
        :param parent_value: The value of the parent key, value pair
        :return: list(tuple(,))
        """

        #
        # If the parent_value is a dict, unpack it
        #
        if isinstance(parent_value, dict):
            return [
                (parent_key + delimiter + key, value)
                for key, value
                in parent_value.items()
            ]
        #
        # If the If the parent_value is a not dict leave it be
        #
        else:
            return [
                (parent_key, parent_value)
            ]

    #
    # Keep unpacking the dictionary until all value's are not dictionary's
    #
    while True:
        #
        # Loop over the dictionary, unpacking one level. Then reduce the dimension one level
        #
        dictionary_ = dict(
            ii
            for i
            in [unpack(key, value) for key, value in dictionary_.items()]
            for ii
            in i
        )
        #
        # Break when there is no more unpacking to do
        #
        if all([
            not isinstance(value, dict)
            for value
            in dictionary_.values()
        ]):
            break

    return dictionary_


texts: Iterating through two objects with different structures in parallel

texts:
I have two objects, one input = Array<Type> and one stored = Array<{..., Type}>

What's the best (cleanest) way to put the elements in the first array into the sub-elements of the second? We can assume they're of the same size.

My current code below works, but looks bad due to the double iterator usage.

var count = 0;
stored.forEach((obj)=> {
    obj.value = input[count];
    count++;
});

Is there some sort of prototyping that I can use to shorten the code up?


texts:
I have 2 strings for example:

abcabc and bcabca

or

aaaabb and abaaba

I checked that second string is the same or not like first string but shifted.
bcabca = ..abca + bc...

using System;

public class TOPSES
{
    static string t1, t2;
    static char[] t1c;
    static char[] t2c;

    static void Main()
    {
        int t;
        t = int.Parse(Console.ReadLine());

        while (t > 0)
        {
            t1 = Console.ReadLine();
            t2 = Console.ReadLine();

            string result = "no";

            t1c = t1.ToCharArray();
            t2c = t2.ToCharArray();

            result = ChangeString(t1c[0], 0);

            Console.WriteLine(result);
            t--;
        }
    }

    public static string ChangeString(char letter, int startIndex)
    {
        int index = t2.IndexOf(letter, startIndex);
        if (index == -1)
            return "no";
        else
        {
            string newString = t2.Remove(0, index);
            newString += t2.Remove(index, t2.Length - index);

            if (t1 != newString)
                return ChangeString(letter, ++index);

            return "yes";
        }
    }
}

How can I improve this code to make it faster? Also, it will be nice if someone could explain what makes this 'program' slow.


texts:
I am using the following code in a Node.js / React project. It works fine but it looks like it could be consolidated a little more using a OO pattern.

import projectsData from '../data/index.js';

function Project(project) {
  this.name = project.name;
  this.order = project.order;
  this.title = project.title;
  this.date = project.date;
  this.tags = project.tags;
  this.logo = project.logo;
  this.html = project.html;
  this.agency = project.agency;
  this.slides = Object.values(project.slides).map(slide => slide);
  this.path = `projects/${this.name}`;
  this.route = `/projects/${this.name}`;
  this.slidesPath = `/projects/${this.name}/slides/`;
  this.hiDefAffix = '@2x';
};

const all = {};
Object.values(projectsData).map(project => all[project.name] = new Project(project));

const projects = {
  all,
  sorted(){ return Object.values(this.all).sort((a, b) => a.order - b.order) },
  get(project) {
    try {
      if (this.all[project]){
        return this.all[project];
      } else {
        throw new Error(`Project "${project}" not found.`);
      }
    } catch (error) {
      return false;
    }
  },
  toJSON() {
    return JSON.stringify(this.all);
  }
};

export default projects;

Basically I have a constructor and an exported object that ends up having a bunch of objects created by the constructor above it. Can these be consolidated in some way?


texts:
I'm trying to practice some C++ and I wrote a simple queue to solve the Producer-Consumer Problem.

class Queue
{

public:
Queue() : mutex(), cv(), queue(), process(true), consumer(&Queue::dequeue, this)
{
}

~Queue()
{
    process = false;
    consumer.join();
}

void enqueue(int i)
{
    std::lock_guard<std::mutex> lock(mutex);
    queue.push(i);
    cv.notify_all();
}

void dequeue()
{
    while(process)
    {
        std::unique_lock<std::mutex> lock(mutex);
        while(queue.empty())
        {
            cv.wait(lock);
        }

        if(!process)
        {
            break;
        }

        int i = queue.front();
        queue.pop();
        std::cout << "Got " << i << '\n';
    }
}

private:
std::mutex mutex;
std::condition_variable cv;
std::queue<int> queue;
bool process;
std::thread consumer;

};

Is my implementation good? Is there anything I could've done better?


texts:
I have two questions about my code:

Are there any performance improvements in this implementation or generally (register int ?) that I could make?
What could I improve in my coding style?

void mergesortArray(int data[], int amount){

    if(amount == 1) return;

    //Precomputing values
    int sizeint = sizeof(int);
    int amountLeft = amount / 2;
    int amountRight = (amount % 2 == 0) ? amountLeft : (amountLeft + 1);

    //Splitting the array in right and left
    int *left = calloc(amountLeft, sizeint);
    int *right = calloc(amountRight, sizeint);
    if(left == NULL || right == NULL) return;

    //Copying the splitted content
    memcpy(left, data, amountLeft * sizeint);
    memcpy(right, data + amountLeft, amountRight * sizeint);

    //Recursive sorting the splitted arrays
    mergesortArray(left,amountLeft);
    mergesortArray(right,amountRight);

    //Merging the numbers
    int *pos1 = &left[0];
    int *pos2 = &right[0];
    int i = 0;
    for(i = 0; i < amount; i++) {
        if(*pos1 <= *pos2) {
            data[i] = *pos1;
            if (pos1 == &right[amountRight - 1])
                break;
            if(pos1 == &left[amountLeft - 1])
                pos1 = &right[amountRight - 1];
            else
                pos1++;
        }
        else {
            data[i] = *pos2;
            if(pos2 == &right[amountRight - 1])
                pos2 = &left[amountLeft - 1];
            else
                pos2++;
        }
    }
}


texts: A bag of numbers in C++ for constant time statistics queries

texts:
(See the next iteration.)

I have this simple "data structure" for storing numbers and querying the statistics on them (average, variance and standard deviation):

numberbag.hpp

#ifndef CODERODDE_STAT_NUMBER_BAG
#define CODERODDE_STAT_NUMBER_BAG

#include <cmath>
#include <cstdlib>
#include <iostream>

namespace coderodde {

    namespace stat {

template<typename Num = long double>
class number_bag {

    size_t m_size;
    Num    m_sum;
    Num    m_square_sum;

public:
    number_bag() : m_size{0}, m_sum{0}, m_square_sum{0} {}

    void add(Num num) {
        m_size++;
        m_sum += num;
        m_square_sum += num * num;
    }

    void remove(Num num) {
        m_size--;
        m_sum -= num;
        m_square_sum -= num * num;
    }

    void clear() {
        m_size = 0;
        m_sum = 0;
        m_square_sum = 0;
    }

    size_t size() const {
        return m_size;
    }

    Num ave() const {
        return m_sum / m_size;
    }

    Num var() const {
        Num step1 = m_square_sum - m_sum * m_sum / m_size;
        return step1 / (m_size - 1);
    }

    Num std() const {
        return sqrt(var());
    }
};

template<typename Num>
std::ostream& operator<<(std::ostream& out, number_bag<Num> const &bag)
{
    out << "[size=" << bag.size() << ", ave=" << bag.ave() << ", var="
        << bag.var() << ", std=" << bag.std() << "]";
    return out;
}

    } // end of namespace coderodde::stat

} // end of namespace coderodde

#endif // CODERODDE_STAT_NUMBER_BAG

main.cpp

#include "numberbag.hpp"
#include <iostream>

int main(int argc, const char * argv[]) {
    using coderodde::stat::number_bag;
    using namespace std;

    number_bag<> bag;
    bag.add(1.0);
    bag.add(1.0);
    bag.add(3.0);

    cout << bag << "\n";

    bag.remove(1.0);

    cout << bag << "\n";

    bag.clear();

    cout << bag << "\n";
    return 0;
}

Demo output

[size=3, ave=1.66667, var=1.33333, std=1.1547]
[size=2, ave=2, var=2, std=1.41421]
[size=0, ave=nan, var=nan, std=nan]

Critique request

Please tell me anything that comes to mind. Especially, I am not sure that putting the output override (operator<<) in the namespace is OK.


texts: Throttled execution of an enumeration of Tasks

texts:
Example of use:
var users = await usernames.SelectTaskResults(GetUserDetails, 4);

where GetUserDetails(string username) is a method that calls HttpClient to access an API and returns a User object. The SelectTaskResults returns the awaited tasks. At most, there will be 4 concurrent threads calling the API at the same time for this example.
Concerns:
I'm worried .Wait() could cause a deadlock.
Code:
public static async Task<IEnumerable<TResult>> SelectTaskResults<TInput, TResult>(
        this IEnumerable<TInput> source,
        Func<TInput, Task<TResult>> taskFunc,
        int degreesOfParallelism = 1,
        bool throwFaulted = false,
        CancellationToken cancellationToken = default(CancellationToken))
    {
        // Task.Run creates the task but it doesn't start executing immediately - for debugging
        var tasks = source
            .Select(input => Task.Run(() => taskFunc(input), cancellationToken))
            .ToArray();

        Parallel.ForEach(tasks,
            new ParallelOptions { MaxDegreeOfParallelism = degreesOfParallelism }
            , task =>
            {
                try
                {
                    task.Wait(cancellationToken); // .Start() doesn't work for promise-like tasks
                }
                catch (Exception)
                {
                    if (throwFaulted)
                    {
                        throw;
                    }
                }
            }
        );

        var output = await Task.WhenAll(tasks.Where(x=> !x.IsFaulted));

        return output.AsEnumerable();
    }


texts:
I am looking for suggestions of improving this function to check whether a memory address is appropriate or not.

def isweird(addr, cpu_name):
    """Check if a memory address is weird
    Args:
        addr (str): a memory address
        cpu_name (str): cpu name
    Returns:
        bool: True if the address is weird
    """
    if not isinstance(addr, six.string_types):
        raise Exception('The memory address must be a string.')

    if addr == '0x0':
        return True

    addr = addr.lower()

    # Strip leading zeroes
    addr = addr[2:].lstrip('0')

    if utils.is64(cpu_name):
        if len(addr) <= 8:
            val = int(addr, 16)
            if val <= (1 << 16):  # val <= 0xffff (ie: first 64k)
                return True
        elif addr.startswith('ffffffff'):
            addr = addr[8:]  # 8 == len('ffffffff')
            val = int(addr, 16)
            if val >= ((1 << 32) - (1 << 16)):  # val >= 0xffffffffffff0000 (ie: last 64k)
                return True
    else:
        val = int(addr, 16)
        if val <= 1 << 16:  # val <= 0xffff (ie: first 64k)
            return True
        if val >= ((1 << 32) - (1 << 16)):  # val >= 0xffff0000 (ie: last 64k)
            return True
    return False


texts: F#, Timer and propperly removed ElapsedEventHandler

texts:
I have a simple method that receives messages from bus, builds response and send it back, and it looks like:

let readFromBusAndSendRequest =
        let mutable timer = new Timer(float 10000)
        let OnTimedEvent (frameId:uint32, projectId:uint32, cabinId:byte) (bus:IBus) : ElapsedEventHandler =
            new ElapsedEventHandler (fun _ _ ->
                printfn "Publishing UM1 Request %A Frame %A" DateTime.Now framId
                //Create request
                bus.Publish<RequestMessage>(request, HubSubscriptionId))

        match this.Bus with
        | Some bus ->
            let cabinetSubscribeId = sprintf "Project.%i.Cabin.%i" this.ProjectId this.CabinId
            let busResponseFactory (response : BasicMessage) =
            match response.FrameType with
            | FrameType.SERVICE_LIST ->
                let serviceListResponse : ServiceListMessage = response :?> ServiceListMessage
                let isMessageValid = serviceListResponse.FrameWithoutCrc.IsValidCrc32(serviceListResponse.ResponseCrc32)
                match isMessageValid with
                | true ->
                     publishAck bus (serviceListResponse, RequestedService.Unknown)
                     timer.Dispose()
                     timer <- new Timer(float 10000, AutoReset = true)
                     timer.AutoReset <- true
                     timer.Elapsed.AddHandler(OnTimedEvent ((serviceListResponse.FrameId + 1u), this.ProjectId, byte this.CabinId) bus)
                     timer.Start();
                | false -> publishNack bus (serviceListResponse, RequestedService.Unknown) NackRejectionReason.InvalidCrc
           | false -> publishNack bus (serviceResponse, serviceResponse.RequestedService) NackRejectionReason.InvalidCrc
         | _  -> printfn "OTHER SUPPORT"

    let handler = Action<ResponseMessage>(fun response ->
          printfn "Response %A frame type %s response id %i" response.ProjectId (response.FrameType.ToString()) response.FrameId;
          busResponseFactory response |> ignore)

    bus.Subscribe<ResponseMessage>(cabinetSubscribeId, handler, Action<FluentConfiguration.ISubscriptionConfiguration>(fun sub -> sub.WithTopic(cabinetSubscribeId) |> ignore)) |> ignore

When I get a certain type of response(in this case SERVICE_LIST), I want it to attach an event to the Timer, and make it run each 10 seconds. All parameters needed are from message received from bus

As you see, I used a mutable timer because each time I press I receive new SERVICE_LIST message, an event is added but but not removed, and believe me I tried:

  timer.Elapsed.RemoveHandler(OnTimedEvent frameId)

Probably because frame id is different every time.

Instead of dispose, but it did not work; new events were just added but not removed. So is there a better way to conquer this mess?

I know it is because I create new event each time, but how to remove old one?


texts:
I want to know the performance of my code for following problem description.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.

public static int getBinaryGap(int N) {
    if (N < 5) {
        return 0;
    }
    String binaryRep = Integer.toBinaryString(N);
    int currentGap = 0;
    int finalGap = 0;
    for (int i = 0; i+1 < binaryRep.length(); i++) {
        if (currentGap == 0) {
            if (binaryRep.charAt(i) == '1' && binaryRep.charAt(i + 1) == '0') {
                currentGap++;
            }
        } else {
            if (binaryRep.charAt(i + 1) == '0') {
                currentGap++;
            }
            if (binaryRep.charAt(i + 1) == '1') {
                finalGap = finalGap<currentGap ? currentGap:finalGap;
                currentGap = 0;
            }
        }
    }
    return finalGap;
}


texts:
To convert JPEG file, C function, bgraToGrayscale is called from Swift.

Is there a better way to

1.allocate memory and

2.access pointers

than the ways they have been done in code below?

And maybe things that have been completely missed, like freeing memory?

converter.swift

func BGRAToGrayscale(srcImg: CGImage) -> CGImage {
    let BytesPerPixel = 4

    guard let srcProv = srcImg.dataProvider else { fatalError("dataProvider is nil") }
    guard let srcProvData = srcProv.data else { fatalError("dataProvider.data is nil") }

    let srcPtr = CFDataGetBytePtr(srcProvData)
    let srcSize = srcImg.width * srcImg.height * BytesPerPixel

    var destPtr = [CUnsignedChar](repeating: 0, count: srcSize)
    bgraToGrayscale(&destPtr, srcPtr, Int32(srcImg.width), Int32(srcImg.height))

    let destCgContext = CGContext(data: &destPtr,
                                  width: srcImg.width, height: srcImg.height,
                                  bitsPerComponent: srcImg.bitsPerComponent,
                                  bytesPerRow: srcImg.bytesPerRow,
                                  space: srcImg.colorSpace!,
                                  bitmapInfo: srcImg.bitmapInfo.rawValue)

    guard let destImg = destCgContext?.makeImage() else {
      fatalError("Destination Image is nil")
    }

    return destImg
}

converter.c (slow way of converting to grayscale, will write assembly code for this, just for the sake of learning :-) )

void bgraToGrayscale( unsigned char * __restrict dest, const unsigned char* src, int width, int height ) {
  int BYTES_PER_PIXEL = 4;
  int numPixels = width * height;

  for( int idx=0; idx < numPixels; idx++ ) {

    float weight = ((float)src[0]) * 0.11 +
                  ((float)src[1]) * 0.59 +
                  ((float)src[2]) * 0.3;

    dest[0] = (int)weight;
    dest[1] = (int)weight;
    dest[2] = (int)weight;
    dest[3] = src[3];
    dest += BYTES_PER_PIXEL;
    src += BYTES_PER_PIXEL;
  }
}


texts:
What do you think?  In particular, I'm not sure about my exception handling approach to raise errors when posting objects; but I couldn't come up with anything better.

public class Thing
{
    public Thing(int number)
    {
        Number = number;
    }

    public int Number { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var thingBatcher = new Batcher<Thing>(ProcessBatch, 100, TimeSpan.FromSeconds(30));

        try
        {
            for (var i = 0; i < int.MaxValue; i++)
            {
                thingBatcher.Post(new Thing(i));
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Here:" + ex.Message);
            throw;
        }

        Console.ReadLine();
    }

    private static void ProcessBatch(IEnumerable<Thing> things)
    {
        Console.WriteLine("Batch found: " + things.Count());

        if (things.Any(thing => thing.Number == 400))
        {
            throw new InvalidOperationException("Something bad happened");
        }
    }
}

public class Batcher<T>
{
    private BufferBlock<T> _buffer;

    private ActionBlock<IEnumerable<T>> _actionBlock;

    public Batcher(
        Action<IEnumerable<T>> processBatch,
        int batchSize,
        TimeSpan maxTimeWaitingForBatch)
    {
        Initialize(batchSize, processBatch, maxTimeWaitingForBatch);
    }

    private void Initialize(int batchSize,
        Action<IEnumerable<T>> processBatch,
        TimeSpan maxTimeWaitingForBatch)
    {
        _buffer = new BufferBlock<T>();

        var batchStockEvents = new BatchBlock<T>(batchSize);

        // Use a timer to make sure that items do not remain in memory for too long
        var triggerBatchTimer = new Timer(delegate { batchStockEvents.TriggerBatch(); });

        // Use a transform block to reset the timer whenever an item is inserted to avoid unnessary batches
        var timeoutBlock = new TransformBlock<T, T>((value) =>
        {
            triggerBatchTimer.Change(maxTimeWaitingForBatch, TimeSpan.FromMilliseconds(-1));
            return value;
        });

        _actionBlock = new ActionBlock<IEnumerable<T>>(processBatch);

        _buffer.LinkTo(timeoutBlock);
        timeoutBlock.LinkTo(batchStockEvents);
        batchStockEvents.LinkTo(_actionBlock);

        _actionBlock.Completion.ContinueWith(x =>
        {
            // todo log exception here
            Console.WriteLine(x.Exception.Message);

        }, TaskContinuationOptions.OnlyOnFaulted);
    }

    public void Post(T someObject)
    {
        if (_actionBlock.Completion.IsCompleted)
        {
            throw new InvalidOperationException("The batcher is not accepting new objects as it is in a failed state");
        }

        _buffer.Post(someObject);
    }
}


texts:
I have a controller that pulls gets data from two different JSON files. One of the calls loadProducts happens when the controller is initiated. The other one, loadPrices, is called when a user clicks a button on the interface.

I have noticed that the controller is starting to get bigger and I was worried about the state of the code. As I am knew to this I was hoping for suggestions about how I can clean it up or make it more efficient.

'use strict';
(function () {

var app = angular.module('priceQuoteApp');

var quoteBuilderController = function ($scope, $http, $timeout) {

    //set the variabls
    $scope.listOfProducts = null;
    $scope.selectedProduct = null;
    $scope.listOfProductVariants = null;
    $scope.formData = {};
    $scope.showTable = 'none';
    $scope.selectedProductId = null;
    $scope.loadingProducts = true;
    $scope.loadedProducts = false;
    $scope.loadingPrices = false;
    $scope.loadedPrices = false;

    // get all the portfolios and the products
    // the timer is to simulate network latency
    var loadProducts = function () {
      $http.get('scripts/json/sample-products.json')
        //$http.get('http://www.thesite/api/Pricing/GetProductCatalogue')
            .then(function (allProducts) {
                $scope.listOfProducts = allProducts.data.Connectivity;
            })
            .finally(function () {
                $scope.loadingProducts = false;
                $scope.loadedProducts = true;
            });
    };
    //loadProducts();
   $timeout(loadProducts, 2000);

    // get all the prices
    // the timer is to simulate network latency
    var loadPrices = function () {
        $http.get('scripts/json/sample-product-prices.json')
            .then(function (res) {
                $scope.selectedProductPrices = res.data.ProductVariants;
                $scope.selectedProductAddOns = res.data.product_addons;
            })
            .finally(function () {
                $scope.loadingPrices = false;
                $scope.loadedPrices = true;
            });
    };

    // get the product details
    $scope.getProductDetails = function (item) {
        $scope.selectedProduct = item.product_name;
        $scope.selectedProductId = item.product_id;
        $scope.listOfProductVariants = item.product_variants;
        $scope.formFields = item.product_price_attributes;
    };

    // select the product and get the price
    $scope.selectProduct = function (item) {
        $scope.selectedRow = item;
        $scope.selectedProductPrice = item.RecurringCost;
    };

    // replace this with api calls to get the prices
    $scope.getProductVariants = function () {
        $scope.loadingPrices = true;
        $timeout(loadPrices, 2000);
    };
};

app.controller('quoteBuilderController', ['$scope', '$http', '$timeout', quoteBuilderController]);

}());

One this for sure is that I should probably break it up as its becoming long. Is there a need to define the variables at the top? Should I be using the This keyword?


texts:
I want to upload images to server from browser window. I'm using this function for image upload. Images are uploaded by GD library.

What is your opinion of this code? Is there still a way to upload a malicious file?

<?php
function imageUpload($name, $thumb = false, $max_size = 5242880, $height = null, $width = null, $T__height = 100, $T__width = 100)
{
    if(!isset($_FILES[$name]))
    {
        return false;
    }

    $allowedTypes = array('image/gif', 'image/jpeg', 'image/png', 'image/wbmp');
    $image = &$_FILES[$name];

    if ($image['error'] == 0 && in_array($image['type'], $allowedTypes) && $image['size'] <= $max_size)
    {
        $in = '';
        switch ($image['type'])
        {
            case 'image/gif':
                $in = 'imagecreatefromgif';
                break;
            case 'image/jpeg':
                $in = 'imagecreatefromjpeg';
                break;
            case 'image/png':
                $in = 'imagecreatefrompng';
                break;
            case 'image/wbmp':
                $in = 'imagecreatefromwbmp';
                break;
        }

        if ($in == '')
        {
            return false;
        }

        $src = $in($image['tmp_name']);
        $height = ($height == null || $height <= 0 ? imagesy($src) : $height);
        $width = ($width == null || $width <= 0 ? imagesx($src) : $width);

        $dst = imagecreatetruecolor($width, $height);
        imagecopyresized($dst, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));

        $fileName = '';
        do
        {
            $fileName = makeHash(mt_rand(0, mt_getrandmax()) . microtime(true), $image['tmp_name']);
        }
        while(file_exists('/image/' . $fileName . '.jpg') || ($thumb && file_exists('/thumb/' . $fileName . '.jpg')));
        if ($fileName == '')
        {
            return false;
        }

        imagejpeg($dst, '/image/' . $fileName . '.jpg', 75);

        if ($thumb)
        {
            $dst = imagecreatetruecolor($T__width, $T__height);
            imagecopyresized($dst, $src, 0, 0, 0, 0, $T__width, $T__height, imagesx($src), imagesy($src));
            imagejpeg($dst, '/thumb/' . $fileName . '.jpg', 75);
        }

        imagedestroy($src);
        imagedestroy($dst);

        return $fileName . '.jpg';
    }
}
?>


texts: Linear conflicts heuristic for 15 puzzle game

texts:
I'm trying to solve the 15 Puzzle problem using IDA* algorithm with a Linear Conflicts heuristic. I already implemented the heuristic from what I understood : link
Here's my goal state ("snail" format) and initial state :
GOAL_STATE =
[[ 1  2  3  4]
 [12 13 14  5]
 [11  0 15  6]
 [10  9  8  7]]

INITIAL STATE =
[[11  3  4  2]
 [14  8 12  9]
 [ 5  0 13  6]
 [ 7 15  1 10]]

I'm wondering how I can optimize my code (the linear_conflict_heuristic() function) which seems to be very redundant.
Also I'm not sure how I should be counting these slides (3, 4, 2) on the initial state. Does that count for 2, 3 or 4 conflicts ?
Here's my code so far :

import numpy as np

m = [[0] * 4 for i in range(4)]
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
x, y, c = 0, -1, 1
for i in range(4 + 4 - 2):
    for j in range((4 + 4 - i) // 2):
        x += dx[i % 4]
        y += dy[i % 4]
        m[x][y] = c
        c += 1

BOARD_LENGTH = 4
GOAL_STATE = np.array(m)

def goal_on_row(num, i):
    for j in range(BOARD_LENGTH):
        if num == GOAL_STATE[i][j]:
            return j

def goal_on_column(num, j):
    for i in range(BOARD_LENGTH):
        if num == GOAL_STATE[i][j]:
            return i

def linear_conflict_heuristic(state):
    result = 0
    for i in range(BOARD_LENGTH):
        for j in range(BOARD_LENGTH):
            num = state[i][j]
            if num != 0:
                position = goal_on_row(num, i)
                if position is not None:
                    if position <= j:
                        for k in reversed(range(j)):
                            num2 = state[i][k]
                            if num2 != 0:
                                position2 = goal_on_row(num2, i)
                                if position2 is not None:
                                    if position < position2:
                                        result += 1
                    else:
                        for k in range(j + 1, BOARD_LENGTH):
                            num2 = state[i][k]
                            if num2 != 0:
                                position2 = goal_on_row(num2, i)
                                if position2 is not None:
                                    if position > position2:
                                        result += 1

                position = goal_on_column(num, j)
                if position is not None:
                    if position <= i:
                        for k in reversed(range(i)):
                            num2 = state[k][j]
                            if num2 != 0:
                                position2 = goal_on_column(num2, j)
                                if position2 is not None:
                                    if position < position2:
                                        result += 1
                    else:
                        for k in range(i + 1, BOARD_LENGTH):
                            num2 = state[k][j]
                            if num2 != 0:
                                position2 = goal_on_column(num2, j)
                                if position2 is not None:
                                    if position > position2:
                                        result += 1

    return result

def main():
    state = np.array([[11, 3, 4, 2], [14, 8, 12, 9], [5, 0, 13, 6], [7, 15, 1, 10]])
    result = linear_conflict_heuristic(state)
    print(f"RESULT = {result}")

if __name__ == '__main__':
    main()


texts:
I created an example of a simple form for multiple inputs (name and phone number) in React. If the user enters invalid data in input field, error text is displayed near the same field. I learned a lot of different examples of the form validation using React and I don't understand where is the better place for validation checking in form.

import React from 'react'
import { render } from 'react-dom'

const ErrorOutput = props => {
  let name = props.name
  let inputValue = props.case
  if (name === 'firstName') {
    if (!inputValue.match(/^[a-zA-Z]+$/) && inputValue.length > 0) {
        return Letters only
      }
    return
  }
  if (name === 'telNo') {
    if(!inputValue.match(/^[0-9]+$/) && inputValue.length > 0) {
        return Numbers only
      }
    return
  }
}

class App extends React.Component {
  constructor(props){
    super(props)

    this.state = {
      firstName: '',
      telNo: ''
    }
  }

  handleValidation(e) {
    this.setState({
      [e.target.name]: e.target.value
    })
  }

  render() {
    return (
      <form>

          First name:

        <input
          type='text'
          name ='firstName'
          value = {this.state.firstName}
          onChange = {this.handleValidation.bind(this)}
        />
        <ErrorOutput case={this.state.firstName} name={'firstName'} />

          Phone number:

        <input
          type='tel'
          name ='telNo'
          value = {this.state.telNo}
          onChange = {this.handleValidation.bind(this)}
        />
        <ErrorOutput case={this.state.telNo} name={'telNo'} />
      </form>
    )
  }
}

render(
  <App />,
  document.getElementById('root')
)


texts:
The biggest question is if it's worth it to use a useless if statement to make the x and y variables local away from the main statement.

    //Unconventional part, make it so that x and y are local variables
if(true){
        int x,y;
        //set x and y to be the width + height of the terminal
        getmaxyx(stdscr,y,x);
        for(int i = 0; i < x; i++){
                //top border
                mvaddch(0,i,'#');
                //bottom border
                mvaddch(y - 1,i,'#');
        }
        for(int i = 0; i < y; i++){
                //left border
                mvaddch(i,0,'#');
                //right border
                mvaddch(i,x - 1,'#');
        }
}


texts: to use a constructor or not use a constructor

texts:
I have a validator class, whose purpose is to validate input data.  Initially I wrote the class like this:

export class ValidatorForInputs {

  constructor(inputData) {
    this._data = inputData;
  }

  validate() {
    let results = {};

    let validateInputDataForMissingKeys = checkInputDataForMissingKeys(this._data);
    if (validateInputDataForMissingKeys) results = { ...results, ...validateInputDataForMissingKeys };

    let validateInputDataForMissingValues = checkInputDataForMissingValues(this._data);
    if (validateInputDataForMissingValues) results = { ...results, validateInputDataForMissingValues };

    let validateInputDataMaximums = checkInputDataMaximums(this._data);
    if (validateInputDataMaximums) results = { ...results, validateInputDataMaximums };

    return results;

  }

}

to be called like this:

  let validatorForInputs = new ValidatorForInputs(inputData);
  let validationForInputsResult = validatorForInputs.validate();
// do something with validationForInputsResult

But then I wondered, is the constructor really necessary when the data could be passed directly to the validate method like so:

  export class ValidatorForInputs {

    validate(data) {
      let results = {};

      let validateInputDataForMissingKeys = checkInputDataForMissingKeys(data);
      if (validateInputDataForMissingKeys) results = { ...results, ...validateInputDataForMissingKeys };

      let validateInputDataForMissingValues = checkInputDataForMissingValues(data);
      if (validateInputDataForMissingValues) results = { ...results, validateInputDataForMissingValues };

      let validateInputDataMaximums = checkInputDataMaximums(data);
      if (validateInputDataMaximums) results = { ...results, validateInputDataMaximums };

      return results;

    }

  }

and then called like this:

  let validatorForInputs = new ValidatorForInputs();
  let validationForInputsResult = validatorForInputs.validate(inputData);
// do something with validationForInputsResult

or even called in a one liner like this:

let validationForInputsResult = ( new ValidatorForInputs() ).validate(inputData);
// do something with validationForInputsResult

With a little bit of testing, I found that the code behaves the same way.  I read the what the docs have to say about constructors but did not find any information that answers this question.

So, in a case like this, should a constructor be used or not?  If so, why?  If not, why not?


texts: WPF - Run an async Task with DispatcherTimer

texts:
I have a small application that checks some system status and display it details.
I have the following code which is working. But I want to make sure it's optimal:

public partial class MainWindow : Window
{

    // Dictionary to hold info
    Dictionary<string, int> dataHolder = new Dictionary<string, string>
    {
        {"status_code", "" },
        {"memory", "" },
        {"process", "" }
    };

    public MainWindow()
    {
        InitializeComponent();
    }

    private void StartBtn_Click(object sender, RoutedEventArgs e)
    {
        StartBtn.IsEnabled = false;

        System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(updateUI);
        dispatcherTimer.Interval = new TimeSpan(0, 5, 0);
        dispatcherTimer.Start();
    }

    private async void updateUI(object source, EventArgs e)
    {
        await loadInfo();
        StartBtn.IsEnabled = true;

        foreach(KeyValuePair<string, string> entry in dataHolder)
        {
            // Display in the UI
        }
    }

    private async Task loadInfo()
    {
        int page = 1;
        var keys = new List<string>(dataHolder.Keys);
        foreach (string key in keys)
        {
            dataHolder[key] = "";
            //await asyncCall(key, page);
        }

        // Better asynchronously and in parallel
        await Task.WhenAll(keys.Select(key => asyncCall(key, page)));
    }

    private async Task asyncCall(string key, int page)
    {
        var htClient = new HttpClient();
        // code to retrieve data...
    }
}

So as I said before, this code is working but I read somewhere that having an async void method is not good practice as in private async void updateUI(object source, EventArgs e). I could change it to private async Task updateUI(object source, EventArgs e) but then I would not be able to do dispatcherTimer.Tick += new EventHandler(await updateUI);

Also how to start counting (Timer) only after the previous process is done?

Thank you

EDIT: I am using the DispatcherTimer because I want the application to retrieve the status information and update the UI every 5 minutes.


texts:
I am learning Scala still and refactoring some old code.  I was hoping the community here could give me pointers to fix this code up since there are some issues I have with it visually, but don't know if there's an elegant solution for my vision.

class PhoneNumber(phonenumber:String) {
  def number: String = {
    phonenumber.filter(_.isDigit) match {
      case x if x.startsWith("1") && x.length == 11 => x.substring(1)
      case x if x.length != 10 => "0000000000"
      case x => x
    }
  }

  def areaCode: String = number.take(3)

  override def toString: String =
    "(" + areaCode + ") " + number.substring(3,6) + "-" + number.takeRight(4)
}

I want to refactor my case statement as much as possible because right now I think it looks kind of strange.  One thing I am particularly not fond of is the case x => x, but I am wondering what others think about my approach in general and what I might do to make this code better visually and functionally.


texts: Function that tests whether all items in a list are the same

texts:
The program consists of two functions: the helper predicate function singleton-list? that checks whether a given list contains only one item and the function that does the actual job all-same?.

;; Predicate function: singleton-list?
;; -----------------------------------
;; The singleton-list? predicate function tests whether a list contains only a
;; single item. That is, if the list provided has got only one element in it,
;; the function returns true. In all other cases, the function returns a value
;; of false. First it checks if the object we're sent is in fact a list. If it
;; is, we check whether "cdr" returns a nonempty list. If it does, that means
;; there is more than one item in the list and thus a value of false is
;; returned.
;;
;; Usage examples:
;;     (singleton-list? '(A))     => #t
;;     (singleton-list? '(A B C)) => #f
;;     (singleton-list? '())      => #f

(define singleton-list?
    (lambda (ls)
        (and (pair? ls) (null? (cdr ls)))))

;; Predicate function: all-same?
;; -----------------------------
;; The all-same? predicate function tests whether all elements in a given list
;; are identical. Fist it checks if the list passed in is an empty list. If it
;; is, we return a value of false because the concept of sameness does not make
;; a whole lot of sense when there are no things to be compared against each
;; other. When there is only one item in a list, we return true. Otherwise,
;; we've got a list with more than one item in it. We compare the first item
;; with the second. If they're equal, we call the function recursively with our
;; list where the first element has been removed.
;;
;; Usage examples:
;;     (all-same? '(A A A)) => #t
;;     (all-same? '(A B A)) => #f
;;     (all-same? '(A))     => #t
;;     (all-same? '())      => #f

(define all-same?
    (lambda (ls)
        (cond ((null? ls)           #f) ; If empty list, return false
              ((singleton-list? ls) #t) ; If single-item list, return true
              (else                 (if (equal? (car ls) (car (cdr ls)))
                                        (all-same? (cdr ls))
                                         #f)))))


texts:
I am studying computer science and just for the sake of practise I thought of implementing an object pool.

This is my first implementation, it is simple and works correctly, but I would love any thoughts on it. Currently, the memory is allocated on the stack, but I am thinking of using policy based design to allow heap allocation as well.

Here is the code of the pool:

#include <iostream>
#include <memory>
#include <functional>

/**
 * Generic class for object pools.
 */
template <class T, int SZ, class Initialiser, class Releaser> class StackObjectPool {
public:
    using pointer = std::unique_ptr<T,std::function<void(T*)> >;
    using PoolType = StackObjectPool<T,SZ,Initialiser, Releaser>;

    StackObjectPool() {}
    StackObjectPool(const PoolType& orig) = delete;
    ~StackObjectPool() {}

    /**
     * Acquires an object not being currently used
     * @return pointer to the acquired object
     * @throw std::out_of_range if all the objects inside the pool are being used
     */
    pointer acquire() {
        unsigned int index = 0; // look for the first free object
        while(m_occupied_registry[index]) ++index;
        if(index >= SZ) throw std::out_of_range("Pool exceeded its size");
        m_occupied_registry[index] = true; // mark it as currently in use
        m_initialiser(&m_objects[index]); // initialise it

        //return an unique_ptr that calls release when reset
        return pointer(&m_objects[index], [this](T* element)->void{release(element);});
    }

    friend std::ostream& operator<<(std::ostream& ostream, const PoolType& pool) {
        for(unsigned int index = 0; index < SZ; ++index) {
            std::cout<<(pool.m_occupied_registry[index]?"[occupied] ":"[free]\n");
            if(pool.m_occupied_registry[index]) {
                std::cout<<pool.m_objects[index]<<"\n";
            }
        }
        return ostream;
    }
private:

    void release(T* element) {
        unsigned int index = 0;
        while(&m_objects[index] != element) ++index;
        m_occupied_registry[index] = false; // mark the released element as free
        m_releaser(element); // call release functor
    }

    Initialiser m_initialiser;
    Releaser m_releaser;
    bool m_occupied_registry[SZ] {0};
    T m_objects[SZ];
};

And here is a Test class and a simple main which I have used to test the pool:

class Test {
public:
    Test():m_a(0),m_b('0'){
        std::cout<<"Construct default Test"<<*this<<"\n";
    }
    Test(int a, char b): m_a(a), m_b(b) {
        std::cout<<"Construct Test"<<*this<<"\n";
    }
    Test(const Test& orig): m_a(orig.m_a),m_b(orig.m_b) {
        std::cout<<"Construct cpy Test"<<*this<<"\n";
    }
    ~Test() {
        std::cout<<"Delete Test"<<*this<<"\n";
    }
    friend std::ostream& operator<<(std::ostream& ostream, const Test& test) {
        ostream<<"["<<test.m_a<<",'"<<test.m_b<<"']";
        return ostream;
    }
private:
    int m_a;
    char m_b;
};

struct Initialiser {
    void operator() (Test* element) {
        std::cout<<"Initialising Test"<<*element<<"\n";
    }
};

struct Releaser {
    void operator() (Test* element) {
        std::cout<<"Releasing Test"<<*element<<"\n";
    }
};

int main(int argc, char** argv) {
    using TestPool = StackObjectPool<Test,5, Initialiser, Releaser>;
    TestPool pool;
    TestPool::pointer pt1, pt2,pt3,pt4,pt5;

    std::cout<<pool;

    pt1= pool.acquire();
    std::cout<<"Aquired pt:"<<*pt1<<"\n";
    //pt1.reset();

    std::cout<<pool;

    pt2 = pool.acquire();
    std::cout<<"Aquired pt:"<<*pt2<<"\n";
    pt2.reset();

    std::cout<<pool;

    pt3 = pool.acquire();
    std::cout<<"Aquired pt:"<<*pt3<<"\n";
    //pt3.reset();

    std::cout<<pool;
    return 0;
}


texts:
This is the working code snippet to download file from a URL. I want to know if there is any optimization I can do to download the file faster.

File localFile = new File(localUrl)
localFile.withOutputStream { out ->
    URLConnection url = new URL(remoteUrl).openConnection()
    def remoteAuth = "Basic " + "${username}:${password}".getBytes().encodeBase64().toString()
    url.setRequestProperty("Authorization", remoteAuth);
        if (url.responseCode == 200) {
            out << url.getInputStream()
        } else {
            System.out.println("Can not download file from ${remoteUrl}")
        }
}