texts:
The objective of this code is to create a command that move files and leaves links in their place. I'm just a beginner in shell scripting and it would be quite useful to hear your opinions on how to improve my code.

I already used https://www.shellcheck.net/ to check my code.

Questions

I change directory several times because I was creating broken links with relative paths. Is there a better way to do this?

Is there a better way to get the path of the files than to use cut with wc and using cd and pwd?

mvln.sh

#!/bin/bash
if [ "$#" -lt 2 ];then
    echo -e "mvln: Move file and leave a link in its place\\nUse: mvln [TARGET] [DIRECTORY]";
    exit 1;
fi

pathTo=$(cut -d ' ' -f "$#" <<< "$*");
if ! [ -d "$pathTo" ]; then
    echo "mvln: $pathTo is not a directory";
    exit 1;
fi

pathOriginal=$(pwd);
cd "$pathTo" || exit 1;
pathTo=$(pwd);
cd "$pathOriginal" || exit 1;

files=$(cut -d ' ' -f -$(("$#" - 1)) <<< "$*");

for i in $files;
do
    if [ "$i" -ef "$pathTo" ]; then
        echo "mvln: '$pathFrom' and '$pathTo' are the same file";
        continue;
    fi
    wordCount=$(tr -t '/' ' ' <<< "$i" | wc -w);
    pathFrom=$(cut -d '/' -f -$((wordCount - 1)) <<< "$i");
    file=$(cut -d '/' -f "$wordCount" <<< "$i");
    mv "$i" "$pathTo" || continue;
    cd "$pathFrom" || exit 1;
    ln -s "$pathTo/$file" ".";
    cd "$pathOriginal" || exit 1
done;
exit 0;

Creating test files

mkdir ~/Documentos ~/Scripts ~/Scripts/test ~/Scripts/test/ln
touch ~/arqHome.txt ~/Documentos/arqDoc.txt ~/Scripts/arqScripts.txt ~/Scripts/test/arq1.txt ~/Scripts/test/arq2.txt ~/Scripts/test/arq3.txt ~/Scripts/test/arq4.txt ~/Scripts/test/arq5.txt

Examples of how the command works:

Example1

Move all files from 1 place

bash mvln.sh ~/Scripts/test/arq* ~/Scripts/test/ln

Example2

Move files from several places

bash mvln.sh ~/arqHome.txt ~/Documentos/arqDoc.txt ~/Scripts/arqScripts.txt ~/Scripts/test/arq* ~/Scripts/test/ln


texts: Count all possible attendance records with length n, which will be regarded as rewardable

texts:
Given a positive integer n, return the number of all possible attendance records with length n, which will be regarded as rewardable. The answer may be very large, return it after \$\mod 10^9 + 7\$.

A student attendance record is a string that only contains the following three characters:

'A' : Absent.
'L' : Late.
'P' : Present.
A record is regarded as rewardable if it doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

Link to this question on leetcode is here

I was able to come up with a recursive approach but could not memoize it like in DP. I want to use the same approach but with memoization. Below is my submitted code.

public class Solution {

    public long count = 0;
    public int checkRecord(int n) {

        func(1,n,0,0);
        return (int)count % (1000000007) ;

    }

    public void func(int pos , int n , int alreadyAbsent , int countOfLate)
    {
        if(pos > n)
        {
            count++;
        }
        else
        {
            func(pos + 1, n , alreadyAbsent,0);
            if(countOfLate < 2)
            {
                func(pos + 1,n,alreadyAbsent,countOfLate + 1);
            }
            if(alreadyAbsent == 0)
            {
                func(pos + 1,n,1,0);
            }
        }
    }
}


texts: Converting Integer to dynamically allocated Char array, digit by digit using pointers

texts:
Problem: Write a function to convert Integer to String, using only
  pointers, without array indexes, string must be dynamically
  allocated.

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

// move each character in array one place to the right
// we need to make place for new character on the left
void moveArrayElementsRight(char *ptr, int len) {
    for (int j = len; j > 1; j--) {
        *(ptr + j - 1) = *(ptr + j - 2);
    }
}

void intToStr(int myNumber, char* myString){
    int i = 1;    //track size of allocated memory
    bool isMinus = false;

    if (myNumber < 0) {

        myNumber *= -1;    //without this (myNumber % 10) + '0' wont work
        isMinus = true;
    }

    if (myNumber == 0){    //special case for 0

        myString = (char*)realloc(myString, ((i + 1) * sizeof(char)));
        *myString = '0';
        *(myString + 1) = '\0';
    }

    while (myNumber != 0) {

        myString = (char*)realloc(myString, ((i + 1) * sizeof(char)));  //increse memory =+1 for next digit
        i++;
        moveArrayElementsRight(myString, i);
        *myString = (myNumber % 10) + '0'; //put digit to array
        myNumber /= 10;
    }

    if (isMinus) {

        myString = (char*)realloc(myString, ((i + 1) * sizeof(char)));  //increse memory =+1 for '-' sign
        i++;
        moveArrayElementsRight(myString, i);
        *myString = '-'; //put sign at the beginning
    }
}

int main() {

    int numberToConvert = -10;
    char *numberAsString = (char*)malloc(sizeof(char));  //create empty array, with place only for '\0'
    *numberAsString = '\0';    //mark the end of array

    intToStr(numberToConvert, numberAsString);

    printf("%s", numberAsString);

    return 0;
}


texts: Game of life C++ implementation memory access bug

texts:
I'm learning C++ so I thought I'd make game of life for practice and explore pointers, 1.5D arrays and stuff like that.

I have "finished" my implementation, but I have trouble with memory access. It seems like I'm stepping over the bounds somewhere and I simply can't figure out where. Everything looks fine to me.

Problem is most likely in the function called void World::follow that is checking surrounding cells if they are alive and than sets state for center cell for the next generation/tick depending of how many neighbors it has but I simply don't see it.

Here is my code:

source.cpp

#include "World.h"

int main() {
    World world = World(40, 20, 20);
    while (world.update())
        world.render();
}

Organism.h

#pragma once

class Organism {
private:
    bool cState, nState;
public:
    Organism(bool state);
    void perish();
    void revive();
    bool status();
    void update();
};

World.h

#pragma once
#include "Organism.h"

class World {
private:
    Organism** plain;
    int population;
    short width, height;
public:
    World(short width, short height, short chance);
    ~World();
    bool update();
    void render();
    void follow(short x, short y);
};

Organism.cpp

#include "Organism.h"

Organism::Organism(bool state) {
    this->cState = state;
}

void Organism::perish() {
    this->nState = false;
}

void Organism::revive() {
    this->nState = true;
}

bool Organism::status() {
    return this->cState;
}

void Organism::update() {
    this->cState = this->nState;
}

World.cpp

#include "World.h"

#include <time.h>
#include <stdlib.h>
#include <iostream>
#include <Windows.h>

using namespace std;

World::World(short width, short height, short chance) {
    this->population = 0;
    this->width = width; this->height = height;

    this->plain = new Organism*[width*height];

    bool state;
    srand(time(nullptr));
    for (int i = 0; i < (width*height); i++) {
        state = rand() % 100 < chance;
        this->plain[i] = new Organism(state);
    }

    for (short x = 0; x < this->width; x++)
        for (short y = 0; y < this->height; y++)
            this->follow(x, y);
}

bool World::update() {
    this->population = 0;

    for (int i = 0; i < (width*height); i++) {
        this->plain[i]->update();
        if (this->plain[i]->status())
            this->population++;
    }

    for (short x = 0; x < this->width; x++)
        for (short y = 0; y < this->height; y++)
            this->follow(x,y);

    return this->population > 0;
}

void World::follow(short x, short y) {
    bool alive;
    short pals = 0;
    Organism* current = this->plain[x*this->width + y];

    short sx = (x - 1 < 0) ? x : x - 1;
    short sy = (y - 1 < 0) ? y : y - 1;
    short ex = (x + 1 == this->width - 1) ? x : x + 1;
    short ey = (y + 1 == this->height - 1) ? y : y + 1;

    for (short row = sx; row < ex; row++) {
        for (short col = sy; col < ey; col++) {
            alive = this->plain[row*this->width + col]->status();
            if (row != x && col != y && alive) pals++;
        }
    }

    if (!current->status() && pals == 3)
        current->revive();
    else if (current->status() && pals != 2 && pals != 3)
        current->perish();
}

void World::render() {
    Sleep(500);
    system("cls");
    for (short x = 0; x < this->width; x++) {
        for (short y = 0; y < this->height; y++) {
            cout << (this->plain[x*this->width + y]->status()) ? " " : "x";
        }
        cout << endl;
    }
}

World::~World() {
    for (int i = this->width * this->height; i >= 0; i--)
        delete this->plain[i];
    delete[] this->plain;
}


texts:
I've created the following node module to define my model. Is this a reasonable approach?

Model.js:

var dynamoose = require('dynamoose');

var product = dynamoose.model('Product', { id: Number, name: String });
var giftCard = dynamoose.model('GiftCard', { id: Number, name: String });

exports.product = product;
exports.giftCard = giftCard;

index.js:

var m = require('model');
var coffeeMug = new m.product('1111','Coffee Mug')
console.log(coffeeMug);


texts: Which name should I choose for private abstract functionality with a public proxy?

texts:
I have an abstract class implementing some concrete functionality for its child classes:

abstract class Function {
  def eval: Double = some_concrete_functionality_which_calls_fEval
  def simplify: Funcion = more_concrete_calling_fSimplify

  protected def fEval: Double
  protected def fSimplify: Funcion
}

The child classes should implement fEval and fSimplify themselves, while eval and simplify act like a public proxy between them to provide common functionality before calling the actual implementation.

f stands for function but, although I feel fName is not very expressive, I can't think of any good alternatives (besides concreteEval which seems very bloated.)

Any suggestions? Should I stick to concreteEval? Maybe keep it like it is?


texts: Regex for matching expression that consists of single digit numbers and operators

texts:
I would like to create a regex that will validate that a string is an equation made up of a single digits and either the * or + operator and is no longer than 100 characters.  So these would be valid:

1+2*3*8+0
9
9*9

And these would not be valid:

1++1
12+1
2*25
1+
47
+
+1
11

I came up with the regex below to accomplish this:

^(\d{1}[\+\*]{1}){0,99}\d$

Which appears to work, but I'm curious if there is a cleaner way to accomplish this.  Any suggestions or is this about as clean as it gets?

It is saved here if you would like to play with it.


texts:
Problem: I need to let my web-app users create their own blade layouts. The content shall change based on what is in the database, hence their layouts should become dynamic in nature. With only the content parts changing and layout different as customized by the user.

Solution: Save the user's layout code into database column.

//Then In controller
//$templateInDatabase = content from database column, which contains user's custom layout code

$content = View::make('final',compact('data'));
$token = "<meta name='_token' content='" . csrf_token() ."'";
$scripts = View::make('final_scripts',compact('data'));

$view = str_replace_first("<%content%>", $content, $templateInDatabase);
$view = str_replace_first("<%token%>", $token, $view);
$view = str_replace_first("<%scripts%>", $scripts, $view);

return $view;

