JavaScript function for the get a specifed weekday n-weeks before / in the future I'm currently working on a intranet application.

It shall have a GUI on which you can choose a weekday and a positive / negative integer. The integer stands for weeks.

So let's say someone chooses the Wednesday and (-7) then it shall display the date of the Wednesday seven weeks ago.

Tuesday and 3 => Tuesday in three weeks.

Here's the code which shall calculate the date:

    // Returns a Date Object which contains
    // the date before/in n-days and
    // before/in n-weeks.

    // -- Parameter ----------------------------
    // 1. String - The desired weekday as an
    //   abbreviation.
    //   Assign for ...
    //     Monday    : 'mo'
    //     Tuesday   : 'tu'
    //     Wednesday : 'we'
    //     Thursday  : 'th'
    //     Friday    : 'fr'
    //     Saturday  : 'sa'
    //     Sunday    : 'su'

    // 2. Number - Positive number => n-weeks in
    //   the future.
    //   Negative number => n-weeks before.

    // -- Return -------------------------------
    // (Date) Object

    function getDayBeforeIn(day, weeks) {
      var currentDate = new Date();
      var currentStamp = currentDate.getTime();
      var weekdays = {
        'mo': 1,
        'tu': 2,
        'we': 3,
        'th': 4,
        'fr': 5,
        'sa': 6,
        'su': 0
      }
      var milliSecondsDay = 24 * 60 * 60 * 1000;

      day   = day   || 'mo';
      weeks = weeks || 0;

      currentStamp += weeks * 7 * milliSecondsDay;
      currentStamp +=
        (weekdays[day] - currentDate.getDate()) *
         milliSecondsDay;

      return new Date(currentStamp);
    }

    // Returns the Day, Month, Year of an
    // JavaScript Date Object as as String
    // in the Date format DMY.

    // -- Parameter ----------------------------
    // 1. Date-Object
    // 2. String - Is used for separating
    // Day-Year and Month-Year.

    // -- Return -------------------------------
    // String

    function getDayMonthYearDate(dateObject, separator) {
      var day   = '0' + dateObject.getDate();
      var month = '0' + (dateObject.getMonth() + 1);
      var year  = dateObject.getFullYear();

      separator = separator || '.';

      return day.slice(-2) + separator +
             month.slice(-2) + separator + year;
    }

    // -- TEST -----------------
    for (var i = 0; i < 10; i++) {
      var result = getDayBeforeIn('th', i * (- 1));

      console.log(getDayMonthYearDate(result));
    }
    /* -- Results ---
        04.02.2016
        28.01.2016
        21.01.2016
        14.01.2016
        07.01.2016
        31.12.2015
        24.12.2015
        17.12.2015
        10.12.2015
        03.12.2015
    */

All suggestions and hints concerning improvements welcome.

var milliSecondsDay = 24 * 60 * 60 * 1000;

This is a constant. Use all caps and underscore to indicate such. If you can use ES6, use const instead of var.

var currentDate = new Date();
var currentStamp = currentDate.getTime();

Use Date.now() to get the current timestamp. This saves you from creating a Date object.

return day.slice(-2) + separator + month.slice(-2) + separator + year;

Appears that you are using zero-padding. Create a separate function for it to make it reusable.

getDayBeforeIn

You aren't really returning the day, you're returning a Date object. Either you rename this to reflect the return value, like getDateBeforeIn or return a representation of the day of the week.


Sum of N primes in parallel-ish Linq's AsParallel() call would be my normal way of doing something like this, but Rust hasn't stolen that just yet. This method has obvious shortcomings, but I'm still sort of hoping for it to shave off a little time by engaging a second core.

How can I achieve this less terribly?

use std::num::Float;
use std::sync::Future;

fn main() {
    // This implementation cheats because it knows the biggest prime value
    // in the range: 7919. Getting primes in parallel is a pain in the ass
    // pretty much no matter what, and it's probably not worth it, but on
    // the up side... Eh. Whatever. Only other way I know to do this would
    // be to get the first *1001* primes, sort them, and then fold the first
    // thousand after stuffing them into a vector.

    let mut path_1 = Future::spawn(proc() {
        Unfold::new(3, incr).filter(prime).take_while(|n| *n <= 7919).fold(0i, |a, b| a + b)
    });
    let mut path_2 = Future::spawn(proc() {
        Unfold::new(5, incr).filter(prime).take_while(|n| *n <= 7919).fold(0i, |a, b| a + b)
    });

    // As you can see, my plan here was to get 999 primes (skipping 2)
    // and then add 2 back in later on.
    println!("{}", path_1.get() + path_2.get() + 2);
}

fn incr(n: &mut int) -> Option<int> {
    let r = Some(*n);
    *n = *n + 4;
    r
}

fn prime(n: &int) -> bool {
    match n {
        &1 => false,
        &2 => true,
        &3 => true,
        n if *n % 2 == 0 => false,
        _ => {
            let max = (*n as f64).sqrt() as int + 1;
            !range(2, max).any(|i| *n % i == 0)
        }
    }
}

It isn't clear to me what you are asking. However, I was able to update your code and run it:

use std::thread;

struct PrimeIncrement(i64);

impl Iterator for PrimeIncrement {
    type Item = i64;
    fn next(&mut self) -> Option<i64> {
        self.0 += 4; // What do you mean "integer overflow"? ^_^
        Some(self.0)
    }
}

fn main() {
    let path_1 = thread::scoped(|| {
        PrimeIncrement(3).filter(prime).take_while(|&n| n <= 7919).fold(0, |a, b| a + b)
    });
    let path_2 = thread::scoped(|| {
        PrimeIncrement(5).filter(prime).take_while(|&n| n <= 7919).fold(0, |a, b| a + b)
    });

    let a = path_1.join();
    let b = path_2.join();

    println!("{}", 2 + a + b);
}

fn prime(n: &i64) -> bool {
    match n {
        &1 => false,
        &2 => true,
        &3 => true,
        n if *n % 2 == 0 => false,
        _ => {
            let max = (*n as f64).sqrt() as i64 + 1;
            !(2..max).any(|i| *n % i == 0)
        }
    }
}

The main changes were:

Removing Unfold, as it isn't stable in the 1.0 beta.
Using thread::scoped instead of a Future.
Using i64 instead of int

Update for Rust 1.3

The thread::scoped API was found to have soundness problems and has been deprecated. In this case, thread::spawn is powerful enough, so I've replaced that:

use std::thread;

struct PrimeIncrement(i64);

impl Iterator for PrimeIncrement {
    type Item = i64;
    fn next(&mut self) -> Option<i64> {
        self.0 += 4; // What do you mean "integer overflow"? ^_^
        Some(self.0)
    }
}

fn main() {
    let path_1 = thread::spawn(|| {
        PrimeIncrement(3).filter(prime).take_while(|&n| n <= 7919).fold(0, |a, b| a + b)
    });
    let path_2 = thread::spawn(|| {
        PrimeIncrement(5).filter(prime).take_while(|&n| n <= 7919).fold(0, |a, b| a + b)
    });

    let a = path_1.join().unwrap();
    let b = path_2.join().unwrap();

    println!("{}", 2 + a + b);
}

fn prime(n: &i64) -> bool {
    match *n {
        1 => false,
        2 => true,
        3 => true,
        n if n % 2 == 0 => false,
        n => {
            let max = (n as f64).sqrt() as i64 + 1;
            !(2..max).any(|i| n % i == 0)
        }
    }
}

Additionally, I now match on *n, which avoids the need to have quite as many dereferences.


pyCMD; a simple shell to run math and Python commands I made a command line in Python.
Before I go on and add more commands, is my program made well?
I don't like the huge amount of "if" statements in it. But I don't know a better way to do it. (JSON may be used later this is why I have it included)
Here's the code:
import time
import json
print("Welcome to pyCMD, user\n")
time.sleep(0.2)
input("Press enter to start\n")
time.sleep(0.2)

def SavetoDisk(data, file):
    with open(file, 'w') as outfile:
        json.dump(data, outfile)

def ReadfromDisk(file):
    with open(file) as json_file:
        data = json.load(json_file)
    return data
print('Starting command line, use "help . ." for help')
running = True
commandList = "add | sub | mult | div | exp | tetrate | python"
while running:
    try:
        userInput = input(': ')
        tokens = userInput.split()
        command = tokens[0]
        args = [(token) for token in tokens[1:]]
    except: print("unknown input error")
    try:
        arg1, arg2 = args
    except ValueError:
        print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')

    if command == "add":
        print(float(arg1) + float(arg2))

    if command == "sub":
        print(float(arg1) - float(arg2))

    if command == "mult":
        print(float(arg1) * float(arg2))        #math commands

    if command == "div":
        print(float(arg1) / float(arg2))

    if command == "exp":
        print(float(arg1) ** float(arg2))

    if command == "tetrate":
        for x in range(int(arg2)):
            arg1 = float(arg1) * float(arg1)
        print(arg1)

    if command == "python":
        exec(open(arg1).read())

    if command == "help":
        if arg1 == '.':
            if arg2 == '.':
                print('To see help about a command, type: "help [command] ." for list of commands type: "help command list"')

        if arg1 == 'command':
            if arg2 == 'list':
                print(commandList)

        if arg1 == 'add':
            print("Add: \n Description: Adds 2 numbers \n Syntax: add [num1] [num2]")

        if arg1 == 'sub':
            print("Sub: \nDescription: Subtracts 2 numbers \n Syntax : sub [num1] [num2]")

        if arg1 == 'mult':
            print("Mult: \nDescription: Multiplies 2 numbers \n Syntax : mult [num1] [num2]")

        if arg1 == 'div':
            print("Div: \nDescription: Divides 2 numbers \n Syntax : div [num1] [num2]")

        if arg1 == 'exp':
            print("Exp: \nDescription: Raises 1 number by another \n Syntax : exp [num1] [num2]")

        if arg1 == 'tetrate':
            print("Tetrate: \nDescription: Tetration \n Syntax : tetrate [num1] [num2]")

        if arg1 == 'python':
            print("Python: \nDescription: Runs a python script \n Syntax : python [path/to/program.py] .")

The first thing I notice with your code is that the code is a very long global script. To resolve this I'd start by moving your code into functions.
The actual calculations could be as simple as say:
def add(arg1, arg2):
    print(float(arg1) + float(arg2))

To then get the help information we could add a docstring.
def add(arg1, arg2):
    """
    Add:
     Description: Adds 2 numbers
     Syntax: add [num1] [num2]
    """
    print(float(arg1) + float(arg2))

We can get both the docstring and the output of the operation with Python. To get the docstring to be nicely formatted we can use textwrap.dedent.
>>> add("10", "5")
15.0
>>> import textwrap
>>> textwrap.dedent(add.__doc__.strip("\n"))
Add:
 Description: Adds 2 numbers
 Syntax: add [num1] [num2]

