texts: Optimize jQuery code includes autocomplete function for different input box with different autocomplete content

texts:
I have this code below for autocomplete feature of several inputTextbox. The input box also share same class".wikiInput". When user typed something in either of them, a relevant autocomplete dropdown box should show up. Instead of hard code one by one. How do I optimize them into a simpler format. Note the lookup has different arrays.

(function () {
    var cdTeamInput = $("#ctl00_ContentPlaceHolder1_txtAssociation");
    if (cdTeamInput.length > 0) {
        cdTeamInput.autocomplete({
            deferRequestBy: 0,
            autoSelectFirst: true,
            lookup: txtAssociation,
            onSelect: function (value, data) {
                cdTeamInput.val(value.value);
                $(".wikiSubmit").click();
            }
        });
    }
})();

(function () {
    var cdSubjectInput = $("#ctl00_ContentPlaceHolder1_txtSubject");
    if (cdSubjectInput.length > 0) {
        cdSubjectInput.autocomplete({
            deferRequestBy: 0,
            autoSelectFirst: true,
            lookup: txtSubject,
            onSelect: function (value, data) {
                cdSubjectInput.val(value.value);
                $(".wikiSubmit").click();
            }
        });
    }
})();

Update: I really like user2734550's first answer. however, the lookup array will be undefined in cross page situation. Like one of the page have only one lookup array but don't have others. so js file would be broken. How do I avoid this problem? Seems like if lookup.length > 0 statement doesn't work.


texts: Minimum cost path of matrix using Python

texts:
I was reading this article about finding the minimum cost path from (0,0) to any (m,n) point in a matrix. Using python the author has provided 2 solutions in Python.

The first one solves it by using a backward induction technique through recursion while the second one uses an auxiliary table (tc). I was wondering if I could solve it using forward induction and without the need of an additional table. Here's my solution:

def test(target_matrix, cost, i, j, m, n):
    if i == m and j == n:
        return cost
    if i + 1 > m:
        cost += target_matrix[i][j + 1]
        return test(target_matrix, cost, i, j + 1, m, n)
    if j + 1 > n:
        cost += target_matrix[i + 1][j]
        return test(target_matrix, cost, i + 1, j, m, n)
    if i + 1 <= m and j + 1 <= n:
        ret_cost, i, j = min(target_matrix[i + 1][j], target_matrix[i][j + 1], target_matrix[i + 1][j + 1], i, j)
        cost += ret_cost
        return test(target_matrix, cost, i, j, m, n)

def min(x, y, z, i, j):
    if x < y:
        if x < z:
            return x, i + 1, j
        else:
            return z, i + 1, j + 1
    else:
        if y < z:
            return y, i, j + 1
        else:
            return z, i + 1, j + 1

if __name__ == '__main__':
    input = [
        [11, 9, 3],
        [3, 1, 0],
        [1, 3, 2]
    ]
    res = test(input, input[0][0], 0, 0, 2, 2)
    print(res)

What are your comments on this? What do you think are its drawbacks compared to the two solutions provided in the article? I'm particularly interested in comments regarding the time and space complexity of my algorithm.


texts: Optimized computation of pairwise correlations in Python

texts:
Given a set of discrete locations (e.g. "sites") that are pairwise related in some categorical ways (e.g. general proximity) and contains local level data (e.g. population size), I wish to efficiently compute the mean correlation coefficients between local level data on pairwise locations that are characterized by the same relationships.

For example, I assumed 100 sites and randomized their pairwise relations using values 1 to 25, yielding the triangular matrix relations:

import numpy as np

sites = 100
categ = 25

relations = np.random.randint(low=1, high=categ+1, size=(sites, sites))
relations = np.triu(relations) # set relation_ij = relation_ji
np.fill_diagonal(relations, 0) # ignore self-relation

I also have 5000 replicates of simulation results on each site:

sims = 5000
res = np.round(np.random.rand(sites, sims),1)

To compute the mean pairwise correlation for each specific relation category, I first calculated for each relation category i the correlation coefficient rho[j] between the simulation results res of each unique site pairs j, and then taking the average across all possible pairs with relation i:

rho_list = np.ones(categ)*99

for i in range(1, categ+1):
    idr = np.transpose(np.where(relations == i)) # pairwise site indices of the same relation category
    comp = np.vstack([res[idr[:,0]].ravel(), res[idr[:,1]].ravel()]) # pairwise comparisons of simulation results from the same relation category
    comp_uniq = np.reshape(comp.T, (len(idr), res.shape[1], -1)) # reshape above into pairwise comparisons of simulation results between unique site pairs

    rho = np.ones(len(idr))*99 # correlation coefficients of all unique site pairs of current relation category

    for j in range(len(idr)): # loop through unique site pairs
        comp_uniq_s = comp_uniq[j][np.all(comp_uniq!=0, axis=2)[j]].T # shorten comparisons by removing pairs with zero-valued result
        rho[j] = np.corrcoef(comp_uniq_s[0], comp_uniq_s[1])[0,1]

    rho_list[i-1] = np.nanmean(rho)

Although this script works, but once I increase sites = 400, then the entire computation can take more than 6 hrs to finish, which leads me to question my use of array functions. What is the reason for this poor performance? And how can I optimize the algorithm?


texts:
I have a method which checks if a control of an entity's attribute is 'multiControl' or not:

private boolean entityHasMultiControl(IEntityMetadata entityMetadata) {

    for(IAttributeMetadata attr : entityMetadata.getAttributes()){
        for(IControl control : attr.getAttributeType().getControls()){
            if(control.getIsMultiControl() == true)
                return true;
        }

    }
    return false;
}

Can this be simplified further in Java 8?


texts:
I'm very new to functional world. I've written a simple brainfuck interpreter as my first F# program.

What I would like to know:

Am I using the right data structure for each situation?
Is my code easy to understand?
Is my code style similar to common F# codes (naming, organization etc)?
Is my code "very declarative" or I'm still thinking in the imperative way?

What is not so relevant:

Performance (but if I've made something very bad, let me now!)
More features

Obs.: I assume input is always a valid brainfuck code and that's ok to me.

open System
open System.IO

let getValue (position:int) (memory:Map<int, int>) =
    match Map.tryFind position memory with
    | None  -> 0
    | value -> value.Value

let calcAccumulator (acc:int) (instruction:char) (search:char) (miss:char) =
    match instruction with
    | x when x = search -> acc+1
    | x when x = miss   -> acc-1
    | _ -> acc

let rec findMatch (code:string) (search:char) (miss:char) (inc:int) (current:int) (acc:int) =
    let instruction = code.[current]

    match instruction, acc with
    | x, 0 when x = search -> current+1
    | _    -> findMatch code search miss inc (current+inc) (calcAccumulator acc instruction search miss)

let updateMemory (instruction:char) (position:int) (memory:Map<int, int>) =
    let oldValue = getValue position memory
    let newValue =
        match instruction with
        | '+' -> oldValue + 1
        | '-' -> oldValue - 1
        | ',' -> Console.ReadKey().KeyChar |> Convert.ToInt32
        | _   -> oldValue

    Map.add position newValue memory

let updateOutput (instruction) (value:int) =
    if instruction = '.'
    then Console.Write ((char) value)

let updatePosition (instruction:char) (position:int) =
    match instruction with
    | '>' -> position+1
    | '<' -> position-1
    | _   -> position

let updateIndex (code:string) (index:int) (value:int) =
    match code.[index], value with
    | '[', 0 -> findMatch code ']' '[' 1 (index+1) 0
    | ']', x when x <> 0 -> findMatch code '[' ']' -1 (index-1) 0
    | _      -> index+1

let rec interpretHelper (code:string) (index:int) (memory:Map<int, int>) (position:int) =
    match code.Length with
    | x when x = index  -> memory
    | _ ->
        let instruction = code.[index]
        let newPosition = updatePosition instruction position
        let newMemory = updateMemory instruction position memory
        let newIndex = updateIndex code index (getValue position memory)
        updateOutput instruction (getValue position memory)
        interpretHelper code newIndex newMemory newPosition

let interpret (code:string) =
    interpretHelper code 0 Map.empty 0

let options (args:string array) =
    let pathToFile = args.[0]
    let showMemory =
        match args with
        | [| _ ; "-memory" |] -> true
        | _                   -> false

    pathToFile, showMemory

let onlyCode (text:string) =
    let validInstructions = "+-.,][<>".ToCharArray()

    String.filter (fun x -> Array.contains x validInstructions) text

[<EntryPoint>]
let main args =
    let pathToFile, showMemory = options args
    let code = onlyCode (IO.File.ReadAllText pathToFile)
    let memory = interpret code

    if showMemory
    then Map.iter (fun a b -> printf "\n%3d: %d" a b) memory

    0


texts:
I have this code to edit certain cells in my Excel file using Apache POI, but it is really slow. How can I improved the performance?

Ideally I would like to edit 20000 rows in less than one minute. At the moment it does ~100/min. Any suggestions would be great.

public static void main(String[] args) throws IOException, InvalidFormatException{
        InputStream inp = new FileInputStream("test.xls");
        FileOutputStream fileOut = new FileOutputStream("edited-test.xls");
        Workbook wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);
        for(int i=2;i <20002;i++){
            Row row = sheet.getRow(i);

            Cell cell4 = row.getCell(4);
            cell4.setCellValue(i);

            Cell cell6 = row.getCell(6);
            cell6.setCellValue("aa"+i);

            Cell cell8 = row.getCell(8);
            cell8.setCellValue("2");

            wb.write(fileOut);
            System.out.println(i);
        }
        fileOut.close();
        System.out.println("Done!");
    }


texts:
Before I used reflection to invoke a state based on the string, it looked like this:

public void setState (String state) {
    try {
        this.state = (State) Class.forName("state"+state).getConstructor().newInstance();
    } catch (Exception e) {
        System.out.println ("Tried to set state to " + state.toString() + ", but no such state exists.");
    }
}

It is supposed to say ...forName("state."+state). Notice the period in "state.".

However, it feels wrong to use reflection when I know all the State the project can be in.

They are:

Title
NewGame
LoadGame
Credits
HighScore
World

I'm rendering the most straightforward solution to be along these lines:

private  void setState (String state) {
    switch (state) {
        case "Title":
            this.state = new Title ();
            break;
        case "NewGame":
            this.state = new NewGame ();
            break;
        case "LoadGame":
            this.state = new LoadGame ();
            break;
        case "Credits":
            this.state = new Credits ();
            break;
        case "HighScore":
            this.state = new HighScore ();
            break;
        case "World":
            this.state = new World ();
            break;
        default:
            System.out.println ("Tried to set state to " + state.toString() + ", but no such state exists.");
    }
}

Is it possible to clean that up?

For example, could instance-mapping be a solution?

There is a very similar situation with the handle method. In the reflection case it looks like this:

public void handle (Event event) {
    try {
        this.getClass().getMethod(event.getMethod(), String.class).invoke(this, event.getArgument());
    } catch (Exception e) {
        state.handle (event);
    }
}