The user shall be made to include the three <%X%> tags in the template code.
Benefits are no server side code execution, hence added security. Cache problems minimize as the final and final_scripts blade templates can be cached. But the string replacements add extra effort.

How bad is this solution?


texts: Catch all checked exceptions and turn into unchecked exception

texts:
I am currently trying to learn Lambdas and following the book Java SE8 for the really Impatient and just finished Chapter 1 of it. This is the question, I am trying to get done with:

  Didn’t you always hate it that you had to deal with checked exceptions
  in a Runnable? Write a method uncheck that catches all checked
  exceptions and turns them into unchecked exceptions. For example,

new Thread(uncheck( () -> { System.out.println("Zzz"); Thread.sleep(1000); })).start(); // Look, no catch (InterruptedException)!

  Hint: Define an
  interface RunnableEx whose run method may throw any exceptions. Then
  implement public static Runnable uncheck(RunnableEx runner). Use a
  lambda expression inside the uncheck function. Why can’t you just use
  Callable<Void> instead of RunnableEx?

This is my solution:

@FunctionalInterface
public interface RunnableEx extends Runnable {
    @Override
    default void run () {
        try {
            doRun();
        } catch (Error | RuntimeException e) {
            throw e;
        } catch (Throwable throwable) {
            throw new IndexOutOfBoundsException("IOBE");
        }
    }

    void doRun ()
        throws Throwable;
}

and

public class Question6 {
    public static void main (String... args) {
        uncheck(() -> {
            System.out.println("Question6");
        });
    }

    public static Runnable uncheck (final RunnableEx runner) {
        final RunnableEx runnable = () -> {
            try {
                runner.doRun();
            } catch (Error | RuntimeException e) {
                throw e;
            } catch (Throwable ignored) {
                runner.doRun();
            }
        };

        return runnable;
    }

    // We can not use Callable<Void> because it throws Checked Exception.
}

I request two things:

How can this be improved, if it can be?
As per my understanding, this implementation seems to be correct, but is it really?


texts: Get icon from website, show and update icon

texts:
I was thinking the other day how could I get the icon from a website and make it show and update when it is updated on the site so I made this code:

URL url2 = null;
boolean updateIcon = true;
try {
    url2 = new URL("https://dl.dropboxusercontent.com/s/70rhm66myw8ay2v/Perception%20Logo.png");
} catch (MalformedURLException ex) {
    updateIcon = false;
    ex.printStackTrace();
}
if (updateIcon) {
    System.out.println("[Perception] Icon updated.");
    if (ComputerCheck.isWindows()) {
        Image bimg = Toolkit.getDefaultToolkit().getImage(url2);
        this.setIconImage(bimg);
    } else if (ComputerCheck.isMac()) {
        Application application = Application.getApplication();
        Image image = Toolkit.getDefaultToolkit().getImage(url2);
        application.setDockIconImage(image);
    }
}

And it works 100% fine but it makes the startup time a lot slower. I was wondering how could I optimize this.


texts: Getting a local file with file_get_contents

texts:
my url is like page.php?path=content/x/y/z/aaa.md. Is the following php code secure?

include "Parsedown.php";

function path_purifier($path) {
  if(substr($path, 0, 8) !== "content/")
    return null;
  if (strpos($path,'..') !== false)
    return null;
  return "./" . $path;
}

$parsedown = new Parsedown();
$path = $_GET['path'];
$path = path_purifier($path);
echo $parsedown->text(file_get_contents($path));


texts: Find specific promise in array that contains both resolved and rejected values

