texts: Get a path between graph nodes using breadth-first search

texts:
This code is meant to implement a Graph class which has a method that returns a path between 2 nodes using breadth-first search.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

from queue import PriorityQueue
from collections import deque
from copy import deepcopy

class Graph:
    def __init__(self):
        self.nodes = dict()

    def add_node(self, id):
        new_node = Node(id)
        self.nodes[id] = new_node
        return new_node

    def get_node(self, id):
        node = self.nodes[id] if id in self.nodes else None
        return node

    def bfs(self, start, end):
        queue = PriorityQueue()
        queue.put((0, start))
        seen = set([start])
        parents = dict()

        while not queue.empty():
            cur_node = queue.get(0)[1]
            if cur_node is not end:
                for neighbour in cur_node.neighbours:
                    if neighbour not in seen:
                        dist_to_neighbour = cur_node.neighbours[neighbour]
                        queue.put((dist_to_neighbour, neighbour))
                        parents[neighbour] = cur_node
                        seen.add(neighbour)
            else:
                path = self.get_path(start, end, parents)
                return path
        return None

    def get_path(self, start, end, parents):
        path = deque([end])
        cur_node = end
        while cur_node is not start:
            cur_node = parents[cur_node]
            path.appendleft(cur_node)
        return list(path)

class Node:
    def __init__(self, id):
        self.id = id
        self.neighbours = dict()

    def add_neighbour(self, to, weight):
        self.neighbours[to] = weight

I have a few ideas about what might be improved but I'm not sure how to do it (or even if it's worth doing).

There might be a better way to do get_node() instead of squashing it into 2 lines like how I've done it.
Maybe cur_node = queue.get(0)[1] should be 2 lines?
Change dist_to_neighbour = cur_node.neighbours[neighbour] to use a method instead of using dictionary notation (which might be a little awkward). Maybe I should have a method instead?
Using something else instead of a deque in get_path() (especially in an interview context where deque might be a bit too exotic).
Have more comments?

Here is my previous attempt at this code. I've also used the answers to my depth-first search attempts here and here to write this code.


texts:
Exploring the VBA Application.InputBox method I've realized that catching user cancellation is tricky when type is reference, so return value is a range object.

As cancellation's return value is False I can't assign it to an object with Set, so I've created a UDF to return Nothing when user pressed cancel / Esc.

Function mjInputBox(prompt As String, title As String, default As Variant, dataType As Integer) As Variant

    If dataType = xlInputReference Then
        On Error GoTo InputCancelled
        Set mjInputBox = Application.InputBox(prompt:=prompt, title:=title, default:=default, Type:=dataType)
        On Error GoTo 0
    Else
        mjInputBox = Application.InputBox(prompt:=prompt, title:=title, default:=default, Type:=dataType)
    End If

    Exit Function

InputCancelled:
    Err.Clear
    Set mjInputBox = Nothing
End Function

(xlInputReference is a constant = 8)

Is it a good practice, or can I improve it?

having a one line code instead of the UDF would be a big improvement
According to MSDN:

  For example, for an input box that can accept both text and numbers,
  set Type to 1 + 2.

