texts: Writing a reusable method in which only some of its parameters are different

texts:
I have the method below but I am going to have more methods similar to this one. They differ in is the last parameters being passed to the method. The first three parameters will always be there and then in the while loop with && conditions, I am going to use the same params that I am passing in.

I am going to need five or six of these methods. Do you think I can write this method in a more reusable way, or do I have to just copy/paste most of it and change the params and condition for each method?

private string FindFullRowForProvider(string id, string lastName, string firstName, string devSystem)
{
    string fullRow = string.Empty;
    StreamReader streamreader = new StreamReader(importSource);
    char[] delimiter = new char[] { '|' };
    int columnLocation = 0;

    string[] columnheaders = streamreader.ReadLine().Split(delimiter);
    foreach (string columnheader in columnheaders)
    {
        columnHeadertoLocation[columnheader.ToUpper()] = columnLocation;
        columnLocation++;
    }

    while (streamreader.Peek() > 0)
    {
        fullRow = streamreader.ReadLine();
        string[] currentRowValues = fullRow.Split(delimiter);

        string _NPI = currentRowValues[columnHeadertoLocation["ID"]];
        string _LName = currentRowValues[columnHeadertoLocation["LNAME"]];
        string _FName = currentRowValues[columnHeadertoLocation["FNAME"]];
        string _devPKCR = currentRowValues[columnHeadertoLocation["DEV_SYSTEM"]];

        if (npi.Trim().ToUpper() == _NPI.Trim().ToUpper()
            && _LName.Trim().ToUpper() == lastName.Trim().ToUpper()
            && _FName.Trim().ToUpper() == firstName.Trim().ToUpper()
            && _dev.Trim().ToUpper() == devSystem.Trim().ToUpper())
        {
            // woot! we found the row of this guy.
            return fullRow;
        }
    }

    return fullRow;
}


texts: Web service for Android clients to store images

texts:
I wrote this code for Android server interaction. The way I built the client was an onSharePreference of strings includes photo encoded to a base64 String object {imei, barcode0, barcode1, photo0, photo1, time_taken0, time_taken1,..} because I had the possibility the user won't be connected to the internet all the time. Then I made a working code to intercept it.

Is it good enough? Is it a good enough code or it has a problem in it? I think it is really straightforward but the server-side guys have had some problems replicating this script in ASP.

<?php

/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/

// array for JSON response
$response = array();

// check for required fields

header('Content-Type: image/jpg; charset=utf-8');
//$base=$_REQUEST['image'];

if ((isset($_POST['imei'])))
{

$counter = $_POST['brcd_counter'];
$imei = $_POST['imei'];            //isset($_POST['imei']) ? $_POST['imei'] : 'NULL';

 //mysqli connect - object oriented style (recommended)
    $mysqli = new mysqli('','','','');
    $mysqli->set_charset("utf8");

    //Output any connection error
    if ($mysqli->connect_error) {
            die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
    }

    // start transaction
 $mysqli->autocommit(FALSE);

for ($i = 0; $i<=$counter; $i++){

    $qr_code[$i] = $_POST['qr_code'.$i];           //isset($_POST['qr_code']) ? $_POST['qr_code'] : 'NULL';
    $time_stamp[$i] = $_POST['time_stamp'.$i];     //isset($_POST['timestamp']) ? $_POST['timestamp'] : 'NULL';
    $photo[$i] =  $_POST['photo'.$i];              //isset($_POST['car_type']) ? $_POST['car_type'] : 'NULL';
    //values to be inserted in database table (for clarity)
    $client_imei = $imei;
    $client_qr_code = $qr_code[$i];
    $client_time_stamp = $time_stamp[$i];
    $client_photo = $photo[$i];   //'DRAGON' .. for chekcing
    $query = "INSERT INTO messages (imei, qr_code , time_stamp, base64image ) VALUES(?,?,?,?)";
    $statement = $mysqli->prepare($query);

    //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
    $statement->bind_param('ssss', $client_imei, $client_qr_code, $client_time_stamp, $client_photo);
    $statement->execute();
}

  if ($mysqli->commit()) {
    // successfully inserted into database

            $response["success"] = 1;
            $response["message"] = "Product successfully created.";

            // echoing JSON response
            echo json_encode($response);
     } else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}

$mysqli->close();}else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Name is missing";

// echoing JSON response
echo json_encode($response);

}


texts: Easy Print PHP From Data array or objects

texts:
I have created a PHP class to print into html easily from an array or object.

Using this class, you can get rid of multiple echo blocks or ugly concatenation while working with data arrays to transform into html.

class PrintEasy {
    /**
     * Print single data item with html
     * Include variable names within a [] block in the html string.
     *
     * @param string $html
     * @param mixed $data Accepts both array and object format
     * @return boolean
     */
    public static function single($html, $data) {
        $newHtml = preg_replace_callback(
            '/\[([^\]]+)\]/',
            function($match) use ($data) {
                $key = $match[1];
                if(is_object($data)) {
                    return $data->$key;
                } elseif(is_array($data)) {
                    return $data[$key];
                } else return $match[0];

            },
            $html
        );
        echo $newHtml;
        return true;
    }

    /**
     * Print multiple items from a data array with html
     *
     * @param string $html
     * @param array $dataArray the dataArray can contain both array and object format data items
     * @param int $count (optional) If provided, only that number of items will be printed from the array
     * @return boolean
     */
    public static function multiple($html, $dataArray, $count = 0) {
        if(!$count) {
            $count = count($dataArray);
        }

        for($i=0;$i<$count;$i++) {
            PrintEasy::single($html, isset($dataArray[$i]) ? $dataArray[$i] : array());
        }
        return true;
    }
}

I have also created a github repo.

Are there any improvements I can make?


texts:
I'm brand new to C# and I've started to make a cipher decryption program. The code works and runs fine, apart from the odd exception. I'm just looking for ways to improve my code and make more efficient.

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

namespace Application
{
class Caesar
{
    static void Main(string[] args)
    {

       try{

        Console.WriteLine("Enter Key:");
        int k = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Press E for Encrypting and D for Decrypting:");
        string choice =Convert.ToString(Console.ReadLine()).ToUpper();

        switch (choice)
        {
            case "E": Console.Write("Enter Plain Text:");
                      string pt = Console.ReadLine();
                      caesar_cipher(k, pt);
                       break;

            case "D": Console.Write("Enter Cipher :");
                       string ct = Console.ReadLine();
                      caesar_decipher(k, ct);
                      break;

            default: Console.WriteLine("You've entered an incorrect   option!");
                       break;
        }
       }
       catch(Exception)
       {
           Console.WriteLine ("The value you entered is incorrect");
           Console.WriteLine ("Press any key to try again");

       }

    }
    static void caesar_cipher(int key, string pt)
    {
        int size = pt.Length;
        char[] value = new char[size];
        char[] cipher = new char[size];
        for (int r = 0; r < size; r++)
        {
            value[r] = Convert.ToChar(pt.Substring(r, 1));
        }

        for (int re = 0; re < size; re++)
        {
            int count = 0;
            int a = Convert.ToInt32(value[re]);
            for (int y = 1; y <= key; y++)
            {
                if (count == 0)
                {
                    if (a == 90)
                    { a = 64; }
                    else if (a == 122)
                    { a = 96; }
                    cipher[re] = Convert.ToChar(a + y);
                    count++;
                }
                else
                {
                    int b = Convert.ToInt32(cipher[re]);
                    if (b == 90)
                    { b = 64; }
                    else if (b == 122)
                    { b = 96; }
                    cipher[re] = Convert.ToChar(b + 1);

                }
            }
        }
        string ciphertext = "";

        for (int p = 0; p < size; p++)
        {
            ciphertext = ciphertext + cipher[p].ToString();
        }
        Console.WriteLine("Cipher Text=");
        Console.WriteLine(ciphertext.ToUpper());
    }

    static void caesar_decipher(int key, string ct)
    {
        int size = ct.Length;
        char[] value = new char[size];
        char[] cipher = new char[size];
        for (int r = 0; r < size; r++)
        {
            cipher[r] = Convert.ToChar(ct.Substring(r, 1));
        }

        for (int re = 0; re < size; re++)
        {
            int count = 0;
            int a = Convert.ToInt32(cipher[re]);
            for (int y = 1; y <= key; y++)
            {
                if (count == 0)
                {
                    if (a == 65)
                    { a = 91; }
                    else if (a == 97)
                    { a = 123; }
                    value[re] = Convert.ToChar(a - y);
                    count++;
                }
                else
                {
                    int b = Convert.ToInt32(value[re]);
                    if (b == 65)
                    { b = 91; }
                    else if (b == 97)
                    { b = 123; }
                    value[re] = Convert.ToChar(b - 1);

                }
            }
        }
        string plaintext = "";

        for (int p = 0; p < size; p++)
        {
            plaintext = plaintext + value[p].ToString();
        }
        Console.WriteLine("Plain Text=");
        Console.WriteLine(plaintext.ToLower());
    }
}
}


texts:
I am writing a python module to interact to the ROD (remedy on demand) BMC ticketing product. So far I have only written the log in and log out methods and tests. Before I crack on with the more complex methods I hope someone can review the current test strategy and happy to hear any suggestions for improvements.
rodAPI.py
import requests

class RodApi:
    def __init__(self, fqdn, username, password, token_type="AR-JWT"):
        self.username = username
        self.password = password
        self.fqdn = fqdn
        self.token_type = token_type
        self.login_url = f"https://{fqdn}/api/jwt/login"
        self.logout_url = f"https://{fqdn}/api/jwt/logout"
        self.token = None

    def login(self) -> bool:
        data = {"username": self.username, "password": self.password}
        headers = {"content-type": "application/x-www-form-urlencoded"}
        response = requests.post(self.login_url, data=data, headers=headers)

        print(f"connecting to URL: {self.login_url}")
        print(f"https status code: {response.status_code}")
        self.token = response.text
        if response.status_code == 200:
            return True
        return False

    def logout(self) -> bool:
        headers = {"Authorization": f"{self.token_type} {self.token}"}
        response = requests.post(self.logout_url, headers=headers)

        print(f"connecting to URL: {self.logout_url}")
        print(f"https status code: {response.status_code}")
        if response.status_code == 204:
            print(f"Logged out with a status of: {response.status_code}")
            return True
        else:
            print(f"Error logging out: {response.text}")
            return False

test_rodAPI
import pytest

from rodAPI import RodApi

@pytest.fixture()
def rod_api_instance():
    rod_api = RodApi("example.com", "some_user", "some_password")
    return rod_api

@pytest.fixture()
def rod_api_logged_in_instance(responses, rod_api_instance):
    responses.add(responses.POST, rod_api_instance.login_url, body="some_token_string")
    rod_api_instance.login()
    return rod_api_instance

def test_login_success(responses, rod_api_instance: RodApi):
    responses.add(responses.POST, rod_api_instance.login_url, body="some_token_string")
    result = rod_api_instance.login()
    assert result is True
    assert rod_api_instance.token == "some_token_string"

def test_login_fail(responses, rod_api_instance: RodApi):
    responses.add(responses.POST, rod_api_instance.login_url, status=404)
    result = rod_api_instance.login()
    assert result is False

