texts: Generic extension method for NullIf() supporting nullable and non-nullable value types

texts:
I would like a simple, modestly efficient NullIf() generic extension for nullable and non-nullable value types including enums. The trickiness seems to be with equality testing in generics.

Any issues with this working implementation?

/// <summary>
/// Return null if the value is equal to the argument.  Applies to value types including enums.
/// </summary>
public static T? NullIf<T>(this T value, T equalsThis)
    where T : struct, IComparable // values types (including enum)
{
    return Comparer<T>.Default.Compare(value, equalsThis) == 0
        ? (T?)null
        : value;
}

/// <summary>
/// Return null if the value is null or the value is equal to the argument.
/// Applies to value types including enums.
/// </summary>
public static T? NullIf<T>(this T? value, T equalsThis)
    where T : struct, IComparable  // values types (including enum)
{
    return !value.HasValue
        ? (T?)null
        : value.Value.NullIf(equalsThis);
}

Test cases:

int i = 32;
int? i2 = i.NullIf(32); // null
int? i3 = i.NullIf(50); // 32

System.IO.FileAccess fa = System.IO.FileAccess.Read;
System.IO.FileAccess? fa2 = fa.NullIf(System.IO.FileAccess.Read);       // null
System.IO.FileAccess? fa3 = fa.NullIf(System.IO.FileAccess.ReadWrite);  // Read

References: Comparer<T>.Default


texts: Designing a simple Battleship game in Python

texts:
I am trying to code Battleship. It should be a text one-player game against computer where computer and human player take turns in shooting at opponent's ships. I decided to start implementation with this part: A human types target coordinates and computer answers if a ship has been hit or even if it has been sunk. Ship positions are fixed (predefined in the program). For some time I wondered how to represent game plan and ships to get this working as smoothly as possible. This is what I have put together:

class GamePlan:

    DIMX = 10
    DIMY = 10

    SHIP_MISS = 0
    SHIP_HIT = 1
    SHIP_DEAD = 2

    SHIP_COUNTS = {
        2: 1,
        3: 1,
    }

    def __init__(self):
        self.ships = [
            [(1,1), (1,2)],
            [(5,6), (5,7), (5,8)],
        ]

    def hit(self, target):
        hit_ship = None
        hit_ship_index = None
        for i, ship in enumerate(self.ships):
            if target in ship:
                ship.pop(ship.index(target))
                hit_ship = ship
                hit_ship_index = i
        if hit_ship == []:
           self.ships.pop(hit_ship_index)
           return self.SHIP_DEAD
        if hit_ship:
            return self.SHIP_HIT
        return self.SHIP_MISS

def main():
    game_plan = GamePlan()

    while True:
        raw_coords = raw_input('Enter coords: ')
        str_coords = raw_coords.split()
        coords = tuple([int(c) for c in str_coords])
        if len(coords) != 2:
            print 'Bad input'
            continue

        result = game_plan.hit(coords)
        if result == GamePlan.SHIP_DEAD:
            print 'Ship dead'
        if result == GamePlan.SHIP_HIT:
            print 'Ship hit'
        if result == GamePlan.SHIP_MISS:
            print 'Missed'

if __name__ == "__main__":
    main()

EDIT: GamePlan should be probably called Board as answer of Janne Karila suggests. Just to clarify what I meant by that name with my flawed English.

There are a few things I am unsure about:

Is it correct that GamePlan processes shooting (in the method hit)?
Is hit a good name for that method or should it be something like process_hit? Because GamePlan is being hit, it is not hitting anything. Is hit still good in such case? This is probably my biggest concern.
Should ships be represented as objects of a class Ship instead?
Is GamePlan a good thing to have or is it useless? I mean I could make class AI that directly owns ships but I am not sure where stuff like SHIP_COUNTS would go then. I have also planned that I will use GamePlan to generate ship positions (hence SHIP_COUNTS and DIMX, DIMY which are unused atm) but plan generation could also easily go to AI, I guess.
Is there anything else that is wrong?


texts:
This is the problem statement for Lonely Integer.

  There are N integers in an array A. All but one integer occur in
  pairs. Your task is to find out the number that occurs only once.

  Input Format

  The first line of the input contains an integer N indicating number of
  integers.   The next line contains N space separated integers that
  form the array A.

  Constraints

  1 <= N < 100
  N % 2 = 1 ( N is an odd number )
  0 <= A[i] <= 100, ∀ i ∈ [1, N]

  Output Format

  Output S, the number that occurs only once.

  Example 1

  Input

1
1

  Output

1

  We see only 1 element and that element is the answer (1).

  Example 2

  Input

3
1 1 2

  Output

2

  We see 3 elements, 1 is repeated twice. The element that occurs only
  once is 2.

  Example 3

  Input

5
0 0 1 2 1

  Output

2

  We see 5 elements, 1 and 0 are repeated twice. And the element that
  occurs only once is 2.

//I did not do the constraints
#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    int size;
    std::cin >> size;
    if (size == 1) {
        int lone;
        std::cin >> lone;
        std::cout << lone << '\n';
    } else {
        std::vector<int> numbers(size);
        int index = 0;
        while (std::cin && index != size) {
            std::cin >> numbers[index++];
        }
        std::sort(numbers.begin(),numbers.end());
        for (std::size_t i = 1; i < numbers.size(); ++i) {
            if (numbers[i-1] != numbers[i] && numbers[i] != numbers[i+1]) {
                std::cout << numbers[i] << '\n';
                break;
            }
        }
    }
}

Is this fast enough for extremely large elements? How to make this faster?
Can this be done efficiently without sorting?
How can I improve this code?


texts: Calculating the most profit from an array of stock prices

texts:
I'm a newbie learning how to code, and I am trying to find the most efficient way to calculate the most profit from an array of stock prices. For a given array,I have a list of stock prices over n days. So for {1, 4, 5, 100}, my maxProfit would be 99 (100-1). The rule for maxProfit would be the greatest difference between two numbers in the Array where you cannot count backwards in the array.

I'm able to get the right solution, but it's not the most efficient. I'm striving for my solution to be \$O(n)\$. At the moment given that single loop and then the Max function, my solution is n^2 because there are two loops. Is there a way I can break it down to just one?

var stockPrices = new List<int>() { 30, 50, 3, 2, 1, 1, 10, 25, 2, 10 };

var maxProfit = 0;
for(int x = 0; x < stockPrices.ToArray().Length; x++)
{
    int maxValue = stockPrices.Max();
    int maxIndex = stockPrices.IndexOf(maxValue);

    var allValuesToTheLeftOftheMax = stockPrices.GetRange(0, maxIndex);

    //Find the min value
    if (maxIndex == 0)
    {
        stockPrices.Remove(maxValue);
    }
    else
    {
        int minValue = allValuesToTheLeftOftheMax.Min();

        //Get the max profit
        if (maxProfit < maxValue - minValue)
        {
            maxProfit = maxValue - minValue;
        }

        stockPrices.Remove(maxValue);
    }
    Console.WriteLine("Max profit currently is {0}", maxProfit);
}

Console.WriteLine("Final max profit is {0}", maxProfit);
Console.ReadLine();


texts:
There are 2 versions of the get_startup_folders() method below, both work as expected and are called only once.

The 1st version has several minor pieces of repeated code which are removed by the use of an inner function in the 2nd version.

I've read several times that the use of inner functions is often frowned on by Python pros, except for in a narrow range of specific cases (e.g. closures and factory functions). I was wondering whether the 2nd version below would be considered superior to the 1st version by experienced Python programmers.

1st version:

def get_startup_folders(self):

    folders = []

    for item in STARTUP_FOLDERS:

        if item == "home":
            if self.home_folder not in folders:
                folders.append(self.home_folder)

        elif item == "file":
            if self.file_folder:
                if self.file_folder not in folders:
                    folders.append(self.file_folder)

        elif item == "project":
            for folder in self.project_folders:
                if folder not in folders:
                    folders.append(folder)

        elif item == "user":
            for folder in self.user_folders:
                if folder not in folders:
                    folders.append(folder)

    # Fail-safe: If empty then use the home folder as a fall back;
    # self.home_folder is guaranteed to contain the home folder.

    if len(folders) == 0:
        folders.append(self.home_folder)

    return folders

2nd version:

def get_startup_folders(self):

    folders = []

    def add_folder(folder):
        if folder and folder not in folders:
            folders.append(folder)

    for item in STARTUP_FOLDERS:

        if item == "home":
            add_folder(self.home_folder)

        elif item == "file":
            add_folder(self.file_folder)

        elif item == "project":
            for folder in self.project_folders:
                add_folder(folder)

        elif item == "user":
            for folder in self.user_folders:
                add_folder(folder)

    # Fail-safe: If empty then use the home folder as a fall back;
    # self.home_folder is guaranteed to contain the home folder.

    if len(folders) == 0:
        add_folder(self.home_folder)

   return folders


texts:
This program automatically makes folders to add scripts to be ran once a computer is logged off a user. It checks to make sure it is not overwriting any previous scripts (windows).

:: Author: Brandon Finley
:: Date: 4/20/2017
:: Purpose: This program automatically makes folders to add scripts to be ran once a computer is logged off a user. It checks to make sure it is not overwriting any previous scripts
:: that may have already been created, and then adds the ChromeClear to the list. THIS PROGRAM IS A TOTAL NUKE TO THE CHROME BROWSER; IT WILL DELETE EVERYTHING!

:: If there are no previous scripts added, it needs to create the file locations to use
@ECHO OFF
IF NOT EXIST C:\Windows\System32\GroupPolicy\User MD C:\Windows\System32\GroupPolicy\User
IF NOT EXIST  C:\Windows\System32\GroupPolicy\User\Scripts MD C:\Windows\System32\GroupPolicy\User\Scripts
IF NOT EXIST C:\Windows\System32\GroupPolicy\User\Scripts\Logoff MD C:\Windows\System32\GroupPolicy\User\Scripts\Logoff

:: Writes the new .bat file to clear the browsers
ECHO SET ChromeDir=C:\Users\%%USERNAME%%\AppData\Local\Google\Chrome\User Data> C:\Windows\System32\GroupPolicy\User\Scripts\Logoff\ChromeClear.bat
ECHO DEL /q /s /f "%%ChromeDir%%">> C:\Windows\System32\GroupPolicy\User\Scripts\Logoff\ChromeClear.bat
ECHO RD /s /q "%%ChromeDir%%">> C:\Windows\System32\GroupPolicy\User\Scripts\Logoff\ChromeClear.bat

:: If there are no previous scripts.ini initialized it makes the begining of the new file (creates a new scripts.ini if not already there).
IF NOT EXIST "C:\Windows\System32\GroupPolicy\User\Scripts\scripts.ini" @echo:>>C:\Windows\System32\GroupPolicy\User\Scripts\scripts.ini
FOR /f "tokens=3" %%k in ('find /c "Logoff" "C:\Windows\System32\GroupPolicy\User\Scripts\scripts.ini"') do set theLogoff=%%k
IF /I %theLogoff%==0 @echo [Logoff]>> C:\Windows\System32\GroupPolicy\User\Scripts\scripts.ini