Is it possible to combine input types including reference too? (note that I can assign return value of inputBox without set which will combine my reference to a cell value, which isn't acceptable).


texts:
Part of my standard modules deal with my company's employees and linking them to/from various data sets.

The following are a series of enums/functions to handle peoples' names, namely an Enum for advisers and functions to:

Provide a collection of names associated to each adviser (e.g. their name before/after getting married)
Provide the current name of each adviser
Determine which adviser's name appears in a given string

Is this a good, maintainable, extensible system? Especially considering the possibility of new employees over time?

Option Explicit

Public Enum LuminAdviser
    MartinCotter = 1
    JonHussey = 2
    JeremySmith = 3
    JonathanBlair = 4
    JohnCusins = 5
    SarahCotter = 6
    MickyMahbubani = 7
End Enum

Public Function NameStringsFromAdviser(ByVal adviser As LuminAdviser) As Collection

    Dim coll As Collection
    Set coll = New Collection

    Select Case adviser

        Case JonHussey
        AddNameVariations coll, "Jon", "Hussey"

        Case MartinCotter
        AddNameVariations coll, "Martin", "Cotter"

        Case JeremySmith
        AddNameVariations coll, "Jeremy", "Smith"

        Case JonathanBlair
        AddNameVariations coll, "Jonathan", "Blair"

        Case SarahCotter
        AddNameVariations coll, "Sarah", "Cotter"
        AddNameVariations coll, "Sarah", "Oluwole"

        Case JohnCusins
        AddNameVariations coll, "John", "Cusins"

        Case MickyMahbubani
        AddNameVariations coll, "Micky", "Mahbubani"

    End Select

    Set NameStringsCollectionFromAdviser = coll

End Function

Public Sub AddNameVariations(ByRef coll As Collection, ByVal forename As String, ByVal surname As String)

    coll.Add forename & " " & surname
    coll.Add surname & ", " & forename

End Sub

Public Function CurrentNameStringFromAdviser(ByVal adviser As LuminAdviser) As String

    Dim nameString As String

    Select Case adviser

        Case JonHussey
        nameString = "Hussey, Jon"

        Case MartinCotter
        nameString = "Cotter, Martin"

        Case JeremySmith
        nameString = "Smith, Jeremy"

        Case JonathanBlair
        nameString = "Blair, Jonathan"

        Case SarahCotter
        nameString = "Oluwole, Sarah"

        Case JohnCusins
        nameString = "Cusins, John"

        Case MickyMahbubani
        nameString = "Mahbubani, Micky"

    End Select

    CurrentNameStringFromAdviser = nameString

End Function

Public Function AdviserFromString(ByVal str As String) As LuminAdviser

    Dim foundAdviser As Boolean
    foundAdviser = True

    Dim adviser As LuminAdviser

    If AdviserNameInString(JeremySmith, str) Then
        adviser = JeremySmith

    ElseIf AdviserNameInString(JohnCusins, str) Then
        adviser = JohnCusins

    ElseIf AdviserNameInString(JonathanBlair, str) Then
        adviser = JonathanBlair

    ElseIf AdviserNameInString(JonHussey, str) Then
        adviser = JonHussey

    ElseIf AdviserNameInString(MartinCotter, str) Then
        adviser = MartinCotter

    ElseIf AdviserNameInString(MickyMahbubani, str) Then
        adviser = MickyMahbubani

    ElseIf AdviserNameInString(SarahCotter, str) Then
        adviser = SarahCotter

    Else
        foundAdviser = False

    End If

    If Not foundAdviser Then PrintErrorMessage "Could not find any adviser in string: " & str

    AdviserFromString = adviser

End Function

Public Function AdviserNameInString(ByVal adviser As LuminAdviser, ByVal str As String) As Boolean

    Dim foundAdviser As Boolean
    foundAdviser = False

    Dim nameColl As Collection
    nameColl = NameStringsFromAdviser(adviser)

    Dim i As Long
    For i = 1 To nameColl.Count
        If InStr(1, str, nameColl(i)) > 0 Then
            foundAdviser = True
            Exit For
        End If
    Next i

    AdviserNameInString = foundAdviser

End Function


texts:
There are many PHP PDO classes out there, agreed. However I find they do not allow for flexibility. So I created one that helps reduce development time as little as it may be but it does the job (maybe apart from the disconnect part, but it allows to trace whether database is connected via $database->isConnected). Can you please point out any flaws and any possible improvements?

<?php
    class db
    {
        public $isConnected;
        protected $datab;
        public function __construct($username, $password, $host, $dbname, $options=array()){
            $this->isConnected = true;
            try {
                $this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
                $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            }
            catch(PDOException $e) {
                $this->isConnected = false;
                throw new Exception($e->getMessage());
            }
        }
        public function Disconnect(){
            $this->datab = null;
            $this->isConnected = false;
        }
        public function getRow($query, $params=array()){
            try{
                $stmt = $this->datab->prepare($query);
                $stmt->execute($params);
                return $stmt->fetch();
                }catch(PDOException $e){
                throw new Exception($e->getMessage());
            }
        }
        public function getRows($query, $params=array()){
            try{
                $stmt = $this->datab->prepare($query);
                $stmt->execute($params);
                return $stmt->fetchAll();
                }catch(PDOException $e){
                throw new Exception($e->getMessage());
            }
        }
        public function insertRow($query, $params){
            try{
                $stmt = $this->datab->prepare($query);
                $stmt->execute($params);
                }catch(PDOException $e){
                throw new Exception($e->getMessage());
            }
        }
        public function updateRow($query, $params){
            return $this->insertRow($query, $params);
        }
        public function deleteRow($query, $params){
            return $this->insertRow($query, $params);
        }
    }
    //USAGE
    /*
        Connecting to DataBase
        $database = new db("root", "", "localhost", "database", array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

        Getting row
        $getrow = $database->getRow("SELECT email, username FROM users WHERE username =?", array("yusaf"));

        Getting multiple rows
        $getrows = $database->getRows("SELECT id, username FROM users");

        inserting a row
        $insertrow = $database ->insertRow("INSERT INTO users (username, email) VALUES (?, ?)", array("yusaf", "yusaf@email.com"));

        updating existing row
        $updaterow = $database->updateRow("UPDATE users SET username = ?, email = ? WHERE id = ?", array("yusafk", "yusafk@email.com", "1"));

        delete a row
        $deleterow = $database->deleteRow("DELETE FROM users WHERE id = ?", array("1"));
        disconnecting from database
        $database->Disconnect();

        checking if database is connected
        if($database->isConnected){
        echo "you are connected to the database";
        }else{
        echo "you are not connected to the database";
        }

    */


texts:
I am using a long array of over 300 var & 7,000 lines of code written like this:

var a = [];
var b = [];
var c = [];
var d = [];
var e = [];

a[0] = "a";
b[0] = "b";
c[0] = "c";
d[0] = "d";
e[0] = "e";

a[1] = "1";
b[1] = "2";
c[1] = "3";
d[1] = "4";
e[1] = "5";

a[2] = "one";
b[2] = "two";
c[2] = "three";
d[2] = "four";
e[2] = "five";

Im guessing it is the same as a much cleaner and shorter -

var a = [a,1,one];
var b = [b,2,two];
var c = [c,3,three];
var d = [d,4,four];
var e = [e,5,five];

Is there an easy or automatic way to rewrite the original array like the 2nd method?


texts:
I implemented a general function for a depth-first-search (DFS) using JavaScript with default arguments and functions that need to be provided in order for it to work.

This function is using async & await, but both can be removed to make it synchronous.

Is the naming sensible?
Are there missing pieces that would be useful for a general DFS?
Any other improvements/suggestions/problems with this code?

async function dfs(
  v         = null,         // vertex `v` for the DFS starting point
  visited   = (v) => false, // function: return true/false if `v` was visited
  visit     = (v) => {},    // function: mark v as visited
  edges     = (v) => [],    // function: return list of vertices reachable from `v`
  previsit  = (v) => {},    // callback called before visiting edges
  postvisit = (v) => {},    // callback called after visiting edges
) {
  await previsit(v)
  await visit(v)
  Promise.all(
    edges(v).map(async (w) => {
      if (!visited(w))
        return await dfs(w, visited, visit, edges, previsit, postvisit)
    })
  )
  await postvisit(v)
}

async function testDfs() {
  const graph = [ // basic adjacency list graph
    { 'id': 'r', 'edges': ['a','b','c'] },
    { 'id': 'a', 'edges': ['b'] },
    { 'id': 'c', 'edges': ['r', 'a'] },
    { 'id': 'b', 'edges': ['d'] },
    { 'id': 'd', 'edges': [] },
  ]
  const visited = [] // list of visited vertex ids
  await dfs(
    graph[0],
    v => visited.includes(v.id),
    v => visited.push(v.id),
    v => graph.filter(w => v['edges'].includes(w.id)),
    v => console.log(' pre', v.id),
    v => console.log('post', v.id)
  )
}

testDfs()


texts:
def mergesort( array ):
    # array is a list

    #base casee
    if len(array) <= 1:
        return array
    else:
        split = int(len(array)/2)
        #left and right will be sorted arrays
        left = mergesort(array[:split])
        right = mergesort(array[split:])

        sortedArray  = [0]*len(array)

        #sorted array "pointers"
        l = 0
        r = 0

        #merge routine
        for i in range(len(array)):

            try:
                #Fails if l or r excede the length of the array
                if left[l] < right[r]:
                    sortedArray[i] = left[l]
                    l = l+1
                else:
                    sortedArray[i] = right[r]
                    r = r+1
            except:
                if r < len(right):
                    #sortedArray[i] = right[r]
                    #r = r+1
                    for j in range(len(array) - r-l):
                        sortedArray[i+j] = right[r+j]
                    break
                else:
                    #sortedArray[i] = left[l]
                    #l = l+1
                    for j in range( len(array) - r-l):
                        sortedArray[i+j] = left[l+j]
                    break

        return sortedArray


texts:
I'm starting to learn C and thought it would be a good idea to try and implement some data structures. I started with a very simple stack and would like to hear some opinions.

Stack.c

#include <stdio.h>
#include <stdlib.h>
#include "stack.h"

struct Node {
    int element;
    struct Node* next;
};

struct Node* head;
int size;

int stack_init() {
    struct Node* dummy = malloc(sizeof(struct Node));
    if(dummy == NULL) {
        return -1;
    }
    head = dummy;
    return 0;
}

int push(int value) {
    struct Node* tmp = malloc(sizeof(struct Node));
    if (tmp == NULL) {
        return -1;
    }
    tmp->element = value;
    tmp->next = head;
    head = tmp;
    size++;
    return 0;
}

int pop() {
   if(size == 0) {
        printf("Stack is empty\n");
    }else {
        printf("Element #%d ->value: %d  has been removed\n", size, head->element);
        free(head);
        head = head->next;
        size--;
    }
    return 0;
}

void print_stack() {
    struct Node* tmp = head;
    printf("Stacksize: %d\n", size);
    for(int i = 0;i < size;i++) {
        printf("Element %d -> %d\n",i,tmp->element);
        tmp = tmp->next;
    }
    printf("#####################\n");
}

int get_size() {
    return size;
}

Stack.h

#ifndef STACK_H
#define STACK_H

int stack_init();

int push(int value);

int pop();

void print_stack();

#endif


texts:
I wrote the following code to read a config file line by line and split each line into 2 parts and store them separately.  The split is done on the basis of a delimiter =:

std::ifstream configfile(path_string.c_str());
std::string line;

std::vector<std::string> linesOfConfigFile;
while (std::getline(configfile, line))
    linesOfConfigFile.push_back(line);

configfile.close();

std::string currentItem;
char delimeter = '=';

std::vector<std::string> RHS;
std::vector<long long> LHS;

bool flag = false;
for (int i =0; i<linesOfConfigFile.size(); i++)
{
    std::stringstream singleLine(linesOfConfigFile[i]);

    while(std::getline(singleLine, currentItem, delimeter))
    {
        if(flag == true)
        {
            RHS.push_back(currentItem);
            flag = false;
        }
        else if (flag == false)
        {
            long long orderbookId = 0;
            <some library class>::toNumeric(currentItem, orderbookId);
            LHS.push_back(orderbookId);
            flag = true;
        }
    }
}

for(int i=0; i<RHS.size(); i++)
    StorageMap.insert( std::pair<long long, std::string>( LHS[i], RHS[i]) );

The review comment I got was this:

  The below code can be written in a better way, Need not use a Boolean flag to differentiate RHS and LHS. The outer for loops should be sufficient.

I cannot understand what difference he wishes to have. Can someone please help me?


texts: Stored procedure where column to ORDER BY depends on input parameters

texts:
I'm getting three inputs and based on those three inputs, I'm returning. Input items may vary, so I used CASE WHEN statements here.

Is this code correct? If so, how can I make it more optimized?

ALTER Procedure [dbo].[WP_GetAllItems]
    @IsActive     bit,
    @OrderMode    bit,
    @OrderBy      varchar(75)
as
Begin
    Select ItemPartNumber, ItemDescription, CreatedDate, InitialPrice from Items where IsActive = @IsActive order by
    CASE WHEN @OrderBy='ItemDescription' AND @OrderMode = 0 THEN ItemDescription END ASC,
    CASE WHEN @OrderBy='ItemDescription' AND @OrderMode = 1 THEN ItemDescription END DESC,
    CASE WHEN @OrderBy='ItemPartNumber' AND @OrderMode = 0 THEN ItemPartNumber END ASC,
    CASE WHEN @OrderBy='ItemPartNumber' AND @OrderMode = 1 THEN ItemPartNumber END DESC,
    CASE WHEN @OrderBy='CreatedDate' AND @OrderMode = 0 THEN CreatedDate END ASC,
    CASE WHEN @OrderBy='CreatedDate' AND @OrderMode = 1 THEN CreatedDate END DESC,
    CASE WHEN @OrderBy='InitialPrice' AND @OrderMode = 0 THEN InitialPrice END ASC,
    CASE WHEN @OrderBy='InitialPrice' AND @OrderMode = 1 THEN InitialPrice END DESC
End


texts:
I've written the code below to compare the two columns of choice of two different excel files (new data and a reference file). If a value in the new data file is present in the reference file, "yes" is added in a new column behind the value in the new data file and "no" if not. The columns to compare can be anything you want and can be specified in the top of the script.

The script does the trick for small datasets (few 100 to few 1000 rows). However, I'm currently comparing two files where each files has ~300 000 columns. It has currently analysed +/- 56% of the new data file rows in ~18 hours. So the script needs to run nearly 36 hours to complete.  It appears that Python only processes ~2 rows per second, hence the time.

Is there a way to speed up this process? I was thinking that perhaps a list comprehension could add a little bit to the speed, but it seems complex to write this as a list comprehension. Any other suggestions?

PS: The error raises perhaps seem redundant but as I'm no Python expert I was experimenting with error raising.

#======SPECIFY COLUMNS TO COMPARE======#
data_column = "column name"
ref_column ="column name"

#=====================================#

import os

basedir = r'C:\path'
datadir = os.path.join(basedir, "data")
refdir = os.path.join(basedir, "ref_db")
exportdir = os.path.join(basedir, "export")

import pandas as pd

#select the excel file (with any name) in the data folder
data_list = [os.path.join(datadir,file) for file in os.listdir(datadir) if file.endswith(".xlsx")]

if len(data_list) == 0:
    raise ImportError("There is no excel file in the data folder")
elif len(data_list) > 1:
    raise ImportError("There is more than 1 excel file in the data folder")

#data_list is a list of excel files in the folder. Select the one with index 0 as this should be the only one present.
new_data = pd.read_excel(data_list[0])

new_data[str("Comparison"+"_"+data_column)] = ""

#load the reference database in the export folder
ref_list = [os.path.join(refdir,file) for file in os.listdir(refdir) if file.endswith(".xlsx")]

if len(ref_list) == 0:
    raise ImportError("There is no excel file in the ref_db folder")
elif len(ref_list) > 1:
    raise ImportError("There is more than 1 excel file in the ref_db folder")

ref_db = pd.read_excel(ref_list[0])

#check if specified columns occur in the excel files
if not data_column in new_data.columns:
    raise KeyError("specified data_column does not exist in the input data file")

if not ref_column in ref_db.columns:
    raise KeyError("specified ref_column does not exist in the input data file")

warn = []

for i,col in enumerate(new_data[data_column]): #iterate over each row in the specified column + save the index "i"

    if col in ref_db[ref_column].values: #check if the value col at index i of new_data occurs in the reference database:

        new_data[str("Comparison"+"_"+data_column)][i] = "yes"

        count = ref_db.groupby(ref_column).size()

        if count[col] > 1:
          warn.append(["WARNING: value",col,"occurs multiple times in column",ref_column,"of the ref_db excel file"])
     #if no:
    else: #assign "no" to the column
        new_data[str("Comparison"+"_"+data_column)][i] = "no"

    #print("Processing sequence",i,"of",len(new_data["sequence"])) #print the progress of the matching process
    print(round((i/len(new_data[data_column]))*100,2),"% of entries processed")

for i,j in enumerate(warn):
    print(*warn[i])

new_data.to_excel(os.path.join(exportdir, "compare_export.xlsx")) #save the file to the export folder


texts: overload c++ enum class operators and enable check value set

texts:
I use c++ 11 enum class usually instead of the old enums because many enums can contain the same value
but as known they don't have the bitwise operators out of the box so we should define them manually

in windows it's already done for us with this macro in windows.h header :

DEFINE_ENUM_FLAG_OPERATORS

but I then encountered another problem

if I use these enum as flags I can put many values in the falg using bitwise operator | , but to test if the flag contains a value I can't check with bitwise operator & like this :

if (flags & value) {...}

I could however write a template function like this to test :

template <class T>
constexpr bool has_value(T flags, T value)
{
    return (std::underlying_type_t<T>)flags & (std::underlying_type_t<T>)value;
}

but I really would like to use the old format to test for values in the flags
I already found a solution on github which wrapped all chosen emums in a class called flags and it was used like the old ones but with the type safety of enum classes

As I don't want to use templates for this purpose and I want only operator & to give me a bool value in if expressions , I used another class that holds the enum value and can be converted to bool and this is what I wrote

#define OVERLOAD_ENUM_OPERATORS(x) \
class EnumBool##x \
{ \
    x enum_value; \
public: \
    constexpr EnumBool##x(const x e_val) : enum_value(e_val) {} \
    constexpr operator x() const { return enum_value; } \
    explicit operator bool() const { return (std::underlying_type_t<x>)enum_value != 0; } \
}; \
inline constexpr EnumBool##x operator&(const x lhs, const x rhs) \
{ \
    return EnumBool##x((x)((std::underlying_type_t<x>)lhs & (std::underlying_type_t<x>)rhs)); \
} \
inline constexpr x operator|(const x lhs, const x rhs) \
{ \
    return (x)((std::underlying_type_t<x>)lhs | (std::underlying_type_t<x>)rhs); \
} \
inline constexpr x operator^(const x lhs, const x rhs) \
{ \
    return (x)((std::underlying_type_t<x>)lhs ^ (std::underlying_type_t<x>)rhs);\
} \
inline constexpr x operator~(const x lhs) \
{ \
    return (x)(~(std::underlying_type_t<x>)lhs);\
} \
inline constexpr x& operator|=(x& lhs, const x rhs) \
{ \
    lhs = (x)((std::underlying_type_t<x>)lhs | (std::underlying_type_t<x>)rhs); \
    return lhs; \
} \
inline constexpr x& operator&=(x& lhs, const x rhs) \
{ \
    lhs = (x)((std::underlying_type_t<x>)lhs & (std::underlying_type_t<x>)rhs); \
    return lhs; \
} \
inline constexpr x& operator^=(x& lhs, const x rhs) \
{ \
    lhs = (x)((std::underlying_type_t<x>)lhs ^ (std::underlying_type_t<x>)rhs); \
    return lhs; \
} \
inline constexpr bool operator==(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs == (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator!=(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs != (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator>(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs > (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator<(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs < (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator>=(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs >= (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator<=(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs <= (std::underlying_type_t<x>)rhs; \
}


texts: Print 2 double arrrays, the second one should be cumulative totals of the elements of the first array

texts:
Please tell me how bad is the code...in the book he said it's possible with either nested loop, or 1 loop

The user should provide the 8 double numbers for the program to set the cumulative totals in the second array.

This is the code:

#include <stdio.h>
#define ASIZE 8

int main()

{
    int index = 0, x, index2;
    double cal;
    double array1[ASIZE], array2[ASIZE];

    printf("Please enter 8 numbers:\n");
    for (index = 0; index < ASIZE; index++)//adding the numbers to the first array
    {
        scanf("%lf", &array1[index]);
    }

    for (x = 0,index2 = 0,index = 0; x < ASIZE; x++, index2++)//adding the second array the elements
    {
        cal += array1[index++];
        array2[index2] = cal;
    }

    printf("the first array numbers are:\n");//printing the first array numbers
    for (index = 0; index < ASIZE; index++)
    {
        printf("%.1lf ", array1[index]);
    }
    printf("\n");
    printf("\n");
    printf("the second array numbers are:\n");//printing the second array
    for (index2 = 0; index2 < ASIZE; index2++)
    {
        printf("%.1lf ", array2[index2]);
    }

}

I'm a beginner in C, and its important for me to know how to get better.


texts: Security of login form using prepared statements

texts:
I've prepared a simple login form, using prepared statements to prevent SQL injections. How secure is this ?

    <title>Login</title>
        <?php
        session_start();

        // set up a token
        $form_token = md5(uniqid('auth', true));

        // session form token
        $_SESSION['form_token'] = $form_token;

        if (isset($_SESSION['user_id'])) {
            print "You're already logged in";
        }
    ?>

Login!

    <?php
    if (isset($_SESSION['user_id'])) {
        print "Log Out Here";
        exit;
    }
    ?>
    <form action="login.php" method="post">

Username :

        <input type="text" name="username" maxlength="20">

Password :

        <input type="text" name="pswd" maxlength="20">
        <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />

        <input type="submit" value="Login">
    </form>

Nothing too special on the form..
Now, the PHP that process the data:

    <title>Login</title>

    <?php
    session_start();
    $message = "";

    if (isset($_SESSION['user_id'])) {
        $message .= "You're already logged in
";
        print $message;
        print "Log Out Here";
        exit;
    }

    //
    // GET THE USER DATA
    //
    $username = $_POST['username'];
    $pswd = $_POST['pswd'];
    $form_token = $_POST['form_token'];

    //
    // CHECK THE DAATA
    //

    if (empty($username) || empty($pswd) || !isset($form_token)) {
        $message .= "Please enter a valid username/password
";
    }
    elseif ($form_token != $_SESSION['form_token']) {
        $message .= "Invalid Form Submission
";
    }
    elseif (strlen($username) > 20 || strlen($username) < 4) {
        $message .= "Invalid length for a username
";
    }
    elseif (strlen($pswd) > 20 || strlen($username) < 4) {
        $message .= "Invalid length for a username
";
    }
    else {

        // encrypting the password

    $pswd = sha1($pswd);

        // *********************
        // CONNECTING TO THE DATABASE
        // *********************

    $servername = "localhost";
    $usrname = "root";
    $password = "";
    $db_name = "auth";

    // connect to the database
    $conn = new mysqli($servername, $usrname, $password, $db_name);
    if ($conn->connect_error) {
        die("Connection failed".$conn->connect_error);
    }

    // statement
    $stmnt = $conn->prepare("SELECT username, pswd FROM users WHERE username = ? AND pswd = ?");
    $stmnt->bind_param('ss', $username, $pswd);

    $stmnt->execute();

    $result = $stmnt->get_result();
    if ($result->num_rows > 0) {
            $user_id = $result;
            $_SESSION['user_id'] = $result;
            $message .= "Succesfully Logged in!";
    }
    else {
        $message .= "Failed to Log In. Invalid Username or Password";
    }

    }

    ?>

<?php
    print $message;

?>


texts: Java Pub Sub implementation using broker

texts:
I have developed a simple pubsub event subscription in java. Something similar to this thread

Simple Pub-Sub Event Emitter

These are the goals.

Class should be able to "listen" to events happening in the module.
It should be disconnected from the event emitter. That is, the listeners shouldn't have to know which classes may be emitting events.
All the subscribers should be notified parallelly.

My Broker.java

import java.util.*;

public final class  Broker {
    private Object mutex = new Object();
    static class CommonTopics{
        private CommonTopics(){}
        public static final String ON_CACHE_RESET = "onCacheReset";
    }
    private static Broker brokerInstance;
    private Broker(){

    }
    public static Broker getInstance(){
        if(null== brokerInstance){
            brokerInstance = new Broker();
        }
        return brokerInstance;
    }

    private Map<String, Set<Subscriber>> subscribers = new HashMap<>();

    public boolean deregister(String topic, Subscriber subscriber) {
        synchronized (mutex) {
            final Set<Subscriber> subs = this.subscribers.get(topic);
            return subs.remove(subscriber);
        }
    }

    public boolean register(String topic, Subscriber subscriber) {
        boolean returnVal;
        synchronized (mutex) {
            if (subscribers.containsKey(topic)) {
                returnVal = subscribers.get(topic).add(subscriber);
            } else {
                Set<Subscriber> sub = new HashSet<>();
                returnVal = sub.add(subscriber);
                subscribers.put(topic, sub);
            }
        }
        return returnVal;
    }

    public void sendMessage(String topic,Map map){
        synchronized (mutex) {
            final Set<Subscriber> sub = this.subscribers.get(topic);
            sub.parallelStream().forEach(subscriber -> subscriber.update(map));
        }
    }

}

My Subscriber interface

import java.util.Map;

public interface Subscriber {
    public void update(Map map);
}

And an example subscriber

import java.util.Map;

public class ExampleSubscriber implements Subscriber {
    @Override
    public void update(Map map) {
        System.out.println(map.get("oldCachedValue"));
        System.out.println(map.get("newCachedValue"));
    }

    public static void main(String[] args) {
        ExampleSubscriber subscriber = new ExampleSubscriber();
        Broker.getInstance().register(Broker.CommonTopics.ON_CACHE_RESET,subscriber);
    }
}

Example event emmitter

Map m = new HashMap();
        m.put("oldCachedValue","Yes");
        m.put("newCachedValue","No");
        Broker.getInstance().sendMessage(Broker.CommonTopics.ON_CACHE_RESET,m);


texts: Faster binary search to find the index in Python?

texts:
I am implementing a binary search algorithm and my code is as shown bellow:
def binary_search(a, x):
    left, right = 0, len(a)
    if right == 0: return -1
    if x < a[0] or x > a[-1]:
        return -1
    elif x == a[0]:
        return 0
    elif x == a[-1]:
        return right - 1
    mid = right // 2
    a_mid = a[mid]
    if x == a_mid:
        return mid
    elif x < a_mid:
        return binary_search(a[left:mid], x)
    elif x > a_mid:
        idx = binary_search(a[mid+1:right], x)
        if idx == -1:
            return -1
        else:
            return mid + 1 + idx

I tested it and cannot find any way to improve it by complexity. Someone suggested that I may "have used an incorrect base condition to terminate your loop" but I still cannot figure out where the problem lies.
Could anyone please help? Thanks in advance.


texts:
Looking for feedback on correctness and code structure.

Follow up to:

SStorage (remember) - v0

Note that b.c. the user can only change the storage type when logging in, there is no need to copy back and forth between storage types.

/***************************************************************************************************
**SStorage - handles remember option of logging in and namespaces the domain as well
*/
    var SStorage = $A.Class.create({
        Name: 'SStorage',
        A: {

            // storage type
            storage:    null,

            // set the namespace here
            ns:         'arcmarks_',

            // storage key which keeps track of storage type
            indicator:  'arcmarks_h_token'
        },

        // type of storage is set when the user logs in
        // and called below
        setType: function (remember) {
            this.A.storage = remember ? $A.localStorage : $A.sessionStorage;
        },

        // determine type of storage at load MUserAny
        load: function () {
            this.setType($A.localStorage[this.A.indicator]);
        },

        // basic setters and getters with namespacing
        set: function (key, value) {
            this.A.storage[this.A.ns + key] = value;
        },
        get: function (key) {
            return this.A.storage[this.A.ns + key];
        },
        setObj: function (o) {
            $A.someKey(o, function (val, key) {
                this.A.storage[this.A.ns + key] = val;
            }, this);
        },
        getObj: function () {
            var o = {},
                real_key,
                namespace;
            $A.someKey(this.A.storage, function (val, key) {

                // retrieves after the name-space
                real_key = key.slice(this.A.ns.length);

                // retrieves the name-space
                namespace = key.slice(0, this.A.ns.length);
                if (namespace === this.A.ns) {
                    o[real_key] = val;
                }
            }, this);
            return o;
        },

        // clear only namespaced items
        clear: function () {
            var key;
            for (key in this.A.storage) {
                if (key.slice(0, this.A.len) === this.A.ns) {
                    this.A.storage.removeItem(key);
                }
            }
        }
    }, true);


texts:
Hide email characters:

When email only has one letter then just cover that letter with the * symbol e.g. *@gmail.com

When email has two letters then cover second letter with the symbol * e.g. t*@gmail.com

When email has three letters then cover second and third with the symbol * e.g. t**gmail.com

When email has four or more letters then show first three letters and add 4 stars at the ends - e.g.
tim****@gmail.com
tom****@gmail.com

My code works but I feel like its way too much hard-coding and can be done much cleaner
public static String hideSomeOfEmailValue(String privateEmail) {
StringBuilder stringBuilder = new StringBuilder(privateEmail);
int atSignIndex = privateEmail.indexOf("@");
String emailName = privateEmail.substring(0, atSignIndex);

if (emailName.length() == 1) {
    return stringBuilder.replace(0, emailName.length(), "*").toString();
}
if (emailName.length() > 1 && emailName.length() < 4) {
    return stringBuilder.replace(1, atSignIndex, StringUtils.repeat("*", emailName.length() - 1)).toString();
} else {
    stringBuilder = new StringBuilder(privateEmail.substring(0, 2));
    String emailProvider = privateEmail.substring(atSignIndex);
    stringBuilder.append("****").append(emailProvider);
    return stringBuilder.toString();
}

locate at what index at sign located
trim  everything until at sign which gives us name of the email only so we can easily.


texts: Create a matrix with all elements having the value of the shortest path to a given position

texts:
You're given the number of rows and columns and the indices for the reference point. Reference point is = 0.
i.e:
3 4 3 3
output:
4 3 2 3
3 2 1 2
2 1 0 1

I managed to solve the problem using the easiest solution there is. I calculated the elements from the same column, and then using 2 for loops I used for every single element the already calculated value from the respective row as a new reference point.
I was stuck on this at first because I tried to come up with a formula so I asked on stackoverflow, and told me to submit a code, any solution.. so I came up with this:

#include <iostream>
using namespace std;
int main()
{
    int v[501][501], i, j, m, n, o, p;
    cin >> m >> n >> o >> p;
    for (i = o; i >= 1; i--)
            v[i][p] = o - i;
    for(i = o;i <= m; i++)
        v[i][p] = i - o;
    for(i = 1; i <= m; i++)
        for(j = 1; j <= n; j++){
            if(j < p)
                v[i][j] = -j + p + v[i][p];
            else if(j > p)
                v[i][j] = j - p + v[i][p];
        }
    for(i = 1 ; i <= m; i++){
        for(j = 1; j <= n; j++)
            cout << v[i][j] << " ";
        cout << '\n';
    }
}

How can I improve it?


texts: Dynamic Dispatch replacement for Generic methods

texts:
Type erasure is giving me nuts recently. I'm designing a class that performs symbolic differentiation on a math expression represented as a binary expression tree. The question is more on the design part than on the actual code part so I'm only giving out the method that looks awful to me.

public Node derive(final Node currentNode, Node parentNode) {
    Node dxNode = null;

    final Object cDataContext = currentNode.getData();
    if (Number.class.isAssignableFrom(cDataContext.getClass()))
        dxNode = new TreeNode<Double>(0.0);
    else if (AddOperator.class.isAssignableFrom(cDataContext.getClass()))
        dxNode = deriveAddContext((Node<AddOperator>) currentNode);
    else if (MulOperator.class.isAssignableFrom(cDataContext.getClass()))
        dxNode = deriveMulContext((Node<MulOperator>) currentNode);
    else if (SineFunction.class.isAssignableFrom(cDataContext.getClass()))
        dxNode = deriveSineContext((Node<SineFunction>) currentNode);

    if (dxNode != null && parentNode != null)
        dxNode.setParent(parentNode);

    return dxNode;
}

I think it already speaks for itself. I'm having methods with different names which is fine. The awful part at least for me is this huge if statement that I truncated for simplicity. Is there a better way of doing this? I mean I would love to live with dynamic dispatch having the whole derive method consisting of a simple:

Node dxNode = deriveNode(currentNode);
dxNode.setParent(parentNode);
return dxNode;

I guess Java won't give me this luxury so perhaps there is some design pattern that I can utilize here? Just to give you a better understanding of the algorithm I'll show a sample method:

private Node<AddOperator> deriveAddContext(final Node<AddOperator> additionContext) {
    // d/dx [f(x) + g(x)] = d/dx [f(x)] + d/dx [g(x)] => d/dx [f(x)] d/dx [g(x)] +

    // ROOT: ADD
    Node<AddOperator> dRoot = new TreeNode<AddOperator>(new AddOperator());
    // ROOT.LEFT: d/dx [f(x)]
    dRoot.setLeft(derive(additionContext.getLeft(), dRoot));
    // ROOT.RIGHT: d/dx [g(x)]
    dRoot.setRight(derive(additionContext.getRight(), dRoot));
    // RET: d/dx
    return dRoot;
}

So the whole algorithm is recursive on the expression traversing the original expr in an inorder fashion.

A Node has the following structure:

 dataField: <DataType>
 leftChild: Node
 rightChild: Node
 parent: Node


texts: Wordpress single post content class customization with if-else function

texts:
I have the following code, which displays the content for my custom page template "landingpage.php" and for single posts. The site is based on Bootstrap 4.
<?php if(is_page_template( 'landingpage.php' )): ?>

        <?php elseif (is_single()): ?>

        <?php else: ?>

<?php endif; ?>

Is there a more elegant and/or shorter way to achieve this?


texts: Getting the smallest possible integer ratio between two numbers

texts:
I wrote this code to find the smallest possible integer ratio between two numbers:

void ratio(int a, int b) {
    int min = Math.min(a, b);
    int max = Math.max(a, b);
    if(max % min == 0) {
               System.out.println("1" + " " + max / min);
               return;
        }
    for (int i = 2; i <= min; i++) {
        while(max % i == 0 && min % i == 0) {
            max /= i;
            min /= i;
        }
    }
    System.out.println(max + " " + min);
}

Is there any better/efficient way to do this? Am I missing any good algorithm?


texts: Creating a directory structure from JSON

texts:
I have a JSON file:

{
'Document':[

[{'fields': {'name': 'js/main.js', 'content': 'hello'}, 'pk': 284, 'model': 'Document'}],

[{'fields': {'name': 'css/main.css', 'content': '2'}, 'pk': 287, 'model': 'Document'}],

[{'fields': {'name': 'about_us.html', 'content': 'again hello'}, 'pk': 306, 'model': 'Document'}]],

'Package':
[{'fields': {'package_type': 'THEME', 'base_package': None, 'created_date': '2015-05-25T15:39:16.781Z', 'name': '25_may', 'rating_avg': 0.0, 'user': 2, 'rating_count': 0, 'is_published': True}, 'pk': 129, 'model': 'Package'}]

}

I want to generate directory structure based on JSON data:

25_may
|- css
|  |- main.css
|- js
|  |-main.js
|- about_us.html

Code to achieve above:

def my_func():
    package_name = response['Package'][0]['fields']['name']
    for doc in response['Document']:
        filename = os.path.join(package_name, doc[0]['fields']['name'])
        content = doc[0]['fields']['content']
        if not os.path.exists(os.path.dirname(filename)):
            os.makedirs(os.path.dirname(filename))
        with open(filename, "w") as f:
            f.write(content)

Is there an efficient and better way to do this?


texts:
After reading a certain question on the Stack Overflow website, I tried to write a solution to the problem just for fun. I'm, however, left with the nagging feeling there is a beautiful one-liner that can be used instead.
The question's premises:

Create a function that will receive a string. The function will count each vowel in the string, and return a count of all the vowels, whether found or not, each in a tuple pair. Each tuple parir will be stored in a list.

Example:
>>> vowels_finder("This has some vowels")
[('a', 1), ('o', 2), ('u', 0), ('e', 2), ('i', 1)] # tuple pair of each vowel.
>>>

My attempt:
def vowels_finder(s):
    vowels = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}
    for el in s:
        if el in {'a', 'e', 'i', 'o', 'u'}:
            vowels[el]+=1
    vowels = [(key, pair) for key, pair in vowels.items()]
    return vowels

My code above is not commented, but I'm confident that its brevity will allow me to pass on this.
Questions:

Is there _any way, besides using a python library, that this can be condensed into a one-liner?
Would there be a way to not have to convert the vowels key's back into tuple pairs, and just have them be tuples in the beginning. eg: vowels = [('a', 0), ('e', 0), ('i', 0), ('o', 0), ('u', 0)] ?

language: Python 3.4


texts: Prioritizing one column over the other column of the same table

texts:
I am creating an API in .net core and I just could not figure out how to put the following Linq expression into a single call:

public async Task<ActionResult<IEnumerable<MyClass>>> GetByReference(string reference)
        {
             var myClassPkColumn = _context.MyClass
                .Where(myClass => myClass.PkColumn.Equals(reference))
                .Take(1)
                .ToList();

            if (myClassPkColumn.Count > 0)
            {
                return myClassPkColumn;
            }
            else
            {
                var myClassDescription = _context.MyClass
                .Where(myClass => myClass.Description.Contains(reference))
                .Take(8)
                .ToListAsync();
                return await myClassDescription;
            }
        }

In my front-end I am creating an autocomplete function and this now serves my intended purpose but I am curious if I could have made this into a single call (I guess for performance purposes).

If not possible then could I have written this in a cleaner way?

I hope that it is understandable that both columns are of type string and the first one I am querying is the primary key column (with 2-3 characters) while the second one is a non unique one with up to 50 characters.

The issue I had with the first approach:

var myClassResult = _context.MyClass
                    .Where(myClass => myClass.PkColumn.Equals(reference) ||
                     myClass.Description.Contains(reference))
                    .Take(8)
                    .ToListAsync();

was that the result was always prioritizing the Description column over the PkColumn intead of my desired expectation which is the other way around. Even after I added orderBy I couldnt get it to show me the pkColumn result when I know there was one.


texts:
I just started coding in Objective-C and would like to know if my simple implementation of a Stack is acceptable & what ways would you improve the Stack code, or the Main code? i'm curious of things such as (but not limited to):

formatting
edge cases
run time (like one part where try to manipulate strings in description)
general good practice
memory management practices (i'm using ARC in this code)

Stack.h:

#import <Foundation/Foundation.h>

@interface Stack : NSObject

-(void)push:(id)obj;
-(id)pop;
-(NSUInteger)size;
-(id)peek;
-(BOOL)isEmpty;

@end

Stack.m file:

#import "Stack.h"

@implementation Stack{
    NSMutableArray *stack;
}

-(id)init{
    self = [super init];
    if(self!=nil){
        stack = [[NSMutableArray alloc] init];
    }
    return self;
}

-(void)push:(id)obj{
    [stack addObject:obj];
}

-(id)pop{
    id lastObj = [stack lastObject];
    [stack removeLastObject];
    return lastObj;
}

-(NSUInteger)size{
    return stack.count;
}

-(id)peek{
    return [[stack lastObject] copy];
}

-(BOOL)isEmpty{
    return stack.count == 0;
}

-(NSString *)description{
    NSMutableString *result = [[NSMutableString alloc] initWithString:@"["];
    for (id s in stack) {
        [result appendFormat:@"%@, ",[s description]];
    }
    if (stack.count>0) {
        result = [[result stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]] mutableCopy];
    }
    [result appendString:@"]"];
    return result;
}

@end

Lastly, this is how i verify my code is "working":

#import <Foundation/Foundation.h>

#import "Stack.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        Stack *s1 = [[Stack alloc] init];
        assert([s1 size]==0);
        assert([s1 pop]==nil);
        assert([s1 peek]==nil);
        assert([s1 isEmpty]==YES);
        NSLog(@"first set of tests passed");
        [s1 push:[NSNumber numberWithInt:0]];
        [s1 push:[NSNumber numberWithInt:3]];
        [s1 push:[NSNumber numberWithInt:5]];
        NSLog(@"%@",[s1 description]);
        assert(![s1 isEmpty]);
        assert(s1.size == 3);
        assert([[s1 peek] isEqual:[NSNumber numberWithInt:5]]);
        assert([[s1 pop] isEqual:[NSNumber numberWithInt:5]]);
        assert(s1.size == 2);
        assert([[s1 pop] isEqual:[NSNumber numberWithInt:3]]);
        assert(![[s1 pop] isEqual:[NSNumber numberWithInt:3]]);
        assert([s1 pop] == nil);
        assert(s1.isEmpty);
        NSLog(@"second set of tests passed");
    }
    return 0;
}


texts: Waiting for a lock to release with Thread.Sleep()?

texts:
There's a follow-up: Waiting for a lock to release with ManualResetEvent and Quartz.

I've written a simple Lock-Mechanism which is saving the states of the locks in a database. Now I need to wait for a Lock to release or timeout after a certain amount of time (blocking the main thread, this is intentional). My implementation is looking like this:

/// <summary>Waits for the lock to be released within the given timeout.</summary>
/// <param name="lockName">The name of the lock.</param>
/// <param name="timeout">The timeout in seconds.</param>
/// <returns>True if the Lock was released.</returns>
public bool waitForLock(String lockName, Int32 timeout)
{
    // IsLocked(String) does query the database for the status
    while(locker.IsLocked(lockName) && timeout > 0)
    {
        Threading.Thread.Sleep(1000);
        timeout--;
    }

    return !locker.IsLocked(lockName);
}

I always get a little bit itchy if I have to use Thread.Sleep, but I'm not sure why.

Is something wrong with this design/approach and will it bite me later? Or is there a better way to handle this?

Edit: Further clarifications: I have full control over the locker and anything affiliated with it. The main intention for this is to make sure that certain operations will not overlap, each of these operations should be taking well less then 5 seconds. The load on the server is not really an issue, because the realistic maximum number of clients simultaneous waiting for a lock could be 10 (in my case).

The blocking of the thread is not as intentional is I have stated. The best thing would be if I could keep the message pumping still active, but I fail to see how I can achieve that goal in combination with polling the database (and without the need to introduce a timer with a callback).

Edit2: The locked part is not the database, the database is only holding the status of the locks. I'm using this locking system to make sure that no operation protected by this can execute at the same time on different client machines.


texts:
I'm relatively new to web development. I started learning JavaScript a few months ago and it's going well. I made this code for someone on fiverr, and it got the job done, but I know there's a more efficient way to write this without using a click handler for each element. There has to be a way to know which element is clicked and show the proper one without a separate click handler for each element.

Here's the Codepen link to the code.

HTML

  Item 1
  Item 2
  Item 3
  Item 4

Item 1

This is Item 1 content

Item 2

This is item 2 content

Item 3

This is item 3 content

Item 4

This is item 4 content

CSS

.item-block {
  display: none;
}

JS

$(document).ready(function() {
  $('#1').show();
})

$('#item-1').click(function() {
  $('.item-block').hide();
  $('#1').show();
})

$('#item-2').click(function() {
  $('.item-block').hide();
  $('#2').show();
})

$('#item-3').click(function() {
  $('.item-block').hide();
  $('#3').show();
})

$('#item-4').click(function() {
  $('.item-block').hide();
  $('#4').show();
})


texts:
I like Ruby's string multiplication so I thought I'd see if I could do it in Swift. I came up with these implementations:

@infix func * (left: String, right: Int) -> String {
    var result = ""
    for _ in 0..right {
        result += left
    }
    return result
}

operator infix ** {}

@infix func ** (left: String, right: Int) -> String {
    return Array(count: right, repeatedValue: left).reduce("", +)
}

println("Andrew rules! " * 42)
println("Andrew rules! " ** 42)

Anyone have improvements or other implementations?


texts:
In my quest to learn F#, I implemented Prime Factorization.

First, the code:

let primefactors x =

    let check = seq { let limit = uint64((ceil(sqrt(float(x)))));
                      for x in Seq.concat [seq { yield 2UL }; { 3UL .. 2UL .. limit }] do
                        yield x }

    let getFirstOrDefault def ns =
        if ns |> Seq.isEmpty then
            def
        else
            ns |> Seq.head

    let nextfactor x =
        match x with
        |1UL -> x
        |_ -> check
              |> Seq.skipWhile(fun idx -> x % idx <> 0UL)
              |> getFirstOrDefault x

    let rec getfactors x factors =
        match nextfactor x  with
        |1UL -> factors
        |factor -> (factors |> List.append [factor]) |> getfactors (x / factor)

    [] |> getfactors x

let smallFactors = primefactors 3672215407307975928UL
let bigPrimeFactor = primefactors 18446744073709551556UL
let biggestuint64Prime = primefactors 18446744073709551557UL

Im satisfied with the performance, but have some gripes with this code that I'd like feedback on:

I'm checking for 1UL in two places. In nextfactor it's there to skip the last run through the numbers; in getfactors it's the break condition. I don't feel like this is as elegant as it could be.

Another thing I don't like is the getFirstOrDefault function. At first I simply had a Seq.head after the Seq.skipWhile but that throws if the number itself is prime and so the sequence is empty. I'd like to do pattern matching with that as I would with lists but in that case I'd have to materialize the whole sequence which I'd like to avoid. Is there something like |[] -> ... for sequences?

I would also like to hear suggestions on how to construct the check sequence in a more elegant way.

I am aware that the algorithm itself is a pretty naive implementation of the problem, but I'm ok with that as it's (for me) sufficiently fast in the range of uint64. If you do have suggestions on how to improve performance while keeping with this simple algorithm, I'd love to hear them, though!

I'm also interested in hearing where I'm missing functional concepts that might be applicable here.


texts:
I tried coding this for practice. Is there a more memory-efficient way to work in place without using more arrays etc (using raw array operations)?

public class SpaceUrlEncoder
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    String unencoded = "Mr John Smith       ";
    int lastCharIdx = 12;
    char[] charr = unencoded.toCharArray();
    for (int i = 12; i >= 0; i--) {
        if (charr[i] == ' ') {
          encodeSpaceAt(i, lastCharIdx, charr);
          lastCharIdx += 2;
        }

    }
    System.out.println("space encoded string: " + new String(charr));
  }

  public static void encodeSpaceAt(int spaceIdx, int lastCharIdx, char[] charr) {
    for (int i = lastCharIdx; i > spaceIdx; i--) {
        charr[i+2] = charr[i];
        charr[i] = ' ';
    }
    charr[spaceIdx] = '%';
    charr[spaceIdx+1] = '2';
    charr[spaceIdx+2] = '0';

  }
}


texts: Iteration over an XDocument based on some existing elements and conditions

texts:
I wrote this piece of code which works as expected:
XElement theContentWhichIncludeBuilds = xDocument.XPathSelectElement($"//Project/Group").Elements()
  .FirstOrDefault(e => e.Name== "Content" && e.Attribute("Included").Value == "buildings");

It targets all the Group elements under the Project nodes,
where its Content has an Include attribute with a value of buildings.
The base sample XML:
<Project>
  <Group>
    <Content Include="buildings"/>

I need to use the provided code on top in 2,3 places in my project, the problem with it is that some XML files that I will process will not have that structure, and I am checking if it has that elements based on the condition or not.
Obviously it may cause errors when it doesn't have that element or the needed architecture. So I need to put it in Try/Catch.
Isn't it better to check each level one-by one and if that existed then check for the next node? (That way also avoid using try/catch)
Does anyone confirm the used method can be good or bad on this case, or can provide any better alternative method for it?
Edit:
The XML files could be similar to the .CSProj structure which I altered a bit for my need.
basically, here we may have:
<Project>
Basic data under the project node, which might be the same in all documents
</Project>

only some may have:
  <Group>
    <Content Include="buildings"/>

Now we want to check if it doesn't have the missed part we be able to add it,
or if it contained the part we may alter its' values.
It is an upgrade process of those documents.


texts: Replace SingletonPattern by using IOC Container based architecture

texts:
I have a legacy winForms application that now I'm in charge of maintaining and developing.
This app has a lot of singleton instance....
Some are very similar to service that wrap other component or class other instead wrap some entities to making a cache-like pattern
This is an example of this cached class
public class SingletonCycle
{
    private static Cycle _instance;
    private static DevExpress.RackManager.RackManager _rackManager;

    public static event EventHandler<Cycle> OnCycleUpdated;

    private static void RaiseOnCycleUpdated(Cycle cycle)
    {
        OnCycleUpdated?.Invoke(cycle, cycle);
    }

    public static Cycle GetInstance()
    {
        return _instance;
    }

    public static void SetCycleInstance(Cycle cycle)
    {
        if (_instance != null)
        {
            SingletonAuditTrail.GetInstance().ModifiedCycle(cycle);
        }
        else
        {
            SingletonAuditTrail.GetInstance().StartCycle(cycle);
        }
        _instance = cycle;
        _instance.CreationDate = DateTime.Now;
        _instance.Operator = CommonUIManager.GetInstance().GetConfig().GetCurrentUser;

        SaveCycle();
    }
}

Because I want to test some part of the software I want to transform all this singleton in service that will be registered in container as singleton Lifestyle.
The problem is that all this services are spread out in all the software and for now I can't use everywhere constructor injection because i can't put all the classes inside container.
For now I try to use the container as static and everywhere use it instead of every singleton instances
Are there any problems of using container instead static singleton? Can you suggest some other advice to replace effectively singleton?
Only as an example to explain....This is my first try example of this implementation with DI and simpleInjector
Register container in the static Main
public static Container Container { get; private set; }

static void Main()
{
........
    var crpConfig = SingletonCrpCompactConfig.GetInstance();
    var container = new Container();

    container.Register(typeof(UnitOfWorkManager),
        CreateUOWManager(crpConfig),
        Lifestyle.Singleton);
    container.Register(typeof(RecipeModuleCache),
        CreateRecipeModuleCache(crpConfig, container),
        Lifestyle.Singleton);
        container.Verify();
    Container = container;
......
}

private static Func<object> CreateUOWManager(CrpCompactConfig crpConfig)
{
    return () => new UnitOfWorkManager(crpConfig.ConnectionString);
}

private static Func<object> CreateRecipeModuleCache(CrpCompactConfig crpConfig, Container container)
{
    return () =>
    {
        var uowManager = container.GetInstance<UnitOfWorkManager>();
        var cache = new RecipeModuleCache(crpConfig, uowManager);
        return cache;
    };
}

Example of the service to be registered inside the container
public class RecipeModuleCache
{
    private readonly CrpCompactConfig _config;
    private readonly UnitOfWorkManager _uow;
    private CrpCompactRecipeModule _instance;
    private bool _cached;

    public RecipeModuleCache(CrpCompactConfig config, UnitOfWorkManager uow)
    {
        _config = config;
        _uow = uow;
    }

    public CrpCompactRecipeModule GetCached()
    {
        if (_cached)
            return _instance;
        _instance = StaticBuilders.Create(_uow);
        _cached = true;
        return _instance;
    }

    public void Invalidate()
    {
        _instance = null;
        _cached = false;
    }
}

So when there is the singleton i use instead
Program.Container.GetInstance<RecipeModuleCache>()


texts:
I have built a class which validates configuration data.  Below is a very simplified version with only the code that's relevant to this question.

class configValidator
{
    private $_errors = [];

    public function validate()
    {
        $this->errorGenerator(1, 'fail');
        if ($this->_errors) return $this->_errors;

        $this->errorGenerator(2, 'pass');
        if ($this->_errors) return $this->_errors;

        $this->errorGenerator(3, 'fail');
        if ($this->_errors) return $this->_errors;

        $this->errorGenerator(4, 'fail');
        if ($this->_errors) return $this->_errors;
    }

    private function errorGenerator($id, $string)
    {
        if ($string == 'fail')  $this->_errors[] = 'an error occurred on ID ' . $id;
    }
}

$configValidator = new ConfigValidator();
$errors = $configValidator->validate();
if (!empty($errors)) {
    exit(json_encode($errors));
} else {
    echo 'config validations passed';
}

In the validate() method, it is important that errors are returned to the caller, if any exist, after each call to the errorGenerator() method.  This is because in the actual version there are arrays with keys and subsequent calls to errorGenerator() are dependent on those array keys existing.  If they don't exist, then PHP gives an "undefined index notice".

As written above, the code operates as expected - it displays ["an error occurred on ID 1"] in the browser and does not get as far as executing the other calls to the errorGenerator() method.  This is the desired behavior.

However, looking at the validate() method, it seems redundant to type this line 4 times
if ($this->_errors) return $this->_errors;
so I experimented with stripping it out of the validate() method and putting that line into the errorGenerator() method like so:

public function validate()
{
    $this->errorGenerator(1, 'fail');

    $this->errorGenerator(2, 'pass');

    $this->errorGenerator(3, 'fail');

    $this->errorGenerator(4, 'fail');
}

private function errorGenerator($id, $string)
{
    if ($string == 'fail')  $this->_errors[] = 'an error occurred on ID ' . $id;
    if ($this->_errors) return $this->_errors;
}

This results in the browser displaying config validations passed, which is not the desired outcome.  It makes sense that is what's being displayed because moving that line into the errorGenerator() method returns control to the validate() method rather than to the code that called the validate() method.

I'm wondering if there's a way to refactor this code such that it returns the errors to the caller of validate(), yet does not repeat this line
if ($this->_errors) return $this->_errors;


texts:
For my game engine I am implementing ImGui for debugging purposes. In order to manage ImGui I have made a singleton to make sure only one ImGui context gets created. I am not entirely sure if this is a good implementation of a Singleton so I am looking for some feedback, also is using a Singleton here the right way or could I better use a full static class?

ImGUIManager.h

#ifndef CHEETAH_CORE_IMGUIMANAGER_H_
#define CHEETAH_CORE_IMGUIMANAGER_H_

#include "Core.h"
#include "../ImGUI/imgui.h"

#include <memory>

namespace cheetah
{
    class CH_API ImGUIManager
    {
    public:
        static void init();
        static void shutDown();
        static void begin();
        static void end();

        static inline ImFont* getTextFont() { return ImGUIManager::getInstance()->m_text; };
        static inline ImFont* getIconSmallFont() { return ImGUIManager::getInstance()->m_iconSmall; };
        static inline ImFont* getIconLargeFont() { return ImGUIManager::getInstance()->m_iconLarge; };

        virtual ~ImGUIManager() = default;

    protected:
        ImGUIManager() = default;
        virtual void init_impl() = 0;
        virtual void shutDown_impl() = 0;
        virtual void begin_impl() = 0;
        virtual void end_impl() = 0;

    protected:
        ImFont* m_text = nullptr;
        ImFont* m_iconSmall = nullptr;
        ImFont* m_iconLarge = nullptr;

    private:
        static ImGUIManager* getInstance();
        static void create();

    private:
        static std::unique_ptr<ImGUIManager> m_instance;
    };
}

#endif // !CHEETAH_ENGINE_IMGUI_IMGUIMANAGER_H_

ImGUIManager.cpp

#include "ImGUiManager.h"
#include "Renderer/RenderAPI.h"
#include "Platform/OpenGL/OpenGLImGUIManager.h"

namespace cheetah
{
    std::unique_ptr<ImGUIManager> ImGUIManager::m_instance = nullptr;

    void ImGUIManager::init()
    {
#ifdef DEBUG
        static bool initialized = false;
        ASSERT(!initialized, "ImGUI is already initialized");
#endif // DEBUG
        ImGUIManager::getInstance()->init_impl();
#ifdef DEBUG
        initialized = true;
#endif
    };

    void ImGUIManager::shutDown()
    {
        ImGUIManager::getInstance()->shutDown_impl();
    };

    void ImGUIManager::begin()
    {
        ImGUIManager::getInstance()->begin_impl();
    };

    void ImGUIManager::end()
    {
        ImGUIManager::getInstance()->end_impl();
    };

    ImGUIManager* ImGUIManager::getInstance()
    {
        if (!m_instance)
            ImGUIManager::create();

        return m_instance.get();
    }

    void ImGUIManager::create()
    {
        switch (RenderAPI::getAPI())
        {
        case RenderAPI::API::OpenGL:
            m_instance = std::make_unique<opengl::OpenGLImGUIManager>();
            break;
        default:
            m_instance = nullptr;
        }
    }
}


texts: C# Regex to extract bug ID from Bugzilla JSON response

texts:
I have written a series of Regex.Replace() lines to take an input like {"id":36} and convert it to id 36 and I was wondering if it is possible to combine all the calls I am making into one.

Results = Regex.Replace(Results, @"\{", "");
Results = Regex.Replace(Results, @"\}", "");
Results = Regex.Replace(Results, @"\""", "");
Results = Regex.Replace(Results, @"\:", " ");

I have done some experimentation but because have not figured out how to tell it "Find the { then the } and drop only those but keep the text in between".

Here is my full code block:

[Route("test")]
public async Task<string> Test()
{
    Dictionary<string, string> BugData = new Dictionary<string, string>
    {
            { "Bugzilla_api_key", "Removed For Security" },
            { "product", "Test" },
            { "component", "Test Component" },
            { "version", "unspecified" },
            { "summary", "App API Test" },
            { "op_sys", "All" },
            { "platform", "Other" },
            { "description", "A basic API test" }
    };

    string Json = JsonConvert.SerializeObject(BugData, Formatting.None);
    var Client = new HttpClient();
    var Request = new HttpRequestMessage(HttpMethod.Post, "http://bugzilla-tools/rest/bug");
    Request.Content = new StringContent(Json, Encoding.UTF8, "application/json");
    Request.Headers.Add("Accept", "application/json");
    var Response = await Client.SendAsync(Request);
    var Results = await Response.Content.ReadAsStringAsync();
    Results = Regex.Replace(Results, @"\{", "");
    Results = Regex.Replace(Results, @"\}", "");
    Results = Regex.Replace(Results, @"\""", "");
    Results = Regex.Replace(Results, @"\:", " ");

    if (Response.StatusCode == HttpStatusCode.OK)
    {
        return Results;
    }
    else
    {
        return "Error Logging to Bugzilla";
    }
}

The overall goal for this (which is working now). Is to pass data to BugZilla to log exceptions from the app as bugs, get the new bug ID and pass that up to an error page which will read something like "An error was encountered processing you request. This error has been logged with the bug ID 36" (Where ID 36 would be what this task passes up to the error page).

I am using the Regexes to make the returned string more readable, as trying to deserialize it with NewtonSoft would produce the error:

  JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.String]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
   To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
   Path 'Bugzilla_api_key', line 1, position 20

From the code:

var T = JsonConvert.DeserializeObject<List<string>>(Json);
Results = string.Concat(T[0], " ", T[1]);


texts:
JavaScript is my first programming language, and I'm still pretty new. I'm just looking for feedback. What can I do to make this more efficient and handle larger numbers?

// Project Euler - Smallest Multiple
// This program finds the smallest positive number
// that is evenly divisible by all numbers between 1 and n.

function smallestMult(n){
    var dividends = []; // the numbers by which the program must divide
    for (var i = 1; i <= n; i ++){
        dividends.push(i);
    }
    var result = n; // will increase in increments of n
    var count = 0; //  result has been found when count == n
    while (count < n){
        for (var x = 0; x < dividends.length; x ++){
            if (result % dividends[x] === 0){
                count += 1; // increases count for every successful division
            }
            else {
                count = 0; // if a division fails, count returns to 0
                result += n; // and the result is increased by n
            }
        }
    }
    return result;
}
console.log(smallestMult(12));


texts:
I'll start by saying that I just started learning Go coming from Python (and some basic on Java), so I am trying to understand how to write Go code in more idiomatic way and not in a Python way. Any feedback on that would be appreciated!
About the exercise: In this exercise I need to implement keep and discard methods, for 3 types of collections []int, []string, [][]int. Both methods take a function and based on the outcome of the function for each element of the collection, element is kept or discarded (outcome should be a new collection).
To solve this I defined the methods, but I realise each method is defined in exact same way except for the if conditions and types. To reduce repetition, I decided to implement a helper method for each collection. This reduces some repetition, but I still feel that this could be simplified further. Would be curious to know if it is possible and whether it would be recommended approach in Go?
Also, any additional feedback on my code would be highly appreciated!
Thanks!
// Package strain defines methods for filtering for collections.
package strain

type Ints []int

// Keep iterates over elements of the collection and keeps ones
// where predicate function returns true.
func (collection Ints) Keep(f func(int) bool) Ints {
    return collection.filterHelper(f, false)
}

// Keep iterates over elements of the collection and discards ones
// where predicate function returns true.
func (collection Ints) Discard(f func(int) bool) Ints {
    return collection.filterHelper(f, true)
}

// Helper method for Keep and Discard methods.
func (collection Ints) filterHelper(f func(int) bool, reversed bool) Ints {
    var kept Ints
    for _, item := range collection {
        if f(item) != reversed {
            kept = append(kept, item)
        }
    }
    return kept
}

type Strings []string

// Keep iterates over elements of the collection and keeps ones
// where predicate function returns true.
func (collection Strings) Keep(f func(string) bool) Strings {
    return collection.filterHelper(f, false)
}

// Keep iterates over elements of the collection and discards ones
// where predicate function returns true.
func (collection Strings) Discard(f func(string) bool) Strings {
    return collection.filterHelper(f, true)
}

// Helper method for Keep and Discard methods.
func (collection Strings) filterHelper(f func(string) bool, reversed bool) Strings {
    var kept Strings
    for _, item := range collection {
        if f(item) != reversed {
            kept = append(kept, item)
        }
    }
    return kept
}

type Lists [][]int

// Keep iterates over elements of the collection and keeps ones
// where predicate function returns true.
func (collection Lists) Keep(f func([]int) bool) Lists {
    return collection.filterHelper(f, false)
}

// Keep iterates over elements of the collection and discards ones
// where predicate function returns true.
func (collection Lists) Discard(f func([]int) bool) Lists {
    return collection.filterHelper(f, true)
}

// Helper method for Keep and Discard methods.
func (collection Lists) filterHelper(f func([]int) bool, reversed bool) Lists {
    var kept Lists
    for _, item := range collection {
        if f(item) != reversed {
            kept = append(kept, item)
        }
    }
    return kept
}

```


texts:
I'm working on an API testing algorithm within the Postman REST client and I wanted a simple and elegant deep diff function to test my JSON responses. I only have access to Lodash within Postman's testing sandbox.

I couldn't find one on SO or elsewhere online so I decided to write one for myself. My goal was to write the function in less than 10 lines of code so that it is easy to copy/paste and easy to tell what is happening for future people working on the project. I actually got it to work in 5 lines!

_.merge(obj1, obj2, function (objectValue, sourceValue, key, object, source) {
    if ( !(_.isEqual(objectValue, sourceValue)) && (Object(objectValue) !== objectValue)) {
        console.log(key + "\n    Expected: " + sourceValue + "\n    Actual: " + objectValue);
    }
});

Obviously you can change the console.log() to suit your application. I don't actually use object and source but the variables are all there for anyone who wishes to expand this function for their own use. You could create an array of values that are different. Not bad for learning JavaScript 2 weeks ago!

If you don't want to clobber your obj1 you can do a var obj1Copy = _.cloneDeep(obj1) and use your clone object instead.

If you want to trace down through your object from high level to low level, you can remove the && (Object(objectValue) !== objectValue) from the if statement.

Is there any way to improve this code?


texts: Tensorflow loop to analyze gradients derived from MRI and PET images

texts:
The code shown below takes the partial derivative of each pixel of the output fused image of a neural network with respect to input image of the neural network using tensorflow's tf.gradients(Y, X) and compute a Jacobian matrix for each of the two input images MRI and PET. However, the code is really slow since I currently define a for loop by iterating through each pixel to compute the Jacobian matrix.

jacob_matrix_mri = np.zeros((65536,256,256))
jacob_matrix_pet = np.zeros((65536,256,256))

count = 0
saver = tf.train.Saver()
with tf.Session() as sess:
   sess.run(tf.global_variables_initializer())
   saver.restore(sess,'/home/nora/Desktop/MBIA 2019/Checkpoint/')
   for i in range(image_width):
        for j in range(image_length):
            grad_mri = tf.gradients(fused_image[0,i,j,0],images_mri)
            grad_pet = tf.gradients(fused_image[0,i,j,0],images_pet)
            gradients_mri, gradients_pet, _ =sess.run([grad_mri,grad_pet,fused_image],
                                       feed_dict{images_mri:test_mri,
                                                 images_pet:test_pet})

            jacob_matrix_mri[count,:,:] = np.squeeze(gradients_mri[0][0,:])
            jacob_matrix_pet[count,:,:] = np.squeeze(gradients_pet[0][0,:])
            count = count+1
            if count % 1000 == 0:
               print count
               t2 = time.time()
               print (t2-t1)
t3 = time.time()


texts: Multiprocess, multithreaded read write on a single file

texts:
I've got a job to create a library that would be able to support multithreaded and multi process read and write to a single file. On that single file we would store C# models in an array in JSON format. It would basically work as a mini file system JSON DB.

When the application that uses this lib starts, it would load existing models (if they do exist) in memory, so that we can query the data in memory. Adding, updating and removing of objects would require to flush the data to that single file. I assume that the hardest thing here to achieve would be synchronization between threads and processes. I actually managed to do that with mutex. Currently, I only have two methods, one for writing, and one for reading:

public void Write (string text)
{
    var appGuid = "{FBE403EA-0D59-48D6-941D-E74E0F20B482}";
    var mutexId = $"Global\\{{{appGuid}}}";

    bool createdNew;

    var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

    using ( var mutex = new Mutex(false, mutexId, out createdNew, securitySettings) )
    {
        var hasHandle = false;
        try
        {
            hasHandle = mutex.WaitOne(Timeout.Infinite, false);
            using ( var fileStream = new FileStream("test.txt", FileMode.Truncate, FileAccess.Write, FileShare.Read) )
            {
                var buffer = Encoding.UTF8.GetBytes(text);
                fileStream.Write(buffer, 0, buffer.Length);
                fileStream.Close();
            }
        }
        finally
        {
            if ( hasHandle )
                mutex.ReleaseMutex();
        }
    }
}

public string Read ( )
{
    var appGuid = "{FBE403EA-0D59-48D6-941D-E74E0F20B482}";
    var mutexId = $"Global\\{{{appGuid}}}";

    bool createdNew;

    var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

    using ( var mutex = new Mutex(false, mutexId, out createdNew, securitySettings) )
    {
        var hasHandle = false;
        try
        {
            hasHandle = mutex.WaitOne(Timeout.Infinite, false);
            using ( var fileStream = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read) )
            {
                var text = "";
                var stringBytes = new byte[fileStream.Length];
                fileStream.Read(stringBytes, 0, (int)fileStream.Length);
                text = Encoding.UTF8.GetString(stringBytes);
                fileStream.Close();
                return text;
            }
        }
        finally
        {
            if ( hasHandle )
                mutex.ReleaseMutex();
        }
    }
}

To test these methods I implemented them in a WPF app, which had two buttons and a textbox. One button would synchronously read a single file in an infinite loop with a wait of 10 ms between cycles and dispatch the text to the textbox. The other button would write to that single file also in an infinite loop with a wait of 10 ms between cycles. In that loop I would download a random text and synchronously write the text to the file.

When there are two instances of that WPF app and they both ran the loops both read and write would work really fast. But after only two more instances read and write would slow down considerably.

Is there anything I can do in these methods to get any boost in performance?

The primary need of this lib is that it always needs to flush data to a file. That's why i'm using Timeout.Infinite when calling WaitOne from a mutex. I can't let it to fail when it tries to access a mutex.


texts: Returning a collection of unique elements: List using Contains() or HashSet

texts:
I'm writing a binary PowerShell module and have recently started to add wildcard support to some cmdlets.

I'm not sure if I'm using an efficient way of creating the final collection of objects to write back to the pipeline.

I'm wondering if it might be slightly more efficient to use a HashSet<T> rather than a List<T> in this case, even though I've been told that Contains() doesn't have a large overhead on small collections (the final collection would can contain anywhere from 0 to ~25 elements).

Is List<T> appropriate in this case or should I try and use a HashSet<T> instead?

[Cmdlet(VerbsCommon.Get, "DatabaseUser")]
[Alias("gdbu")]
[OutputType(new Type[] { typeof(User)})]
public class GetDatabaseUserCmdlet : PSCmdlet
{
    [Parameter(ValueFromPipeline = true,
               ValueFromPipelineByPropertyName = true,
               ValueFromRemainingArguments = true)]
    public string[] Name { get; set; }

    [Parameter]
    public SwitchParameter IncludeSystemAccounts{ get; set; }

    List<User> _users = new List<User>();
    Hashtable _privateData;
    Server _server;
    Database _database;

    protected override void BeginProcessing()
    {
        _privateData = (Hashtable)MyInvocation.MyCommand.Module.PrivateData;
        _server = new Server((string)_privateData["Server"]);
        _database = _server.Databases[(string)_privateData["Database"]];
    }

    protected override void ProcessRecord()
    {
        var users = _database.Users.Cast<User>();

        if(IncludeSystemAccounts.IsPresent == false)
        {
            users = users.Where(user => user.IsSystemObject == false);
        }

        if (Name == null)
        {
            _users = users.ToList();
        }
        else
        {
            foreach(var item in Name)
            {
                var wildcard = new WildcardPattern(item, WildcardOptions.IgnoreCase);
                var result = users.Where(user => wildcard.IsMatch(user.Name));
                if(result != null)
                {
                    foreach(var user in result)
                    {
                        if(_users.Contains(user) == false)
                        {
                            _users.Add(user);
                        }
                    }
                }
            }
        }
    }

    protected override void EndProcessing()
    {
        WriteObject(_users);
    }
}

To give an example of how this cmdlet functions. Assume my database has 10 users: named User1 through User10 (not counting dbo, sys, etc.).

If I call the cmdlet like so:

Get-DatabaseUser -Name user[135], user[2-4] | Format-Table -Property Name

This is the expected (and actual result):

Name
----
User1
User3
User5
User2
User4


texts:
I have a csv-file that consists of all match outcome probabilities for soccer matches. Each math can be result in a win, draw or loss. I also included the actual outcome. In order to test how accurate my predictions are I want to use the Ranked Probability Score (RPS). Basically, the RPS compares the cumulative probability distributions of the predictions and the outcome:

  \$ RPS = \frac{1}{r-1} \sum\limits_{i=1}^{r}\left(\sum\limits_{j=1}^i p_j - \sum\limits_{j=1}^i e_j \right)^2, \$

  where \$r\$ is the number of potential outcomes, and \$p_j\$ and
  \$e_j\$ are the forecasts and observed outcomes at position \$j\$.

For additional information, see the following link.

import numpy as np
import pandas as pd

def RPS(predictions, observed):
   ncat = 3
   npred = len(predictions)
   RPS = np.zeros(npred)

   for x in range(0, npred):
      obsvec = np.zeros(ncat)
      obsvec[observed.iloc[x]-1] = 1
      cumulative = 0
      for i in range(1, ncat):
          cumulative = cumulative + (sum(predictions.iloc[x, 1:i]) - sum(obsvec[1:i])) ** 2
          RPS[x] = (1/(ncat-1)) * cumulative

    return RPS

df = pd.read_csv('test.csv', header=0)
predictions = df[['H', 'D', 'L']]
observed = df[['Outcome']]
RPS = RPS(predictions, observed)

The first argument (predictions) is a matrix with the predictions and the corresponding probabilities.  Each row is one prediction, laid out in the proper order (H, D, L), where each element is a probability and each row sum to 1. The second argument (observed) is a numeric vector that indicates which outcome that was actually observed (1, 2, 3)

Feel free to give any feedback!
Thank you

Edit:

For some reason I am not able to reproduce the results of Table 3 of the link. I use Table 1 as input for predictions and observed. Any help is much appreciated!

Edit #2:

Hereby the small sample of the paper:

predictions = {'H': [1, 0.9, 0.8, 0.5, 0.35, 0.6, 0.6, 0.6, 0.5, 0.55],
               'D': [0, 0.1, 0.1, 0.25, 0.3, 0.3, 0.3, 0.1, 0.45, 0.1],
               'L': [0, 0, 0.1, 0.25, 0.35, 0.1, 0.1, 0.3, 0.05, 0.35]}

observed = {'Outcome': [1, 1, 1, 1, 2, 2, 1, 1, 1, 1]}


texts:
This code starts a new thread for login and reacts according to the JSON result returned by the server.

I think this code has too many conditionals, exception handlers, and nested functions.

public void Login() {
    mButton.setClickable(false);
    mButton.setText("Loading...");
    final String username = mUserName.getText().toString().trim();
    final String password = mPassWord.getText().toString().trim();

    new Thread() {
        public void run() {
            final String result = NetUtil.loginByGet(username, password);
            if (result != null) {
                try {
                    JSONTokener jsonTokener = new JSONTokener(result);
                    JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
                    final String message = jsonObject.getString("message");
                    if (jsonObject.getInt("error") == 0) {
                        String token = jsonObject.getString("token");
                        boolean isSaveSuccess = InfoUtil.saveUserInfo(LoginActivity.this,token);
                        if (isSaveSuccess) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                    initIntent(MainActivity.class);
                                    finish();
                                }
                            });
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, "保存登录信息失败", Toast.LENGTH_SHORT).show();
                                    mButton.setClickable(true);
                                    mButton.setText("登录");
                                }
                            });
                        }
                    } else if(jsonObject.getInt("error") == 1) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "" + message,
                                        Toast.LENGTH_SHORT).show();
                                mButton.setClickable(true);
                                mButton.setText("登录");
                            }
                        });
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                        mButton.setClickable(true);
                        mButton.setText("登录");
                    }
                });
            }
        }
    }.start();
}


texts:
I would like to implement a concurrent (multi-thread, multi-process) queue that is backed by file system. Data is pickled over a file, stored in a directory and given a sequential name.

The sequential name is milliseconds since epoch plus a random number that should prevent clashes. The queue will actually serve few processes and do few operations per second, but I wanted to be more general.

Also, this is thought to work on Linux, and I assumed that the rename of a file is atomic (I am not sure if it is the same on other platforms).
Therefore, I implemented a simple lock mechanism: *.lock files are ignored when popping from the queue, so a file will be locked (.lock suffix added) when being written and locked also when being read, then unlinked.

I think the only major flaw here is that collisions might occur when many threads or processes are being used, which won't happen in my case, but getting reviews from other eyes is definitely going to help.

import os
import time
import pickle
import random

from pathlib import Path

class FSQueue:
    def __init__(self, root, fs_wait=0.1, fifo=True):
        """Creates a FSQueue that will store data as pickle files in root."""
        self._root = Path(root)
        self._root.mkdir(exist_ok=True, parents=True)
        self._wait = fs_wait
        self._fifo = fifo

    def put(self, data):
        """Adds data to the queue by dumping it to a pickle file."""
        now = int(time.time() * 10000)
        rnd = random.randrange(1000)
        seq = f'{now:016}-{rnd:04}'
        target = self._root / seq
        fn = target.with_suffix('.lock')
        pickle.dump(data, fn.open('wb'))  # Write to locked file
        fn.rename(target)  # Atomically unlock

    def get(self):
        """Pops data from the queue, unpickling it from the first file."""
        # Get files in folder and reverse sort them
        while True:
            _, _, files = next(os.walk(self._root))
            files = sorted(files, reverse=not self._fifo)
            for f in files:
                if f.endswith('lock'):
                    continue  # Someone is writing or reading the file
                try:
                    fn = self._root / f
                    target = fn.with_suffix('.lock')
                    fn.rename(target)
                    data = pickle.load(target.open('rb'))
                    target.unlink()
                    return data
                except FileNotFoundError:
                    pass  # The file was locked by another get()
            # No files to read, wait a little bit
            time.sleep(self._wait)

    def qsize(self):
        """Returns the approximate size of the queue."""
        _, _, files = next(os.walk(self._root))
        n = 0
        for f in files:
            if f.endswith('lock'):
                continue  # Someone is reading the file
            n += 1
        return n

if __name__ == '__main__':
    q = FSQueue('/tmp/test_queue')
    for i in range(10):
        q.put(f'data {i}')
    assert q.qsize() == 10
    for i in range(11):
        print(q.get())  # The last one should wait


texts: Clear out a textbox after submitting its content

texts:
I struggled to figure out how to clear a textbox after submitting it's contents via a button control.

I would like to know if my solution is an accepted practice for initializing a control after an action has been made by a user.

Is embedding event data (i.e. SendRequested) within a model an accepted practice for updating UI within Elm?

module Main exposing (..)

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import WebSocket

main =
    program
        { init = init
        , update = update
        , view = view
        , subscriptions = subscriptions
        }

-- MODEL

type alias Model =
    { input : String
    , messages : List String
    , sendRequested : Bool
    }

init : ( Model, Cmd Msg )
init =
    ( Model "" [] False, Cmd.none )

-- UPDATE

type Msg
    = Input String
    | Send
    | NewMessage String

update : Msg -> Model -> ( Model, Cmd Msg )
update msg { input, messages, sendRequested } =
    case msg of
        Input newInput ->
            ( Model newInput messages False, Cmd.none )

        Send ->
            ( Model "" messages True, WebSocket.send "ws://echo.websocket.org" input )

        NewMessage message ->
            ( Model input (message :: messages) False, Cmd.none )

-- SUBSCRIPTIONS

subscriptions : Model -> Sub Msg
subscriptions model =
    WebSocket.listen "ws://echo.websocket.org" NewMessage

-- VIEW

view : Model -> Html Msg
view model =
    let
        inputElement =
            if not model.sendRequested then
                input [ onInput Input ] []
            else
                input [ onInput Input, value "" ] []
    in
        div []
            [ div [] (List.map viewMessage model.messages)
            , inputElement
            , button [ onClick Send ] [ text "Send" ]
            ]

viewMessage : String -> Html Msg
viewMessage message =
    div [] [ text message ]


texts: Querying MySQL from an external application

texts:
I have a database that I need to query over and over as fast as possible. My queries execute pretty quickly, but there seems to be some additional lag. I have a feeling that this lag is due to the fact that I am initiating and de-initiating a connection the connection each time. Is there a way to avoid this?

I am not using libmysql (at least, not directly). I am using the "mysql50" package in Lazarus/FreePascal (similar to Delphi), which in turn uses libmysql (I think).

The purpose of this library is to pass along a query sent from MQL4 (a propitiatory C-like language for the financial exchange market), and return a single row from my MySQL database (to which it connects through a pipe).

I would really appreciate if someone took a look at my code and pointed out (or maybe even fixed) some inefficiencies.

{$CALLING STDCALL}

library D1Query;

{$mode objfpc}{$H+}

uses
  cmem,
  Windows,
  SysUtils,
  profs_win32exceptiontrap,
  mysql50;

var

  sock: PMYSQL;
  qmysql: st_mysql;

type
  VArray = array[0..100] of Double;
  PArray = ^VArray;

  procedure InitSQL; stdcall;
  begin

    mysql_init(PMySQL(@qmysql));
    sock :=
      mysql_real_connect(PMysql(@qmysql), '.', 'root', 'password', 'data', 3306, 'mysql', CLIENT_MULTI_STATEMENTS);
    if sock = nil then
    begin
      OutputDebugString(PChar('  Couldn''t connect to MySQL.'));
      OutputDebugString(PChar(mysql_error(@qmysql)));
      halt(1);
    end;

  end;

  procedure DeInitSQL; stdcall;
  begin

    mysql_close(sock);
  end;

  function SQL_Query(QRY: PChar; output: PArray): integer; stdcall;
  var
    rowbuf: MYSQL_ROW;
    recbuf: PMYSQL_RES;
    i: integer;
    nfields: LongWord;

  begin
    InitSQL();

    if (mysql_query(sock, QRY) < 0) then
    begin
      OutputDebugString(PChar('  Query failed '));
      OutputDebugString(PChar('   ' + mysql_error(sock)));
    end;

    recbuf := mysql_store_result(sock);
    nfields :=  mysql_num_fields(recbuf);
    rowbuf := mysql_fetch_row(recbuf);

    if (rowbuf <> nil) then
    begin
      for i:=0 to nfields-1 do
          output^[i] := StrToFloatDef(rowbuf[i], -666);
    end;

    mysql_free_result(recbuf);
    DeInitSQL();
    Result := i;

  end;

exports
  SQL_Query,
  InitSQL,
  DeInitSQL;

begin
end.


texts: Counting the occurrence of each letter in a string

texts:
This function counts the number of times each letter appears in a string, then display the one that appears the most, and the number of times it appears. If there's a tie, it shows all of them, like "bz,5".

I've got the feeling this could be done much better. Suggestions?

private static void LinqTest()
{
    const string testString = "abbsabwertbfacsfgggdfgascd";
    var count = 0;

    var charGroups = (from c in testString
                      group c by c into g
                      select new
                      {
                          c = g.Key,
                          count = g.Count(),
                      }).OrderByDescending(c => c.count);
    foreach (var @group in charGroups.Where(@group => count <= @group.count))
    {
        Console.WriteLine(@group.c + ": " + @group.count);
        count = @group.count;
    }
}


texts: Bash function that allows running user aliases with sudo on Ubuntu

texts:
I wrote this little Bash function to replace my sudo command.

It checks whether I have an alias for the given command and runs the aliased command instead of the literal one in that case.

As this is going to be used with sudo, I want to be sure there are no critical mistakes in it which generate security or safety issues. Please check whether everything is okay with it, like quoting issues or improvements to the sed pattern maybe. Thanks.

Here is my function:

sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" ; else command sudo $@ ; fi }

Or nicely formatted:

sudo() {
    # check if the command passed as argument is an alias
    if alias "$1" &> /dev/null ; then
        # extract the aliased command from the output of 'type'
        # and run it with the remaining arguments
        $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}"
    else
        # run the original 'sudo' command with all arguments
        command sudo $@
    fi
}