texts:
I basically want to find a specific promise in a given array of promises. The thing is that (I'm using bluebird promises, but the same hold true for anouther standard implementations):

it is impossible to use just Promise.some/Promise.any, because between resolved values I'm interested in resolved value of a special kind
it is impossible to use Promise.filter because array can have rejected values and it is completely OK.

Here's code I'm currently using. I'm OK with it, it works, but had I find anything more elegant it would be nice:

  var findPromise = function findPromise(promises, findFunc) {
    var rejected = [];
    Object.defineProperty(rejected, 'name', {
        enumerable: false,
        value: 'NOT_FOUND'
    });

    var step = function step(count, promises) {
        if (count < promises.length) {
            var promise = promises[count];
            return promise.then(function(data) {
               if (findFunc(data)) {
                  return Promise.resolve(data);
               } else {
                  return step(count + 1, promises);
               }
            }, function(reason) {
                rejected.push(reason);
                return step(count + 1, promises);
            });
        } else {
            return Promise.reject(rejected);
        }
    }

    return step(0, promises);
}


texts:
How can I increase speed performance of this Python 3 programming challenge?

  Find the shortest path from one point to another (last line)

  Example:

4 4
1 2
4 1
2 3
3 1
2 4

  Output:

2

  Explanation:

4--3
| /|
|/ |
1--2

  The shortest path: 2-1-4

import sys
from queue import Queue

def bfs(graph, start, end):
    global distance
    # path var for store current path
    path = ()
    Q = Queue()
    Q.put(start)
    # visited dict, store key - visited vertices, value - path from the start
    # query - to store current queue items
    while Q.empty() is False:
        # take last element from the queue
        u = Q.get()
        path = path + (u,)
        # set it to visited and add current path
        if u == end:
            return distance[end]
        # go trough its children
        for child in graph[u]:
            if distance[child] == 0:
                # add it to queue
                Q.put(child)
                distance[child] = distance[u] + 1
    else:
        return -1

if __name__ == '__main__':
    global distance
    input = sys.stdin.read()
    data = list(map(int, input.split()))
    n, m = data[0:2]
    data = data[2:]
    adj = [[] for _ in range(n)]
    distance = [0 for _ in range(n)]
    edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
    edges.sort()
    for (a, b) in edges:
        adj[a - 1].append(b - 1)
        adj[b - 1].append(a - 1)
    s, t = data[2 * m] - 1, data[2 * m + 1] - 1
    print(bfs(adj, s, t))

This code must build a graph adjacency list in format [[1][0,2][1], where list index is graph node index, and numbers are connected edges to it.

The input format is next:

3 2
1 2
2 3

where the first two numbers is the number of vertexes (3) and number of edges (2), and the next lines describe the connections through graph vertices.


texts: Finding the min and max of an array, using a pointer

texts:
Modify the maxmin.c program so that the max min function uses a
  pointer instead of an integer to keep track of the current position in
  the array.

  maxmin.c

/* Finds the largesy and smallest elements in an array */

#include <stdio.h>
#define N 10

void max_min(int a[], int n, int *max, int *min);
int: main (void)
 {
  int b[N], i, big, small;
  printf (''Enter %d numbers: ", N) ;

  for (1 = 0: i < N: i++)
   scanf ( "%d'', &b[i] ) ;

  max_min (b, N. &big , &small);
  printf (" Largest : %d\n " , big) ;
  printf (" Smallest: %d\n", small);
  return 0;

  void max_min(lnt a[] , int n, int *max, int *min)
{
int i;
*max = *min = a[O];

   for (i = 1; i > n; i++) {
  if ([a[i] > *max)
  *max - a[i];

  else if (a[i] < *min)
  *min - a (i] ;
 }
 }

The code I have written:

#include <stdio.h>
#define N 10

void max_min(int a[], int n, int *max, int *min);
int main(void)

{
int b[N], *i, big, small;

printf("Enter %d numbers\t:",N);
for(i=&b[0];i<&b[N];i++)
    scanf("%d",i);

max_min(b, N, &big, &small);

printf("\nlargest:\t%d",big);
printf("\nsmallest:\t%d",small);

return 0;
}

void max_min(int a[], int n, int *max, int *min)
{
int *i;
*max = *min = a[0];
for (i=&a[0]; i<&a[n]; i++)

{
    if(*i>*max)
    *max=*i;
    else if (*i<*min)
    *min=*i;
}}


texts:
I've got a service that loads data from a databasr and it performs almost the same operations in all methods.
   private async Task GetProvenances()
    {
        try
        {
            var result = await commonRepository.GetProvenances();
            if (result != null)
            {
                provenanceContainerService.Provenances = result;
                LogTo.Information(InitCacheMessages.STR_GET_PROVENANCES, result.Count);
            }
            else
            {
                LogTo.Warning(InitCacheMessages.STR_GET_PROVENANCES_FAILED);
            }
        }
        catch (Exception ex)
        {
            exceptionService.HandleException(ex);
        }
    }

    private async Task GetPkInstrumentMarkets()
    {
        try
        {
            var result = await commonRepository.GetPkInstrumentMarkets();
            if (result != null)
            {
                pkInstrumentMarketContainerService.PkInstrumentMarkets = result;
                LogTo.Information(InitCacheMessages.STR_GET_PK_INSTRUMENT_MARKETS, result.Count);
            }
            else
            {
                LogTo.Warning(InitCacheMessages.STR_GET_PK_INSTRUMENT_MARKETS_FAILED);
            }
        }
        catch (Exception ex)
        {
            exceptionService.HandleException(ex);
        }
    }

    private async Task GetPkMotivations()
    {
        try
        {
            var result = await commonRepository.GetPkMotivations();
            if (result != null)
            {
                pkMotivationsContainerService.PkMotivations = result;
                LogTo.Information(InitCacheMessages.STR_GET_PK_MOTIVATIONS, result.Count);
            }
            else
            {
                LogTo.Warning(InitCacheMessages.STR_GET_PK_MOTIVATIONS_FAILED);
            }
        }
        catch (Exception ex)
        {
            exceptionService.HandleException(ex);
        }
    }

How can I refactor this so I don't have to repeat the same code for about 30 methods?
UPDATE 1
Hello,
I've done this way this night
  protected async Task PerformInitInternal(string okMessage, string koMessage, Func<Task<IList<T>>> function)
    {
        try
        {
            var result = await function();
            if (result != null)
            {
                Items = result;
                LogTo.Information(okMessage, result.Count);
            }
            else
            {
                LogTo.Warning(koMessage);
            }

            isInitialized = true;

        }
        catch (Exception ex)
        {
            ExceptionService.HandleException(ex);
        }
    }

And I call it this way
  public override Task Init()
    {
        return PerformInitInternal(InitCacheMessages.STR_GET_COUNTERPARTS,
            InitCacheMessages.STR_GET_COUNTERPARTS_FAILED, () => CommonRepository.GetCrossSplitAsync());
    }

Can this be ok?


texts: Lightweight flexible observer framework using weak references

texts:
I found a need for a simple, generic publish-subscribe framework for my Java application.  I looked over a few implementations on Code Review and I think mine avoids most of the pitfalls.  Single-class implementation using a Consumer to receive messages and an Object for indexing.

import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.function.Consumer;

public class Broadcaster<M> {
    private final Map<Object,Consumer<M>> listeners = Collections.synchronizedMap(new WeakHashMap<>());

    public void post(M message){
        listeners.values().forEach(c->c.accept(message));
    }

    public void listen(Object listener, Consumer<M> consumer){
        listeners.put(listener, consumer);
    }

    public void ignore(Object listener){
        listeners.remove(listener);
    }
}

Here's a demo of (most of) the functionality.  Hopefully I wrote enough to give a general idea of how it works.

import java.util.function.Consumer;

public class NeedsToBroadcast{
    private Broadcaster<Thing> thingBroadcaster = new Broadcaster<>();

    public void listen(Object listener, Consumer<Thing> consumer){
        thingBroadcaster.listen(listener, consumer);
    }

    public void ignore(Object listener){
        thingBroadcaster.ignore(listener);
    }

    public void doStuff(int i){
        do{
            Thing thing = StuffProcessor.process(i);
            if(thing != null){
                // Multiple objects care about the Things we get
                i = thing.getNumber();
                thingBroadcaster.post(thing);
            }else{
                i = 0;
            }
        }while(i>1);
    }

    public static void main(String... args){
        NeedsToBroadcast ntb = new NeedsToBroadcast();
        StandingLog standingLog = new StandingLog(ntb);

        ntb.doStuff(20);

        System.out.println(standingLog.toString());
    }

    public static class Thing{
        private final int number;
        private final String text;

        private Thing(int number, String text){
            this.number = number;
            this.text = text;
        }

        public int getNumber(){
            return number;
        }

        public String getText(){
            return text;
        }
    }

    public static class StandingLog{
        private final StringBuffer buffer = new StringBuffer();

        public StandingLog(NeedsToBroadcast ntb){
            // As long as this object has a reference, it will receive updates
            ntb.listen(this, (thing)->{
                buffer.append(thing.getNumber()).append(":").append(thing.getText()).append('\n');
            });
        }

        @Override
        public String toString(){
            return buffer.toString();
        }
    }
}

Update

I'm not trying to make something competitive with, say, 0MQ.  I'm trying to create a drop-in, single-class replacement for something like Java's Observable and Observer, with the added benefits of thread safety, cleanup for GC-elegible objects, and generic typing.

The original title of this post used "publish-subscribe".  I changed it to "observer" since, while I feel they are similar enough for this class, the distinction seems to have given people the wrong idea.

It seems the demo I posted doesn't do a fantastic job of demonstrating the functionality.  I'll see if I can rework something for clarity's sake.


texts:
Based off my Java Petals Around the Rose, I thought it would be good practice to write something again in a different language.

Because the language is Python, I named it "Pythons Around the Rose", and everywhere in my code, the word "rose" would be replaced with "python".

Also, "Potentate" is replaced with "Pytentate".

Code:

import random

def display_help():
    example = get_dice_result()
    print("The name of the game is Pythons Around the Rose.",
          "The name is important. I will roll five dice,",
          "and I will tell you how many pythons there are.",
          "\nFor example:", sep = "\n")
    print_dice(example)
    print("Will result in ", get_answer(example), ".", sep = "")
    print("\nIf you answer correctly 8 times in a row, you",
          "will be declared a \"Pytentate of the Rose\".", sep = "\n")

def play():
    streak = 0
    while True:
        dice = get_dice_result()
        if play_once(dice):
            streak += 1
        else:
            streak = 0
        if streak == 8:
            print('You are now declared a "Pytentate of the Rose"!')
            break;
    print("Thank you for playing!")

def get_dice_result():
    result = [get_dice_roll(), get_dice_roll(),
              get_dice_roll(), get_dice_roll(), get_dice_roll()]
    return result

def get_dice_roll():
    return random.randrange(6) + 1

def play_once(results):
    print("How many pythons here?")
    print_dice(results)
    guess = get_guess()
    answer = get_answer(results)
    if guess == answer:
        print("Correct!")
        return True
    print("Incorrect. The answer is ", answer, ".", sep = "")
    return False

def get_guess():
    guess = 0
    valid = False
    while not valid:
        try:
            guess = int(input("> "))
            valid = True
        except:
            print("\nOops! That is not a number. Try again: ")
    return guess

def get_answer(dice):
    answer = 0
    for i in dice:
        if i == 3:
            answer += 2
        elif i == 5:
            answer += 4
    return answer;

def print_dice(dice):
    rows = ["|", "|", "|"]
    for i in dice:
        if i == 1:
            rows[0] += "       |"
            rows[1] += "   .   |"
            rows[2] += "       |"
        elif i == 2:
            rows[0] += " .     |"
            rows[1] += "       |"
            rows[2] += "     . |"
        elif i == 3:
            rows[0] += " .     |"
            rows[1] += "   .   |"
            rows[2] += "     . |"
        elif i == 4:
            rows[0] += " .   . |"
            rows[1] += "       |"
            rows[2] += " .   . |"
        elif i == 5:
            rows[0] += " .   . |"
            rows[1] += "   .   |"
            rows[2] += " .   . |"
        elif i == 6:
            rows[0] += " .   . |"
            rows[1] += " .   . |"
            rows[2] += " .   . |"
    print(rows[0], rows[1], rows[2], sep = "\n")

def main():
    display_help()
    play()

if __name__ == '__main__':
    main()

I wrote it to be based of standard conventions as close as possible. Because I'm a Java person, I might have added a ; somewhere in my code, or perhaps accidentally forgot to follow conventions somewhere.


texts: This spec creates very few connects, is that plausible?

texts:
I'm attempting exercise A.2.1 from the book http://alloytools.org/book.html. Having got this far, I find that when stepping through instances I only ever get 2 connects links, no matter how many requests links, when using the MiniSat solver. When using MiniSat plus Unsat core, I sometimes get more connects, but not many requests. Obviously, these all satisfy the model, but it feels wrong to me. Am I over-thinking this?
module exercises/telephone

sig Phone {
    , requests : set Phone
    , connects: lone Phone
}

fact minimum_system {
    some requests
    some connects
}

fact dont_call_yourself {
  no p: Phone | p.connects = p
  no p: Phone | p in p.requests
}

fact connect_from_a_request {
    no (connects - requests)
}

fact only_receive_once {
    all p: Phone.connects | one ~connects[p]
}

fact receiver_or_caller_only {
    no (Phone.connects & Phone.~connects)
}

pred show {}

run show for exactly 12 Phone


texts: Binary tree level order traversal algoritm

texts:
I am trying to solve this Binary tree lever order traversal:

Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:
[
  [15,7]
  [9,20],
  [3],
]

How can I improve the speed of the code below? It always gives me a time exceed error.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();
        Stack<Integer> stack = new Stack<Integer>();
        ArrayList<Integer> node = new ArrayList<Integer>();

        this.iterateAll(root, stack);

        while (!stack.empty()) {
            if (stack.peek() != null) {
                node.add(stack.pop());
                if (!stack.isEmpty()) {
                    if (stack.peek() != null) {
                        tree.add(node);
                        node = new ArrayList<Integer>();
                    } else {
                        stack.pop();
                        if (!stack.isEmpty()) {
                            if (stack.peek() != null) {
                                tree.add(node);
                                node = new ArrayList<Integer>();
                            }
                        }
                    }
                } else {
                    tree.add(node);
                }
            } else {
                stack.pop();
            }
        }
        return tree;
    }

        public Stack<Integer> iterateAll(TreeNode root, Stack<Integer> stack) {
        if (root != null) {
            stack.push(root.val);
            if (root.right != null) {
                iterateAll(root.right, stack);
            } else {
                stack.push(null);
            }

            if (root.left != null) {
                iterateAll(root.left, stack);
            } else {
                stack.push(null);
            }
        }
        return stack;
    }
}


texts: Exposing configuration elements to program

texts:
I have a config file stored in a java properties file:

output_path=/some/path/somewhere
num_threads=42
# ad infinitum

I have an singleton enum which controls the building of the config:

public enum ConfigFactory {
    INSTANCE;

    public static final String OUTPUT_PATH = "output_path";
    public static final String NUM_THREADS = "num_threads";

    private Map<String, ConfigParameter> mSettings = new HashMap<String, ConfigParameter>();

    public void build(String path) {
        InputStream inputStream = getClass().getResourceAsStream(path);
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            inputStream.close();
            for(Map.Entry<Object, Object> entry : properties.entrySet()) {
            // for brevity I only look for ints
            if(StringUtils.isNumeric(entry.getValue().toString())) {
                    mSettings.put(entry.getKey().toString(), new ConfigParameter<Integer>((Integer) entry.getValue()));
                } else {
                    mSettings.put(entry.getKey().toString(), new ConfigParameter<String>(entry.getValue().toString()));
                }
            }
        } catch(IOException e) {
            // intentionally left empty
        }
    }

    public ConfigParameter getValue(String s) {
        return mSettings.get(s);
    }

    private class ConfigParameter<T> {
        private T mConfigParameter;

        public ConfigParameter(T var) {
            mConfigParameter = var;
        }

        /**
         * Set the value of the parameter
         * @param param Generic object to be stored
         */
        public void set(T param) {
            mConfigParameter = param;
        }

        /**
         * Retrieve the object
         * @return Generic object stored
         */
        public T get() {
            return mConfigParameter;
        }
    }
}

Elsewhere in my program, when I want to obtain a config element, I reference it this way:

int numberOfThreads = ConfigFactory.INSTANCE.getValue(ConfigFactory.NUM_THREADS).get();

This method can be seen as untenable as I need to have static string literals for each config value defined in the properties file.  Is there a better way to expose these config values to the program and have only one place to change them if the properties file changes?  Is this considered best practices for exposing properties values to the program?


texts:
I've been trying to create a calculator to find mass using any and all known equations.  The program will also return the steps used to find mass so the user can 'check their work' on physics assignments.

My biggest problem so far (and was solved by much copy-pasta) is the equations themselves. I'd like to be able to create an equation variable that contains other variables inside itself, if possible, I want the variable to state:

var.mass = var.force / var.acceleration && var.energy / var.c^2 && var.density / var.volume

How, if possible, would I go about creating this variable? I could certainly define a different variable for each equation, but that would be extremely time-consuming and I'm sure Python has something that could help! I haven't tried an array, and would prefer not to as I have very little experience with them.  However, if someone could give me an idea, even just the command name I would be very appreciative!

Feel free to use the code however and with whatever you want.

#this script is for solving for mass
#Define variables
g = 9.8
c = 3.00 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10
c2 = c * c
E = mass * c * c
#Ask if the user wants to see how problem was solved
show_work = input('Show work? ')
#Asks for variable input
force_val = float(input('Force? (In Newtons) '))
mass_val = float(input('Mass? (In kg) '))
acceleration_val = float(input('acceleration? (In m/s^2) '))
p_val = float(input('density? (In Kg/m^3) '))
volume_val = float(input('Volume? (m^3) '))
weight_val = float(input('Weight? (Normal Force) '))
energy_val = float(input('Energy? '))
kinetic_val = float(input('Kinetic Energy? '))
velocity_val = float(input('Velocity? (In m/s) '))

#Solve for mass based on known values
#show work off

if show_work == 'no':
    if mass_val > 0.00:
        print(mass_val)
    elif force_val > 0:
        if acceleration_val > 0:
            mass_val = force_val / acceleration_val
            print(mass_val)
    elif p_val > 0:
        if volume_val > 0:
            mass_val = p_val / volume_val
            print(mass_val)
    elif weight_val > 0:
        mass_val = weight_val / g
        print(mass_val)
    elif energy_val > 0:
        mass_val = energy_val / c2
        print(mass_val)
    elif kinetic_val > 0:
        if velocity_val > 0:
            mass_val = 1/2 * kinetic_val / velocity_val / velocity_val
            print(mass_val)

#show work on

if show_work == 'yes':
    if mass_val > 0.00:
        print(mass_val)
    elif force_val > 0:
        if acceleration_val > 0:
            mass_val = force_val / acceleration_val
            print('Force = Mass * Acceleration ')
            print('Mass = Force / Acceleration ')
            print('Mass =', force_val, '/', acceleration_val)
            print('Mass =', mass_val)
    elif p_val > 0:
        if volume_val > 0:
            mass_val = p_val / volume_val
            print('Mass = Density / Volume ')
            print('Mass =', p_val, '/', volume_val)
            print('Mass =', mass_val)
    elif weight_val > 0:
        mass_val = weight_val / g
        print('Mass = Weight / Gravity ')
        print('Mass =', weight_val, '/', g)
        print('Mass =', mass_val)
    elif energy_val > 0:
        mass_val = energy_val / c2

        print('E=mc^2')
        print('m=E/c^2')
        print('Mass =', energy_val, '/', 'c^2')
        print('Mass =', mass_val)
    elif kinetic_val > 0:
        if velocity_val > 0:
            mass_val = 2 * kinetic_val / velocity_val / velocity_val
            print('KE = 1/2mv^2')
            print('Mass = 2(KE/v^2)')
            print('Mass =', kinetic_val, '/', velocity_val, '^2')
            print('Mass =', mass_val)
            print(mass_val)


texts: Critique Request: Reversing a singly linked list

texts:
I find the tail in the first while loop and store it in the tailEnd node.
I update the tail to the previous node and change the tail.next to point to the previous node.
Once head.next.next == head, the reversing is finished.

package LinkedLists;

class Reverse {

    public static LinkedList reverse(LinkedList Node) {
        LinkedList head = Node;

        while (Node.next != null) {
            Node = Node.next;
        }

        LinkedList tail = Node;
        LinkedList tailEnd = Node;

        Node = head;

        while (Node.next != null) {
            if (head.next.next == head) {
                head.next = null;
                return tailEnd;
            }

            while (Node.next != tail) {
                Node = Node.next;
            }
            tail.next = Node;
            tail = Node;
            Node = head;
        }

        return tailEnd;
    }

    public static void main(String[] args) {
        LinkedList HeadNode = new LinkedList(1);
        LinkedList Node1 = new LinkedList(2);
        LinkedList Node2 = new LinkedList(3);
        LinkedList Node3 = new LinkedList(4);
        LinkedList TailNode = new LinkedList(5);
        HeadNode.next = Node1;
        Node1.next = Node2;
        Node2.next = Node3;
        Node3.next = TailNode;
        TailNode.next = null;
        LinkedList revHead = Reverse.reverse(HeadNode);
        while (revHead != null) {
        System.out.println(revHead.data);
        revHead = revHead.next;
        }
    }
}


texts: Checking for duplicate values in database with Python

texts:
I'm working on a Python application where I read and extract data from an HTML file. The data is stored in a list, and the number of items in a list is, on average, 50,000+.
The items from the list are added to a database. I cannot allow duplicate datetime values in one of the columns, and so, I have to check if a specific value exists in the database already, and if it does, keep incrementing it until there's no duplicates.

Here's what my code looks like (I'm using SQLAlchemy):

import re
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
from models import db, Notes

def import_file(filename, user):
    file = open(filename, 'r')
    html = file.read()
    file.close()
    soup = BeautifulSoup(html, "lxml")
    for link in soup.find_all('a'):
        validurl = re.compile(
            r'^(?:[a-z0-9\.\-]*)://'
            r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}(?<!-)\.?)|'
            r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|'
            r'\[?[A-F0-9]*:[A-F0-9:]+\]?)'
            r'(?::\d+)?'
            r'(?:/?|[/?]\S+)$', re.IGNORECASE)
        url = validurl.match(link.get('href'))
        if url:
                url = link.get('href')
                if len(url) <= 2000:
                    if link.get('add_date'):
                        date = datetime.utcfromtimestamp(int(link.get('add_date')))
                        while Notes.query.filter_by(user=user, added_on=date).first():
                            date += timedelta(0, 1)
                        title = link.string
                        import_notes = Notes()
                        import_notes.main_url = url
                        import_notes.title = title
                        import_notes.user = user
                        import_notes.added_on = date
                        db.session.add(import_notes)
                        db.session.commit()