def test_logout_success(responses, rod_api_logged_in_instance: RodApi):
    responses.add(responses.POST, rod_api_logged_in_instance.logout_url, status=204)
    result = rod_api_logged_in_instance.logout()
    assert result is True

def test_logout_fail(responses, rod_api_logged_in_instance: RodApi):
    responses.add(responses.POST, rod_api_logged_in_instance.logout_url, status=404)
    result = rod_api_logged_in_instance.logout()
    assert result is False
```


texts:
I have the following tables:

                 player
| id         | name        | surname      |
|:-----------|------------:|:------------:|
| 1001       |    Mike     |    Tyson     |
| 2001       |    John     |    Carlin    |
| 3001       |    Dan      |    StanH     |
| 4001       |    Alen     |     Derl     |

                  person
| id         | name        | surname      |
|:-----------|------------:|:------------:|
| 1001       |    Mike     |    Tyson     |
| 2001       |    Pirlon   |    Austin    |
| 6001       |    Danly    |    StanH     |
| 4001       |    Alen     |     Derl     |

I want create an SQL query in order to get the same records of the above schemes and print first and last name.

The query is

SELECT player.name, player.surname
   FROM  player INNER JOIN person
     on  player.id =  person.id
    AND  player.name = person.name
    AND  player.surname = person.surname;

Is there any way to create a more efficient query?


texts: Python implementation of find_all_indexes

texts:
I got asked this question before in an interview.

For example, find_all_indexes('ababc', 'abc') returns 2. This Python function should find the index of first occurrence pattern. I also wrote a function that returns a list of starting indexes of all occurrences of the pattern in a text.

I have the following implementation that handles most of the cases:

def find_all_indexes(text, pattern):
    indexes = []
    text_index = 0
    while text_index != len(text):
        if pattern == '':
            indexes.append(text_index)
        else:
            for i in range(len(pattern)):
                if text_index + i < len(text):
                    if text[text_index + i] != pattern[i]:
                        break
                    if i == len(pattern) - 1:
                        indexes.append(text_index)
        text_index += 1
    return indexes

def test_string_algorithms(text, pattern):
    indexes = find_all_indexes(text, pattern)
    print('find_all_indexes({!r}, {!r}) => {}'.format(text, pattern, indexes))

def main():
    test_string_algorithms(text, pattern)
    print('Usage: {} text pattern'.format(script))
    print("find_all_indexes('abra cadabra', 'abra') => [0, 8]")

if __name__ == '__main__':
    main()

I am not sure if I exhausted all of the edge cases, but I ran this unit test, and it passed all tests.

The pytest output:

pytest test.py
======================= test session starts ========================
platform darwin -- Python 2.7.12, pytest-3.0.5, py-1.4.32, pluggy-0.4.0

collected 3 items

test.py .........

===================== 3 passed in 0.07 seconds


texts:
I am new to programming and I am trying to develop a machine learning approach for image segmentation (https://en.wikipedia.org/wiki/Image_segmentation) and here I want to evaluate the predicted (output) segmentation. In order to do this, I am using multiple (common) metrics (dice score, jacquard index, surface distance Hausdorff distance, diameter error and volume error).

The code works, but it really looks bad! I heard that one of the best practices is to avoid repetition in the code. For my piece I have to create multiple arrays which will all have different usage, but generating a lot of repetitions, and I am sure there might be better way to get better performance for this piece of code.

Do you have an idea of how to optimize this for speed and readability?

The details of the code:

folder = glab() : gets the name of the different folders containing the arrays that I want to open (glab() = glob() with natural sorting)

prediction/ground_truth : loads the predicted segmentation and ground_truth to be compared

scores() : calculates the different metrics (dice score, jacquard index, sensibility and specificity) between the ground truth and prediction

surfd() : calculates the surface distance between ground truth and prediction

diam_vol : calculates the diameter/volume and error between ground truth and prediction

Since I am evaluating multiple cases I want to know the mean() metrics to assess my model that's why I call for np.mean() for all the values at the end.

def metrics(savedir):

    """3D metrics for segmentation evaluation:

    dice score : https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
    jacquard index : https://en.wikipedia.org/wiki/Jaccard_index
    sensibility & specificity : https://en.wikipedia.org/wiki/Sensitivity_and_specificity
    diameter and volume error
    Surface distance : https://www.cs.ox.ac.uk/files/7732/CS-RR-15-08.pdf
    Hausdorff distance : https://en.wikipedia.org/wiki/Hausdorff_distance
    """

    folder = glab(savedir+"/OutputData/*/")

    # array initialization
    np_dice = np.zeros([len(folder)])
    np_jacq = np.zeros([len(folder)])
    np_sens = np.zeros([len(folder)])
    np_spec = np.zeros([len(folder)])
    np_surf = np.zeros([len(folder)])
    np_haus = np.zeros([len(folder)])

    np_diam_GT = np.zeros([len(folder)])
    np_diam_pred = np.zeros([len(folder)])
    np_diam_err = np.zeros([len(folder)])

    np_vol_GT = np.zeros([len(folder)])
    np_vol_pred = np.zeros([len(folder)])
    np_vol_err = np.zeros([len(folder)])

    for number, folder_name in enumerate(folder):

        prediction = np.load(folder_name+"prediction.npy")
        ground_truth = np.load(folder_name+"test_label.npy")

        scores = scoring(ground_truth, prediction)
        surface_distance = surfd(prediction, ground_truth, [0.625, 0.625, 0.625], 1)
        diam_vol = diam(prediction, ground_truth)

        np_dice[number] = scores[0]
        np_jacq[number] = scores[1]
        np_sens[number] = scores[2]
        np_spec[number] = scores[3]
        np_surf[number] = surface_distance.mean()
        np_haus[number] = surface_distance.max()

        np_diam_GT[number] = diam_vol[0]
        np_diam_pred[number] = diam_vol[1]
        np_diam_err[number] = diam_vol[2]

        np_vol_GT[number] = diam_vol[3]
        np_vol_pred[number] = diam_vol[4]
        np_vol_err[number] = diam_vol[5]

    mean_dice = np.mean(np_dice)
    mean_jacq = np.mean(np_jacq)
    mean_sens = np.mean(np_sens)
    mean_spec = np.mean(np_spec)
    mean_surf = np.mean(np_surf)
    mean_haus = np.mean(np_haus)
    mean_diam_GT = np.mean(np_diam_GT)
    mean_diam_pred = np.mean(np_diam_pred)
    mean_diam_err = np.mean(np_diam_err)
    mean_vol_GT = np.mean(np_vol_GT)
    mean_vol_pred = np.mean(np_vol_pred)
    mean_vol_err = np.mean(np_vol_err)

    return ([mean_dice, mean_jacq, mean_sens, mean_spec, mean_surf, mean_haus, mean_diam_GT, mean_diam_pred, mean_diam_err, mean_vol_GT, mean_vol_pred, mean_vol_err])


texts:
Here's my implementation of a bare-bones HashMap in Python.
Expected behavior, it returns None if a key is missing,
When a key is inserted the second time it just overwrites the first value.

class HashMap:
    def __init__(self):
        self.store = [None for _ in range(16)]
        self.size = 0

    def get(self, key):
        key_hash = self._hash(key)
        index = self._position(key_hash)
        if not self.store[index]:
            return None
        else:
            list_at_index = self.store[index]
            for i in list_at_index:
                if i.key == key:
                    return i.value
            return None

    def put(self, key, value):
        p = Node(key, value)
        key_hash = self._hash(key)
        index = self._position(key_hash)
        if not self.store[index]:
            self.store[index] = [p]
            self.size += 1
        else:
            list_at_index = self.store[index]
            if p not in list_at_index:
                list_at_index.append(p)
                self.size += 1
            else:
                for i in list_at_index:
                    if i == p:
                        i.value = value
                        break

    def __len__(self):
        return self.size

    def _hash(self, key):
        if isinstance(key, int):
            return key
        result = 5381
        for char in key:
            result = 33 * result + ord(char)
        return result

    def _position(self, key_hash):
        return key_hash % 15

class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value

    def __eq__(self, other):
        return self.key == other.key

if __name__ == '__main__':
    hashmap = HashMap()
    hashmap.put(2, 12)
    hashmap.put('asd', 13)
    hashmap.put(2, 11)
    print(hashmap.get(2))
    print(hashmap.get('asd'))
    print(hashmap.get('ade'))

Invite comments and reviews.


texts: Parsing a long without using inbuilt function parseLong

texts:
I came across it as a problem to solve. What kind of limitations are there?

public long parseLong(String number)
{
    long n=0;
    if(number==null || number.isEmpty())
    {
        System.out.println("Number is null or empty");
        return n;
    }
    boolean isNegative = false;
    if(number.charAt(0)=='-')
    {
        isNegative=true;
    }
    else {
        n = getValue(number.charAt(0));
    }
    for(int i=1;i<number.length();i++)
    {
        n = n*10 + getValue(number.charAt(i));
    }
    return isNegative ? (-1*n) : n;
}
public int getValue(char ch)
{
    int value = ch;
    if(value<'0' || value>'9')
    {
        throw new NumberFormatException();
    }
    return value-'0';
}


texts: Switch case reviews, finding days of the week that coresponds to a number given

texts:
Given a number between 1 and 7, this will display which day of the week corresponds to that number, starting with Monday. This is pretty simple and pretty easy, but it seems that there would be a much better way to do this, where I wouldn't have to write out each day of the week, and possibly iterate through an array..?

using System;

namespace FindDay
{
    class Program
    {
        static void Main(string[] args)
        {
            //This program will provide you the day of the week
            //through a given number that coresponds to that day
            //of the week, IE: Monday => 1st day of the week

            int num;
            string result;

            label:

            Console.Write("Enter a number between 1 and 7: ");
            num = Convert.ToInt32(Console.ReadLine());

            switch (num)
            {
                case 1:
                    result = "Monday";
                    Console.WriteLine("{0} => {1}st day of the week", result, num);
                    break;
                case 2:
                    result = "Tuesday";
                    Console.WriteLine("{0} => {1}nd day of the week", result, num);
                    break;
                case 3:
                    result = "Wednesday";
                    Console.WriteLine("{0} => {1}rd day of the week", result, num);
                    break;
                case 4:
                    result = "Thursday";
                    Console.WriteLine("{0} => {1}th day of the week", result, num);
                    break;
                case 5:
                    result = "Friday";
                    Console.WriteLine("{0} => {1}th day of the week", result, num);
                    break;
                case 6:
                    result = "Saturday";
                    Console.WriteLine("{0} => {1}th day of the week", result, num);
                    break;
                case 7:
                    result = "Sunday";
                    Console.WriteLine("{0} => {1}th day of the week", result, num);
                    break;
                default:
                    Console.WriteLine("That's not a day..");
                    goto label;

            }

        }
    }
}

Would it be better to iterate through an array within this instead of writing out each day separately, how can I improve this little program?


texts: One function two functionalities or two functions each with one functionality

texts:
Within our project we've used a lot of boolean setOutputValue(char pinNumber, boolean pinValue) kind of functions.

Within those functions we do the following (for example):

hardware_layer:

#define L9823_HIGH  0
#define L9823_LOW   1
void hardware_L9823_setOutput(U8BIT pin, U8BIT value)
{
  /* some SPI interfacing is handled here */
}

IO_layer:

#define IO_ACTIVE   1
#define IO_INACTIVE 0
void io_outputDriver_setOutput(U8BIT pin, U8BIT value)
{
  if (value == IO_ACTIVE)
  {
    hardware_L9823_setOutput(pinMapping[pin], L9823_HIGH);
  }
  else
  {
    hardware_L9823_setOutput(pinMapping[pin], L9823_LOW);
  }
}

component_layer:

#define COMPONENT_ASIMPLEDEVICE_A_ON    1
#define COMPONENT_ASIMPLEDEVICE_A_OFF   0
void component_aSimpleDeviceA_set(U8BIT value)
{
  if (value == COMPONENT_ASIMPLEDEVICE_A_ON)
  {
    io_outputDriver_setOutput(DEVICE_PIN_A, IO_INACTIVE);
  }
  else
  {
    io_outputDriver_setOutput(DEVICE_PIN_A, IO_ACTIVE);
  }
}

#define COMPONENT_ASIMPLEDEVICE_B_ON    1
#define COMPONENT_ASIMPLEDEVICE_B_OFF   0
void component_aSimpleDeviceB_set(U8BIT value)
{
  if (value == COMPONENT_ASIMPLEDEVICE_B_ON)
  {
    io_outputDriver_setOutput(DEVICE_PIN_B, IO_INACTIVE);
  }
  else
  {
    io_outputDriver_setOutput(DEVICE_PIN_B, IO_ACTIVE);
  }
}

unit_layer:

#define COMPLEXDEVICE_ON    1
#define COMPLEXDEVICE_OFF   0
void component_aComplexDeviceWithMultipleComponents_set(U8BIT value)
{
  if (value == COMPLEXDEVICE_ON)
  {
    component_aSimpleDeviceA_set(COMPONENT_ASIMPLEDEVICE_A_ON);
    component_aSimpleDeviceB_set(COMPONENT_ASIMPLEDEVICE_A_ON);
  }
  else
  {
    component_aSimpleDeviceA_set(COMPONENT_ASIMPLEDEVICE_A_OFF);
    component_aSimpleDeviceB_set(COMPONENT_ASIMPLEDEVICE_A_OFF);
  }
}

This is a rather simple example, but in our case we have a total of 4 layers to seperate hardware/io/component and module implementations. So this has to propagate 4 layers down before it reaches the hardware register.

It does give less code to maintain and less comments to maintain (each function has a header of atleast 9 lines of code.

I've raised the concern of having many if-statements while trying to set a hardware register and proposed to start splitting these functions in to each having their own function like so:

boolean setOutputLow(char pinNumber)
{
    if (pinNumber is within limits of output register mapping)
    {
        regMapping[pinNumber] = OUTPUTLOW;
    }
}

and the same ofc. for the High variant. Which seems to save a lot of if-else logic down the road but does increase code size a tiny bit.

Which would be a prefered way of handling these kind of things? Are there even better ways? Or is this the right road to walk?


texts:
My overall strategy is to load a block size (512bytes) into memory and check if that blocks first 4 bytes match a JPEGS first 4 bytes.

If it does then, I'll open a new out file and start writing the bytes into the out file. I'll repeat this for every "lost" JPEG.

You can assume that the "lost" JPEGs are stored consecutively.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

int main( int argc, char *argv[] )
{
  //check for proper usage
  if ( argc != 2 )
  {
      fprintf(stderr, "Proper usage: ./recover file\n" );
      return 1;
  }

  //Remember name of file
  char *infile = argv[1];

  //open infile
  FILE *inptr = fopen( infile, "r");
  if ( inptr == NULL )
  {
      fprintf(stderr, "Could not open %s, please try again\n", infile );
      return 2;
  }

  //INIT block size and buffer
  int blockSize = 512;
  unsigned char buffer[blockSize];

  //Storage for file name and file
  char fileBuffer[8];
  FILE *outptr = NULL;

  //count how many images have been found
  int imageCount = 0;

  //iterate over the infile 512 bytes at a time
  while ( fread( buffer, blockSize, 1, inptr ) == 1 )
  {
      //look for jpeg header
      if ( buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0 ) {

          //close output file if its open
          if( outptr != NULL)
          {
              fclose(outptr);
          }

          //create the new file name and open that file
          sprintf( fileBuffer, "%03d.jpg", imageCount );

          outptr = fopen( fileBuffer, "w" );
          if ( outptr == NULL )
          {
              fprintf( stderr, "Could not create %s", fileBuffer );
              return 3;
          }

          //INCREMENT Image count
          imageCount++;
      }

      //write to out file if an image was found
      if( outptr != NULL )
      {
           fwrite( buffer, blockSize, 1, outptr);
      }

  }

  //close last photo
  fclose(outptr);

  //close input file
  fclose(inptr);

  //success
  return 0;

}


texts: Parsing PHP-style nested query string parameters

texts:
I searched all over for a query string parser that could handle nested parameter names ala parse_str in PHP. I was unable to find anything, so this is what I've come up with so far.

Assumptions:

client[0][organizations][0][id]

is the same as

client[0].organizations[0].id

Restrictions:

Given that all keys may be non-sequential and non-numeric, does not utilize Lists, but rather pushes everything into a hierarchical Map.
Does not handle any sort of encoding right now.

Implementation

public class Util {
    private static final Pattern PATTERN = Pattern.compile("([^\\[\\]\\.]+)");

    public static Map<String, Object> parse_str(String str) {
        final String pairs[] = StringUtils.split(str, "&");
        final OurMap result = new OurMap();
        if (pairs == null || pairs.length == 0) {
            return result;
        }

        for (String pair : pairs) {
            final String[] tmp = StringUtils.split(pair, "=", 2);
            final String key = tmp[0];
            final String[] path = keyToPath(key);
            final String value = tmp.length > 1 ? tmp[1] : "";

            // Now iterate over the key path until we're done
            OurMap map = result;
            for (int i = 0; i < path.length; i++) {
                final String part = path[i];
                // If no element exists for this part, we can add it straight
                // away
                if (!map.containsKey(part)) {
                    // This is the end of the key path, so just put the value
                    if (i >= path.length - 1) {
                        map.put(part, value);
                    }
                    else {
                        OurMap m = new OurMap();
                        map.put(part, m);
                        map = m;
                    }
                }

                // An element already exists, so we have to check to see what it
                // is, see if we need to do any conversions, etc.
                else {
                    Object current = map.get(part);
                    // If it's already a map, we can continue on down the path
                    if (current instanceof OurMap) {
                        if (i >= path.length - 1) {
                            ((OurMap)current).put(part, value);
                        }
                        else {
                            map = (OurMap)current;
                        }
                    }
                    // If it's a scalar object, we need to convert it to a list
                    // (in map form for weird indices)
                    else {
                        OurMap m = new OurMap();
                        m.add(current);
                        if (i >= path.length) {
                            m.add(value);
                        }
                        m.add(value);
                        map.put(part, m);
                        map = m;
                    }
                }
            }
        }
        return result;
    }

    protected static String[] keyToPath(final String key) {
        final Matcher matcher = PATTERN.matcher(key);
        final List<String> result = new ArrayList<>();
        while (matcher.find()) {
            result.add(matcher.group());
        }
        return result.toArray(new String[result.size()]);
    }

    public static class OurMap extends HashMap<String, Object> {
        public void add(final Object obj) {
            put(String.valueOf(keySet().size()), obj);
        }
    }
}

Tests

firstName=Jane&lastName=Smith&organizations[0][id]=1234&organizations[0].addresses[].street=Wentworth%20Dr

yields the following map representation

{lastName=Smith, organizations={0={id=1234, addresses={street=Wentworth%20Dr}}}, firstName=Jane}


texts: How do I make the search in the typeahead widget more efficient

texts:
I have a typeahead widget to get the state or city's population according to what the user types

Instead of issuing a GET request every time the user is done typing, the way this typeahead widget works is fetch data beforehand and store it in memory and every time user types, we are iterating through the data to retrieve the stuff that we need.

The live demo is here: https://codesandbox.io/s/saveddatatypeahead-lcyfg?file=/src/index.js

So the data is fetched like this

const data = [];

fetch(endpoint)
  .then(res => res.json())
  .then(result => {
    data.push(...result);
  });

and we listen for the input event on the input field, the timeId is for debouncing the searching, we don't want to search too frequently

searchInput.addEventListener("input", e => {
  if (e.target.value.length > 2) {
    if (timeId) {
      clearTimeout(timeId);
    }
    timeId = setTimeout(() => {
      displayMatches(e.target.value);
    }, 500);
  }
});

and the search is performed here

function findMatches(regex, data) {
  // the time complexity is
  // O(M x K)
  // M is the length of a city or state
  // K is the keyword to match
  // e.g. M - 'New York' K - 'yo'
  return data.filter(
    place => place.city.match(regex) || place.state.match(regex)
  );
}

Here the regex is constructed based on what the user typed const regex = new RegExp(text, "ig");

So for now it seems to me that the time complexity for the searching here is  O(N x M x K)
N is the number of entries in the data array, M is the average length of every city or state's name, and K is the keyword the user typed.

So my question is, is there a way to make the search more efficient? For now I have done two things to improve the efficiency.

1.if what the user types is less than 3 characters, we don't perform the search

2.debounce the search and only fire it when the user is done typing

Right the amount of data is not huge but I can see that it doesn't scale well with this naive implementation of search. Maybe building a trie can help? I am not sure.

Also any other suggestions and critiques about this widget are highly welcomed


texts: More elegant array multiplication than multiple concat statements

texts:
Background

Trevor wishes to duplicate an array, transforming it by multiplying its elements four times.

Existing Solution

//
var atest =   ['a','b','c'];
var btest =   [];
btest     =   atest.concat(atest).concat(atest).concat(atest);
//
console.log(btest.length);  // btest.length == 12
console.log(btest);         // ["a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c"]

Goal

Trevor does not like this because it is ugly. Can you help Trevor find his happy place again? It's bugging Trevor.


texts:
This entire class came out of a chat discussion, and I'm curious on how it looks. (This is like literally 30 minutes of development time.)

The idea is to allow very easy, quick implementations of Google's reCAPTCHA ("I am not a robot") checkbox CAPTCHA algorithm. It only requires minor work from the implementor to make it work properly, and that was the point.

Warning: Minimal implementation effort required.

public class ReCaptchaValidator
{
    private const string _HeadScriptInclude = "";
    private const string _ReCaptchaLocationInclude = "

";

    private readonly string _ReCaptchaSecret;
    private readonly string _ReCaptchaSiteKey;

    ///
    /// Returns the script to be included in the &lt;head&gt; of the page.
    ///
    public string HeadScriptInclude { get { return _HeadScriptInclude; } }

    ///
    /// Use this to get or set any extra classes that should be added to the &lt;div&gt; that is created by the <see cref="ReCaptchaLocationInclude"/>.
    ///
    public List<string> ExtraClasses { get; set; }

    ///
    /// Returns the &lt;div&gt; that should be inserted in the HTML where the reCAPTCHA should go.
    ///
    /// <remarks>
    /// I'm still not sure if this should be a method or not.
    /// </remarks>
    public string ReCaptchaLocationInclude { get { return _ReCaptchaLocationInclude.Replace("%SITEKEY%", _ReCaptchaSiteKey).Replace("%EXTRACLASSES%", string.Join(" ", ExtraClasses)); } }

    ///
    /// Creates a new instance of the <see cref="ReCaptchaValidator"/>.
    ///
    /// <param name="reCaptchaSecret">The reCAPTCHA secret.</param>
    /// <param name="reCaptchaSiteKey">The reCAPTCHA site key.</param>
    public ReCaptchaValidator(string reCaptchaSecret, string reCaptchaSiteKey)
    {
        _ReCaptchaSecret = reCaptchaSecret;
        _ReCaptchaSiteKey = reCaptchaSiteKey;
    }

    ///
    /// Determines if the reCAPTCHA response in a NameValueCollection passed validation.
    ///
    /// <param name="form">The Request.Form to validate.</param>
    /// <returns>A boolean value indicating success.</returns>
    public bool Validate(NameValueCollection form)
    {
        string reCaptchaSecret = _ReCaptchaSecret;
        string reCaptchaResponse = form["g-recaptcha-response"];
        bool passedReCaptcha = false;

        using (WebClient client = new WebClient())
        {
            byte[] response = client.UploadValues("https://www.google.com/recaptcha/api/siteverify",
                                                    new NameValueCollection() { { "secret", reCaptchaSecret }, { "response", reCaptchaResponse } });

            string reCaptchaResult = System.Text.Encoding.UTF8.GetString(response);

            if (reCaptchaResult.IndexOf("\"success\": true") > 0)
                passedReCaptcha = true;
        }

        return passedReCaptcha;
    }
}

Usage:

string reCaptchaSecret = "";
string reCaptchaSiteKey = "";

ReCaptchaValidator rcv = new ReCaptchaValidator(reCaptchaSecret, reCaptchaSiteKey);
bool passedReCaptcha = rcv.Validate(Request.Form);

It should be pretty self-explanatory. You can use the ReCaptchaValidator.HeadScriptInclude to get the entire


texts: aggregate sheets from many excel workbooks into one workbook

texts:
I want to put the worksheets from several (2-5) excel workbooks (files) into one single workbook.

The names of the workbooks are not standardized and so I opted for a dialog box to select the workbooks.

Here is the code. It meets the basic requirement that all the worksheets (sheets actually) from the selected files are collected into a single file (the ActiveWorkbook).

Sub openDialogBoxAndSelectFiles()

  Dim wb1 As Workbook
  Set wb1 = ActiveWorkbook

  With Application.FileDialog(msoFileDialogFilePicker)

    .AllowMultiSelect = True
    .InitialFileName = ThisWorkbook.path & "\"
    .Title = "Paddington Bear Selection Window"
    .ButtonName = "Omlette"

    .Filters.Clear
    .Filters.Add "All Files", "*.*"

    If .Show = True Then

      Dim file As Variant
      For Each file In .SelectedItems

        Dim wb2 As Workbook
        Set wb2 = Workbooks.Open(Filename:=file, ReadOnly:=True)

        Dim i As Long
        For i = 1 To wb2.Sheets.Count
          wb2.Sheets(i).Copy before:=wb1.Sheets(1)
        Next i

        wb2.Close
      Next

    End If

  End With

End Sub

The code is pretty clean (I think) for the time being and pretty much fits the bill, but that's because it doesn't do the following:

If the ActiveWorkbook which I've defined as wb1 has blank sheets (and a wb has  to have at least 1 sheet), once this process is done, I will have a few blank sheets left over.

So if file1.worksheets.count = 4, and file2.worksheets.count = 5, I will have a minimum of 10 (1 + 4 + 5) worksheets in the final workbook.

Questions:

Insofar as aggregating the sheets of the files is concerned, is this a reasonable way of doing it?
Is there a simple of ensuring there are no blank worksheets left over? Unless the input files have blank sheets that is.

Kindly,


texts:
I have small class which interprets TV show filenames to extract the show title and episode number. Due to the nature of the filenames, I have chosen for a cleaning approach: I clean the filename first as much as possible and then extract the necessary data (instead of matching the data right away with regexp).

I'm kind of stuck on the following problem:

I have a cleanFilename() method and a getEpisodeNumber() method, which rely on each other to work but I want to be able to use them independently.

I would also like to note that the getEpisodeNumber() method requires a cleaned filename to work properly and that the cleanFilename() method requires the episode number to be removed for it to return the correct value.

NOTE: if anyone knows a better solution to extract the relevant data, please do let me know.

public function cleanFilename($filename)
{
    // run first string replace filter
    $step = str_replace($this->bad_filter, '', $filename);

    // replace underscore "_" with space " "
    $step = str_replace('_', '', $step);

    // run version filter
    $step = str_replace($this->version_filter, '', $step);

    // remove all not ascii characters
    $step = preg_replace('/[[:^print:]]/', '', $step);

    // remove everything between braces
    $step = preg_replace("/(\\[.*?\\])/is", '', $step);

    // remove everything between brackets
    $step = preg_replace("/(\\(.*\\))/is", '', $step);

    //remove episode number
    $step = str_ireplace($this->getEpisodeNumber($step, true), '', $step);

    //trim trailing dash
    $step = trim($step, ' -');

    return $step;

}

public function getEpisodeNumber($string, $filtered = false)
{
    if ($filtered === false) {
        $string = $this->cleanFilename($string);
    }

    // match integers
    $c = preg_match_all("/(\\d+)/is", $string, $matches);

    return sprintf('%02d', end($matches[0]));

}

These are some filenames:

[HorribleSubs] Shounen Hollywood - Holly Stage for 50 - 09 [480p].mkv.torrent
[DameDesuYo] Junketsu no Maria - 07 (1280x720 10bit AAC) [873A1506].mkv.torrent
[Cthuko] Shirobako - 20 [720p H264 AAC][6363865C].mkv.torrent
[Hatsuyuki]_Ansatsu_Kyoushitsu_OVA_[848x480][10bit][6BE57B34].mkv


texts:
I'm working on an application that allows users edit/fix XML.
A part of this is to format the XML for better readability.
As the XML might be invalid, the existing methods I found for formatting (like XmlWriter or XDocument) don't work for me.
There might be all sorts of problems with the XML, although the most common is unescaped special characters.
public static string FormatXml(string xml)
{
    var tags = xml
        .Split('<')
        .Select(tag => tag.TrimEnd().EndsWith(">") ? tag.TrimEnd() : tag); //Trim whitespace between tags, but not at the end of values

    var previousTag = tags.First(); //Preserve content before the first tag, e.g. if the initial < is missing
    var formattedXml = new StringBuilder(previousTag);
    var indention = 0;

    foreach (var tag in tags.Skip(1))
    {
        if (previousTag.EndsWith(">"))
        {
            formattedXml.AppendLine();
            if (tag.StartsWith("/"))
            {
                indention = Math.Max(indention - 1, 0);
                formattedXml.Append(new string('\t', indention));
            }
            else
            {
                formattedXml.Append(new string('\t', indention));
                if (!tag.EndsWith("/>"))
                {
                    indention++;
                }
            }
        }
        else
        {
            indention = Math.Max(indention - 1, 0);
        }

        formattedXml.Append("<");
        formattedXml.Append(tag);
        previousTag = tag;
    }

    return formattedXml.ToString();
}

Sofar the method produces reasonable output for all cases I came up with.
I'm mostly worried that I missed some special cases of valid XML that would get messed up.


texts: C++: k-Nearest Neighbours with Lambdas and Priority Queues

texts:
I implemented getting the \$k\$-nearest neighbours of an origin point to a set of points in C++17. I tried to use some more modern C++ lambda techniques and was looking for feedback on use of lambdas, auto return types, and using a custom comparison function with priority queue.

Should other lambdas be captured by referenced or by value?
For auto return types, when should you use the arrow notation to signify a return type?
Is there a cleaner way to declare the type of queue in the code below?

Other feedback is welcome too.
#include <algorithm>
#include <iostream>
#include <queue>

using Point = std::pair<int, int>;

auto knn(const std::vector<Point>& points,
         const Point& origin,
         const int k) -> std::vector<Point> {
  auto squared_distance = [&origin](const Point& p) {
    const int dx = std::get<0>(p) - std::get<0>(origin);
    const int dy = std::get<1>(p) - std::get<1>(origin);
    return dx*dx + dy*dy;
  };

  auto closer = [&squared_distance](const Point& p1, const Point& p2) {
    return squared_distance(p1) > squared_distance(p2);
  };
  std::priority_queue<Point, std::vector<Point>, decltype(closer)> queue(closer);

  for (const auto& point : points) {
    queue.push(point);
  }

  std::vector<Point> nearest_neighbours;
  for (int i = 0; i < k; ++i) {
    nearest_neighbours.emplace_back(std::move(queue.top()));
    queue.pop();
  }
  return nearest_neighbours;
}


texts: Function to return subword of a camelcase string

texts:
Given a camelcase string and an index, return the subword of the string that includes that index, e.g.:

find_word('CamelCaseString', 6) -> 'Case'
find_word('ACamelCaseString', 0) -> 'A'

My code:

def find_word(s, index):
    for i in range(index, 0, -1):
        if s[i].isupper():
            left = i
            break
    else:
        left = 0

    for i in range(index, len(s)-1):
        if s[i].islower() and s[i+1].isupper() or s[i:i+2].isupper():
            right = i
            break
    else:
        right = len(s) - 1

    return s[left:right+1]

Can this be made more concise/efficient?


texts:
so I've been working with R quite a while now, but due to very stressful deadlines in my last university module I had, I wrote code that I'm not very proud of. I would like to be more efficient in data wrangling, e.g. reading files, rearranging and cropping dfs. Here's a short excerpt of my code
 # Reading files
 org_bm <- read.delim("DE_gebesee_metrx_org_physiology-daily.txt")
 t_bm <- read.delim("DE_gebesee_metrx_t_physiology-daily.txt")
 co2_bm <- read.delim("DE_gebesee_metrx_co2_physiology-daily.txt")

# Format Dates
org_bm$datetime <- as_datetime(org_bm$datetime) + years(98)
t_bm$datetime <- as_datetime(t_bm$datetime) + years(98)
co2_bm$datetime <- as_datetime(co2_bm$datetime) + years(98)

# Select cols
org_ghg <- select(org_ghg, c(datetime,
                         aN_n2o_emis.kgNha.1.,
                         aC_ch4_emis.kgCha.1.,
                         aC_co2_emis_hetero.kgCha.1.,
                         aC_co2_emis_auto.kgCha.1.))
t_ghg <- select(t_ghg, c(datetime,
                     aN_n2o_emis.kgNha.1.,
                     aC_ch4_emis.kgCha.1.,
                     aC_co2_emis_hetero.kgCha.1.,
                     aC_co2_emis_auto.kgCha.1.))
co2_ghg <- select(co2_ghg, c(datetime,
                         aN_n2o_emis.kgNha.1.,
                         aC_ch4_emis.kgCha.1.,
                         aC_co2_emis_hetero.kgCha.1.,
                         aC_co2_emis_auto.kgCha.1.))

As you can see I mastered c/p and "search and replace" XD
But seriously, I'm wondering how I could "automate" these tasks. Maybe loading everything into a list and than write helper functions to apply certain actions (i.e. date formatting, selecting cols) to every list entry ?
I've always struggled to find good practice tasks, b/c during class I usually don't have the time to read up on nicer ways to make things work. So if anybody has some suggestions on where to find exercises on data analysis tasks, I would very much appreciate that.
Looking forward to read your replies !
Leon


texts:
To brush up my Python knowledge I an algorithm to generate permutations in lexicographic order. I ended up with the following code:

def swap(a, i, j):
    tmp = a[i]
    a[i] = a[j]
    a[j] = tmp

def next_permutation(a):
    n = len(a)
    if n == 0 or n == 1:
        return False
    kFound = False
    for k in reversed(range(n - 1)):
        if a[k] < a[k + 1]:
            kFound = True
            break
    if not kFound:
        return False

    for l in reversed(range(n)):
        if a[k] < a[l]:
            break
    swap(a, k, l)
    return a[:k + 1] + [i for i in reversed(a[k + 1:])]

I did a lot of C++ and miss std::swap(..), what is the proper way to do this in Python? In the last line, because reversed(..) returns an iterator I cannot write simply: a[:k + 1] + reversed(a[k + 1:]), is there a simpler way to trigger the unfolding of the iterator into a list?


texts:
I am working on a website for a group of artists and want to know of a way to make my code cleaner and my website run faster. I am working on the gallery page, and there are over 100 pictures I want to show. I have been entering them in as shown below, but I know there must be a better way to try and do this, but I just need some help.

/*****************************
    PIC GALLERY
*****************************/

.gallerySize {
  /*height: 25%;*/
  /* overflow-x:30%;*/
}
.galleryContainer {
  margin-top: 5%;
  width: 90%;
  overflow-x: scroll;
  overflow-y: hidden;
  /*height: 15%;*/
  /*margin: 2%;*/
  /*height: 10%;*/
}
. .galleryContainer img {
  height: 171px;
  width: 180px;
}
.profile {
  margin-top: 5%;
}
.galleryContainer img {
  height: 300px;
  width: 400px;
}
.fullDrawing img {
  height: 117.273px;
  width: 1042.273px;
}
.topImg {
  margin: 5% 2% 0% 5%;
}
.list-inline {
  white-space: nowrap;
}
.galleryContainer > .row [class*="col-lg"],
.galleryContainer > .row [class*="col-md"],
.galleryContainer > .row [class*="col-md"] {
  float: none;
  display: inline-block;
  white-space: normal;
  vertical-align: top;
}
#main-content > .row {
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
}


texts: Cancelable AsyncLazy that is thread-safe

texts:
I've been thinking about the AsyncLazy<T> class that Stephen Toub and Stephen Cleary present in various resources such as this.  I am trying to find a way to integrate cancellation with AsyncLazy<T>.  Microsoft has a version of AsyncLazy<T> in their Visual Studio 2019 SDK that offers a GetValueAsync(CancellationToken) method, but if you read the fine print, it says:

  Note that this will not cancel the value factory (since other callers
  may exist).

I would like something that does cancel the value factory.  After failing to get anywhere with my research, I decided to attempt my own which is shown in the code below.  However, I'm having trouble with thread safety, as I don't want multiple threads to execute the long-running value factory. I want any thread that comes in behind the first one to essentially await the completion of that first thread, and then the subsequent thread would have the trivial task of just returning the already-created value.

Here is the code:

public sealed class CancelableAsyncLazy<T>
{
    private readonly Func<CancellationToken, Task<T>> _valueFactory;
    private T _createdValue;
    private bool _isValueCreated = false;
    private volatile bool _shouldWait = false;

    public CancelableAsyncLazy(Func<CancellationToken, Task<T>> valueFactory)
        => _valueFactory = valueFactory;

    public async Task<T> GetValueAsync(CancellationToken cancellationToken)
    {
        await Task.Run(() =>
        {
            while (_shouldWait) Thread.Sleep(1);
        });

        _shouldWait = true;

        try
        {
            if (_isValueCreated) return _createdValue;
            cancellationToken.ThrowIfCancellationRequested();
            _createdValue = await _valueFactory(cancellationToken).ConfigureAwait(false);
            _isValueCreated = true;
            return _createdValue;
        }
        finally
        {
            _shouldWait = false;
        }
    }
}

I don't like the fact that I'm using Task.Run and Thread.Sleep to wait for the value to be created by an earlier thread, but I can't think of a better way to do it.  The key is that it shouldn't block.  I tried using a Mutex, but it's possible the same thread could call the method before the value is created, so the subsequent call (from the same thread) would just blow past the Mutex.


texts:
I have the following PHP code but I'm unsure, based on the many things I've read, whether or not this is actually safe from an SQL injection attack.

$mysqli = new mysqli("address.address.address", "username", "password", "database");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare('INSERT INTO tablename (value) VALUES (?)');
$stmt->bind_param("s", $val);

$val = $_GET['val'];
$stmt->execute();

$stmt = $mysqli->prepare('SELECT * FROM tablename WHERE value = ?');
$stmt->bind_param('s', $val);

$val = $_GET['val'];

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['id'].'<br />';
}

$stmt->close();

$mysqli->close();

Can anyone offer their opinion on how to improve this, please?


texts: Optimizing very simple piece of “Game of Life” code by taking advantage of NumPy's functionality

texts:
Here is the code as it stands right now:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from random import randint

arraySize = 50
Z = np.array([[randint(0, 1) for x in range(arraySize)] for y in range(arraySize)])

def computeNeighbours(Z):
    rows, cols = len(Z), len(Z[0])
    N = np.zeros(np.shape(Z))

    for x in range(rows):
        for y in range(cols):
            Q = [q for q in [x-1, x, x+1] if ((q >= 0) and (q < cols))]
            R = [r for r in [y-1, y, y+1] if ((r >= 0) and (r < rows))]
            S = [Z[q][r] for q in Q for r in R if (q, r) != (x, y)]
            N[x][y] = sum(S)

    return N

def iterate(Z):
    Zprime = Z.copy()
    rows, cols = len(Zprime), len(Zprime[0])
    N = computeNeighbours(Zprime)

    for x in range(rows):
        for y in range(cols):
            if Zprime[x][y] == 1:
                if (N[x][y] < 2) or (N[x][y] > 3):
                    Zprime[x][y] = 0
            else:
                if (N[x][y] == 3):
                    Zprime[x][y] = 1

    return Zprime

fig = plt.figure()

Zs = [Z]
ims = []

for i in range(0, 100):
    im = plt.imshow(Zs[len(Zs)-1], interpolation = 'nearest', cmap='binary')
    ims.append([im])
    Zs.append(iterate(Zs[len(Zs)-1]))

ani = animation.ArtistAnimation(fig, ims, interval=250, blit=True)
plt.show()

I am interested in knowing what sequence of optimizations one would perform for this sort of an application, so that I can get a handle on how to use NumPy's power for my current project, which is simply a (perhaps) three dimensional, cellular automaton with many rules.


texts: Dealing with KB, MB, GB and TB and bytes

texts:
This function is simple, it gets a number of bytes and returns its representation in either Bytes, KB, MB, GB and TB.

As simple as it is, I am sure there are other (and perhaps better ways) to write it.

function kmgtbytes (num) {
    if (num > 0 ){
        if (num < 1024)             { return [num, "Bytes"] }
        if (num < 1048576)          { return [num/1024, "KB"] }
        if (num < 1073741824)       { return [num/1024/1024, "MB"] }
        if (num < 1099511600000)    { return [num/1024/1024/1024, "GB"] }

        return [num/1024/1024/1024/1024, "TB"]
    }

    return num
}


texts:
Is there a better way to do this? I'm kinda ending up having a lot of if statements.

if params[:custom_url] || params[:user_id]
    if !params[:user_id].blank?
      @user = User.find(params[:user_id]).first
      @url = @user.custom_url
    else
      @url = params[:custom_url]
      @user = User.where(:custom_url => @url).first
    end
end


texts: Updating an inventory with R using apply functions

texts:
I have created an inventory that works via QR codes. Briefly: the QR code codes for an email with the book/student checking it out. The email is downloaded into R using the gmailR package (code not shown). The info from the email is taken and added to a table which is compared to a master table (the inventory) and the changes are then made accordingly to update the master table.

The updating works by looking to see if the book is already IN or OUT and then simply flipping it to the opposite. And if it is being checked in the student and the date are erased (switched back to NA).

My original approach to updating the table was to use a function from the apply family but the problem I ran in to was that I do not want to change ALL rows in the master table but only the ones that need to be updated. I could not figure out a way to do this without using a for loop. Is there a way to write this code more efficiently, perhaps using apply, or via any other vectorized functions? Also, any other suggestions about my general design strategy/approach for this inventory would be appreciated.

(By the way, I know I should probably use the date class for the date column but don't worry about that for now).

## Sample data.
# new = List of books to update, the date, and student name.
# master = The inventory
new <- structure(list(book = structure(1:3, .Label = c("Almost moon", "Ava my story", "Catching fire"), class = "factor"), date = structure(c(1L, 1L, 1L), .Label = "8/23/15", class = "factor"), student = structure(1:3, .Label = c("John", "Mary", "Sue"), class = "factor")), .Names = c("book", "date", "student"), row.names = c(NA, -3L), class = "data.frame")
master <- structure(list(book = c("A trick I learned from dead men", "Almost moon", "Austin monthly july 2013", "Ava my story", "Becoming jane austen", "Bossypants", "Catching fire", "Cold mountain", "Comfort food", "Confessions of a jane austen addict"), author = c("Aldridge", "Sebold", "Various", "Gardner", "Spence", "Fey", "Collins", "Frazier", "Jacobs", "Rigler"), status = c("IN", "IN", "IN", "IN", "IN", "IN", "IN", "IN", "IN", "IN"), student = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), date = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("book", "author", "status", "student", "date"), row.names = c(NA, 10L), class = "data.frame")

## Update inventory
if(sum(new[,1] %in% master$book) == length(new[,1])) {
    matches <- which(master$book %in% new[,1])
    for(i in matches) {
        if(master[i, 3] == "IN") {
            master[i, 3] <- "OUT"
            master[i, 4] <- as.character(new[new$book == master[i, 1], "student"])
            master[i, 5] <- as.character(new[new$book == master[i, 1], "date"])
        } else if(master[i, 3] == "OUT") {
            master[i, 3] <- "IN"
            master[i, 4] <- NA
            master[i, 5] <- NA
        }
    }
} else {
    stop("At least one book not found in database")
}


texts: Find integer pairs in an array which adds to a given sum

texts:
I came up with the following solution.

Is there a better way to solve this problem than the proposed?
Also I used LinkedList to convey the result back to the API caller. Is there a better data structure to use?
I tried using a 2 dimensional array to store the pairs, but int creation requires a size, which we are not aware of until we evaluate the array. So I had to use a LinkedList where the size can be dynamic.

public class FindPairsInAnArrayAddingToASum {

    private static class ResultPair{
        ResultPair prev;
        ResultPair next;
        int a;
        int b;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] items = new int[]{1,2,3,4,5,5,6,7};
        System.out.println("Pairs: ");
        ResultPair currentNode = getPairsAddingToSum(items, 10);
        while(currentNode != null){
            System.out.println("--> "+currentNode.a+", "+currentNode.b);
            currentNode = currentNode.next;
        }
    }

    public static ResultPair getPairsAddingToSum(int[] items, int prescribedSum){
        ResultPair headNode = null;
        ResultPair currentNode = null;

        //Sort the array
        Arrays.sort(items);

        //Introduce left and right pointers
        int left = 0;
        int right = items.length-1;

        //Navigate from both directions
        while(left < right){
            if(items[left] + items[right] == prescribedSum){

                currentNode = addThePair(items[left], items[right], currentNode);

                //Save the head - Only the first time a node is created
                if(headNode == null)
                    headNode = currentNode;

                //Increment left and decrement right
                left++;
                right--;

            }else if(items[left] + items[right] < prescribedSum){
                left++;
            }else{
                right--;
            }
        }

        return headNode;
    }

    public static ResultPair addThePair(int a, int b, ResultPair currentNode){
        ResultPair newNode = new ResultPair();
        newNode.a = a;
        newNode.b = b;
        if(currentNode != null){
            currentNode.next = newNode;
            newNode.prev = currentNode;
        }
        return newNode;
    }

}


texts:
I have two tables : Category and ProductFilter.
Category table is hierarchy and I have depth in each row like it start at 1.
Categories in level two have List<ProductFilter>.

user clicked on category and I want to get ProductFilter to do this I have two code . which one is better :

1.

var category = _categories.Where(row => row.Code == categoryCode).FirstOrDefault();

var attributesModel =new  List<Entities.ProductFilter>();
if (category.Depth == 2)
    attributesModel = category.ProductFilters.ToList();
else if (category.Depth == 3)
    attributesModel = category.Parent.ProductFilters.ToList();
else if (category.Depth == 4)
    attributesModel = category.Parent.Parent.ProductFilters.ToList();

2.

var attributesModel =
    await _productFilters
        .Where(row => row.Categories.Any(c =>
            c.Code == categoryCode ||
            c.Categories.Any(item => item.Code==categoryCode)))
        .ToListAsync();


texts: Generating a not-the-same-as-last-time random number

texts:
I have to generate random number which differs from the number generated last time.

Which of these two variants is better? Or maybe you can suggest better implementation.

int generateRandom() {
    int randomNumber;
    do {
        randomNumber = random.nextInt(UPPER_BOUND);
    } while (randomNumber == lastRandomNumber);
    lastRandomNumber = randomNumber;
    return randomNumber;
}

vs

int generateRandom() {
    while (true) {
        int randomNumber = random.nextInt(UPPER_BOUND);
        if (randomNumber != lastRandomNumber) {
            lastRandomNumber = randomNumber;
            return randomNumber;
        }
    }
}


texts: Flood-clearing routine for a JavaFx Minesweeper

texts:
I really hate copy and pasting my code from one method to another. It signals something in my brain, "This could be done either more efficiently or more readable". This is used in a minesweeper program I am implementing with a JavaFx GUI (that's not very relevant, but it might help to know). Hopefully this is enough context!

@Contract(pure = true)
private int setMinX(int x){ return (x == 0 ? 0:(x-1)); }
@Contract(pure = true)
private int setMinY(int y){ return (y == 0 ? 0:(y-1)); }
@Contract(pure = true)
private int setMaxX(int x){ return (x == this.width-1 ? this.width-1 : x+1); }
@Contract(pure = true)
private int setMaxY(int y){ return (y == this.height-1 ? this.height-1 : y+1);}

private void adjacents(int x, int y){
    //calculate adjacents for the just placed mine
    int minX = setMinX(x);
    int minY = setMinY(y);
    int maxX = setMaxX(x);
    int maxY = setMaxY(y);

    if (this.mineField[minX][minY] != -1){ this.mineField[minX][minY] += 1; } //left top corner
    if (this.mineField[maxX][minY] != -1){ this.mineField[maxX][minY] += 1; } //right top corner
    if (this.mineField[maxX][maxY] != -1){ this.mineField[maxX][maxY] += 1; } // bottom right corner
    if (this.mineField[minX][maxY] != -1){ this.mineField[minX][maxY] += 1; } // bottom left corner

    if(x > 0 && x < this.width-1){
        if (this.mineField[x][minY] != -1){ this.mineField[x][minY] += 1; } // top-middle
        if (this.mineField[x][maxY] != -1){ this.mineField[x][maxY] += 1; } //bottom-middle
    }

    if(y > 0 && y < this.height-1){
        if (this.mineField[minX][y] != -1){ this.mineField[minX][y] += 1; } // left-middle
        if (this.mineField[maxX][y] != -1){ this.mineField[maxX][y] += 1; } //right-middle
    }
}

public void floodClear(int x, int y) {

    int minX = setMinX(x);
    int minY = setMinY(y);
    int maxX = setMaxX(x);
    int maxY = setMaxY(y);

    if (this.mineField[x][y] >= 0 && !this.liveGame[x][y]) {
        //IMPLEMENT WITH GUI
        //show(x,y);
        if (this.mineField[minX][minY] == 0) {
            floodClear(minX, minY);
        }
        if (this.mineField[maxX][minY] == 0) {
            floodClear(maxX, minY);
        }
        if (this.mineField[maxX][maxY] == 0) {
            floodClear(maxX, maxY);
        }
        if (this.mineField[minX][maxY] == 0) {
            floodClear(minX, maxY);
        }

        if (x > 0 && x < this.width - 1) {
            if (this.mineField[x][minY] == 0) {
                floodClear(x, minY);
            } // top-middle
            if (this.mineField[x][maxY] == 0) {
                floodClear(x, maxY);
            } //bottom-middle
        }

        if (y > 0 && y < this.height - 1) {
            if (this.mineField[minX][y] == 0) {
                floodClear(minX, y);
            } // left-middle
            if (this.mineField[maxX][y] == 0) {
                floodClear(maxX, y);
            }  //right-middle
        }
    }
}


texts: LinkedList of Nodes at each level - optimalization

texts:
That's already known problem: to return an array of linked lists that contain values of elements at each level. Eg for tree with depth n there should be n linked lists.

I wrote the solution:

public ArrayList<LinkedList<Integer>> levelLists() {

    class NodeLevel {
      public BinaryTreeNode node;
      public int level;

      public NodeLevel(BinaryTreeNode n, int l) {
        this.node = n;
        this.level = l;
      }
    }

    ArrayList<LinkedList<Integer>> levels = new ArrayList<LinkedList<Integer>>();
    Queue<NodeLevel> queue = new LinkedList<NodeLevel>();

    int currentLevel = -1;

    queue.add(new NodeLevel(root, 0));

    while (!queue.isEmpty()) {
      NodeLevel current = queue.poll();

      if (current.level != currentLevel) {
        levels.add(new LinkedList<Integer>());
        currentLevel++;
      }

      levels.get(levels.size() - 1).add(current.node.value);

      if (current.node.getLeftChild() != null) {
        queue.add(new NodeLevel(current.node.getLeftChild(), currentLevel + 1));
      }
      if (current.node.getRightChild() != null) {
        queue
            .add(new NodeLevel(current.node.getRightChild(), currentLevel + 1));
      }
    }

    return levels;
  }

But I am sure it's very space inefficient. I am quite sure it can be done without remembering level for each node (and so without this whole additional class NodeLevel). I was thinking about just adding null node to the queue at the end of each level, but still I don't know how to indicate  end of the level without this whole structure. Can anyone give me a hint?


texts: Large matrix with lots of repetitive fields (C++)

texts:
I wrote a timetabling program and I have been using a matrix to check for clashes between courses. Index (i, j) in the matrix tells us how many people are in both courses i and j.

My previous Matrix was just using nested vectors:

std::vector<std::vector<int>> clashes;

This would throw std::bad_alloc because the matrix is of dimension 18000 x 18000.

Since many of the entries would be 0, I made my own matrix class using unordered maps. This preserves a lot of data as it uses a default value for all of entries that have not been given a value.

template <typename T>
class UMapMatrix
{
public:

UMapMatrix(T default_val) : default_val(default_val) {
}

T get(const int& a, const int& b) const {
    int x, y;
    if (a < b) {
        x = a;
        y = b;
    }
    else {
        x = b;
        y = a;
    }

    auto search = data.find(x);
    if (search != data.end()) {
        auto search2 = search->second.find(y);
        if (search2 != search->second.end()) {
            return search2->second;
        }
    }
    return default_val;
}

void set(const int& a, const int& b, T val) {
    if (a < b) data[a][b] = val;
    else data[b][a] = val;
}

private:
T default_val;
std::unordered_map<int, std::unordered_map<int, T>> data;
};

Are there any significant improvements that could be made to the memory usage and/or speed?
Are there any other data structures that could be used here?


texts:
I've written a toy neural network in Java. I ran it several million times with the same outputs with only the randomized weights changing from run to run. The average of all of the outputs is not 0.5, as I would have expected. The code is in this Github Repository.

The Layer class:

public class Layer extends AbstractLayer {

    private double[][] weights;

    public Layer(int neurons, int prevLayerNeurons) {
        super(neurons);
        weights = new double[neurons][prevLayerNeurons + 1];
        randomize(weights);
    }

    protected void randomize(double[][] x) {
        for (int j = 0; j < x.length; j++) {
            for (int i = 0; i < x[j].length; i++) {
                weights[j][i] = Math.random();
            }
        }
    }

    @Override
    public double[] compute(double inputs[]) {
        Preconditions.checkArgument(inputs.length == weights[0].length - 1, "incorrect number of inputs");
        double[] ret = new double[neurons];
        for (int i = 0; i < neurons; i++) {
            double acc = 0;
            for (int j = 0; j < inputs.length; j++) {
                acc += inputs[j] * weights[i][j];
            }
            acc -= weights[i][weights[i].length - 1];
            acc = sigmoid(acc);
            ret[i] = acc;
        }
        return ret;
    }

    private double sigmoid(double x) {
        return 1 / (1 + Math.exp(-x));
    }
}

And the Network class:

public class Network {

    private List<AbstractLayer> layers;

    public Network(int[] neuronCounts) {
        layers = new LinkedList<AbstractLayer>();
        layers.add(new InputLayer(neuronCounts[0]));
        for (int i = 1; i < neuronCounts.length; i++) {
            layers.add(new Layer(neuronCounts[i], neuronCounts[i - 1]));
        }
    }

    public boolean[] run(double[] inputs) {
        double[] tmps = inputs;
        for (int i = 0; i < layers.size(); i++) {
            tmps = layers.get(i).compute(tmps);
        }
        boolean[] rets = new boolean[tmps.length];
        for (int i = 0; i < rets.length; i++) {
            rets[i] = tmps[i] > 0.5;
        }
        return rets;
    }

    public AbstractLayer getLayer(int i) {
        return layers.get(i);
    }

}

These are the most relevant classes, but there are several others in the repository.

As it stands now, the class Bootstrap will run a 3-layer network with a fixed arrangement and set of inputs.

I'd appreciate any comments on the structure of the program, and on the correctness (or incorrectness) of the output.


texts:
As the title indicates this is one of the last most problems of Project Euler. The problem is straightforward. However, similar to the rest of the Euler Project problems either Memory Error or long execution times are problems. An explanation of the problem is:

Consider the Fibonacci sequence \$\{1,2,3,5,8,13,21,\ldots\} \$.
We let \$f(n)\$ be the number of ways of representing an integer
\$n\ge 0\$  as the sum of different Fibonacci numbers. For example,
\$16 = 3+13 = 1+2+13 = 3+5+8 = 1+2+5+8\$ and hence \$f(16) = 4\$ . By
convention \$f(0) = 1\$ .
Further we define,  \$\displaystyle S(n) = \sum_{k=0}^n f(k)\$   You
are given \$S(100) = 415\$ and \$S(10^4) = 312807 \$  .
Find \$ \displaystyle S(10^{13})\$ .

I'll show my code, and then explain what I have done so far. Lastly, ask for any kind of help. Thanks in advance.
"""
    * EULER PROJECT PROBLEM 755
"""
import itertools

def sumOfList(aList):
    sumL = 0
    for x in aList:
        sumL += x
    yield sumL

mostList = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657,
             46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465,
             14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170,
             1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173,
             86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920,
             2504730781961, 4052739537881, 6557470319842]

def fibonList(x):
    fibonSeq = []
    firstT = 0

    while mostList[firstT] <= x:
        fibonSeq.append(mostList[firstT])
        firstT += 1

    yield fibonSeq

def powerset(iterable):
    b = list(set(iterable))
    for s in range(1, len(b) + 1):
        for comb in itertools.combinations(b, s):
            yield comb

def repWay(x):
    ways = 0
    for each in fibonList(x):
        for i, combo in enumerate(powerset(each), 1):
            for ea in sumOfList(combo):
                if ea == x:
                    ways += 1
    yield ways

def rangerepWays(x):
    generalSum = 0
    for i in range(x + 1):
        for x in repWay(i):
            generalSum += x
    yield generalSum + 1    # + 1 because 0 = 0, while creating fib list I didn't incorporate 0 into fiblist.

for x in rangerepWays(10 ** 2):
    print(x)

1- First: It works, but, unfortunately, is too slow.

I have tested the program with the given examples in the question and it works. It passed both.

2- Second: What I have done

As you can see, the functions don't return anything, instead, I used
generators to avoid Memory Error errors.
To prevent calculating Fibonacci numbers that are below a number at each recursion, I
first created mostList than created a list whose elements are
smaller than an upper limit.

3- Third: What else can be done?

I am aware of this is one of the last questions of the Euler Project. Therefore, probably it requires a deep knowledge of mathematics. However, I lack that. It is okay if you share just only the names of applicable formulas or theories. I can try them to implement my current code.
My code may also have algorithmic fallacies or misinterpretations of the question. If there is one, you can just mention where it is and why there is a problem, not the solution.

Thanks in advance!


texts:
I have code to ensure parameters existence all over the place. Is there a better way to do it? So that I do not have so many repeated codes inside different functions

export const requestUpdateAccountDetail = (
  firebase,
  uid,
  accountId,
  accountDetail = {}
) => {
  if (firebase === undefined) {
    throw Error('`firebase` instance is required')
  } else if (uid === undefined) {
    throw Error('`uid is required to update account detail`')
  } else if (accountId === undefined) {
    throw Error('`accountId` is required to update account detail')
  }

  return firebase.update(`/accounts/${uid}/${accountId}`, accountDetail)
}

export const requestAddNewAccount = (firebase, uid) => {
  if (firebase === undefined) {
    throw Error('`firebase` instance is required')
  } else if (uid === undefined) {
    throw Error('`uid is required to update account detail`')
  }

  const EMPTY_ACCOUNT_OBJ = {
    name: '',
    note: '',
    owner: uid
  }

  return firebase.push(`/accounts/${uid}`, EMPTY_ACCOUNT_OBJ)
}

export const requestDeleteAccount = (firebase, uid, accountId) => {
  if (firebase === undefined) {
    throw Error('`firebase` instance is required')
  } else if (uid === undefined) {
    throw Error('`uid is required to update account detail`')
  } else if (accountId === undefined) {
    throw Error('`accountId` is required to update account detail')
  }

  return firebase.remove(`/accounts/${uid}/${accountId}`)
}


texts:
I happened to delve into tkinter and created a couple of mini projects so I could get more familiar with it. I was wondering if there was any portion of my code or code structure that is sloppily written and could be more python-esque. As a beginner in both python and tkinter (been learning during this quarantine) it would be great if you fellow coders would be willing to give me some pointers about my code which will benefit me in the future (breaking bad habits now rather than later, creating good habits instead). Thanks!

from tkinter import *

window = Tk()
window.title("Basic Converter")

window.geometry("500x300+500+350")

#globally declare measurement variables
measurement1 = ""
measurement2 = ""

def convert_SI(val, unit_in, unit_out):     #based on unitconverters.net
    SI = {'Meter':1, 'Kilometer':1000, 'Centimeter':0.01, 'Millimeter':0.001,
          'Micrometer':0.000001, 'Mile':1609.35, 'Yard':0.9144, 'Foot':0.3048,
          'Inch':0.0254}
    return val*SI[unit_in]/SI[unit_out]

def helpsection():
    pass    #put helpful info text here (e.g. no entering in right entry box else error)

def selectedInput():
    global measurement1
    measurement1 = listbox.get(listbox.curselection())#whatever is currently selected

def selectedOutput():
    global measurement2
    measurement2 = listbox1.get(listbox1.curselection()) #whatever is currently selected

def converter():
    try:
        global measurement1, measurement2
        result.set(str(convert_SI(float(inputEntry.get()), measurement1, measurement2)))

    except:
        result.set("Error")

title = Label(window, text="Basic Converter", font="Calibri 16")
title.grid(columnspan=3)
result = StringVar()    #initalize dispalyed output variable
#create a top-level menu
filemenu = Menu(window)
filemenu.add_command(label='Help', command=helpsection)
window.config(menu=filemenu)    #displays menu
#input and output entry fields
inputEntry = Entry(window)
inputEntry.grid(row=1, column=0)
arrow = Label(window, text="--->", font="Calibri 20").grid(row=1, column=1)
outputEntry = Entry(window, textvariable=result).grid(row=1, column=2)

convertButton = Button(window, text='Convert!', command=converter).grid(row=2, column=1)

#if nonetype error, because .grid needs to be called on their own line since it always returns None
scrollbar = Scrollbar(window)   #left scrollbar
scrollbar.grid(row=2, column=0, sticky = NE + SE)
listbox = Listbox(window, exportselection=False)   #left listbox
#exportselection option in order to select 2 different listbox at same time
listbox.grid(row=2, column=0)

measurement_list = ['Meter', 'Kilometer', 'Centimeter', 'Millimeter',
                    'Micrometer', 'Mile', 'Yard', 'Foot', 'Inch']
for measurement in measurement_list:
    listbox.insert(END, measurement)
listbox.bind("<<ListboxSelect>>", lambda x: selectedInput())   #this instead of command= option
# attach listbox to scrollbar
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

scrollbar1 = Scrollbar(window)   #right scrollbar
scrollbar1.grid(row=2, column=2, sticky = NE + SE)   #add sticky if scrollbar not showing
listbox1 = Listbox(window, exportselection=False)   #right listbox
listbox1.grid(row=2, column=2)

for measurement in measurement_list:
    listbox1.insert(END, measurement)
listbox1.bind("<<ListboxSelect>>", lambda x: selectedOutput())
listbox1.config(yscrollcommand=scrollbar1.set)
scrollbar1.config(command=listbox1.yview)

#configure grid layout to adjust whenever window dimensions change
for i in range(3):
    window.grid_rowconfigure(i, weight=1)
    window.grid_columnconfigure(i, weight=1)

window.mainloop()


texts:
I am trying to program a skew logistic distribution function to return the PDF, the CDF, and (later) the inverse CDF.  Although there are several forms of skew logistic, this is for perhaps the most widely known, a variation of the skew normal distribution introduced by Azzalini and covered by Saralees Nadarajah.  Aside from a formal paper on Springer, it's covered in "Focus on African Diaspora Mathematics By Toka Diagana".  A Google search will turn up the book and the skew logistic portion starts at the bottom of page 41.

I am comfortable with the PDF function (included below), but I am struggling with the CDF, primarily because I am not quite familiar with the math.

Here's the skew logistic CDF taken from the formal paper on Springer (Nadarajah, S. The skew logistic distribution, AStA Adv Stat Anal (2009) 93: 187–203):

$$F(x)=\left\{\begin{array}{lr}1-2\sum_{j=0}^{\infty}\sum_{k=0}^{\infty}\binom{-1}{j}\binom{-2}{k}\frac{1}{1+\lambda j +k}\exp\left[-\frac{(1+\lambda j + k)x}{\beta}\right]&\text{if } x>0,\\
2\sum_{j=0}^{\infty}\sum_{k=0}^{\infty}\binom{-1}{j}\binom{-2}{k}\frac{1}{1+\lambda+\lambda j +k}\exp\left[\frac{(1+\lambda+\lambda j+k)x}{\beta}\right]&\text{if }x<0.\end{array}\right.$$

I understand everything except this portion:

$$\sum_{j=0}^{\infty} \sum_{k=0}^{\infty} \binom{-1}{j}\binom{-2}{k}$$

My current approach is to simply start with the value, step up and down by 0.0001 to sum the PDF in each direction, and then divide the area below the value by the total area.

However, this strikes me as extremely inefficient and inaccurate past five or six decimal places.  I have to believe a better function could be written based off the CDF formula Nadarajah gives.

Once I get the SkewLogisticCDF done properly, I'd like to also have a SkewLogisticCDFInverse as well.

// Skew Logistic PDF
double SkewLogisticPDF(double value, double location, double scale, double shape)
{

double x = exp((-(value - location)) / scale);
double y = exp((-(value - location)) * shape / scale);

x = 2 * x / (scale * pow(1 + x, 2) * (1 + y));

return x;
}

// Skew Logistic CDF
double SkewLogisticCDF(double value, double location, double scale, double shape)
{
const double step = 0.00001;
const double precision = 0.0000001;

double areaBelowValue = 0;
double areaAboveValue = 0;

double currentValue = 0;
double currentPDF = 0;

currentValue = value;
do
{
    currentPDF = SkewLogisticPDF(currentValue, location, scale, shape);
    areaBelowValue += currentPDF;

    currentValue -= step;

} while (currentPDF >= precision);

currentValue = value;
do
{
    currentPDF = SkewLogisticPDF(currentValue, location, scale, shape);
    areaAboveValue += currentPDF;

    currentValue += step;

} while (currentPDF >= precision);

double x = areaBelowValue / (areaBelowValue + areaAboveValue);

return x;
}


texts: Reorder the letters of one string to match the order of letters in a second string

texts:
I have a solution to the following problem that I'd like to know if there's a way I could decrease runtime complexity for.

The directions are: reorder the letters of the first string to match the order of the letters in the second string. If a letter in the first string is not present in the second string, add it to the end of the reordering.

Example input: 'shouts', 'soup'
Example output: 'ssouht'

My code is as follows:

const reOrderLetters = (string1,string2) => {
  let tailString = '';
  let newString = '';
  const mapped = {};

  for (let i=0;i<string1.length;i++) {
    let char = string1[i];
    if (string2.indexOf(char) !== -1) {
      if (!mapped[char]) {
        mapped[char] = char;
      } else {
        mapped[char] = mapped[char] += char;
      }
    } else {
      tailString += char;
    }
  }
  for (let i=0;i<string2.length;i++) {
    let char = string2[i];
    if (mapped[char]) {
      if (mapped[char].length > 1 && string2.slice(i+1).indexOf(char) !== -1) {
        newString += mapped[char].slice(mapped[char].length-1);
        mapped[char] = mapped[char].slice(0,mapped[char].length-1);
      } else {
        newString += mapped[char];
      }
    }
  }
  return newString += tailString;

}


texts: Reorder a list in Python to avoid repeats

texts:
I am trying to check if a list has any consecutive repeating elements and then reorder it such that the repeats are avoided. If that is impossible, then return False. For example:

checkRepeat([1,2])
Out[61]: [1, 2]

checkRepeat([1,2,2])
Out[62]: [2, 1, 2]

checkRepeat([1,2,2,1,1])
Out[63]: [1, 2, 1, 2, 1]

checkRepeat([1,2,2,1,1,3,3,3,3])
Out[64]: [1, 3, 1, 3, 2, 1, 3, 2, 3]

checkRepeat([1,2,2,1,1,3,3,3,3,3])
Out[65]: [3, 1, 3, 2, 3, 1, 3, 1, 3, 2]

checkRepeat([1,2,2,1,1,3,3,3,3,3,3])
Out[66]: [3, 1, 3, 1, 3, 1, 3, 2, 3, 2, 3]

checkRepeat([1,2,2,1,1,3,3,3,3,3,3,3])
Out[67]: False

Here is what I have. Is there a more elegant solution?

from itertools import groupby
from collections import Counter

def checkRepeat(lst):
    """Returns a list that has no repeating elements. Return False if such a list can't be found"""

    def hasRepeat(lst):
        """Returns true if there are any repeats"""
        return len([x[0] for x in groupby(lst)]) < len(lst)

    offset=numIter=0
    if Counter(lst).most_common()[0][1]*2 > len(lst)+1: #checks if it will be impossible to find a working order
        return False

    while hasRepeat(lst):
        for i,curElt in enumerate(lst):
            try:
                if lst[i]==lst[i+1]:
                    lst[i+1],lst[(i+offset) % len(lst)] = lst[(i+offset) % len(lst)],lst[i+1] #swap j+1 with j+offset. wrap around the list
            except:
                break
        offset+=1
        numIter+=1
    return lst


texts:
I have used PHPmailer to send email to users upon registering to the site. Now, everything works as should, however, I find myself doing painstaking work adding the HTML elements in.

Here's an example piece of HTML code:

This is a paragraph

 Now this is important!

Uh Oh!

Now in the PHP class, I would have to '' and . after each HTML element, so for example:

'
'.
'
'.
''.
'
'.
'
';

As you could imagine, doing this for a whole XHTML page, can take a very long time. I was wondering if there's a method that's quicker and more efficient than my technique.

Here's my entire PHP class that includes the HTML elements:

        $mail->Body =
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
        ''.
        ''.
        '  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'.
        '  <title>Demystifying Email Design</title>'.
        ' <link href="https://fonts.googleapis.com/css?family=Dosis" rel="stylesheet" type="text/css"/>'.
        '  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>'.
        ''.
        ''.
        '
'.
        '
'.
        ''.
        '
'.
        '
'.
        '
      '.
      '	'.
      '
'.
      '
'.
      ''.
      '
'.
      '
'.
      '';
      echo "Hello there hero!";
      '	'.
      '
'.
      '
'.
      '';
      echo " Cheesy heading, we know. BUT! Thanks for signing up with us! We just need you to do one, tiny little thing! You see that button down there? The big yellow one? We're going to need you to click that.. Seems daunting, but trust us. Once you do, you'll get access to all our websites features! Easy right? So go ahead, what are you waiting for?";
      '	'.
      '
'.
      '
'.
      ''.
      '
'.
      '
'.
      ''.
      '
'.
      ''.
      '
';
      echo "Verify Account!";
      '
'.
      '	'.
      '
'.
      '
';


texts: Handling a spinner for multiple REST calls

texts:
Context
In an Angular application, I have three <select> boxes that are fed from the database with a relatively small data set. These boxes are part of a filter Component that is displayed next to a server-side data table. The component outputs the filter asynchronously to the parent component, which then pipes into the table, invokes server, filters out SQL etc.
Focusing on the scope, when the control is loaded, I want to invoke the server with three GET invocations. Until they complete, I want to display a spinner.
Since I am using a library of controls, part of the code is already done. I want to ask here if I am handling the Observables correctly from the Angular point of view
Code I wrote so far
The code works
export class MyComponent implements OnInit, OnDestroy {

  public filterLoading$: BehaviorSubject<boolean>;
  public select1: Observable<string[]>;
  public select2: Observable<string[]>;
  public select3: Observable<string[]>;
  private filterLoadingSub$?: Subscription;

  constructor(private remoteService: RemoteService) {
    this.select1 = remoteService.getFirst();
    this.select2 = remoteService.getSecond();
    this.select3 = remoteService.getThird();
    this.filterLoading$ = new BehaviorSubject<boolean>(true);
  }

  ngOnInit(): void {
    this.filterLoadingSub$ = forkJoin([this.select1, this.select2, this.select3])
      .subscribe(() => this.filterLoading$.next(false))
    ;
  }

  ngOnDestroy(): void {
    if (!!this.filterLoadingSub$) {
      this.filterLoadingSub$.unsubscribe();
    }
  }

}

Explanation:

selectX are bound to the front end with <option *ngFor="let x of (selectX | async)" ...>
The subject filterLoading$ is used to display the spinner. Actually my custom accordion handles it for me <acme-filter-panel isLoaded="!(filterLoading$ | async)>
Then I used forkJoin operator to wait for the completion of all three calls. I don't care about the last returned valued, only that the three have completed. But this leads to a Subscription
Under the philosophy of dispose your own garbage, every time I hit a Subscription I always write code to unsubscribe. However, these are just HTTP calls that return only once when invoked.

I truly understand that I am not handling error logic, but really that goes beyond the scope of the question
Questions
My question is about two aspects.
Apart from moving code from constructor to ngOnInit, on reasons of symmetry, am I writing too much code or is there some simplification I can use to say Angular to unlock the spinner when all of the three invocations occurred?
Is it always necessary to always unsubscribe from subscriptions? Or are there cases in which a dangling subscription harms none? I learned that subscriptions use memory, so I deem necessary to clean up resources whenever possible, even if modern machines have gigabytes of RAM.
More in general, is it possible to write this piece in a more concise way? For three data sets I had to instantiate a fourth member, which is actually needed to monitor the spinner, and a fifth member used only on destruction to clean up. I often work with Observables & co.


texts:
I want to create a JS MVVM framework for learning and personal project.

jsFiddle

HTML:

<input type="text" mk="value=test" value="test" />

JS (markjs):

(function () {
    Mark = {};
    var mark = {
        text: {},
        value: {}
    };

    Mark.set = function (name, value) {
        for (var key in mark) {
            if (mark[key][name]) {
                mark[key][name].value = value;
                rejuvenate();
            }
        }
    }

    function rejuvenate() {
        for (var key in mark) {
            for (var name in mark[key]) {
                if (mark[key][name]) {
                    if (key === 'text') mark[key][name].node.innerText = mark[key][name].value;
                    else if (key === 'value') mark[key][name].node.value = mark[key][name].value;
                    else if (key === 'click') mark[key][name].node
                }
            }
        }
    }

    var elems = document.getElementsByTagName('*');
    for (var ii = 0; ii < elems.length; ii++) {
        if (elems[ii].getAttribute('mk')) {
            var marks = elems[ii].getAttribute('mk').split(';');
            if (marks.length > 0) {
                for (var jj = 0; jj < marks.length; jj++) {
                    var d = marks[jj].split('=');
                    if (d[0] === 'value' || d[0] === 'text') {
                        mark[d[0]][d[1]] = {
                            node: elems[ii],
                            name: d[1],
                            value: ''
                        };
                        if (d[0] === 'value') {
                            elems[ii].onkeydown = function (e) {
                                e = e || window.event;
                                var charCode = e.charCode || e.keyCode,
                                    character = String.fromCharCode(charCode),
                                    value = this.value;

                                var cmk = this.getAttribute('mk').split(';');
                                for (var cc = 0; cc < cmk.length; cc++) {
                                    var dd = cmk[cc].split('=');
                                    Mark.set(dd[1], value);
                                }
                            }
                        }

                    }
                }
            }
        }
    }
})();

Mark.set('test', 'Yoza');

I tried to create angular-model-like or ko-observable-like. I created a model name: test. If any mark (mk) with marker value=test update will update any element innerTextwith marker text=test. It's like KnockoutJS but for now I want to understand how it works. My problem is that input update is always late, not like Angular every type will update model.

I also provide Mark.set(name, value). It will update every marker with same name to that value.

Please help me to improve this code and review my code and concept.


texts:
We have a base interface:

        public interface IMessage
        {
            //Some properties
        }

then we have derived messages that implement this interface such as:

        public class AlarmEventMessage: IMessage
        {   //Some properties  }

Now, these messages get routed to a message handler that receives them.
So we have multiple overloads for this Handle(IMessage message) to handle the specific derived messages.

        public class MessageHandler
        {
             public bool Handle(IMessage message)
             {
                 if (message is AlarmEventMessage)
                 {
                     return Handle(message as AlarmEventMessage);
                 }
                 // some more message routing here
             }

             public bool Handle(AlarmEventMessage message)
             {
                 // Some business logic here
             }

             //Handle more messages here
        }

I believe it violates the Single-Responsibility Principle.  This class constantly keeps changing because of new messages being added and also the business logic that relates with this new message.

Are there any other SOLID principles it violates? Does it look like an Anti-Pattern?


texts: Programs for different language learning - Perl

texts:
I've created a program for my own purposes in three different languages, Perl, Python, and Ruby. Each program will be posted in with their own tag but I will add links to them through on each post. The program itself is very simple, all it does is ask the user about three different languages which are saved into an array, it then prompts the user to choose a language that runs through an if statement, and if the user chooses the language they're writing in it then takes a random language from the array and outputs it.

See also Python

See also Ruby

use strict;
use warnings;

sub welcome {
    my @choices = qw( Perl Python Ruby );
    my $lang = 3;
    print("Welcome, to the test script, this will test what language you would like to learn.. In order to find out these choices, write this same definition in all three different languages\n");
    print("There are  $lang, languages to chose from please pick one:\n");
    print "@choices\n";
    my $choice = <STDIN>;
    chomp $choice;
    if ($choice eq "Ruby") {
        print("You have chosen Ruby!\n");
    }
    elsif ($choice eq "Python") {
        print("You have chosen Python!\n");
    }
    else {
        print("You're already writing in Perl!! Let me choose for you:\n");
        my $rand_elm = @choices[rand @choices];
        print "$rand_elm\n"
    }
}
welcome();

Perl took me the longest out of all the programs I wrote, this was my first ever Perl script. With all the ; and the random symbols I had to use to make variables and arrays, it was defiantly hard. However I really enjoyed writing this in Perl, it was something different. Perl maxed out as the longest program at a total of 30 lines. At one point I kept getting an NameError that was due to me missing a ; at the chomp function. All in all I think Perl is definitely a great language to learn.

I also have some questions about Perl:

Is there any better syntax that I should be using here in order to shorten the program?
Does Perl have an equivalent to Ruby's puts?
Why is it easier to use a sub instead of a function?

example:

 welcome();
 # instead of
 sub welcome();