:: Writes to the scripts.ini file, and tries to continue the script counter if previous scripts are already added (which is why it doesn't just simply start at 0, but instead counts the scripts).
FOR /f "tokens=3" %%f in ('find /c "CmdLine" "C:\Windows\System32\GroupPolicy\User\Scripts\scripts.ini"') do set isComplete=%%f
ECHO %isComplete%CmdLine=ChromeClear.bat>> C:\Windows\System32\GroupPolicy\User\Scripts\scripts.ini
ECHO %isComplete%Parameters=>> C:\Windows\System32\GroupPolicy\User\Scripts\scripts.ini

:: Deletes the .bat file at it's location.
DEL "%~f0"


texts: Test if a network is online by using urllib2

texts:
My concerns:

Is the code pythonic
Is the code practical

I tend on expanding the usefulness of this script, if you don't think it's stupid idea. One thing I will implement is command-line arguments by way of argparse.

#!/usr/bin/env python

'''
Test if network is online by sending and http request to a remote
web-server. I wrote this because my network connection sucks.
'''

import urllib2
import sys

def is_online(**kwargs):
    '''
    Determine weather or not your network is online
    by sending a HTTP GET request. If the network is
    online the function will return true. If the network
    is not online the function will return false
    '''

    # Set the default request time out.
    # This will be passed as a keyword argument
    # to urllib2.urlopen.
    kwargs.setdefault('timeout', 0.30)
    kwargs.setdefault('url', 'http://www.google.com')
    timeout = kwargs.get('timeout')
    url = kwargs.get('url')

    try:
        print 'Sending request to {}'.format(url)
        response = urllib2.urlopen(url, timeout=timeout)
    except KeyboardInterrupt:
        sys.exit(0)
    except Exception:
        # Generally using a catch-all is a bad practice but
        # I think it's ok in this case
        response = False
        print 'Request to {} failed'.format(url)
    if response:
        return True
    else:
        return False

def main():
    '''
    Continually check if the network is online.
    If the network is online stop checking.
    '''
    while True:
        if is_online():
            print 'Net is up'
            break
        else:
            print 'Net down.'

if __name__ == '__main__':
    main()


texts:
I am working with a mesh of triangles (in 3D, although I doubt it makes a difference). The mesh is given as list of lists, each list containing the indices of the three vertices of a triangle in said mesh.

For example:

0 2 6
0 12 15
2 66 10234

I want to find the neighbours of each point, i.e., to have an array where the first row contains the neighbours of point 0, the second the neighbours of point 1 and so on.

How do I make it more efficient?

points is a list of lists containing the point coordinates, while triangles is a list of lists containing the triangles in the mesh:

from numpy import ma

pointsNb = points.shape[0]

trianglesNb = triangles.shape[0]

neighbours = [[] for i in range(pointsNb)] # for each point in points, make a list of its neighbours

# find neighbours
for i in range(0, trianglesNb):
    triangle = ma.array(triangles[i][:], mask=False)
    for j, point in enumerate(triangles[i]):
        triangle[j] = ma.masked
        for possible_neighbour in triangle[~triangle.mask]:
            if possible_neighbour not in neighbours[point]:
                neighbours[point].append(possible_neighbour)
        triangle[j] = point


texts: JavaScript change image every three seconds

texts:
I have a function that changes the image on a webpage every three seconds. I would like feedback on efficiency, good code practices, and anything else that can improve the quality of this code. It works, I just want any insight if it can work any better. Any and all feedback is welcomed and considered.

Slideshow Script

HTML Images accessed


texts:
I'm doing a clock in javascript and I am not sure this way is the best way to rotate the pointers.

Is this ok, or is there a better way?

// browser vendors
var browsers = [
    'webkit',
    'Moz',
    'ms',
    'O',
    ''];

// function to move the pointers
function moveMe(el, unit) {
    var deg = unit * 360 / 60;
    browsers.each(function (b) {
        el.style[b + 'Transform'] = 'rotate(' + deg + 'deg)';
    });
}

// function to check the time
function checkTime() {
    var date = new Date();
    var seconds = date.getSeconds();
    var minutes = date.getMinutes();
    var hours = date.getHours();
    moveMe(sPointer, seconds);
    !seconds && moveMe(mPointer, minutes);
    !minutes && moveMe(hPointer, hours);
}

The fiddle I'm playing with is here.


texts:
I'm working on a client-side API for my ASP.net MVC application and I'm not quite sure I've got the code right. This API allows me to call server-side action methods via Ajax and I've designed it to have a similar call syntax like jQuery uses.

Is the variable HomeActions._ajaxSettings static the way this written right now? I'm concerned that if two or more calls are made simultaneously to this API that they would effectively be using/updating the same static variable and cause intermittent bugs or failure. If this variable is an issue how can it be re-written and still maintain the call pattern shown in the example?

Example usage:

MVC.Home.Actions.RefreshCache("myKey").Start().success(function (result) {
            // refresh the window
            window.location.reload(true);
        }).error(function () {
        console.error("epic fail");
    });

API code:

var MVC;
(function (MVC) {
    var HomeActions = (function () {
        function HomeActions() {}
        HomeActions.RefreshCache = function (key, returnUrl, ajaxSettings) {
            HomeActions._ajaxSettings = ajaxSettings || {};
            HomeActions._ajaxSettings['data'] = JSON.stringify({
                key: key,
                returnUrl: returnUrl
            });
            HomeActions._ajaxSettings['url'] = MVC.Home.ActionNames.RefreshCache;
            if ('type' in HomeActions._ajaxSettings == false) HomeActions._ajaxSettings['type'] = 'POST';
            if ('context' in HomeActions._ajaxSettings == false) HomeActions._ajaxSettings['context'] = this;
            if ('contentType' in HomeActions._ajaxSettings == false) HomeActions._ajaxSettings['contentType'] = 'application/json';
            return this;
        };
        HomeActions.IndexAllRecords = function (ajaxSettings) {
            HomeActions._ajaxSettings = ajaxSettings || {};
            HomeActions._ajaxSettings['data'] = JSON.stringify({
            });
            HomeActions._ajaxSettings['url'] = MVC.Home.ActionNames.IndexAllRecords;
            if ('type' in HomeActions._ajaxSettings == false) HomeActions._ajaxSettings['type'] = 'POST';
            if ('context' in HomeActions._ajaxSettings == false) HomeActions._ajaxSettings['context'] = this;
            if ('contentType' in HomeActions._ajaxSettings == false) HomeActions._ajaxSettings['contentType'] = 'application/json';
            return this;
        };
        HomeActions.Start = function () {
            return $.ajax(HomeActions._ajaxSettings);
        };
        return HomeActions;
    }) ();
    var HomeActionNames = (function () {
        function HomeActionNames() {}
        HomeActionNames.RefreshCache = '/refreshcache';
        HomeActionNames.IndexAllRecords = '/indexallrecords';
        return HomeActionNames;
    }) ();
    var Home = (function () {
        function Home() {}
        Home.Actions = HomeActions;
        Home.ActionNames = HomeActionNames;
        return Home;
    }) ();
    MVC.Home = Home;
}) (MVC || (MVC = {}));


texts: Is this an acceptable implementation of the Adapter pattern?

texts:
I've used the UK Plug -> US Socket and US Plug -> UK Socket analogy. I've also made it possible for UK plug to use a UK socket and a US plug to use a US socket. The output of the SSCCE below is

UKPlug -> UKSocket
USPlug -> USSocket
UKPlug -> UKUSAdapter -> USSocket
USPlug -> USUKAdapter -> UKSocket

And the code

package com.structural.adapter.adapter2;

interface IAdapter {
  public void plugin();
}

class UKUSAdapter implements IAdapter {
  UKPlug plug;
  USSocket socket;
  public UKUSAdapter(UKPlug plug, USSocket socket) {
    this.plug = plug;
    this.socket = socket;
  }

  @Override
  public void plugin() {
    System.out.print("UKUSAdapter -> ");
    socket.accept_2pin_plug(plug.pin1, plug.pin2);
  }
}

class USUKAdapter implements IAdapter {
  USPlug plug;
  UKSocket socket;
  public USUKAdapter(USPlug plug, UKSocket socket) {
    this.plug = plug;
    this.socket = socket;
  }

  @Override
  public void plugin() {
    System.out.print("USUKAdapter -> ");
    socket.accept_3pin_plug(plug.pin1, plug.pin2, 1);
  }

}

class USSocket {
  USPlug plug;
  public USSocket(USPlug plug) {
    this.plug = plug;
  }

  public void accept_2pin_plug(int pin1, int pin2) {
    System.out.print("USSocket");
  }
}

class UKSocket {
  UKPlug plug;
  public UKSocket(UKPlug plug) {
    this.plug = plug;
  }
  public void accept_3pin_plug(int pin1, int pin2, int pin3) {
    System.out.print("UKSocket");
  }
}

class UKPlug {
  int pin1;
  int pin2;
  int pin3;

  IAdapter adapter;
  UKSocket socket;

  public UKPlug(int pin1, int pin2, int pin3) {
    this.pin1 = pin1;
    this.pin2 = pin2;
    this.pin3 = pin3;
  }

  public void plug_into_3pin() {
    System.out.print("UKPlug -> ");
    if(this.socket == null) {
      adapter.plugin();
    } else {
     socket.accept_3pin_plug(pin1, pin2, pin3);
    }
  }

  public void setAdapter(IAdapter adapter) {
    this.adapter = adapter;
    this.socket = null;
  }

  public void setSocket(UKSocket socket) {
    this.socket = socket;
    this.adapter = null;
  }
}

class USPlug {
  int pin1;
  int pin2;

  IAdapter adapter;
  USSocket socket;

  public USPlug(int pin1, int pin2) {
    this.pin1 = pin1;
    this.pin2 = pin2;
  }

  public void plug_into_2pin() {
    System.out.print("USPlug -> ");
    if(this.socket == null) {
      adapter.plugin();
    } else {
      socket.accept_2pin_plug(pin1, pin2);
    }
  }

  public void setAdapter(IAdapter adapter) {
    this.adapter = adapter;
    this.socket = null;
  }

  public void setSocket(USSocket socket) {
    this.socket = socket;
    this.adapter = null;
  }
}

public class TestPlugAdapters {
  public static void main(String[] args) {
    UKPlug ukPlug = new UKPlug(1,1,1);
    UKSocket ukSocket = new UKSocket(ukPlug);

    USPlug usPlug = new USPlug(1,1);
    USSocket usSocket = new USSocket(usPlug);

    //Test UK Plug to UK Socket
    ukPlug.setSocket(ukSocket);
    ukPlug.plug_into_3pin();
    System.out.println();

    //Test US Plug to US Socket
    usPlug.setSocket(usSocket);
    usPlug.plug_into_2pin();
    System.out.println();

    //Test UK Plug to US Socket
    IAdapter ukusAdapter = new UKUSAdapter(ukPlug, usSocket);
    ukPlug.setAdapter(ukusAdapter);
    ukPlug.plug_into_3pin();
    System.out.println();

    //Test US Plug to UK Socket
    IAdapter usukAdapter = new USUKAdapter(usPlug, ukSocket);
    usPlug.setAdapter(usukAdapter);
    usPlug.plug_into_2pin();
    System.out.println();
  }
}


texts:
In the current code, the animation is very unclear, and not "polished" (it doesn't run smooth).

Can I make the animation smoother?
And/or, why it doesn't run smooth?

from tkinter import *
import time

WIDTH = 800
HEIGHT = 500
SIZE = 50
tk = Tk()
canvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg="grey")
canvas.pack()
color = 'black'

class Ball:
    def __init__(self):
        self.shape = canvas.create_oval(0, 0, SIZE, SIZE, fill=color)
        self.speedx = 9 # changed from 3 to 9
        self.speedy = 9 # changed from 3 to 9
        self.active = True
        self.move_active()

    def ball_update(self):
        canvas.move(self.shape, self.speedx, self.speedy)
        pos = canvas.coords(self.shape)
        if pos[2] >= WIDTH or pos[0] <= 0:
            self.speedx *= -1
        if pos[3] >= HEIGHT or pos[1] <= 0:
            self.speedy *= -1

    def move_active(self):
        if self.active:
            self.ball_update()
            tk.after(40, self.move_active) # changed from 10ms to 30ms

ball = Ball()
tk.mainloop()


texts: Sort multidimensional array based on another one containing the desired order

texts:
I have an array like this:
$array = [
    ['id' => 1, 'content' => 'value 1'],
    ['id' => 2, 'content' => 'value 2'],
    ['id' => 3, 'content' => 'value 3'],
];

I have another array containing the actual order of ids in which $array should be sorted :
$order = [3, 1, 2];

Which means, the result should be this:
$sorted = [
    0 => ['id' => 3, 'content' => 'value 3'],
    1 => ['id' => 1, 'content' => 'value 1'],
    2 => ['id' => 2, 'content' => 'value 2'],
];

The final requirement is, that the array should be printed using foreach:
foreach($sorted as $value) {
    print $value['content'];
}

I came up with this solution:
function orderArray(array $array, array $order) {
    $sorted = [];

    foreach($array as $value) {
        $id = $value['id'];
        $index = array_search($id, $order);
        $sorted[$index] = $value;
    }

    ksort($sorted);

    return $sorted;
}

This works fine. However, I wonder whether this is efficent, especially as I have to call ksort to make the array be printed correctly by foreach.
Can this be optimized? Maybe there's also a more elegant solution to the problem.

It's a given, that all ids and only those are in $order - so no need to test for that.


texts: How can I reduce this .less call to one line per image

texts:
How can I simplify this .less code to require less repetition (i.e., so that I can have many buttons with normal, rollover, and pressed states without using 3 lines for each button):

.SBtnM(@urlprefix, @width, @height, @urlsuffix) {
        width: @width;
        height: @height;
        background-image: url(%("%s_%s.png", @urlprefix,@urlsuffix));
}

@url1prefix : 'chrome://xtoolbar/skin/img1';
toolbarbutton > .btnCSS1 {.SBtnM(@url1prefix, 42px, 24px,'normal');}
toolbarbutton:hover > .btnCSS1 {.SBtnM(@url1prefix, 42px, 24px, 'rollover');}
toolbarbutton[checked="true"] > .btnCSS1 {.SBtnM(@url1prefix, 42px, 24px, 'pressed');}

Ideally, I would want to be able to use a one-liner to handle all 3 states.  E.g., something like this:

.SBtnM(@urlprefix, @width, @height) {
    //Magic Happens.  This part may become more complicated
}

.btnCSS1 {.SBtnM('chrome://xtoolbar/skin/img1', 42px, 24px);}

Output, for reference:

toolbarbutton > .btnCSS1 {
  width: 42px;
  height: 24px;
  background-image: url("chrome://xtoolbar/skin/img1_normal.png");
}
toolbarbutton:hover > .btnCSS1 {
  width: 42px;
  height: 24px;
  background-image: url("chrome://xtoolbar/skin/img1_rollover.png");
}
toolbarbutton[checked="true"] > .btnCSS1 {
  width: 42px;
  height: 24px;
  background-image: url("chrome://xtoolbar/skin/img1_pressed.png");
}

As far as I can tell, .less doesn't have any sort of parent selector for mixins.


texts:
I have written a code that triggers my div with another menu. I do not know which one is better and should be used. Can I get some feedback?
First code in one function:
function sidebar() {
var menu = document.querySelector('#sidebar-container');
      var menuSmall = document.querySelector('#sidebar-container2');
      var icon = document.getElementById('right');
      menuSmall.style.display = "block";
      menu.style.display = "none";
      if(menu.style.display == "none") {
        icon.onclick = function () {
          menu.style.display = "block";
          menuSmall.style.display = "none";
}
}

Second code with two functions but does the same work:
function sidebar() {
      var menu = document.querySelector('#sidebar-container');
      var menuSmall = document.querySelector('#sidebar-container2');
      menuSmall.style.display = "block";
      menu.style.display = "none";

    },
    function openbar() {
      var menu = document.querySelector('#sidebar-container');
      var menuSmall = document.querySelector('#sidebar-container2');
      menuSmall.style.display = "none";
      menu.style.display = "block";
    }


texts: Triggering a callback when user put in the Konami cheat code anywhere in the page

texts:
I wrote this just for some fun and also to practise my ES6 skills.
When user key in the Konami Cheat Code(⬆⬆⬇⬇⬅➡⬅➡↩) anywhere in the page, it should trigger a callback. In the following example, it should trigger an alert.

What could be improved?

Are there more ES6 features I could use in this code?

const {onKonamiSequenceTriggered, clearKonamiSequanceTriggered} = (() => {
    const konamiSequence = ["ARROWUP", "ARROWUP", "ARROWDOWN", "ARROWDOWN", "ARROWLEFT", "ARROWRIGHT", "ARROWLEFT", "ARROWRIGHT", "B", "A", "ENTER"];
    konamiSequence.reverse();
    let currentSequence = Array.prototype.slice.call(konamiSequence);

    const callbacks = {};

    let eventId = 0;

    const onKonamiSequenceTriggered = callback => {
        callbacks[eventId] = callback;
        return eventId++;
    };

    const clearKonamiSequanceTriggered = id => delete callbacks[id];

    document.addEventListener("keyup", event => {
        if (event.key.toUpperCase() !== currentSequence.pop()) {
            currentSequence = Array.prototype.slice.call(konamiSequence);
        }
        if (!currentSequence.length) {
            Object.values(callbacks).forEach(callback => {
                try {
                    callback();
                } catch (e) {
                    console.error(e);
                }
            });
            currentSequence = Array.prototype.slice.call(konamiSequence);
        }
    });

    return {
        onKonamiSequenceTriggered,
        clearKonamiSequanceTriggered
    };
})();

onKonamiSequenceTriggered(() => alert("You've got it!"));


texts: Self-modifying esoteric language interpreter in Ruby

texts:
I recently created Copy, an esoteric language, and wrote an implementation in Ruby.

The language has only 7 instructions:

copy <a> <b> <c> Copy the code block from a to b at c
remove <a> <b> Remove the code block from a to b
skip <value> Skip the next instruction if value is not 0
add <var> <value> Add value to var
negate <var> Negate var
print <value> Print value as an ASCII character
getch <var> Read a character and store it character code in var

All addresses are relative and values can be variables or signed integers,

require "io/console"

class Copy
    def initialize(code)
        @code = code.lines.map &:chomp
        @len = @code.length*2
        @i = 0
        @vars = {}
    end

    def value(s)
        if s =~ /-?\d+/
            s.to_i
        else
            @vars[s] or 0
        end
    end

    def step
        while @code.length > @len do
            @code.shift
            @i -= 1
        end
        line = @code[@i].split " "
        case line[0]
        when "copy"
            @code.insert(
                @i + value(line[3]),
                *@code.slice((@i + value(line[1]))..(@i + value(line[2])))
                )
        when "remove"
            @code.slice!((@i + value(line[1]))..(@i + value(line[2])))
        when "skip"
            if value(line[1]) != 0
                @i += 1
            end
        when "add"
            @vars[line[1]] = (@vars[line[1]] or 0) + value(line[2])
        when "negate"
            @vars[line[1]] *= -1
        when "print"
            STDOUT.write value(line[1]).chr
        when "getch"
            @vars[line[1]] = STDIN.getch.ord
        end
        @i += 1
    end

    def run
        while @i < @code.length
            step
        end
    end
end

if __FILE__ == $0
    unless ARGV[0]
        puts "Copy interpreter in Ruby"
        puts "Usage: #{$0} <file>"
    end

    c = Copy.new File.read(ARGV[0])
    c.run
end

Truth machine (If the input is 0, print 0 and exit, if the input is 1, print 1 in an infinite loop):

getch a
add b a
add b -48
print a
skip b
skip 1
copy -4 0 1

I am not really good at Ruby, can someone review this?


texts:
Given a string S, count and return the number of substrings of S that
  are palindromes. Single length substrings are also palindromes. We
  just have to count the substring that are palindrome.

  INPUT: aba
   OUTPUT: 4
   EXPLANATION: String aba has a,b,a,aba as palindromic
  substrings.

My code is running correctly but I need more efficient code.

public class PalindromeSubstrings {

    public static int countPalindromeSubstrings(String s)
    {
        String a;
        int countSubs=s.length();
        for(int i=0;i<s.length();i++)
        {
          for(int j=i+2;j<=s.length();j++)
          {
            a=s.substring(i,j);
            countSubs+=count(a);
          }
        }
        return countSubs;
    }
    public static int count(String a)
    {
        for(int i=0;i<a.length();i++)
        {
            if(a.charAt(i)!=a.charAt(a.length()-1-i))
                return 0;
        }
        return 1;
    }
}


texts:
Sonar/FxCop are telling us that we shouldn't use void async methods. That's ok.
This is the current implementation:

private async void InitMethod(ServiceControl serviceControl)
{
    if (serviceControl != null)
    {
        await Task.Factory.StartNew(() => serviceControl.Execute());
    }
}

// fire and forget ... calling from a non-async method!
InitMethod(serviceControl);

Is this a good way or how would you refactor this method?

private async Task InitMethod(ServiceControl serviceControl)
{
    if (serviceControl != null)
    {
        await Task.Factory.StartNew(() => serviceControl.Execute());
    }
}

// fire and forget ... calling from a non-async method!
// when calling without Start then VS is complaining about "not awaiting" this method
InitMethod(serviceControl).Start();


texts: Is this an excessive abstraction using objects?

texts:
We have two physical AWS S3s called in the code s3Legacy and s3Cache. They store the same data but with different S3 key structures.
The fists solution shared below uses objects, the second does not.
Is the solution using objects an excessive abstraction or there are benefits to it?
(There is no need to comment on the use of the callback.)
Here is a version using objects:
// not all code is shown here for the sake of brevity
module.exports.handle = (event, context, cb) => {

    const s3Sdk = new AWS.S3({ region: config.s3.region });
    const s3Legacy = new S3(s3Sdk, config.s3.legacyBucketName);
    const s3Cache = new S3Cache(s3Sdk, config.s3.cacheBucketName);

    s3Legacy.putObject(key, event.body, callback);
    s3Cache.putObject({
                unitId: event.pathParameters.unitId,
                timestamp: event.timestamp,
                eventId: event.id,
                eventFileName: event.id,
                body: event.body
            }, callback)'

}

class S3 {
    constructor(s3Sdk, bucketName) {
        this.s3Sdk = s3Sdk;
        this.bucketName = bucketName;
    }

    putObject(key, body, callback) {
        this.s3Sdk.putObject({ Bucket: this.bucketName, Key: key, Body: body }, (err, response) => {
            callback(err, response);
        });
    }
}

class S3Cache extends S3 {

    constructor(s3Sdk, bucketName) {
        super(s3Sdk, bucketName);
    }

    putObject(params, callback) {
        const key = this.toS3Key(
            params.unitId,
            this.toTimestampObject(params.timestamp),
            params.eventId,
            params.eventFileName
        );
        super.putObject(key, params.body, callback);
    }

    toS3Key(unitId, incidentTimestamp, incidentId, archiveIncidentObjectName) {
       return ....
    }

    toTimestampObject(timestamp) {
        return ....
    }
}

Here is a version without using objects:
// not all code is shown here for the sake of brevity
module.exports.handle = (event, context, cb) => {

    const s3 = new AWS.S3({ region: config.s3.region });
    await s3.putObject({ Bucket: config.s3.legacyBucketName, Key: key, Body: event.body }).promise();
    await s3.putObject({
            Bucket: config.s3.cacheBucketName,
            Key: toS3Key(event.unitId, toTimestampObject(event.timestamp), event.eventId, event.eventId),
            Body: event.body
        }).promise();
}

function toS3Key(unitId, incidentTimestamp, incidentId, archiveIncidentObjectName) {
       return ....
}

function toTimestampObject(timestamp) {
        return ....
}

In this version of the code, both the service orchestration code (write to s3Legacy and if successful write to s3Cache) and the s3Legacy, s3Cache, the code constructing the S3 key resides in one source file.
So this source file could change for multiple unrelated reasons.
For example when we want to change the orchestration, change the order of writing to S3s or if we want to write to DynamoDB for example.
The source file would also change if we need to change the S3 key schema.
We set a pattern here that every new addition would be added to this single source file which size would grow as a result and the list of reasons for a change would also grow.
While this example here is still small, calls only 2 services, I wonder whether extracting out the S3 code would set a better starting point for additional new development and enhancement.


texts: Process a line in chunks via Regular Expressions with Ruby

texts:
I'm writing a Ruby script to reverse engineering message log files. They come from an external system with the following characteristics:

Each line of the log file has at least one message.
Each line of the log file can have multiple messages.
Each message consists of a set of numbers separated by spaces (e.g. 30 0 -1 1 2 1).
Each message can have one of many different templates (e.g. some contain five numbers, others contains six).

The approach I'm using is to process each line, one at a time, via a method that takes a string to work on as an argument. It saves a copy of the initial input (for later comparison) then tries to match known patterns. When a pattern is matched, the string that made it up is removed. If there is nothing left, or if no more matches are found, the method exits. Otherwise, it calls itself with the remainder of the string to process. Here's the code I camp up with along with an example.

#!/usr/bin/evn ruby

def parse_line remainder_of_line

  puts "Processing: #{remainder_of_line}"

  # Save a copy of the initial input for later comparison
  initial_snapshot = remainder_of_line.dup

  # Look for known pattern matches, removing them if found
  if remainder_of_line.gsub!(/^(\d+) 0 -1 1 (\d+) \d+\s*/, '')
    puts " - Matched format 1 - found: #{$1} - #{$2}\n\n"
  elsif remainder_of_line.gsub!(/^\d+ 0 -1 2 (\d+) \d+\s*/, '')
    puts " - Matched format 2 - found: #{$1}\n\n"

  ### More patterns here.
  end

  # If noting changed, then no matches were found.
  if initial_snapshot.eql? remainder_of_line
    puts " - Line still has data but no matches found. (Left with: #{remainder_of_line}\n\n"
  # Keep going if there is anything left.
  elsif !remainder_of_line.empty?
    parse_line remainder_of_line
  end

end

line = "11 0 -1 2 13560 2 11 0 -1 2 13564 2 11 0 -1 1 36880 106 91 0 -1 1 36881 106 36881 106 91 1 13556 2 36880 106 36880 106 11 1 734 11 0 -1 1 36884 106 91 0 -1 1 36885 106 36885 106 91 1 13556 2 36884 106 36884 106 11 1 735 13556 2 31 18 799 13556 2 31 25 799 "

parse_line line

This works but I'm wondering if there is a better way.


texts: Converting pseudocode for max subarray into working Java code

texts:
I have been tasked with converting some pseudocode to working Java code and I would like someone to review my code for correctness.

The pseudocode is as follows:

Algorithm MaxsubFaster(A):
Input: An n-element array A of numbers, indexed from 1 to n.
Output: The maximum subarray sum of array A.
S0 ← 0 // the initial prefix sum
for i ← 1 to n do
    Si ← Si−1 + A[i]
m ← 0 // the maximum found so far
for j ← 1 to n do
    for k ← j to n do
        s = Sk − Sj−1
        if s > m then
            m ← s
return m

My code is as follows:

public static int maxSubFaster(int[] array)
    {
        Integer S[] = new Integer[array.length];
        Arrays.fill(S,0);

        //initial prefix sum
        S[0] = 0;
        for (int i = 1; i < array.length; i++)
        {
            //S_i = S_i-1 + A[i]
            S[i] = S[i - 1] + array[i];
        }
        //maximum found so far
        int max = 0;
        for (int j = 1; j < array.length; j++)
        {
            for (int k = j; k < array.length; k++)
            {
                //s = S_k - S_j-1
                int s = S[k] - S[j - 1];
                //if s > m, m <- s
                if (s > max)
                {
                    max = s;
                }
            }
        }
        return max;
    }//end maxSubFaster

The algorithm seems to work, but any pointers or corrections would be great!


texts: Access a variable after several references

texts:
I have a team lead that used to write references in a single script then access it in every script. Like for accessing a variable he has to write code in this way staticRef.scpRefGui.CLDropDown_Ref.Dropdown_ref.value

And sometime I see this kind of function calling  staticRef.scpRefGui.CQAScrollViewPOI_Ref.ShowExcelObjsInScrollView(username,WS_EnumClass.POIYaInfo.POI, list);

Here is another example, this code is getting a key from references file:

 public void testDict() {
        if (scpRef.AutoQADict_Ref.DictQA.ContainsKey(SheetNameDict))
        {
            if (scpRef.AutoQADict_Ref.DictQA[SheetNameDict].ContainsKey(UsernameDict))
            {
                if (scpRef.AutoQADict_Ref.DictQA[SheetNameDict][UsernameDict].ContainsKey(ObjName)) {
                    Debug.Log("dict: " + scpRef.AutoQADict_Ref.DictQA[SheetNameDict][UsernameDict][ObjName]);
                }
                else {
                        Debug.Log("ObjName: " + ObjName + " Not Found");

                    }
            }
            else {
                Debug.Log("UsernameDict: " + UsernameDict + " Not Found");
            }
        }
        else {
            Debug.Log("SheetNameDict Key: " + SheetNameDict + " Not Found");
        }
    }

I have strong disagreement of this way of coding. As it is unclear, contains several references, against SOLID, hard to debug etc (maybe I am wrong thats why i posted here).  Please help me that this is a valid approach? You(this site) have reviewed so many codes! Seriously bad code design kills you, and i am killing myself after seeing/updating this kind of code.


texts: Using a recurring System.Threading.Timer in an Mvc Application

texts:
I'd like your opinion on something. I have the following class:

public class ApplicationClock
{
    void tick(object _)
    {
        lock (tickLock)
        {
            try
            {
                MessageBroker.Publisher.Publish(new Tick());
            }
            catch (Exception e)
            {
                this.Logger().Error("Application clock tick error", e);
                //who knows why this happened, let's try and restart
                if (ticker != null) ticker.Dispose();
                Start();
            }
        }
    }
    readonly Object tickLock = new Object();
    Timer ticker = null;
    public ApplicationClock Start()
    {
        ticker = new Timer(tick, null, 0, 60*1000);
        return this;
    }
}

launched from the MvcApplication bootstrapper

...
ApplicationClock clock;
protected void Application_Start()
{
   //...
   clock = new ApplicationClock().Start();
}

I realize that a service and some sort of inter-process communication (whether windows inter-process communication, HTTP, or something else) is more standard and reliable but I have a frequently changing team and don't want to add another step that is necessary to run the app.

This seems to work but I've only launched it in a dev scenario. Am I missing anything that would cause problems in production?

That's a System.Threading.Timer by the way.


texts:
Problem Statement

  There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.

Input Format

  The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.

Constraints

  \$1≤N<100\$

  \$N % 2 = 1\$ (N is an odd number)

  \$0≤A_{i}≤100,∀i∈[1,N]\$

Output Format

  Output S, the number that occurs only once.

Solution

#!/usr/bin/py
from collections import Counter

def histogram(ary):
    """ Creates a histogram of the given array.
    Args:
        ary: The array.
    Returns:
        The dictionary with key as number and value as count.
    """
    return Counter(ary)

def lonelyinteger(ary):
    """ Finds the unique element in the array.
    Args:
        ary: The input array.
    Returns:
        Number or None
    """
    for frequency in histogram(ary).items():
        if frequency[1] == 1:
            return frequency[0]
    return None

if __name__ == '__main__':
    a = int(raw_input())
    b = map(int, raw_input().strip().split(" "))
    print lonelyinteger(b)

The solution works perfectly fine. But in the process of learning problem-solving, I am interested in a few things:

I don't think that the information like N is odd or maximum limit of 100 is related to my solution. Is there some optimizations I am missing?
What about the space complexity? I think it's \$O(N)\$ + size of the histogram.
Runtime seems linear i.e \$O(N)\$.

Solution 2

It includes the factors like why N should be odd.

Example: 1 ^ 1 ^ 2 ^ 2 ^ 3

#!/usr/bin/py
def lonelyinteger(a):
    res = 0
    for each in a:
        res ^= each
    return res

if __name__ == '__main__':
    a = input()
    b = map(int, raw_input().strip().split(" "))
    print lonelyinteger(b)


texts:
This is a follow-up to Boggle board solver in Ruby

class Trie < Hash
  def build(string)
    string << '.' # Terminator indicating end of a complete word
    string.chars.inject(self) do |h, char|
      h[char] ||= {}
    end
  end
end

# Build the trie from all the words
@trie = Trie.new
File.foreach('wordlist.txt') { |w| @trie.build(w.chomp) }

Here I use a simplistic Trie structure based on a Hash in Ruby. It does the trick very nicely, but I am wondering whether there is a better way to implement this in Ruby that will consume less memory.
(It lacks lookup methods which is perfectly fine, because I track through the Trie along with the path through letters on a board - the '.' acts as a marker for a complete word).

When I load the file, which contains 270K+ words and is ~2.9MB in size, the memory consumption is over 188 megabytes.

Is there a way to reduce the memory consumption, perhaps, implementing this differently?


texts: Resource caching in Java with soft references

texts:
I'd like to cache some heavy resources locally. The goal of this implementation is to have be able to load resources for an unknown amount of time and then keep them in memory and finally evict them upon needs. So there is no "time-based" evictions needed: only "memory-based" ones.

As written in comment, I'm writing this code in the scope of a small library using only Guava as dependency, and currently, Guava doesn't support the single-element cache.

I've developped the following code:

Resource.java

import com.google.common.io.ByteSource;
import java.io.UncheckedIOException;
import java.lang.ref.SoftReference;
import java.util.function.Supplier;

public class Resource<T> implements Supplier<T>, AutoCloseable {

  private final ByteSource source;
  private final ResourceLoader<T> loader;
  private SoftReference<T> reference;

  Resource(ByteSource source, ResourceLoader<T> loader) {
    this.source = source;
    this.loader = loader;
    reference = new SoftReference<>(null);
  }

  @Override
  public T get() throws UncheckedIOException {
    // Double-checked locking
    T object = reference.get();
    if (object == null) {
      synchronized(this) {
        object = reference.get();
        if (object == null) {
          object = this.loader.uncheckedLoad(this.source);
          this.reference = new SoftReference(object);
        }
      }
    }
    return object;
  }

  @Override
  public void close() {
    synchronized(this) {
      this.reference = new SoftReference<>(null);
    }
  }
}

ResourceLoader.java

import com.google.common.io.ByteSource;
import java.io.IOException;
import java.io.UncheckedIOException;

public interface ResourceLoader<T> {

  public default <T> T uncheckedLoad(ByteSource source) throws UncheckedIOException {
    try {
      return this.load(source);
    } catch (IOException ex) {
      throw new UncheckedIOException(ex);
    }
  }

  public <T> T load(ByteSource source) throws IOException;
}

I've also written the test:

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class ResourceTest {

  @org.junit.Test
  public void shouldCacheInstanceAndReturnIt() throws java.io.IOException {
    ResourceLoader<String> loader = mock(ResourceLoader.class);
    String abc = new String("abc"); // Force a specific address to avoid javac optimization
    when(loader.uncheckedLoad(any())).thenReturn(abc);
    when(loader.load(any())).thenReturn(abc);

    Resource<String> resource = new Resource(null, loader);

    assertThat(resource.get(), is(sameInstance(abc)));
    assertThat(resource.get(), is(sameInstance(abc)));

    verify(loader, times(1)).uncheckedLoad(any());
  }
}

My various questions regarding this code are the following:

Is this implementation appropriate for a cache?
Is the double-checked locking the right way to use this? A priori, various calls to Resource::get should return identical object (not especially in regard to Object::equals or ==, but mostly in regards to what the final user sees).
How can I properly test this implementation? I see it's working: my test passes, but how can I simulate a soft reference eviction? Can I simply call my close() method?


texts:
How can I improve my code, make it more efficient, and are there any tips you have?

Project Euler 3:

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

public class LargestPrimeFactor {

    public static void main(String[] args) {

        long num = 600851475143L;
        boolean isPrime = true;

        // this is to see if num is factorable
        for (int i = 2; i < num; i++) {

            //if i is a factor, check if its prime
            if (num % i == 0) {

                for (int j = 2; j < i; j++) {

                    if (i % j == 0) {

                        isPrime = false;

                    }

                }

                if (isPrime) {

                    System.out.println(i);

                }

            }

        }

    }

}


texts: Conversion functions between binary, hexadecimal and ASCII

texts:
I've written a small suite to easily convert my data between binary, hexadecimal and ASCII:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys

def to_list(chain, offset):
    return [chain[i:i+offset] for i in range(0, len(chain), offset)]

def bin2str(chain):
    return ''.join((chr(int(chain[i:i+8], 2)) for i in range(0, len(chain), 8)))

def bin2hex(chain):
    return ''.join((hex(int(chain[i:i+8], 2))[2:] for i in range(0, len(chain), 8)))

def str2bin(chain):
    return ''.join((bin(ord(c))[2:].zfill(8) for c in chain))

def str2hex(chain):
    return ''.join((hex(ord(c))[2:] for c in chain))

def hex2bin(chain):
    return ''.join((bin(int(chain[i:i+2], 16))[2:].zfill(8) for i in range(0, len(chain), 2)))

def hex2str(chain):
    return ''.join((chr(int(chain[i:i+2], 16)) for i in range(0, len(chain), 2)))

if __name__ == '__main__':
    word = sys.argv[1]
    word_bin = str2bin(word)
    word_hex = str2hex(word)

    # tests
    assert bin2str(word_bin) == word
    assert bin2hex(word_bin) == word_hex
    assert hex2str(word_hex) == word
    assert hex2bin(word_hex) == word_bin

    # output
    print "bin:", to_list(word_bin, 8)
    print "hex:", to_list(word_hex, 2)

Example:

$ ./utils.py test
bin: ['01110100', '01100101', '01110011', '01110100']
hex: ['74', '65', '73', '74']

How would you optimize those methods?

Also, I realize I'm actually only working with str representations of the different formats. What would you do to get real binary or hexadecimal results from those functions?


texts:
Robot Name

  Manage robot factory settings.

  When robots come off the factory floor, they have no name.

  The first time you boot them up, a random name is generated in the format
  of two uppercase letters followed by three digits, such as RX837 or BC811.

  Every once in a while we need to reset a robot to its factory settings,
  which means that their name gets wiped. The next time you ask, it will
  respond with a new random name.

  The names must be random: they should not follow a predictable sequence.
  Random names means a risk of collisions. Your solution must ensure that
  every existing robot has a unique name.

That was the instructions given to me.  The only constraints is the tests.  From my previous post I'm trying to improve on my naming conventions, DRY code, access modifiers, and keeping it readable.  Any advice would help me a lot since I'm learning C# and teaching myself.  Thank you for your help especially to those that follow my progress and help me.

using System;
using System.Collections.Generic;
using System.Linq;

public class Robot
{
    private static Random _random;
    private string _name;
    private static readonly HashSet<string> _nameList = new HashSet<string>();
    public string Name => _name;

    public Robot()
    {
        _random = new Random();
        _name = GenerateRandomName();
    }

    public void Reset()
    {
        _nameList.Remove(_name);
        _name = GenerateRandomName();
    }

    private static string GenerateRandomLetters() => new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 2)
      .Select(s => s[_random.Next(s.Length)]).ToArray());

    private static string GenerateRandomName()
    {
        string name;

        do
        {
            name = $"{GenerateRandomLetters()}{_random.Next(10)}{_random.Next(10)}{_random.Next(10)}";
        }
        while (_nameList.Contains(name));

        _nameList.Add(name);
        return name;
    }
}