To then reduce the amount of lines of code we can bundle all these functions into a dictionary. And just index the dictionary to get a specific function.
COMMANDS = {
    "add": add,
    "sub": sub,
    # ...
}

fn = COMMANDS["add"]
fn("10", "5")

15.0

Whilst you can build the dictionary and execute the commands yourself, you could instead subclass cmd.Cmd. You will need to change the functions slightly to only take a string as input, and prefix do_ to any commands available to the commandline.
import cmd

class PyCMD(cmd.Cmd):
    intro = 'Welcome to pyCMD, user\nStarting command line, use "help" for help'
    prompt = ": "

    def do_add(self, arg):
        """
        Add:
         Description: Adds 2 numbers
         Syntax: add [num1] [num2]
        """
        arg1, arg2 = arg.split()
        print(float(arg1) + float(arg2))

PyCMD().cmdloop()

Welcome to pyCMD, user
Starting command line, use "help" for help
: help

Documented commands (type help <topic>):
========================================
add  help

: help add

        Add:
         Description: Adds 2 numbers
         Syntax: add [num1] [num2]

: add 10 5
15.0

The help is clearly a bit on the broken side. To fix this we can change the docstring after the function.
class PyCMD(cmd.Cmd):
    def do_add(self, arg):
        # ...

    do_add.__doc__ = textwrap.dedent(do_add.__doc__.rstrip(" ").strip("\n"))

This is a bit ugly and doing this for each function would be horrible. So we can create a function to do this.
def clean_doc(fn):
    fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\n"))

class PyCMD(cmd.Cmd):
    def do_add(self, arg):
        # ...

    clean_doc(do_add)

This is still a bit on the ugly side so we can use @ to do this for us. This is called a decorator. This makes sense because we're decorating how __doc__ is seen. Note that we changed clean_doc to return fn.
def clean_doc(fn):
    fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\n"))
    return fn

class PyCMD(cmd.Cmd):
    @clean_doc
    def do_add(self, arg):
        # ...

We can add another function like clean_doc, but this time make it a closure if you want to easily add your validation of two arguments.
import functools

def command(fn):
    @functools.wraps(fn)
    def wrapper(self, arg):
        args = [token for token in arg.split()]
        try:
            arg1, arg2 = args
        except ValueError:
            print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')
        else:
            return fn(self, arg1, arg2)
    return wrapper

class PyCMD(cmd.Cmd):
    @command
    @clean_doc
    def do_add(self, arg1, arg2):
        """
        Add:
         Description: Adds 2 numbers
         Syntax: add [num1] [num2]
        """
        print(float(arg1) + float(arg2))

import cmd
import textwrap
import functools

def command(fn):
    @functools.wraps(fn)
    def wrapper(self, arg):
        try:
            arg1, arg2 = arg.split()
        except ValueError:
            print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')
        else:
            return fn(self, arg1, arg2)
    return wrapper

def clean_doc(fn):
    fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\n"))
    return fn

class PyCMD(cmd.Cmd):
    intro = 'Welcome to pyCMD, user\nStarting command line, use "help" for help'
    prompt = ": "

    @command
    @clean_doc
    def do_add(self, arg1, arg2):
        """
        Add:
         Description: Adds 2 numbers
         Syntax: add [num1] [num2]
        """
        print(float(arg1) + float(arg2))

PyCMD().cmdloop()

Welcome to pyCMD, user
Starting command line, use "help" for help
: help

Documented commands (type help <topic>):
========================================
add  help

: help add
Add:
 Description: Adds 2 numbers
 Syntax: add [num1] [num2]
: add 10 5
15.0

Other commands left for you to implement


Creating List of String elements that occur a certain amount of times using only the List ADT I am tasked with creating a list with no duplicates of all String elements, in this case first names, of an ArrayList. The method is passed a threshold, and the method must store the first name if it has occurred at least the amount of the threshold. The restriction is that I am only allowed to use the List ADT. I have this code storing it in a ArrayList and it works, but I am worried about the algorithmic complexity which seems to be \$O(n^2)\$ as a worst case. Is there a more efficient way of writing this method?

static List<String> commonFirstNames(ArrayList<Student> students, int threshold) {
    ArrayList<String> results = new ArrayList<String>();

    String[] nameArray;
    String firstName;
    int counter = 0;
    for (int i = 0; i < students.size(); i++) {
        nameArray = students.get(i).getName().split(" ");
        firstName = nameArray[0];

        boolean isInResults = results.contains(firstName);
        if (!isInResults) {
            for (int j = i; j < students.size(); j++) {
                String[] otherNameArray = students.get(j).getName().split(" ");
                String otherFirstName = otherNameArray[0];

                if (otherFirstName.equals(firstName)) {
                    counter++;
                }
            }
            if (counter >= threshold) {
                results.add(firstName);
            }
        }
            counter = 0;
    }

    return results;
}

This is more of a hint but unfortunately I cannot comment on your post.

As greybeard already mentioned, you could sort the List and then count the elements with equal firstName. A representation of the sorted List may give you an idea how to implement this:

List("Alice A", "Alice B", "Alice C", "Brian A", "Brian B", "Jason A", "Jason B", "Jason C", ...)

Another solution is to use a Collection that counts equal entries.

This Collection implementation is often available as Bag. This is unfortunately not included in the Java standard library, but implementations are available in Apache Commons. Note that you have to transform the List of firstName + lastName to a list that only contains the firstName. You can use a Transformer also available in Apache Commons that strips the lastName (the values of the resulting List will then be lazy evaluated).


Timers to use various Task(s) I am developing a C# program, which performs various tasks in parallel threads. I created a Base task and let all tasks derived from this class execute. I just want to know if this a viable approach which won't cause unforeseen consequences if various tasks run in conjunction.

public abstract class BaseTask
{
     private readonly Timer _taskTimer = new Timer();

    // Derived classes to define thier own time Intervals
    protected abstract double TimerInterval { get; set; }

    public void Start()
    {
        // Set default Timer -- 10 seconds
        TimerInterval = 10000;

        _taskTimer.AutoReset = true;
        _taskTimer.Interval = TimerInterval;
        _taskTimer.Elapsed += ExecuteTask;
        _taskTimer.Start();
    }

    public void Stop()
    {
        _taskTimer.Stop();
    }

    public abstract void ExecuteTask(object sender, ElapsedEventArgs e);
}

// Derived Task Class
 class DerivedTask : BaseTask
 {
   protected override double TimerInterval
    {
        get { return 5000; }
        set {  }
    }

    public override void ExecuteTask(object sender, ElapsedEventArgs e)
    {
        // Do My Derived task operations here
    }
 }

 // Now In Main..
 static void Main()
 {
    DerivedTask dTask = new DerivedTask ();
    _dTask .Start();
 }

I don't see any reason to use Base and Derived classes in your case. At least with the context you've provided.

public class TimerTask
{
    private readonly Timer _taskTimer;

    public TimerTask(Action action, int interval = 10000)
    {
        _taskTimer = new Timer { AutoReset = true, Interval = interval };
        _taskTimer.Elapsed += (_, __) => action();
    }

    public void Start() { _taskTimer.Start(); }

    public void Stop() { _taskTimer.Stop(); }
}

Usage:

void Main()
{
    var t1 = new TimerTask(() => Console.WriteLine("t1"), 100);
    t1.Start();
    Thread.Sleep(1000);
    t1.Stop();
}

System.Timers.Timer is thread-safe, but you have to make sure that your code is thread-safe.


Selecting an algorithm and key for Java Card encryption I was playing around with Java Card and I try to do one of the examples.

P1 is what it has to do (e.g. decrypt, encrypt, etc) and P2 is to select which key to use in P1. Here is what the code looks like - well, half of it anyway, since I'm not really used to formatting in this site and it takes awhile to copy the code and make it pretty.

So my question here is, how can I simplify this nested switch? Or maybe I don't need to use nested switch at all?

switch (buf[ISO7816.OFFSET_P1]){
    case (byte) 0x01:
        switch (buf[ISO7816.OFFSET_P2]){
            case (byte) 0x01:
                doSingleDES(apdu, DESKey1);
                return;
            case (byte) 0x02:
                doSingleDES(apdu, DESKey2);
                return;
            case (byte) 0x03:
                doSingleDES(apdu, DESKey3);
                return;
            case (byte) 0x04:
                doSingleDES(apdu, DESKey3);
                return;
            default:
                ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
        }return;
    case (byte) 0x02:
        switch (buf[ISO7816.OFFSET_P2]){
            case (byte) 0x01:
                doEncrypt(apdu, DESKey1);
                return;
            case (byte) 0x02:
                doEncrypt(apdu, DESKey2);
                return;
            case (byte) 0x03:
                doEncrypt(apdu, DESKey3);
                return;
            case (byte) 0x04:
                doEncrypt(apdu, DESKey4);
                return;
            default:
                ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
    }return;
    default:
            ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);

I would focus on eliminating the inner switch statements.  You could try to eliminate the outer switch as well, but it's probably not worthwhile, especially for a resource-constrained environment.

byte[][] desKeys = new byte[][] {
    null, DESKey1, DESKey2, DESKey3, DESKey4
};

try {
    switch (buf[ISO7816.OFFSET_P1]) {
      case 0x01:
        doSingleDES(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);
        return;
      case 0x02:
        doEncrypt(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);
        return;
      default:
        ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
    }
} catch (ArrayIndexOutOfBoundsException badP2) {
    ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}


ISO8583 encoding data fields I just want to confirm that my ISO8583 format is correct.

Example:

For the data field 35, the length of the data is 36, so I put 36 before the 4842. Then all the data is inserted in a string (dataISO). This dataISO variable is then sent to another function SendISO().

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    string command = cboISOCommand.SelectionBoxItem.ToString();
    string dataISO = "";

    if (command == "Pre-Auth")
    {
        string dataLength = "019A";
        string TPDU = "6001010000";
        string MTI = "0100";
        string BITMAP = "3020078020C00204";
        string ProCode = "380000"; // 3
        string Amount = "000000010000"; // 4
        string STAN = "000031"; // 11
        string POSEM = "051"; // 22
        string PANSequence = "001"; // 23
        string FunctionCode = "101"; // 24
        string ConditionCode = "00"; // 25
        string Track2 = "36484200000000009=15000000000000000000"; //35
        string TerminalID = "00000000"; //41
        string IdentificationCode = "000000000000000"; //42
        string ReservedISO = "2725F2A02045882023C008407A0000000031010950500000080009A031407229C01009F0206000000000010";
        ReservedISO +="9F03060000000000009F0902008C9F100706010A03A0A0029F1A0204589F1E0831313731313534399F26";
        ReservedISO +="081344604C7E2C7B589F2701809F3303E0B0C89F34031E03009F3501229F360204379F3704746733F19F4";
        ReservedISO +="104000000079F530152"; //55
        string ReservedPrivate = "006000019"; //62

        string total = dataLength + TPDU + MTI + BITMAP + ProCode + Amount + STAN + POSEM + PANSequence + FunctionCode + ConditionCode + Track2 + TerminalID + IdentificationCode + ReservedISO + ReservedPrivate;
        dataISO = total;
    }

    _controller.SendISO(client2, dataISO);
}