If the method can't be invoked in this class then it will be invoked in the state instead. Meaning, the exception can be caught for that reason.

However, it does not look as neat if I were to use mapping or a switch-case clause here:

public void handle (Event event) {
    switch (event.getMethod()) {
        case "setState":
            setState (event.getArgument());
            break;
        case "loadGame":
            loadGame (event.getArgument());
            break;
        case "logDebug":
            logDebug (event.getArgument());
            break;
        case "exitGame":
            exitGame (event.getArgument());
            break;
        default:
            state.handle(event);
            break;
    }
    logDebug ("Event handled: " + event.toString());
}

Can something similar be used in these two cases or is it fine to use reflection?


texts: Fast hamming distance function in Julia that returns a distance matrix

texts:
I would like to use Julia to compute the hamming distance on a very large dataset.
I need to get back a distance matrix between rows in order to run further analysis on this matrix.
For my purposes, it is useful that the data are stored in a DataFrame type.
using DataFrames

The data looks something like this
a = [1 0 1 0 ; 1 1 1 1; 0 0 0 0; 0 0 0 0 ; 0 0 0 1]

df = convert(DataFrame, a);

nrows = size(df, 1)
ncols = size(df, 2)

I made a function in Julia
function hamjulia(df)

    nrows = size(df, 1)
    ncols = size(df, 2)
    m, n = nrows, nrows
    A = fill(0, (m, n))

    for i in 1:nrows
    for k in 1:nrows

        v = 0
        for j in 1:ncols
            if df[i,j] != df[k,j]
            v += 1
            end
        end
        A[i,k] = v
    end
    end
    return A
end

p = hamjulia(df)
p

My issue is that this code is super slow compared to some R packages. For instance, when I compared this function to the rdist package, rdist(df, metric = 'hamming'), R is faster.
How could I make this code really efficient? Especially that I would need to run it on a very large dataframe.
Thanks.


texts:
I've written code that will take any basic math sum input as a string (for instance, 2*3+4/4) and solve it. The way I achieve this is by splitting the string into sub-strings, with multiplication and division being done first (based on the regular order of operations). So in our example sum we would be left with 2*3 and 4/4.

It then solves these sums and replaces the original sub-string with the answer : 2*3+4/4 would become 6+1. The numbers left in the addition string are then added into an array. All elements in the array are then added.

The part of my code in question is the function that identifies if there are any multiplication or division operations left to do, and if so, performs them. I feel like this function is very long and cumbersome and needs to be shortened, hence why I'm posting it here on CodeReview.

void mathInterpreter::format()
{
    BasicQuestion TempQuestion;
    basic_ops *solver = new basic_ops();

    //If we have multiplication or division in our sum then we should do this loop.
    for (int i = 0; MultDevCount != 0; i++)
    {
        //get some information about the question we are on, and create a temp string.
        op_positions temp;
        temp = positions_d[i];
        std::string temp_str;

        double MyAnswer;

        //if the operation that we are on in the for loop happens to be a multiply or divide, then lets do that.
        if (temp.operation == MULTIPLY || temp.operation == DIVIDE)
        {
            if (operation_count == 1) /* ONLY ONE OPERATION */
            {
                temp_str = user_string;
            }
            else if (positions_d[i].operation_at == positions_d.front().operation_at) /* FIRST OPERATION IN SUM */
            {
                temp_str = get_sum(temp, 0, positions_d[i + 1].operation_at);
            }
            else if (positions_d[i].operation_at == positions_d.back().operation_at) /* LAST OPERATION IN SUM */
            {
                temp_str = get_sum(temp, positions_d[i - 1].operation_at, 0);
            }
            else /* THE OPERATION IS IN THE MIDDLE OF THE SUM */
            {
                temp_str = get_sum(positions_d[i], positions_d[i - 1].operation_at, positions_d[i + 1].operation_at);
                if (positions_d[i - 1].operation == SUBTRACT) temp_str = SUBTRACT_SYM + temp_str;
            }

            //setup the return question properly and then send it to the solver.
            TempQuestion = quest_from_tuple(get_nums(temp_str));

            answer SumAns;

            SumAns = solver->performCalc(TempQuestion);
            MyAnswer = SumAns.answer;

            if (SumAns.error)
            {
                error = true;
                delete TempQuestion.numbers;
                return;
            }

            //replace the original sum string with it's answer string.
            user_string = replace_strings(std::to_string(MyAnswer), temp_str, user_string);

            delete (TempQuestion.numbers);

            //sort operation counts.
            operation_count = CountOperations();
            positions_d.clear();
            populate_op_positions();

            //an operation has been removed, so positions_d[i] may have changed. If positions_d[i] is still a mult or dev, we need to
            //redo this loop with the same value for i. So subtract one so that the loop is redone with the same value.
            if (positions_d[i].operation == MULTIPLY || positions_d[i].operation == DIVIDE) i--;

        }
    }

}

Some additional information: positions_d is a deque which holds struct elements - the struct contains the position of an operation and what it is.

The get_sum() function takes in a struct element (same struct as mentioned above) and the positions of the operations before and after it. It will then return a string with two operands and the operation (e.g. 2*3).


texts: Objects/closures for storing movie information

texts:
I'm currently in the process of learning JavaScript and what it has to offer. I thought writing a simple web app that would allow me to add/remove/show my favorite movies would be a nice learning experience. I'm curious as to what the best solution would be for an object to house all of the data. It would be triggered by an event such as the clicking of a button.

var Movies = (function() {
    var movieList = [];

    return {
        add : function(newTitle, newRating) {
            movieList.push({title: newTitle, rating: newRating});
        },
        show : function() {
            for(var i = 0; i < movieList.length; i += 1) {
                console.log(movieList[i].title + ": " + movieList[i].rating);
            }
        },
        del : function(titleString) {
            for(var i = 0; i < movieList.length; i += 1) {
                if(movieList[i].title === titleString) {
                    movieList.splice(i, 1);
                    break;
                }
            }
        }
   };
}());

If I'm using an IIFE, or the use of closures incorrectly, please let me know. I want to learn JavaScript properly.


texts: Transform an entity from a type to another

texts:
I need to transform an entity from an external DLL to another entity which is from a different external DLL.

My question is: Is this the best solution or is there a better solution (type-save)? I hope there is a better idee because I don't really like to use the dynamic type.

using ExternalDllOne.Fruit; //contains(Apple, Banana, Melon, Peach)
using ExternalDllTwo.Fruit; //contains(ReturnApple, ReturnBanana, ReturnMelon, ReturnPeach)

public static dynamic Transform(Type type, string path)
{
    switch (type.Name)
    {
        case nameof(Banana):
            {
                Banana serializedFruit = SerializerFactory<Banana>.Create(SerializerType.Xml).Deserialize(path);
                ReturnBanana fruit = TransformBanana(serializedFruit);
                return fruit;
            }
        case nameof(Apple):
            {
                Apple serializedFruit = SerializerFactory<Apple>.Create(SerializerType.Xml).Deserialize(path);
                ReturnApple fruit =  TransformApple(serializedFruit);
                return fruit;
            }
        case nameof(Peach):
            {
                Peach serializedFruit = SerializerFactory<Peach>.Create(SerializerType.Xml).Deserialize(path);
                ReturnPeach fruit =  TransformPeach(serializedFruit);
                return fruit;
            }
        case nameof(Melon):
            {
                Melon serializedFruit = SerializerFactory<Melon>.Create(SerializerType.Xml).Deserialize(path);
                ReturnMelon fruit =  TransformMelon(serializedFruit);
                return fruit;
            }
        default:
            throw new ArgumentException($@"Type: [{type.Name}] is not a valid type for this application");
    }
}

The conversion is done thru a facade which is located in an external DLL. They way the Transform<fruit>() works is for every fruit type the same:

private static ReturnBanana TransformBanana(Banana fruit)
{
    var extraSettings = GetBananaSettings();

    var transformedFruit = FruitTransformationFacade.Transform(fruit, extraSettings);

    return transformedFruit;
}

Using the transformer method I have this code:

private static dynamic Load(string path)
{
    XDocument document = FileHelper.ParseFile(path);

    Type fileType = TypeHelper.DetermineFileType(document);

    dynamic component = Transformer.Transform(fileType, path);

    return component;
}

Do I need a wrapper object for each Return<fruit> entity with a coherent Interface, and return the interface?


texts: Checking if a directory is empty when having over a million files inside

texts:
I have the following function to confirm if a directory contains files:

/**
 * Check if the directory is empty
 *
 * Function to ascertain if the specified directory contains files.
 * Comparing to two, because parent and current are present inside
 * the returned array. Only 3+ denotes files on the target dir.
 *
 * @param str $dir              Directory to scan.
 * @param bol $count            Whether the return value should be the count result
 *
 * @return bool|int Integer with count, TRUE or FALSE for check
 */