using System.Collections.Generic;
using Xunit;

public class RobotNameTests
{
    private readonly Robot robot = new Robot();

    [Fact]
    public void Robot_has_a_name() => Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name);

    [Fact]
    public void Name_is_the_same_each_time() => Assert.Equal(robot.Name, robot.Name);

    [Fact]
    public void Different_robots_have_different_names() => Assert.NotEqual(new Robot().Name, robot.Name);

    [Fact]
    public void Can_reset_the_name()
    {
        var originalName = robot.Name;
        robot.Reset();
        Assert.NotEqual(originalName, robot.Name);
    }

    [Fact]
    public void After_reset_the_name_is_valid()
    {
        robot.Reset();
        Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name);
    }

    [Fact]
    public void Robot_names_are_unique()
    {
        var names = new HashSet<string>();
        for (int i = 0; i < 10_000; i++) {
            var robot = new Robot();
            Assert.True(names.Add(robot.Name));
        }
    }
}

The test are immutable.  They cannot be altered at all.  I did not write these test.  I have to work within the test.  I would be interested in learning on how to improve on them out of curiosity at best.


texts: Efficiently returning the string basis on current datacenter

texts:
We have machine hostname as -

dbx111.dc1.host.com
dbx112.dc2.host.com
dcx113.dc3.host.com

