texts:
After reading this, I decided to transition my DQN code from the keras library to tf.keras library (code is located in this repo) and my original code used NCHW format, as it was faster with GPUs. As I need to run in CPUs also, I found out that it ran only with NHWC format on my tf version (1.12 with python 3.7, compiled with AVX2 flags).

I redesigned my code and it's working, but I stack in the NCHW format and then I have to transpose it every function call, which is costly.

My code

There is a 'frames' list sized 'self.nb_frames', which will hold the (10, 10) states. Then I expand_dims and transpose, returning the list in NHWC format.

example.py

#!/usr/bin/env python

import numpy as np

class Agent():

    def __init__(self):
        """Initialize the agent with given attributes."""
        self.frames = None
        self.nb_frames = 4

    def get_game_data(self, state):
        """Create a list with 4 frames and append/pop them each frame."""
        frame = state

        if self.frames is None:
            self.frames = [frame] * self.nb_frames
        else:
            self.frames.append(frame)
            self.frames.pop(0)

        # from (4, 10, 10) to (1, 4, 10, 10)
        expanded_frames = np.expand_dims(self.frames, 0)

        # From (1, 4, 10, 10) to (1, 10, 10, 4) | NCHW -> NHWC
        expanded_frames = np.transpose(expanded_frames, [0, 3, 2, 1])

        return expanded_frames

board_size = 10
state = np.zeros((board_size, board_size))
agent = Agent()
stacked_state = agent.get_game_data(state)

In order to verify how costly is to transpose, I've executed the code below for two conditions:

Without transposing (NCHW) = 5.775287926 s;
Transposing (NHWC) = 7.381751397 s.

from timeit import Timer

t = Timer(lambda: agent.get_game_data(state))
print (t.timeit(number = 1000000))

So transposing is responsible for 27% of the running time of the function get_game_data.

Is there a better option to create the list directly in the (10, 10, 4) format? Does my code follow best practices?


texts: Check if a given string matches a wildcard pattern

texts:
I'm trying to optimize my solution to the following question:

given a regular expression with chars and special char '*', (star which is a joker we can replace with any string), and a string, write a program which determines if the regular expression can represent that string or not.
for example: "a'*b" can represent "aaaacbbbb" , in contrast "a'*b'*c" cant represent "aaaabcccccccccb"

I solved the problem and inserted the code below, I want to optimize either space or time, and if possible to make it more readable or shorter.
#include <stdio.h>
#include <string.h>

int compareHelper(char *s, char *regex, int star);

int compareStrings(char *s, char *r);

int main()
{
    printf("%d\n", compareStrings("aaaacbbb", "a*b"));
    printf("%d\n", compareStrings("aaaabccccccccb", "a*b*c"));
    return 0;

}

//aaaaacbbb
//a*b

int compareStrings(char *s, char *r)
{
    return compareHelper(s, r, 0);

}

int compareHelper(char *s, char *regex, int star)
{
    if (*s == '\0' && *regex == '\0')
    {
        return 1;
    } else if (*regex == '*')
    {
        return compareHelper(s, regex + 1, 1); // star is seen hence will be set to true.
    } else
    {
        if (!star)
        {
            if (*s != *regex)
            { // star was not seen and they differ in char
                return 0;
            } else
            {
                return compareHelper(s + 1, regex + 1, star);
            }

        } else
        {
            while (*s && *s != *regex)
            {
                s++;
            }
            if (*s == '\0') return 0;
            else
            {
                return compareHelper(s + 1, regex + 1, 0) | compareHelper(s + 1, regex, 1);
            }
        }
    }
}


texts:
Okay, I'm under the impression that my current jQuery can be simplified (don't worry! It's short!) and I'm curious to know how this can be achieved. I think a solution to this will help produce a lot less code.

I currently have a list menu set up, with class names referring to their titles (HTML below) and if you click a list item, the menu item slides out and it's relevant content fades in. If you click the main heading again, the content fades out and the menu item slides back in.

Here's an example of my HTML

Corporate

Commercial

Construction

Corporate

Lorem ipsum lorem ipsum lorem ipsum

Commercial

Lorem ipsum lorem ipsum lorem ipsum

Here's some example JS:

jQuery('.wwd-choices-container ul.wwd-filters li a.corporate').click(function () {
    jQuery('.wwd-content-container .wwd-content-each').fadeOut();
    jQuery('.wwd-content-container .wwd-content-each.corporate').fadeIn();
});

My problem is that I don't want to have to repeat the jQuery code for each list item and it's content (e.g. li a.corporate, li a.commercial, li a.li a.corporate). As the class names for both the list item anchor and each content, is there an easy way to simplify this?

Everything is built via a CMS, so new sections and menu items would be added as time goes on so it has to remain as dynamic as possible. I'm thinking some form of array would work... and if it matches each other then it connections.


texts: Making an email text-parser generic using PredicateBuilder

texts:
I have some code that reads an email from a text file, parses the text, removes some lines (the 'cc' and 'to' lines) and then finds the line numbers of various phrases (e.g. "Regards", "Thanks") and then removes all the text for the lines after the first phrase found.

It works fine, but is not generic enough as I will have a variable number of phrases to look for to remove text. I want to use PredicateBuilder to add the OR conditions but I am not sure of the syntax to use.

I have attached a cut down version of the code below. The part with 'regards', 'thanks', 'please do not forward' is that part I want to use PredicateBuilder on.

foreach (List<string> list in groups)
{
    IEnumerable<string> lines3 = list.Where(line => !line.StartsWith("Cc:", StringComparison.OrdinalIgnoreCase));
    lines3 = lines3.Where(line => !line.StartsWith("To:", StringComparison.OrdinalIgnoreCase));

    var result = lines3.Select((r, i) => new { line = r, index = i })
                    .Where(r =>
                        r.line.StartsWith("Regards", StringComparison.OrdinalIgnoreCase)
                        || r.line.StartsWith("Thanks", StringComparison.OrdinalIgnoreCase)
                        || r.line.ToLower().Contains("please do not forward")
                        ))
                        .Select(r => new { LineNo = r.index }).OrderBy(r => r.LineNo);

    foreach (var item in result)
    {
        lineNumber = item.LineNo;
        if (lineNumber > 0)
            emailText += String.Join(System.Environment.NewLine, lines3.Take(lineNumber - 1));
        else
            emailText += String.Join(System.Environment.NewLine, lines3);
        break;
    }
}


texts: Writing out names of files on local C drive to a text document

texts:
This program writes out all the files in the current directory level to a text file, outputs an array of sub-directories at the current level, then repeats this process until there are no more sub-directories to search.  The code below take 50 seconds to run.

I was hoping I could get any pointers on the code in general (I'm very new to C#) and also any suggestions for improving the runtime.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ComputerFileOutput
{
    class Program
    {
        // Prints a string array of files located in specified path
        static void filesArray(string path)
        {
                string[] array = Directory.GetFiles(path);
                addFilesToTextFile(array);
        }

        //Appends files to .txt document
        static void addFilesToTextFile(string[] fileArray)
        {
            //Append fileArray to current .txt document
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\ComputerFiles.txt", true))
            {
                for (int i = 0; i < fileArray.Length; ++i)
                {
                    file.WriteLine(fileArray[i]);
                }
            }
        }

        //Returns a string array of directories in a specified path
        static string[] getDirectories(string path)
        {
            return (Directory.GetDirectories(path));
        }

        static void Main(string[] args)
        {
            DateTime t1 = DateTime.Now;
            string[] startUp = { "------LIST OF ALL COMPUTER FILES------" };
            System.IO.File.WriteAllLines(@"C:\ComputerFiles.txt", startUp);

            //Get files in c directory; append to .txt file
            filesArray("C:\\");

            //Get array of primary directories in C drive
            string[] directoryArray = getDirectories("C:\\");

            //initialize subdirectory search
            bool moreDirectories = true;

            //Go through each directory
            while (moreDirectories == true)
            {
                 List<string> subDirectories = new List<string>();
                foreach(string directoryName in directoryArray)
                {
                    try
                    {
                        filesArray(directoryName);

                        subDirectories.AddRange(getDirectories(directoryName));
                    }
                    catch(Exception)
                    {
                        Console.WriteLine("Unathorized to access directory: {0}", directoryName);
                    }
                }

                directoryArray = subDirectories.ToArray();

                if (directoryArray.Count() == 0)
                {
                    moreDirectories = false;
                    break;
                }
            }

            // wait for input before exiting
            DateTime t2 = DateTime.Now;
            Console.WriteLine("Total seconds = {0}", (t2 - t1).TotalSeconds);
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();

        }
    }
}


texts: Finding Possible Strings from Series of Numbers

texts:
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters is done just like they are arranged on a telephone keypad.

Looking for ways of making the code more consise and easily readable. Want to learn the C# tricks to make solving or implementing this solution easier.

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            LetterCombinations("34");
        }
        public static void LetterCombinations(String number)
        {
            string[][] StringMapping = new string[number.Length][];
            int LengthIndex = 0;

            foreach (char c in number)
            {
                switch (c)
                {
                    case '2':
                        StringMapping[LengthIndex] = new string[] {"a", "b", "c"};
                        break;
                    case '3':
                        StringMapping[LengthIndex] = new string[] {"d", "e", "f"};
                        break;
                    case '4':
                        StringMapping[LengthIndex] = new string[] {"g", "h", "i"};
                        break;
                    case '5':
                        StringMapping[LengthIndex] = new string[] {"j", "k", "l"};
                        break;
                    case '6':
                        StringMapping[LengthIndex] = new string[] {"m", "n", "o"};
                        break;
                    case '7':
                        StringMapping[LengthIndex] = new string[] {"p", "q", "r", "s"};
                        break;
                    case '8':
                        StringMapping[LengthIndex] = new string[] {"t", "u", "v"};
                        break;
                    case '9':
                        StringMapping[LengthIndex] = new string[] {"w", "x", "y", "z"};
                        break;
                }
                LengthIndex++;
            }

            int[] SizeArray = new int[StringMapping.Length];        //Keeps track of the size of each inner String array
            int[] counterArray = new int[StringMapping.Length];     //Keeps track of the index of each inner String array, which will be used to make the next combination

            //Discover the size of each inner array and populate sizeArray.
            //Also calculate the total number of combinations possible using the inner String array sizes.
            int totalCombinationCount = 1;
            for (int i = 0; i < StringMapping.Length; i++)
            {
                SizeArray[i] = StringMapping[i].Length;
                totalCombinationCount *= StringMapping[i].Length;
            }

            //Store the combinations in a List of String objects
            List<String> combinationList = new List<String>(totalCombinationCount);
            String sb = "";

            for (int countdown = totalCombinationCount; countdown > 0; countdown--)
            {
                sb = "";
                for (int i = 0; i < StringMapping.Length; i++)
                {
                    sb += StringMapping[i][counterArray[i]];
                }

                combinationList.Add(sb.ToString());

                //Now we need to increment the counterArray so that the next
                //combination is taken on the next iteration of this loop.
                for (int incIndex = StringMapping.Length - 1; incIndex >= 0; incIndex--)
                {
                    if (counterArray[incIndex] + 1 < SizeArray[incIndex])
                    {
                        ++counterArray[incIndex];
                        break;
                    }
                    counterArray[incIndex] = 0;
                }
            }

            //Output the strings in the list
            foreach (String s in combinationList)
            {
                Console.WriteLine(s);
            }
        }
    }
}