public function directory_with_contents($dir, $count = false) {

    try {
        if (!is_readable($dir)) return NULL;

        if ($count) {
            return count(scandir($dir));
        } else {
            return (count(scandir($dir)) == 2) ? false : true;
        }
    }
    catch(PDOException $e) {
        throw new userman_Exception("
ups!

". $e->getMessage());
    }

}

The functions works well, but it is being used with directories that contain over one million files inside. The scandir() takes his time to return the results, and in turn this function with a large amount of files becomes slow.

Is any optimization that can be done as to have this function performing any faster when dealing with directories that have a large number of files?


texts:
Here is a non-predictive recursive descent parser I wrote for the following grammar:

E : E1 '*' E
  | E1 '/' E
  | E1 '+' E
  | E1 '-' E
  | E1
  ;

E1 : NUM
   | '(' E ')'
   ;

It can be run against the token stream

func main() {
    // (m) * (m / (m))
    valid := Parse([]Token{
        {Value: "("},
        {Type: T_NUM},
        {Value: ")"},
        {Value: "*"},
        {Value: "("},
        {Type: T_NUM},
        {Value: "/"},
        {Value: "("},
        {Type: T_NUM},
        {Value: ")"},
        {Value: ")"},
    })

    println(valid)
}

It doesn't build an AST, it simply validates a token stream against the language.

// an enumeration of named token types. for
// this language, there is only one named
// token type (the number). all other token
// types are referred to by their string value
const (
    _ = iota
    T_NUM
)

// a token type refers to the terminal class of the
// token (eg T_NUM), whereas the value refers to
// its textual representation (eg "23")
type Token struct {
    Type  int
    Value string
}

// a slice of tokens that represents the input stack.
// the base pointer is passed to the production func
// that is matching against the stack.
type TokenStack []Token

// type definition for a production. given a stack and
// a base pointer, return the position at which the
// production ends. if no production is
// matched return NoMatch, or -1.
type Production func(TokenStack, int) int

// returned by a production func if no match  is found
// on the token stack at a given base pointer
const NoMatch = -1

// will return true if a given stack is valid for the
// language. a parse is valid when the return value from
// a production equals the length of the input stack
// (meaning the entire stack matches the production)
func Parse(s TokenStack) bool {
    p := E(s, 0)
    return M(p) && p == len(s)
}

// a production func for the rule:
//
//  E : E1 '*' E
//    | E1 '/' E
//    | E1 '+' E
//    | E1 '-' E
//    | E1
//    ;
func E(s TokenStack, p int) int {
    if p1 := Consecutive(s, p, E1, V("*"), E); M(p1) {
        return p1
    } else if p1 := Consecutive(s, p, E1, V("/"), E); M(p1) {
        return p1
    } else if p1 := Consecutive(s, p, E1, V("+"), E); M(p1) {
        return p1
    } else if p1 := Consecutive(s, p, E1, V("-"), E); M(p1) {
        return p1
    } else if p1 = E1(s, p); M(p1) {
        return p1
    }
    return NoMatch
}

// a production func for the rule:
//
//  E1 : T_NUM
//     | '(' E ')'
//     ;
func E1(s TokenStack, p int) int {
    if p1 := T(T_NUM)(s, p); M(p1) {
        return p1
    } else if p1 = Consecutive(s, p, V("("), E, V(")")); M(p1) {
        return p1
    }
    return NoMatch
}

// will try to match consecutive productions against
// a token stack, keeping track of the length of each
// match. if every consecutive rule matches, return
// the length of every match added to the base pointer
// originally passed to this function
func Consecutive(s TokenStack, p int, rules ...Production) int {
    var match_len = 0
    for _, rulei := range rules {
        if p1 := rulei(s, p+match_len); M(p1) {
            match_len += p1 - (p + match_len)
        } else {
            return NoMatch
        }
    }
    return p + match_len
}

// return a production func that will
// match a given token value
func V(v string) Production {
    return func(s TokenStack, p int) int {
        if len(s) > p && string(s[p].Value) == v {
            return p + 1
        }
        return NoMatch
    }
}

// return a production func that will
// match a given token type
func T(t int) Production {
    return func(s TokenStack, p int) int {
        if len(s) > p && s[p].Type == t {
            return p + 1
        }
        return NoMatch
    }
}

// a function to conveniently check the
// return value of a production for a match
func M(p int) bool {
    return p > NoMatch
}


texts: Calculating positions along the edges of a rectangle

texts:
I had the following three Tcl procedures, which calculate positions along three edges of a rectangle:

#---- Numbered pins at the top ---------------------------------------
# Given a list of triplets (number, name, index), place the pins for the
# signals "name<index>" along the top edge, positioned vertically at 'y'
# and horizontally at 'number' times a constant space left of 'xRight'
# (plus an arbitrary offset of 2).
proc setNumberedTopPins {xRight y pins} {
    set padWidth 95
    foreach {number name index} $pins {
        set xOffset [expr $number * $padWidth + 2]
        setPin $name [expr $xRight-$xOffset] $y Top $index
    }
}
#---- Numbered pins at the right -------------------------------------
# The same for the right edge.
proc setNumberedRightPins {x yTop pins} {
    set padWidth 95
    foreach {number name index} $pins {
        set yOffset [expr max(0, $number * $padWidth - 2.5)]
        setPin $name $x [expr $yTop-$yOffset] Right $index
    }
}
#---- Numbered pins at the bottom ------------------------------------
# The same for the bottom edge.
proc setNumberedBottomPins {xRight y pins} {
    set padWidth 95
    foreach {number name index} $pins {
        set xOffset [expr $number * $padWidth + 2]
        setPin $name [expr $xRight-$xOffset] $y Bottom $index
    }
}

Since the code for each of the procedures is almost identical, I decided to write a single generalized procedure and three specializations of it.

I had some difficulties with generalizing the fact that the offset is sometimes applied to the second (x) and sometimes to the third (y) argument of setPin. I wanted to make sure that this decision is only taken once, outside the foreach loop.

Here is the solution I came up with:

#---- Numbered pins at the top ---------------------------------------
proc setNumberedTopPins {xRight y pins} {
    setNumberedPins Top 2 $xRight $y $pins
}
#---- Numbered pins at the right -------------------------------------
proc setNumberedRightPins {x yTop pins} {
    setNumberedPins Right -2.5 $x $yTop $pins
}
#---- Numbered pins at the bottom ------------------------------------
proc setNumberedBottomPins {xRight y pins} {
    setNumberedPins Bottom 2 $xRight $y $pins
}
#---- Generic numbered pins ------------------------------------------
proc setNumberedPins {side offsetPin0 x y pins} {
    set padWidth 95
    switch $side {
        Top - Bottom {set coords {list [expr $x-$offset] $y}}
        Right {set coords {list $x [expr $y-$offset]}}
    }
    foreach {number name index} $pins {
        set offset [expr max(0, $number * $padWidth + $offsetPin0)]
        setPin $name {*}[eval $coords] $side $index
    }
}

I'm not an experienced Tcl programmer and I wonder if there is a better way to solve this. Particularly, there is still some amount of code duplication left (almost identical definition of auxiliary variable coords inside switch) and I would like to eliminate that (while keeping the code reasonably readable).


texts:
In my web projects I often need a simple way to trigger callbacks defined somewhere else. Leaving jQuery finally behind me, I was missing their simple event system and tried to create my own. I'd like to know if this is a good implementation since I am not that proficient with Javascript yet.

function Events ()
{
    /**
     * handlers for an event
     *
     * @var {object}
     */
    this.stack = {}

    /**
     * on function.
     * adds a callback to an event stack
     *
     * @param {string} event       the event to subscribe to
     * @param {function} callback  the event callback to subscribe
     *
     * @return void
     */
    this.on = function (event, callback)
    {
        // if there is no callback registered for this event yet,
        // create an array for this event
        if (! this.stack.hasOwnProperty(event)) {
            this.stack[event] = []
        }

        // push the event callback to the handler stack
        this.stack[event].push(callback)
    }

    /**
     * off function.
     * removes a callback from an event stack
     *
     * @param {string} event       the event to unsubscribe from
     * @param {function} callback  the event callback to unsubscribe
     *
     * @return {bool}              whether the callback was removed or not
     */
    this.off = function (event, callback)
    {
        // if the event does not exist, return false
        if (! event in this.stack) return false

        // iterate over handlers, remove the callback in question
        this.stack[event] = this.stack[event].filter(
            function(item) {
                if (item !== callback) {
                    return item
                }
            }
        )

        return true
    }

    /**
     * trigger function.
     * calls all registered callbacks for an event
     *
     * @param {string} eventName  the event to trigger callbacks for
     * @param {mixed} data        optional data to hand over to the callbacks
     *
     * @return {bool}             whether the event has been fired
     */
    this.trigger = function (event, data)
    {
        // use an empty object if no data given
        var data = (typeof data === 'undefined') ? {} : data;

        // the event does not exist.
        if (! this.stack.hasOwnProperty(event)) return false

        // iterate over all callbacks, run them as expected
        for (var i = 0; i < this.stack[event].length; i++) {

            // @TODO: the scope should maybe be modifyable, even though
            //        this would require to specify a scope parameter
            //        for every event trigger...
            this.stack[event][i].call(window, event, data)
        }

        return true
    }
}

The Events class can later be instantiated and used in other objects like so:

// ...

this.eventHandler = new Events

this.eventHandler.on('testEvent', function(event, data) {
    console.log(event + ' fired! Data: ' + data)
})

this.eventHandler.trigger('testEvent', 'test data') // testEvent fired! Data: test data

// ...


texts: Removing this odd while(true) for checking the queue

texts:
I was reviewing some WPF code I've written in C# last year.

The scenario is the following:

I've got a usercontrol that show usermessages and it's docked in the bottom of the application's workspace
I've got a ConcurrentQueue that receives message via a IMessageMediator (from Catel, but's irrilevant how data are pushed)
I've a workerprocess that checks if there's some item in the queue and add them to a list that's bound to a grid

private readonly ConcurrentQueue<UserMessage> queue;
private readonly List<UserMessage> dataItems;

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    while (true)
    {
        if (!queue.IsEmpty)
        {
            UserMessage message;
            while (queue.TryDequeue(out message))
            {
                dataItems.Add(message);
            }
            RaisePropertyChanged(() => FilteredDataItems);
            RaisePropertyChanged(() => ErrorCountMessage);
            RaisePropertyChanged(() => WarningsCountMessage);

        }
        Thread.Sleep(500);
    }
}

//That's used to show only filtered items (Error/Warning....)

public IEnumerable<UserMessage> FilteredDataItems
{
    get
    {
        if (!enabledFilters.Any())
            return dataItems;
        return dataItems.Where(x => enabledFilters.Contains(x.LogMessageType));
    }
}

How can I remove this while(true) and the ugly/odd Thread.Sleep(500)?


texts: Printing the minuend and subtrahend in a Minimum Difference algorithm

texts:
I have a Minimum Difference algorithm, and I wanted to expand on it by printing the actual elements that were subtracted. I'm just wanting to know if this is the best way to do it.

public static int findMinimumDifference(int[] arr) {

    int minuend = 0; //initialize them here
    int subtrahend = 0;
    Arrays.sort(arr); //sort the array first

    int difference = 0;

    if (arr.length == 1) {
        difference = arr[0];
    }
    if (arr.length > 1) {
        difference = Math.abs(arr[0] - arr[1]); //This will give only positive integers for difference - e.g. 6 - 7 = -1 = 1

        for (int i = 0; i <= arr.length; i++) {
            if (i + 1 < arr.length) { //as long as we're not at the end yet
                int temp = Math.abs(arr[i] - arr[i + 1]); // temp variable is assigned to difference of consecutive elements i and i + 1
                if (temp < difference) // if temp is the new minimum difference, assign difference to temp
                    difference = temp;
                if(arr[i + 1] - arr[i] == difference) {
                    minuend = arr[i + 1]; //Here's where I assign them
                    subtrahend = arr[i];
                }
            }
        }
    }
    if(arr.length == 1) { //If there's only one element it will
                          //display arr[0] - 0 = arr[0]
                          //e.g. 12 - 0 = 12
        System.out.print(arr[0] + " - " + minuend + " = ");
    }
    else { //otherwise, show the subtraction
        System.out.print(minuend + " - " + subtrahend + " = ");
    }
    return difference;
    }
}

This is the output for two arrays as an example:

int[] array1 = {5, 16, 3, 32, 6};
int[] array2 = {13, 22, 37, 40, 11, 99, 100, 222, 1000, 101, 9999, 10000};

The minimum differences in the arrays are:
6 - 5 = 1
10000 - 9999 = 1

NOTE: I understand that second array actually has another subset (99, 100) that will equal 1. I just haven't figured out how to display both sets yet. I will work on that later.


texts: Detecting the mime type using an agnostic method

texts:
This function is used to get the mime type of any given file. The intended purpose was to have it working within any of our servers that vary from the latest PHP version down to PHP 4.