dcx115.dev.host.com

Here dc1, dc2, dc3 and dev are our datacenter and we will be having only four datacenter as of now. And also it might be possible that machine hostname can have more dots in between separated by another domain in future.

Now I need to find out which datacenter my current machine is in as I will be running below code on the actual machine.

And also I have two flows as of now: USERFLOW and DEVICEFLOW.

public enum FlowTypeEnum {
    USERFLOW, DEVICEFLOW
}

Problem Statement:

If my machine is in DC1 and flow type is USERFLOW then I need to return /test/datacenter/dc1 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc1
But if my machine is in DC2 and flow type is USERFLOW then I need to return /test/datacenter/dc2 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc2.
And if my machine is in DC3 and flow type is USERFLOW then I need to return /test/datacenter/dc3 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc3.
But if my machine datacenter is in DEV, and flow type is USERFLOW then I need to return "/test/datacenter/dc1" but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc1.

The only difference between USERFLOW and DEVICEFLOW is - For USERFLOW, I need to use /test and for DEVICEFLOW, I need to use /testdevice and other things are same.

TestingEnum class -

public class TestingDatacenter {

    public static void main(String[] args) {
        String LOCAL_POOK = DatacenterEnum.getOurlocation().toLocalPook(FlowTypeEnum.USERFLOW);
        System.out.println(LOCAL_POOK);
    }
}