texts: Shuffling many collections by folding over a numeric range

texts:
Often, I find myself folding over a range object if I need to repeatedly transform something. This, to me though, feels like an abuse of fold since I never even use the numbers that I'm folding with.

Almost perfect example:

(ns shuffle-example
    (:import [java.util Collection Collections]))

(defn shuffle [^Collection coll rand-gen]
  (let [j-coll (java.util.ArrayList. coll)]
    (Collections/shuffle j-coll rand-gen)
    (into (empty coll) j-coll)))

(defn shuffle-many [^Collection coll n-shuffles rand-gen]
  (reduce (fn [c _] (shuffle c rand-gen))
          coll
          (range n-shuffles)))

Is this considered bad form? Is there a more idiomatic way of achieving this? I know in this case it's inefficient since it requires constant conversions between list types, but it shows my question well.
Is there a better way to deterministically shuffle a list in Clojure? Clojure comes with a shuffle function, but it doesn't accept a Random, so it's not very useful. Short of writing my own shuffle from scratch, this is the best I've been able to come up with.


texts: Thread-safe hashset that enumerates according to insertion order

texts:
According to the .NET documentation, HashSet<T> does not maintain order when enumerated so I implemented my own using F#.

Can anyone help review if this is threadsafe and correct?

open System
open System.Collections
open System.Collections.Generic