/**
 * Get the mime type for any given file.
 *
 * @param str $filename Path to the file including the filename
 *
 * @return mixed bol|arr Either false or the array provided by the PHP function
 */
function getMimeType($filename) {
  $mimetype = false;

  if (function_exists('finfo_fopen')) {
    $mimetype = finfo_fopen($filename);
  } elseif (function_exists('getimagesize')) {
    $mimetype = getimagesize($filename);
  } elseif (function_exists('exif_imagetype')) {
    $mimetype = exif_imagetype($filename);
  } elseif (function_exists('mime_content_type')) {
    $mimetype = mime_content_type($filename);
  }

  return $mimetype;
}

While the function is already tested on different PHP versions, I'm trying to ascertain if the methodology implemented can be improved, thus leading to code reduction and preventing any redundant verifications.

Can this function receive any type of improvement?


texts:
Just looking to do some super-duper basic email validation and was wondering if my code is efficient.

IE8 compatibility is a requirement.

/**
 * Email validation is futile
 * Make sure the @ symbol is not the first or last character
 */
jQuery.validator.addMethod("easyEmail", function(value, element, param) {
    value = $.trim(value);
    return this.optional(element) || (value.indexOf('@') > 0 && value.charAt((value.length-1)) !== '@');
}, "Please enter a valid email address.");

I am trying not to step on any toes since the RFC is mind-bogglingly complicated.


texts:
I made a template pipe and filters to replace an old pipe and filters implementation that used inheritance and had a very heavy base class.

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <list>

template <typename Data>
class pipeline {
    typedef boost::function<Data(Data)> filter_function;
    typedef std::list<filter_function> filter_list;
    filter_list m_list;

public:
    template<typename T>
    void add(T t) {
        m_list.push_back(boost::bind(&T::filter, t, _1));
    }

    Data run(Data data) {
        typedef typename filter_list::iterator iter;
        iter end = m_list.end();

        for(iter it = m_list.begin(); it != end; ++it) {
            data = (*it)(data);
        }

        return data;
    }
};

struct foo {
    int filter(int i) {
        return i + 1;
    }
};

int main(int argc, _TCHAR* argv[])
{
    pipeline<int> pipe;
    foo f;
    pipe.add(f);
    std::cout << pipe.run(0);
    char c;
    std::cin >> c;
}

Except the fact that add() is a template, are there any issues anyone sees with this approach?


texts: Extraction of value from a dict-tree, given a path of arbitrary length

texts:
Problem: We read a complex json-file which grants us a tree in terms of a python "dict of dicts". We're then requested to retrieve a specific path from the tree, represented by a list of elements. The list (i.e. the path) may have any, arbitrary length.

Simple Example:

# The dict-tree:
d = {"a":{"1":{"aa":"a2", "aaa":"a3"}},
     "b":{"2":{"bb":"b2", "bbb":"b3"}},
     "c":{"3":{"cc":"c2", "ccc":"c3"}},
     "d":{"4":{"dd":"d2", "ddd":"d3"}},
     "e":{"5":{"ee":"e2", "eee":"e3"}}
     }

# The path ..
p = ["b", "2", "bb"] # --> "b2"

Solution (to be improved):
Now, a naive solution could be to simply return d[p[0]][p[1]][p[2]]. However this obviously fails for any path-length not equal to three. Thus, I wrote two functions as shown below,

# Recursive approach
def get_val_from_path_1(d, p):
    if len(p)>1 and p[0] in d:
        return get_val_from_path_1(d[p[0]], p[1:])
    if p[0] in d:
        return d[p[0]]
    return None

# Iterative approach
def get_val_from_path_2(d, p):
    tmp = d
    for s in p:
        if not s in tmp:
            return None
        tmp = tmp[s]
    return tmp

A (very) simple time-consumption test can be run on my repl.it, which suggests that the iterative approach (no.2) is significantly faster than the recursive (no.1).

Preferably, I would really like a simpler approach, without any need of loops, however, any suggestions that improves performance, readability and/or code-line-usage are most appreciated.

EDIT: The question was intended for Python-3.x. I do not edit the label, because it is discussed in the comments of the below answer(s).


texts:
I am making an object formatter for use when debugging.

Formatted class:

package com.myname.somepackage;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

// Allows a variable to be displayed when using Formatter.format
@Retention(RetentionPolicy.RUNTIME)
public @interface Formatted {

}

Formatter class:

package com.myname.somepackage;

import java.lang.reflect.Field;

public final class Formatter {
    private Formatter() {}

    // Returns a string containing the object's information, for debugging
    // Format: ClassName[var1=somevalue, var2=somevalue]
    // The object's variables must have the Formatted annotation to be displayed here
    public static String format(Object object) {
        String className = object.getClass().getSimpleName();
        Field[] fields = object.getClass().getDeclaredFields();
        String string = className + "[";
        for (Field field : fields) {
            field.setAccessible(true);
            Formatted annotation = field.getAnnotation(Formatted.class);
            if (annotation != null) {
                String varName = field.getName();
                try {
                    String value = field.get(object).toString();
                    string += varName + "=" + value + ", ";
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    string += varName + "=" + "{Unavailable}, ";
                }
            }
        }
        // remove last ", "
        if (string.endsWith(", "))
            string = string.substring(0, string.length() - 2);
        string += "]";
        return string;
    }
}

A class for testing this:

package com.myname.somepackage.math.geom.r2;

import com.myname.somepackage.Formatted;
import com.myname.somepackage.Formatter;

public final class Point2d {
    @Formatted
    private final double x, y;

    public Point2d(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double getX() {
        return this.x;
    }
    public Point2d setX(double x) {
        return new Point2d(x, this.y);
    }
    public double getY() {
        return this.y;
    }
    public Point2d setY(double y) {
        return new Point2d(this.x, y);
    }

    @Override
    public String toString() {
        return Formatter.format(this);
    }
}

The code to test it:

Point2d point = new Point2d(4, 2);
System.out.println(point);

The console then outputs "Point2d[x=4.0, y=2.0]".

How does my code look? I understand reflection is considered bad, but this is just my lazy way of quickly debugging. Thanks


texts:
I am new in JS, I am writing some extra filters on the Interface. So extra filter needs to add or update the parameter in the URL.

Option 1. No parameter in existing URL:

url = https://custom.net/

We want to add new parameter in the URL where key issector and value is IndependentConsultingDoctors

Output will be: https://custom.net/?sector=IndependentConsultingDoctors

Option 2. Update value in parameter of existing URL

URL = https://custom.net/?filter=title&sector=1234&sortby=1&page=1

We want to update parameter in the URL where key issector and value is IndependentConsultingDoctors

Output will be: URL = https://custom.net/?filter=title&sortby=1&page=1&sector=IndependentConsultingDoctors

Option 3. Delete and add parameter:

URL = https://custom.net/?filter=title&reportype=1234&sortby=1&page=1

We want to add new parameter in the URL where key issector and value is IndependentConsultingDoctors and delete reportype and  inspectiontype parameters.

Output will be: URL = https://custom.net/?filter=title&sortby=1&page=1&sector=IndependentConsultingDoctors

The following is my code:

$(this).find('.btn').click(function(){
    //var pathname = window.location.href;
    var pathname = "https://abc.com/?filter_by=title&filter_condition=&sector=1234&reportype=3455&sortby=1&page=1&itemperpage=10&input_list=&current_selected_option=2&masterfilter=%26itemperpage%3D10%26filter_by%3DAll%26filter_condition%3D%26sortby%3D1%26from_date%3D%26to_date%3D&from_date=&to_date="
    // Key and Value which need to add in paramaetrs
    var key = "sector"
    var value = "Acutes";
    // Delete key from the parameters
    var delete_key = ["reportype", "inspectiontype"];

    // Split URL BASE and Get Parameters
    split_href = pathname.split("?");

    //No parameter present
    if (split_href.length==1) {
         window.location.href = split_href[0]+'?'+key+'='+value;
    }else{
        // Create dictionary of parameter
        var para_dict = {};
        var para_list = split_href[1].split("&");
        for (ii in para_list){
            var tmp = para_list[ii].split("=");
            para_dict[tmp[0]] = tmp[1];
        }
        // Add target kay and Value
        para_dict[key] = value;

        // Delete key from the dinctionary
        for (ii in delete_key){
            delete para_dict[delete_key[ii]];
        }
        //Create New Parameter string
        var new_para = "?";
        for (ii in para_dict){
            new_para = new_para+ii+"="+para_dict[ii]+"&";
        }
        console.log(split_href[0]+new_para);
    }

});

Can you review my code and give me a more optimized solution?


texts:
Task:

  Given a dictionary of words, and a set of characters, judge if all the
  characters can form the words from the dictionary, without any
  characters left.  For example, given the dictionary {hello, world, is,
  my, first, program}, if the characters set is "iiifrssst", you should
  return 'true' because you can form {is, is, first} from the set; if
  the character set is "eiifrsst", you should return 'false' because you
  cannot use all the characters from the set.

  P.S. there may be tens of thousands of words in the dictionary, and
  the chars set length could be up to hundreds, so I really need some
  efficient algorithm.

Source: http://www.careercup.com/question?id=5841660122497024

Here is my solution in Python:

from collections import Counter
from itertools import combinations_with_replacement
import copy

# Check if word can be made up with the characters in char_count
def valid_word(word):
    # build character count for word
    word_char_count = Counter(word)

    # check if character count for word
    for char in word_char_count.keys():
        if char not in char_count or word_char_count[char] > char_count[char]:
            return False

    return True

# Only return words that can be made up from characters with char_set
def prune_words(words):
    res = []
    for word in words:
        if valid_word(word):
            res.append(word)

    return res

def main(words, char_set):
    global char_count
    char_count = Counter(char_set)  # count character occurrences

    # Prune words that cannot possible be made from the set of characters
    words = prune_words(words)
    words_len = [len(word) for word in words]

    # Maximum number of r with generating combinations
    max_r = len(char_set) / min(words_len)

    # Generate permutations with the valid words
    for r in range(1, max_r + 1):
        for comb in combinations_with_replacement(words, r):
            # If the total length of the combination matches length of char_set,
            # do further checks
            if sum(map(len, comb)) == len(char_set):
                temp_count = copy.deepcopy(char_count)

                # Subtract char count of each word in combination from char_set
                for word in comb:
                    temp_count.subtract(word)

                # If the remaining count are all zero, then we have found an
                # answer
                if all([count == 0 for count in temp_count.values()]):
                    print comb
                    return True