DatacenterEnum class -

public enum DatacenterEnum {

DEV, DC1, DC2, DC3;

    public static DatacenterEnum getOurlocation() {
        return ourlocation;
    }

    public static String forCode(int code) {
        return (code >= 0 && code < values().length) ? values()[code].name() : null;
    }

    private static final DatacenterEnum ourlocation = compareLocation();

    private static DatacenterEnum compareLocation() {
        String currenthost = getHostNameOfServer();

        if (currenthost != null) {
            if (isDevMachine(currenthost)) {
                return DC1;
            }

            for (DatacenterEnum dc : values()) {
                String namepart = "." + dc.name().toLowerCase() + ".";
                if (currenthost.indexOf(namepart) >= 0) {
                    return dc;
                }
            }
        }
        return null;
    }

    public String toLocalPook(FlowTypeEnum f) {
        String prefix = "";
        // below if else, looks pretty  odd, may be it can be improved better?
        if (f.equals(FlowTypeEnum.DEVICEFLOW)) {
            prefix = "/testdevice";
        } else if (f.equals(FlowTypeEnum.USERFLOW)) {
            prefix = "/test";
        }
        if (this == DEV) {
            return prefix + "/datacenter/dc1";
        }

        return prefix + "/datacenter/" + name().toLowerCase();
    }

    private static final String getHostNameOfServer() {
        try {
            return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
        } catch (UnknownHostException e) {
            // log an exception
        }

        return null;
    }

    private static boolean isDevMachine(String hostName) {
        return hostName.indexOf("." + DEV.name().toLowerCase() + ".") >= 0;
    }
}

I'm opting for code review to see whether there is any better way of doing this. Is there anything which can be simplified and improved?


texts:
I'm implementing KNN algorithm to predict outliers in network data which contains the following columns: source IP address, source port number, protocol and total bytes transferred. To achieve this, I'm using the Python library sklearn to predict response variable (total bytes) with regards to explanatory variables (source IP address, source port number, protocol).

However, the accuracy of prediction on test data is extremely low (0.21). Any recommendations to improve the accuracy score will be much appreciated.

import pandas as pd
from sklearn.neighbors import KNeighborsRegressor
import random
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from numpy.random import permutation
from sklearn.metrics import accuracy_score
import sys
import math
import netaddr as nt
from netaddr import IPAddress

#Import csv into dataframe
df = pd.read_csv('data.csv')
df = df[['sourceaddress','sourceport','protocol','total_bytes']]

df_arr = df.as_matrix()

for i in range(df_arr.shape[0]):
    df_arr[i,0] = int(nt.IPAddress(df_arr[i,0]))

