texts: Bash script to temporarily run a shell without certain group memberships

texts:
I have here a script called rwog (run without groups) that allow a user to run a shell without particular group memberships.  rwog, in more detail...

Is primarily for a support staffer to pretend to be an ordinary user without  su-ing to anybody.
Must be run as root, but those allowed to run it will be given an entry in /etc/sudoers.
Should be executed as sudo rwog groups to drop.
Will have a uid of root, a gid of the_support_team, and permissions 0550 (i.e. user and group can read and execute, world can do nothing, and no setgid/setuid bits).
Cannot change your gid, change your uid, or add yourself to supplementary groups.
Revokes pretty much all capabilities, though this may be a tad zealous.
Does not modify /etc/group (so id will be changed, but id $USER will not).
Is primarily (but not exclusively) intended to run on a Centos 7 environment..

My main concern: Can this script be exploited to gain escalated privileges?
 I won't ignore suggestions not related to security.

The Script

#!/bin/bash

function help(){
    echo "rwog - run without groups";
    echo "Runs a shell as if you weren't in certain supplementary groups."
    echo "Good for pretending that you're not a support user."
    echo "Usage example:";
    echo -e "\trwog [(-h|--help)] [group ...]";
    echo "Options:";
    echo -e "\t-h or --help: Displays this information.";
    exit 1;
}

# Declare vars. Flags initalizing to 0.

# Execute getopt
ARGS=$(getopt -o "h" -l "help" -n "rwog" -- "$@");

#Bad arguments
if [ $? -ne 0 ];
then
    help;
fi

eval set -- "$ARGS";

while true; do
    case "$1" in
        -h|--help)
            shift;
            help;
            ;;

        --)
            shift;
            break;
            ;;
    esac
done

if [[ $(id -u) != 0 ]]; then
    # If you're not root...
    echo "You must be root to use this script. Run it with sudo."
    exit 1
fi

for group in $@; do
    # For each group we want to drop...

    if [[ "$group" == "$SUDO_USER" ]]; then
        # If you're trying to drop your own gid...
        echo "You cannot drop your own gid."
        exit 1
    elif ! getent group "$group" &>/dev/null ; then
        #If this group doesn't exist...
        echo "$group is not a valid group."
        exit 1
    elif  ! groups "$SUDO_USER" | grep -E &>/dev/null "\b$group\b"; then
        # Else if you're not actually a member of this group...
        echo "Not a member of $group, cannot drop it"
        exit 1
    fi
done

my_groups=$(id -Gn "$SUDO_USER" | xargs -n1 | sort -u)
groups_to_drop=$(echo $@ | xargs -n1 | sort -u)
# Put the groups that you want to drop on multiple lines, then sort them

if [[ -z "$groups_to_drop" ]]; then
    # If you didn't pick a group to drop...
    echo "Please specify at least one supplementary group to drop."
    help
fi

reduced_groups=$(comm -13 <(echo "$groups_to_drop") <(echo "$my_groups") | paste -s -d,)
# Subtract the groups we want to drop from the groups we're in, then merge them onto one line

export USERNAME="$SUDO_USER"
export USER="$SUDO_USER"
export LOGNAME="$SUDO_USER"
export HOME=$( getent passwd "$SUDO_USER" | cut -d: -f6 )

dropped_capabilities=$(capsh --print | grep -E "Bounding set =(.+)" | sed "s/Bounding set =//g")

capsh --secbits=0xf --drop="$dropped_capabilities" --groups="$reduced_groups" --gid="$SUDO_GID" --uid="$SUDO_UID" -- --login


texts:
I wrote this for an SO question on formatting numbers to specific quantities of significant figures (after all, reinventing-the-wheel), anyway, all critiques welcome.

It's pretty easy to use, FormatSignificantFigures(0.123, 2) should return 0.12; FormatSignificantFigures(0.123, 5) should return 0.12300; FormatSignificantFigures(0.123456, 5) should return 0.12346, etc.

public static string FormatSignificantFigures(double number, int figures)
{
    int e = 0;

    while (number >= 10.0)
    {
        e += 1;
        number /= 10;
    }

    while (number < 1.0)
    {
        e -= 1;
        number *= 10;
    }

    figures--;

    number = Math.Round(number, figures);

    figures += 0 - e;
    while (e > 0)
    {
        number *= 10;
        e -= 1;
    }

    while (e < 0)
    {
        number /= 10;
        e += 1;
    }

    if (figures < 0)
    {
        figures = 0;
    }

    return number.ToString($"f{figures}");
}


texts: Calculate all the prime numbers between two given numbers

texts:
I've made an application that calculates all the prime numbers between two given numbers and prints then into a .txt document... anything I can improve?
use std::io;
use std::fs::{OpenOptions};
use std::io::{Write, BufWriter};

fn main() {

    loop{

        let mut format = 1;

        let mut input = String::new();
        println!("Say a start for the prime loop! ");

        io::stdin().read_line(&mut input).unwrap();
        let start: u128 = input.trim().parse().unwrap();

        let mut input = String::new();
        println!("Say an end for the prime loop! ");

        io::stdin().read_line(&mut input).unwrap();
        let end: u128 = input.trim().parse().unwrap();

        let path = "path/to/file.txt";

        let f = OpenOptions::new()
            .write(true)
            .open(path)
            .expect("Could not open file");

        let mut f = BufWriter::new(f);

        for i in start..end{
            if prime(i) == true{
                f.write_all(i.to_string().as_bytes()).expect("unable to write to file");
                f.write_all(b"\t").expect("unable to write to file");
                format += 1;
            }

            if format == 10{
                f.write_all(b"\n").expect("unable to write to file");
                format = 0;
            }

        }
    }
}