    return False

if __name__ == '__main__':
    print main(['hello', 'world', 'is', 'my', 'first', 'program'],
               'iiifrssst')

What improvements can be made to my code (e.g. algorithmic speed, make it more 'Python', style, etc etc)?  Happy to hear any constructive comments!


texts: Variadic Functions in NASM Win64 Assembly

texts:
Simple variadic function implementation in NASM Assembly. When implemented like I have below:

sum.asm

;; bits 64
default rel

extern printf

section .text
    global main
    global sum
main:
    sub     rsp, 40
    mov     r9d, 3
    mov     r8d, 2
    mov     edx, 1
    mov     ecx, 3
    call    sum
    lea     rcx, [fmt]
    mov     edx, eax
    call    printf
    xor     eax, eax
    add     rsp, 40
    ret
sum:
    sub     rsp, 24
    test    ecx, ecx
    mov     qword [rsp+28H], rdx
    lea     rdx, [rsp+28H]
    mov     qword [rsp+30H], r8
    mov     qword [rsp+38H], r9
    mov     qword [rsp+8H], rdx
    jle     .end
    lea     eax, [rcx-1H]
    lea     rcx, [rsp+rax*8+30H]
    xor     eax, eax
.recurse:
    add     eax, dword [rdx]
    add     rdx, 8
    cmp     rdx, rcx
    jnz     .recurse
    add     rsp, 24
    ret
.end:
    xor     eax, eax
    add     rsp, 24
    ret

%macro str 2
    %2: db %1, 0
%endmacro

section .rdata
    str "%d", fmt

We can change how many variables are being given to the function without having to change the amount of memory being allocated to the function itself.

main:
    sub     rsp, 72
    mov     dword [rsp+30H], 6
    mov     dword [rsp+28H], 5
    mov     dword [rsp+20H], 4
    mov     r9d, 3
    mov     r8d, 2
    mov     edx, 1
    mov     ecx, 6
    call    sum
    lea     rcx, [fmt]
    mov     edx, eax
    call    printf
    xor     eax, eax
    add     rsp, 72
    ret

There are no comments in the code since what I'm doing should be pretty self-explanatory. Any advice and all topical comments on optimizing the code and its performance, as well as standard conventions, is appreciated!

Compiled as follows using VS2017 x64 Native Tools Command Prompt:

> nasm -g -f win64 sum.asm

> cl /Zi sum.obj msvcrt.lib legacy_stdio_definitions.lib


texts:
Is this a fair/clean way to detect a cycle in a LinkedList? Should work for both single and double LinkedLists'.

public bool IsCircular()
{
    if (Head != null && Head.Next != null)
    {
        var slow = Head;
        var fast = Head.Next;
        while (slow.Next != null && fast.Next != null && fast.Next.Next != null)
        {
            if (slow == fast)
            {
                return true;
            }
            slow = slow.Next;
            fast = fast.Next.Next;
        }
        return false;
    }
    else
    {
        return Head != null ? (Head == Head.Next) : false;
    }
}


texts:
Basically, I wish to have 3 printers to print in error state, success state or info state which means nothing but different colors.

    class ColorCode{
        private static $options = [
            "dark_gray"     => "1;30",
            "light_gray"    => "0;37",
            "blue"          => "0;34",
            "green"         => "0;32",
            "cyan"          => "0;36",
            "red"           => "0;31",
            "yellow"        => "1;33"
        ];

        public static function get($key){
            if(isset(self::$options[$key])){
                return self::$options[$key];
            } else {
                return '';
            }
        }
    }

    class ColorPrint {
        public $color = '';

        function __construct($color) {
            $this->color = ColorCode::get($color);
        }

        public function printc($msg) {
            echo "\033[". $this->color ."m".$msg."\033[0m\n";
        }

    }

    $out = [
        'error'     => new ColorPrint('red'),
        'info'      => new ColorPrint('cyan'),
        'success'   => new ColorPrint('green'),
    ];
    $out['error']->printc('Invalid Option');


texts:
Since I could not get numpy.gradient() to compute a derivative successfully, I wrote a script to compute it manually. Running the script below will output a plot of two functions f(x) = sin(x) and f'(x) = cos(x) over the interval 0 ≤ x ≤ 2 pi.

import numpy as np
import matplotlib.pyplot as plt

def compute_numerical_derivative(func, x, method='custom'):
    y = func(x)
    if method == 'custom':
        size = len(y0)
        res = np.zeros(size, 'd') # 'd' for double
        # centered differences
        for idx in range(1, size-1):
            res[idx] = (y[idx+1] - y[idx-1]) / (x[idx+1] - x[idx-1])
        # one-sided differences
        res[0] = (y[1] - y[0]) / (x[1] - x[0])
        res[-1] = (y[size-1] - y[size-2]) / (x[size-1] - x[size-2])
    # elif method == 'numpy':
    #     res = np.gradient(y)
    return res

x = np.linspace(0, 2*np.pi, 100)
y0 = np.sin(x)
y1_true = np.cos(x) # exactly d/dx (y0)

y1_cust = compute_numerical_derivative(np.sin, x, method='custom')
# y1_nump = compute_numerical_derivative(np.sin, x, method='numpy')

plt.plot(x, y1_true, 'r', marker='o', linestyle=None, alpha=0.5)
plt.plot(x, y1_cust, 'b', marker='^', linestyle=None, alpha=0.5)
# plt.plot(x, y1_nump, 'k', marker='*', linestyle='-', alpha=0.5)
plt.show()

Can the speed and/or accuracy of this algorithm be improved? Is it proper to use centered differences at interior points and one-sided differences at the boundaries?


texts:
Merged cells are a PITA in Excel. They prevent doing a lot of actions and make copying columns impossible. So I wrote this little code to change all the merged cells in a given sheet into 'Center across selection'.
I did NOT test against vertically merged cells, but it should not trigger an error (just unmerge them).

Sub fixMergedCells(sh As Worksheet)
'replace merged cells by Center Acroos Selection
'high perf version using a hack: https://stackoverflow.com/a/9452164/78522
    Dim c As Range, used As Range
    Dim m As Range, i As Long
    Dim constFla: constFla = Array(xlConstants, xlFormulas)

    Set used = sh.UsedRange
    For i = 0 To 1  '1 run for constants, 1 for formulas
        Err.Clear
        On Error Resume Next
        Set m = Intersect(used.Cells.SpecialCells(constFla(i)), used.Cells.SpecialCells(xlBlanks))
        On Error GoTo 0
        If Not m Is Nothing Then
            For Each c In m.Cells
                If c.MergeCells Then
                    With c.MergeArea
                        'Debug.Print .Address
                        .UnMerge
                        .HorizontalAlignment = xlCenterAcrossSelection
                    End With
                End If
            Next c
        End If
    Next i
End Sub

Sub test_fixMergedCells()
    fixMergedCells ActiveSheet
End Sub


texts:
My code is a mix-up between dynamic programming with the HashMap and brute force with the way I reach out the results and substring. I don't know how to optimize my algorithm without googling and looking for already solved solutions with different approaches.

class Solution {
    public String longestPalindrome(String s) {
        if (s.length() > 1000) return "";
        if (s.length() == 0) return "";
        HashSet<String> hs = new HashSet<>();
        int size = 1;
        String longest = s.substring(0, 1);
        for (int i = 0; i < s.length(); i++)
        {
            for (int j = i; j < s.length() - 1; j++)
            {
                String ss = s.substring(i, j+2);
                int ssl = ss.length();
                if (hs.contains(ss))
                {
                    if (ssl > size) {
                        size = ssl;
                        longest = ss;
                    }
                }
                else{
                    if (isPalindrome(ss)){
                        hs.add(ss);
                        if (ssl > size) {
                            size = ssl;
                            longest = ss;
                        }
                    }
                }
            }
        }
        return longest;
    }