However, this code runs very slowly. I calculated how long it was taking per insert, and it came out at exactly 13 seconds per insert. I ran a profiler, and the filter_by query was taking the majority of the time. I figured it was because the script had to run a query so many times per item, and so I changed my code to use a static list instead:

import re
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
from models import db, Notes

def import_file(filename, user):
    file = open(filename, 'r')
    html = file.read()
    file.close()
    soup = BeautifulSoup(html, "lxml")
    for link in soup.find_all('a'):
        validurl = re.compile(
            r'^(?:[a-z0-9\.\-]*)://'
            r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}(?<!-)\.?)|'
            r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|'
            r'\[?[A-F0-9]*:[A-F0-9:]+\]?)'
            r'(?::\d+)?'
            r'(?:/?|[/?]\S+)$', re.IGNORECASE)
        url = validurl.match(link.get('href'))
        if url:
                url = link.get('href')
                if len(url) <= 2000:
                    if link.get('add_date'):
                        date = datetime.utcfromtimestamp(int(link.get('add_date')))
                        while Notes.query.filter_by(user=user, added_on=date).first():
                            date += timedelta(0, 1)
                        title = link.string
                        import_notes = Notes()
                        import_notes.main_url = url
                        import_notes.title = title
                        import_notes.user = user
                        import_notes.added_on = date
                        db.session.add(import_notes)
                        db.session.commit()

I thought this might make the code run faster, but there was little to no change in runtime. For comparison, if I remove the duplicate check, I get ~300 inserts per second.

I cannot let duplicate datetime values into the database. What can I do to make my code faster?


texts: simple "if"-less algebraic computation using CLOS

texts:
For educational purposes I've tried to implement a simple algebraic OOP example using CLOS. The functionality is as far as I can say as it is supposed to be. The intended approach was to implement a simple example of ideomatic OOP polymorphism. For a greater learning experience I've wanted to show the code to get suggestions, critic and so on.

;; main node class, most general
(defclass node ()
  ;; abstract class for nodes
  ((value :initarg :value :reader value)))

(defgeneric evaluate (node)
  (:documentation "the standard evaluation"))

;; node containing an operation, more specific
(defclass op-node (node)
  ;; abstract class for a node containing an operation
  ((left-node  :initform nil :initarg :left-node  :reader left-node)
   (right-node :initform nil :initarg :right-node :reader right-node)))

(defmethod evaluate ((node op-node))
  (apply (value node)
         (list (evaluate (left-node node))
               (evaluate (right-node node)))))