df = pd.DataFrame(df_arr)
df.columns = ['sourceaddress','sourceport','protocol','total_bytes']
df = df.astype('str')

# Design matrix X and target vector y
X = np.array(df.ix[:, 0:3])
Y = np.array(df['total_bytes'])

# split into train and test
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state=42)

knn = KNeighborsClassifier(n_neighbors=24)
# fitting the model
knn.fit(X_train, Y_train)

# prediction of the response variable
pred = knn.predict(X_test)
print pred

# evaluate accuracy
print accuracy_score(Y_test, pred)


texts:
I am currently using the following query to add a specific row (with 10 columns) from an Excel spreadsheet (~1500 rows and hosted on SharePoint - I've also tested locally with the same issue) to an array in PowerShell.

$connection = New-Object System.Data.OleDb.OleDbConnection

$connectstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=$Source;Extended Properties='Excel 12.0 Xml;HDR=YES'"; $connection.ConnectionString = $connectstring

$connection.open()

$cmdObject = New-Object System.Data.OleDb.OleDbCommand

$query = "Select * from [Sheet1$]
WHERE [Sheet1$].[Test] = '$Test'"
$cmdObject.CommandText = $query
$cmdObject.CommandType = "Text"
$cmdObject.Connection = $connection

$oReader = $cmdObject.ExecuteReader()

[void]$oReader.Read()
    $Global:oData = New-Object PSObject
    $oData | Add-Member NoteProperty List1    $oReader[0]
    ...
    $oData | Add-Member NoteProperty List10   $oReader[9]

$oReader.Close()
$cmdObject.Dispose()
$connection.Close()
$connection.Dispose()

This works absolutely fine, however, it is often quite slow. Is there any way in which I could speed up the query? I can't add the entire Excel sheet into an array, as the data changes throughout the day and is queried regularly.

I've found other questions, such as this one. However, that doesn't seem relevant to this particular issue.


texts: Highlight the active link in a navigation menu

texts:
I wonder if my script is all right. Please review my code:

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Menu</title>

Home

News

Contact

About

It should highlight the current page link in the navigation bar.


texts:
I am coding a game, and I need to detect the color of a rectangles on a canvas, by moving a character and  touching them, so that a message will be displayed "this is magenta" and so on. Please find below the game and my coding, so that you will better understand me:

jsFiddle

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

/*moving grey character*/
var xPos = 0;
var yPos = 0;

var bucketWidth = 100;
var bucketHeight = 10;

context.fillStyle = "grey";
context.fillRect(xPos, yPos, bucketWidth, bucketHeight);
context.strokeRect(xPos, yPos, bucketWidth, bucketHeight);

/*static red character*/
var xPos2 =  canvas.width / 2;
var yPos2 =  canvas.height / 2;

var bucketWidth2 = 100;
var bucketHeight2 = 10;

context.fillStyle = "red";
context.fillRect(xPos2, yPos2, bucketWidth2, bucketHeight2);

/*static magenta character*/

var bucketWidth3 = 100;
var bucketHeight3 = 10;

var xPos3 =  canvas.width / 2;
var yPos3 =  - bucketHeight3 - bucketHeight3 + canvas.height / 2;

context.fillStyle = "magenta";
context.fillRect(xPos3, yPos3, bucketWidth3, bucketHeight3);

/*Function to move the grey character from left to right and from top to button*/

function move(e){

if (e.keyCode === 37 && xPos > 0 && xPos <= canvas.width-bucketWidth){
    xPos -= bucketWidth;
} else if (e.keyCode === 39 && xPos >= 0 && xPos < canvas.width-bucketWidth){
    xPos += bucketWidth;
}  else if (e.keyCode === 40 && yPos >= 0 && yPos < canvas.height-bucketHeight){/*down arrow*/
    yPos += bucketHeight;
}  else if (e.keyCode === 38 && yPos > 0 && yPos <= canvas.height-bucketHeight){ /*up arrow*/
    yPos -= bucketHeight;
}

canvas.width= canvas.width;

context.fillStyle = "grey";
context.fillRect(xPos, yPos, bucketWidth, bucketHeight);
context.strokeRect(xPos, yPos, bucketWidth, bucketHeight);

context.fillStyle = "red";
context.fillRect(xPos2, yPos2, bucketWidth2, bucketHeight2);

context.fillStyle = "magenta";
context.fillRect(xPos3, yPos3, bucketWidth3, bucketHeight3);

}

document.onkeydown = move;

By the way, I was told to use the function getImageData(), but I could not apply the function by moving the character. Somebody send me an example, but it is working by using the mouse and jQuery was used, but I am not allowed to use jQuery. Please see this link.


texts: Powershell search millions of files as fast as possible

texts:
I once asked a similar question but in C#. Now I have the same problem in powershell..

What is the fastest way, to search files newer than 15 minutes, in a file system with more than 1 million files?

Is there any faster way than using pipe?

Get-ChildItem -Path $path -Recurse | Select Name, PSIsContainer, Directory, LastWriteTime, Length| where {($_.LastWriteTime -gt (Get-Date).AddMinutes(-15))}

I already cut off some attributes to minimize the object size. It still takes ages.


texts:
I needed short, unique, seemingly random URLs for a project I'm working on, so I put together the following after some research. I believe it's working as expected, but I want to know if there's a better or simpler way of doing this. Basically, it takes an integer and returns a string of the specified length using the character list. I'm new to Python, so help is much appreciated.

def genkey(value, length=5, chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', prime=694847539):
    digits = []
    base = len(chars)
    seed = base ** (length - 1)
    domain = (base ** length) - seed
    num = ((((value - 1) + seed) * prime) % domain) + seed

    while num:
        digits.append(chars[num % base])
        num /= base
    return ''.join(reversed(digits))


texts:
I attempted to make better Fibonacci sequence calculation algorithm in C++. This was the best I could:

constexpr unsigned fibonacci(unsigned n) {
    unsigned result[2] = {1, 0};
    for (unsigned i = 1; i < n; ++i)
        result[i%2] = result[0] + result[1];
    return result[1 - n%2];
}

...which runs at O(n) time complexity and O(1) space complexity.
Is there any better?


texts: Combine multiple jQuery click events and functions

texts:
I have a page with multiple menus. Once I hit a certain window width, I use CSS and jQuery to turn them into accordions. I also check the screen size when resizing so the accordions don't stay hidden if the user resizes the window. Since I have two window widths I need to adjust for, I am using two click events to open and close the accordions and two to check the window width.

I could really use some help to clean up this code and combine if possible.

$('footer').find('.col-md-2 .accordion-toggle').click(function () {
    var width = $(window).width();
    if (width <= 991) {
        $(this).next('div').slideToggle('medium');
    }
});

$('footer').find('.details-wrapper .accordion-toggle').click(function () {
    var width = $(window).width();
    if (width <= 475) {
        $(this).next('div').slideToggle('medium');
    }
});

$(window).resize(function () {
    checkWidth();
});

function checkWidth(){
    $width = $(window).width();
    var locationToggle = $(".details-wrapper .accordion-toggle").next('div');
    if($width > 475){
        $(locationToggle).show();
    } else {
        $(locationToggle).hide();
    }

    var accordionToggle = $(".col-md-2 .accordion-toggle").next('div');
    if($width > 991){
        $(accordionToggle).show();
    } else {
        $(accordionToggle).hide();
    }
}

```


texts: Collapse long text (with more/less links)

texts:
I wrote a little function to compact long text. I am relatively new to JavaScript so I am not sure I wrote it as elegantly as possible. I wrote it to be runnable on the server side (Node.js) as well, so can't use jQuery or such. Can the code be improved?

// change a long text into  "bla bla bla... (more)" where (more) is a link to open the rest of the text
// compact text if over maxWords words (split by ' ', default 25)
//           or if over maxRows lines (split by '
', default 2)
// but avoid compacting if no more than "almostFinished" (default 5) words to the end of the text
compactText = function(text, prefix, maxWords, maxRows, almostFinished) {
    if (!maxWords) {
        maxWords = 25;
    }
    if (!maxRows) {
        maxRows = 2;
    }
    if (!almostFinished) {
        almostFinished = 5;
    }

    var result = [];
    var compacted = false;
    // escape the html code in the text
    text = (text || '').replace(/</g, '&lt;').replace(/>/g,'&gt;').replace(/\r/g, ' ').replace(/\n/g, '
 ')
    var pn = text.split(' ');
    var row = 1;
    for (var word=0; word< pn.length; word++) {
        if (pn[word] === "
") {
            row++;
        }
        if (!compacted && (row > maxRows || word == maxWords) && word< pn.length - almostFinished) {
            compacted = true;
            /* too long - add a (more) link and open hidden span for rest of text */
            result.push('...(show more)');
            result.push('');
        }

        result.push(pn[word]);
    }
    if (compacted) {
        // compacted: add link to toggle back (less) and close the hidden span.
        result.push('(show less)');
    }

    return result.join(' ');
}


texts:
Follow-up to Python program to find a word ladder transforming "four" to "five"

I'm trying to write a program to solve a word ladder puzzle to brush up on my Python. For those who don't know:

  A word ladder puzzle begins with two words, and to solve the puzzle one must find a chain of other words to link the two, in which two adjacent words (that is, words in successive steps) differ by one letter. - Wikipedia

I've implemented breadth first search as opposed to depth first search for a big performance boost since my last question, as suggested in the answers.
I've also added a new mode, that can add and remove letters as well as just swapping them.
Additionally, the program now takes user input, and can take more than two words to link together (given a b c, it runs a b, and then runs b c).

The program now takes ~6 seconds on my machine to run with input of five four and 1. I'm still interested in making this faster, and also would like to know how to make it more Pythonic.

# -------- Data Structures --------
class Queue():
    """ FIFO Queue """
    def __init__(self, parent = None):
        self.list = []
        self.parent = parent
    def append(self, value):
        self.list.append(value)
    def pop(self):
        return self.list.pop(0)

class Node():
    """ Node of a Tree """
    def __init__(self, value, parent = None):
        self.value = value
        self.parent = parent

# -------- Distance Functions --------
def hamming(s1, s2):
    return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))

def levenshtein(s1, s2):
    if len(s1) < len(s2):
        return levenshtein(s2, s1)
    if len(s2) == 0:
        return len(s1)
    previous_row = range(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1
            deletions = current_row[j] + 1
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row
    return previous_row[-1]

# -------- IO --------

# Print sequence from root to node
def print_words(node):
    values = []
    while isinstance(node, Node):
        values.append(node.value)
        node = node.parent
    print(list(reversed(values)))

# Get all input
all_words = open("/usr/share/dict/words", "r").read().lower().splitlines()
input_words = input("Enter list of words, seperated by spaces: ").split()
input_mode = int(input("Enter 1 for swap-only mode, or 2 for swap-add-rem mode: "))

# Validate user input
if not 1 <= input_mode <= 2:
    raise ValueError("Invalid mode: " + input_mode)

for word in input_words:
    if word not in all_words:
        raise ValueError("Invalid word: " + word)

# Adapt to mode
distance = [hamming, levenshtein][input_mode - 1]
if input_mode == 1:
    all_words = [word for word in all_words if len(word) == len(input_words[0])]

# -------- Breadth First Search --------
def fill(node, to_check, checked):
    checked.add(node.value)
    for word in all_words:
        if 1 >= len(word) - len(node.value) >= -1 and distance(word, node.value) == 1:
            to_check.append(Node(word, node))

for i in range(len(input_words) - 1):
    root = Node(input_words[i])
    checked = set()
    to_check = Queue()

    fill(root, to_check, checked)
    while to_check.list:
        node = to_check.pop()
        if node.value == input_words[i + 1]:
            print_words(node)
            break
        if node.value not in checked:
            fill(node, to_check, checked)


texts: Exception handling continuing the excecution

texts:
This code is for continuing the execution after an exception, and this is ugly:

    int step=0;

    do{
        try{
                switch(step)
                {
                case 0:
                    step=1;
                    methodAAAAACanThrowException();
                    break;
                case 1:
                    step=2;
                    methodBBBBBCanThrowException();
                    break;
                case 2:
                    step=3;
                    methodCCCCCanThrowException();
                    break;
                    //....

                    //more and more

                    //....
                case 25:
                    step=26;
                    methodZZZZZCanThrowException();
                }
        }catch( Exception ex)
        {

            Logger.getLogger(ABC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }while(step<26);
}

but writing a single try-catch loop for every call, seems even uglier..

Is there any other more elegant option for doing that?
thanks


texts:
In my Repository class:

public class DeliveryRepository : IDeliveryRepository
{
    private readonly List<Delivery> deliveries = new List<Delivery>();

    public Delivery Add(Delivery item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }
        deliveries.Add(item);
        return item;
    }
}

...I could implement my Add() method this way:

public Delivery Add(Delivery item)
{
    Contract.Requires(item != null);
    deliveries.Add(item);
    return item;
}

...or this way instead:

public Delivery Add(Delivery item)
{
    Contract.Requires<ArgumentNullException>(item != null, "item");
    deliveries.Add(item);
    return item;
}

Which of the three is best? Does it matter? Just a matter of style/preference?

Are they 2 of one, a pair of the other, and a couple of the third?


texts:
I'm new to programming in general, started on boxing day. I'm trying to
learn python.
The list remove method only removes the first instance of the value found.
In the code below I attempted to remove all the instances.
Are there better ways of accomplishing this? Is this efficient? Any and all feedback is wanted.

wordlist = ["dog", "cat", "mouse", "giraffe", "cat"]
remove_queue = []
userinput = input("remove: ")
for i in range(len(wordlist)):
    if wordlist[i] == userinput:
        remove_queue.append(i)

""""reversed the list, so when deleting a value, the position of the other
values don't change"""
remove_queue.sort(reverse=True)
for i in range(len(remove_queue)):

"""uses the remove_queue list to find the position of value that needs to be
removed, and removes it. """
    del wordlist[remove_queue[i]]
print(wordlist)


texts:
This reverses the case of a character in a string (a string being an array of characters). How does it look? Anything I can improve on? Let's get critical here.

#include <iostream>
#include <string>
//
// return a new string
//
std::string camel_case_rev(const std::string &word)
{
        std::string ret = "";

        for(unsigned i = 0; i < word.size(); i++) {
                if(word[i] <= 'Z' && word[i] >= 'A') {
                        ret += tolower(word[i]);
                }
                else if(word[i] <= 'z' && word[i] >= 'a') {
                        ret += toupper(word[i]);
                }
                else {
                        ret += word[i];
                }
        }
        return ret;
}

int main(int argc, char **argv)
{
        if(argc < 2) {
                std::cerr << "USAGE: " << argv[0] << " " << "<string>\n";
                return 1;
        }

        std::string a = camel_case_rev(argv[1]);

        std::cout << a << "\n";

        return 0;
}


texts: Minesweeper grid representation + calculating neighbor-sums

texts:
I'm trying to get better at Python and would like a critique.

Problem statement:

  Accept a 2D grid containing 1's and 0's (1 being mine locations) and
  print a solved sum grid (the way the final grid would show upon
  completion of a minesweeper game with all the neighbor sums).

Beyond that, what might be horribly wrong with the code below?  I am interested in finding a recommended balance between readability and what the cool kids call idiomatic. For example, List comprehension in some places was deliberately omitted in favor of making something that I thought was easier on the eyes.

The top-level functions are called via:

if __name__ == '__main__':
    locMap = [[1,0,0,0],[0,0,1,0],[0,1,0,1]] # Sample input
    print "Location map = "
    printMineField(locMap,locMap)
    newMap = getSummedMap(locMap)
    print "Summed map = "
    printMineField(locMap,newMap)

The output is:

'''

Location map =
* 0 0 0
0 0 * 0
0 * 0 *

Summed map =
* 2 1 1
2 3 * 2
1 * 3 *

'''

The actual functions are:

def generatePaddedGrid(grid):
    """
    Input: 2D list.
    Output: 2D list
    Purpose: Returns a 0-padded boundary around a grid.  Useful to perform
    easier 2D traversal + operations of the inner grid without painful
    boundary checking
    """

    # Get Dimensions of grid
    nRows = len(grid)
    nCols = len(grid[0])

    # Create a grid with +2 row/col padding (on all sides)
    paddedGrid = [[0 for x in range(0,nCols + 2)] for x in range(0,nRows + 2)]

    # Insert 'centered' locMap into the Padded Grid
    for xIter in range(0,nRows):
        for yIter in range(0,nCols):
            paddedGrid[xIter+1][yIter+1] = grid[xIter][yIter]

    return paddedGrid

def getSummedMap(locMap):
    """
    Input: 2D list
    Output: 2D list
    Purpose: Takes in a 2D array (locMap)   and returns a same-sized array
    with each cell now containing the sum of all the neighbors including
    diagonals (max of 8 neigbor cells)
    """

    # Insert + Center this grid into a padded grid to prevent access errors
    paddedGrid = generatePaddedGrid(locMap)

    nRows = len(locMap)  #Actual rows to be iterated
    nCols = len(locMap[0]) #Actual cols to be iterated.

   # Create a target/output grid of the actual size to write the sums into
    sumGrid = [[0 for x in range(0,nCols)] for y in range(0,nRows)]

    for xIter in range(1,nRows+1):
        for yIter in range(1,nCols+1):
            Sum = 0
            # Top + Bottom + Left + right
            Sum  += paddedGrid[xIter-1][yIter] +\
                    paddedGrid[xIter+1][yIter] +\
                    paddedGrid[xIter][yIter+1] +\
                    paddedGrid[xIter][yIter-1]

            # Then 4 diagonals
            Sum  += paddedGrid[xIter-1][yIter-1] +\
                    paddedGrid[xIter+1][yIter-1] +\
                    paddedGrid[xIter+1][yIter+1] +\
                    paddedGrid[xIter-1][yIter+1]

            sumGrid[xIter-1][yIter-1] = Sum

    return sumGrid

def printMineField(locMap, SumMap):
    """
    Input: 2 x 2D Arrays
    Output: No return, just print an overlayed Sum-map over a given Loc-map
    but leave the mine-locations as '*' (instead of the neighbor-sums)
    """

    numActualRows = len(locMap)  #Actual rows to be iterated
    numActualCols = len(locMap[0]) #Actual cols to be iterated.

    for xIter in range(0,numActualRows):
        for yIter in range(0,numActualCols):
            if locMap[xIter][yIter] == 1:
                print '*',
            else:
                print str(SumMap[xIter][yIter]),
        print '\n'


texts:
I'm looking to simplify the below code for validating an onChange event. The allowedInput is a regex that is passed (optional) from all the form components.
    const validatedOnChange = (event: ChangeEvent<HTMLInputElement>): void => {
        if (isDisabled) {
            return;
        }
        if (allowedInput) {
            if (allowedInput.test(event.target.value)) {
                onChange({ name, value: event.target.value });
            }
            return;
        }
        onChange({ name, value: event.target.value });
    };

This is a common utility method used for all my React form components. Hence looking to write a readable and consistent code.


texts:
I am learning to write micro bench marks for Java methods. I read that while writing methods for bench marking we should be careful of writing code which compiler/JVM can optimize.

I have writeen my first bench mark for stack. Just by looking at my code it looks like a lot of code being repeated hence i doubt whether this code can be optimized by JVM. Please have a look at the code and share your thoughts?

Basically I want to test for multiple push and pop calls.

 @Benchmark
@BenchmarkMode(Mode.All)
@OutputTimeUnit(TimeUnit.SECONDS)
public void benchMark_Array(Blackhole blackhole) {
    StringBuilder stringBuilder = new StringBuilder();

    Stack<String> stack = new StackArrayImpl<>();
    stack.push("String 11");
    stack.push("String 12");
    stack.push("String 13");
    stack.push("String 14");
    stack.push("String 15");
    stack.push("String 16");
    stack.push("String 17");
    stack.push("String 18");
    stack.push("String 19");
    stack.push("String 2");
    stack.push("String 1");

    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());

    blackhole.consume(stringBuilder.toString());
}


texts: Execute .NET Core 3.1 background worker tasks simultaneously

texts:
I have following code:
public class Worker : BackgroundService
{

    public Worker()
    {
    }

    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var task1 = Task.Run(() =>
                MethodOneAsync(stoppingToken)
            ).ContinueWith(_ => Debug.WriteLine($"MethodOneAsync finished @ {DateTime.Now:dd.MM.yyyy HH:mm:ss.ffff}"));
            var task2 = Task.Run(() =>
                MethodTwoAsync(stoppingToken)
            ).ContinueWith(_ => Debug.WriteLine($"MethodTwoAsync finished @ {DateTime.Now:dd.MM.yyyy HH:mm:ss.ffff}"));

            await Task.WhenAll(task1, task2);

            await Task.Delay(10000);
        }
    }

    private async Task<bool> MethodOneAsync(CancellationToken stoppingToken)
    {
        Debug.WriteLine($"MethodOneAsync started @ {DateTime.Now:dd.MM.yyyy HH:mm:ss.ffff}");
        await Task.Delay(1000); // emulating some long work

        return true;
    }

    private async Task<bool> MethodTwoAsync(CancellationToken stoppingToken)
    {
        Debug.WriteLine($"MethodTwoAsync started @ {DateTime.Now:dd.MM.yyyy HH:mm:ss.ffff}");
        await Task.Delay(1000); // emulating some long work

        return true;
    }
}

What I want to achieve is:

to create background worker that will call MethodOneAsync and MethodTwoAsync on separate threads (start both tasks simultaneously)
log time each task started and finished
wait for them both to finish
then wait another 10 seconds
repeat all over again

The code I wrote does its job as expected.
Since I am still trying to get a grasp of .NET Core tasks, I would like to know is this the right way to do it?


texts:
The code implements fully generic sliding window with linear complexity. It should usually be paired with transforming iterator to reach full potential.

Sliding window is a grouping of elements by exactly length of sliding window, then "sliding" the window by one element on each iteration.
Example: Given A = [0, 1, 2, 3], L=3, there are 2 windows: [0, 1, 2], [1, 2, 3].

But instead of working only on numbers, the code works on anything, given that user supplies their own add operation (adds an element into the window), and remove operation (removes the element from the window).
#ifndef SUNRISE_SLIDING_WINDOW_HPP
#define SUNRISE_SLIDING_WINDOW_HPP

#include <functional>
#include <stdexcept>
#include <iterator>

namespace shino
{
    template<typename BidirIt,
             typename OutputIt,
             typename T = typename std::iterator_traits<BidirIt>::value_type,
             typename BinaryDoOp = std::plus<>,
             typename BinaryUndoOp = std::minus<>>
    std::pair<BidirIt, OutputIt> sliding_window(BidirIt first,
                        BidirIt last,
                        OutputIt d_first,
                        typename std::iterator_traits<BidirIt>::difference_type length,
                        T init = {},
                        BinaryDoOp add_op = {},
                        BinaryUndoOp remove_op = {})
    {
        if (first == last || length == 0)
        {
            return std::make_pair(first, d_first);
        }

        BidirIt milestone(std::next(first, length)); //try to default construct
        auto tail = first;

        while (first != last && first != milestone)
        {
            init = add_op(init, *first);
            ++first;
        }

        if (first != milestone)
        {
            throw std::invalid_argument("Iterator range is smaller than length of the window");
        }

        *d_first = init;
        ++d_first;

        if (first == last)
        {
            return std::make_pair(first, d_first);
        }

        while (first != last)
        {
            init = remove_op(init, *tail);
            init = add_op(init, *first);
            *d_first = init;
            ++tail;
            ++first;
            ++d_first;
        }

        return std::make_pair(first, d_first);
    }
}

#endif //SUNRISE_SLIDING_WINDOW_HPP

So aim is to make a generic version of this code,  providing some defaults to make it easy to use. Though the best way of using the generic sliding algorithm is to write more specialized ones, for the sake of clarity and narrowing down the error vectors. Also, using transform_iterator, it is possible to get full power over grouped manipulation.
So, here is example: the sliding average using generic sliding window:
template <typename InputIt, typename OutputIt>
std::pair<InputIt, OutputIt> sliding_average(InputIt first, InputIt last,
                    const typename std::iterator_traits<InputIt>::difference_type window_length,
                    OutputIt d_first)
{
    using value_type = typename std::iterator_traits<InputIt>::value_type;
    auto divide = [&window_length](const value_type& value)
    {
        return value / window_length;
    };

    auto iterator = shino::transformer(divide, d_first); //transform_iterator<Functor, Iterator>

    auto result = shino::sliding_window(first, last, iterator, window_length);

    return std::make_pair(result.first, result.second.internal_iterator());
}

The algorithm also warns if input type is int, and output type is double, e.g. compiler will warn if narrowing conversions are performed.


texts:
I want to just write a simple function to check if my linux box has hyperthreading enabled. I want to know if there's a simpler way to produce the cpuinfo dict (would be great if I could use a dict comprehension somehow) or generally a better way to check this information:

def is_hyperthreading_enabled():
    cpuinfo = dict(map(str.strip, line.split(':'))
                   for line in open('/proc/cpuinfo')
                   if ':' in line)

    return cpuinfo['siblings'] != cpuinfo['cpu cores']


texts: Accessing time series development data from World Bank API

texts:
I wrote a script that connects to World Bank API, gathers some data (indicators) for a number of countries, creates pd.DataFrame, and saves the result as xlsx file.

What I had in mind when I was writing the code:

I wanted to avoid constructing pd.DataFrame within the function or using the append method to store data in-memory (not sure if it helps in this case; is it a good practice in general?).
I thought it was a good idea to split the code into separate functions (one that iterates over data, one that makes requests for every page that is related to the indicator, and finally, the one that iterates over all indicators and calls other functions).
It was the first time I used yield from and I'm not sure if it's the correct way of using the construct.
Not sure about typings.

import os
import requests
import pandas as pd
from time import sleep
from itertools import chain
from datetime import datetime
from typing import List, Iterator

COUNTRIES = {
    "Baltic States": ["EST", "LVA", "LTU"],
    "Central Asia": ["KAZ", "KGZ", "TJK", "TKM", "UZB"],
    "Eastern Europe": ["BLR", "MDA", "UKR"],
    "Eurasia": ["RUS"],
    "Transcaucasia": ["ARM", "AZE", "GEO"]
}
INDICATORS = {
    "Infrastructure": ["EG.ELC.ACCS.RU.ZS", "IT.CEL.SETS"],
    "Medicine": ["SH.DYN.MORT", "SH.DYN.AIDS.ZS"],
    "Public Sector": ["GC.TAX.TOTL.GD.ZS", "MS.MIL.TOTL.TF.ZS"]
}

URL = "http://api.worldbank.org/v2/country/"
DATE = datetime.today().strftime("%Y-%m-%d %H_%M")
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
ISO3_PARAM = ';'.join(chain(*COUNTRIES.values()))
INDICATOR_PARAM = list(chain(*INDICATORS.values()))

def mapping(s: pd.Series, metadict: dict) -> str:
    """ Assign categories to Series' values according to dict's keys. """

    return ' '.join((k) for k,v in metadict.items() if s in v)

def item_level(data: List) -> Iterator:
    """ Iterate over data and yield dict containing specific fields. """

    for item in data:
        yield {
            "iso3": item["countryiso3code"],
            "indicator": item["indicator"]["value"],
            "id": item["indicator"]["id"],
            "year": item["date"],
            "value": item["value"]
        }

def page_level(indicator: str) -> Iterator:
    """ Iterate over all pages related to specific indicator. """

    base_url = f"{URL}{ISO3_PARAM}/indicator/{indicator}?format=json"

    next_page = 1
    while True:
        meta, data = requests.get(f"{base_url}&page={next_page}").json()
        yield from item_level(data)

        num_pages, next_page = meta["pages"], next_page + 1
        if next_page > num_pages:
            break

        sleep(1)

def indicator_level(indicators: List) -> Iterator:
    """ Iterate over all indicators. """

    for indicator in indicators:
        yield from page_level(indicator)

def main():
    """ Create pd.DataFrame from generator and save it. """
    df = pd.DataFrame(indicator_level(INDICATOR_PARAM))
    df["year"] = df["year"].astype(int)
    df["region"] = df["iso3"].apply(mapping, metadict=COUNTRIES)
    df["category"] = df["id"].apply(mapping, metadict=INDICATORS)
    df.loc[df["year"] >= 1991].to_excel(f"{CURRENT_DIR}/../../data/raw/dataset_{DATE}.xlsx", index=False)

if __name__ == "__main__":
    main()


texts: C++: Generating similar methods with macros

texts:
I am currently working on a project that involves Lua. For convenience, I created a wrapper class for the Lua state structure. However, I also added some methods for getting globals and table fields. Since these methods are very similar, I decided do turn them into macros.

Do you consider this a good solution? Would you have done it another way?

#include <lua/lua.hpp>

#include <util/Exception.h>
#include "LuaState.h"

namespace gnaar {

LuaState::LuaState() : ls(luaL_newstate())
{
    luaL_openlibs(ls);
}

void LuaState::doFile(const char* file)
{
    if (luaL_dofile(ls, file) != 0)
    {
        throwException(lua_tostring(ls, -1));
    }
}

lua_State* LuaState::operator*()
{
    return ls;
}

LuaState::~LuaState()
{
    lua_close(ls);
}

//==================== ugly macro stuff below, beware ====================

#define _getGlobal(_lua, _type, _check, _conversion)                    \
    template <>                                                         \
    _type LuaState::getGlobal<_type>(const char* name, _type dfault)    \
    {                                                                   \
        lua_getglobal(_lua, name);                                      \
        if (_check(_lua, -1))                                           \
        {                                                               \
            return (_type) _conversion(_lua, -1);                       \
        }                                                               \
        else                                                            \
        {                                                               \
            return dfault;                                              \
        }                                                               \
    }

#define _getTableField(_lua, _type, _check, _conversion)    \
    template <> _type LuaState::getTableField<_type>        \
    (const char* table, const char* key, _type def)         \
    {                                                       \
        lua_getglobal(_lua, table);                         \
        if (!lua_istable(_lua, -1))                         \
        {                                                   \
            return def;                                     \
        }                                                   \
        _type result;                                       \
        lua_pushstring(_lua, key);                          \
        lua_gettable(_lua, -2);                             \
        if (!_check(_lua, -1))                              \
        {                                                   \
            result = def;                                   \
        }                                                   \
        else                                                \
        {                                                   \
            result = (_type) _conversion(_lua, -1);         \
        }                                                   \
        lua_pop(_lua, 1);                                   \
        return result;                                      \
    }

_getGlobal(ls, int, lua_isnumber, lua_tonumber)

_getGlobal(ls, const char*, lua_isstring, lua_tostring)

_getGlobal(ls, bool, lua_isboolean, lua_toboolean)

_getTableField(ls, int, lua_isnumber, lua_tonumber)

_getTableField(ls, const char*, lua_isstring, lua_tostring)

_getTableField(ls, bool, lua_isboolean, lua_toboolean)

} // namespace gnaar


texts:
Today I tried Bonobo + SQLAlchemy (for the first time), so it's bound to be full of bad practices. However, this is working code. I'm hoping for some feedback to for doing it correctly.

I started out using the SQLAlchemy extension for Bonobo, but I ran into limitations, so I wrote my own loader. My DB is SQLite3, so it doesn't support multiple connections.

What this does is read from one table, do a simple transformation and load into a target table with a different table structure.

SQLite database:

CREATE TABLE sys_batch (
    batch_id        INTEGER PRIMARY KEY AUTOINCREMENT,
    batch_name      VARCHAR2 ( 100 ) );

CREATE TABLE sys_batch_tgt (
    batch_id        INTEGER PRIMARY KEY,
    name_of_batch   VARCHAR2 ( 100 ) );

Python code:

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.sql import select
from sqlalchemy.orm import Session

import bonobo
#import bonobo_sqlalchemy

engine = sqlalchemy.create_engine('sqlite:///C:/Py/bonobo/coolstuff.db')
Base = automap_base()
Base.prepare(engine, reflect=True)

# Tables
sys_batch = Base.classes.sys_batch
sys_batch_tgt = Base.classes.sys_batch_tgt

#def get_services():
#   return {'sqlalchemy.pgengine': sqlalchemy.create_engine('sqlite:///C:/Py/bonobo/coolstuff.db')}

def extract_sys_batch():
    conn = engine.connect()
    s = select([sys_batch])
    result = conn.execute(s)
    #conn.close()
    row = result.fetchone()
    yield row

# convert incoming SQLAlchemy "ProxyRow" to a dict, so we can manipulate it.
def tfm_0(row):
    tgt_row = {}
    tgt_row['batch_id'] = row['batch_id']
    tgt_row['name_of_batch'] = row['batch_name']
    return tgt_row

def tfm_1(row):
    row['batch_id'] = row['batch_id'] + 100
    return row

def ldr_1(row):
    # write to target
    session = Session(engine)
    thing = sys_batch_tgt(**row)
    session.add(thing)
    session.commit()

def get_graph(**options):

    return bonobo.Graph(
        extract_sys_batch,
        tfm_0,
        tfm_1,
        ldr_1,
        bonobo.PrettyPrinter(),
    )

# The __main__ block actually execute the graph.
if __name__ == '__main__':
    parser = bonobo.get_argument_parser()

    #each transformation is its own thread, so we have to open/close in there.
    #conn = engine.connect()

    with bonobo.parse_args(parser) as options:
        bonobo.run(get_graph(**options)) #, services=get_services(**options)

    #conn.close()