    public boolean isPalindrome(String s) {
        int j = s.length() - 1;
        int i = 0;
        while (i < j){
            if (s.charAt(i) != s.charAt(j)){
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}

The webpage where this problem is posted says the max size of the string can be 1000. However if a string of that size is the input the algorithm takes 200-210 ms to execute and return the substring.

I'm 100% sure it works, but it's slow.


texts: Simple wrapper function grouping and summarising variable

texts:
Background

I've wrote a trivial wrapper function summarising variable by group for dplyr. I would like to handle quosures more efficiently. In particular, I've a hunch that rlang::UQE(var) could be written more efficiently.

Code

#' @title Create a simple sum by grouping variables
#'
#' @description
#' \code{sum_by_group} is simple wrapper groping variables and deriving sum
#'
#' @details
#' This is a primitive utility function performing
#'   \code{group_by %>% summarise(sum(.)) %>% ungroup} on passed variables.
#'
#' @param df A data.frame or tibble to conduct summary on
#' @param var A numeric variable to summarise
#' @param ... Grouping variables.
#'
#' @return A \code{data.frame} with grouping variables and summary.
#'
#' @import rlang
#'
#' @export
#'
#' @examples
#' mtcars %>% sum_by_group(disp, cyl, am)
sum_by_group <- function(df, var, ...) {
    # Take variables to group by
    group_vars <- quos(...)
    # Take sum variable
    var <- enquo(var)
    # Group and summarise
    df %>%
        group_by(!!!group_vars) %>%
        summarise(sum_var = sum(!!var)) %>%
        ungroup() %>%
        # Rename variable
        setNames(gsub("sum_var",
                      paste(rlang::UQE(var), "sum", sep = "_"), names(.)))

}

Example

>> mtcars %>% sum_by_group(var = disp, am, cyl)
# A tibble: 6 x 3
     am   cyl disp_sum
  <dbl> <dbl>    <dbl>
1     0     4    407.6
2     0     6    818.2
3     0     8   4291.4
4     1     4    748.9
5     1     6    465.0
6     1     8    652.0


texts: Unordered list in HTML with animated list points

texts:
I had this idea today, but I don't have any practical usage for it right now. Any feedback or improvements welcome.

Code is found at CodePen, and also presented here as a snippet:

ul {
  list-style-type: none;
  width: 250px;
  border: 2px solid #a9a9a9;
  border-radius: 16px;
  margin: 0 auto;
}

.item {
  margin: 10px 0;
}

.point {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 20px;
  border-radius: 0 50%;
  transform: rotate(0deg);
}

.point:hover {
  transform: rotate(-45deg);
}

.text {
  display: inline-block;
  width: 200px;
  color: #121212;
  font-family: helvetica;
}

li:nth-of-type(1) div:first-child {
  background-color: rgba(30, 30, 30, 1.0);
}

li:nth-of-type(2) div:first-child {
  background-color: rgba(60, 60, 60, 1.0);
}

li:nth-of-type(3) div:first-child {
  background-color: rgba(90, 90, 90, 1.0);
}

li:nth-of-type(4) div:first-child {
  background-color: rgba(120, 120, 120, 1.0);
}

li:nth-of-type(5) div:first-child {
  background-color: rgba(150, 150, 150, 1.0);
}

Alpha

Beta

Gamma

Delta

Epsilon


texts:
My objective is computing a table of primes up to n, where n is a natural number passed as an argument to the prime_table function.

Here is src/lib.rs:

#![feature(vec_remove_item)]

// Return a vector containing all the products between i and natural numbers beyond 2.
// The vector only includes products which are not greater than the maximum specified.
fn get_multiples(i: u32, max: u32) -> Vec<u32> {
    let mut results = Vec::new();
    let max_multiplier = max / i;
    for number in 2..=max_multiplier {
        results.push(i * number);
    }
    results
}

// Return a vector containg all the primes up to n.
pub fn prime_table(n: u32) -> Vec<u32> {
    let root_of_n = (n as f64).sqrt() as u32;
    let mut table: Vec<u32> = (2..=n).collect();
    for i in 2..=root_of_n {
        if !table.contains(&i) {
            continue;
        }
        for multiple in get_multiples(i, n).iter() {
            table.remove_item(&multiple);
        }
    }

    table
}

Something I'd like but I'm not sure is possible would be changing get_multiples to return an iterator of the results vector instead of the vector itself, but I'm not sure how. If there is a way, I suspect it necessitates lifetimes, something I haven't grasped yet

My main concern is avoiding unnecessarily allocating memory.


texts: Loading either all shops or a specifically named shop from a DataTable

texts:
public  delegate DataTable loadDataTable();

DataTable shops = (cmbShop.Text == "All Shops") ?
      new loadDataTable(() =>
       {
       Program.con.GET_Table_From_DataBase("sh", "select * from shops ");
       return Program.con.dst.Tables["sh"];
       }
      ).Invoke()
     :
       new loadDataTable(() =>
       {
        Program.con.GET_Table_From_DataBase("sh", "select * from shops where shopname='" +  cmbShop.Text + "' ");
        return Program.con.dst.Tables["sh"];
       }
  ).Invoke();

I am just setting the value of DataTable shops here.

I am learning about lambda expressions, so just for learning purposes, I want to know if this code can be shortened while using lambda expressions.


texts: Ruby Regex to update various variables inside a file

texts:
In our applications we have a version file that has three variables that are then joined to create a string that can be used for the semantic version.

The file looks like:

# frozen_string_literal: true

major = 0
minor = 1
patch = 0

PORTAL_VERSION = [major, minor, patch].join('.')

And then we update it using the following from our CI server:

@version = '0.1.1' # this is passed from somewhere

puts 'updating version'
version_file = File.open("version.rb").read
version = @version.split('.')
version_file = version_file.gsub(/(major = \w)/, "major = #{version[0]}")
version_file = version_file.gsub(/(minor = \w)/, "minor = #{version[1]}")
version_file = version_file.gsub(/(patch = \w)/, "patch = #{version[2]}")
File.open('version.rb', 'wb') { |file| file.write(version_file) }
puts "updated version to #{@version}"

Is there a better way to do the replacement using the regex? As by having to find each line and then replace it feels a little dirty, plus if there was or wasn't spaces between the variable name and value it wouldn't work. So it feels a little fragile.


texts: correctly implement PHP OOP in blog Post Class

texts:
I would like to know the best way to setup my PHP Blog classes.

I have created a Post class which creates a blog post.

class Post
{

private $title;
private $body;
private $createdDate;
private $publishedDate = null;
private $published = false;

public function __construct(string $title, string $body)
{
    $this->setTitle($title);
    $this->setBody($body);
    $this->createdDate = date('d/M/Y/');
}

public function publish()
{
    $this->published = true;
    $this->publishedDate = date('d/M/Y/');
}

public function unpublish()
{
    $this->published = false;
    $this->publishedDate = null;
}

public function setTitle(string $title)
{
    $this->title = $title;
}

public function getTitle(): string
{
    return $this->title;
}

public function setBody(string $body)
{
    $this->body = $body;
}

public function getBody(): string
{
    return $this->body;
}

}

I also have a simple Database class

class Database
{

private $db;

public function __construct($host, $name, $username, $password)
{
    $dsn = "mysql:host=$host;dbname=$name";
    try {
        $this->db = new PDO($dsn, $username, $password);
    } catch (PDOException $e) {
        die('Error: ' . $e->getMessage());
    }
}
}

My question is where should the database class be extended from? I could use it in my Post class, but it wouldn't really make sense to make Post queries related to just this specific blog post. It also wouldn't make sense to perform a query to get all posts just from this object. The SOLID principle states a class should just have one single responsibility. Therefore I'm concerned that creating a post object and running multiple queries within the class is causing the class to have lots of responsibilities.

I have read about static methods where these could be of use, as I could run a query on a Post object, which wouldn't need to be instantiated. However, I have read that static methods should be avoided due to a variety of reasons, such as breaking encapsulation.

I have searched for examples online, but they don't seem to be implementing OOP completely. Any Pure OOP examples you know would be great to hear about.


texts: Switching between queues in cellForIndexPath method

texts:
My tableView is scrolling very slowly because there is a fetch request done in every cellForIndexPath method. I have verified this using instruments. The result of the fetch request determines the color of the label inside the cell.

Here is a solution I am using inside the custom cell:

func configureWith(myObject: MyObject) {
    titleLabel.text = myObject.text
    DispatchQueue.global(qos: .background).async {
        let color = self.getColor(forGroup: myObject.group)

        DispatchQueue.main.async {
            self.titleLabel.textColor = color
        }
    }
}

Is this a good solution?

Edit: Changing qos to userInitiated seems to work slightly better in that the scrolling is still virtually instant and the labels show the right color much faster.


texts:
I'm practicing Swing effects. Everything works but for some reason I get a ton of error messages in the command prompt when the fields are empty, despite my attempt to add some exception handling (this has made me realize I need to practice that a lot more).

    /* Author: Luigi Vincent
Practicing Java Swing button and button events; Window that does simple calculation on two numbers
TO DO: Figure out why command prompt show so many messages when fields are empty & stop it
*/

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;

public class SimpleCalc extends JFrame {

    SimpleCalc (String name) {
        super(name);

        setLayout(new FlowLayout());

        // Fields for input and output
        JTextField result = new JTextField(10);
        JTextField num1 = new JTextField(5);
        JTextField num2 = new JTextField(5);
        result.setEditable(false);

        // Buttons for operations
        JButton b_add = new JButton("Add");
        JButton b_sub = new JButton("Subtract");
        JButton b_mul = new JButton("Multiply");
        JButton b_div = new JButton("Divide");

        // Listener to handle operations
        ActionListener calculator = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if (num1.getText().length() == 0 || num2.getText().length() == 0) {
                        throw new Exception();
                    }
                }
                catch (Exception ex){
                    JOptionPane.showMessageDialog(null, "Field missing", "Warning", JOptionPane.WARNING_MESSAGE);
                }

                Double alpha = Double.parseDouble(num1.getText());
                Double beta = Double.parseDouble(num2.getText());
                Double omega = null;
                DecimalFormat f = new DecimalFormat("##.00");

                if (e.getSource() == b_add) {
                    omega = alpha + beta;
                }
                else if (e.getSource() == b_sub) {
                    omega = alpha - beta;
                }
                else if (e.getSource() == b_mul) {
                    omega = alpha * beta;
                }
                else if (e.getSource() == b_div) {
                    omega = alpha / beta;
                }
                result.setText(f.format(omega).toString());
            }
        };
       // Register buttons to event listener
        b_add.addActionListener(calculator);
        b_sub.addActionListener(calculator);
        b_mul.addActionListener(calculator);
        b_div.addActionListener(calculator);

       // Add everything to frame + labels
        add(new JLabel("First Number"));
        add(num1);
        add(new JLabel("Second Number"));
        add(num2);
        add(new JLabel("Result"));
        add(result);
        add(b_add);
        add(b_sub);
        add(b_mul);
        add(b_div);
    }
    public static void main(String[] args) {
        SimpleCalc frame = new SimpleCalc("Simple Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 100);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

I'm open to any and all improvements possible.


texts: Toggling between light and dark mode using JavaScript

texts:
This is some code written in a course I'm busy taking on Udemy. It serves as a basic toggle switch to flip between light and dark mode. This includes the nav bar, background, images and the icon that changes from a sun to a moon.
The objective after the lesson was to clean up the code and make it DRY. I've done so to some of the code already. But there are some instances where it still repeats, for instance isDark in my lightDarkMode function. Is there a way to eliminate the repetitive usage of isDark?
const toggleSwitch = document.querySelector('input[type="checkbox"]');
const nav = document.getElementById('nav');
const toggleIcon = document.getElementById('toggle-icon');
const textBox = document.getElementById('text-box');
const darkLightTheme = ['dark', 'light'];

function imageMode(color) {
    image1.src = `img/undraw_proud_coder_${color}.svg`;
    image2.src = `img/undraw_feeling_proud_${color}.svg`;
    image3.src = `img/undraw_conceptual_idea_${color}.svg`;
}

    lightDarkMode = (isDark) => {
    nav.style.backgroundColor = isDark ? 'rgb(0 0 0 / 50%)' : 'rgb(255 255 255 / 50%)';
    textBox.style.backgroundColor = isDark ? 'rgb(255 255 255 / 50%)' : 'rgb(0 0 0 / 50%)';
    toggleIcon.children[0].textContent = isDark ? 'Dark Mode' : 'Light Mode';
    isDark ? toggleIcon.children[1].classList.replace('fa-sun', 'fa-moon') : toggleIcon.children[1].classList.replace('fa-moon', 'fa-sun');
    isDark ? imageMode(darkLightTheme[0]) : imageMode(darkLightTheme[1]);
}


texts:
i've written a basic function to split an array into stride by 2:

[z] -> [x],[y]

    func splitArray(Z x:[Float64])->(Real:[Float64],Imag:[Float64])
    {
      guard (x.count % 2 == 0) else {"BOMB:: need even number of elements in array \(#file) \(#line) \(#function)"
      return ([0.0],[0.0])
      }
      var Real:[Float64] = zeroD(npts: Int(x.count/2) )
      var Imag:[Float64] = zeroD(npts: Int(x.count/2) )
      var ida:Int = 0, idb:Int = 0
  for elem in stride(from:0, to: x.count-1, by:2)
  {
      Real[ida] = x[elem]
      ida += 1
  }
  for elem in stride(from:1, to:x.count, by:2)
  {
    Imag[idb] = x[elem]
    idb += 1
  }
      return (Real,Imag)
}

Does anyone have a faster map? Sometimes map is not that fast and just hides the loop?

I'm hoping for solutions which have been designed to crunch big data arrays or like google's big table, although not sparse.  Something like a Metal/GPU pipeline? hyper-threading model? an Atomic que/stack? pulling in an external optimized lib like boost?

The algorithm behind map is unknown, sometimes it's faster than a simple loop sometimes not.  It's not deterministic, generally not a good thing, but it's easy to implement.

I've tried unrolling loops in Xcode flags but seems to make no different with an arrays of size MxN>[500,500].


texts: Initializing more than one instance object at a time in init method

texts:
I have a RadioStation class file and a view controller where I create two station objects based on this class, one for FM and one for AM.

I created both of these station objects from within the same required init method. I'm not sure this was this the best way to do this, for example can you imagine if you wanted 8 such objects, this would just get very clunky. Is the issue rather that I am creating them in the view controller, and should I have in fact created separate subclass files for each and init them in those?
Or should I have created two separate init methods, one for each new object?

RadioStation Class File: RadioStation.swift

import UIKit

class RadioStation: NSObject {

    var name: String
    var frequency: Double

    override init() {  //init class method to set default values.
        name = "Default"
        frequency = 100
    }

    static var minAMFFrequency: Double = 520.0
    static var maxAMFFrequency: Double = 1610.0
    static var minFMFFrequency: Double = 88.3
    static var maxFMFFrequency: Double = 107.9

    func isBandFM() -> Int {
        if frequency >= RadioStation.minFMFFrequency && frequency <= RadioStation.maxAMFFrequency {
            return 1 //FM
        } else {
            return 0 //AM
        }
    }

}

View Controller Class

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var stationName: UILabel!
    @IBOutlet weak var stationFrequency: UILabel!
    @IBOutlet weak var stationBand: UILabel!

    var myStation: RadioStation

    var myStationAM: RadioStation //second object variable

    required init?(coder aDecoder: NSCoder) {
        myStation = RadioStation()
        myStationAM = RadioStation()
        myStation.frequency = 104.7
        myStationAM.frequency = 600.2
        myStation.name = "FM1"
        myStationAM.name = "AM1"
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func buttonClick(_ sender: Any) {
        stationName.text = myStation.name //set top left label text to name property of myStation object instance
        stationFrequency.text = "\(myStation.frequency)"
        if myStation.isBandFM() == 1 {
            stationBand.text = "FM'"
        } else {
            stationBand.text = "AM"
        }
    }

    @IBAction func buttonClickAM(_ sender: Any) {
        stationName.text = myStationAM.name
        stationFrequency.text = "\(myStationAM.frequency)"
        if myStationAM.isBandFM() == 1 {
            stationBand.text = "FM"
        } else {
            stationBand.text = "AM"
        }
    }

}


texts: Optimizing nested if statements in switch

texts:
I have this code and I think it is very slow, about 50ms. I need to make it execute faster:

 switch (unit)
   {
       case 0:
       if (u == 2)
       {
           if (u1 == "piece" || u1 == "gram")
               result = quantity * y;
           else
               result = quantity * z;
       }
       if (u == 1)
       {
           if (u1 == "piece" || u1 == "gram")
               result = quantity * y;
           else
               result = quantity;
       }
       res_name = "gram";
       break;

       case 1: //ml
       if (u == 2)
       {
           if (u1 == "piece" || u1 == "gram")
               result = quantity * x;
           else
               result = quantity * y;

       }
       if (u == 0)
       {
           if (u1 == "piece" || u1 == "gram")
               result  = quantity * x;
           else
               result = quantity;
       }
       res_u = "ml";
       break;

case 2:
    res_u = "pieces";
    break;
 }


texts: Implementing Passport authentication with promises

texts:
Here is code implementing Passport authentication with a Google Strategy. It uses Mongoose to store and retrieve user data.

You might need to be familiar with both of these technologies to review this code if not check out the two links I provided.

I have included only the Passport file. I was told I am not using promises correctly and would like to rectify this if it is in fact true.

The code is full of comments below.  Please let me know if more clarification or context is needed.

Thanks for any feedback.

Passport

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const DBM = require('../../database/mongoose');
const helper = require('../../config/helper');

// review this post
// https://stackoverflow.com/questions/50339887/can-i-reduce-this-passport-code

// configure Passport to use Google Auth
passport.use('google', new GoogleStrategy(helper.getPassport(), getOrCreateUser));

// passed to passport, this is the starting point for Google Auth
function getOrCreateUser (accessToken, refreshToken, profile, done) {

  // abstracts out relevant information from what Google returns
  const user_props = obtainProps(profile);
  DBM.getUser(user_props.id_google).then( (res) => {

    // res[0] will be "true" if the user exists
    return res[0] ? done(null, user_props) : createUser(done, user_props);
  }).catch( error => {
    return done(error, null);
  });
}

// the user was not found, create the user
function createUser (done, user_props) {
  DBM.createUser(user_props).then(() => {
    return done(null, user_props);
  }).catch( error => {
    return done(error, null);
  });
}

// serializeUser required by passport to identify the user uniquely on the client
passport.serializeUser( (profile, done) => {
  done(null, profile.id_google);
});

// deserializeUser required by passport to retrieve data on the server using unique
// identifier created by serializeUser
passport.deserializeUser( (id_google, done) => {
  DBM.getUser(id_google).then((res) => {
    done(null, res[0]);
  }).catch( (error) => {
    console.error('DBM.getUser() Error: ', error);
  });
});

// takes a profile from Google and extracts parameters to save
function obtainProps (profile) {
  let props = {};
  props.id_google = profile.id;
  props.email = profile.emails[0].value;
  props.name = profile.displayName;
  props.pic_url = profile.photos[0].value;
  props.type = profile._json.objectType;
  return props;
}

module.exports = passport;


texts:
I have this method, which first basically shows a Welcome screen to user only once per day. The code I have so far is this

private func showGreetingScreen (tabbar: UITabBarController) {
    let defaults = UserDefaults.standard
    if defaults.object(forKey: "greetingDate") == nil {
        defaults.set(Date(), forKey: "greetingDate")
        presentWelcomeScreen(tabbar: tabbar)
    } else {
        if let greetingDate = defaults.object(forKey: "greetingDate") as? Date {
            let order = Calendar.current.compare(Date(), to: greetingDate, toGranularity: .day)
            if order == .orderedDescending {
                defaults.set(Date(), forKey: "greetingDate")
                presentWelcomeScreen(tabbar: tabbar)
            }
        }
    }
}

Now as you can see first I am checking whether Welcome Screen was shown in past or not and then I am saving current date. Then next time app will load, it will compare current date and the date Welcome Screen was shown and based on that It will show Welcome screen to User.
I have feeling that this code can be refactored more.


texts: Program to display a matrix in a spiral form

texts:
I found an interview question which requires us to print the elements of the matrix in a spiral order starting from the top left. I need some pointers on how to improve my code:

#include <stdio.h>

//function that prints a row from startx,starty to endy
void printRow(int arr[][4],int startx,int starty,int endy)
{
    int yCtr;
    for(yCtr = starty; yCtr <= endy ; yCtr ++)
       printf("%d ",arr[startx][yCtr]);
}

//function that prints a row from startx,starty to endy (decreasing columns)
void printRowBackward(int arr[][4],int startx,int starty,int endy)
{
    int yCtr;
    for(yCtr = starty; yCtr >= endy ; yCtr --)
       printf("%d ",arr[startx][yCtr]);
}

//function that prints a column from startx,starty to endx
void printColumnBackward(int arr[][4],int startx,int starty,int endx)
{
   int xCtr;
    for(xCtr = startx; xCtr >= endx; xCtr --)
       printf("%d ",arr[xCtr][starty]);
}

// column backwards
void printColumn(int arr[][4],int startx,int starty,int endx)
{
    int xCtr;
    for(xCtr = startx; xCtr <= endx; xCtr ++)
       printf(" %d ",arr[xCtr][starty]);
}

// prints a section of the spiral
void printSpiralSection(int arr[][4],int startx,int starty,int size)
{
   printRow(arr,startx,starty,size - 1);
   printColumn(arr,startx + 1 ,size - 1 ,size -1);
   printRowBackward(arr,size - 1,size - 2,starty);
   printColumnBackward(arr,size - 2,starty,startx + 1);
}

int main()
{
    int array[4][4] = { 22 ,323,2342,222,
                          2,234,243,333,
                          21,13,23,444,
                          223,234,231,234};

    int startx =0, starty = 0, size = 4;
    // prints each section of the spiral ...
    while(size >=1) {
       printSpiralSection(array,startx,starty,size);
       size --;
       startx++;
       starty++;
    }
    getchar();
    return 0;
}


texts: Sorting function that also works with containers having only forward iterators

texts:
I was playing around with some code trying to implement a sorting algorithm in C++ that also works with singly linked lists. Since the merge routine of mergesort only scans forward, implementing a generic mergesort seemed like the way to go.

In C, I would have implemented it as follows:

typedef struct node {
  int val;
  struct node *next;
} node_t;

/* Merges two sorted linked lists placing the result in the
   first list. The function modifies both lists */
node_t* merge(node_t *ha, node_t *hb)
{
  if(!ha)
    return hb;
  if(!hb)
    return ha;

  node_t *i;
  node_t *prev;
  node_t *j = hb;

  prev = NULL;
  i = ha;
  while(i || j) {
    if(!j) break;
    if(!i) {
      prev->next = j;
      break;
    }

    if(j->val < i->val) {
      if(!prev)
        ha = j;
      else
        prev->next = j;

      prev = j;
      j = j->next;
      prev->next = i;
    }
    else {
      prev = i;
      i = i->next;
    }
  }

  return ha;
}

node_t* mergesort(node_t *ha)
{
  if(!ha || !ha->next)
    return ha;

  node_t * prev;
  node_t *mid = ha;
  node_t *fast = ha;

  /* Find midpoint of linked list */
  while(1) {
    fast = fast->next;
    if(!fast) break;
    fast = fast->next;
    if(!fast) break;
    mid = mid->next;
  }

  prev = mid;
  mid = mid->next;
  prev->next = NULL;
  ha = mergesort(ha);
  mid = mergesort(mid);
  return merge(ha, mid);
}

Here is my C++ implementation, which I would like to have reviewed:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <list>

template<typename InputIt1, typename InputIt2, typename OutputIt>
OutputIt my_merge(InputIt1 first1,
               InputIt1 end1,
               InputIt2 first2,
               InputIt2 end2,
               OutputIt out)
{
  while(first1 != end1) {
    if(first2 == end2)
      return std::copy(first1, end1, out);

    if(*first1 < *first2) {
      *out = *first1;
      ++first1;
    }
    else {
      *out = *first2;
      ++first2;
    }
    ++out;
  }

  return std::copy(first2, end2, out);
}

template<typename InputIt>
void mergesort(InputIt first, InputIt end)
{
  size_t n = std::distance(first, end);
  if(n < 2)
    return;
  InputIt mid = first;

  for(size_t i = 0; i < n/2; ++i)
    ++mid;

  std::vector<typename InputIt::value_type> res;
  mergesort(first, mid);
  mergesort(mid, end);
  my_merge(first, mid, mid, end, std::back_inserter(res));
  std::copy(res.begin(), res.end(), first);
}

int main()
{
  std::list<int> a { 1,2,8,4,2457,5,2,58,3,564,6,7 };
  mergesort(a.begin(), a.end());
  for(auto& i : a)
    std::cout << i << std::endl;
  return 0;
}

Questions:

Are there any obvious ways of improving my C++ implementation?
Are there any possible efficiency improvements? My annoyance is mostly that I walk any list twice for searching the midpoint. Is there a way of doing this without having to manually write a traversal of the list of two iterators, one moving one step at a time and the other two to get the midpoint in one sweep?
Do I have to give up generality in C++? I don't see how to do the linear "in-place merge" as with the C implementation unless we specialize. I'm not sure if it's possible to do an in-place merge of two STL lists either, since you don't have direct access to the next and previous pointers?


texts:
I am working on a application that is made completely in JavaScript (other than the database) and I've created a simple user management system for the application.

This user management system creates a query to the database containing the user info (the database contains the user info not the query) based on a few command line arguments, decrypts the data in the database, and then prints the result to the console.

I have been programming for 2 years but am self-taught and was looking for some feedback/criticism on my code.

Note: Some of the modules in the Main script are not included but, for the most part, their functions should be intuitive.

Edit: for more information about the DataBase class see this question.

Here is my code:

Main script:

// this is a instance of a `DataBase` class:
const users = require('../../Code/MiddleWare/Database-comms/createUser').users
const lookup = require('./lookup')
const decryptAll = require('./decrypt')

void async function() {
  if(process.argv[2] === '-e') {
    console.dir(decryptAll(await lookup('Email', process.argv[3], users, process.argv[4] === '-ex')), {colors: true, depth: Infinity})
  } else if(process.argv[2] ? process.argv[2].match(/^\d+$/) : false) {
    console.dir(decryptAll(await lookup('ID', parseInt(process.argv[2]), users, process.argv[3] === '-ex', false)), {colors: true, depth: Infinity})
  } else {
    console.dir(decryptAll(await lookup('Username', process.argv[2] ? process.argv[2] : '', users, process.argv[3] === '-ex')), {colors: true, depth: Infinity})
  }
}()

"lookup" module:

module.exports = async function(type, string, users, exact,  encrypted = true) {
  const aes = require('../../Code/MiddleWare/Security/index').encryption.AES
   const retval = []
   await users.query('Users').then((data) => {
     for(let i of data) {
        if(encrypted ? (exact? aes.decrypt(i[type]) === string : aes.decrypt(i[type]).match(string)) : i[type] === string) {
          retval.push(i)
        }
     }
   })

   return retval.length === 0 ? false : retval
}

The "decrypt" module:

const decrypt = require('../../Code/MiddleWare/Security/encryption').AES.decrypt

module.exports = function(array) {
  if(!array) {
    return false
  }

  const retval = []

  function decryptAll(obj) {
    return {ID: obj.ID, Username: decrypt(obj.Username), Email: decrypt(obj.Email), Data: decrypt(obj.Data), Password: obj.Password}
  }

  for(const i of array) {
    const item = decryptAll(i)
    item.Data = JSON.parse(item.Data)
    retval.push(item)
  }

  return retval
}


texts: Finding a way to obtain some volume of water using a large and small bucket

texts:
I have a set of if/else statements that trigger certain actions. As a first step, I was thinking about moving the logic in each if statement to be its own function, but are there any recommendations on what design patterns can help clean this code up?

I guess I am trying to see if there is a cleaner way to determine what the next action/command should be based on a set of criteria. I see people recommend the Command pattern, but how does one abstract the logic in the if-statement to begin with?

function WaterRetriever(largeBucketSize, smallBucketSize, waterSize) {
    var buckets = {};

    if (waterSize > largeBucketSize) {
        throw new Error("The buckets are not large enough.");
    }

    buckets.firstContainer = new Bucket(largeBucketSize);
    buckets.secondContainer = new Bucket(smallBucketSize);

    this.getWaterFromLake = function () {
        var maxSteps = 25,
            step = 1;

        buckets.firstContainer.fill();

        while (step <= maxSteps && buckets.firstContainer.getCurrentAmount() !== waterSize) {
            if (buckets.firstContainer.isFull() && buckets.secondContainer.isEmpty()) {
                buckets.firstContainer.transferTo(buckets.secondContainer);

            } else if (buckets.secondContainer.isFull() && buckets.firstContainer.hasCapacityAvailable()) {
                buckets.secondContainer.empty();
                buckets.firstContainer.transferTo(buckets.secondContainer);
            } else if (buckets.firstContainer.isEmpty() && buckets.secondContainer.hasCapacityAvailable()) {
                buckets.firstContainer.fill();
            } else if (buckets.firstContainer.isFull() && buckets.secondContainer.hasCapacityAvailable()) {
                buckets.firstContainer.transferTo(buckets.secondContainer);
            }
            console.log(buckets.firstContainer.getCurrentAmount() + ", " + buckets.secondContainer.getCurrentAmount());
            step = step + 1;
        }

        if (step > maxSteps) {
            console.log("could not find a solution within the steps limit...");
        }
    };
}


texts: Writing an HTTP POST body that has new lines

texts:
I am looking for general ways to simplify this. What it does is write a body and send an HTTP POST request to an endpoint. I had the method require a list just to append new lines for each string I build at an earlier point in time. The expected response is in JSON, so I'm also looking for ways to simplify capturing the response. If there are any small libraries that can do this I can consider using them.

private void makeRequest(List<String> records) throws IOException
{
    URL url = new URL("http://my-api.com/post-endpoint");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    try (OutputStream output = connection.getOutputStream()) {
        Iterator<String> iterator = records.iterator();
        while (iterator.hasNext()) {
            String json = iterator.next();
            output.write(json.getBytes(Charset.forName("UTF-8")));
            if (iterator.hasNext()) {
                output.write('\n');
            }
        }
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    System.out.println("RESPONSE: " + response.toString());
}


texts:
I needed to write a settings class for my web app; ideally this class should read its settings from a file (and be able to save them back to the file), and have only 1 instance per application - all threads read the same object, so that the settings only need to be loaded from the file when the app runs for the first time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Security.Cryptography;
using System.Configuration;
using System.Xml.Serialization;
using System.Web.Caching;
using System.IO;

namespace Secure_Password_Repository.Settings
{
    [Serializable]
    public sealed partial class AppSettings
    {
    private static readonly XmlSerializer serial = new XmlSerializer(typeof(AppSettings));
    private static AppSettings instance;
    private static Object thisLock = new Object();

    private static void serializeToDisk(string key, CacheItemUpdateReason reason, out Object expensiveObject, out CacheDependency dependency, out DateTime absoluteExpiration, out TimeSpan slidingExpiration)
    {

        string filename = HttpContext.Current.Server.MapPath("settings.xml");

        expensiveObject = instance;
        dependency = new CacheDependency(filename);
        absoluteExpiration = Cache.NoAbsoluteExpiration;
        slidingExpiration = Cache.NoSlidingExpiration;

        using (StreamWriter sw = new StreamWriter(filename))
        {
        serial.Serialize(sw, instance);
        }
    }

    public static void Save()
    {
        string filename = HttpContext.Current.Server.MapPath("settings.xml");
        using (StreamWriter sw = new StreamWriter(filename))
        {
        serial.Serialize(sw, instance);
        }
    }

    public static AppSettings Default
    {
        get
        {

        Cache cache = HttpRuntime.Cache;
        string filename = HttpContext.Current.Server.MapPath("settings.xml");

        if (cache[filename] != null) {
            return (AppSettings)cache[filename];
        }

        lock (thisLock)
        {

        if (cache[filename] != null) {
            return (AppSettings)cache[filename];
        }

            using (StreamReader sr = new StreamReader(filename))
            {
            instance = (AppSettings)serial.Deserialize(sr);
            cache.Insert(filename, instance, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);

            if (instance.EncryptionKeySalt == "")
            {
                //random number generator
                RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();

                //create 20 random bytes for the salt
                byte[] CryptoBytes = new byte[40];
                rngCsp.GetBytes(CryptoBytes);

                rngCsp.Dispose();

                instance.EncryptionKeySalt = Convert.ToBase64String(CryptoBytes);
            }

            return (AppSettings)cache[filename];
            }
        }

        }
    }

    public string LogoImage{ get; set; }

    public string DefaultAccountRole{ get; set; }

    public string SMTPServerAddress{ get; set; }

    public string SMTPServerUsername{ get; set; }

    public string SMTPServerPassword{ get; set; }

    public string EncryptionKeySalt{ get; set; }

    }
}

I'm just curious: is this "good code"? Are there any potential pitfalls I'm not seeing? is there anything I could be doing better?


texts: Number-guessing game, for numbers between 0 and 99

texts:
I have written a complex number guess game. The output should be like this:

Enter initial guess between 0 and 99:
45
Initial guess is 45
45 is too high. Make a guess between 0 and 45
10
10 is too high. Make a guess between 0 and 10
50
50 out of range. Make a guess between 0 and 10
2
2 is too low. Make a guess between 2 and 10
8 is the correct guess! Game over!

What I wrote is this:
int main(){

srand(time(NULL));
int rannum;
int guess;
int max1=0,min2=0;
rannum = rand() % 99 + 1;

printf("Enter guess");
scanf("%d", &guess);

printf("%d", guess);

while (guess<99 && guess>0){
    if (rannum < guess){
        guess = max1;
        printf("%d is too high,0 and %d", max1, max1);
    }
    scanf("%d", &guess);

     if (guess > max1){

        printf("%d is out of range,enter between 0 and %d", guess, max1);
    }
     scanf("%d", &guess);
     if (guess < rannum){
        guess = min2;
        printf("%d is too low,guess between %d and %d", min2, max1, max1);
    }
     scanf("%d", &guess);
     if (guess == rannum){
         printf("You win");
     }
}

return 0;
}

It works somehow, but I would like some input on how well it's written.


texts: Truncate 160-bit output from SHA-1 to 64-bit uint64_t

texts:
I'd like to truncate 160-bit output from SHA-1 to receive a (weaker) 64-bit digest.

It has been a while since I did the type of low-level C pointer arithmetic in the but-last line. Could you please review it for me? It should return the last 64 bits of the the byte array in a uint64_t. (I guess conceptually I could just as well take the first 64 bits, which would make the code simpler but here we are.)

#import <CommonCrypto/CommonDigest.h>

- (uint64_t)digestFromString: (NSString *)s {
    NSData *input = [s dataUsingEncoding: NSUTF8StringEncoding];
    unsigned char output[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(input.bytes, (CC_LONG)input.length, output);
    uint64_t digest;
    NSAssert(CC_SHA1_DIGEST_LENGTH >= sizeof(uint64_t), nil);
    digest = *(uint64_t *)(output + CC_SHA1_DIGEST_LENGTH - sizeof(uint64_t));
    return digest;
}

How could this code be improved upon?

UPDATE Here is a second (alternative) version with an attempt at avoiding any alignment issues. (Its much more straigtforward to truncate to the first 64 bits in this case.) Actual digests will differ from the 1st version.

- (uint64_t)digestFromString: (NSString *)s {
    NSData *input = [s dataUsingEncoding: NSUTF8StringEncoding];
    union { // uint64_t-aligned
        uint64_t      uint64s[CC_SHA1_DIGEST_LENGTH / sizeof(uint64_t) + sizeof(uint64_t)];
        unsigned char bytes[CC_SHA1_DIGEST_LENGTH];
    } output;
    CC_SHA1(input.bytes, (CC_LONG)input.length, (unsigned char *)output.bytes);
    return output.uint64s[0];
}