//To Send ISO Data Over TCP Socket
public void SendISO(TcpClient client, string isoData)
{
    string ip =     ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
    int port = ((IPEndPoint)client.Client.RemoteEndPoint).Port;

    if (!client.Connected)
    {
        OnControllerErrorFunction(
            new ControllerErrorArguments(String.Format("02<> IP {0} Port {1} not Connected", ip, Convert.ToString(port)), "DISCONNECTED"));
        return;
    }
    try
    {
        NetworkStream stream = client.GetStream();

        byte[] byteArray = Encoding.Default.GetBytes(isoData);

        if (stream.CanWrite)
        {
            stream.Write(byteArray, 0, byteArray.Length);
            stream.Flush();

            onControllerRawDataFunction(
                    new ControllerRawArguments(
                        string.Format("Send Controller {0} : {1}", ip, isoData)));
        }
    }
    catch (Exception err)
    {
        OnControllerErrorFunction(
            new ControllerErrorArguments(string.Format("02<>Controller {0} Error on sending data : {1} ", ip, isoData), err.Message));
        WriteSystemLog(err.Message, "Send Data To Controller");
        return;
    }
}

And for the function to send ISO Data over a TCP socket, is it correct in terms of the encoding before sending it using stream.Write?

The capitalization rules say:

  Do capitalize both characters of two-character acronyms, except the first word of a camel-cased identifier.

  A property named DBRate is an example of a short acronym (DB) used
  as the first word of a Pascal-cased identifier. A parameter named
  ioChannel is an example of a short acronym (IO) used as the first word
  of a camel-cased identifier.
  Do capitalize only the first character of acronyms with three or more characters, except the first word of a camel-cased identifier.

  A class named XmlWriter is an example of a long acronym used as the
  first word of a Pascal-cased identifier. A parameter named htmlReader
  is an example of a long acronym used as the first word of a
  camel-cased identifier.
  Do not capitalize any of the characters of any acronyms, whatever their length, at the beginning of a camel-cased identifier.

  A parameter named xmlStream is an example of a long acronym (xml)
  used as the first word of a camel-cased identifier. A parameter named
  dbServerName is an example of a short acronym (db) used as the first
  word of a camel-cased identifier.

You violate these rules numerous times: dataISO, TPDU, BITMAP, cboISOCommand, SendISO, etc.

What is the point of this:

string dataLength = "019A";
string TPDU = "6001010000";
string MTI = "0100";
string BITMAP = "3020078020C00204";
string ProCode = "380000"; // 3
string Amount = "000000010000"; // 4
string STAN = "000031"; // 11
string POSEM = "051"; // 22
string PANSequence = "001"; // 23
string FunctionCode = "101"; // 24
string ConditionCode = "00"; // 25
string Track2 = "36484200000000009=15000000000000000000"; //35
string TerminalID = "00000000"; //41
string IdentificationCode = "000000000000000"; //42
string ReservedISO = "2725F2A02045882023C008407A0000000031010950500000080009A031407229C01009F0206000000000010";
ReservedISO +="9F03060000000000009F0902008C9F100706010A03A0A0029F1A0204589F1E0831313731313534399F26";
ReservedISO +="081344604C7E2C7B589F2701809F3303E0B0C89F34031E03009F3501229F360204379F3704746733F19F4";
ReservedISO +="104000000079F530152"; //55
string ReservedPrivate = "006000019"; //62

string total = dataLength + TPDU + MTI + BITMAP + ProCode + Amount + STAN + POSEM + PANSequence + FunctionCode + ConditionCode + Track2 + TerminalID + IdentificationCode + ReservedISO + ReservedPrivate;

Are all of those string const? If so, why aren't they defined as such?
The comments make no sense: //55, //42
To me this feels like code that should be in a separate class, with the likes of dataLength, TPDU etc. being properties or const, and total being a get-only property with a more meaningful name.
What is the point of total, considering you immediately assign its value to dataISO?
They're currently all local variables, yet most of them are PascalCase when they should be camelCase.

Is ControllerErrorArguments a class you control? If so: why not have a version with the String.Format() functionality built-in?

Twice you do this cast: (IPEndPoint)client.Client.RemoteEndPoint. Do it once, store it in a variable, use that variable.


Stacked inputs with rows using flexbox I am trying to create stacked inputs using flexbox, with the additional ability to also set rows. Here is the code:

.stacked-inputs,
.stacked-inputs .row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-flow: row wrap;
    flex-flow: row wrap;
    -ms-flex-align: center;
    align-items: center;
}
.stacked-inputs .row {
    width: 100%;
    margin-bottom: 10px;
}
.stacked-inputs > input,
.stacked-inputs .row > input {
    position: relative;
    -ms-flex: 1 1 0%;
    flex: 1 1 0%;
    min-width: 0;
}

  <input type="text" placeholder="First name">
  <input type="text" placeholder="Last name">

    <input type="text" placeholder="First name">
    <input type="text" placeholder="Last name">

    <input type="text" placeholder="Job title">
    <input type="text" placeholder="Year started">

When inputs are stacked without using rows, they will all be stacked horizontally. However, if a row is used, then obviously the rows of stacked inputs can be divided up nicely. Would love a review of this code from someone. Thanks in advance.

The following is my opinion on how to improve your code.

You don't need write flex-flow: row-wrap because flex by default set row, then you can use another property of css flex-wrap: wrap.
If you want to use flex in the whole of your code, you can set flex properties for .row class.
Care about responsiveness, because flex is very good for making your page responsive. Due to this, we use flex-wrap and min-width to our input.

.stacked-inputs,.stacked-inputs .row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;

}
.stacked-inputs .row {
    display: flex;
    flex-grow: 1;
    flex-shrink: 1;
    flex-basis: 100%;
    margin-bottom: 10px;
}
.stacked-inputs > input,
.stacked-inputs .row > input {
    -ms-flex: 1 1 0%;
    flex: 1 1 0%;
    min-width: 200px;
}


AngularJS expression redundancy in templates I sometimes find myself using multiple expressions checking on a single flag to control the state of some template, in this example, a Facebook log in button.

On a second look, however, I noticed this pattern might bear a significant performance drawback for making Angular have to update the DOM in multiple places every time a single flag changes.

Mind you, this is a login-button directive so it's not supposed to alternate too much, it's just the latest use case I have on my hands at the moment. Other components might feature busier templates, both in condition expressions and in live updates to the DOM.

Am I just being paranoid? Or is my concern regarding performance impact here justified? Do you know of a better way to implement this (for example: a single ng-if)?

{{ isUserConnected ? 'Welcome' : 'For points' }}

  <button type="button" class="btn btn-login-fb {{isUserConnected ? 'connected' : ''}}" ng-click="facebookHandler()" unselectable="on">
    {{user.name}}
  </button>

I think the way you've chosen to do it here is probably the best option.  The other reasonable options, as far as I can see, are:

moving the h3 content string and button class out of the template, and setting them in code based on isUserConnected.  So the HTML for the header would be e.g.:

{{loginPromptHeader}}

This has the disadvantage of having presentation concerns moved out of the template and into the code somewhere.
wrapping the entire HTML in an if-else statement, with each branch repeating all of the HTML structure that doesn't change.  The disadvantage of this is that it involves much more of a maintenance overhead from repeated code.  It wouldn't surprise me if this option was also more processor-intensive, because it involves more DOM elements being created/removed each time.


Logical contradiction type definitions (Homework alert)

Working my way through "The Haskell Road...", not sure about my solution to exercise 2.15 on page 48 of the second edition:

  A propositional contradiction is a formula that yields false for every combination of truth values for its propositional letters. Write Haskell definitions of contradiction tests for propositional functions with one, two, and three variables.

I somehow gather from the way the question is asked that they expect something along the lines of:

contradiction_1 :: (Bool -> Bool) -> Bool
contradiction_1 f = (f True) == False && (f False) == False

and so on.

However, previously in the text it has been shown how to use a type class to implement validity and logical equivalence:

{-# LANGUAGE FlexibleInstances #-}

class TF p where
  valid :: p -> Bool
  lequiv :: p -> p -> Bool

instance TF Bool where
  valid = id
  lequiv f g = f == g

instance TF p => (Bool -> p) where
  valid = valid (f True)
       && valid (f False)
  lequiv f g = lequiv (f True) (g True)
            && lequiv (f False) (g False)

This above is all in the textbook.

So I thought that I can simply add the definition for contradiction as follows:

class TF p where
  valid :: p -> Bool
  contradiction :: p -> Bool -- added
  lequiv :: p -> p -> Bool

instance TF Bool where
  valid = id
  contradiction f = f == False -- added
  lequiv f g = f == g

instance TF p => (Bool -> p) where
  valid = valid (f True)
       && valid (f False)
  contradiction f = contradiction (f True) -- added
                 && contradiction (f False) -- added
  lequiv f g = lequiv (f True) (g True)
            && lequiv (f False) (g False)

This now is the code from the textbook, still unchanged, only with my additions.

It seems to work, in the sense that it only returns true for actual contradictions for what I've tried so far, for example, with GHCI:

*Main> contradiction (\p -> p && (not p))
True
*Main> contradiction (\p q -> (p || q) && ((not p) && (not q)))
True
*Main> contradiction (\p q r -> p && q && ((not p) && r))
True

But I have to admit that I really don't understand what exactly the code I wrote is doing (I did it with "pattern matching", if you know what I mean).

PS: I cannot tag the question as I would like because I don't have enough rep to create new tags.

Alright, this is the first time I've used Typeclasses so someone feel free to slap me with a tuna if I mess something up.
First of all, I don't understand why the use of "FlexibleInstances" is necessary, and it scares me because these kinds of warnings are usually put in place for a reason. With that out of the way, I'll go through the code.

The first thing you should realize is that in Haskell, typeclasses are basically the same thing as Java's interfaces. They define a contract of behaviour which instances of the class must obey. In this case, the typeclass I'm calling Prop promises the user three methods:

valid to check if the proposition is logically valid (true for all possible inputs)
contradiction to check if the proposition is false for all possible inputs.
lequiv to check if two propositions of the same number of arguments have an identical truth value given the same inputs.

These correspond to three questions which we could ask of any proposition which is a function of any number of propositional atoms. In case you're unfamiliar with this terminology, an 'atom' is one of the inputs to a proposition which is a function taking some number of atoms and itself evaluating to either True or False.
Typeclass Declaration
The name TF for the type class bears no meaning for me, so I changed it to Prop short for "Proposition".
-- A typeclass which different types may implement.
class Prop p where
  valid         :: p -> Bool            -- Same thing as a Tautism
  contradiction :: p -> Bool            -- False under all conditions/opposite of Tautism
  lequiv        :: p -> p -> Bool

What we're doing here is creating a new typeclass called Prop. We need the syntax Prop p because we need to define the behaviour of an instance p of the Prop class. If we don't introduce a symbol for it, then how will the compiler know what we're talking about the in the typeclass definition? For example, the line valid :: p -> Bool says that for every instance p of typeclass Prop, there must be a method called valid which maps p to a boolean value. Likewise, there must be a similar method for contradiction.
Now the line lequiv :: p -> p -> Bool may cause some confusion because p appears twice. It's important to understand that p, being an instance of a typeclass, is a type. There are no "objects" as in object-oriented languages. Remember: p is a type which satisfies the typeclass contract given by Prop. The Java equivalent would be a class p implementing an interface Prop. What we're saying here is that for type which implements/is a part of this typeclass Prop, there is a method called lequiv of comparing them. And its type is p -> p -> Bool meaning that it takes in two expressions of type p and returns a boolean indicating whether or not they're equivalent.

Boolean Instance Definition
All we've told the compiler so far are our promises: there will be methods for checking whether an instance of Prop is valid or a contradiction, and a method for comparing two propositions of the same type for equality.
To start, we implement these procedures for the most basic type of proposition: one that is just True or False.
-- This is a proposition which is simply a literal Bool!
instance Prop Bool where
  valid         = id
  contradiction = not
  lequiv b1 b2  = b1 == b2

Here, Prop Bool says that in the expression Prop p above, the type whose behaviour/implementation we're defining is the Bool type. How do we check if a Bool is valid? Well, it takes no arguments, so a proposition that is just True or False is valid if it's true, and otherwise a contradiction.

valid = id says that the function valid mapping our proposition type of Bool to whether or not it's a valid formula is the function id. (This function just returns whatever it's given).
contradiction = not says that the function contradiction mapping the proposition type Bool to whether or not it's a contradiction is the function not. Just as well, because not takes just one Bool as an argument, and returns a Bool. This is compatible with the contract we laid out earlier in the typeclass definition of Prop.
lequiv b1 b2 = (b1 == b2) says that the way of comparing two of these propositions (once again, of type Bool here) for logical equivalence is to simply invoke the already existing method ==.