fn prime(x: u128) -> bool {

    if x == 4 || x == 6 || x == 8 || x == 9{ //The loop doesnt quite work for numbers below 10 so this is for those numbers
        return false;
    }
    for i in 2..((x as f64).sqrt() as u128){
        if x % i == 0 { return false; }  //modulo to see if the number is dividable by variable i
    }
    true
}
```


texts:
The prime 41, can be written as the sum of six consecutive primes:

  41 = 2 + 3 + 5 + 7 + 11 + 13
  This is the longest sum of consecutive primes that adds to a prime below one-hundred.

  The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

  Which prime, below one-million, can be written as the sum of the most consecutive primes?

My solution (very fast):

asFarAsPossibleCondition :: (a -> Bool) -> [a] -> Maybe [a]
asFarAsPossibleCondition _ [] = Nothing
asFarAsPossibleCondition f xs = if f $ last xs then Just xs else asFarAsPossibleCondition f $ init xs

maxPrimeSum :: Int -> Int
maxPrimeSum n = snd $ maximumBy (comparing fst) series
    where
        series = map (\x -> (length x, last x)) $ mapMaybe checkSeries [0..10]
        checkSeries x = asFarAsPossibleCondition (isPrime) $ takeWhile (<n) $ scanl1 (+) $ drop x primes

asFarAsPossibleCondition looks for the last element in a list that satisfies a condition then returns that list up to that point (e.g. asFarAsPossibleCondition (<5) [1..10] -> Just [1,2,3,4]. (Note that it differs from takeWhile, since takeWhile will start at the beginning of the list and stops as soon as it encounters an element that does not satisfy the condition. My function starts at the end of the list and looks for the last element that satisfies the condition, regardless of whether there are elements before that that don't satisfy the condition, e.g. asFarAsPossibleCondition (<5) [1,2,3,4,5,6,7,8,9,10,4] -> Just [1,2,3,4,5,6,7,8,9,10,4]. This is useful to check a list of consecutive prime sums (e.g. [2, 5, 10, ...]) and get the longest one that adds to a prime, for instance:

last $ fromJust $ asFarAsPossibleCondition isPrime $ scanl1(+) $ take 20 primes
281

This is the highest consecutive prime sum that results in a prime number that  you can get with x<=20 prime numbers starting from 2 (2+3+5+7+11+13+17+19+23+29+31+37+41+43 = 281).

To start from the next prime, you simply drop the first prime, and so forth, e.g.

last $ fromJust $ asFarAsPossibleCondition isPrime $ scanl1(+) $ take 20 $ drop 1 primes
499

This is the highest consecutive prime sum that results in a prime number that  you can get with x<=20 prime numbers starting from 3.

The rest is fairly obvious; it checks for each starting prime the greatest prime below 1,000,000, gets the length and the prime it adds up to, then gets the prime with the maximum length.

Any advice is welcome, specifically on:

the use of Maybe (I'm just learning about this); is it correct? Justified? ...
how to determine on how many items that I should map the checkSeries function on. ([0..10] was sufficient, but that was simply because I got lucky).
is there a builtin that does what my asFarAsPossibleCondition function does?


texts:
I spent the past hour trying to optimize a block of code I wrote that renders a simple coloured line directly to a backbuffer.

I've compared it with one of the DrawLine method implementations of the WriteableBitmapEx project, and found that my algorithm isn't quite as fast (unless I use Parallel).

public static unsafe void DrawLineVector(this IntPtr target, Line2D line, int colour, int width, int height)
{
    var buf = (int*) target;
    var start = line.Start;
    var lineVector = line.Stop - start;
    var steps = (int)lineVector.Magnitude();
    var uX = lineVector.X / steps;
    var uY = lineVector.Y / steps;
    var col = colour;
    Parallel.For(0, steps, i =>
    //for (var i = 0; i != steps; ++i)
    {
        var x = start.X + uX * i;
        var y = start.Y + uY * i;
        if (x > -1 && y > -1 && x < width && y < height)
            buf[(int)y * width + (int)x] = col;
        //x += uX;
        //y += uY;
    }
    );
}

Note, the Line2D object is basically just a container for two VectorD objects (which are my own implementation of vectors).

Running this as it is currently, will get me, on my machine, roughly 300MPixels per second, while the "default" DrawLine method from WriteableBitmapEx gets me around 170MPixels per second. If I use the 'serial' version of this (i.e. not use Parallel), I get around 100MPixels per second.

Is there any way I can optimize this further?


texts: Converting decimal integers to a string representation in an arbitrary base between 2 and 26

texts:
This code takes an integer and returns a string representing the value in a different base. The value for the base can range between 2 and 26. I have had someone already look over this code and they told me that I was committing a "cardinal sin" of memory management and referred me to the documentation for malloc(). I am confused as to what he is referring to. The only thing I have come up with so far is that I do not check to see if memory allocation succeeds when using calloc() or malloc(). Are there any other things that could or should be improved?

char int_to_char(int number){
    if (number > 9) return (char)(((int)'A') + number - 10);
    else return (char)(((int)'0') + number);
}

int change_base(char* output, int buffer_size, int decimal_number, int base){
    //check for valid parameters
    if((base < 2) || (base > 26)) return -1;        //range error

    //ready variables
    int output_i = 0;
    int tmp_string_i = 0;
    int dividend;
    char remainder;
    char * tmp_string = calloc(buffer_size, sizeof(char));
    memset(output, '\0', buffer_size*sizeof(char));

    //check for negative input
    if(decimal_number < 0){
        output[0] = '-';
        dividend = -decimal_number;
        output_i++;
    }
    else dividend = decimal_number;

    //find digits
    while(dividend / base != 0){
        remainder = int_to_char(dividend % base);
        dividend = dividend / base;
        tmp_string[tmp_string_i] = remainder;
        tmp_string_i++;
        if(tmp_string_i + 1 > buffer_size){     //+1 for the extra negative sign
            free(tmp_string);
            return -2;      //buffer size error
        }
    }
    //add last digit to string
    remainder = int_to_char(dividend);
    tmp_string[tmp_string_i] = remainder;

    //copy tmp_string to output in reverse order
    for(; tmp_string_i >= 0; tmp_string_i--){
        output[output_i] = tmp_string[tmp_string_i];
        output_i++;
    }
    free(tmp_string);
    return 0;
}

I have also used this for testing:

int main(){
    char * output = calloc(100, sizeof(char));
    int ret_val = 0;

    //test cases
    ret_val = change_base(output, 100, 37, 8);
    printf("%s\t%d\n", output, ret_val);
    ret_val = change_base(output, 100, -45, 8);
    printf("%s\t%d\n", output, ret_val);
    ret_val = change_base(output, 100, 33945877, 8);
    printf("%s\t%d\n", output, ret_val);
    ret_val = change_base(output, 100, 32, -7);
    printf("%s\t%d\n", output, ret_val);
    ret_val = change_base(output, 100, 37, 4);
    printf("%s\t%d\n", output, ret_val);
    ret_val = change_base(output, 100, 37, 23);
    printf("%s\t%d\n", output, ret_val);
    ret_val = change_base(output, 100, 37, 2);
    printf("%s\t%d\n", output, ret_val);
    ret_val = change_base(output, 100, -375212123, 26);
    printf("%s\t%d\n", output, ret_val);
    ret_val = change_base(output, 5, -375212123, 26);
    printf("%s\t%d\n", output, ret_val);
    char * output2 = calloc(5, sizeof(char));
    ret_val = change_base(output2, 5, 37, 2);
    printf("%s\t%d\n", output2, ret_val);

    free(output);
    free(output2);
    return 0;
}


texts: Directed graph similarity calculation -- optimizing Mathematica code

texts:
I am looking to optimize the following computation.  First, some explanations:

Explanation

I have a directed graph whose adjacency matrix may only contain 1s and 0s.  The similarity of nodes i and j is defined as follows:

count how many nodes have an edge pointing to both i and j, and count how many nodes do both i and j point to
divide the sum of these two counts by the total number of nodes either i or j is connected to

I need to find the maximum similarity of each node in graph (its similarity with any other node except itself), and compute the average of these numbers.

The graphs I'm working with are not necessarily connected, but they don't have components of size 1 (i.e. nodes that are not connected to any other nodes).

The code

meanMaxSim[g_Graph] :=
 Module[{am, pList, similarityMatrix},
  am = AdjacencyMatrix[g];
  pList = Transpose@Join[am, Transpose[am]];
  similarityMatrix = Outer[Total[#1 #2]/Total[Sign[#1 + #2]] &, pList, pList, 1];
  Mean[Max /@ dropDiagonal[similarityMatrix]]
]

(Sign is used to keep 0s and convert anything larger to 1s.)

This function just removes the elements on the diagonal of an n by n matrix, ending up with an n by n - 1 matrix:

dropDiagonal[matrix_] :=
 MapThread[Drop[#1, {#2}] &, {matrix, Range@Length[matrix]}]

Graph[] is only available in Mathematica 8, but this is irrelevant here as most of the time is spent in Outer[] anyway.  If you have an earlier version, just assume that you have the adjacency matrix as a SparseArray as starting point.

I am looking for modifications that speed this up significantly (more than 3x), but any other comment on the code is most welcome.  Hopefully a speedup is possible without a significant increase in code complexity.

Notes

Doing the computations with machine-numbers is okay, but I didn't bother doing that since it doesn't provide a significant speedup.

A note about self-loops: they are allowed in the graph, and yes, they're double-counted in this implementation.

EDIT:

I was too quick to ask this question.  Here's a ~4x speedup using Compile.  I'm still interested in comments / further speedups.

simMatCompiled =
  Compile[{{p, _Real, 2}},
    Table[Total[a b]/Total@Sign[a + b], {a, p}, {b, p}]
  ];

mxSim[g_Graph] :=
  Module[{am, pList, similarityMatrix},
    am = N@AdjacencyMatrix[g];
    pList = Transpose@Join[am, Transpose[am]];
    similarityMatrix = simMatCompiled[Normal[pList]];
    Mean[Max /@ dropDiagonal[similarityMatrix]]
  ]

I needed to change Outer to Table in order for Compile to be able to do its job.


texts: Program that finds the longest word not containing one of the disallowed characters

texts:
Problem definition

Find the longest word that doesn't contain any of the following characters:

gkmqvwxz

Input comes from a file named words.txt and contains one word per line. A word is anything that is not a whitespace.

The twist

My C++ implementation posted below is surprisingly slow, taking 1.7 seconds to run, whereas my javascript implementation (link, will obviously be slower because it's online) takes only 55ms. Is it possible to somehow optimize my C++ implementation?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdint>

#include "TimeUtil.h"

int main()
{
    uint64_t begin_time = currentTimeNanoseconds();

    std::string longestAcceptableWord; // Variable to contain the longest word

    std::string currentLine;
    const char badLetters[] = { 'g', 'k', 'm', 'q', 'v', 'w', 'x', 'z' };

    std::ifstream in;
    in.open("words.txt");
    while (!in.eof()) // Loop through the entire file (466 544 lines, 4 749 kB).
    {
        getline(in, currentLine);

        if (currentLine.length() <= longestAcceptableWord.length())
        {
            continue;
        }

        // If the word contains one of the bad letters, don't accept it.
        for (unsigned int i = 0; i < sizeof(badLetters); i++)
        {
            if (currentLine.find(badLetters[i]) != std::string::npos)
            {
                continue;
            }
        }

        // If the word is longer than the current longest word found,
        // and doesn't have any bad letters, make it the new longest
        // word found.
        longestAcceptableWord = currentLine;
    }
    in.close();

    std::cout << "[" << (double) ((currentTimeNanoseconds() - begin_time) / 1000) / 1000.0f << "ms] " << longestAcceptableWord << std::endl;

    return 0;
}


texts:
Basically, there is an election on 3 regions where either candidate needs to win 2 in order to win the election. Idea is to simulate 10000 elections to see which candidate wins. I think my solution works but I am not happy with the huge list of if statements and wondering of if there is a better way for this.

# Assignment simulate elections page 257

# 2 Candidates A and B

# Candidate A has following odds:
# 87% change of winning in region 1
# 65% changes of winning in region 2
# 17% changes of winning in region 3

from random import random

candidate_a_won = 0
candidate_b_won = 0

for i in range(0, 10000):
    result = random()
    candidate_a = 0
    candidate_b = 0
    if result + .87 >= 1:
        candidate_a += 1
    else:
        candidate_b += 1
    if result + .65 >= 1:
        candidate_a += 1
    else:
        candidate_b += 1
    if result + .17 >= 1:
        candidate_a += 1
    else:
        candidate_b += 1
    if candidate_a > candidate_b:
        candidate_a_won += 1
    else:
        candidate_b_won += 1

print('Candidate A won elections {} times, candidate B won elections {} times'.format(candidate_a_won, candidate_b_won))


texts: Extending react hook useState for use in event handlers

texts:
I use React with material-ui.com and I love them both, but I'm tired with writing the boilerplate handlers like

onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.currentTarget.value)}

again and again. Especially when stopPropagation is needed (AFAICT it's always either needed or harmless), it gets pretty verbose.

So I tried to extend useState so that it provides everything I need, so I can write things like:

const [email, setEmail, emailAgg] = useStateEx('');
...
onChange={emailAgg.changeHandler}

or

const [showPassword, , showPasswordAgg] = useStateEx(false);
...
onClick={showPasswordAgg.toggleHandler}

and similar.

My approach follows. I'd like it to be reviewed in general, especially for better typing (I had to use @ts-ignore) and improvements.

I case you hate semicolons, please ignore them as my eslint is set up to require them. ;)

import { useState, Dispatch, SetStateAction } from 'react';

function booleanAgg(value: boolean, setter: (value: boolean) => void, makeSetter: (value: boolean) => ((event?: any) => void)) {
    return {
        value,
        setter,
        falseHandler: makeSetter(false),
        trueHandler: makeSetter(true),
        toggleHandler: makeSetter(!value),
    };
}

function stringAgg(value: string, setter: (value: string) => void) {
    return {
        value,
        setter,
        changeHandler: (e: React.ChangeEvent<HTMLInputElement|HTMLTextAreaElement>) => {
            e.stopPropagation();
            setter(e.currentTarget.value);
        }
    };
}

function numberAgg(value: number, setter: (value: number) => void) {
    return {
        value,
        setter,
        changeHandler: (e: React.ChangeEvent<HTMLInputElement|HTMLTextAreaElement>) => {
            e.stopPropagation();
            setter(+e.currentTarget.value);
        }
    };
}

/**
 * Works like useState and adds a third element containing boolean-specific handlers directly useable in buttons and checkboxes.
 */
export function useStateEx(initialState: boolean) : [boolean, Dispatch<SetStateAction<boolean>>, ReturnType<typeof booleanAgg>];

/**
 * Works like useState and adds a third element containing string-specific handlers directly useable in text fields.
 */
export function useStateEx(initialState: string) : [string, Dispatch<SetStateAction<string>>, ReturnType<typeof stringAgg>];

/**
 * Works like useState and adds a third element containing number-specific handlers directly useable in text fields.
 */
export function useStateEx(initialState: number) : [number, Dispatch<SetStateAction<number>>, ReturnType<typeof numberAgg>];

/**
 * Prohibits use with any type not handled in the above overloads.
 */
export function useStateEx(initialState: any) : never;

export function useStateEx<S extends boolean|string|number>(initialState: S) : unknown {
    const [value, setter] = useState(initialState);
    function makeSetter(value: S) {
        return function(e: any) {
            if (typeof e?.stopPropagation === 'function') e.stopPropagation();
            setter(value);
        };
    }
    if (typeof value === 'boolean') {
        // @ts-ignore
        return [value, setter, booleanAgg(value, setter, makeSetter)]
    } else if (typeof value === 'string') {
        // @ts-ignore
        return [value, setter, stringAgg(value, setter)];
    } else if (typeof value === 'number') {
        // @ts-ignore
        return [value, setter, numberAgg(value, setter)];
    } else {
        throw new Error('Only boolean, string and number is supported');
    }
}


texts: Calculating and Outputting Pascal's Triangle with only Indices

texts:
I'm relatively new to Python, and decided to write this program that outputs Pascal's Triangle to test myself. About halfway through, I realized that it's a lot of work to find the value of Pascal's Triangle from an index instead of a (row, column) formula, and ended up taking a journey to StackExchange Math for an answer.

If anyone could provide some guidance on improving the code's readability or efficiency, I would be very appreciative. I'm sure that my code doesn't complete its task in the most pythonic way. Two specific examples of possibly inefficient code are the way that the code checks user inputs and the way that the triangle is displayed.

Thanks in advance for the help.

"""Prompts the user for a number of rows, then displays that many rows of Pascal's Triangle"""

import numpy
import math

# Used for simplifying FindValueFromIndex
def PlusOne(index):
    return numpy.floor((numpy.sqrt(8*index+1)-1)/2)
def MinusOne(index):
    return numpy.floor((numpy.sqrt(8*index+1)+1)/2)

# Finds the Value of a particular index of Pascal's Triangle
def FindValueFromIndex(index):
    return math.factorial(MinusOne(index))/(math.factorial(index-(MinusOne(index)*PlusOne(index))/2)
        *math.factorial(MinusOne(index)+(MinusOne(index)*PlusOne(index))/2-index))

# Determines whether a number is triangular
def IsTriangular(index):
    currtrinum = 0
    n=0
    while currtrinum < index:
        currtrinum += n
        n+=1
    if currtrinum != index:
        return False
    else:
        return True

# Variable Declaration
rows = 'a'
while not rows.isdigit():
    rows = input("Enter number of rows: ")
rows = int(rows)
count = rows
onesindex = []
nononesindex = 1

# The left-side ones values of Pascal's Triangle can be defined as a summation
# The right-side ones values of Pascal's Triangle can be found by subtracting one from the index from the left side
# The range starts at 2 because the first value is considered as part of the right side
for i in range(2,rows+1):
    onesindex.append(sum(range(i)))
    onesindex.append(sum(range(i))-1)

# The ones values can be populated from the onesindex values found in the previous section
# The non-one values can be calculated using the equation found in FindValueFromIndex()
triangle = [0 for x in range(sum(range(rows)))]
for i in range(len(triangle)):
    if i in onesindex:
        triangle[i] = 1
    else:
        while triangle[i] == 1 or triangle[i] == 0:
            triangle[i] = int(FindValueFromIndex(nononesindex))
            nononesindex += 1

# Prints out the result
rows -= 1
for i in range(rows-1):
    print('    ',end='')

for i in range(len(triangle)):
    print('{:^4}'.format(str(triangle[i])),end='    ')
    if IsTriangular(i+1):
        rows -= 1
        print('\n',end='')
        [print('    ',end='') for j in range(rows-1)]


texts: How to optimize population projections for speed?

texts:
I am currently working on a problem of an online judge (not a contest). The program must calculate how many years will require for the population A (which is always less than B) to be higher than B. If the time is more than a Century then print "More than a century" in Portuguese.
Input

1
90000 120000 5.5 3.5

Where 1 is the number of test cases and in the next line are the population of A, population of B, percentage growing rate of A and percentage growing rate of B. For this input the result will be 16 years.

However, my code keeps exceeding the time limit, which is only 1 second. I have used Scanner and System.out.print() however I have been told that such methods will make my code slower and will consume more memory, that is way I buffered the input and output. I cannot use types such as long or int as the data stored the variables is longer than those values.

import java.io.*;
import java.math.BigDecimal;

class Main {
    public static void main(String[] args) throws NumberFormatException, IOException{
        java.io.InputStreamReader iSR = new java.io.InputStreamReader(System.in);
        java.io.BufferedReader bR = new java.io.BufferedReader(iSR, 16 * 1024);
        BufferedWriter bW = new BufferedWriter(new OutputStreamWriter(System.out));
        String tL;
        BigDecimal PRA = BigDecimal.ZERO, PRB = BigDecimal.ZERO, PA = BigDecimal.ZERO, PB = BigDecimal.ZERO;
        int input = Integer.parseInt(bR.readLine());
        for(int j = 0; j < input; j++){
            tL = bR.readLine();
            String [] = arr = tL.split(" ");
            PA = BigDecimal.valueOf(Integer.parseInt(arr[0]));
            PB = BigDecimal.valueOf(Integer.parseInt(arr[1]));
            PRA = BigDecimal.valueOf(Double.parseDouble(arr[2]));
            PRB = BigDecimal.valueOf(Double.parseDouble(arr[3]));
            PRA = PRA.divide(BigDecimal.valueOf(100)); PRA = PRA.add(BigDecimal.ONE);
            PRB = PRB.divide(BigDecimal.valueOf(100)); PRB = PRB.add(BigDecimal.ONE);
            int i = 1;
            while(PA.compareTo(PB) < 0 && i < 103){
                BigDecimal ibd = BigDecimal.valueOf(i);
                PA = PA.multiply(PRA).multiply(ibd);
                PB = PB.multiply(PRB).multiply(ibd);
                i++;
            }
            i--;
            if(i > 100) bW.write("Mais de 1 seculo.\n");
            else bW.write(String.valueOf(i) + " anos.\n");
            bW.flush();
        }
    }
}


texts:
I am kind of new to Java and I have tried making a simple calculator. This lets you do different calculations in a row until you type done then you get the answer. It works as I expected but I was just wondering if I could get some feedback on it and how I can improve on it or what better approaches I could have taken.

This is my main class:

public class Main {
static  float Result = 0.0f;
static String input, Iteration;
static float firstInput = 0.0f;
static float secondInput;
static Calculations calculations = new Calculations();

public static void main(String[] args) {
    getFirstNumber();
    tryCatchMethod();
    calculations.sortCalc();
    outPutResult();

}

public static void getFirstNumber(){
    input = getInput("Enter the first number to work with");

}

public static void getIteration(){
    Iteration = getInput("Please enter the number");
    try {
        secondInput = Float.parseFloat(Iteration);
    } catch (NumberFormatException e) {

        input = getInput("Please enter a valid number");
        tryCatchMethod();   ////recursion, this is for when a valid number is not entered. This will continue happening until a valid number is entered.
    }
}

private static void tryCatchMethod(){

    try {
        firstInput = Float.parseFloat(input);
        Result = firstInput;
    } catch (NumberFormatException e) {

        input = getInput("Please enter a valid number");
        tryCatchMethod();   ////recursion, this is for when a valid number is not entered. This will continue happening until a valid number is entered.
    }

}

public static void outPutResult(){

    System.out.println("the result is :" + Result);
}

static String getInput(String prompt) {
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

    System.out.print(prompt);
    System.out.flush();

    try {
        return stdin.readLine();
    } catch (Exception e) {
        return "Error: " + e.getMessage();
    }
}

}

Then the class with my calculation methods:

  public class Multiplication extends Main  {

public void basicMult(){
    Result = Result * secondInput;

}

public void basicSubt(){
     Result = Result - secondInput;
}

public void  basicAdd(){
     Result = Result + secondInput;
}

public void basicDiv(){
if(secondInput == 0.0f){
    System.out.println("Cannot divide by 0");
}
else{
    Result = Result / secondInput;
}

}
}

Class to switch between each calculation:

 public class Calculations extends Main{

    Multiplication calculation = new Multiplication();
    String getCalc;

    public void sortCalc(){
         getCalc = getInput("'+' '-' '*' or '/' or 'Done'");
         calcSwitch();
    }

    private void calcSwitch(){
        switch(getCalc){
        case "+":
            getIteration();
            calculation.basicAdd();
            sortCalc();
            break;
        case "-":
            getIteration();
            calculation.basicSubt();
            sortCalc();
            break;
        case "*":
            getIteration();
            calculation.basicMult();
            sortCalc();
            break;
        case "/":
            getIteration();
            calculation.basicDiv();
            sortCalc();
        case "Done":

            break;
        case "default":
                System.out.println("That isn't a mathematical function");
                sortCalc();
            break;
        }

    }

}


texts:
I've created a Combobox GUI that allows the user to search through the Combobox by entering a letter on the keyboard. If user enter letter 'L' it will search through the Combobox drop-down list for the first occurrence of a word that starts with letter 'L'.

Please let me know if I could have made my findInBox method better. Do you know of a way to search through the drop-down list while it is open?

import tkinter
tk = tkinter

from tkinter import StringVar, Label, Button
from tkinter import font
from tkinter.ttk import Combobox

class Parking_Gui(tk.Frame):

    def __init__(self):
        """Sets up the window and widgets"""
        tk.Frame.__init__(self)

        self.myfont = font.Font(family="Calibri", size=11, weight="normal")

        self.master.geometry("315x125")
        self.master.title("MSU PARKING APP")
        self.master.rowconfigure(0, weight = 1)
        self.master.columnconfigure(0, weight = 1)
        self.grid(sticky = 'NW')

        # Label for the parking lots
        self.LotLabel = tk.Label(self, text = "MSU Parking",  font=self.myfont)
        self.LotLabel.grid(row = 0, column = 0)

        # Combo Box for parking lots
        self._ComboValue = tk.StringVar()
        self._LotCombo = Combobox(self, textvariable=self._ComboValue,
                                  state='readonly', height = '6',
                                  justify = 'center', font=self.myfont)

        # List of parking lots
        self._LotCombo['values']=('ARTX', 'BURG', 'CLAY_HALL', 'GLAB',
                                  'HAMH_HUTC', 'HHPA', 'JVIC', 'LIBR','PLSU',
                                  'POST',  'PROF', 'STEC', 'STRO_NORTH',
                                  'STRO_WEST', 'TROP')
        self._LotCombo.grid(row = 0, column = 1)

        # Button to open parking diagram
        self._button = tk.Button(self, text = "Open", font=self.myfont)
        self._button.bind('<Button-1>', self._runParkingLot)
        self._button.grid(row = 0, column = 2)

        # Press enter to open selected parking diagram
        self._LotCombo.bind("<Return>", self._runParkingLot)

        # Search Combobox with keyboard
        self._LotCombo.bind("<Key>", self.findInBox)

        self._LotCombo.focus()

    def _runParkingLot(self, event):
        """Event handler for the button. Will run the
           functinon associated with selected item"""

        parkingLot = self._LotCombo.get()

        """The 'globals' keyword, will return a dictionary of every function,
           variable, etc. currently defined within the global scope."""
        if parkingLot in globals():
            func = globals()[parkingLot]
            func()

    def findInBox(self, event):
        """findInBox method allows user to search through Combobox values
           by keyboard press"""

        alpha = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                 'U', 'V', 'W', 'X', 'Y', 'Z')

        lot = ('ARTX', 'BURG', 'CLAY_HALL', 'GLAB', 'HAMH_HUTC', 'HHPA',
               'JVIC' ,'LIBR', 'PLSU', 'POST', 'PROF', 'STEC',
               'STRO_NORTH', 'STRO_WEST', 'TROP')

        keypress = event.char
        keypress = keypress.upper()

        # If key pressed is a letter in alphabet
        if keypress in alpha:

             # if user press 'A' on keyboard return first item in list
             if(keypress == lot[0][0]):
                    self._LotCombo.current(0)

             # Searches list for first occurrence of key entered by user
             else:
                 count = 1
                 while(keypress != lot[count][0] and count < len(lot)-1 ):
                     count +=1

                 self._LotCombo.current(count)
                 count = 1

def main():
    Parking_Gui().mainloop

main()


texts: List all files matched by glob within JSON file

texts:
Based on a set of globs contained in a custom field within a package.json file, I'm trying to get a list of all the files that the glob matches. In my continual quest to get more familiar with Bluebird, I've chosen to use it to facilitate this task. What I have works, but I'm not sure if I am using the methods as intended as I always find the docs a bit mystifying.

Is there a cleaner way to do this? Could I be using these methods better?

Sample of JSON prop containing globs. I am just attempting to match the files within the variableGlobs object.

"@me": {
   "singleGlob": "path/to/single/glob/*.txt",
   "variableGlobs": {
    "glob1": "path/to/files1/*",
    "glob1": "path/to/files2/*"
   }
}

var _ = require('lodash')
  , Promise = require('bluebird')
  , globAsync = Promise.promisify(require('glob'))

const npmScope = '@me';
const nodeBase = path.join(__dirname, 'node_modules', npmScope);

function getFilenamesFromJson(){
  componentStaticAssetGlobs = Promise.map(components, componentName => {
    return extractComponentPackageJsonValue(componentName, npmScope);
  })
  .then(componentsPackageJson => {
    return Promise.map(componentsPackageJson, (singlePackage, componentIndex) => {
      return Promise.map(Object.keys(singlePackage[npmScope].staticAssetGlobs), (staticAssetKey, assetIndex) => {
        return globAsync(path.join(nodeBase, componentsPackageJson[componentIndex].componentName, singlePackage[npmScope].staticAssetGlobs[staticAssetKey]));
      })
    })
  })
  .then(staticAssetFiles => {
    staticAssetFiles = _.flattenDeep(staticAssetFiles);
    console.log('staticAssetFiles', staticAssetFiles); //array of files
  });
}

//returns object that always has component name
function extractComponentPackageJsonValue(componentName, property) {
  let packageJsonLocation = path.join(nodeBase, componentName, 'package.json');
  return fs.readFileAsync(packageJsonLocation, 'utf8')
    .then(jsonData => {
      jsonData = JSON.parse(jsonData);
      var tempObj = {componentName: componentName};
      tempObj[property] = jsonData[property]
      return tempObj;
    });
}


texts:
I wrote the following script in the hopes of streamlining the finding and reading of multiple manual pages. Since I am always looking up different utilities' manual pages I thought this would a good learning aid.

#!/bin/bash

while true
do
    echo
    echo "1) /bin"
    echo "2) /sbin"
    echo "3) /usr/bin/"
    echo "4) /usr/sbin"
    echo "5) /usr/local/bin"
    echo "6) /usr/local/lib"
    echo "7) /usr/local/share"
    echo "8) /usr/local/include"
    echo "9) exit"
    echo
    read -p 'Select a directory ' d
    if [[ $d = 1 ]]; then
        dir=/bin
    elif [[ $d = 2 ]]; then
        dir=/sbin
    elif [[ $d = 3 ]]; then
        dir=/usr/bin
    elif [[ $d = 4 ]]; then
        dir=/usr/sbin
    elif [[ $d = 5 ]]; then
        dir=/usr/local/bin
    elif [[ $d = 6 ]]; then
        dir=/usr/local/lib
    elif [[ $d = 7 ]]; then
        dir=/usr/local/share
    elif [[ $d = 8 ]]; then
        dir=/usr/local/include
    elif [[ $d = 9 ]]; then
        exit
    else
        echo 'No such directory'
        exit 1
    fi
    echo
    while true
    do
        menu=( $(ls -1 ${dir}) )
        i=0
        for m in ${menu[@]}
        do
            echo "$(( i++ ))) $(basename $m)"
        done | xargs -L3 | column -t
        echo
        echo 'Select from the list above'
        echo 'Type b to go back to main menu'
        read -p 'Type q to quit at anytime ' n
        echo
        if [[ $n = 'b' || $n = 'B' ]]; then
            break 1
        elif [[ $n = 'q' || $n = 'Q' ]]; then
            exit
        else
            for item in ${menu[$n]}
            do
                if [[ $item =~ '.txt' ]]; then
                    item="$(echo ${item%.*})"
                fi
                man $item
            done
        fi
    done
done

One thing I should point out. My /usr/local/bin directory has several .txt files. That is the reason for if [[ $item =~ '.txt' ]]; then item="$(echo ${item%.*})"; fi Maybe it is normal to have plain text files in this directory or maybe this is something I did unintentionally when experimenting writing this script. (An earlier version of this script wrote all the man pages to plain text files.) I really don't know but that's why that part of the script is there.

I think this script does what I hoped it would do so now I would like other people's opinion. Is there anything I could do better? Am I overlooking anything?


texts:
Just completed a /r/dailyprogrammer challenge. Challenge #238 to be precise.

A Github repository with the wordbank.txt is available here.

import random

difficulty = {1: [4, 5, 6], 2: [7, 8],
              3: [9, 10, 11], 4: [12, 13],
              5: [14, 15]
              }
#Keys are the various word lengths for each difficulty (1-5).
acceptedWord = []
#Start a blank list, used in getWords()

def getWords():
    while True:
        try:
            level = int(input("What difficulty would you like? (1,2,3,4,5) "))
            break
        except (ValueError, KeyError):
            print("That is not a number")
    #Take a numerical input from the user, attempt to parse it, if it fails, carry on the loop.
    num = random.choice(difficulty[level])
    #num (used to store word lengths) is a random choice from the available lengths for the selected difficulty.
    with open('wordbank.txt', 'r') as file:
        #Open the file containing word-bank
        for x in map(str.upper, map(str.strip, file.readlines())):
            #loop over the stripped down words
            if len(x) == num:
                acceptedWord.append(x)
                 #If length of word is equal to random choice from suitable lengths, add it to a list.

    #Random index from total number of items in list.
    answers  = random.sample(acceptedWord, num)
    #picks a selection of the available words. Amount of words = word length.
    trueWord = answers[random.randint(0, len(answers)-1)]
    #trueWord = answer. Random item of the shortlisted avaliable words
    print('\n'.join(answers))
    #Prints hints.
    game(trueWord)

def game(trueWord):
    for x in range(0,5):
        #The user has 5 guesses
        print("Guesses Left: ", 5-x)
        userInput = input("Guess: ").upper()
        #All guesses/inputs are parsed to uppercase.
        userList = list(userInput)
        #List of the letters the user inputed
        trueList = list(trueWord)
        #List of letter of
        if userInput == trueWord:
            print("Well done, you guessed correctly")
            getWords()
            #If the user enters the correct word, quit the program
        correctGuess = 0
        for item in list(userList):
            #for each letter the user inputed
            if item == trueList[userList.index(item)]:
                #if the letter is in the same position as the answer
                correctGuess += 1
                #increment the correct amount of letters by 1
        print(correctGuess, "out of ", len(trueList), "correct.")
    print("Bad luck! The answer was: ", trueWord)
    getWords()

getWords()


texts: Multiply vector elements by a scalar value using STL and templates

texts:
I wrote a small scientific simulation where I wanted to manipulate vectors with the same kind of functionality that Python's NumPy vectors use. Namely, I wanted to be able to add vectors together, multiply by constants, etc. I have need for both vectors of type int and floating point, so I wanted to template the overloading. As an example (and for something to review), I overloaded scalar multiplication as:

template <class T, class Q>
vector <T> operator*(const Q c, const vector<T> &A) {
  vector <T> R(A.size());
  for(int i=0;i<A.size();++i)
    R[i] = c*A[i];
  return R;
}

The STL algorithm way I hinted at looks like this:

template <class T, class Q>
vector <T> operator*(const Q c, const vector<T> &A) {

  vector <T> R(A.size());
  std::transform(A.begin(), A.end(), R.begin(),
                 std::bind1st(std::multiplies<T>(),c));
  return R;
}

I would appreciate all criticism relevant to code, style, flow. My project is in C++11, so in theory I could use the newer range-based for loops for readability (I do in other parts of my code). Additionally, I think I could rewrite this using std::transform, but I'm not sure if it would help improve the efficiency or the readability of my code.


texts: List of previous and upcoming months to a given date (year and month)

texts:
I need a menu with buttons of months previous and after a given month,
something like this:

| month | month | month | current month | month | month | month |

Can this function further be improved?

/**
* Generates array of months previous and after given date
* @param $p_base_data       - array of base year and months,
         if not provided current date is used ['year'=>false, 'month'=>0]
* @param $p_nr_prev_months - number of previous mounts to calculate
* @param $p_nr_post_months - number of upcoming mounts to calculate
* @return populated array
*/

function buildListOfMonths( array $p_base_date = ['year'=>false, 'month'=>0],
                            int $p_nr_prev_months = 5,
                            int $p_nr_post_months = 6) : array
{
    // init var
    $months_list    = [];
    // setting base year and date if parameter not passed
    $base_year  = $p_base_date['year'] ? $p_base_date['year'] : date('Y');
    $base_month     = $p_base_date['month'] > 0
        ? (int)$p_base_date['month']
        : date('n');

    // looping through prev to post number of months
    for ($i = -$p_nr_prev_months; $i <= $p_nr_post_months; $i++) {
        // creating date object of actual date
        $date_obj       = strtotime(date($base_year.'-'.$base_month.'-01')." +$i months");
        // building array of months
        $months_list[]  = [ 'year'       => date('Y', $date_obj),
                               'nr_month'   => date('n', $date_obj),
                               'month_name' => date("M", $date_obj),
                               'current'    => (date('n', $date_obj) == $base_month) ? true : false ];
    } // end for

    return $months_list;
} // end func.


texts: Alternative to clicklistener inside an anonymous class

texts:
For a trivial word game, I wrote the following code for the player to choose one of the two choices of words that in turn were read from a sentence.

My question lies in first in the click-listener of the buttons of the choice.

The main code, in Java:

private void initAnswerButtons() {

    //2. here
    if (questionNum == wordList.size()){
        return;
    }
    String s = wordList.get(questionNum);
    String[] choices = s.split("/");
    int numOfChoices = choices.length;
    for (int i=0; i<numOfChoices ; i++)
    {
        choiceButton[i] = new TextButton(choices[i], skin, "default");
        choiceButton[i].setPosition( 20 + i*120, app.camera.viewportHeight - 200);
        choiceButton[i].setSize(100, 50);
        choiceButton[i].addListener(new ClickListener() {

            //1. here
            @Override
            public void clicked(InputEvent event, float x, float y) {
                if (questionNum == wordList.size()){
                    return;
                }
                questionNum++;
                initAnswerButtons();
            }
       });
       stage.addActor(choiceButton[i]);
    }

}

The wordList array which I have hard-coded for:

private void initWordlist() {
    wordList = new ArrayList<String>();
    wordList.add("nyumba/humba");
    wordList.add("ya/za");
    wordList.add("mji/kijiji");
    wordList.add("yake/hiki");
    wordList.add("ni sa udongo/si sa mawe");
}

The first question (see "1.here"): I am using a click-listener which is in the form of an anonymous class. As a result, I check whether I have run out of questions, i.e. if (questionNum == wordList.size()). If NOT so, it goes to the next question i.e. questionNum++ and then:

initAnswerButtons();

I callback the method itself, yes, recursively from inside the method. What would you do instead to avoid such a structure?

Second question: in order to avoid running out of questions and out of range of the wordList array, I put an if-check (see "2. here"). That doesn't look good either, but that is also a natural consequence of the present structure of the code.

So, what would you do instead?


texts: Year with the most living (given a list of births and deaths)

texts:
I am trying to find the year most people are alive, given a list of births and deaths.  I am not sure my approach is optimal or if am calculating the time complexity correctly

Break down:
I sort the dates
O(n log n)
I walk the dates in order
O(b + n log n)

Hashing the births, because they pivot the shifts between the number of living from those already dead. Since a birth year will be the year in which most people lived.

I am also pushing the deaths into a common array.

I then loop over the deaths
O(n^2 + n log n)

grabbing the count of those deceased and subtracting that from those still alive, and resting the array with those still alive on every iteration.

finally, I loop over the hash results to get the highest result.
with a final time complexity after dropping all constants

O(n+m) or O(n^2)

const people = [{ birth: 1720, death: 1860 },{ birth: 1720, death: 1860 },{ birth:1803, death: 1809},{ birth: 1730, death: 1810 },{ birth: 1920, death: 1950 },{ birth: 1930, death: 1940 },{ birth: 1940, death: 1990 }, { birth: 1970, death: 2010 }]
function yearMaxAlive(people) {
  people.sort((a, b) => a.birth - b.birth)
  let high = {
      year: 0,
      count: 0
    },
    alive = 0,
    survivors = [];
  for (let [year, count] of Object.entries(people.reduce((deaths => (ledger, year) => {
      if (ledger[year.birth]) {
        alive++
        ledger[year.birth].alive = alive
      } else if (!ledger[year.birth]) {
        if (deaths.length > 0) {
          let deleted = deaths.filter((a, i, aa) => {
            if (a <= year.birth) {
              return true
            } else {
              survivors.push(a)
              return false
            }
          })
          deaths = survivors
          survivors = []
          alive = alive - deleted.length
          alive++
          ledger[year.birth] = {
            alive: alive,
            deaths: deaths
          }
        } else {
          alive++
          ledger[year.birth] = {
            alive: alive,
            deaths: deaths
          }
        }
      }
      deaths.push(year.death)
      return ledger
    })([]), {}))) {
    if (high.count < count.alive) {
      high = {
        year: year,
        count: count.alive
      }
    }
  }
  return high
}

console.log(yearMaxAlive(people))


texts: Remove specific CSS rules from WYSIWYG text

texts:
I have created a working function for cleaning some specific styles within the text from a WYSIWYG editor.

  var rulesText = textArea.value;

  var selector = "a:link, span.MsoHyperlink";
  var pattern = new RegExp(selector.replace(/\./g, "\\.") + "\\s*{[^}]*?}", "gim");

  rulesText = rulesText.replace(pattern,"");

  var nextSelector = "a:visited, span.MsoHyperlinkFollowed";
  var nextPattern = new RegExp(nextSelector.replace(/\./g, "\\.") + "\\s*{[^}]*?}", "gim");

  rulesText = rulesText.replace(nextPattern,"");

  textArea.value = rulesText;

  console.log("FIRED!");

Here are the styles being cleaned:

a:link, span.MsoHyperlink
{mso-style-unhide:no;
color:blue;
text-decoration:underline;
text-underline:single;}

a:visited, span.MsoHyperlinkFollowed
{mso-style-noshow:yes;
mso-style-priority:99;
color:purple;
mso-themecolor:followedhyperlink;
text-decoration:underline;
text-underline:single;}

This solution seems a bit wonky to me... And I feel like there is definitely more room for elegance. How can improve on this, possibly combine the two RegExp instances, and make sure that multiple instances of this are being removed?


texts:
The code calculates a n-bonnaci sequence to a certain number, based on the user's input. It then can print it to a file and/or print it to the console.

The calculateSequence function calculates the sequence. The first loop fills the sequence with ones (0, 1, 1, 2...). Next, it calculates the value of the current number, using crrntVlue as a placeholder, and using i as the location of the value to add (a number is the sum of the preceding two numbers). sqnceItratr is location of the number that is being calculated.

My questions are:

Is there anything immediately wrong that you see in the code?
How can I make the code more readable/better variable names, as it was hard to understand the code while coding it?
How can I restructure the program to make it better?

This is one of my first Python programs, so I want to know what I might be coding 'wrong'.

def calculateSequence(n, amntToCalc):
    sqnceItratr = 1
    sequence = [0] * numbrsToCalc

    #Add 1's to the array(Duonacci is 1, 1, 2... Tribonacci is 1, 1, 1, 3...)
    while sqnceItratr < n:
        sequence[sqnceItratr] = 1
        sqnceItratr += 1

    #Actually Calculate the Sequence
    while sqnceItratr < numbrsToCalc:
        i = N
        #i is the location of the amount to add to crrntVlue
        #Ex: sequence[3] = 1 + 1 + 1 = 3, i is sequence[3 - 1]

        crrntVlue = 0
        while i > 0:
            #This is to calculate the actual value of a number
            #in the sequence
            crrntVlue += sequence[sqnceItratr - i]
            i -= 1
            #Count Down for the number to add to crrntValue(n-bonnacci)

        sequence[sqnceItratr] = crrntVlue
        # Add crrntValue to the array
        sqnceItratr += 1
        #Continue to the next value in the array
    return sequence

def convertInput(inputToConvert):
    inputToConvert = inputToConvert.upper()
    if inputToConvert == 'Y':
        return True
    elif inputToConvert == 'YES':
        return True
    else:
        return False

N = int(input("What do you want to n in N-bonnacci to be? \n"))
numbrsToCalc = int(input("How many digits do you want to calculate? \n This should probably be bigger than n \n"))
sequence = calculateSequence(N, numbrsToCalc)

userInput1 = convertInput(input("Do you want to write it to a file? \n"))
sequencePosition = 0
if userInput1 == True:
    file = open("Seqence.txt", "w")
    while sequencePosition < len(sequence):
        file.write(str(sequencePosition + 1) + ': ' + str(sequence[sequencePosition]) + '\n')
        sequencePosition += 1
    file.close()

userInput2 = convertInput(input("Do you want to print it out? \n"))
if userInput2 == True:
    sequencePosition = 0
    while sequencePosition < len(sequence):
        print(str(sequencePosition + 1) + ': ' + str(sequence[sequencePosition]))
        sequencePosition += 1


texts:
I am stuck on recursive selection of the objects for TreeView.

I have some class IMenuDataSet, that stores objects, named 'I' in the List property:

public partial class IMenuDataSet
{
    private List<I> itemsField = new List<I>();

Each 'I' object has XDocument doc and public IT[] T properties:

public partial class I
{

    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public XDocument doc;
    public IT[] T

And IT object is

public partial class IT
{

    private string nField;

    private string valueField;

IT object is a part of serialized XML, that could looks like

<?xml version="1.0" encoding="UTF-8"?>
<I c="PieMenuCategory" i="pie_menu_category" m="abc" n="someM" s="16312547127249792256">
  <T n="_collapsible">False</T>
  <T n="_display_name">0x3F70BCAA</T>
  <T n="_parent">12342647638224932948</T>
</I>

An important note: each XML file (each IT object) has s attribute, the value of this attribute is ID of the I tag (IT object).
ID of the parent element stored in T tag, that has attribute n="_parent" .
Each main (top/root) hasn't such <T n="_parent"> tag.

I need to build TreeView with LINQ query, something like an example in the How to use Linq to Xml to get tree data with recursive querying?

var dataSource = (from results in ids.Items.Descendants("nodeObject")
                                  select new nodeObject
                                  {
                                      nodeName = results.Element("nodeName").Value.ToString(),
                                      nodeChildren = this.GetChilden(results)
                                  });

Currently, my solution is

            List<I> xi = (from c in ids.Items
                          where !(
                                    from b in c.T.ToList()
                                    select b.n
                                  ).Contains("_parent")
                          select c
                 ).ToList<I>();

            foreach (I iobj in xi)
            {
                String nameId = iobj.T.ToList()
                    .Where(zxc => zxc.n.Equals("_display_name"))
                    .First().Value;

                uint elNameUint = Convert.ToUInt32(nameId, 16);
                String elName = translations[elNameUint];

                TreeNode treeNode = new TreeNode(elName);
                treeNode.Tag = iobj.rie.Instance;

                treeView1.Nodes.Add(treeNode);
            }

            xi = (from c in ids.Items
                  where (
                            from b in c.T.ToList()
                            select b.n
                          ).Contains("_parent")
                  select c

                ).ToList<I>();

            while (xi.Count > 0)
            {
                foreach (I iobj in xi)
                {
                    String nameId = iobj.T.ToList()
                        .Where(zxc => zxc.n.Equals("_display_name"))
                        .First().Value;

                    String parentId = iobj.T.ToList()
                       .Where(zxc => zxc.n.Equals("_parent"))
                       .First().Value;

                    uint elNameUint = Convert.ToUInt32(nameId, 16);
                    String elName = translations[elNameUint];

                    TreeNode treeNode = new TreeNode(elName);
                    treeNode.Tag = iobj.rie.Instance;

                    TreeNode ttmp = FindNode(treeView1.Nodes, parentId);
                    if (ttmp != null)
                    {
                        ttmp.Nodes.Add(treeNode);
                        xi.Remove(iobj);
                        break;
                    }
                }
            }

            treeView1.ExpandAll();

But I think, that my solution with breaks isn't a very  clean solution and I was hoping to figure out a more elegant solution using LINQ


texts: A possibly-terrible alternative to conditionals full of null checks

texts:
I am always super annoyed when I have to write a bunch of if statements whenever I have to traverse an object graph of possibly null objects. As there is not yet a ?. operator I resorted to creating this wonderful piece of work: TryGetProperty. Please tear it apart. This was written for LINQPad.

public bool TryGetProperty<TInstance, TFinal>(TInstance instance, Expression<Func<TInstance, TFinal>> propertyAccessor, out TFinal output)
{

    var currentExpression = propertyAccessor.Body as MemberExpression;
    var stack = new Stack<PropertyInfo>();
    do
    {
       stack.Push(currentExpression.Member as PropertyInfo);
    } while((currentExpression = currentExpression.Expression as MemberExpression) != null);

    var failed = false;

    object currentObject = instance;
    while(!failed && stack.Count > 0 )
    {
        currentObject = stack.Pop().GetMethod.Invoke(currentObject, null);
        failed = currentObject == null && stack.Count != 0;
    }

    output = failed ? default(TFinal) : (TFinal) currentObject;
    return !failed;
}

Example call from the same file.

void Main()
{
    List<Class1> instances = new List<Class1>
    {
        new Class1(),
        new Class1
        {
            Class2 = new Class2
            {
                Class3 = new Class3
                {
                    AProperty = "not null"
                }
            }
        },
        new Class1
        {
            Class2 = new Class2
            {
                Class3 = new Class3()
            }
        }
    };

    string propertyToGet;

    foreach(var instance in instances)
    {
       if(TryGetProperty(instance, c => c.Class2.Class3.AProperty, out propertyToGet) && propertyToGet != null)
       {
            "Yay!".Dump();
       }
       else
       {
            "Boo!".Dump();
       }
    }
}

public class Class1
{
    public Class2 Class2{ get; set; }
}

public class Class2
{
    public Class3 Class3 { get; set; }
}
public class Class3
{
    public string AProperty { get; set; }
}


texts: Command line tool for Italian language studies

texts:
I made a small command line tool to help my Italian studies. Any thoughts on how it could be improved? I can't think of much but would like to be proved wrong.

import random

class RegularVerb(object):
    def __init__(self, name):
        self._name = name

    def name(self):
        return self._name

    def _make(self, verb_end):
        return self.name()[:-3] + verb_end

    def _build_condizionale_semplice(self, verb_forms, prefix):
        def verb_base(prefix):
            return (prefix + condizionale_semplice_base
                    for condizionale_semplice_base in
                    ['rei', 'resti', 'rebbe', 'remmo', 'reste', 'rebbero']
                   )
        return dict(zip(verb_forms, verb_base(prefix)))

class EreVerb(RegularVerb):
    def __init__(self, name, verb_forms):
        super(EreVerb, self).__init__(name)
        self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'e')

    def condizionale_semplice(self, verb_form):
        return self._make(self._condizionale_semplice[verb_form])

class IreVerb(RegularVerb):
    def __init__(self, name, verb_forms):
        super(IreVerb, self).__init__(name)
        self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'i')

    def condizionale_semplice(self, verb_form):
        return self._make(self._condizionale_semplice[verb_form])

class AreVerb(RegularVerb):
    def __init__(self, name, verb_forms):
        super(AreVerb, self).__init__(name)
        self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'e')

    def condizionale_semplice(self, verb_form):
        return self._make(self._condizionale_semplice[verb_form])

class Questioner():

    def __init__(self, verb_forms, verbs):
        self._verb_forms = verb_forms
        self._verbs = verbs

    def _handle_answer(self, user_answer, correct_answer):
        if user_answer == correct_answer:
            print "bravo!"
        else:
            print "no, correct form is:", correct_answer

    def ask_random_condizionale_semplice(self):
        def ask(verb_form, verb):
            print "condizionale semplice for {0} in {1}?".format(verb.name(), verb_form),
            self._handle_answer(raw_input(), verb.condizionale_semplice(verb_form))
        ask(random.choice(self._verb_forms), random.choice(self._verbs))

def build_regular_verbs(verbs, verb_forms):
    def make(verb):
        if verb[-3:] == 'are':
            return AreVerb(verb, verb_forms)
        elif verb[-3:] == 'ire':
            return IreVerb(verb, verb_forms)
        elif verb[-3:] == 'ere':
            return EreVerb(verb, verb_forms)
        else:
            raise Exception("not a regular verb")
    return [make(v) for v in verbs]

def build_questioner(verb_forms, regular_verbs):
    return Questioner(verb_forms,
                      build_regular_verbs(
                        regular_verbs,
                        verb_forms
                      )
                     )

if __name__ == "__main__":
    questioner = build_questioner(
                        ['I sg', 'II sg', 'III sg', 'I pl', 'II pl', 'III pl'],
                        ['passare', 'mettere', 'sentire'],
                       )
    while True:
        questioner.ask_random_condizionale_semplice()


texts: Idiomatic ruby to calculate distance to points on a graph

texts:
Can this code be made more like idiomatic ruby using methods such as map or inject?

@random_tour is a variable length array of points on a graph:
[[0, 0], [2, 1], [4, 3]]

I want to calculate the distance to reach each point using the manhattan distance (number of moves horizontally + number of moves vertically).

For example, starting at [0, 0] - the next point [2, 1] is 2 moves horizontally, 1 move vertically which is 3 moves. The next point is [4, 3] which is 4 moves away from the last. Total number of moves is 7.

def cost
  i = 0
  total_cost = 0
  while i < @random_tour.length - 1 do
    total_cost += (@random_tour[i + 1][0] - @random_tour[i][0]).abs + (@random_tour[i + 1][1] - @random_tour[i][1]).abs
    i += 1
  end
  total_cost
end


texts: Extending method chaining IEnumerable with Add..If

texts:
I'm trying to write an extension (method chaining) for playing around a bit.
What I made work is an extension to add an item to the list (what is pretty easy):
IEnumerable<int> myList = originalList.Add(12);

What I now want to do is:
IEnumerable<int> myList = originalList.Add(12).If((list, @new) => !list.Contains(@new));

What it should do:
If the originalList doesn't already contain @new (12), then it may not add it to the list.
If the If-sequence is not added, the element gets added.
So this is my code:

public static class EnumerableExtension
{
    public static IAddEnumerable<T> Add<T>(this IEnumerable<T> @this, T element)
        => new AddEnumerable<T>(@this, element);

}

public interface IAddEnumerable<T> : IEnumerable<T>
{
    IEnumerable<T> If(Func<IEnumerable<T>, T, bool> expression);
}

internal class AddEnumerable<T> : IAddEnumerable<T>
{
    private IEnumerable<T> _sequence;
    private readonly T _elementToAdd;

    private bool _added;

    public AddEnumerable(IEnumerable<T> sequence, T elementToAdd)
    {
        _sequence = sequence;
        _elementToAdd = elementToAdd;
    }

    public IEnumerable<T> If(Func<IEnumerable<T>, T, bool> expression)
    {
        _added = true;

        if (expression(_sequence,_elementToAdd))
            _sequence = _sequence.AddItem(_elementToAdd);

        return this;
    }

    public IEnumerator<T> GetEnumerator()
    {
        if (_added)
            return _sequence.GetEnumerator();

        _sequence = _sequence.AddItem(_elementToAdd);
        _added = true;

        return _sequence.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        if (_added)
            return _sequence.GetEnumerator();

        _sequence = _sequence.AddItem(_elementToAdd);
        _added = true;

        return _sequence.GetEnumerator();
    }
}

It works, but I wanted to ask, if there are any problems that could come up with, or if there is something I could do better.


texts: Helper for DropDownLists with extension method

texts:
Is the following helper idiomatic ASP.NET MVC? All the built-in DropDownListFor helpers only accept IEnumerable<SelectListItem>. If the Model doesn't have this list, but an IEnumerable<SomeEntity>, avoiding this conversion in the Razor template seems to require some more of its helpers.

namespace CompanyName.ProjectName.PresentationLayer.Helpers
{
    // ...documentation omitted...
    public static MvcHtmlString DropDownListFor<TModel, TElem>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, string>> expression,
        IEnumerable<TElem> elements,
        Func<TElem, string> valueFunc,
        Func<TElem, string> textFunc
    )
    {
        ModelMetadata metadata =
            ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        IEnumerable<SelectListItem> items =
            elements.Select(elem => new SelectListItem()
            {
                Value = valueFunc(elem),
                Text = textFunc(elem),
                Selected = elem.Equals(metadata.Model)
            });

        return htmlHelper.DropDownListFor<TModel, string>(expression, items);
    }
}


texts: Creating Two-Dimensional String Array for Plane Seats

texts:
I'm creating a ticket reservation system in Java, I want to use a Two-dimensional String array for managing the seats. I have enums that hold the plane model and the amount of seats available so the array pulls the rows and columns from there. I just want to see efficient my code is and how can I improve it.
    public String[][] createSeatArray() {
    String[] alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r"
            ,"s","t","u","v","w","x","y","z","aa","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk","ll","mm","nn","oo","pp"};

    String[][] seatArray = new String[this.getNumOfRows()][this.getNumOfColumns()];
    int alphabetPos = 0;
    for(int i = 0; i < this.getNumOfRows(); i++) {
        for (int j = 1; j <= this.getNumOfColumns(); j++){
            String columnToString = String.valueOf(j);
            seatArray[i][j-1] = alphabet[alphabetPos] + columnToString;

            if (this.getNumOfColumns() == 4) {
                if (j == 2) {
                    System.out.print(seatArray[i][j-1] + "       ");
                } else {
                    System.out.print(seatArray[i][j-1] + " ");
                }
            } else {
                if (j == 3) {
                    System.out.print(seatArray[i][j-1] + "       ");
                } else {
                    System.out.print(seatArray[i][j-1] + " ");
                }
            }
        }
        System.out.println("\n");
        alphabetPos++;
    }
    return seatArray;
}

Thank you for any feedback! also keep in mind that if the indentation is off it may be due to bringing it over to stack overflow, on intellij it's perfect.


texts: Program to tell which if any of three numbers is in the middle

texts:
I wrote this program, and it does what it asks, but it's so big and ugly. What can I change?

Some examples:

a  b  c --->
5  1  12   a is between b and c
5  12 1    a is between c and b
5  5  2    there is no gap

This was in an example of a test that is supposed to be small, so that's why I'm asking if there is another way.

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

int main (void){
int a,b,c;

printf("Inserir 3 números: "); //its in portuguese, insert 3 numbers
scanf("%i %i %i",&a,&b,&c);

if(a==b||b==c||a==b){
    printf("não há intervalo\n"); //there is no gap
    exit(0);
}

int maior, meio, menor,flag,flag2,flag3;

maior=a; //maior means biggest
flag=1;
if(maior<b){
    maior=b;
    flag=2;
}if(maior<c){
    flag=3;
    maior=c;
}

if(maior!=a){
    meio=a;  //meio means middle
    flag2=1;
    if(meio<b&&b<maior){
        meio=b;
        flag2=2;
    }if(meio<c&&c<maior){
        flag2=3;
    }
}else{
    meio=b;
    flag2=2;
    if(meio<c&&c<maior){
        flag2=3;
    }
}

menor=a; //menor means smallest
flag3=1;
if(menor>b){
    menor=b;
    flag3=2;
}if(menor>c){
    flag3=3;
}

if(flag2==1)
    printf("o a entre [");
if(flag2==2)
    printf("o b entre [");
if(flag2==3)
    printf("o c entre [");

if(flag3==1)
    printf("a e ");
if(flag3==2)
    printf("b e ");
if(flag3==3)
    printf("c e ");

if(flag==1)
    printf("a]\n");
if(flag==2)
    printf("b]\n");
if(flag==3)
    printf("c]\n");

return 0;
}


texts:
I am trying to create an application that on the front end presents the user with a text editor to input code into and then I will run that code and return the result. I thought it would be a fun project to try and build my own version of leetcode as a learning project.
Right now this is what I am doing to run the provided code. Let's say we are running python code, because that's all I have implemented right now.
First I take in the code that the user submits and create an a file that contains the given code:
std::string python(std::string code){
    std::string langCommand = "python3 ";
    std::string outFile;

    //I am hoping to parallelize this operation so I add threadID to output
    outFile = createOutFileName("PythonRunner.py");

    std::ofstream output;
    output.open(outFile);
    output << code;
    output.close();
    return langCommand + outFile;
}

The next thing I do is create an output file and run the previously created file but I send my stdout/stderr to another outputfile:
std::string Program::run(){
    std::string command = createFile(this->lang, this->code);

    this->outputFile = createOutFileName("output.txt");

    std::stringstream newCommand;
    newCommand << command;
    newCommand << ">> ";
    newCommand << outputFile;
    newCommand << " 2>&1";

    system(newCommand.str().c_str());
    std::string output = getOutputFileData(this->outputFile);
    cleanupFiles(command);
    return output;
}

Finally I return whatever I got from my output file and that is how I am executing my code.
I gotta think there is an easier way to do this. Especially since I am doing so much writing to a file and then reading from it is there anyway to get rid of that?
I also want to include more than one language in the future so I don't want to use any libraries that are specific to a certain language.
Lastly, this is my first C++ project so I would love any C++ tips!
Edit: I do want to eventually parallelize this code and find some way to encapsulate the program so it can't damage the system it is running on. If there is maybe some external program that would be good for that let me know and also gives me its stderr/stdout let me know.
Edit: As someone asked, here is the entire repo
https://github.com/lkelly93/coderunner


texts:
This is how I posted a method from C to Swift. I tested it well, it seems to work. It's there a way to write this better, following good practices of Swift? The original is in C and the target must be in Swift.

Original C Code:

inline float mac(const float *a, const float *b, unsigned int size)
{
    float sum = 0;
    unsigned int i;

    for (i = 0; i < size; i++)
        sum += (*a++) * (*b++);
    return sum;
}

and the translation to Swift:

func mac(a : [Float], b : [Float], size : Int) -> Float
{
    var sum : Float = 0;

    for (var i = 0; i < size; i++){
        sum += (a[i]) * (b[i]);
    }
return sum;
}


texts: Returns values for a specific array and key

texts:
This PHP (5.3) code is intended to take an array and a key as inputs, and return an array of the values paired with that key‡

function valuelist($array, $array_column) {
    $return = array();
    foreach($array AS $row){
        $return[]=$row[$array_column];
    };
    return $return;
};

Can this be improved in terms of processing speed?

‡-For example, given:

$get_role_action = array(
    array("ACTION_CD" => "RETURN_PETITION"),
    array("ACTION_CD" => "UNLOCK_RECORD"),
    array("ACTION_CD" => "ACKNOWLEDGE"),
    array("ACTION_CD" => "REQUEST_POST_ACTION"),
    array("ACTION_CD" => "CHANGE_REQUEST_TYPE")
);

$variables['role_action_list']=valuelist($get_role_action, 'ACTION_CD'); should yield:

["role_action_list"]=>
    array(17) {
    [0]=>
    string(15) "RETURN_PETITION"
    [1]=>
    string(13) "UNLOCK_RECORD"
    [2]=>
    string(11) "ACKNOWLEDGE"
    [3]=>
    string(19) "REQUEST_POST_ACTION"
    [4]=>
    string(19) "CHANGE_REQUEST_TYPE"
}


texts:
The code is an implementation of looping text (similar to a circular buffer - wraps around when it reaches the edge of the defined bounds) with directional control.

The code is functional and works as intended, but I'm curious if there is anyway to improve the code even if it is only a small improvement (e.g. less garbage produced per loop cycle as a micro-optimisation, etc).

using System;
using System.Text;
using System.Threading;

namespace LoopingTextScroll
{
    internal class Program
    {
        private enum Direction
        {
            LeftToRight = -1,
            RightToLeft = 1
        }

        private static StringBuilder PadText(string text, int padding = 5)
        {
            var stringBuilder = new StringBuilder(text);
            stringBuilder.Append(new string(' ', padding));
            return stringBuilder;
        }

        private static void ShiftText(StringBuilder textBuilder, Direction direction)
        {
            var directionOffset = (int)direction;
            var textLength = textBuilder.Length;

            switch (direction)
            {
                case Direction.LeftToRight:
                {
                    for(var i = textLength - 1; i >= 0; i--) textBuilder[i] = textBuilder[Modulo(i + directionOffset, textLength)];
                    break;
                }

                case Direction.RightToLeft:
                {
                    var firstElement = textBuilder[0];
                    for(var i = 0; i < textLength; i++) textBuilder[i] = textBuilder[Modulo(i + directionOffset, textLength)];
                    textBuilder[textLength - 1] = firstElement;
                    break;
                }
            }
        }

        private static void UpdateLoop(string text, Direction direction = Direction.LeftToRight, int updateRate = 100)
        {
            var textBuilder = PadText(text);

            while (true)
            {
                ShiftText(textBuilder, direction);
                Console.Write($"\r{textBuilder}");
                Thread.Sleep(updateRate);
            }
        }

        private static int Modulo(int x, int m)
        {
            var remainder = x % m;
            return remainder < 0 ? remainder + m : remainder;
        }

        public static void Main(string[] args)
        {
            UpdateLoop("Beautiful Lie", Direction.RightToLeft);
        }
    }
}


texts: Compare data within an interval and draw rectangles accordingly

texts:
I have an interval array like below:

var interval = [[1], [1,3], [3,5], [5,7], [7,9], [9]];

I want to compare an input value say 1.5 with in the interval, and create an array drawData = [0,1,0,0,0]. To do this, i'm using a if loop like below:

            if(attr.freq < interval[0]){
                freqData = [0,0,0,0,0];
            }
            if(attr.freq >= interval[1][0] && attr.freq < interval[1][1]){
                freqData = [1,0,0,0,0];
            }
            if(attr.freq >= interval[2][0] && attr.freq < interval[2][1]){
                freqData = [1,1,0,0,0];
            }
            if(attr.freq >= interval[3][0] && attr.freq < interval[3][1]){
                freqData = [1,1,1,0,0];
            }
            if(attr.freq >= interval[4][0] && attr.freq < interval[4][1]){
                freqData = [1,1,1,1,0];
            }
            if(attr.freq >= interval[5]){
                freqData = [1,1,1,1,1];
            }

but the interval may change and I also want to know if there is a better way to to compare within the intervals.


texts: Finding two movies whose lengths add up to a given length

texts:
Here's some code which, given a list of \$N\$ movie lengths, checks if there are two movies that equal the exact length of a flight. This solution runs in \$\mathcal{O}(N)\$ time since I used a hash table.

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int main() {
    const int LENGTH = 170;
    vector<int> movies = {60, 120, 50, 150, 30, 45};
    unordered_map<int, bool> secondMovies;

    for (int movie: movies)
        secondMovies[movie] = true;

    for (int firstMovie: movies)
        if (secondMovies[LENGTH-firstMovie]) {
            cout << firstMovie << " and " << LENGTH-firstMovie;
            return 0;
        }

    cout << "No movies found.";
    return 0;
}

In the second for loop, I immediately return from main if two valid movies are found. Is this considered bad practice?


texts:
I have this simple looping macro, but I can't seem how to figure out how to make it run faster. I tried including more update = false statements as well as well as removing any selecting type behavior.

 Sub AbesLoop()

 Dim wbk As Workbook
 Dim ws As Integer
 Dim Filename As String
 Dim Path As String
 Dim rCell As Range
 Dim rRng As Range
 Dim wsO As Worksheet

 Application.ScreenUpdating = False
 Application.DisplayAlerts = False
 Application.Calculation = xlCalculationManual

 Path = "PathToFolder" & "\"
 Filename = Dir(Path & "*.xl??")
 Set wsO = ThisWorkbook.Sheets("Sheet1")

 Do While Len(Filename) > 0
     Set wbk = Workbooks.Open(Path & Filename, True, True)
     ws = wbk.Worksheets.Count
     For i = 1 To ws
     Application.ScreenUpdating = False
     Application.DisplayAlerts = False
     Application.Calculation = xlCalculationManual
     Set rRng = Range("b1:b20")
         For Each rCell In rRng.Cells
             If rCell <> "" And rCell.Value <> "Not Tested" Then

             wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = rCell
             wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = rCell.Offset(0, -1)
             wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 2).Value = Right(ActiveWorkbook.FullName, 15)
             End If
         Next rCell
     Next i
     wbk.Close False
     Filename = Dir
 Loop

 Application.ScreenUpdating = True
 Application.DisplayAlerts = True
 Application.Calculation = xlCalculationAutomatic

 End Sub


texts: Shoping cart code using a loop to print multiple times

texts:
This code belongs to a shopping cart which I want to print multiple times with the help of a loop.

There are 9 SQL queries and I want all these queries to run at a time with the below table every time the SQL query changes, but the below table remains the same.

          //SQL query define in array
  $query = array(
  "SELECT  * FROM products   WHERE   rowno=1
   and   colno=1 and pageno=1 and  productLine like '$cat'",
   "SELECT  *  FROM   products  WHERE  rowno=1  and  colno=2
   and  pageno=1   and   productLine   like   '$cat'",
   "SELECT *  FROM  products WHERE rowno=1 and colno=3
    and pageno=1 and productLine like '$cat'",
   "SELECT * FROM products  WHERE rowno=2 and colno=1 and pageno=1
   and productLine like '$cat'",
  "SELECT * FROM products WHERE rowno=2 and colno=2
   and pageno=1 and productLine like '$cat'",
   "SELECT * FROM products WHERE rowno=2 and colno=3
   and pageno=1 and productLine like '$cat'",
   "SELECT * FROM products WHERE rowno=3 and colno=1
    and pageno=1 and productLine like '$cat'",
   "SELECT * FROM products WHERE rowno=3 and colno=2
    and pageno=1 and productLine like '$cat'",
    "SELECT * FROM products WHERE rowno=3 and colno=3
    and pageno=1 and productLine like '$cat'");

 foreach($query as  $a)
 {

$cmd=mysql_query($query,$conn);  // con query
$row=mysql_fetch_row($cmd);    // fetch the table in database
echo
  "

  $row[1]	      // table row

  RS $row[7]&nbsp;	         // this table same in  loop but sql change

  $row[8]

   $row[5]

 Details

";
  } // end loop


texts: Cancelling ongoing http requests when next one is started - web app search feature

texts:
This piece of code is aimed to cancel any ongoing search requests sent from the web application if next request is started, e.g. after user updates the search term.

I tested it in the final application and everything looks fine. It has already been deployed to the remote environment in our organization.

It appears to work fine, but are there any pitfalls in the code?

const ongoingRequests = [];
const fetchData = (text, activePage, itemsPerPage) => async dispatch => {
dispatch({ type: FETCH_ENTITIES });
const page = activePage - 1;

let response;

// cancel any ongoing search requests
if (ongoingRequests.length > 0) {
    ongoingRequests.map(x => x.cancel('next request started'));
    ongoingRequests.length = 0;
}

// start a new request
response = await (async () => {
    const cts = axios.CancelToken.source();
    ongoingRequests.push(cts);

    let path =
    text !== ''
        ? `/Search?PageNumber=${page}&PageSize=${itemsPerPage}&SearchTerm=${text}`
        : `?QueryLead=true&PageNumber=${page}&PageSize=${itemsPerPage}`;

    return axios
    .get(`${env_urls.api.entity}Entity${path}`, {
        cancelToken: cts.token,
    })
    .then(response => {
        return response;
    })
    .catch(error => {
        if (
        typeof cts !== 'undefined' &&
        typeof cts.token !== 'undefined' &&
        typeof cts.token.reason !== 'undefined' &&
        cts.token.reason.message === 'next request started'
        ) {
            // request cancelled, everything ok
        } else {
        throw error;
        }
    });
})();

// response is undefined if the request has been cancelled
if (typeof response !== 'undefined') {
    const data = response.data;

    dispatch({ type: FETCH_ENTITIES_SUCCESS, data });
}
};


texts:
I have spent countless hours trying to speed up my bilinear interpolation up. I even tried implementing an SSE version (a double version and a float version), but that was even slower than this version.

Does anyone have any ideas?

I wrote this under VS2010 and it is intended to be called from MATLAB as a MEX function (thus the minus one subtraction in interp2_mx because indexing in MATLAB is from 1:end as opposed to 0:end-1).

My function interp2 requires a T (intended float/double type) pointer to Z (mz by nz matrix) and interpolates the points in XI and YI into ZI (which are all the same size mi by ni).

template <typename T>
__forceinline void interp2_mx(const T& x, const T& y,
                          const T* z,
                          const int32_t& n,
                          const int32_t& mm2,
                          const int32_t& nm2,
                          T& val,
                          const T& extrapval = T(0))
{
    int64_t xp = (int64_t)(x) - 1;      // adjust for MATLAB indexing
    int64_t yp = (int64_t)(y) - 1;
    if (xp < 0 || xp > nm2 || yp < 0 || yp > mm2)
    {
        val = extrapval;
    }
    else
    {
    const T* line = z + yp * n + xp;
    T xf = x - (int64_t)(x);   // get decimal portion
    T yf = y - (int64_t)(y);
    T x1mf = (T)1 - xf;
    T y1mf = (T)1 - yf;

    T v00 = x1mf * y1mf * (*(line));
    T v01 = xf * y1mf * (*(line + 1));
    T v10 = x1mf * yf * (*(line + n));
    T v11 = xf * yf * (*(line + n + 1));
    val = v00 + v01 + v10 + v11;
    }
}

template <typename T>
void interp2(const T* z,
         const int32_t& mz, const int32_t& nz,
         const T* xi, const T* yi,
         const int32_t& mi, const int32_t& ni,
         T* zi,
         const T& extrapval = T(0))
{
const int32_t nzm2 = nz - 2;
const int32_t mzm2 = mz - 2;
#pragma omp parallel for
for (int m = 0; m < mi; ++m)
{
    T* line_zi = zi + m * ni;
    const T* x = xi + m * ni;
    const T* y = yi + m * ni;
    for (int n = 0; n < ni; ++n, ++x, ++y, ++line_zi)
    {
        interp2_mx((*x), (*y), z, nz, mzm2, nzm2, (*line_zi));
    }
 }
}


texts:
I wrote a program to evenly divide pizzas.
And I tried to stylize it as a console.
I will be grateful for tips on improving my code.

Here is a sample image of the program after a user has entered values:

$(function(){
 $('.secondQuestion').hide();
 $('#peopleInput').focus();

 //Three functions for outputting the result
 const firstOutput = function(a, b){
  if(b>1){
   $('#firstStr').text(a + " people with " + b + " pizzas")
  } else {
   $('#firstStr').text(a + " people with " + b + " pizza")
  }
 }
 const piece = (a, b) => Math.floor((b * 8) / a);
 const secondOutput = function(a){
  if(a > 1){
   $('#secondStr').text("Each person gets " + a + " pieces of pizza")
  } else {
   $('#secondStr').text("Each person gets " + a + " piece of pizza")
  }
 }
 const leftover = (a, b) => (b * 8) % a;
 const thirdOutput = function(a){
  if(a > 1){
   $('#thirdStr').text("There are " + a + " leftover pieces")
  } else {
   $('#thirdStr').text("There is " + a + " leftover pieces")
  }
 }

 //Action after pressing the enter key on the first line
 $('#peopleInput').bind("enterKey", function(e){
  $('.secondQuestion').show();
  $('#pizzaInput').focus();
 });
 $('#peopleInput').keyup(function(e){
  if(e.keyCode == 13){$(this).trigger("enterKey")}
 });

 //Action after pressing the enter key on the second line
 $('#pizzaInput').bind("enterKey", function(e){
  $('#peopleInput').focus();
  const people = $('#peopleInput').val();
  const pizza = $('#pizzaInput').val();
  firstOutput(people, pizza);
  setTimeout(function(){secondOutput(piece(people, pizza)); }, 300);
  setTimeout(function(){thirdOutput(leftover(people, pizza)); }, 600);
 });
 $('#pizzaInput').keyup(function(e){
  if(e.keyCode == 13){$(this).trigger("enterKey")}
 });
});
body{
 background: #000;
 color: #fff;
 font-family: 'Inconsolata', monospace;
}

h2{
 font-weight: normal;
}

.output{
 margin-top: 10px;
}

p{
 margin: 0 0 5px 0;
}
input {
 border: none;
    background-color: #000;
    width: 50px;
    color: #fff;
    padding-left: 5px;
    margin-bottom: 5px;
}
input:focus{
 outline-color: #000;
}

main{
 position: absolute;
    left: 200px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
<link href="https://fonts.googleapis.com/css?family=Inconsolata:400,700" rel="stylesheet">

Pizza Party >

  How many people?
  <input type="number" class="form-control" id="peopleInput" value="" name="" min="0" oninput="validity.valid||(value='');">

  How many pizzas do you have?
  <input type="number" class="form-control" id="pizzaInput" value="" name="" min="0" oninput="validity.valid||(value='');">


texts: Template function for splitting strings in C++

texts:
I'd like to write a function to split strings in C++ to check my template learning. I've also read some relavent questions in this site but most of them don't use templates or string_view. A related question in StackOverflow I asked is here.

My goal is to write a function such that:

The function can split std::basic_string, not only std::string.
The delimiter can be a CharT, or const CharT* p or std::basic_string<CharT>, multiple chars means the delimiter should be fully matched (like str.split in Python), not any of the chars.
The results are put into a sequence container from STL.
The user need not do any explicit conversion when parsing arguments, e.g. std::string_view(some_str).
(Optional) The function can split const CharT* p or any string literals.

My major concerns are

To minimize the number of the functions need to be overloaded.
To write template codes in a more modern C++ way. (For example, I've learn a lot by reading boost::algorithm::trim, many generic functions work on iterator ranges. But the boost version of split seems a bit complicate for me right now.)
How string_view in C++17 can help in this example. My version seems not take full advantages of it.
How to design a better function signature of the master template to relieve the pain when writing overloading?

Below is my first attempt.

#include <iostream>
#include <list>
#include <string>
#include <string_view>
#include <vector>

template <typename CharT, typename ContainerT>
void split(
    std::basic_string_view<CharT> str,
    std::basic_string_view<CharT> delimiters,
    ContainerT &conts) {
    conts.clear();
    std::size_t start = 0, end;
    std::size_t len = delimiters.size();
    while ((end = str.find(delimiters, start)) !=
           std::basic_string_view<CharT>::npos) {
        if (end - start) {
            conts.emplace_back(str, start, end - start);
        }
        start = end + len;
    }

    if (start != std::basic_string_view<CharT>::npos && start < str.size()) {
        conts.emplace_back(str, start, str.size() - start);
    }
}

template <typename CharT, typename ContainerT>
void split(
    const std::basic_string<CharT> &str,
    const std::basic_string<CharT> &delimiters,
    ContainerT &conts) {
    split(
        std::basic_string_view<CharT>(str),
        std::basic_string_view<CharT>(delimiters), conts);
}

template <typename CharT, typename ContainerT>
void split(
    std::basic_string<CharT> str, const CharT *delimiter, ContainerT &conts) {
    split(
        std::basic_string_view<CharT>(str),
        std::basic_string_view<CharT>(delimiter), conts);
}

template <typename CharT, typename ContainerT>
void split(
    const std::basic_string<CharT> &str, CharT delimiter, ContainerT &conts) {
    split(
        std::basic_string_view<CharT>(str),
        std::basic_string_view<CharT>(&delimiter, 1), conts);
}

template <typename Iter>
void print(Iter begin, Iter end) {
    for (auto it = begin; it != end; ++it) {
        std::cout << *it << "/";
    }
    std::cout << std::endl;
}

int main(int argc, char **argv) {
    std::string str("haha,ha,,haha,,ha,,,ha,");
    std::vector<std::string> strs;

    split(std::string_view(str), std::string_view(","), strs);
    print(strs.begin(), strs.end());

    split(str, std::string(","), strs);
    print(strs.begin(), strs.end());

    split(str, ',', strs);
    print(strs.begin(), strs.end());

    split(str, ",,", strs);
    print(strs.begin(), strs.end());

    return 0;
}


texts:
I am implementing some basic data structures to freshen up my memory and I wanted my DoubleLinkedList remove method to be reviewed. I feel like it has extra checks but I could not think of another way to implement.

My implementation holds both the head and the tail of the list making things a bit more complex.

remove method:

public void remove(T data) {
    if (isEmpty()) {
        throw new NoSuchElementException();
    }

    for (Node<T> current = this.head; current != null; current = current.getNext()) {
        if (current.getData().equals(data)) {
            Node<T> previous = current.getPrevious();
            Node<T> next = current.getNext();

            if (this.size == 1) { // At head with size == 1
                this.head = this.tail = null;
            } else if (previous == null) { // At head with size > 1
                this.head = next;
                next.setPrevious(previous);
            } else if (next == null) { // At tail
                previous.setNext(next);
                this.tail = previous;
            } else { // Rest of cases
                previous.setNext(next);
                next.setPrevious(previous);
            }
            this.size--;
            return;
        }
    }
    throw new NoSuchElementException();
}


texts: Show User that Page is Loading using dots (...)

texts:
I'm trying to show to the user that the page is reading/loading by creating an animation of dots.

Here is the HTML:

Authenticating

<button id="run">
    Run It
</button>
<button id="stop">
    Stop
</button>

And here is the script:

$(document).ready(function(){

    var interval;

    function countdown(){
        counter = 1;
        interval = setInterval(function(){
            if(counter > 0 && counter < 4){
                $("#dot").append('.');
            } else {
                counter = 0;
                $("#dot").text('Authenticating');
            }
            counter += 1;
        },1000);
    }

    $("#run").click(function(){
        countdown();
    })

    $("#stop").click(function(){
        $("#dot").text('Authenticating');
        clearInterval(interval);
    })

})

Any better way to implement it?

Check fiddle here.


texts: Return the first word with the greatest number of repeated letters

texts:
I'm learning JavaScript and have written a function that accepts a string and returns the first word with the greatest number of repeated letters. For example:

Input:"Hello apple pie" - Output:"Hello"
Input:"Hello apple pie yelllow" - Output:"yelllow"

I've tried to keep it as concise as possible. I wonder whether later on in the code it starts to become more verbose. The answer it returns seems to be correct for all tests.

Could someone give some advice about improving my code? Or is it not bad?

function whichWord(str) {

// 1. split into array with words - EG if var str = "wodrd sy hello";
var arr = str.split(' '); // puts str into array ["wodrd", "sy", "hello"]
var mdArr = arr.map(function(el){ return el.split('') }); // puts str into MD array [["w","o","d","r","d"],["s","y"],["h","e","l","l","o"]]

// 2. get each unique letter (remove duplicates)
function removeDuplicates(a) {
 return Array.from(new Set(a))
}
var letters = mdArr.map(removeDuplicates);

// 3. count # of each letter occurrences
var temp = [];
var numbers = [];

for(i=0;i < mdArr.length;i++) {

for(k=0;k < letters[i].length;k++) {temp.push(mdArr[i].filter(function(c2){return c2==letters[i][k]}).length)}

numbers.push(temp);
temp=[];

}

var letterCount = letters.map((innerArr, i) => innerArr.map((letter, ii) => ({letter: letter, instances: numbers[i][ii]}))); // puts into MD array with objects:
/* returns: [
    [{letter: "w", instances: 1},{letter: "o", instances: 1},{letter: "d", instances: 2},{letter: "r", instances: 1}],
    [{letter: "s", instances: 1},{letter: "y", instances: 1}],
    [{letter: "h", instances: 1},{letter: "e", instances: 1},{letter: "l", instances: 2},{letter: "o", instances: 1}]
] */

// 4. return word from index with largest number, & first instance if matching numbers
var highestNumbers = letterCount.map((outerArr,i) => Math.max.apply(Math,outerArr.map((innerArr,ii) => innerArr.instances)));

var highestNumber = Math.max.apply(Math,highestNumbers);

var indexToReturn = highestNumbers.findIndex(function(c) { return c == highestNumber } );

return arr[indexToReturn];

}


texts:
I decided to make a quick little encoder in Python as a little challenge for myself. I decided to submit my program as I am very interested in improving my programming skills and learning better ways to code. My program simply asks for a string and for a key. The key could be +3, +4, etc. The key will add the number inputted to the number corresponding to each letter, then return the new letters.

dic = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W": 22, "X": 23, "Y": 24, "Z": 25, " ": 26}
dic2 = {}
for x,v in dic.items():
    dic2[v] = x

program = True

while program:
    list = []
    encodeNums = []
    encodeStr = []
    task = input("Would you like to encode or decode?: ").lower()
    if task == "encode":
        string = input("What would you like to encode?: ").upper()
        key = input("What key would you like to use?: ")
        for x in string:
            list.append(dic[x])
        for x in list:
            encodeNums.append(eval("{}{}".format(x,key)) % 27)
        for x in encodeNums:
            encodeStr.append(dic2[x])
        print("".join(encodeStr))