type LinkedHashSet<'a when 'a : equality> () =
    let mutable index = 0
    let indexed = SortedDictionary<int, 'a> ()
    let hash = HashSet<'a> ()
    let theLock = obj ()

    interface ICollection<'a> with
        member __.Count = lock theLock (fun () -> hash.Count)
        member __.IsReadOnly = false
        member __.Add e =
            lock theLock (fun () ->
                if hash.Add e
                then
                    indexed.[index] <- e
                    index <- index + 1
            )
        member __.Clear () =
            lock theLock (fun () ->
                index <- 0
                indexed.Clear ()
                hash.Clear ()
            )
        member __.Contains e =
            lock theLock (fun () -> hash.Contains e)
        member __.CopyTo (array, arrayIndex) =
            lock theLock (fun () ->
                let kvps =
                    Seq.toArray indexed
                let kvpLength = Array.length kvps
                for i in arrayIndex..kvpLength - 1 do
                    array.[i - arrayIndex] <- kvps.[i].Value
            )
        member __.GetEnumerator () =
            let values = lock theLock (fun () ->
                indexed
                |> Seq.map (fun kvp -> kvp.Value)
            )
            values.GetEnumerator ()
        member this.GetEnumerator () : IEnumerator =
            (this :> IEnumerable<'a>).GetEnumerator ()
            :> IEnumerator
        member __.Remove e =
            let matcher (kvp: KeyValuePair<int, 'a>) = kvp.Value = e
            lock theLock (fun () ->
                if hash.Remove e
                then
                    let kvps = indexed :> seq<KeyValuePair<int, 'a>>
                    match Seq.tryFind matcher kvps with
                    | Some x -> indexed.Remove x.Key
                    | None -> false
                else false
            )

Usage (distinctChar takes a string aabbb and returns ab):

let distinctChars (s: string) =
    s.ToCharArray ()
    |> Array.fold (fun (set: ICollection<char>) e -> set.Add e; set) (LinkedHashSet () :> ICollection<char>)
    |> Seq.toArray
    |> String


texts:
Inspired by this question I've come up with a solution of my own. The task is to find longest sequence of zeroes surrounded by ones in a binary representations of an integer (e.g. 1041 == 0b10000010001, thus the answer is 5). The task also requires the complexity of \$O(log(N))\$. As far as I understand it means that it means linear complexity in terms of digits, whose number is \$log(N)\$. Am I correct in this conclusion?

private int biggestBinaryGap(int n) {
    while (endsWithZero(n))
        n >>= 1;
    return biggestBinaryGapRec(n >> 1);
}

private int biggestBinaryGapRec(int n) {
    if (n == 0)
        return 0;

    int gap = 0;
    for (; endsWithZero(n); n >>= 1, gap++);
    return Math.max(gap, biggestBinaryGapRec(n >> 1));

}

private boolean endsWithZero(int n) {
    return n > 0 && (n & 1) == 0;
}


texts: Unique random number generation in Swift

texts:
In the process of learning Swift, I'm building a lotto numbers generator that generates a random number and appends it into an array, if the number already exists then it should re-generate a random numbers and append that one to the array.

I've come up with this. I want to be able to have a reusable class where I can decide how many numbers I want it to generate.

How would you guys solve this in a simpler way?

class EuroMillions {

    var randomNumber:Int = 0
    var numberArray = [Int]()

    func generateRandomNumber (numbers: Int, repetitions: Int) -> (Int, Int, Int) {

    for number in 1...6 {
        randomNumber = Int(arc4random_uniform(UInt32(numbers)))
        checkArray(numbers: numbers)
    }
        return (randomNumber, numbers, repetitions)

    }

func checkArray(numbers: Int) {
if numberArray.contains(randomNumber){
    //re-generate
    print("Number \(randomNumber) exists!")
    randomNumber = Int(arc4random_uniform(UInt32(numbers)))
    checkArray(numbers: numbers)

        print("Replacing it with \(randomNumber)")
    } else {
        numberArray.append(randomNumber)
    }
  }
 }
}

let firstNumbers = EuroMillions()
firstNumbers.generateRandomNumber(numbers: 50, repetitions: 6)
let finalNumbers = firstNumbers.numberArray
print(finalNumbers)


texts: C dynamic array implementation using preprocessor

texts:
I have implemented a generic dynamic array implementation using defines. As I am new to C, I am not sure whether the code has any flaws. The code is as follows,

#define INIT_CAPAC 5
#define INC_CAPAC 5
#define list(t) struct{ t* data; unsigned int count; unsigned int capac;}
#define list_init(lst)  lst.data = malloc(sizeof(*lst.data) * INIT_CAPAC); \
                        lst.count = 0; \
                        lst.capac = INIT_CAPAC;
#define list_append(lst, item) lst.data[lst.count++] = item; \
                               if(lst.count >= lst.capac) { \
                                    realloc(lst.data, sizeof(*lst.data) * (lst.capac + INC_CAPAC)); \
                               }
#define list_count(lst) lst.count
#define list_at(lst, index) lst.data[index]

typedef list(int) int_list_t;

int main() {
    int_list_t arr;
    list_init(arr);

    list_append(arr, 10);
    list_append(arr, 20);
    list_append(arr, 30);

    printf("Count: %d\n", list_count(arr));
    printf("Item at 0: %d\n", list_at(arr, 0));
    printf("Item at 1: %d\n", list_at(arr, 1));
    printf("Item at 2: %d\n", list_at(arr, 2));
}

This implementation seems better than other C solutions because,

We don't store the item size as the part of array structure. In other dynamic array implementations, the size of each element is stored in along with the element count and array capacity.
This is as intuitive as the dynamic arrays in other high level languages like C++, C#.


texts:
I need to review this code:

import java.util.HashMap;
import java.util.Map;

// REVIEW
public abstract class Digest {
    private Map<String, byte[]> cache = new HashMap<>();

    public byte[] digest(String input) {
        byte[] result = cache.get(input);
        if (result == null) {
            synchronized (cache) {
                result = cache.get(input);
                if (result == null) {
                    result = doDigest(input);
                    cache.put(input, result);
                }
            }
        }
        return result;
    }

    protected abstract byte[] doDigest(String input);
}

Should I mark cache as volatile ?
I have doubts because we use cashe.get in method body instead of direct cashe
Would it make sense to replace the map with ConcurrentHashMap?
Is there way to fix code without replacing map implementation?


texts: How can I improve this version of the board game Mastermind?

texts:
It's a standalone HTML file on GitHub

I included the CSS and JavaScript with the HTML so it would be easier to e-mail the game.

I'm most interested in comments about the solution-checking functions. This is the main function:

var evaluateSolution = function () {
//"In play" is the default state for the game.
var state = stateGame;

//Look for exact matches.
checkColorPositionMatches();

//If every peg matches exactly, the game was won
if (colorPositionMatches == codeLength) {
    state = stateWin;

} else {
    //Look for color matches among the unmatched pegs.
    checkColorMatches();
    state = stateLose;
}

//Reset the match state of each codePeg
unmatchCodePegs();

return state;
}

This one checks for exact matches.

var checkColorPositionMatches = function() {
colorPositionMatches = 0;

codePegLoop:
for (var codePegIdx=0;codePegIdx<codePegs.length;codePegIdx++) {
    var codePeg = codePegs[codePegIdx];

    //evaluate each gamePeg, stopping if we hit an exact match.
    gamePegLoop:
    for (var gamePegIdx=0;gamePegIdx<gamePegs.length;gamePegIdx++) {
        var gamePeg = gamePegs[gamePegIdx];

        if ((gamePeg.color == codePeg.color) &&
            (gamePeg.position == codePeg.position)) {

                gamePeg.colorPositionMatched = true;
                codePeg.colorPositionMatched = true;

                colorPositionMatches++;

                break gamePegLoop;
        }
    }
}
}

This one checks for color-only matches.

var checkColorMatches = function() {
colorMatches = 0;

codePegLoop:
for (var codePegIdx=0;codePegIdx<codePegs.length;codePegIdx++) {
    var codePeg = codePegs[codePegIdx];

    //evaluate each unmatched game peg, recording matches as they occur
    gamePegLoop:
    for (var gamePegIdx=0;gamePegIdx<gamePegs.length;gamePegIdx++) {
        var gamePeg = gamePegs[gamePegIdx];

        if (gamePeg.color == codePeg.color &&
           (gamePeg.colorMatched == false) &&
           (codePeg.colorMatched == false) &&
           (gamePeg.colorPositionMatched == false) &&
           (codePeg.colorPositionMatched == false)) {

            gamePeg.colorMatched=true;
            codePeg.colorMatched=true;

            colorMatches++;

            break gamePegLoop;
        }
    }
}
}


texts:
I'm working on improving my knowledge of OOP in JS. I just created this custom dropdown selector. It's working nicely, but I'm not super happy about the Filter constructor. I would like to make all that code more readable. It's basically just defining some attributes and setting some event listeners.

function Filter(element) {
  this.element = element;
  this.dropdown = this.element.querySelector('.dropdown');

  var link = this.element.querySelector('.link');
  var options = this.dropdown.querySelectorAll('a');

  var selectOption = function(event) {
    event.preventDefault();

    link.textContent = event.target.textContent;
    this.toggle();
  }

  for (var i = 0; i < options.length; i++) {
    options[i].addEventListener('click', selectOption.bind(this));
  }

  link.addEventListener('click', this.toggle.bind(this));
};

Filter.prototype.isExpanded = function() {
  return !this.dropdown.classList.contains('hidden');
}

Filter.prototype.collapse = function() {
  if (this.isExpanded()) {
    this.dropdown.classList.add('hidden');
  }
}

Filter.prototype.toggle = function() {
  if (!this.isExpanded()) {
    var filterExpandedEvent = new CustomEvent('filterExpanded', {detail: this});
    document.dispatchEvent(filterExpandedEvent);
  }

  this.dropdown.classList.toggle('hidden');
}

How you would you simplify that constructor? Any ideas?


texts:
I'm using the command pattern to enable actions in my game to be undoable. ICommand defines individual commands, ICommandHandler does the undo-redo logic and might be decorated with other handlers like logging etc.

public interface ICommand
{
    void Execute();
    void Undo();
}

public interface ICommandHandler
{
    void Execute(ICommand command);
    void Undo();
    void Redo();
}

public class CommandHandler : ICommandHandler
{
    Stack<ICommand> _undoStack = new Stack<ICommand>();
    Stack<ICommand> _redoStack = new Stack<ICommand>();

    public void Execute(ICommand command)
    {
        if (command == null)
            throw new ArgumentNullException("command");

        command.Execute();
        _undoStack.Push(command);
        _redoStack.Clear();
    }

    public void Undo()
    {
        if (_undoStack.Count > 0)
        {
            ICommand undoCommand = _undoStack.Pop();
            undoCommand.Undo();
            _redoStack.Push(undoCommand);
        }
    }

    public void Redo()
    {
        if (_redoStack.Count > 0)
        {
            ICommand redoCommand = _redoStack.Pop();
            redoCommand.Execute();
            _undoStack.Push(redoCommand);
        }
    }
}

So far I'm not having any problems. Please correct me if I'm doing anything horribly wrong, but my actual questions is: Can I safely use a struct as a concrete command object or should I use a class?

public struct MoveCameraCommand : ICommand
{
    public CameraController cameraController;
    public Vector2 moveDelta;

    public MoveCameraCommand(CameraController controller, Vector2 moveDelta)
    {
        this.cameraController = controller;
        this.moveDelta = moveDelta;
    }

    public void Execute()
    {
        cameraController.Move(moveDelta);
    }

    public void Undo()
    {
        cameraController.Move(-moveDelta);
    }
}

I've noticed that when using a regular class, I'm generating garbage each frame with my camera, because move commands are issues very often. Since the game will be running on Android tablets, I was worried and switched to the struct implementation, although I've never seen it before. Might this cause other problems? Is this bad design in general? Should I not be using the command pattern for something like a camera, that is updated each frame?


texts: Grouping consecutive numbers into ranges in Python 3.2

texts:
The following is a function that I wrote to display page numbers as they appear in books.

If you enter the list [1,2,3,6,7,10], for example, it would return:

1-3,6-7,10

This seemed like a nice example of how the dictionary data type can be used in Python.

Is there is an even more code-efficient way to do this?

def formatpagelist (numberlist):
    tempdic={}
    returnstring=''

    for number in numberlist:
        if number-1 in tempdic.keys():
            tempdic[number-1]=number
        elif number-1 in tempdic.values():
            for key in tempdic.keys():
                if number-1==tempdic[key]: foundkey=key
            tempdic[foundkey]=number
        else:
            tempdic[number]=0

    keylist=list(tempdic.keys())
    keylist.sort()

    for key in keylist:
        if tempdic[key]>0:
            returnstring+=(str(key)+'-'+str(tempdic[key])+',')
        else: returnstring+=str(key)+','

    return returnstring


texts:
I have this Java solution to LeetCode's 3Sum problem.
I would be really grateful if I could get feedback on correctness, scalability, efficiency, coding best practices, and OOP design.
I'm relatively new to Java.
class Solution
{
    public List<List<Integer>> threeSum(int[] nums)
    {
        List l1 = new ArrayList<ArrayList>();

        for (int idx = 0; idx < nums.length; idx++)
        {
            if (idx > 0 && nums[idx] == nums[idx - 1]) continue;

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

            for (int idxInner = idx + 1; idxInner < nums.length; idxInner++)
            {
                if (
                     hash.get(nums[idxInner]) != null &&
                     nums[idxInner]+hash.get(nums[idxInner]) == -1*nums[idx]
                   )
                {
                    List l2 = new ArrayList<Integer>();

                    addInList(l2, nums[idx]);
                    addInList(l2, hash.get(nums[idxInner]));
                    addInList(l2, nums[idxInner]);

                    l1.add(l2);
                }
                else
                {
                    hash.put(-1*(nums[idx] + nums[idxInner]), nums[idxInner]);
                }
            }
        }

        removeDuplicates(l1);

        return l1;
    }

    public void addInList(List<Integer> list, int num)
    {
        if (list == null) return;

        int lSize = list.size();

        if (lSize == 0)
        {
            list.add(num);
            return;
        }

        int idx = 0;
        while (idx < lSize && list.get(idx) < num)
        {
            idx++;
        }

        if (idx < lSize) list.add(idx, num);
        else list.add(num);

        return;
    }

    public void removeDuplicates(List<ArrayList<Integer>> lists)
    {
        if(lists == null) return;

        for(int outer = 0; outer < lists.size(); outer++)
        {
            for(int inner = outer + 1; inner < lists.size(); inner++)
            {

                if (areDuplicates(lists.get(outer), lists.get(inner)))
                {

                    lists.remove(inner);
                    inner--;
                }
            }
        }
    }

    public boolean areDuplicates(ArrayList<Integer> first, ArrayList<Integer> second)
    {
        if (first == null && first == second) return true;
        if (first == null || second == null) return false;

        int fSize = first.size();
        int sSize = second.size();

        if (fSize != sSize) return false;

        for(int idx = 0; idx < fSize; idx++)
        {
            if (first.get(idx) != second.get(idx)) return false;
        }

        return true;
    }
}

I get a timeout error on LeetCode if I try to run this.


texts: Clone a LinkedList with each node having a next and a random pointer

texts:
The LinkedList nodes can be 1-->2-->3-->4, where --> indicates next. For their random pointers: 1--> 2, 2--> 4 3-->2 4--1. There can be duplicate data values of the nodes. I'm looking to see if the solution can be improved upon.

class Node
{
int data;//Node data
Node next, random;//Next and random reference

//Node constructor
public Node(int data)
{
    this.data = data;
    this.next = this.random = null;
}
}

// linked list class
class LinkedList
{
Node head;//Linked list head reference

// Linked list constructor
public LinkedList(Node head)
{
    this.head = head;
}

// push method to put data always at the head
// in the linked list.
public void push(int data)
{
    Node node = new Node(data);
    node.next = this.head;
    this.head = node;
}

// Method to print the list.
void print()
{
    Node temp = head;
    while (temp != null)
    {
        Node random = temp.random;
        int randomData = (random != null)? random.data: -1;
        System.out.println("Data = " + temp.data +
                ", Random data = "+ randomData);
        temp = temp.next;
    }
    }

// Actual clone method which returns head
// reference of cloned linked list.
public LinkedList clone()
{
    // Initialize two references, one with original
    // list's head.
    Node origCurr = this.head, cloneCurr = null;

    // Hash map which contains node to node mapping of
    // original and clone linked list.
    Map<Node, Node> map = new HashMap<Node, Node>();

    // Traverse the original list to help copy into the HashMap
    while (origCurr != null) {
        cloneCurr = new Node(origCurr.data);
        cloneCurr.next = origCurr.next;
        cloneCurr.random = origCurr.random;
        map.put(origCurr, cloneCurr);
        origCurr = origCurr.next;
    }

    //return the head reference of the clone list.
    return new LinkedList(map.get(this.head));
}
}

public class Clone
{

public static void main(String[] args)
{
    // Pushing data in the linked list.
    LinkedList list = new LinkedList(new Node(5));
    list.push(4);
    list.push(3);
    list.push(2);
    list.push(1);

    list.head.random = list.head.next.next;
    list.head.next.random =
            list.head.next.next.next;
    list.head.next.next.random =
            list.head.next.next.next.next;
    list.head.next.next.next.random =
            list.head.next.next.next.next.next;
    list.head.next.next.next.next.random =
            list.head.next;

    // Making a clone of the original linked list.
    LinkedList clone = list.clone();

    // Print the original and cloned linked list.
    System.out.println("Original linked list");
    list.print();
    System.out.println("\nCloned linked list");
    clone.print();
}
}


texts: Restart network-manager service if connection down on wake shell script

texts:
I use Ubuntu (Trusty and Xenial) and usually put my computer in sleep mode rather than power it down.  A common problem is that upon wake the network is down so one has to restart the network-manager service.  E.g.

sudo service network-manager restart

I am tired of doing this so I have hacked the following together:

#!/bin/sh

# should live in /lib/systemd/system-sleep/...
# sudo mv restart-network-on-wake.sh /lib/systemd/system-sleep/
# sudo chmod a+x /lib/systemd/system-sleep/restart-network-on-wake.sh

case $1/$2 in
    pre/*)
        echo "Going to $2..."
        exit 0
        ;;
    post/*)
        echo "Waking up from $2..."
        if ! ping -q -c 1 -W 1 8.8.8.8 > /dev/null; then
            echo "IPv4 is down, restarting network-manager"
            service network-manager restart
        fi
        ;;
esac

I am a novice at shell scripting I guess and don't have a strong understanding of Linux internals. Do you have any thoughts?


texts: Is this use of ConcurrentDictionary truly thread safe?

texts:
I'm working on some teaching examples showing the perils of accessing the Dictionary class concurrently.  In the code below each function is designed to do a word count across a number of files.  (This isn't the best way of doing the count but it's there to make a point about Dictionary.)

The first example, using a Dictionary and no parallelism works fine.

The second example, using a Dictionary and Array.parallel can fail with an exception and also produces different results each time.  This is deliberate and is there to make the point.

The final example uses ConcurrentDictionary and seems to me to work fine.  My concern is: given this uses a delegate to do the count addition, is this version genuinely thread safe?

// Simple version:
let WordCount dirPath wildCard =

   let wordCounts = Dictionary<string, int>()

   let ProcessFile fileName =
      let text = File.ReadAllText(fileName)

      text.Split([|'.'; ' '; '\r'|], StringSplitOptions.RemoveEmptyEntries)
      |> Array.map (fun w -> w.Trim())
      |> Array.filter (fun w -> w.Length > 2)
      |> Array.iter (fun w ->
         let ok, count = wordCounts.TryGetValue(w)
         if ok then
            wordCounts.[w] <- count+1
         else
            wordCounts.[w] <- 1)

   Directory.EnumerateFiles(dirPath, wildCard)
   |> Seq.iter ProcessFile

   wordCounts
   // |> Seq.sumBy (fun kv -> kv.Value)
   |> Seq.sortBy (fun kv -> -kv.Value)

// Naive concurrent version:
let WordCount2 dirPath wildCard =

   let wordCounts = Dictionary<string, int>()

   let ProcessFile fileName =
      let text = File.ReadAllText(fileName)

      text.Split([|'.'; ' '; '\r'|], StringSplitOptions.RemoveEmptyEntries)
      |> Array.map (fun w -> w.Trim())
      |> Array.filter (fun w -> w.Length > 2)
      |> Array.iter (fun w ->
         let ok, count = wordCounts.TryGetValue(w)
         if ok then
            wordCounts.[w] <- count+1
         else
            wordCounts.[w] <- 1)

   Directory.EnumerateFiles(dirPath, wildCard)
   |> Array.ofSeq
   |> Array.Parallel.iter ProcessFile

   wordCounts
   |> Seq.sumBy (fun kv -> kv.Value)
   // |> Seq.sortBy (fun kv -> -kv.Value)

// Safe concurrent version:
let WordCount3 dirPath wildCard =

   let wordCounts = ConcurrentDictionary<string, int>()

   let ProcessFile fileName =
      let text = File.ReadAllText(fileName)

      text.Split([|'.'; ' '; '\r'|], StringSplitOptions.RemoveEmptyEntries)
      |> Array.map (fun w -> w.Trim())
      |> Array.filter (fun w -> w.Length > 2)
      |> Array.iter (fun w -> wordCounts.AddOrUpdate(w, 1, (fun _ count -> count+1 )) |> ignore)

   Directory.EnumerateFiles(dirPath, wildCard)
   |> Array.ofSeq
   |> Array.Parallel.iter ProcessFile

   wordCounts
   |> Seq.sumBy (fun kv -> kv.Value)
   // |> Seq.sortBy (fun kv -> -kv.Value)


texts:
From my repository.

This is my first time implementing a Fibonacci Heap, and since it's pretty complicated (at least to me), I would like to check if it is all correct.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Objects;

public class FibonacciHeap {

  private final HashMap<Integer, Node> references;
  private Node min;
  public FibonacciHeap() {
    references = new HashMap<>();
  }

  public void insert(int val) {
    Node newNode = new Node(val);
    references.put(val, newNode);

    if (min == null) {
      min = newNode;
      min.left = min;
      min.right = min;
    } else {
      min.insert(newNode);
      if (newNode.val < min.val) {
        min = newNode;
      }
    }
  }

  public int extractMin() {
    int toReturn = min.val;
    references.remove(toReturn);

    if (min.left == min && min.child == null) {
      min = null;
    } else {
      min.safeUnlink();
      min = min.left;
      consolidate();
    }

    return toReturn;
  }

  public void delete(int val) {
    Node nodeForm = references.get(val);
    nodeForm.val = Integer.MIN_VALUE;
    min = nodeForm;
    extractMin();
  }

  public boolean isEmpty() {
    return min == null;
  }

  private void consolidate() {
    Node[] degrees = new Node[45];
    Node dummy = min;
    HashSet<Node> visited = new HashSet<>();

    do {
      if (visited.contains(dummy)) {
        break;
      }

      if (dummy.val < min.val) {
        min = dummy;
      }

      while (degrees[dummy.degree] != null) {
        Node other = degrees[dummy.degree];

        if (other.val < dummy.val) {
          Node temp = other;
          other = dummy;
          dummy = temp;
        }

        dummy.link(other);
        degrees[dummy.degree - 1] = null;
      }

      degrees[dummy.degree] = dummy;
      visited.add(dummy);
      dummy = dummy.right;
    } while (dummy != min);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();

    if (min != null) {
      Node dummy = min;

      do {
        sb.append(dummy.val).append(" ");
        dummy = dummy.right;
      } while (dummy != min);
    }

    return sb.toString();
  }

  private static class Node {

    public int val;
    public Node left, right, child;
    public int degree;
    public boolean mark;

    public Node(int _val) {
      val = _val;
    }

    public void insert(Node other) {
      if (left == this) {
        left = other;
        right = other;
        left.right = this;
        left.left = this;
      } else {
        Node temp = left;
        left = other;
        left.right = this;
        left.left = temp;
        temp.right = left;
      }
    }

    public void unlink() {
      left.right = right;
      right.left = left;
    }

    public void safeUnlink() {
      saveChildren();
      unlink();
    }

    public void link(Node other) {
      other.unlink();
      if (child == null) {
        child = new Node(other.val);
        child.left = child;
        child.right = child;
      } else {
        child.insert(other);
      }

      other.mark = false;
      degree++;
    }

    public void saveChildren() {
      if (child != null) {
        Node dummy = child;

        do {
          Node tempNext = dummy.right;
          insert(dummy);
          dummy = tempNext;
        } while (dummy != child);

        child = null;
      }
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      Node node = (Node) o;
      return val == node.val
          && degree == node.degree
          && mark == node.mark
          && Objects.equals(left, node.left)
          && Objects.equals(right, node.right)
          && Objects.equals(child, node.child);
    }

    @Override
    public int hashCode() {
      return Objects.hash(val);
    }

    @Override
    public String toString() {
      return val + "";
    }
  }
}


texts: Unix shell function for adding directories to PATH

texts:
Adding a directory to the PATH in Unix/Linux is a very common task.  However, what if the directory is already in the path?  My goal is to write a shell function (preferably portable) that will add a directory to the front or back of the PATH variable, but only if it's not already there.

Here's what I have (syntax is in zsh / bash):

#-------
# DESC: Adds a directory to the PATH if it's not already in the PATH
# ARGS:
#  1 - The directory to add
#  2 - Which end of PATH to add to.  Use "front" to prepend.
#-------
add2path() {
  if ! echo $PATH | egrep "(^|:)$1(:|\$)" > /dev/null ; then
    if [[ $2 = "front" ]]; then
      PATH="$1:$PATH"
    else
      PATH="$PATH:$1"
    fi
    export PATH
  fi
}

This function works.  I have tested it on Ubuntu, Solaris, and FreeBSD.  And I have tested it in bash, zsh, and ksh.  But I want to make sure that it is as portable (first and foremost), readable, and as efficient as possible.

Remarks

I know that the =~ operator would be more readable, but I had trouble with it not working on certain OSes, particularly Solaris.
I know I could (and arguably should) use grep -Fq instead of egrep routing to /dev/null, but again this didn't work on certain OSes (Solaris)

Ironically, the way to fix this on Solaris is to add /usr/xpg4/bin to the PATH.  :)


texts:
Hey guys I am trying to improve my Python Programming skills, I tried to build a hangman code.
I know it is not perfect but I works. I am looking for some hints or advice to improve this script.

    txt_file = open('dictionnary.txt','r') # Open the file with read option

    words = txt_file.readlines() # Read all the lines

    words =[word.replace('\n','') for word in words] # Remove '\n' and words is now a list

    import random

    random_number = random.randint(11,len(words)-1) # Choose a random number between 11 (to avoid words like 'aa', 'aaargh',etc) and the lenght of words

    word_to_guess = words[random_number]

    user_guesses=['#' for i in word_to_guess]

# Function to check if the input letter is in the world to guess if yes replace '#' with the input letter

def check_index_and_replace(letter):
    letter_index=[i[0] for i in enumerate(word_to_guess) if i[1]==letter]
    for i in letter_index:
        user_guesses[i] = user_guesses[i].replace('#',letter)
    return(user_guesses)

# Function to tell how many letter to guess left

def letterleft(user_guesses):
    return(user_guesses.count('#'))

# My core code (input and prints)

tries = int(input('How many tries you want ? '))
test = 0
while test < tries+1:
    letter = input('Try a letter ')
    print(check_index_and_replace(letter))
    print(letterleft(user_guesses),'letter left to guess !')
    test=test+1
print(word_to_guess)


texts:
I am trying to simplify the amount of code required here using arrays, I feel like my foreach loop is still excessively long. Any advice would be appreciated.

$date_list = Array(
Array( 'age', "$birthday", 'now' ),
Array( 'membership', "$datejoined", 'now' ),
Array( 'promoted', "$lastpromo", 'now' ),
);

foreach ( $date_list as $date_set ) {
$var = $date_set[0];
$start = $date_set[1];
$end  = $date_set[2];
$datetime1 = date_create($start);
$datetime2 = date_create($end);
$interval = date_diff($datetime1, $datetime2);
if ( substr_count( $var, 'age' ) > 0 ){
    $age = $interval->format('%y');
}
elseif ( substr_count( $var, 'membership' ) > 0 ){
    $years = $interval->format('%y');
    $months = $interval->format('%m');
    $membership = floor(($years*12)+$months);
    if($membership > 1){
        $suffix = 'Months';
    }
    elseif($membership == 1){
        $suffix = 'Month';
    }
    else{
        $membership = "< 1";
        $suffix = 'Month';
    }
}
elseif ( substr_count( $var, 'promoted' ) > 0 ){
    $years = $interval->format('%y');
    $months = $interval->format('%m');
    $test = $interval->format('%a');
    $promoted = floor(($years*12)+$months);
    if($promoted > 1){
        $suffix = 'Months ago';
    }
    elseif($promoted == 1){
        $suffix = 'Month ago';
    }
    else{
        $promoted = "< 1";
        $suffix = 'ago';
    }
}

}


texts: Monkey-patching Jasmine's it() function to log errors

texts:
The introduction of async native support in Jasmine doesn't log the errors (i.e., specific line number where the error occurs) to the console. So, to get around this behavior and to make the errors appears in the console, I came up with this following solution to patch Jasmine.

I have the following function which I implemented to monkey patch the Jasmine. And I would like to reuse the same function for other functions like beforeEach, beforeAll and so on..

     function patchJasmineForAsyncError(method: string) {
        let oldFn = window[method];
        if (method === 'it' || method === 'fit') {
            window[method] = function (desc: string, fn: Function) {
                    oldFn(description, (done) => {
                    let p = fn();
                    if (p instanceof Promise) {
                        p.then(() => done()).catch(e => {
                            console.error(e);
                            done.fail(e);
                        });
                    }
                    });
            }
        } else {
            window[method] = function (axn: Function) {
                oldFn((done) => {
                    let p = axn();
                    if (p instanceof Promise) {
                        p.then(() => done()).catch(e => {
                            console.error(e);
                            done.fail(e);
                        });
                    }
                });
            }
        }
}

As you can see the second part of the function (the else block) has quite a lot of duplication. I was wondering if there is an elegant way to minimize this and implement the function.

Note: the it and fit functions have two arguments desc and fn.. but the beforeAll, beforeEach.. etc have only one argument axn.


texts: Going from Spaghetti PHP OOP to SOLID OOP

texts:
I am beyond stuck in a half way point between PHP structural and OOP, but I can never achieve proper SOLID patterns despite reading DI, IOC, and reading about the interfaces.

Rather than to read logical examples (i.e. a storage class that takes a book class and you typecast an interface etc...).  I want to know how I can take my brain off thinking I got SOLID down but I actually didn't. There is talk about trying to refactor a small chunk but then that small chunk isn't SOLID enough.

Here are the code segments - my thought and goals are after:

class DataID
{
    protected $_id_array;
    protected $_storage;

    public function __construct(StorageInterface $db_conn, $tables = array())
    {
       $this->_storage = $db_conn;
        foreach ($tables as $table) {
            $sql = "SELECT `id` as `id`, `name` as `value` FROM $table ORDER BY `value` ASC";
            $result = $this->_storage->read($sql);
            if (!empty($result)) {
                foreach ($result as $row) {
                    $this->_id_array[$table][$row['value']] = $row['id'];
                }
            }
        }
    }
    public function getID($table, $value)
    {
        if (!empty($this->_id_array[$table])) {
            if (isset($this->_id_array[$value])) {
                return $this->_id_array[$table][$value];
            }
        }

        return null;
    }
}

Goal:

I have tables that has ID vs Value data. I'm going to use this class to run through data (value) and I want to retrieve the ID of it. Best way to avoid too many DB request is to put it inside an array of [value] = ID I believe and then check corresponding index as value and fetch ID.

Storage is an container that goes into the DB via SQL and go fetch me all the data over. This way if the method of the storage changes (Mongo, SQL, pod, MySQLi) I can change how I treat my read.

Tables is a list of known tables in the DB that I need that Data from. That list will be from an array config file that shall be loaded in a main.

Issues:

I have a strong feeling that I can make this better but I don't know how - because to me a constructor initialize things and well I'm going into the DB to initialize my array but for some reason i feel that SOLID fails for me here.
If I have tables that have too many values (i.e. let's say if a table look up is more than 50) I want to hit the DB and not store it inside an array.

If that's the case, I'll have to make queries inside getID to use storage to go fetch it.  How do I maintain SOLID while adding that extra logic?


texts: Is it worthy to create a wrapper function like this?

texts:
I have a few Python codes like this:

 workflow = []
 conf = {}
 result = []
 prepare_A(workflow, conf)
 prepare_B(workflow, conf)
 prepare_C(workflow, conf)
 result.append(prepare_D_result(workflow, conf))
 prepare_E(workflow, conf)
 #.... about 100 prepare functions has the same parameter list

I was wondering that whether I need to rewrite like this:

 workflow = []
 conf = {}
 result = []
 def prepare_wrapper(prepare_function):
         return prepare_function(workflow, conf)

 prepare_wrapper(prepare_A)
 prepare_wrapper(prepare_B)
 prepare_wrapper(prepare_C)
 result.append(prepare_wrapper(prepare_D_result))
 prepare_wrapper(prepare_E)
 #.... about 100 prepare functions has the same parameter list

Though it might reduce the burden of passing 2 parameters into the function each time, it might bring difficulties for those who read codes. Is there better ways to ameliorate the code quality in such situation?


texts: Make huge view in C# readable and maintanable

texts:
I have an application that is using MVC5 with C# and Razor Engine.  This view displays a huge table:

            Actions
            Order Status
            Order Details
            Order Date
            Expected Delivery Date
            Ordered By
            Employee ID
            Employee Status
            Employee Name
            Employee Type
            Scope
            Delivery Address
            Comment

Now, the problem is that everything is in one huge file. As you can guess, this file is a nightmare to update and maintain.

I am familiar with the C# region directive, but I can't find anything similar for Views. I also know about partial views, but I have the strong impression from discussions in Stack Overflow that these should only be used when I have a piece of code in a View that is re-usable, which is not the case.

What is the best way to deal with Views this large?


texts: Solving 'decent numbers' that follow specific division rules

texts:
HackerRank Problem Statement

I have to find the largest 'decent number' having N digits. A decent number has the following properties:

3, 5, or both as its digits. No other digit is allowed.
Number of times 3 appears is divisible by 5.
Number of times 5 appears is divisible by 3.

My code works perfect, but, I am afraid it is far from efficient:

Input:

4 #number of test cases, i.e., the following 4 inputs
1
3
5
11

Output:

-1
555
33333
55555533333

My version of the solution:

T = int(input()) #number of test cases

def computePair(N):
    multiplesOf3 = [i for i in range(N+1) if i%3 == 0]
    if multiplesOf3 != [0]: #reversing a [0] results in a 'NoneType'
        multiplesOf3.reverse()
    multiplesOf5 = [i for i in range(N+1) if i%5 == 0]

    for i in multiplesOf3:
        for j in multiplesOf5:
            if (i+j) == N:
                return (i, j)
    return -1

for testCase in range(T):
    N = int(input()) #test case
    result = computePair(N)
    if result == -1:
        print(result) #If no such combination exists return '-1'
    else:
        print('5' * (result[0]) + '3' * (result[1]))

I assume my code has a time-complexity of \$O(n^2)\$; because of the two for loops. I want this to be more efficient in the order of \$O(n)\$ - linear.

This is a very generic question: also, do you have any resources to time-complexity best practices? I suck at it.


texts:
I am using Socket.IO-java on the desktop application to handle realtime communication with the server. I was wondering if I could get some feed back on the setup as I am not happy with how it's done, but I can't come up with a better solution.

There exists a Main thread (from main(..) method) that launches a Daemon thread (DT). Daemon thread calls a method that creates SocketIO object and installs its callbacks. I show one here for brevity.

public void websocketConnectionSetup(...) {
        Executor executor = Executors.newSingleThreadExecutor();

        Socket socketIOSocket = null;
        try {
            IO.Options options = new IO.Options();
            socketIOSocket = IO.socket("hostname", options);
        } catch (URISyntaxException e) {
            Logger.error(e);
        }
        socketIOSocket.on(
                WSEvents.ON_DEMAND_SYNC, // WSEvents class just contains static strings
                new WSHandler<>(WSEvents.ON_DEMAND_SYNC, socketIOSocket, executor));

        socketIOSocket.connect();
}

WSHandler implements Emitter.Listener which is required by Socket.IO to create a callback. WSHandler has a single method, which is basically a big if statement that switches on websocket events:

@Override
public void call(final Object... objects) {
    if (event.equals(WSEvents.PING)) {
        executor.execute(new WSSimpleWorker<>(event, socketIOSocket, null, getParameterClass()));
    ...
    } else if (event.equals(WSEvents.ON_DEMAND_SYNC)) {
        executor.execute(new WSWorker(args));
    }
    ...
}

As you can see I create a thread to handle the event. In the case of the on-demand sync, I create a task that pushes some data back to the server.

This is the question: I want to make sure that there is only one Executor for these websocket workers. That's why I create it in the Daemon thread and then pass it down to WSWorker threads. However, that seems wrong because I pass the same object to different threads. I have other shared objects (for db connection and login config), and I use a synchronized Singleton to make sure they are thread safe. However, I don't understand how to ensure that I have one Executor and that's its thread safe. Or does the framework ensure it?

I also need to be able to shutdown this Executor when the Daemon thread exits, so I think I need to make this object accessible from anywhere in the application. The only solution I can think of is to wrap it into a singleton class to ensure that only one Executor is created. But in that case I am solving all synchronization problems with singletons..


texts:
I threw together this Python function to check if a User has a certain Permission.

First of all, Permissions have this kind of format: category1.category2.some.task

and can also include wildcards like this: app.view.*

All the permissions a User has are stored in a list, so for example:

["app.cat1.*", "app.cat2.do.something", "app.cat2.cat3.*"]

You can then use the function below to check if a User has a certain Permission in his list:

def check_permission(needed_permission, permissions):
    #normalise needed permissions ending with a "." dot, convert filter to list again!
    needed_permissions_list = list(filter(None, needed_permission.split(".")))
    #loop over the permissions the user has, check if each matches the needed one until we find one and return True
    for permission in permissions:
        #permission is the permission the user already has and we are working on
        #permission_list is the list representation of the permission mentioned above
        permission_list = permission.split(".")
        #if the needed permission is exactly the same as the one we are working on, return True. E.g. needed: app.*, in list: app.*
        if permission_list == needed_permissions_list:
            return True
        #needed permission nearly matches, not the same because of wildcard. Return True
        if permission_list[-1] == "*" and (permission_list[:-1] == needed_permissions_list):
            return True
        #zip the to lists together to iterate
        zipped = zip(permission_list, needed_permissions_list)
        #iterate over the two lists simultaneousley
        for item, item2 in zipped:
            #whoa, an item doesn't match, time for further checks
            if item != item2:
                if item == "*":
                    #it's not matching because it's a wildcard, so return True
                    return True
                else:
                    #it's not a wildcard, so it's definetely not the permission we are looking for
                    break
                return True
    #nothing matched, return False. Permission we're looking for not in the list
    return False

permissions = ["app.cat1.*", "app.cat2.do.something", "app.cat2.cat3.*"]
assert check_permission("app.cat2.do.something", permissions) == True
assert check_permission("app.cat2.do.something.special", permissions) == False
assert check_permission("app.cat1.some.task", permissions) == True
assert check_permission("app.cat2.cat4", permissions) == False
assert check_permission("app.cat2.cat3.do.something.special", permissions) == True
assert check_permission("something.completely.different", permissions) == False


texts: Interpret English as Math and Perform Operations

texts:
The idea is to accept an English string of math operations and evaluate it from left to right.

Regarding Order of Operations: when speaking operations aloud, it is often with implied parenthesis that denotes a left-to-right chain.

For example:

  4 plus 3 times 2 squared
   === (((4 plus 3) times 2) squared)

The rhythm which it was spoken dictates whether or not to square the 2 before multiplying — but in this case the goal is to go strictly left-to-right.

The starting point to my review here was my answer to a StackOverflow question which was direct, correct, but unsatisfying in design and style.

import math
import re
import operator

# try "3 add 4 times 5"
inputs = input(">").lower()

# Using RE to find all numbers in string.
numInString = [int(d) for d in re.findall(r'-?\d+', inputs)]
inputs = inputs.split()

print('Numbers found: ', numInString)
print('Inputs found: ', inputs)

# Define all of the operators
def multiplication():
    multAns = operator.mul(numInString.pop(0) , numInString.pop(0))
    numInString.insert(0, multAns)
    print(multAns)

def division():
    divAns = operator.truediv(numInString.pop(0) , numInString.pop(0))
    numInString.insert(0, divAns)
    print(divAns)

def addition():
    addAns = operator.add(numInString.pop(0) , numInString.pop(0))
    numInString.insert(0, addAns)
    print(addAns)

def subtraction():
    subAns = operator.sub(numInString.pop(0) , numInString.pop(0))
    numInString.insert(0, subAns)
    print(subAns)

def squareRoot():
    SqrtAns = math.sqrt(numInString.pop(0))
    numInString.insert(0, SqrtAns)
    print(SqrtAns)

def squared():
    SquareAns = math.pow(numInString.pop(0), 2)
    numInString.insert(0, SquareAns)
    print(SquareAns)

def cubed():
    CubedAns = math.pow(numInString.pop(0), 3)
    numInString.insert(0, CubedAns)
    print(CubedAns)

def power():
    PowerAns = math.pow(numInString.pop(0), numInString[1])
    numInString.insert(0, PowerAns)
    print(PowerAns)

# Dictionary mapping search words to operator function
Operation = {
    'multiply': multiplication,
    'times' : multiplication,
    'multiplied': multiplication,
    'divide': division,
    'divided': division,
    'into': division,
    'add': addition,
    'sum': addition,
    'added': addition,
    'subtract': subtraction,
    'minus': subtraction,
    'take': subtraction,
    'subtracted': subtraction,
    }

for words in inputs:
    if words in Operation:
        print(Operation[words]())

How should I be naming variables? Are Operation and numInString good names?
Should I print the result of a function operator?
Should I be storing the numbers in a global list (e.g. numInString) instead of passing them to operator functions?
Should I print errors like this?:

print('NO OPERATION GIVEN')

Is it okay to assume all numbers will be of type int?
Should I leave unguarded script code such as input('>')?


texts: SQL query to order by the difference between FIRST and BEST scores

texts:
Can anyone help me optimise this query?  I have the following table:

cdu_user_progress:
--------------------------------------------------------------
|id    |uid     |lesson_id    |game_id    |date    |score    |
--------------------------------------------------------------

For each user, I'm trying to obtain the difference between the best and first scores for a particular game_id for a particular lesson_id, and order the results by that difference ('progress' in my query):

SELECT ms.uid AS id, ms.max_score - fs.first_score AS progress
FROM (
    SELECT up.uid, MAX(CASE WHEN game_id = 3 THEN score ELSE NULL END) AS max_score
    FROM cdu_user_progress up
    WHERE  (up.uid IN  ('1671', '1672', '1673', '1674', '1675', '1676', '1679', '1716', '1725',         '1726', '1937', '1964', '1996', '2062', '2065', '2066', '2085', '2086')) AND (up.lesson_id = '65') AND (up.score > '-1')
GROUP BY up.uid
) ms
LEFT JOIN (
    SELECT up.uid, up.score AS first_score
    FROM cdu_user_progress up
    INNER JOIN (
        SELECT up.uid, MIN(CASE WHEN game_id = 3 THEN date ELSE NULL END) AS first_date
        FROM cdu_user_progress up
        WHERE  (up.uid IN  ('1671', '1672', '1673', '1674', '1675', '1676', '1679', '1716', '1725', '1726', '1937', '1964', '1996', '2062', '2065', '2066', '2085', '2086')) AND (up.lesson_id = '65') AND (up.score > '-1')
        GROUP BY up.uid
    ) fd ON fd.uid = up.uid AND fd.first_date = up.date
) fs ON fs.uid = ms.uid
ORDER BY progress DESC

Any help would be most appreciated!


texts: Convert and print Celsius to Fahrenheit from certain range of values

texts:
I just started learning C, and got to the "for loops"—where an exercise is given to convert Celsius to Fahrenheit ( from -50 to 1000 with a step of 20 ), and print the values. I decided to play with it by adding different steps when certain values are reached.

I do have some programming experience ( Python/Java/JavaScript ) but it's all in beginner level scope.My concern is that i could have used one loop and check each (bp) with a condition... or maybe use module operator to determine a step change ... or something third.
I need an expert opinion on the code i wrote.

Is this a good approach for this particular problem?

Is this considered bad or good practice?If bad what would you change and why?

Would you (assuming as an expert) go with this or other way ? If other, why ?

#include <stdio.h>

int main(){

    float fahr, cels, step, min, max;

    float count[4] = {10,1,10,100};
    float bp[4] = {-50,-10, 10, 100};

    size_t bp_size, st_size;
    int c,c2;

    bp_size = *(&bp + 1) - bp;
    st_size = *(&count + 1) - count;

    min = -50; max = 1000;
    step = count[0];
    c2 = 0;

    for (cels = min; cels <= max; cels += step){

        fahr = cels * 1.8 + 32;
        printf("%4.0f C\t= %6.1f F\n", cels, fahr);

        for(c = 0; c < bp_size; c++){
            if (cels == bp[c]){
                if (c2 == st_size){ c2 = 0;}
                step = count[c2];
                c2++;
            }
        }
    }
}


texts:
What's a better and more elegant way of writing this:

$('#footer form').submit(function(event) {
    event.preventDefault(event);
    $('#footer form .preload').spin(opts);
    $.post('contact.php', $(this).serialize(), function(response) {
        $('#footer form .preload div').remove();
        $('#footer form h5').remove();
        $('#footer form .error').html('');
        if (response == 1) {
            $('#footer form h3').after('
Your message has been sent!
');
            $('#footer form input[type=submit]').fadeOut();
        } else if (response == 0) {
            $('#footer form h3').after('
A problem occured. Please try again later.
');
            $('#footer form input[type=submit]').fadeOut();
        } else {
            var errors = $.parseJSON(response);
            $('label[for=name] .error').html(errors.name);
            $('label[for=email] .error').html(errors.email);
            $('label[for=message] .error').html(errors.message);
        }
    });
});


texts:
EDIT:
I've created a repo and uploaded it to Maven (still in dev though).
Any suggestion or pull request is more than appreciated. :)

https://github.com/enrichman/vigenere

I had the need to write a simple encryption algorithm (no security needs, it just needs to look a bit random) and I thought to add a bit of random things to a Vigenere cipher.

The idea was simply to create a random key of a fixed length, use it as key in the Vigenere, then append it to the encrypted text. Then encrypt again the whole text with the secret key.

In this way the same text, encrypted with the same key looks more random.

Any suggestion about the algorithm or implementation?

A simple run:

1)
Plaintext: HELLO
Encrypted: FF22LDAQ
Decrypted: HELLO

2)
Plaintext: HELLO
Encrypted: 7MYUS92X
Decrypted: HELLO

Maybe the last thing to add is a way to add the initial size to the encrypted text, but I don't want it to be fixed in some way.

public class Crypto {

    private static Random rand = new Random();
    private static char[] alphabet = new char[] {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };
    private static String KEY = "DSNJKDNFJKSNDJKNOCNSJCKNK";

    public static void main(String[] args) {

        int size = 3;
        String plaintext = "HELLO";

        System.out.println("Plaintext: " + plaintext);

        String enc = encrypt(plaintext, size);
        System.out.println("Encrypted: "+enc);

        String dec = decrypt(enc, size);
        System.out.println("Decrypted: "+dec);
    }

    public static String encrypt(String plaintext, int size) {

        StringBuilder sb = new StringBuilder();
        for(int i=0; i<size; i++) {
            sb.append(alphabet[rand.nextInt(alphabet.length)]);
        }
        String initVector = sb.toString();

        String firstPass = shift(plaintext, initVector, false);

        return shift((initVector+firstPass), KEY, false);
    }

    public static String decrypt(String encrypted, int size) {
        String firstPass = shift(encrypted, KEY, true);
        return shift(firstPass.substring(size), firstPass.substring(0, size), true);
    }

    private static String shift(String clear, String shifter, boolean backward) {

        while (shifter.length() < clear.length())
            shifter += shifter;
        shifter = shifter.substring(0, clear.length());

        StringBuilder sb = new StringBuilder();
        for(int i=0; i<clear.length(); i++) {
            sb.append(shift(clear.charAt(i), shifter.charAt(i), backward));
        }
        return sb.toString();
    }

    private static char shift(char c, char s, boolean backward) {
        int indexC = indexOf(c);
        int indexS = indexOf(s);

        int indexShifted;
        if(backward) {
            indexShifted = ((indexC - indexS) + alphabet.length) % alphabet.length;
        } else {
            indexShifted = (indexC + indexS) % alphabet.length;
        }

        return alphabet[indexShifted];
    }

    private static int indexOf(char c) {
        int index = -1;
        for(int i=0; i<alphabet.length; i++) {
            if(c == alphabet[i]) {
                index = i;
                break;
            }
        }
        return index;
    }
}


texts:
I wrote a simple PHP script which allows the user to upload a file to the server. It works, but I'm not very sure about security. Could you give me some hints about security mistakes?

In a nutshell: The user uploads a file from form.html, then a file is saved in uploads/ directory on the server, and a direct link to it is recorded in a database. Then that link is presented to the user, so he/she is able to download the file. The execution of that file is forbidden using .htaccess.

form.html

                <form enctype="multipart/form-data" class="smallForm"
                      action="action.php?act=quickFileSubmit" method="post"
                      style="margin-top: 5px;">
                    File:
                    <input type="file" name="uploadfile" readonly="true" size="30"/>
                    <input type="submit" value="Submit" />
                </form>

action.php

//some actions

else if ($_REQUEST["act"] == "quickFileSubmit") {
    $basename = getUploadBasename();
    uploadFile();
    header("location:index.php");
}

function uploadFile() {

    if (strlen($_FILES['uploadfile']["name"]) > 0) {
        $target_path = "uploads/";
        $basename = basename( $_FILES['uploadfile']['name']);
        $target_path = $target_path . $basename;
        if (encode($basename) == $basename) {
            if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $target_path)) {

                // here goes saving of file info

                return $basename;
            } else{
                // upload failed.
                echo "File upload failed.";
                return null;
            }
        } else {
            echo "Illegal characters in file name.";
            return null;
        }
    }
}

Also, I have put .htaccess in the uploads dir:

.htaccess

SetHandler default-handler
Options -Indexes


texts:
I was playing arround with some CSS and ended up in making some 3D hover icons with font awesome.

I wanted to ask for some feedback on my CSS: Best-practices, any other comments, maybe bad things that you should not do...

article {
 position: relative;
 left: 50%;
 transform: translateX(-50%);
 min-height: 100%;
}

article h2{
 text-transform: uppercase;
}

.intro-contact {
 height: 100vh;
 display: flex;
 align-items: center;
 justify-content: center;
}

.ul_icons {
 position: relative;
 margin: 0;
 padding: 0;
 display: flex;
 justify-content: center;
 align-items: center;
 margin-top: 30px;
 margin-bottom: 20px;
}

.ul_icons .li_icons {
 position: relative;
 list-style-type: none;
 width: 60px;
 height: 60px;
 margin: 0 30px;
 transform: rotate(-30deg) skew(25deg);
 background: #ccc;
}

.ul_icons .li_icons span {
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;
 background: #000;
 transition: 0.5s;
 display: flex !important;
 align-items: center;
 justify-content: center;
 color: #fff;
 font-size: 30px !important;
}

.ul_icons .li_icons:hover span:nth-child(5) {
 transform: translate(40px, -40px);
 opacity: 1;
}
.ul_icons .li_icons:hover span:nth-child(4) {
 transform: translate(30px, -30px);
 opacity: 0.8;
}
.ul_icons .li_icons:hover span:nth-child(3) {
 transform: translate(20px, -20px);
 opacity: 0.6;
}
.ul_icons .li_icons:hover span:nth-child(2) {
 transform: translate(10px, -10px);
 opacity: 0.4;
}
.ul_icons .li_icons:hover span:nth-child(1) {
 transform: translate(0, 0);
 opacity: 0.2;
}

.ul_icons .li_icons:nth-child(1) span {
 background: #3b5999;
}
.ul_icons .li_icons:nth-child(2) span {
 background: #87CEEB;
}
.ul_icons .li_icons:nth-child(3) span {
 background: #E3D094;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Contact


texts: Including a page specified in query string

texts:
This is how I include a page depending by name.

Example URL:

  http://www.page.com/index.php?page=admin

where admin.inc.php lays inside /modules/ directory.

The files are located in a directory I specified. The included files should not render when connected to them directly.

Are there ANY issues with the code?
Are there any security flaws, such as remote file inclusion?
What could I improve in this approach?
Is this the right approach to modularize a page?
Are included pages secure enough to not be rendered by themselves?

<?php
    class cms {
        private $config_module_name;
        private $config_module_extention        = '.inc.php'; // ex: .inc.php
        private $config_module_directory        = 'modules'; // ex: modules
        private $config_module_list;

        function __construct() {
            $this->SetModuleList();
        }

        public function GetModuleExtention() {
            return $this->config_module_extention;
        }

        private function GetModuleDirectory() {
            return $this->config_module_directory;
        }

        public function GetModuleList() {
            $moduleList = array();
            foreach($this->config_module_list as $module) {
                if($this->CheckModule($module) == 1) { // 1 for pure module result
                    $moduleNoExt = str_replace($this->GetModuleExtention(), '', $module);
                    $moduleList[] = str_replace($this->GetModuleExtention(), '', $moduleNoExt);
                }
            }
            return $moduleList;
        }

        private function SetModuleList() {
            $this->config_module_list = array_diff(scandir($this->GetModuleDirectory(), 1), array('..', '.'));
        }

        // 0 - invalid; 1 - correct module; 2 - folder
        private function CheckModule($module) {
            $moduleNameArray = explode(".", $module);
            $countParts = count($moduleNameArray);
            if($countParts == 1) { // folder return 2
                return 2;
            }
            else if($countParts == 3) { // module must count 3
                $moduleNameExtention = '.' .  $moduleNameArray[1] . '.' . $moduleNameArray[2];
                // module must match set module extention
                if($this->GetModuleExtention() == $moduleNameExtention) {
                    return 1;
                }
            }
            return 0; // invalid module - if reached
        }

        public function IncludeModule($name) {
            if(in_array($name, $this->GetModuleList())) {
                include($this->GetModuleDirectory() . '/' . $name . $this->GetModuleExtention());
            }
            else { // if module doesn't exist - throw 404
                header('HTTP/1.0 404 Not Found');
                $this->ConcatContent('
Error 404

This page doesn\'t exist.');
            }
        }
    }
?>

Index page where all pages get included:

<?php
    define('CMS_TOKEN', '');
    include('config/config.inc.php');
    $cms = new cms()

    if(($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_GET['page'])) {
        if($_GET['page'] == '404') {
            header('HTTP/1.0 404 Not Found');
            $cms->ConcatContent('
Error 404

This page doesn\'t exist.');
        }
        else {
            print_r($_GET);
            $cms->IncludeModule($_GET['page']);
        }
    }
?>

This is how included module looks like. The file must be included by index, or else it should redirect.

<?php
    $module_name        = 'Register';
    if(!defined('CMS_TOKEN')) {
        // page cannot be rendered
        header('Location: ../');
    }
    else {
        // render page
    }
?>


texts: How to copy and paste a filtered range more efficiently

texts:
I have this bit of code that works for copy and pasting an autofiltered range. I just wanted to see if anyone knew a more efficient way to do so as it does take quite a while to complete it the way I have it now. I looked into trying to do so with a copying into an array but did not seem to work so I'm happy to hear some of your suggestions! Also I have to be sure that the range I am copying and pasting is not the full data range and only the range after the filter was applied.
Sub FullWork()

Dim shWorkBook As Worksheet
Dim shPivotTable As Worksheet
Dim shCarrierRates As Worksheet
Dim shWholesaleLocation As Worksheet
Dim shPWLocation As Worksheet
Dim wkb As Workbook
Dim shSegmentation As Worksheet
Dim MilageMatrix As Worksheet
Dim FullYearData As Worksheet
Dim StartForm As Worksheet
Set wkb = ThisWorkbook
With wkb

Set shWorkBook = .Sheets("Workbook")
Set shPivotTable = .Sheets("PivotTable")
Set shCarrierRates = .Sheets("CarrierRates")
Set shWholesaleLocation = .Sheets("WholesalerLocation")
Set shPWLocation = .Sheets("PWLocation")
Set shSegmentation = .Sheets("Segmentation")
Set shMilageMatrix = .Sheets("MilageMatrix")
Set shFullYearData = .Sheets("FullYearData")
Set shStartForm = .Sheets("StartForm")

End With

Dim DataRange As Range
Dim PWSelection As Variant
Dim LastRow As Long
Dim LastColumn As Long
Dim LocationZip As Variant
Dim dTime As Double

dTime = Timer

Call TurnOffCalc

Set StartCell = shFullYearData.Range("A1")

'Find Last Row and Column

LastRow = shFullYearData.Cells(shFullYearData.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = shFullYearData.Cells(StartCell.Row, shFullYearData.Columns.Count).End(xlToLeft).Column

shFullYearData.Activate
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).Select

PWSelection = shStartForm.Cells(1, 1).Value

shFullYearData.Range(shFullYearData.Cells(1, 1), shFullYearData.Cells(1, LastColumn)).AutoFilter
If PWSelection <> "All" Then
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).AutoFilter Field:=12,         Criteria1:=PWSelection
End If
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).AutoFilter Field:=26, Criteria1:=">=1"
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).AutoFilter Field:=3, Operator:= _
xlFilterValues, Criteria2:=Array(0, "12/31/2019")
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).Sort Key1:=Range("G1"), Order1:=xlAscending, Header:=xlYes, Key2:=Range("B1"), Header:=xlYes

''''''Line I need looked at
shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn)).Copy Destination:=shWorkBook.Range("A1")

call TurnOnCalc
end sub


texts: Is this a sensible way to implement a model?

texts:
I've created the following model for an academic project, and I'm wondering if this is a sensible way to manage a model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Windows.Forms;

namespace IceCreamShop
{
    [Serializable]
    public class Customer : ISerializable
    {
        private const string SAVE_FILE_NAME = @".\Customers.bin";

        #region static model accessors

        private static List<Customer> customers = new List<Customer>();

        public static ReadOnlyCollection<Customer> Customers
        {
            get
            {
                return customers.AsReadOnly();
            }
        }

        public static int Cardinality { get; private set; }

        public static void saveCustomers(List<Customer> customers)
        {
            IFormatter formatter = new BinaryFormatter();

            Stream stream = File.Open(SAVE_FILE_NAME, FileMode.Create);

            formatter.Serialize(stream, customers);

            formatter.Serialize(stream, Customer.Cardinality);

            stream.Close();
        }

        public static void loadAllCustomers()
        {
            IFormatter formatter = new BinaryFormatter();

            List<Customer> customers = new List<Customer>();

            try
            {
                Stream stream = File.Open(SAVE_FILE_NAME, FileMode.OpenOrCreate);

                if (stream.Length > 0)
                {
                    customers = (List<Customer>)formatter.Deserialize(stream);

                    Customer.Cardinality = (int)formatter.Deserialize(stream);
                }

                stream.Close();
            }
            // Shouldn't happen during normal operation, pending any permissions/file write issues
            catch (Exception ex)
            {
                throw ex;
            }

            if(customers.Count == 0)
            {
                // Dummy customer for patrons who don't want their data tracked
                customers.Add(new Customer("nobody", "nobody"));

                Customer.Cardinality = 1;
            }

            Customer.customers = customers;
        }
        #endregion

        #region individual model data

        private string firstName;
        public string FirstName { get { return firstName; } }

        private string lastName;
        public string LastName { get { return lastName; } }

        private int id;
        public int ID { get { return id; } }

        //Used externally to generate a new customer
        public Customer(string firstName, string lastName)
        {
            this.id = Customer.Cardinality++;
            this.firstName = firstName;
            this.lastName = lastName;
        }

        #endregion

        #region serialization

        Customer(SerializationInfo info, StreamingContext context)
        {
            this.id = info.GetInt32("i");
            this.firstName = info.GetString("j");
            this.lastName = info.GetString("k");
        }

        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("i", this.id);
            info.AddValue("j", this.firstName);
            info.AddValue("k", this.lastName);
        }

        #endregion
    }
}

An individual Customer consists of an id, first name and a last name. I realize there are still some issues to be ironed out, but I'm primarily wondering if it makes sense to use statics in this way.

This is part of an MVP-based project, which focuses on putting application logic in the controllers and data-based operations in the model with dumb views.


texts:
Is this code missing any "Kotlinisms"?

I've just started learning Kotlin so I'm not yet familiar with the Kotlin way of doing things.

The program will guess a number you are thinking of.

package challenges.difficult

/**
 * Created by jbarnes on 04/06/2016.
 * Challenge: https://www.reddit.com/r/dailyprogrammer/comments/pii6j/difficult_challenge_1/
 */

fun main(args:Array<String>) {
    Guesser();
}

class Guesser(range:IntRange) {

    private var range = range;
    private var upperLimit:Int = range.last;
    private var lowerLimit:Int = range.first;
    private var turnCount:Int = 0;
    private var lastGuess:Int = 0;
    private var lastResponse:Response = Response.UNKNOWN;

    constructor():this(1..100)

    init {
        printIntro();
        while (lastResponse != Response.CORRECT) {
            lastResponse = presentNextGuess();
            turnCount++;
            if (lastResponse == Response.CORRECT) {
                println("I guessed your number in $turnCount turns.");
            }
            if (lastResponse == Response.UNKNOWN) {
                println("I'm sorry, I didn't understand that.");
            }
        }

    }

    fun calcNextGuess():Int {
        var roundingFactor = 0;
        if (lastResponse == Response.HIGHER) {
            lowerLimit = lastGuess;
            roundingFactor = 1; //compensates for rounding down
        } else if (lastResponse == Response.LOWER) {
            upperLimit = lastGuess;
        }
        return (lowerLimit + ((upperLimit - lowerLimit) / 2)) + roundingFactor;
    }

    fun presentNextGuess():Response {
        val nextGuess = calcNextGuess();
        println("Is your number $nextGuess?");
        val response = readLine();
        lastGuess = nextGuess;
        return parseResponse(response);
    }

    fun parseResponse(response:String?):Response {
        if (response == null) {
            return Response.UNKNOWN;
        } else if (response.equals("higher", true) || response.equals("h", true)) {
            return Response.HIGHER;
        } else if (response.equals("lower", true) || response.equals("l", true)) {
            return Response.LOWER;
        } else if (response.equals("yes", true) || response.equals("y", true)) {
            return Response.CORRECT;
        } else {
            return Response.UNKNOWN;
        }
    }

    fun printIntro() {
        println("Think of a number between 1 and 100. I am going to try and guess it.");
        println("If i guess correctly respond with 'yes' (or 'y')");
        println("Otherwise respond to with either 'higher' (or 'h') or 'lower' (or 'l')");
        println("Okay, here we go...");
    }

    enum class Response {
        HIGHER, LOWER, CORRECT, UNKNOWN
    }
}

https://github.com/JNBarnes/LearningKotlin/blob/master/src/challenges/difficult/GuessingGame.kt


texts: more elegant way when call parent method with the same name

texts:
My subclass extends the Formatter class,
I wonder know is there any elegant way, to rewrite my code

Parent

class Formatter(object):
    def resp_in_hash(self, resp):
        ...
        return rtn_hash

Child

from formatter import Formatter
# -----------------------------------------------------------------
class Request(Formatter):

    def req(self, url_path, is_no_cache=True):
        ...
    def resp_in_hash(self, url_path):
        resp, content = self.req(url_path)
        return super(Request, self).resp_in_hash(content)


texts: Assembler PIC programming, is this correct?

texts:
The question is:

Write the following pseudo in assembler code:

if portC bit 3 == 0
(switch content of var1 and var2)
else
(add var1 with var2 and place the result in var1)

My answer is:

btfsc portC,3
goto add
movf var1,w
movwf temp
movf var2,w
movwf var1
movf temp,w
movwf var2
return

add movf var2,w
addwf var1,f

Since I dont know the right answer, can you please help me and tell me if I wrote it correct?


texts: Quadrilaterals containing a square number of lattice points

texts:
I am working on Project Euler problem 504, which states:

  Let \$ABCD\$ be a quadrilateral whose vertices are lattice points lying on the coordinate axes as follows:

  \$A(a, 0), B(0, b), C(−c, 0), D(0, −d)\$ where \$1 ≤ a, b, c, d ≤ m\$ and \$a, b, c, d, m\$ are integers.

  It can be shown that for \$m = 4\$ there are exactly 256 valid ways to construct \$ABCD\$. Of these 256 quadrilaterals, 42 of them strictly contain a square number of lattice points.

  How many quadrilaterals \$ABCD\$ strictly contain a square number of lattice points for \$m = 100\$?

My code is working fine, but the issue is optimization. I am already using memoization.

from fractions import gcd
from math import fabs
def PolygonArea(corners):
    n = len(corners)
    area = 0.0
    for i in range(n):
        j = (i + 1) % n
        area += corners[i][0] * corners[j][1]
        area -= corners[j][0] * corners[i][1]
    area = abs(area) / 2.0
    return area

def isSquare(n):
    sqrt = n ** 0.5
    if sqrt == int(sqrt):
        return True
    return False

memo = {}
def lattice(p1, p2):
    t = (fabs(p2[0] - p1[0]), fabs(p2[1] - p1[1]))
    g = gcd(t[0], t[1]) + 1
    if not t in memo:
        memo[t] = g
    return memo[t]

def boundary(p1, p2, p3, p4):
    return (lattice(p1, p2) + lattice(p2, p3) + lattice(p3, p4) + lattice(p4, p1) - 4)

def interior(p1, p2, p3, p4):
    corners = [p1, p2, p3, p4]
    A = PolygonArea(corners)
    B = boundary(p1, p2, p3, p4)
    I = A - B/2 + 1
    return I

squares = set([x**2 for x in xrange(1000)])
count = 0
for a in xrange(1, 101):
    for b in xrange(1, 101):
        for c in xrange(1, 101):
            for d in xrange(1, 101):
                I = interior((a, 0),(0, b),(-1*c, 0),(0, -1*d))
                if I in squares:
                    count += 1
print count


texts:
I created a project for a programming class that asks you to make a userform in Visual Studio that calculates mileage, given the user inputs of gallons of gas consumed and distance traveled. The code does its job fine, but I can't help but feel that my use of Do...While and Try...Catch statements are less than elegant. If anyone has suggestions or tips or cryptic hints about what would improve my code, I would be grateful!

Private Sub btnMileage_Click(sender As Object, e As EventArgs) Handles btnMileage.Click
    Dim sngGas As Single, sngDistance As Single, sngMileage As Single

    Do While sngGas <= 0 'force user to input positive number for gallons of gas consumed
        Try 'reject all inputs that are not real numbers
            sngGas = CSng(InputBox("Please enter gasoline consumed in gallons:"))
            If sngGas <= 0 Then 'remind user to input number greater than 0
                MsgBox("Please make sure your input is greater than 0.")
            End If
        Catch ex As Exception
            MsgBox("Error: Please enter a valid number.") 'remind user that all inputs that aren't numbers are rejected
        End Try
    Loop

    Do While sngDistance <= 0
        Try 'reject all inputs that are not real numbers
            sngDistance = CSng(InputBox("Please enter distance travelled in miles:")) 'force user to enter positive value for distance
            If sngDistance <= 0 Then
                MsgBox("Please make sure your input is greater than 0.")
            End If
        Catch ex As Exception
            MsgBox("Error: Please enter a valid number.") 'reminder user that all inputs that aren't numbers are rejected
        End Try
    Loop

    sngMileage = Math.Round((sngDistance / sngGas), 1, MidpointRounding.AwayFromZero) 'calculate mileage

    PopulateForm(CStr(sngGas), CStr(sngDistance), CStr(sngMileage)) 'update form with gas, distance & mileage

    MsgBox("All done!")
End Sub

The sub I use to populate the form follows:

Private Sub PopulateForm(Optional ByVal strGas As String = "", Optional ByVal strDistance As String = "", Optional ByVal strMileage As String = "") 'wipes form or populates with new values

    lblGas.Text = "Gas Consumed: " & strGas
    lblDistance.Text = "Distance Travelled: " & strDistance
    lblMileage.Text = "Mileage: " & strMileage

End Sub


texts: MySQL database connection in the constructor

texts:
I'm an absolute beginner in PHP OOP in search of the "Holy Grail" of connecting to MySQL database once and reusing this connection for the whole site.

classes/db.php

<?php
define('SERVER', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', 'password');
define('DATABASE', 'cms');

class DB {
    function __construct(){
        $connection = @mysql_connect(SERVER, USERNAME, PASSWORD) or die('Connection error -> ' . mysql_error());
        mysql_select_db(DATABASE, $connection) or die('Database error -> ' . mysql_error());
    }
}
?>

classes/users.php

<?php
class Users {
    function __construct(){
        $db = new DB();
    }

    public function read(){
        $query = mysql_query("select use_id, use_name, use_email FROM users");
        while ($row = mysql_fetch_array($query)){
            $data[] = $row;
        }
        return $data;
    }
}
?>

users.php

<?php require_once('classes/db.php'); ?>
<?php require_once('classes/users.php'); ?>
<?php
$Users = new Users();
$users = $Users->read();
?>
<?php
if ($users) {
    echo '
';
    foreach($users as $user){
        echo '
' . $user['use_name'] . '
';
    }
    echo '
';
}
?>

My doubts are mostly on the Users class part:

function __construct(){
    $db = new DB();
}

It seems to be an easy way to have the connection available, but I read somewhere that instantiate the db connection in the constructor is a bad idea.  Can you explain why, and if there's a better way to have the db connection easily available in every class that needs it?

I read a similar question here, but I can't understand the abstraction/holding reference/singleton suggestion from the accepted answer, and the lack of a full practical example doesn't help me.


texts: Generic Repository: Am I over-complicating?

texts:
I have created a generic repository for my MVC 3 page. I am using interfaces and a UnitOfWork. But before I set out to do this? Is this the right way to separate my databaseaccess from my viewmodels and views?

WHY I DID IT:

I want to seperate my databaseaccess from my viewmodels and my views, I also want the option to have specific methods for inserting some of my data hence the UserRepository. I also want a controlled environment using the UnitOfWork.

FEARS:

Am I over-complicating everything using these interfaces? Should I ditch the generic repository, I will use it for "basic" inserts so it's not useless by any means. I do understand that I might save some time having the generic repository, only to be creating specific repositories for some of my inserts/update/deletes.

Summary:

It consists of 6 files at the moment of which 2 are:

IRepository
GenericRepository
IUnitOfWork
UnitOfWork
IUserRepository
UserRepository

Code

IRepository:

public interface IRepository<T> where T : class
{
        IEnumerable<T> BaseFetchAll();
        void BaseAdd(T entity);
        void BaseDelete(T Entity);
}

Repository:

public abstract class GenericRepository<T> : IRepository<T> where T : class
{
    private IObjectSet<T> _dbContext;
    private Entities _context;
    protected DbSet<T> dbSet;

    internal GenericRepository(Entities context)
    {
        this._context = context;
        dbSet = context.Set<T>();
    }

    public void BaseDelete(T entity)
    {
        dbSet.Remove(entity);
    }

    public IEnumerable<T> BaseFetchAll()
    {
        return (IEnumerable<T>)(from x in dbSet select x).ToList<T>();
    }

    public void BaseAdd(T entity)
    {
        dbSet.Add(entity);
    }
}

IUnitOfWork:
Before you kick my butt, I am to implement the save,rollback etc. methods this is just to show you what I'm doing.

public interface IUnitOfWork
{
    IUserRepository UserRepository { get; }
    IUserFileRepository UserFileRepository { get; }
}

UnitOfWork:

public class UnitOfWork : IUnitOfWork
{
    private IUserRepository _userRepository;
    private Entities context = new Entities();

    public IUserRepository UserRepository
    {
        get
        {
             if(this._userRepository == null)
               this._userRepository = new UserRepository(context);
             return this._userRepository;
        }
    }
}

IUserRepository:

public interface IUserRepository: IRepository<t_users>
{
    IEnumerable<t_users> FetchAllUsers();
    void InsertToUserTableWithSpecs();
}

UserRepository:

public class UserRepository : GenericRepository<t_users>, IUserRepository
{

    private Entities dbContext;
    public UserRepository(Entities context) : base(context)
    {
        this.dbContext = context;
    }

    public IEnumerable<t_users> FetchAllUsers()
    {
        return (IEnumerable<t_users>)(from x in dbContext.t_users select x);
    }

    public void InsertToUserTableWithSpecs()
    {

    }
}

Not a lot of code but hopefully something to give you an idea in which direction I'm going.