Inductive Instance Definition - First Step
This is the fun part. We're using induction. Here's the full code snippet, and then I'll break down each line.
instance (Prop p) => Prop (Bool -> p) where
  valid f         = (valid (f True)) && (valid (f False))
  lequiv f g      = (lequiv (f True) (g True)) && (lequiv (f False) (g False))
  contradiction f = (contradiction $ f True) && (contradiction $ f False)

Now the first line says this: (Bool -> p) is of type Prop, as long as the constraints in what we call the context are met. Here the context is what comes before the =>, and what it says is that p, the type, is a member of the Prop typeclass. This means that we're saying that any type which maps a Bool to any type of Prop is itself an instance of Prop. Why are we doing this? Well, let's start with the simplest case.
Bool is an instance of typeclass Prop, because we defined this 'base case' explicitly. Okay, so then (Bool -> Bool) is also of typeclass prop, because we said that any type (Bool -> <something in class Prop>) is in class Prop. This gives us the functions which take in one boolean argument and return a boolean. Examples: not, id, (\a -> True), (\a -> False). (In fact, these are all such functions).
How have we defined whether to determine whether one of these functions is valid? Our definition says that
valid f = (valid (f True)) && (valid (f False))

It says that a boolean function f of one boolean is valid if and only if (f True) and (f False) are both valid. Of course, the validity of boolean is just that boolean. So in this case, valid can be thought of as being a bit simpler:
valid f = (f True) && (f False)

Alright, so f is valid if and only if it evaluates to True for both arguments! That's what we want.
Now for contradiction:
contradiction f = (contradiction $ f True) && (contradiction $ f False)

This is the key: contradiction asks the question "Is this proposition false for all possible inputs"? To test this, we split f into two parts: its first argument and the rest. If the first argument is True, then is it possible to satisfy proposition f with the remaining arguments? If not, then it's a contradiction. This is the part contradiction $ f True.
f True is itself a function of 1 Bool argument, so it is in class Prop, and so we're able to apply contradiction to it to see if it's a contradiction. We also need to be sure that it's not possible to satisfy f if the first argument is False either, which is why we && this with contradiction $ f False.
I'll leave the lequiv function as an exercise, and move on to the next inductive step.
Inductive Instance Definition - Inception
Since (Bool -> Bool) is of class Prop, then so too is Bool -> (Bool -> Bool). I could be mistake, but I'm fairly sure that Bool -> Bool -> Bool is actually just short-hand for this. So this means that a boolean function of two boolean variables is itself a proposition. How do we determine its validity? We check if both f True and f False are valid. The former means 'if f True False and f True True both evaluate to True'.
Hopefully you can see now the recursion that's going on (I haven't done a great job explaining it; sorry)-- what we're doing is recursively defining the validity of the type Bool -> Bool -> .... -> Bool so that such a function is valid if and only if it evaluates to True for all possible inputs.


Checking if a port is in use Review this code, which should return true if a port is in use or false if the port is not in use.

Clarification: "In use" means that the port is already open (and used by another application). I'm trying to find a port number between (49152 and 65535) to open that is available.

private boolean isPortInUse(String hostName, int portNumber) {
        boolean result;

        try {

            Socket s = new Socket(hostName, portNumber);
            s.close();
            result = true;

        }
        catch(Exception e) {
            result = false;
        }

        return(result);
}

Don't test for port-in-use in advance. Just let your application do what it wants to do, and catch the exception there. The situation can change between the time you test and when you actually try to use the port.

Furthermore, if you are trying to write a server application, you can have Java automatically pick a free port for you.  From the JavaDoc for ServerSocket(int):

  Creates a server socket, bound to the specified port. A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.


Shortest path in maze Please help review my code.

public class Maze {
    // question: give a maze. Find shortest path from left top corner to right bottom corner.
    // 1 is wall. cannot go thru.
    int minFoundLen = Integer.MAX_VALUE;
    int m = 0;
    int n = 0;
    public void findPath(int[][] mazePlan){
        if(mazePlan.length == 0) return;

        m = mazePlan.length;
        n = mazePlan[0].length;
        int[][] path = new int[m][n];

        helper(mazePlan, 0, 0, 0,path);
        System.out.println("shortest path is " + minFoundLen);
    }

    private void helper(int[][] maze, int x, int y, int pathLen,int[][] path){
        if(x < 0 || y < 0 || x >= m || y >= n){
            return;
        }
        if(path[x][y]!=0){
            return;
        }
        if(maze[x][y] != 0){
            return;
        }
        if(x == m-1 && y == n-1){
            minFoundLen = Math.min(minFoundLen, pathLen);
            return;
        }
        path[x][y] = 1;
        helper(maze, x+1,y,pathLen+1,path);
        helper(maze, x-1,y,pathLen+1,path);
        helper(maze, x,y+1,pathLen+1,path);
        helper(maze, x,y-1,pathLen+1,path);
        path[x][y] = 0;

    }
    public static void main(String[] args){
        int[][] mazePlan = {
        {0,1,0,0,0},
        {0,0,0,1,0},
        {0,0,0,0,0},
        {1,1,1,0,0},
        {0,0,0,0,0}
        };

        Maze maze = new Maze();
        maze.findPath(mazePlan);
    }
}

1 Algorithm

This is not Dijkstra's algorithm and that is not breadth-first search either. It's an unweighted brute-force shortest path algorithm. Basically, you generate all possible paths from the source node (top-left cell) to the target node (bottom-right) cell.

On my machine (2.5 GHz) the following maze takes about 300 milliseconds to solve:

int[][] mazePlan = {
    {0,1,0,0,0,0,0,0},
    {0,0,0,1,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {1,1,1,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
};

2 Coding

You should rename the fields minFoundLen, n and  m to something like shortestPathLengthSoFar mazeHeight and mazeWidth, respectively. Also, you do not have to initialize m and n to zero; Java initializes integer fields to zero by default.

Taking into consideration what you do with int[][] path, I suggest you rename it to boolean[][] visited.

System.out.println("shortest path is " + minFoundLen);

It's not funky to print the result of an algorithm to standard output; instead, return the actual result, and let the caller of the algorithm do whatever he/she wants.

You can always store maze and visited in the fields of your object; that way, helper asks only three arguments instead of five.

if(path[x][y]!=0){
    return;
}

There should be one space before and after a binary operator.
There should be one space before and after a parenthesized expression.

So, combining the two above points you should rather write:

if (path[x][y] != 0) {
    return;
}

You should also separate "logical blocks" by a single empty line; like this:

    if (maze[x][y] != 0) {
        return;
    }

    if (x == m - 1 && y == n - 1) {
        minFoundLen = Math.min(minFoundLen, pathLen);
        return;
    }

    path[x][y] = 1;

    helper(maze, x + 1, y, pathLen + 1, path);
    helper(maze, x - 1, y, pathLen + 1, path);
    helper(maze, x, y + 1, pathLen + 1, path);
    helper(maze, x, y - 1, pathLen + 1, path);

    path[x][y] = 0;

And don't forget that you should have a space after any comma.

3 Alternative impelmentation

I have gathered all the points and used breadth-first search for solving the maze. That it how it might look:

Maze.java:

import java.awt.Point;
import java.util.List;
import java.util.Objects;

public class Maze {

    private static final boolean CELL_OCCUPIED = true;

    private final boolean[][] maze;

    public Maze(final boolean[][] maze) {
        Objects.requireNonNull(maze, "The input maze is null.");

        final int numberOfRows = maze.length;

        if (numberOfRows == 0) {
            throw new IllegalArgumentException("The input maze is empty.");
        }

        int numberOfColumns = 0;

        for (int row = 0; row < maze.length; ++row) {
            numberOfColumns = Math.max(numberOfColumns, maze[row].length);
        }

        this.maze = new boolean[numberOfRows][numberOfColumns];

        for (int row = 0; row < numberOfRows; ++row) {
            for (int column = 0;
                     column < Math.min(numberOfColumns, maze[row].length);
                     column++) {
                this.maze[row][column] = maze[row][column];
            }
        }
    }

    public int getWidth() {
        return maze[0].length;
    }

    public int getHeight() {
        return maze.length;
    }

    public boolean cellIsFree(final Point p) {
        return cellIsFree(p.x, p.y);
    }

    public boolean cellIsWithinMaze(final Point p) {
        return p.x >= 0 && p.x < getWidth() && p.y >= 0 && p.y < getHeight();
    }

    public boolean cellIsTraversible(final Point p) {
        return cellIsWithinMaze(p) && cellIsFree(p);
    }

    public boolean cellIsFree(final int x, final int y) {
        checkXCoordinate(x);
        checkYCoordinate(y);
        return maze[y][x] != CELL_OCCUPIED;
    }

    public String withPath(final List<Point> path) {
        final char[][] matrix = new char[getHeight()][getWidth()];

        for (int i = 0; i < matrix.length; ++i) {
            for (int j = 0; j < matrix[0].length; ++j) {
                matrix[i][j] = maze[i][j] ? 'x' : '.';
            }
        }

        for (final Point p : path) {
            matrix[p.y][p.x] = 'o';
        }

        final StringBuilder sb = new StringBuilder();

        sb.append(new String(matrix[0]));

        for (int i = 1; i < matrix.length; ++i) {
            sb.append('\n');
            sb.append(new String(matrix[i]));
        }

        return sb.toString();
    }

    private void checkXCoordinate(final int x) {
        if (x < 0) {
            throw new IndexOutOfBoundsException(
                    "The x-coordinate is negative: " + x + ".");
        }

        if (x >= maze[0].length) {
            throw new IndexOutOfBoundsException(
                    "The x-coordinate is too large (" + x +
                    "). The amount of columns in this maze is " +
                    maze[0].length + ".");
        }
    }

    private void checkYCoordinate(final int y) {
        if (y < 0) {
            throw new IndexOutOfBoundsException(
                    "The y-coordinate is negative: " + y + ".");
        }

        if (y >= maze.length) {
            throw new IndexOutOfBoundsException(
                    "The y-coordinate is too large (" + y +
                    "). The amount of rows in this maze is " +
                    maze.length + ".");
        }
    }
}

MazePathFinder.java:

package review;

import java.awt.Point;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;

public class MazePathFinder {

    private Maze maze;
    private Point source;
    private Point target;
    private boolean[][] visited;
    private Map<Point, Point> parents;

    public MazePathFinder() {}

    private MazePathFinder(final Maze maze,
                           final Point source,
                           final Point target) {
        Objects.requireNonNull(maze, "The input maze is null.");
        Objects.requireNonNull(source, "The source node is null.");
        Objects.requireNonNull(target, "The target node is null.");

        this.maze = maze;
        this.source = source;
        this.target = target;

        checkSourceNode();
        checkTargetNode();

        this.visited = new boolean[maze.getHeight()][maze.getWidth()];
        this.parents = new HashMap<>();
        this.parents.put(source, null);
    }

    public List<Point> findPath(final Maze maze,
                                final Point source,
                                final Point target) {
        return new MazePathFinder(maze, source, target).compute();
    }

    private List<Point> compute() {
        final Queue<Point> queue = new ArrayDeque<>();
        final Map<Point, Integer> distances = new HashMap<>();

        queue.add(source);
        distances.put(source, 0);

        while (!queue.isEmpty()) {
            // Removes the head of the queue.
            final Point current = queue.remove();

            if (current.equals(target)) {
                return constructPath();
            }

            for (final Point child : generateChildren(current)) {
                if (!parents.containsKey(child)) {
                    parents.put(child, current);
                    // Appends 'child' to the end of this queue.
                    queue.add(child);
                }
            }
        }

        // null means that the target node is not reachable
        // from the source node.
        return null;
    }

    private List<Point> constructPath() {
        Point current = target;
        final List<Point> path = new ArrayList<>();

        while (current != null) {
            path.add(current);
            current = parents.get(current);
        }

        Collections.<Point>reverse(path);
        return path;
    }

    private Iterable<Point> generateChildren(final Point current) {
        final Point north = new Point(current.x, current.y - 1);
        final Point south = new Point(current.x, current.y + 1);
        final Point west = new Point(current.x - 1, current.y);
        final Point east = new Point(current.x + 1, current.y);

        final List<Point> childList = new ArrayList<>(4);

        if (maze.cellIsTraversible(north)) {
            childList.add(north);
        }

        if (maze.cellIsTraversible(south)) {
            childList.add(south);
        }

        if (maze.cellIsTraversible(west)) {
            childList.add(west);
        }

        if (maze.cellIsTraversible(east)) {
            childList.add(east);
        }

        return childList;
    }

    private void checkSourceNode() {
        checkNode(source,
                  "The source node (" + source + ") is outside the maze. " +
                  "The width of the maze is " + maze.getWidth() + " and " +
                  "the height of the maze is " + maze.getHeight() + ".");

        if (!maze.cellIsFree(source.x, source.y)) {
            throw new IllegalArgumentException(
                    "The source node (" + source + ") is at a occupied cell.");
        }
    }

    private void checkTargetNode() {
        checkNode(target,
                  "The target node (" + target + ") is outside the maze. " +
                  "The width of the maze is " + maze.getWidth() + " and " +
                  "the height of the maze is " + maze.getHeight() + ".");

        if (!maze.cellIsFree(target.x, target.y)) {
            throw new IllegalArgumentException(
                    "The target node (" + target + ") is at a occupied cell.");
        }
    }

    private void checkNode(final Point node, final String errorMessage) {
        if (node.x < 0
                || node.x >= maze.getWidth()
                || node.y < 0
                || node.y >= maze.getHeight()) {
            throw new IllegalArgumentException(errorMessage);
        }
    }

    public static void main(String[] args) {
        int[][] mazePlan = {
            {0,1,0,0,0,0,0,0},
            {0,0,0,1,0,0,0,0},
            {0,0,0,0,0,0,0,0},
            {1,1,1,0,0,0,0,0},
            {0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0},
        };

        boolean[][] maze2 = new boolean[mazePlan.length][mazePlan[0].length];

        for (int i = 0; i < maze2.length; ++i) {
            for (int j = 0; j < maze2[i].length; ++j) {
                maze2[i][j] = mazePlan[i][j] > 0;
            }
        }

        final Maze maze = new Maze(maze2);
        final Point source = new Point(); // Same as new Point(0, 0):
        final Point target = new Point(7, 5);

        long startTime = System.nanoTime();
        final List<Point> path = new MazePathFinder().findPath(maze,
                                                               source,
                                                               target);
        long endTime  = System.nanoTime();

        System.out.printf("BFS maze finder in %d milliseconds.\n",
                          (endTime - startTime) / 1_000_000L);

        System.out.println("Shortest path length: " + (path.size() - 1));
        System.out.println(maze.withPath(path));
    }
}

Hope that helps.


Longest carbon chain My Code measures the longest path, not allowing cycles. For the example input below, the longest chain would be 4

Please can you review my code?

import numpy as np
inputgrid = np.array([['.','.','.','.','.'],
                      ['C','-','C','-','C'],
                      ['.','.','|','.','.'],
                      ['.','.','C','.','.'],
                      ['.','.','|','.','.'],
                      ['.','.','C','.','.'],
                      ['.','.','.','.','.']])# This Is Input

inputgrid = np.where(inputgrid=='.', 0, inputgrid)
inputgrid = np.where(inputgrid=='C', 1, inputgrid)
inputgrid = np.where(inputgrid=='-', 9, inputgrid)
inputgrid = np.where(inputgrid=='|', 9, inputgrid)

np.array(inputgrid).tolist()

grid = [[int(item) for item in row] for row in inputgrid]

def display(grid):
    for row in grid:
      print(row)

display(grid)

lst = []
for rows, row in enumerate(grid):
    for cols, col in enumerate(row):
        if grid[rows][cols] in [1]:
            lst.append((rows, cols))

bondlst = []
for rows, row in enumerate(grid):
    for cols, col in enumerate(row):
        if grid[rows][cols] in [9]:
            bondlst.append((rows, cols))

print(lst)
print(bondlst)

bondx = []
bondy = []

for item in bondlst:
    (bondx).append(item[0])
    (bondy).append(item[1])

print(bondx)
print(bondy)

adjacencylist = []

def adjacentnode(nodea ,nodeb):
    if nodea[0] == nodeb[0] and nodea[1] == nodeb[1]+2:
        adjacent = True
    elif nodea[0] == nodeb[0] and nodea[1] == nodeb[1]-2:
        adjacent = True
    elif nodea[1] == nodeb[1] and nodea[0] == nodeb[0]+2:
        adjacent = True
    elif nodea[1] == nodeb[1] and nodea[0] == nodeb[0]-2:
        adjacent = True
    else:
        adjacent = False
    return adjacent

print (adjacentnode((1,0),(1,2)))

count = 0

tempgraph = {}
for node in range(len(lst)):
    print (node)
    adjacencylist.append((lst[node] ,[]))
    for neighbour in range(len(lst)):
        adjacentnodes = (adjacentnode(lst[node] ,lst[neighbour]))
        print(adjacentnodes)
        if adjacentnodes == True:
            count = count +1
            adjacencylist[node][1].append(lst[neighbour])
            # adjacencylist.append((lst[node],[]))
            # adjacencylist.append(lst[node])
            # adjacencylist.append(lst[neighbour])

print (count)
print (adjacencylist)

for item in adjacencylist:
    tempgraph[str(item[0])] = (item[(1)])

carbongraph = {}
for i in tempgraph:
    carbongraph[i] = [str(k) for k in tempgraph[i]]

print(carbongraph)

#print(adjacencylist)

#print (carbongraph)
'''
carbongraph = {'(0, 1)' :['(0, 2)'], '(0, 2)' :['(0, 1)' ,'(0, 3)' ,'(1, 2)'],
               '(0, 3)' :['(0, 2)'], '(1, 2)' :['(0, 2)', '(2, 2)'], '(2, 2)': ['(1, 2)']}

WEIGHTS = 1
'''
def shortestpath(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if start not in graph:
        return None
    for node in graph[start]:
        if node not in path:
            newpath = shortestpath(graph, node, end, path)
            if newpath:
                return newpath
    return None

LeafArray = []
for leaf in carbongraph:
    degree = (len(carbongraph[leaf]))
    if degree == 1:
        LeafArray.append(leaf)

print(LeafArray)

chainlist = []
for node in LeafArray:
    for neighbour in LeafArray:
        currentpath = (shortestpath(carbongraph, node, neighbour))
        carbonchain = len(currentpath)
        print(currentpath)
        chainlist.append(carbonchain)

longestchain = max(chainlist)
print(longestchain)

def Prfix():
    global prefix
    if longestchain == 4:
        prefix = "But"
    elif longestchain == 5:
        prefix = "Pent"
    elif longestchain == 6:
        prefix = "Hex"
    elif longestchain == 7:
        prefix = "Hept"
    elif longestchain == 8:
        prefix = "Oct"
    return prefix

print(Prfix())
```


Displaying separated multi-line text fields The following code grabs the HTML-encoded, multi-line content of a text field. It then splits the content on line breaks, and finally displays it with commas as separators.

I would like to have this code reviewed to see if there is a simpler way to grab the string, split and display it.

Note - I hated the idea of writing 2 collection iterations, but I found if a user in the CMS entered one line of real data, and then a couple of empty line breaks, it would throw the array length off and display a comma on a single item e.g. output should look like this :

Correct: Allowed Uses: example 1 | Allowed Uses: example 1, example 2
Incorrect: Allowed Uses: example 1, | Allowed Uses: example 1, example 2,

  var retailBreaks = umbraco.library.ReplaceLineBreaks(Model.landAllowedUses);
  string[] retailBreaksSplit = retailBreaks.Split(new string[] { "
" }, StringSplitOptions.RemoveEmptyEntries);
  int breaksLength = 0;
  List<String> repeatableProperty = new List<String>();
  foreach (string s in retailBreaksSplit)
  {
    if (!string.IsNullOrWhiteSpace(s))
       {
         repeatableProperty.Add(s);
       }
  }
 breaksLength = repeatableProperty.Count();

    Allowed Uses:

    @foreach (string s in repeatableProperty)
    {
     @s.Trim()@((breaksLength > 1 && repeatableProperty.Last<string>() != s) ? ", " : string.Empty)
    }

Just do a string replace to swap the html breaks for commas, then trim the end to remove any extra commas:

retailBreaks.Replace("<br/>",",").TrimEnd(',')


Pivot script for sales numbers I've recently been tasked with migrating some code stacks for an applicatin that is moving from using Access to using SQL-Server.

I don't usually use PIVOT all that much, and most of my code is scripting intended for in-house administration of our SQL Servers. As such my code is not that great.

How could I clean up this code, and make it easier to maintain? My main concern is, I want this simpler, but how?

USE [Database1]
GO
SELECT
       Region,
       Year,
       Month,
       SalesPersonNR,
       (ISNULL(SUM(SalesA),0) + ISNULL(SUM(SalesB),0) + ISNULL(SUM(SalesC),0) + ISNULL(SUM(Sales),0) + ISNULL(SUM(NA),0)) AS Total,
       SUM(Sales) Sales,
       SUM(SalesA) SalesA,
       SUM(SalesB) SalesB,
       SUM(SalesC) SalesC
FROM
(
SELECT
       Region,
       Year,
       Month,
       SalesPersonNR,
       COUNT(SalesNumber) as total,
       expr1
FROM (
       SELECT A.Region,
       Year([Date]) AS Year,
       Month([Date]) AS Month,
       A.SalesPersonNR,
       A.SalesNumber AS SalesNumber,
       CASE
             WHEN B.DateSalesC IS NOT NULL THEN 'SalesC'
             WHEN B.DateSalesB IS NOT NULL THEN 'SalesB'
             WHEN B.DateSalesA IS NOT NULL THEN 'SalesA'
             WHEN B.DateSales IS NOT NULL THEN 'Sales'
             ELSE 'NA'
       END AS expr1
FROM [Table1] A
       JOIN [Table2] B
       ON A.SalesNumber = B.SalesNumber
WHERE
       A.Status = 99
       ) Internal
GROUP BY
       Region,
       Year,
       Month,
       SalesPersonNR,
       expr1
) AS x
PIVOT
(
       SUM(Total)
       FOR expr1 IN (SalesC, SalesB, SalesA, Sales, NA)
       ) AS y
GROUP BY
Region,
Year,
Month,
SalesPersonNR

A few things that I noticed:

Nesting

You're nesting selects two levels deep. That's usually a bad sign for most of the data mining and report generation I had to do. You might be able to get rid of the innermost Select with some clever thinking.

This may greatly improve performance for that query.

Use a CTE

You can possibly simplify the second select into a "Common Table Expression" (CTE) like so:

WITH (SELECT
    Region
    , Year
    , Month
    , SalesPersonNR
    , COUNT(SalesNumber) as total
    , expr1
FROM  -- ...

Formatting

As you may have noticed above I personally prefer the leading comma style for column specifications. I find it easier to maintain, because you can just delete a single row and can be sure the SELECT (or whatever else) is still valid.

Additionally I strongly recommend you indent your Statements according to the level of nesting they're in.

Usually I follow the folllowing structure

SELECT col1
    , col2
FROM tableName
JOIN otherTable ON tableName.id = otherTable.foreign
WHERE condition
    && condition
HAVING condition
    || condition
GROUP BY col1
    , col2
ORDER BY col1

Any time you increase the level of nesting, I'd increase the indent, too, to make it easier to follow.

Naming

Your table aliases are .. suboptimal. I assume this may be because you anonymized them, but A and B are really not great table names.

Same applies to expr1 and x

Magic numbers

What's the idea behind Status 99? If I read that query I have no idea which sales you're actually selecting. Drop a comment there (or even run a self-documenting select onto a named table)


Checking all elements against each other for elements strictly worse Consider the following function:

def test_func(all_copies, checker):
    bad_copies = set(c[0] for c in itertools.permutations(all_copies, 2) if not checker(*c))
    all_copies = [c for c in all_copies if c not in bad_copies]
    return all_copies

This function returns a list of elements that are not overshadowed by any other element. Considering the checker:

def checker(l, r):
    return l[0] < r[1] or l[1] < r[1]

and the input:

all_copies = [(2,3)(2,2),(3,3),(3,1),(1,3),(4,1)]

This will return:

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

Now this works in 3 steps:

First itertools.permutations creates all combinations to check against. Secondly set() - because it can only contain one of each element is basically an "any". And any(not(x)) is basically the complement of all(x). So if an element turns "strictly worse" against any other element it is added to the "bad_copies".
Finally the last line selects all elements that are not bad copies.

Now this seems nice, but it basically performs the check n2 - n times. And the takes another O(n) to create the list.

Can I optimize this? Can the code become more clear and direct?

A more elaborate function that does the same thing is (can this be optimized using list comprehensions):

def test_func(all_copies):
    out = []
    for i in all_copies:
        add = True
        for j in all_copies:
            if i != j:
                if not check_post(i,j):
                    add = False
        if add:
            out.append(i)
    return out

Disclaimer: this is not a review but an extended comment.

You surely can optimize. The problem you are trying to solve is known as finding a non-dominated set, and allows a best case of \$O(n \log n)\$ solution; worst case is of course \$O(n^2)\$. You may want to start here.


Script to push data from one database via api to another I'm still a beginner so any pointers to make this code more professional/production ready are appreciated. The tokens and database connections have been anonymized.
The script is working, its goal is to copy prices from one database and push them via api into another database.
This data is monthly price data that usually arrives early in the month. So march prices arrive somewhere early march, but usually not on the first. They are then supposed to be pushed to the destination database via rest api.

The catch is that we never know when the prices arrive in the source database, so the idea is to run this script daily via task scheduler and only push the data to the destination database once when they arrive, but we have to make sure that the data is not pushed twice and duplicates are created.
I achieved this by only pushing when the data is in the source database, but not yet in the destination databse via IF check.

I feel like this code is not very pythonic and lacking some possible error catchings for it to be ran automatically on a daily basis. Any pointers are appreciated.

import json
import pandas as pd
import pyodbc
import sqlalchemy
import datetime
import sys
import requests
import pdb
import pymysql

#RPA API Connector
target_url = "exampleurl"
target_token = "exampletoken"
target_headers = {"AUTH-TOKEN": target_token, "Content-Type": "application/json"}

#Store todays date in variable
now = datetime.datetime.now()

#connecting to source DB
def connect_mssqlserver():
    engine_stmt = ("mssql+pyodbc://@server/database?driver=SQL+Server")
    engine = sqlalchemy.create_engine(engine_stmt)
    engine.connect()
    return engine
#connect to destination DB
def connect_mysqlserver():
    engine_stmt = ('mysql+pymysql://user:password@server:host/database')
    engine = sqlalchemy.create_engine(engine_stmt)
    engine.connect()
    return engine
def create_df(query, engine):
    #save table to df
    df = pd.read_sql(query, engine)
    return df

#store source data in df
source_df = create_df("SELECT * FROM PriceMonthly", connect_mssqlserver())
#Some dataframe modification to fit destination format
source_df = source_df[source_df.Year == now.year]
source_df['Tax'].fillna(0, inplace=True)
source_df['Year'] = source_df['ImportFileName'].str[0:4].astype(int)
source_df['Month'] = source_df['ImportFileName'].str[4:6].astype(int)

#store destination table in dataframe
dest_df = create_df("SELECT * FROM prices", connect_mysqlserver())
#Filter both dataframes by current year and month
source_df = source_df[(source_df.Year == now.year) & (source_df.Month == now.month)]
dest_df = dest_df[(dest_df.Year == now.year) & (dest_df.Month == now.month)]

#Logic to check if data is in source and not yet in destination, only then push via api
if source_df.empty == False and dest_df.empty == True:
    print('Data will be pushed')
    data = source_df.to_json(orient = "records")
    data = json.loads(data)
#This loop is used for chunking as API times out when pushing a lot of data at the same time
    url = 'price'
    j = 0
    i = 400
    length = len(data)
    while j <= length:
        print(j,i)
        data2 = data[j:i]
        target_response = requests.put(target_url + url + "/json", json=data2, headers=target_headers)
        assert target_response.status_code == 200, f"{target_url + url} -> Expected 200, but received {target_response.status_code}"
        j = i
        i = i+400
elif dest_df.empty == False:
    print("Data Already At Destination")
elif source_df.empty == True:
    print("No Data In Source")
else:
    print("issue")

A few notes on your code above:

connect_mssqlserver and connect_mysqlserver could be condensed to a single 'connect' function that takes a conn_str arg to be used in create_engine.
I believe create_df seems to be unnecessary at this point. If the process for creating the df involves more than just calling read_sql in the future, then I would opt for moving that logic into a separate function.
nitpick: I would change source_df.empty == False and the following True check to just not source.empty and dest_df.empty


Project Euler 357 prime number generator in Python 3 I'm brute forcing the Project Euler 357 since no better algorithm comes to my mind. The challenge asks:

  Find the sum of all positive integers n not exceeding 108 such that for every divisor d of n, d+n/d is prime.

The code is this:

#!/bin/env python3

import time
import math

"""
https://projecteuler.net/problem=357

"""

start = time.time()

def primes(ubound=10**5):
    """ Generating prime numbers LIST
        https://stackoverflow.com/a/8627193/1770460
    """
    size = (ubound - 3) // 2
    a = [False] * size
    s = 0
    primes = []
    while s < size:
        t = 2 * s
        p = t + 3
        primes.append(p)
        for n in range(t * (s + 3) + 3, size, p):
            a[n] = True
        s = s + 1
        while s < size and a[s]:
            s = s + 1
    return primes

the_primes = primes()

def number_divisors(max_limit=10**5):
    """ Find the divisors of every number.
        Return it in a dict in the format:
        { number1: [divisor1, divisor2 ... ], .. }
    """
    num_divs = {}
    for i in range(4, max_limit):
        if i in the_primes:
            continue
        else:
            sq = math.sqrt(i)
            for n in range(2, int(sq) + 1):
                if i not in num_divs:
                    num_divs[i] = [1]
                if i % n == 0:
                    if n == i / n:
                        num_divs[i].append(n)
                    else:
                        num_divs[i].extend((n, i / n))
    return num_divs

def find_count(d):
    """ Check every number whether the divisors i.e. d + number / d is
        prime.
    """
    assert d is not None

    count = 0
    for number, list_divisors in d.items():
        all_primes = True
        for each_div in list_divisors:
            val = (each_div + (number / each_div))
            if val not in the_primes:
                all_primes = False
                break
        if all_primes:
            count += 1
    return count

if __name__ == '__main__':

    num_divisors = number_divisors()
    print(find_count(num_divisors))

    elapsed_time = (time.time() - start)
    print('time elapsed %s sec.' % elapsed_time)

Profiling the script shows that the find_count is the first bottleneck and by advice of other answers the values should be cached(?) somehow.

$ python3 -m cProfile 357.py
275
time elapsed 167.41558241844177 sec.
         583580 function calls in 167.416 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000  167.416  167.416 357.py:3(<module>)
        1    0.020    0.020    0.020    0.020 357.py:30(primes)
        1   24.526   24.526   24.740   24.740 357.py:51(number_divisors)
        1  142.655  142.655  142.655  142.655 357.py:75(find_count)

Any advice on how to improve find_count()?

The most obvious improvement is to notice that if i in the_primes and if val not in the_primes both take \$\mathcal{O}(n)\$ time. If you made the_primes a set instead of a list it would only be \$\mathcal{O}(1)\$. So just write:

the_primes = set(primes())

Also note that your "prime number generator" is not actually a Python generator. For that you would need to add a yield:

def primes(ubound=10**5):
    """ Generating prime numbers https://stackoverflow.com/a/8627193/1770460 """
    size = (ubound - 3) // 2
    a = [False] * size
    s = 0
    while s < size:
        t = 2 * s
        p = t + 3
        yield p
        for n in range(t * (s + 3) + 3, size, p):
            a[n] = True
        s = s + 1
        while s < size and a[s]:
            s = s + 1

The set() call will then consume the generator. This will not make your code run faster, though (it needs about the same CPU) It might save you some memory, because you don't need the conversion from the internal list to the external set.

Your original code takes about 43.5s on my machine. With the two changes in this post this drops down to less than 1.7s:

$ python3 -m cProfile 357.py
275
time elapsed 1.6228196620941162 sec.
         583585 function calls in 1.623 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   ...
     9592    0.011    0.000    0.011    0.000 euler_357.py:14(primes)
        1    0.001    0.001    1.623    1.623 euler_357.py:3(<module>)
        1    1.524    1.524    1.584    1.584 euler_357.py:34(number_divisors)
        1    0.026    0.026    0.026    0.026 euler_357.py:56(find_count)
   ...


Is this right way to implement Abort, Retry and Ignore activity pattern? I've a bunch of sequential activities. These are long running. Once an activity is complete, it can't be rolled back. Now something deep down the line fails. Now I've few options

Report this to end user and ask him to fix something. And then Retry same thing.
End user has no clue on what to do. He can choose to ignore. (Just retry won't fix things)
Abort/Pause? Now this is something tricky. This will stop the program. If program is rerun, it should resume from this failed point and not from the starting point.

I'm thinking to implement this by defining a custom exception, Action delegate set, coming from exception object. So my question is
Do you see any issue with this pattern? Any better way to do the same?

[Serializable]
public class SafetyNetException : Exception
{
    public SafetyNetException(SafetyNet callBack) { Net = callBack; }
    public SafetyNetException(SafetyNet callBack, string message) : base(message) { Net = callBack; }
    public SafetyNetException(SafetyNet callBack, string message, Exception inner) : base(message, inner) { Net = callBack; }
    protected SafetyNetException(
      System.Runtime.Serialization.SerializationInfo info,
      System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }

    public SafetyNet Net { get; private set; }
}

public class SafetyNet
{
    public Action Abort;

    public Action Retry;

    public Action Ignore;
}

[TestClass()]
public class SafetyNetTest
{
    [TestMethod()]
    public void APIUsageTest()
    {
        try
        {
            DoSomething();
        }
        catch (SafetyNetException targetException)
        {
            Debug.WriteLine(targetException.Message);

            SafetyNet target = targetException.Net;
            switch (AskUser())
            {
                case "r":
                    target.Retry();
                    break;
                case "a":
                    target.Abort();
                    break;
                case "i":
                    target.Ignore();
                    break;
            }
        }
    }

    private void DoSomething()
    {
        try
        {
            // try something
        }
        catch (Exception ex)
        {
            SafetyNet net = new SafetyNet();
            net.Abort = () => DoSomething_Abort();
            net.Retry = () => DoSomething();
            net.Ignore = () => DoNextThing();

            throw new SafetyNetException(net, "Ask user", ex);
        }
    }

You really shouldn't be using exceptions to control the flow of your program's logic. What you're trying to do tends to work much better as a simple state machine that, when it fails, asks whoever is listening what it should do and responds accordingly. Here's a very rough example (which hasn't been tested, is not threadsafe, etc).

public interface ISequentialActivity
{
    bool Run();
}

public enum UserAction
{
    Abort,
    Retry,
    Ignore
}

public class FailureEventArgs
{
    public UserAction Action = UserAction.Abort;
}

public class SequentialActivityMachine
{
    private Queue<ISequentialActivity> activities = new Queue<ISequentialActivity>();
    public event Action<FailureEventArgs> OnFailed;
    protected void PerformOnFailed(FailureEventArgs e)
    {
        var failed = this.OnFailed;
        if (failed != null)
            failed(e);
    }
    public void Add(ISequentialActivity activity) { this.activities.Enqueue(activity); }
    public void Run()
    {
        while (this.activities.Count > 0)
        {
            var next = activities.Peek();
            if (!next.Run())
            {
                var failureEventArgs = new FailureEventArgs();
                PerformOnFailed(failureEventArgs);

                if (failureEventArgs.Action == UserAction.Abort)
                    return;
                if (failureEventArgs.Action == UserAction.Retry)
                    continue;
            }

            activities.Dequeue();
        }
    }
}

In this example, classes would encapsulate sections of retry-able logic by implementing ISequentialActivity, returning true from their Run() method if they succeeded and false if they failed in some way. Failure would then be pushed up to the listener through the event for decision making.


A few notes:  (I implemented this in Octave, so there may be differences between my code and a proper Matlab implementation, but there shouldn't be).

First we care about only unique dates, right?  So lets grab
indices for their groupings.  I'm assuming this original data is
stored in the matrix A.

[X, y, z] = unique(A(:, 4))

Now z is the only value I used from this output, so you could
ignore the other returns by putting ~ in their place.
Second, let's split out data up based on these groups.  We can use
the function accumarray() to accomplish this nicely.  If we
pass in the function handle @max to it, it'll even find the max
within these groups.

B = accumarray(z, A(:, 1), [], @max)

There is some trick to get each row corresponding to that maximum value based on the z parameter, but after investigating this for a few hours I still haven't figured it out and have given up.  You could try using find() to get these rows instead, using z to make sure we are grabbing the right values.


Predicting the next pseudorandom value The archived material for the Stanford University course on cryptography at coursera.org includes a problem where you have to predict the next output of a weak PRG. It can be briefly restated as follows:

  $$\begin{align*}
                   P =&\ 295075153 \\
                 z_n =&\ x_n \oplus y_n,\qquad \textrm{where}\ 0 \le x_0, y_0 \lt P\ \textrm{(unknown random integers)} \\
             x_{n+1} =& (2x_n + 5) \mod P \\
             y_{n+1} =& (3y_n + 7) \mod P \\
(z_0, z_1, ..., z_8) =& (210205973, 22795300, 58776750, \\
                      &\ \ 121262470, 264731963, 140842553, \\
                      &\ \ 242590528, 195244728, 86752752) \\
                 z_9 =& ???
\end{align*}$$

I wrote a small program in C to solve this by brute force, and it finds a solution in just over 2 seconds:

#include <stdio.h>
#define P 295075153L

int main() {
  long seq[] = { 210205973, 22795300, 58776750, 121262470, 264731963,
                 140842553, 242590528, 195244728, 86752752 };
  long i, x, y, x0, y0;

  for (x0=0; x0<P; x0++) {   /* Try every value of x_0 */
    y0 = seq[0] ^ x0;        /* Calculate y_0 from x_0 */
    for (x=x0,y=y0,i=1; i<9; i++) {
      x = (2 * x + 5) % P;   /* Iterate PRG and check values */
      y = (3 * y + 7) % P;
      if ((x ^ y) != seq[i]) break;
    }
    if (i==9) {
      printf ("Solution found: x0=%ld, y0=%ld\n",x0, y0);
      for (x=x0,y=y0,i=1; i<10; i++) {
        x = (2 * x + 5) % P;
        y = (3 * y + 7) % P;
      }
      printf("Next value: %ld\n",x^y);
      return 0;
    }
  }
  puts("No solution found");
  return 0;
}

I also tried to solve this problem in Python, but ran into two problems:

Although it does find the same solution, it takes about 3½ minutes to do so. This means it is about a hundred times slower than the C program. Surely this can't be right?
I'm also not happy with the way I'm checking for a match with the sequence values. In the C code, i is incremented at the end of each for() loop iteration, so when i==9 I can be sure that every value was matched successfully. But this incrementing happens somewhere else in Python, so instead I have to check for i==8 and will report a successful match even if the last comparison fails. How can I do this properly?

from itertools import count

seq = [210205973,22795300,58776750,121262470,264731963,
       140842553,242590528,195244728,86752752]
P = 295075153L
for x0 in count():   # better than range(0,P), which is **extremely** slow
    if x0==P:
        break
    y0 = seq[0] ^ x0
    x, y = x0, y0
    for i in range(1,9):
        x = (2 * x + 5) % P
        y = (3 * y + 7) % P
        if (x ^ y) != seq[i]:
            break
    if i==8:        # will be true even if seq[8] not matched :-(
        break

if i==8:
    print "Solution found: x0=%d, y0=%d" % (x0,y0)
    x, y = x0, y0
    for i in range(1,10):
        x = (2 * x + 5) % P
        y = (3 * y + 7) % P
    print "Next value: %d" % (x ^ y)
else:
    print "No solution found"

There are a few code issues that tools like flake will pick up on, but I'll just focus on performance.

First up, switching to pypy reduces the runtime on my machine from ~3 minutes to 16 seconds.

⚡ time pypy orig.py
Solution found: x0=89059908, y0=164204369
Next value: 231886864
pypy orig.py  15.79s user 0.07s system 99% cpu 15.915 total

Removing the L gives us another drastic speedup:

⚡ diff orig.py orig2.py
5c5
< P = 295075153L
---
> P = 295075153

⚡ time pypy orig2.py
Solution found: x0=89059908, y0=164204369
Next value: 231886864
pypy orig2.py  3.93s user 0.04s system 99% cpu 3.988 total

Changing the control flow gives us a smaller boost

def solve():
    seq = [210205973, 22795300, 58776750,
           121262470, 264731963, 140842553,
           242590528, 195244728, 86752752]
    P = 295075153
    for x0 in xrange(0, P):
        y0 = seq[0] ^ x0
        x, y = x0, y0
        for i in xrange(1, 9):
            x = (2 * x + 5) % P
            y = (3 * y + 7) % P
            if (x ^ y) != seq[i]:
                break
            if i == 8:
                print "Solution found: x0=%d, y0=%d" % (x0, y0)
                x, y = x0, y0
                for i in xrange(1, 10):
                    x = (2 * x + 5) % P
                    y = (3 * y + 7) % P
                print "Next value: %d" % (x ^ y)
                return
    print "No solution found"

solve()

⚡ time pypy orig3.py
Solution found: x0=89059908, y0=164204369
Next value: 231886864
pypy solve.py  2.60s user 0.03s system 99% cpu 2.633 total

Which gets us very close to the C solution

⚡ time ./a.out
Solution found: x0=89059908, y0=164204369
Next value: 231886864
./a.out  2.36s user 0.01s system 99% cpu 2.369 total

Forgot to compile with optimisations, which puts the Python version ~6x slower than C:

⚡ time ./a.out
Solution found: x0=89059908, y0=164204369
Next value: 231886864
./a.out  0.44s user 0.00s system 99% cpu 0.448 total


Add "1" and overwrite the previous value I have a cookie where a number is stored.
When I want to add "1" to the stored number and then overwrite it, I use this php code:

$temp = $_COOKIE['mycookie']++;
$_COOKIE['mycookie']=$temp;

Is it the best way to do that?

I think what you may be looking for is found on this page.

  This is happening because of the ++ being used as a post-increment
  instead of a pre-increment. Essentially what is happening is you're
  saying, "set $cookie to the value of $_COOKIE['count'], and then
  increment $_COOKIE['count'].

Go for ++$_COOKIE['mycookie']; instead and let us know how that works out.


Matlab to C++ percentile clipping I have a 2D matrix in Matlab and I want to convert the Matlab code into C++.

In C++ I have int* channel_gr. The commented code is the original Matlab code.

Is there a faster way to execute this code?

//Gr(1:ROIY(1), :)      = clipLevel;
for (int i = 0; i < _roiY1; i++)
{
    for (int j = 0; j < newWidth; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}

//Gr(ROIY(2)+1:end, :)  = clipLevel;
for (int i = _roiY2-1; i < newHeight; i++)
{
    for (int j = 0; j < newWidth; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}

//Gr(:, 1:ROIX(1))      = clipLevel;
for (int i = 0; i < newHeight; i++)
{
    for (int j = 0; j < _roiX1; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}
//Gr(:, ROIX(2)+1:end)  = clipLevel;
for (int i = 0; i < newHeight; i++)
{
    for (int j = _roiX2-1; j < newWidth; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}

The block

for (int i = 0; i < _roiY1; i++)
{
    for (int j = 0; j < newWidth; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}

can be made more concise by using std::fill.

std::fill(channel_gr, channel_gr+_roiY1*newWidth, cliplevel);

I won't vouch for better performance though.


JavaScript - Difference between two dates in days or less I have 2 dates that I would like to have the difference between them in days and if less than a one day simply show "less than a day".

remainingTime() {
  // Scientific notation of 8.64e+7
  const DAY_IN_MILLISECONDS = 8.64 * (10 ** 7);

  const date1 = new Date('2019-02-28T01:22:06.671Z').getTime();
  const date2 = new Date('2019-02-28T04:01:06.671Z').getTime();

  const differenceInMS = date2 - date1;

  const days = Math.floor(differenceInMS / DAY_IN_MILLISECONDS);
  return (days > 1) ? `They have ${days} days` : (days === 1) ? `They have ${days} day` : `you have less than a day left`;
}

Is this way correct if localization is taken into account?

what exactly is the difference between getTime (), getMilliseconds () and getUTCMilliseconds ()?

Your code looks good to me. I think 1000 * 60 * 60 * 24 would be more intuitive than the scientific notation, but either way gets the job done.

The script doesn't actually take localization into account because Date's getTime method is not localized. To account for time zone, you'd want to get the "timezone offset" of the user's location. (Note that getTimezoneOffset returns a number of minutes, and that number isn't a property of the date object but just an indication of what timezone the code is running in.)

As for the other methods
 - getTime returns the actual "timestamp", a big integer showing how many milliseconds have passed since the 60s ended in London
 - getUTCMilliseconds is just the last three digits of that timestamp (ie how many milliseconds it's been since the last full second since the "epoch", as it's called.)
 - Leaving out the UTC bit (as in getMilliseconds,  or in any of the similar get methods, excepting getTime) makes javascript calculate the local version for you (and in the case of milliseconds, I'd be pretty surprised if it were different from the universal version.)

...You can see the whole buffet on MDN:
   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Date.prototype_Methods


Send blob image using Ajax/PHP I have an image cropper that crops the uploaded image, Before sending it to the server using PHP and AJAX.

Here is a live fiddle to preview a working cropping example.

Here is the code:

// Create cropped part.
function getRoundedCanvas(sourceCanvas) {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  var width = sourceCanvas.width;
  var height = sourceCanvas.height;
  canvas.width = width;
  canvas.height = height;
  context.imageSmoothingEnabled = true;
  context.drawImage(sourceCanvas, 0, 0, width, height);
  context.globalCompositeOperation = 'destination-in';
  context.beginPath();
  context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
  context.fill();
  return canvas;
}

// On uploading a file
$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],
      image = new Image();
  image.src = _URL.createObjectURL(file);
  image.onload = function(e) {
    var image = document.getElementById('image'),
        button = document.getElementById('button');
    $('#image').attr('src',  _URL.createObjectURL(file));
    $('#image').show();
    $('#button').show();
    var cropper = new Cropper(image, {
      aspectRatio: 1,
      movable: false,
      cropBoxResizable: true,
      dragMode: 'move',
      ready: function () {
        croppable = true;
        button.onclick = function () {
          var croppedCanvas;
          var roundedCanvas;
          var roundedImage;
          if (!croppable) {
            return;
          }
          // Crop
          croppedCanvas = cropper.getCroppedCanvas();
          cropper.getCroppedCanvas({
            fillColor: '#fff',
            imageSmoothingEnabled: true,
            imageSmoothingQuality: 'high',
          });
          // Round
          roundedCanvas = getRoundedCanvas(croppedCanvas);
          // Show
          roundedImage = document.createElement('img');
          roundedImage.src = roundedCanvas.toDataURL();
          result.innerHTML = '';
          result.appendChild(roundedImage);

        }
      }
    });
  }
});
#image,
#button{
  display:none
}

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css">

 <input type="file" id="input" name="image">

 <button type="button" id="button">Crop</button>

Upload an image and click crop, The cropped part would be displayed beneath it.

Then I use the following code to send a blob to PHP using Ajax:

cropper.getCroppedCanvas().toBlob(function (blob) {
  var formData = new FormData();
  formData.append('avatar', blob);
  // Use `jQuery.ajax` method
  $.ajax('upload.php', {
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
    },
    error: function () {
    }
  });
});

In upload.php:

if( isset($_FILES['avatar']) and !$_FILES['avatar']['error'] ){
  file_put_contents( "uploads/image.png", file_get_contents($_FILES['avatar']['tmp_name']) );
}

Should I make some checks for security or just the dimensions and size checks?

Should I make some checks for security or just the dimensions and size checks?

It would be simple to check the type of the file uploaded. For example, you could check if the type is an image. For example, if the user uploads a PNG file, $_FILES['avatar']['type'] should be image/png, so a check for that value starting with image would be a simple conditional (e.g. using strpos() and looking for it to return 0, or preg_match('^image/', $_FILES['avatar']['type]).

The HTML could also be updated to only accept certain file types. One technique for this is to add the accept attribute to the input element with a value like image/* to limit the selectable files to images. While this does not prevent a user from selecting any file (or modifying a file to look like an image), it can act like a filter to the file selection dialog if the OS and browser support it. Read more about this in answers to Limit file format when using ?

<input type="file" id="input" name="image" accept="image/*">

One could also add a change handler to check the extension of the file submitted (bear in mind that the user can also change the extension of a file through the OS).

var allowedExtensions = ['jpg', 'gif', 'bmp', 'png', 'tif'];
document.addEventListener('DOMContentLoaded', function() {
  var fileInput = document.getElementById('input');
  fileInput.addEventListener('change', function(e) {
    var parts = this.value.split('.');
    if (allowedExtensions.indexOf(parts[parts.length - 1].toLowerCase()) < 0) {
      this.value = ''; // clear value
      console.log('invalid extension');
    }
  });
});
<input type="file" id="input" name="image" accept="image/*">

Combining one or both of those approaches with the server-side check would be a good approach. Bearing in mind that a user could alter the HTML attributes with tools like browser consoles, as well as submit a form manually with their own page or a tool like Postman, the server-side check should be utilized for optimal protection.

Other Feedback

JavaScript

Variable croppable

It apppears that croppable is set to true in the ready function:

ready: function () {
    croppable = true;
    button.onclick = function () {

While it would be undefined before that line, the onclick function wouldn't be set until after that is set to true, so the following block seems superflous in the onclick function:

if (!croppable) {
    return;
}

This is because by the time the click handler is set on the button, that variable will have been set to true so the condition will never evaluate to a truthy value.

I also noticed in that onclick function that three variables (i.e. croppedCanvas, roundedCanvas, and roundedImage) are declared before the conditional return. There isn't really any reason to declare those variables before the condition. Then those variables can be declared whenever assigned.

Cache DOM references

DOM lookups aren't exactly cheap, so it may be better to store references to elements fetched via document.getElementById() as well as using the jQuery function in variables and referencing those variables later.

Use consistent DOM lookups

Much of the code uses jQuery to look up elements, but then there are other places using document.getElementById(). If you are going to have jQuery, it makes sense to use it for all DOM lookups - for the case of getting a single element (e.g. image and button) .get() can be used to access the element.

So these lines:

var image = document.getElementById('image'),
    button = document.getElementById('button');

Can be simplified using jQuery and .get():

var image = $('#image').get(0),
    button = $('#button').get(0);

Variable name reused

While moving image and button out of the onload callback I noticed that image was used for an Image object and then inside the callback re-assigned to the element with id attribute image. It is wise not to re-use variables like that... Perhaps a better name for the variable referencing the element would be imageElement.

PHP

You state that upload.php contains the following:

if( isset($_FILES['avatar']) and !$_FILES['avatar']['error'] ){
  file_put_contents( "uploads/image.png", file_get_contents($_FILES['avatar']['tmp_name']) );
}

Is there any error handling/response to the client as to to activity on the server? What happens if the write to "uploads/image.png" would fail?