;; concrete nodes
(defclass add-node (op-node)
  ;; class for addition
  ((value :initform #'+ :reader value)))

(defclass minus-node (op-node)
  ;; class for subtraction
  ((value :initform #'- :reader value)))

(defclass multi-node (op-node)
  ;; class for multiplication
  ((value :initform #'* :reader value)))

(defclass value-node (node)
  ;; class for a node containing a numerical value
  ((value :initarg :value :reader value)))

(defmethod evaluate (value-node)
  (value value-node))

;; 1 + 3
(setf *simple-add* (make-instance 'add-node
                                  :left-node  (make-instance 'value-node :value 1)
                                  :right-node (make-instance 'value-node :value 3)))

;; 1 * 10
(setf *simple-multi* (make-instance 'multi-node
                                    :left-node  (make-instance 'value-node :value 1)
                                    :right-node (make-instance 'value-node :value 10)))

;; (1 + 3) + (1 * 10)
(setf *advanced-add* (make-instance 'add-node
                                    :left-node *simple-add*
                                    :right-node *simple-multi*))

(evaluate *simple-add*)   ;; => 4
(evaluate *simple-multi*  ;; => 10
(evaluate *advanced-add*) ;; => 14


texts:
Due to the fact that nobody's ever posted this before (sarcasm) I've made a brainfuck interpreter in java. The interpreter fits in a single method, and is designed to be readable, fast, and concise, so please review on those things. I have tested it to confirm that it works.

/**
 * Interpret program as a brainfuck program with the given standard input
 * and output.
 *
 * @throws IOException
 *             if thrown by stdin or stdout
 */
public static void brainfuck(String program, OutputStream stdout, InputStream stdin) throws IOException {
    int[] commands = program.chars().filter(c -> "><+-./[]".indexOf(c) != -1).toArray();
    int commandPointer = 0;
    int[] memory = new int[30_000];
    int memoryPointer = 0;
    while (commandPointer < commands.length) {
        switch (commands[commandPointer]) {
        case '>':
            memoryPointer++;
            if (memoryPointer >= memory.length)
                memoryPointer = 0;
            break;
        case '<':
            memoryPointer--;
            if (memoryPointer < 0)
                memoryPointer = memory.length - 1;
            break;
        case '+':
            memory[memoryPointer]++;
            if (memory[memoryPointer] > 255)
                memory[memoryPointer] = 0;
            break;
        case '-':
            memory[memoryPointer]--;
            if (memory[memoryPointer] < 0)
                memory[memoryPointer] = 255;
            break;
        case '.':
            stdout.write(memory[memoryPointer]);
            break;
        case ',':
            memory[memoryPointer] = stdin.read();
            memory[memoryPointer] %= 256;
            break;
        case '[':
            if (memory[memoryPointer] == 0) {
                int depth = 1;
                while (depth > 0) {
                    commandPointer++;
                    if (commands[commandPointer] == '[')
                        depth++;
                    else if (commands[commandPointer] == ']')
                        depth--;
                }
            }
            break;
        case ']':
            if (memory[memoryPointer] != 0) {
                int depth = 1;
                while (depth > 0) {
                    commandPointer--;
                    if (commands[commandPointer] == ']')
                        depth++;
                    else if (commands[commandPointer] == '[')
                        depth--;
                }
            }
            break;
        }
        commandPointer++;
    }
}


texts: Can this FindString function be optimized further, in terms of speed?

texts:
int FindStr(char* str, int strsize, char* fstr, int from)
{
    for(int i=from, j=0; i<strsize; i++)
    {
        if(str[i]==fstr[j])
            j++;
        else
            {i-=j; j=0;}

        if(fstr[j]=='\0')
            return i-j+1;
    }

    return -1;
}

The function searches for a string fstr in str and returns its index in str if found, otherwise, it will return -1.  It's also possible to specify where to start searching in the string.

My question is, can I optimize this function further? Also, do you see any potential problems in this function?


texts:
The following regex is meant to improve stringmatching by sanitizing the user -defined commandPrefix and checking for whitespace and line-endings after the specified text. command will generally be a single word, hence not escaped.

var prefix = commandPrefix.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
return text.test("/^" + prefix + command + "(?=\s|$)/");

Can this be improved for code readability? And am I missing any regex special characters in the sanitation?


texts: Mapping from string "aa=bb" to Dictionary

texts:
I am converting a input like :

aa=bb
Fruit1=Potato
Fruite2=Banana

Into a Dictionary, using this code.

string tmp = "\r\naa=bb\r\nFruit1=Potato\r\nFruite2=Banana";
Dictionary<string, string> tempValueList = new Dictionary<string, string>();

var lines = tmp.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
    var keyValue = line.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
    tempValueList.Add(keyValue[0],keyValue[1]);
}

tempIniObject.Key = key;
tempIniObject.ValueList = tempValueList;

This is simple, but I believe there is a mutch classier way to do it.


texts: Class for returning a different value every so often

texts:
I have a class that I'm trying to determine a good name for. I don't know if this concept comes up a lot in programming or not, but I'm wondering if I can get some suggestions for a good name for the class.
Basically, this is how the class functions:

The first time its Get() method is called, it returns value A.
Every subsequent time, it returns value B.
If enough time has passed (provided), return value A one time, then revert back to sending 'B'. Repeat ad finitum.

Is there any name for something that functions like this? It's somewhat like memoization, and kind of like caching, but not quite.
The application of this construct is so described: Every so often I want a method to load complex data from Active Directory to load into our database before returning the results from the table. This ensures that we have recent data in our database. However, the time to execute this is high, and 99% of the time nothing has changed. So I want to limit the checking for changes to long timespans in my web app. So, using this construct I can say "only do the long version every X hours, and once it's been done, don't do it again for X more hours."
Implementation
The ICurrentDateTimeProvider simply has a Now property so it can be faked for unit tests.
public interface ICurrentDateTimeProvider
{
    DateTime Now { get; }
}

public class CurrentDateTimeProvider : ICurrentDateTimeProvider
{
    public DateTime Now { get { return DateTime.Now; } }
}

public class ReturnDifferentValueEverySoOften<T>
{
    public ReturnDifferentValueEverySoOften(T firstAndSometimes, T most, TimeSpan flipTime = default(TimeSpan), ICurrentDateTimeProvider provider = null)
    {
        FirstAndSometimes = firstAndSometimes;
        MostOfTheTime = most;
        if (flipTime == default(TimeSpan))
            flipTime = TimeSpan.FromHours(6);
        FlipTime = flipTime;
        if (provider == null)
            provider = new CurrentDateTimeProvider();
        DateTimeProvider = provider;
    }

    public void SetTimeProvider(ICurrentDateTimeProvider provider)
    {
        DateTimeProvider = provider;
    }

    public T FirstAndSometimes;
    public T MostOfTheTime;

    ICurrentDateTimeProvider DateTimeProvider { get; set; }
    TimeSpan FlipTime;
    DateTime LastFlip { get; set; }
    DateTime NextFlip { get { return LastFlip.Add(FlipTime); } }
    bool ever = false;

    public T Get()
    {
        var now = DateTimeProvider.Now;
        if (!ever)
        {
            ever = true;
            LastFlip = now;
            return FirstAndSometimes;
        }
        if (NextFlip < now)
        {
            LastFlip = now.Add(FlipTime);
            return FirstAndSometimes;
        }
        return MostOfTheTime;
    }
}

Unit Test
Below is a unit test I wrote to ensure that it functions properly:
[Fact]
public void CanFlipBetweenValues()
{
    var timeToWait = TimeSpan.FromMilliseconds(10);

    var currentTime = DateTime.Now;
    var timeProvider = new Mock<ICurrentDateTimeProvider>();
    timeProvider.SetupGet(x => x.Now).Returns(currentTime);
    var cacher = new ReturnDifferentValueEverySoOften<bool>(false, true, timeToWait);
    cacher.SetTimeProvider(timeProvider.Object);

    Assert.False(cacher.Get());
    Assert.True(cacher.Get());
    Assert.True(cacher.Get());
    Assert.True(cacher.Get());
    Assert.True(cacher.Get());

    //add some arbitrary time > timeToWait
    var newTime = currentTime.Add(timeToWait).Add(new TimeSpan(0, 0, 1));
    var newTimeProvider = new Mock<ICurrentDateTimeProvider>();
    newTimeProvider.SetupGet(x => x.Now).Returns(newTime);
    cacher.SetTimeProvider(newTimeProvider.Object);

    Assert.False(cacher.Get());
    Assert.True(cacher.Get());
    Assert.True(cacher.Get());
    Assert.True(cacher.Get());
    Assert.True(cacher.Get());
}

Again, I'm mostly looking to see if there exists a better name for something like this, but I'm open to other code review suggestions as well.


texts: Largest Prime factor (Project Euler in Rust)

texts:
I've been working on my Rust a bit and want to know how idiomatic my rust code is for the following Project Euler problem:
What is the largest prime factor of the number 600851475143 ?
I'm not looking for ways to improve efficiency or how to improve the strategy, but purely what I can improve with my Rust technique. There's two files: src/prime/sieve.rs which has a function for generating a vector of prime numbers, and src/p003.rs which is where the problem is solved.
// src/prime/sieve.rs

pub fn sieve(ceil: usize) -> Vec<usize> {
    let mut is_prime = vec![true; ceil + 1];
    is_prime[0] = false;
    if ceil >= 1 {
        is_prime[1] = false
    }

    for num in 2..ceil + 1 {
        if is_prime[num] {
            let mut factor = num * num;
            while factor <= ceil {
                is_prime[factor] = false;
                factor += num;
            }
        }
    }

    is_prime
        .iter()
        .enumerate()
        .filter_map(|(p, &is_p)| if is_p { Some(p) } else { None })
        .collect()
}

// src/prime/mod.rs

pub mod sieve;

// src/p003.rs

// https://projecteuler.net/problem=3
mod prime;
use prime::sieve::sieve;

fn biggest_prime_factor(n: usize) -> usize {
    for p in sieve((600851475143_f32.sqrt()) as usize).iter().rev() {
        if n % *p == 0 {
            return *p;
        }
    }
    return 0;
}

fn main() {
    println!("{}", biggest_prime_factor(600851475143));
}


texts: Fetching a post from the database based on a query parameter

texts:
I get an id via Get request to fetch an object from the database.

I have used mysqli prepared statements to avoid any security problems. As I am new to these stuff I would like a confirmation that implemented the logic correctly and safe.

User goes to

website.com/post.php?post=130

In post.php i do the following:

Check if user sent a value in "post" parameter, otherwise redirect to the start page:

if(strlen($_GET["post"]) == 0){
    header("Location: index.php");
    exit();
}

then i use the paramter to fetch the object from the database:

$requestedID = $_GET["post"];
if(is_numeric($requestedID)){
  if($stmt = $mysqli->prepare("SELECT * FROM posts WHERE id =?")) {
     $stmt->bind_param('s', $requestedID);
     $stmt->execute();
     $result = $stmt->get_result();

     if($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        // logic for the content
     }else{
        header("Location: index.php");
        exit();
     }

   } else {
     header("Location: index.php");
     exit();
   }
 }else {
    header("Location: index.php");
    exit();
 }

Is my mysqli code secure?  Is my handling of GET parameter secure enough? Do you see anything that concerns you?


texts: Using python to estimate the range of unstructured data

texts:
I have unstructured input-output data, f=f(x). I want to estimate the range of f as a function of x, given limited sampled. So, I tried to discretize the data use small bins in x to estimate the variance of f associated with that bin. After a lot of work, I cobbled together a working code. But, I'm sure there must be a better way. My results are very sensitive to the bin size. Please review my approach and let me know how it can be improved.

from scipy.stats import binned_statistic
import matplotlib.pyplot as plt
import numpy as np

# Choose the number of bins
NBINS = 100

# define custom function for findin range
def myrangefunciton(arrA):
    return(np.max(arrA) - np.min(arrA))

# set seed for reproducability, there is nothing special about this seed
np.random.seed(1)

# generate sample data
x = np.random.normal(3, 1, 1000)
f = np.random.normal(0, np.max([x, np.zeros(x.size)], 0))

# compute ranges of f across x
stats, binEdges, binNum = binned_statistic(x, f,
                                           statistic=myrangefunciton, bins=100)

# scatter data
plt.scatter(x, f, s=0.5, label='Observed f(x) Data', c='k')

# transform the bin edges to centered x values
rangeX = binEdges[:-1] + (binEdges[1] - binEdges[0]) / 2.

# plot ranges to envelop the mean, which is 0.
plt.plot(rangeX, stats / 2, label='Estimated Range', c='blue')
plt.plot(rangeX, -1 * stats / 2, c='blue')

# complete summary plot
plt.title("%i bins" % NBINS)
plt.legend(prop={'size': 4})
plt.xlabel('x')
plt.savefig('rangeEx')
plt.clf()


texts: Adding rows to LinearLayouts which serve as lists

texts:
I have a fragment with a ScrollView and, inside of it, I need maybe 5 or 6 lists. To make things simpler, let's say there are three lists - list of names, list of places and list of events.

The problem is, I can't use lists inside of ScrollViews so I need to use LinearLayouts and do the adding to the list thing by myself. This causes me all sorts of problems.

I'm using index variables to keep track of where in my layout to put the new row when the user clicks "Add".

int currIndNames;
int currIndPlaces;
int currIndEvents;

Now this is my onCreate function:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null){
        names = savedInstanceState.getStringArrayList("names");
        places = savedInstanceState.getStringArrayList("places");
        events = savedInstanceState.getStringArrayList("events");
    } else {
        if (names == null){
            names = new ArrayList<String>();
        };
        if (places == null){
            places = new ArrayList<String>();
        }
        if (events == null){
            events = new ArrayList<String>();
        }
    }

    realNames = new LinkedHashSet<>(names);
    realPlaces = new LinkedHashSet<>(places);
    realEvents = new LinkedHashSet<>(events);
}

The "real" variables are there because I didn't find a way to put sets into savedInstanceState, so I keep each group of items both in a set and in a list.

Now, in my onViewCreated method, I'm calling prepareNames, preparePlaces and prepareEvents. The names are the first list in the layout, so the function looks something like this:

private void prepareNames(){

  edtAddName = (EditText)getActivity().findViewById(R.id.edtName);

  LinearLayout linearLayoutNames = (LinearLayout)getActivity().
            findViewById(R.id.linearLayoutNamesTitle);

    currIndNames = ((ViewGroup)linearLayout).indexOfChild(linearLayoutNames)+1;

    for (String name: names){
        addNamesRow(name, currIndNames++);
        currIndPlaces++;
        currIndEvents++;
    }

    prepareToggleButtonNames();
    prepareButtonAddName();
    prepareButtonNames();

}

Now, as you see, after adding the names row, I also have to increase the indexes for places and events, because they're further down in the linear layout.

Furthermore, users can remove rows, and I have to do something similar when removing rows. This is my addNamesRow function:

private void addNamesRow(final String text, int position){
    final LinearLayout rowLayout = (LinearLayout)LinearLayout.inflate(
            getActivity().getBaseContext(), R.layout.item,null);

    rowLayout.setTag(NAMES_TAG);

    TextView tvItem = (TextView)rowLayout.findViewById(R.id.tv_item);
    tvItem.setText(text);

    Spinner spItem = (Spinner)rowLayout.findViewById(R.id.sp_item);
    spItem.setAdapter(ArrayAdapter.createFromResource(getActivity().getBaseContext(),
            R.array.ratings,android.R.layout.simple_spinner_item));
    spItem.setSelection(2);

    Button btnItem = (Button)rowLayout.findViewById(R.id.btn_item);
    btnItem.setText("X");
    btnItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            currIndNames--;
            currIndPlaces--;
            currIndEvents--;
            linearLayout.removeView(rowLayout);
            realNames.remove(text);
        }
    });

    linearLayout.addView(rowLayout, position);

    linearLayout.invalidate();
    edtAddName.setText("");
}

My code works but I have a lot of duplication and it's very messy. I have some ideas on how to avoid some of the repetition but I'm new to Android development and I feel like I have some deeper issues in my code, and I would like to do things the right way.


texts:
I have implemented an exhaustive depth-first grid search that searches for all possible words in the 8 connected regions. Is there any way I can make this faster or memory efficient than it is now?
I feel like passing a copy of the seen set in dfs(xx, yy, seen.copy(), word + grid[x][y]) is an overhead that can possibly be avoided.
Or is my algorithm completely wrong and I should use something else?
This is not a code site challenge, I am just trying to implement this out of curiosity.
My first question on code review so let me know if there is something that I can add to make this better.
Also can this be made more "pythonic"?
def possible_directions(x, y):
    """
    Returns at most 8 connected co-ordinates for given `x` and `y`
    """
    for xx in range(-1, 2):
        for yy in range(-1, 2):
            if not xx and not yy:
                continue
            if 0 <= x + xx < len(grid) and 0 <= y + yy < len(grid[x]):
                yield x + xx, y + yy

def dfs(x, y, seen, word = ''):
    """
    Recursive Generator that performs a dfs on the word grid
    seen = set of seen co-ordinates, set of tuples
    word = word to yield at each recursive call
    """
    if (x, y) in seen:
        return
    yield word + grid[x][y]
    seen.add((x, y))
    for xx, yy in possible_directions(x, y):
        yield from dfs(xx, yy, seen.copy(), word + grid[x][y])

grid = [['c', 'f', 'u', 'c'], ['e', 'a', 't', 'e'], ['b', 'h', 'p', 'y'], ['o', 'n', 'e', 'p']] # word grid, can be any size, n x n

for x in range(len(grid)):
    for y in range(len(grid[x])):
        for i in dfs(x, y, set()):
            print(i)


texts:
Right now I have this messy method to collect the deck statistics while building a window that will display those statistics.  These statistics are things like the type and mana cost of the card.  I know that this method is too large, so I would like to get some advice for how to make it smaller.

The challenge is that I have to check if the current property in the for loop matches certain predetermined strings before putting the updated information back into the map.  This is messy now, but it will get much messier later when even more properties need to be evaluated.

Here is the method:

private void buildDeckInfoBox() {
    this.deckInfoLabelBox.getChildren().clear();

    Map<Integer, Integer> manaCostValues = new HashMap<>();
    Map<Integer, Integer> scrapCostValues = new HashMap<>();
    Map<String, Integer> creatureTypes = new HashMap<>();

    for (int cardId : this.activeDeckConfig.getChosen().keySet()) {

        CardInfoMessage card = this.cardList.get(cardId);
        int cardCount = this.activeDeckConfig.getChosen().get(cardId);

        for (Map.Entry<String, Object> entry : card.getProperties().entrySet()) {
            String key = entry.getKey();
            String value = String.valueOf(entry.getValue());

            //The value is used as the key for the new map
            //increment the number of cards and put it back in the map
            if (key.equals("creatureType")) {
                if (creatureTypes.get(value) == null) {
                    creatureTypes.put(value, cardCount);
                } else {
                    int creatureCount = creatureTypes.get(value);
                    int newCreatureCount = creatureCount + cardCount;
                    creatureTypes.put(value, newCreatureCount);
                }
            } else if (key.equals("MANA_COST")) {
                if (manaCostValues.get(Integer.parseInt(value)) == null) {
                    manaCostValues.put(Integer.parseInt(value), cardCount);
                } else {
                    int manaCostCount = manaCostValues.get(Integer.parseInt(value));
                    int newManaCostCount = manaCostCount + cardCount;
                    manaCostValues.put(Integer.parseInt(value), newManaCostCount);
                }
            } else if (key.equals("SCRAP_COST")) {
                if (scrapCostValues.get(Integer.parseInt(value)) == null) {
                    scrapCostValues.put(Integer.parseInt(value), cardCount);
                } else {
                    int scrapCostCount = scrapCostValues.get(Integer.parseInt(value));
                    int newScrapCostCount = scrapCostCount + cardCount;
                    scrapCostValues.put(Integer.parseInt(value), newScrapCostCount);
                }
            }
        }
    }

    for (int manaCost : manaCostValues.keySet()) {
        Label manaCostLabel = new Label();
        manaCostLabel.setText(String.format("Mana Cost = %d, Count = %d", manaCost, manaCostValues.get(manaCost)));
        this.deckInfoLabelBox.getChildren().add(manaCostLabel);
    }
    for (int scrapCost : scrapCostValues.keySet()) {
        Label scrapCostLabel = new Label();
        scrapCostLabel.setText(String.format("Scrap Cost = %d, Count = %d", scrapCost, scrapCostValues.get(scrapCost)));
        this.deckInfoLabelBox.getChildren().add(scrapCostLabel);
    }
    for (String creatureType : creatureTypes.keySet()) {
        Label creatureTypeLabel = new Label();
        creatureTypeLabel.setText(String.format("Creature Type %s, Count = %d", creatureType, creatureTypes.get(creatureType)));
        this.deckInfoLabelBox.getChildren().add(creatureTypeLabel);
    }
}

Here is an example of the output:

Eventually I will turn these labels into a fancy statistics graph like the one in Hearthstone, separated by the type of property.


texts: Place a button after an input and show it's password in plain text

texts:
I have managed to achieve this action through this:

function togglePasswordVisibility($pw, on, id) {
  $pw.attr('type', on ? 'password' : 'text');
  $('[data-id=' + id + '] > i').toggleClass('fa-eye-slash fa-eye');
 }

 // $("#pass-on").after('

');

 $('[data-id]').on('click', function() {
  var id = $(this).data('id'),
   $pw = $('#' + id);

  togglePasswordVisibility($pw, false, id);

  setTimeout(function() {
   togglePasswordVisibility($pw, true, id);
  }, 800);
 });
<link href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" rel="stylesheet"/>

       <input type="password" id="pass-on" title="<?php echo $user->valid_password_error; ?>" class="form-control" name="txt_upass" placeholder="Enter Password" autocomplete="off" value="" oninvalid="setCustomValidity('<?php echo $user->password_error; ?>')" oninput="setCustomValidity('')" required />
     Password

      <input type="password" id="pass-verify-on" title="<?php echo $user->valid_password_error; ?>" class="form-control" name="txt_upass_ok" placeholder="Retype Password" autocomplete="off" value="" oninvalid="setCustomValidity('<?php echo $user->password_error; ?>')" oninput="setCustomValidity('')" required />
      Retype Password

But I would like to place the password button from within the function using the commented line with the after callback and making it apply the same effect. Right now the button correlates with the input through the association of data-id and id. If I would to place it inside the function I would have to get rid of the data-id and still make it act individually on each input, I just can't figure how. Thank you for your time.


texts:
I solved this problem

  Given three sorted arrays A, B and C of not necessarily same sizes.

  Calculate the minimum absolute difference between the maximum and
  minimum number from the triplet a, b, c such that a, b, c belongs
  arrays A, B, C respectively. i.e. minimize | max(a,b,c) - min(a,b,c)
  |.

  Example :

  Input:

  A : [ 1, 4, 5, 8, 10 ] B : [ 6, 9, 15 ] C : [ 2, 3, 6, 6 ]

  Output:

  1

  Explanation:

  We get the minimum difference for a=5, b=6, c=6 as |
  max(a,b,c) - min(a,b,c) | = |6-5| = 1.

The idea behind my solution was if at each iteration we have the closest triplets we will be able to get the optimal absolute minimum.

I  couldn't find a clean way to implement this logic. And my solution is this.

int Solution::solve(vector<int> &A, vector<int> &B, vector<int> &C) {
    int answer = INT_MAX;
    int a = 0, b = 0, c = 0;
    while(a < A.size() || b < B.size()  || c < C.size() )
    {
        // cout << a << ' ' << b << ' ' << c << endl;
        int MinVal = min(min(A[a], B[b]), C[c]);
        int MaxVal = max(max(A[a], B[b]), C[c]);
        bool na = false, nb = false, nc = false;
        answer = min(answer, abs(MaxVal - MinVal));
        if(a + 1 < A.size() && A[a + 1] <= MaxVal)
        {
            ++a;
        }
        else if(b + 1 < B.size() && B[b + 1] <= MaxVal)
        {
            ++b;
        }
        else if(c + 1 < C.size() && C[c + 1] <= MaxVal)
        {
            ++c;
        }
        else
        {
            // cout << "Next Max\n";
            int next_a = a + 1 < A.size() ? A[a + 1] : INT_MAX;
            int next_b = b + 1 < B.size() ? B[b + 1] : INT_MAX;
            int next_c = c + 1 < C.size() ? C[c + 1] : INT_MAX;
            // cout << next_a << ' ' << next_b << ' ' << next_c << endl;
            if(next_a <= min(next_b, next_c) && next_a != INT_MAX)
            {
                ++a;
            }
            else if(next_b <= min(next_a, next_c) && next_b != INT_MAX)
            {
                ++b;
            }
            else if(next_c < min(next_a, next_b) && next_c != INT_MAX)
            {
                ++c;
            }
            else
            {
                break;
            }

        }
    }
    return answer;
}

Could you please suggest how to avoid excessive if-else statements in the solution. Also, this solution wouldn't be scaleable for more array's so a more general approach would be helpful as well


texts:
This is a function written in Python I wrote to process galaxy catalogs for cosmology research, however it is more generally applicable than just my pipeline.

The goal is to take a Python list of coordinates in 3D, optionally with associated weights, define a cubic grid over the coordinates which divides the points into a variable number of "bins" or cells, and then computes the total number of points in each bin (or the sum of the weights). These sums are then associated to either the coordinates or indices of the bin.

Obviously there are existing functions in Python libraries which do this, namely numpy.histogram, scipy.stats.histogram, and less obviously numpy.unique. The reason I didn't use those is that I had to process huge catalogs of \${\sim}10^6\$ galaxies or more, and I wanted to make fairly small bins. The histogram functions store empty bins in memory, so I would often run out of memory trying to store huge numpy arrays of mostly zeros. numpy.unique avoids this, but it cannot handle summing weights instead of just counts.

So I created this function, abusing using the defaultdict subclass of the native Python dictionary to gain the summing feature. I found it to be both fast enough and that it solved my memory problems, but I am interested in improving it.

from collections import defaultdict

"""Accepts a python list of 3D spatial points, e.g. [[x1,y1,z1],...],
optionally with weights e.g. [[x1,x2,x3,w1],...], and returns the sparse
histogram (i.e. no empty bins) with bins of resolution (spacing) given by
res.
The weights option allows you to chose to histogram over counts
instead of weights (equivalent to all weights being 1).
The bin_index option lets you return the points with their bin indices
(the integers representing how many bins in each direction to walk to
find the specified bin) rather than centerpoint coordinates."""
def sparse_hist(points, res, weights=True, bin_index=False):
    def _binindex(point):
        point = point[:3]
        bi = [int(x//res) for x in point]
        bi = tuple(bi)
        return bi

    def _bincenter(point):
        point = point[:3]
        bc = [(x//res+0.5)*res for x in point]
        bc = tuple(bc)
        return bc

    if not bin_index:
        if weights:
            pointlist = [(_bincenter(x), x[3]) for x in points]
        else:
            pointlist = [(_bincenter(x), 1) for x in points]
    else:
        if weights:
            pointlist = [(_binindex(x), x[3]) for x in points]
        else:
            pointlist = [(_binindex(x), 1) for x in points]

    pointdict = defaultdict(list)
    for k,v in pointlist:
        pointdict[k].append(v)

    for key,val in pointdict.items():
        val = sum(val)
        pointdict.update({key:val})

    return pointdict


texts: Selecting a thumbnail from among a large, medium, and small image

texts:
I'm parsing some data in C# where I have an object with 3 properties: "large", "medium", "small"; each property may contain a string array with an image path, and I'm trying to extract that path.

The data should always have a large image, but not always a medium or small. I'm trying to generate thumbnail images, so I prefer the small, but if it's not there I want the medium, otherwise the large. The following code works and I understand it but I have the feeling there's a more expressive way:

var thumb = (images == null)
            ? null
            : (images.small == null) || (images.small.Length == 0)
                ? (images.medium == null) || (images.medium.Length == 0)
                    ? (images.large == null) || (images.large.Length == 0)
                        ? null
                        : images.large[0]
                    : images.medium[0]
                : images.small[0];

I could at least break out the guard clauses to a Boolean method like hasImage("small") or better yet hasImage(imageEnum.SMALL) -- that would make the tests easier to understand and also encapsulate them so changes to the test logic wouldn't pollute the retrieval logic.

Other than that, is there a better (i.e. easier to understand) way to express the overall algorithm?


texts:
I want to implement a utility class which manages tokens generated by any API. The idea is simple:

  It should store the current token value. The token should be initialized just before first use and then re-initialized after some time has elapsed. If the API returns an error related to the token, it should be regenerated and job should be repeated.

Here we have the utility class:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public abstract class TokenManager {

    private volatile String token;
    private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private ScheduledFuture<?> schedule;

    public void useToken(TokenConsumer tokenConsumer) {
        useToken(tokenConsumer, true);
    }

    private void useToken(TokenConsumer tokenConsumer, boolean retryWhenTokenExpired) {
        try {
            tokenConsumer.useToken(getToken());
        } catch (Exception e) {
            if (retryWhenTokenExpired && tokenExpired(e.getMessage())) {
                System.out.println("token expired, retry");
                resetToken();
                useToken(tokenConsumer, false);
            }
        }
    }

    synchronized private String getToken() {
        if (token == null) {
            resetToken();
        }
        return token;
    }

    synchronized private void resetToken() {
        if (schedule != null) {
            schedule.cancel(false);
        }
        System.out.println("reset token");
        token = generateToken();
        int oneMinute = 60 * 1000;
        long delay = getTokenValidityTimeMillis() - oneMinute;
        schedule = scheduler.schedule(this::resetToken, delay > 0 ? delay : getTokenValidityTimeMillis(), TimeUnit.MILLISECONDS);

        System.out.println("reset token finished");
    }

    protected abstract String generateToken();

    protected abstract boolean tokenExpired(String message);

    protected abstract long getTokenValidityTimeMillis();

    @FunctionalInterface
    public interface TokenConsumer {
        void useToken(String token) throws Exception;
    }
}

And here we have its simple implementation with use example:

import java.util.Random;

public class TokenManagerImpl extends TokenManager {
    @Override
    protected String generateToken() {
        //here would go some api call which retrieves token
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "token " + new Random().nextInt();
    }

    @Override
    protected boolean tokenExpired(String message) {
        return "Token expired".equals(message);
    }

    @Override
    protected long getTokenValidityTimeMillis() {
        return 1000;
    }

    public static void main(String[] args) {
        TokenManager tokenManager = new TokenManagerImpl();
        TokenConsumer tokenConsumer = token -> {
            //here would go some api call which uses token
            System.out.println("using token : " + token);
        };
        while (true) {
            tokenManager.useToken(tokenConsumer);
            try {
                Thread.sleep(50L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


texts: Checking an existing item doesn't already exist in my component's list of items

texts:
Here's a function in my PersonList component:

addPerson(person) {
    /*srsly there must be a better way to do this*/
    if (!this.state.people.map((v,i) => {
        return v.id;
        }).includes(person.id)
    ){
        this.setState({
            people: this.state.people.concat([person])
        });
    }
}

This is fairly simple function. We're passed a Person object, but we only want to add it to the list, if it's not already there - to prevent duplication.

Is there a tidier way to achieve this?


texts:
Please refer following graph.

Please review following code for topological sort.

I can sense one odd thing in my code, TS() is calling TSUtil(), still I had to write  Visited.emplace(n.first); and Sorted.emplace(n.first); in TS().

Please suggest if I could handle it better.

test() method is called from main to test the code.

I tried to follow C++ 11 standard.

.h file

#pragma once
#include <set>
#include <stack>
#include <unordered_map>
#include <vector>

using std::set;
using std::stack;
using std::unordered_map;
using std::vector;

class TopolocialSort
{
private:
    set<char> Visited;
    stack<char> Sorted;
    unordered_map<char, vector<char>> G;
    void createGraph();
    void TS();
    void TSUtil(vector<char> childNode);
    void PrintTS();

public:
    void test();
};

.cpp

#include "TopolocialSort.h"
#include <iostream>

using std::cout;
using std::endl;

void TopolocialSort::createGraph()
{
    G['A'].push_back('E');
    G['A'].push_back('C');

    G['B'].push_back('D');
    G['B'].push_back('C');

    G['C'].push_back('\0');

    G['D'].push_back('F');

    G['E'].push_back('F');
    G['E'].push_back('H');

    G['F'].push_back('G');

    G['G'].push_back('\0');

    G['H'].push_back('\0');

}

void TopolocialSort::test()
{
    createGraph();
    TS();
    PrintTS();
}

void TopolocialSort::PrintTS()
{
    while (!Sorted.empty())
    {

        cout << Sorted.top() <<" ";
        Sorted.pop();
    }
}

void TopolocialSort::TSUtil(vector<char> childNode)
{
    for (auto n : childNode)
    {
        //will visit node only once
        if (Visited.find(n) != Visited.end())
        {
            continue;
        }

        Visited.emplace(n);
        TSUtil(G[n]);

        Sorted.emplace(n);
    }

}

void TopolocialSort::TS()
{
    for (auto n : G)
    {
        //will visit node only once
        if (Visited.find(n.first) != Visited.end())
        {
            continue;
        }

        Visited.emplace(n.first);
        TSUtil(n.second);

        Sorted.emplace(n.first);
    }
}


texts: Getting all descendants IWebElements (using XPath) is too slow in Selenium

texts:
Well, I'm working with Selenium to scrap a webpage that has obfuscated class names (example <div class="example-gHJkLM">...)...

So I needed to create an extension method to get

public static ReadOnlyCollection<IWebElement> Descendants(this IWebElement element, bool hasChildren = false, int index = -1, string postAppend = "")
{
    var web = element.GetWebDriver(); // < 1ms
    var xpath = element.XPath(); // 5 ms

    return web.FindElements(By.XPath(xpath + "//" + (hasChildren ? "child::node()" : "*") + (index > -1 ? $"[{index + 1}]" : string.Empty) + postAppend)); // 64 ms
}

public static ReadOnlyCollection<IWebElement> GetNodesByContainingClass(this IWebElement element, string className,
    bool toLower = false, bool useFullHierarchy = false)
{
    return new ReadOnlyCollection<IWebElement>(element?.Descendants()
        .Where(n =>
            (toLower ? n.GetAttribute("class")?.ToLowerInvariant() : n.GetAttribute("class"))
            ?.Contains(className) == true).ToList()); // ????
}

public static IWebElement GetNodeByContainingClass(this IWebElement node, string className)
{
    return node?.GetNodesByContainingClass(className).FirstOrDefault();
}

Example usage:

            var watch = Stopwatch.StartNew();

            var welcomeMessage = messageBox
                .GetNodesByContainingClass(
                    "icon-", false, true)?
                .LastOrDefault();

            watch.Stop();
            Console.WriteLine($@"[Getting welcome message element] Ellapsed {watch.ElapsedMilliseconds} ms!", Color.Yellow);

  messageBox is a IWebElement
  I'm using Colorful.Console package

And this is what I got:

4 and 9 seconds to materialize a Where LINQ clause, seriously? I debugged the element?.Descendants() part and this has only 727 elements...

Can anyone guide me?

Also, I will be so thankfully if somebody suggests me a better approach to do this.


texts: Create histogram with greater than symbol in x axis in pyplot

texts:
I wanted to create a histogram from a list of positive integers. I want to bin it so that I show all single numbers, say K through N, with more than k elements in the data set, as well as the number of elements greater than N.

'''
The goal is to max a histogram from integer data.
The last bin should represent all cases with at least K elements.
 x x                    x x
 x x x                  x x x x
 x x x   x x    ---->   x x x x
____________           __________
 1 2 3 4 5 6            1 2 3 >3
'''
import matplotlib.pyplot as plt
import numpy as np

# Insert your favorite integer data here
data = [1, 1, 1, 2, 2, 2, 3, 3, 5, 6]

# Vanilla histogram for reference
hist, bins = np.histogram(data, bins=np.arange(1, 15))
center = (bins[:-1] + bins[1:]) / 2 - 0.5
f, ax = plt.subplots()
ax.bar(center, hist, align='center', edgecolor='k')
ax.set_xticks(center)
ax.set_title('vanilla hist')
plt.savefig('vanillahist')
plt.clf()

# Select the point after the last time we see at least k elements
K = 2
maxnum = bins[1:-1][np.abs(np.diff(hist >= K)) > 0][-1]

# filter the bins from numpy to only contain this point and those prior
center = bins[bins <= maxnum]

# filter frequency data from numpy;
# bins/hist are ordered so that the first entries line up
newhist = hist[(bins[:-1] <= maxnum)]
newhist[-1] += np.sum(hist[(bins[:-1] > maxnum)])

# make the plot, hopefully as advertised!
f, ax = plt.subplots()
ax.bar(center, newhist, align='center', edgecolor='k')
ax.set_xticks(center)
ax.set_xticklabels(list(center[:-1].astype(int)) + ['> %i' % (maxnum - 1)])
plt.savefig('myhist')
plt.clf()

This involved a lot of trial and error, and I'm still not 100% sure this can handle all cases, though it's passed every test I've tried so far. Could I have made this code more readable? I feel particularly unsure about lines 28-38. My justification for the [:-1] line is that the first entry of bins corresponds to the first entry of hist.


texts:
I've been learning JavaScript for a few weeks and thought to give the ol' fizzbuzz another try. My goal was for expandability. In other words, I wanted to be able to add more keywords without having to rewrite parts of the code.

I tried to add comments to clarify some of the more unorthodox parts of my code. However, I still feel my code is somewhat terse... Is it better to just write the plain old for-loops for readability and support of IE?

I also opted to check if the string existed instead of checking if the length was greater than zero. Are there any pitfalls I might fall into just checking for existence? I mean if my key were false it would fail, however that would never happen as all the key values are strings anyways.

function fizzBuzz(divisors = {
        fizz: 3,
        buzz: 5
    }, maxNumber = 100) {
        /* Takes in a object of divisors of the form
           divisors = {
               name: value,
           };
           and an integer. Loops through the list if number below or equal
           maxNumber. If a number is divisible by one of the values, print the name.
          */
        for (var num = 1; num <= maxNumber; num++) {
            var str = "";
            // Loops through the keys of the divisors
            Object.keys(divisors).forEach(function(key)  {
                // Ternary expression, if divisible append key else do nothing
                str += num % divisors[key] == 0 ? key : '';
            });
            // If anything got appended print string else num
            console.log(str ? str : num)
        }
    }

    fizzBuzz()


texts:
I have some framework in PHP/MySQL for developing web services. Finally my code works on two servers - production and developer. My idea is to create one code without differences, which will work different on both servers, depend of config. I created table [ini], with two rows of data, where I can specifically change settings of many parameters like:

email address of administrator, which is used to inform him about registration new user,
IDs of advertising banners to display on some pages,
page name to redirect after successful logging,
ID of default role of new user
etc.

I can of course prepare a class for read one specify setting when it is necessary, but it means that I will read data from my [ini] table dozen times in many PHP files.

Is it safe to read it once and globalize by following code?

//on developer machine my INI_ID == 0, on production server INI_ID == 1
if($_SERVER['SERVER_NAME'] == 'www.developer_domain_name.com'){
 define('INI_ID',0);
}
else{
 define('INI_ID',1);
}

$row = function_SQLToRow('SELECT * FROM ini WHERE ini_id = ' . INI_ID . '');
$GLOBALS['ini'] = $row;

I'm open for other solutions, maybe storing config in file and read specific file depend on server, or prepare list of constants depend on server are safer solutions?


texts: F# Either computation expression with while loop

texts:
I want to implement an Either computation expression in F#. The computation executes a function inside a while loop, and this function's return type is Result<int, string>. The function might return an Error<string> if some condition is met, and then the whole computation expression should be stopped.

This is the code I have so far to illustrate what I am trying to achieve:

type EitherBuilder () =
  member this.Bind(x, f) =
    match x with
    | Ok s -> f s
    | Error f -> Error f
  member this.Return x = Ok(x)
  member this.ReturnFrom x = x
  member this.Zero() = Ok()
  member this.Delay(f) = f
  member this.Combine(x, f) = this.Bind(x, f)
  member this.Run(f) = f()
  member this.While(guard, body) =
    if guard () then this.Bind(body (), fun _ -> this.While(guard, body))
    else this.Zero()

let either = EitherBuilder ()

let mutable i = 0

let func i =
  if i < 3 then Ok(i)
  else Error("error")

let result = either {
  let mutable res = 0
  while i < 10 do
    let! output = func i
    res <- output
    i <- i + 1
  return res
}

I have tested it and it looks like it is working and doing what I am after (in the example above, the computation is stopped when i becomes 3 and result is set to Error "error"), but I am not 100% sure if the implementation of the EitherBuilder is fully correct. I would appreciate some feedback.


texts:
In particular, if someone could describe a better way to go from the tokenized list to the Expression tree, it would be super helpful.  I would like to get rid of the casting in the parser but am not sure how.

Full code here

package org.bws.calc;

import java.util.ArrayList;

import org.bws.calc.exception.ParseException;
import org.bws.calc.expression.Expression;
import org.bws.calc.expression.ValueExpression;
import org.bws.calc.tokens.OpToken;
import org.bws.calc.tokens.Token;

public class SimpleParser implements Parsable{

    public Expression parse(ArrayList<Token> tokens){
        if(tokens.size() == 1){
            Token t = tokens.get(0);
            try{
                int intVal = Integer.parseInt(t.getValue());
                return new ValueExpression(intVal);
            }catch(NumberFormatException nfe){
                throw new ParseException("expected int but found: "+t.getValue());
            }
        }

        Expression left;
        Expression right;

        int index=0;
        Token firstToken = tokens.get(index++);

        if("(".equals(firstToken.getValue())){
            int openParens =1;
            while(openParens > 0 ){
                if(index>tokens.size()-1){throw new ParseException("Missing right Parenthesis");}
                Token token = tokens.get(index);
                if("(".equals(token.getValue())){ ++openParens;}
                if(")".equals(token.getValue())){ --openParens;}
                ++index;
            }
            if(index == tokens.size()){
                return parse(new ArrayList<Token>(tokens.subList(1, index-1) ) );
            }
            left = parse(new ArrayList<Token>(tokens.subList(1,index-1)));

        }else{
            int tokenVal = Integer.parseInt(firstToken.getValue());
             left = new ValueExpression(tokenVal);
        }

        Token op = tokens.get(index);
        if(! (op instanceof OpToken) ){
            throw new ParseException("Invalid Syntax. expected Operator but found:"+op);
        }
        OpToken opToken = (OpToken) op;
        ++index;

        Token firstRightToken = tokens.get(index++);
        if("(".equals(firstRightToken.getValue() ) ){
            right = parse(new ArrayList<Token>(tokens.subList(index,tokens.size()-1)));
        }else{
            int tokenVal = Integer.parseInt(firstRightToken.getValue());
            right = new ValueExpression(tokenVal);
        }

        return opToken.toExpression(left, right);
    }
}


texts: FizzBuzz in F# with functional programming

texts:
Learning F#, created a somewhat elaborate fizzbuzz-builder implementation to see if I'm starting to "get" F# and thinking functionally:

type FBCase = FBCase of (int * string)

let makeFBCase num = FBCase (num, "")

let unpackFBCase case =
    match case with
    | FBCase (num, str) when str = "" -> num |> string
    | FBCase (_, str) -> str

let fbBuilder (num) (str:string) input =
    match input with
    | FBCase (x, y) when x % num = 0 -> FBCase (x, y+str)
    | _ -> input

let createFBFunc input = fbBuilder (fst input) (snd input)

let createFBPipeline inputList =
    inputList
    |> List.map createFBFunc
    |> List.reduce (>>)

let createFBPattern inputList =
    makeFBCase
    >> (inputList |> createFBPipeline)
    >> unpackFBCase

let fizzBuzz = createFBPattern [(3, "Fizz"); (5, "Buzz")]

let fizzBuzzBaz = createFBPattern [(3, "Fizz"); (5, "Buzz"); (7, "Baz")]

let fizzBuzzBazQuux = createFBPattern [(3, "Fizz"); (5, "Buzz"); (7, "Baz"); (11, "Quux")]

[1..100]
    |> List.iter (fizzBuzz >> printfn "%A")
[1..100]
    |> List.iter (fizzBuzzBaz >> printfn "%A")
[1..100]
    |> List.iter (fizzBuzzBazQuux >> printfn "%A")

Where is it obvious that I'm not thinking functionally?
What could I change to make a more idiomatic F#-style program?
(Note that I don't really "get" monads or workflows yet, although I'm aware they exist).


texts: Merge and sorting arrays of String and int in more efficient methods

texts:
Are there better methods for merge and sorting arrays of int and String in more efficient methods both time-complexity wise and code-pattern wise? I also wonder if I could have a generic method that could work for any kind of given type like <E>.

I am preparing for coding interviews, so I prefer to see solutions that involve known Java APIs and nothing fancy.

/**
 * Created by mona on 5/24/16.
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MergeArrays {

    public static String[] mergeAndSortStringArrays(String[] first, String[] second){
        List<String> merged = new ArrayList<>();
        Collections.addAll(merged,first);
        Collections.addAll(merged,second);
        Collections.sort(merged);
        return merged.toArray(new String[merged.size()]);
    }

    public static int[] mergeAndSortIntArrays(int[] firstInt, int[] secondInt){

        List<Integer> merged = new ArrayList<>();

        for (int i=0; i<firstInt.length; i++){
            merged.add(firstInt[i]);
        }

        for (int i=0; i<secondInt.length; i++){
            merged.add(secondInt[i]);
        }

        Collections.sort(merged);
        int[] result=new int[merged.size()];
        for (int i=0; i<merged.size(); i++){
            result[i]=merged.get(i);
        }
        return result;
    }

    public static void main(String[] args){
        String[] first={"hi", "mona", "how", "are", "you"};
        String[] second={"hello", "world", "good", "morning", "USA"};
        String[] merged=mergeAndSortStringArrays(first, second);
        for (int i=0; i<merged.length; i++){
            System.out.print(merged[i]+" ");
        }

        int[] firstInt={1, 4, 2, 6, 7};
        int[] secondInt={2, 8, 2, 9, 1, 12};
        int[] resultedMerge=mergeAndSortIntArrays(firstInt, secondInt);
        for (int i=0; i<resultedMerge.length; i++){
            System.out.print(resultedMerge[i]+" ");
        }
    }
}


texts: Finding integer lengths for a right triangle with a given perimeter

texts:
I'm using Python 3 and have written this code to find the right triangle sides when given the perimeter:

def intRightTri(p):
    l = [(a,b,c) for a in range (1, p)
                 for b in range (1, p)
                 for c in range (1, p)
                 if (a**2 + b**2 == c**2) and (a + b + c == p) and (a<=b) and (b<c)]
    return l

When I run my tests, they work, but the last one seems to be taking a really long time. What would be a good way to improve my code so it executes quicker?

import unittest
tc = unittest.TestCase()
tc.assertEqual(intRightTri(100), [])
tc.assertEqual(intRightTri(180), [(18, 80, 82), (30, 72, 78), (45, 60, 75)])
tc.assertEqual(intRightTri(840),
           [(40, 399, 401),
            (56, 390, 394),
            (105, 360, 375),
            (120, 350, 370),
            (140, 336, 364),
            (168, 315, 357),
            (210, 280, 350),
            (240, 252, 348)])

Update

New quicker method combining both answers.

def integer_right_triangles(p):
    l = [(a,b,p-a-b) for a in range (1, p)
            for b in range (a, p-a)
            if (a**2 + b**2 == (p - (a+b))**2 )]
    return l


texts: A structure for a text messages dictionary with system notifications/errors

texts:
I would like to arrange a system messages dictionary for an application in JavaScript.
As an initial intention, I thought something about the following structure:
export const SYS_MESSAGES = Object.freeze({

    fileSizeExceeded: {
        code: "FILE_SIZE_EXCEEDED",
        text: "The file size exceeds allowed limit"
    }

});

But then I realized, the structure could be even more simple:
export const SYS_MESSAGES = Object.freeze({

    FILE_SIZE_EXCEEDED: "The file size exceeds allowed limit"

});

Which option of two structures is a preferred-one from maintenance/style perspective?