texts:
Currently, I'm working on a game with directional movement influenced by the numpad. The player AI should intelligently pick a direction to move (so it's not entirely random, and can be somewhat coherent).

For reference, this is the numpad I'm using:

7 | 8 | 9
- - - - -
4 | x | 6
- - - - -
1 | 2 | 3

(5 is ignored as moving to your current location is considered invalid).

Essentially, I want to take the players prior movement direction and prioritize it where possible, making it "fan out" into lesser probabilities the more "unlikely" the movement is. Suppose the players prior direction was 8, the probability distribution should look like this:

60 | 80 | 60
-- | -- | --
30 | xx | 30
-- | -- | --
20 | 10 | 20

Just to provide another example, a prior movement of 1 would look like this:

30 | 20 | 10
-- | -- | --
60 | xx | 20
-- | -- | --
80 | 60 | 30

The algorithm I've come up with looks like this:

let neighbors = {
  1: [4, 2],
  2: [1, 3],
  3: [2, 6],
  4: [7, 1],

  6: [9, 3],
  7: [4, 8],
  8: [7, 9],
  9: [8, 6]
};

let probabilities = [80, 60, 30, 20, 10];

let recurse = (obj, pos, level = 0) => {
  if(!probabilities[level] || obj[pos]) return;

  obj[pos] = probabilities[level];
  recurse(obj, neighbors[pos][0], level+1);
  recurse(obj, neighbors[pos][1], level+1);
};

export default (firstDir) => {
  var ret = {};
  recurse(ret, firstDir);
  return ret;
}

The implementation spits out a hash with the probabilities, so, the output from the 8 situation above would look like this:

{
  1: 20,
  2: 10,
  3: 20,
  4: 30,
  6: 30,
  7: 60,
  8: 80,
  9: 60
}

I'm not really sold on this implementation - it requires a map of neighbors for recursion. I can't quite figure out if there's some fancy math I can use to derive this, so I'm instead using recursion.

Could this be done better?


texts: Is there a better way to condense the while loop?

texts:
I have been trying to write a number guessing game and I am trying to condense the second while loop when guess =! random_number. I can't figure out if there is any better way to shorten the code but to still achieve the same result. I wonder if someone is able to help me out.  If there's anything else which is redundant or not efficient in my code or how i could code it better please criticize the hell out me my work!
import random

def inputNumber(message):
    while True:
        try:
            userInput = int(input(message))
        except ValueError:
            print("Not an integer! Try again.")
            continue
        else:
            return userInput
            break

#ranges must be integers
min_range = int(inputNumber("Please insert the min range: "))
temp_range = int(inputNumber("Please insert the max range: "))

#max range must be bigger than min
while min_range >= temp_range:
    temp_range = int(inputNumber("Please insert a max range which is smaller than min range!: ")) + 1

max_range = temp_range

random_number = random.randint(min_range, max_range)

guess = int(input("Please enter your guess: "))
counter = 1;  # you guessed once already
while guess != random_number:  # 1 guess incorrect
    print(f"{random_number} is the random number")# to see for myself which is the random numb
    if min_range < guess < max_range:  # WITHIN THE RANGE
        if random_number - random_number / 12 < guess-random_number < random_number + random_number / 12:  # 3 super hot
            print("Please try again, you are super hot!")
        elif random_number - random_number / 8 < guess-random_number < random_number + random_number / 8:  # 3 hot
            print("Please try again, you are hot!")
        elif guess < random_number - random_number / 2 or guess-random_number > random_number + random_number / 2:  # 3 cold
            print("Please try again, you are cold!")

    else:  # OUTSIDE RANGE
        print("You are outside the range, try again!")
    guess = int(input())
    counter += 1
if guess == random_number:  # guess correct
    print(f"Congratulations, you guessed correctly in {counter} tries!")

edit: thanks you all so much for taking the time to review my code, i will try to improve on the noted points, much appreciated (:


texts: Minimize sum of array by applying specific operation on x carefully chosen elements

texts:
This code works, and solves the problem, but doesn't satisfy some time requirements, especially when the 'nums' array can have a length of over 1000. How can this be optimized?
Just reference:
This function does x number of operations on any element in the nums array so that the sum of all elements in the final array is always as small as possible. As a result, you have to perform the operation on the elements with the highest values first.
function minSum(nums, x) {
    if (nums.length === 0) {
        return false;
    }
    function operation(max) {
        let redcuedMax = Math.floor(max / 10);
        return redcuedMax
    }
    let ops = x;
    while (ops > 0) {
        let max = Math.max(...nums);
        const ofNumber = (element) => element >= max ;
        let maxIndex = nums.findIndex(ofNumber)
        let operated = operation(max);
        nums[maxIndex] = operated;
        ops--
    }
    return nums.reduce((prev,next) => prev + next, 0)
}

minSum([400,209,77], 4) //out: 31
minSum([5000,5000,5000,5000,5000,], 4) //out: 7000


texts: Hexadecimal to decimal converter in C (htoi.c)

texts:
Is there any way I can make this code more efficient? I'm new to C, any suggestion is welcome!

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

#define LIMIT 1024

unsigned long htoi(char s[], int len);

int main(void){
    char line[LIMIT+1];

    int i=0;
    for(int c=0; i<LIMIT-1 && (c = getchar()) != '\n' && c != EOF; ++i){
        line[i] = c;
    }
    line[i] = '\0';

    printf("%lu\n", htoi(line, i));
}

unsigned long htoi(char s[], int len){

    unsigned long total = 0;
    unsigned short currdigit = 0;
    int power = 0;

    for(int i=len; i>-1; --i){

        if(s[i] == 'X' || s[i] == 'x' || s[i] == 0){
            continue;
        }

        if(s[i] >= '0' && s[i] <= '9'){ // if it is a numerical char
            currdigit = s[i]-'0';
        }
        else{
            if(s[i] >= 'a' && s[i] <= 'z'){ // if it's a lower case char
                currdigit = s[i] - 'a';
            }
            else{ // if not, then we assume it is an upper case char (should I?)
                currdigit = s[i] - 'A';
            }

            currdigit+=10;
        }

        total += (currdigit * pow(16, power));

        ++power;
    }

    return total;
}

I have a few questions as well:

The book I am using to learn C didn't reach the point of teaching pointers yet; however, I do know at least the basics. Is there any way pointers could be used in this program?
Should I make change the parameter char s[] to const char s[] since I am not changing any of its elements' values? Is that common practice?
Should I use short instead of int when I know the number won't surpass great quantities? As an instance, when developing a game, if I know my player's health is from 0 to 100, should I be using a short to store that value? And should it be unsigned as well if I know it won't be negative?


texts: Run an external program and extract a pattern match along with the result file

texts:
The script takes two input files of protein sequences and runs an external program (installed in linux/MacOS). The result provides a text output file example output.. Identity percentage is extracted from the matched keyword "Identity" in the line. Also, the script returns the result text file.

Can you help me to improve this script?

import re
import subprocess

def cmdline(command):
    process = subprocess.Popen(
        args=command,
        stdout=subprocess.PIPE,
        shell=True
    )
    return process.communicate()[0]

def blast_two_sequences(file1, file2):

    try:
        # fetch the identity percentage
        #https://www.biostars.org/p/200256/

        cmd = 'needle -datafile EBLOSUM62 -auto Y' + ' -asequence ' + file1 +' -bsequence ' + file2 +  ' -sprotein1 Y -sprotein2 Y ' + ' -auto -stdout'
        # cmd = 'needle -asequence ' + file1 +' -bsequence ' + file2 + ' -auto -stdout'

        results = cmdline(cmd)

        results = results.decode("utf-8")

        identity = re.search(r"\d{1,3}\.\d*\%", results)
        identity = identity.group()
        identity = identity.replace('%', '')

        return identity, results

    except:
        return None

file1 = "/Users/catuf/Desktop/file1.txt"
file2 = "/Users/catuf/Desktop/file2.txt"

if blast_two_sequences(file1, file2) is not None:
    identity, result = blast_two_sequences(file1, file2)


texts: Find sum of all the subarrays of an array

texts:
I have an array. Now I want to find the total of, sum of the subarray multiplied by its last element, for all the possible subarrays. This is what I have right now:

n = int(input())
a = []
for _ in range(n):
    a.append(int(input()))
total = 0
for i in range(1, n+1):
    for j in range(n+1-i):
        temp = a[j:j+i]
        total += sum(temp)*temp[-1]
print(total)

Example Input:

3
1
2
3

Output:

53

Explanation:

1*1 + 2*2 + 3*3 + (1+2)*2 + (2+3)*3 + (1+2+3)*3 = 53

My code works fine, but is quite slow. How can I optimise it?


texts: Is this code protected against SQL injection attacks?

texts:
I'm just wondering if this code is good against SQL injection attacks. I don't know how to check if is good. Also I would like to know if is good how I'm working or this is just bad practice?

<?php

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

$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$salt = "Not important";
$password_hash = crypt($password, "$2y$". $salt);

if (strlen($username) > 20) {
    echo "Username is too big";
}elseif (strlen($password) > 32) {
    echo "Password is too big";
}elseif (strlen($email) > 100) {
    echo "E-Mail is too big";
}elseif(strlen($username) == 0 || strlen($password) == 0 || strlen($email) == 0){
    echo "Fill every field";
}
else{
    $sth_username = $dbh->prepare("SELECT username FROM user WHERE username = :username");
    $sth_username->bindParam(":username", $username);
    $sth_email = $dbh->prepare("SELECT email FROM user WHERE email = :email");
    $sth_email->bindParam(":email", $email);
    $sth_username->execute();
    $sth_email->execute();
    if ($result = $sth_username->fetch(PDO::FETCH_OBJ)) {
        print $result->username . "The username is already is use";
    }elseif ($result = $sth_email->fetch(PDO::FETCH_OBJ)){
        print $result->email . "That e-mail is already in use";
    }else{
        $sth = $dbh->prepare("INSERT INTO user (username, password, email, salt) VALUES (:username, :password, :email, :salt)");
        $sth->bindParam(":username", $username);
        $sth->bindParam(":password", $password_hash);
        $sth->bindParam(":email", $email);
        $sth->bindParam(":salt", $salt);
        $sth->execute();
        $sth = $dbh->prepare("INSERT INTO stats (strength,agility,intelligence) VALUES (10,10,10)");
        $sth->execute();

        echo "You have been registered";
    }
}
?>


texts: Dijkstra Implementation: Comparing my program with widely available Internet Java program

texts:
I wanted to discuss Dijkstra's implementation that I generally find on Internet, and then compare it with my own implementation.

On Baeldung and on Vogella (Thanks to both and many others, that I haven't referred here, for providing the program). What these programs basically do is first find the node with the minimal distance and then calculate the minimum distance! In this approach, we are looping more and also increasing unnecessary complexities...

I have written my Dijkstra implementation, and basically that's a BFS with a little bit of modification to find the minimum distance! I have given my program below and the crux to find the minimum distance is if (!distances.containsKey(thisCity)) { and the else part of it along with Map<City, Integer> distances = new HashMap<>();. My program gives the expected output without any problem. To me it looks easier implementation and also easier to understand.

I understand the same program can be written in thousand different ways but I just wanted to get it reviewed and wants opinion of fellow programmers... Thanks for your time and help

public int findMinDistance(City src, City dest) {
    Set<City> visited = new HashSet<>();

    Queue<City> queue = new LinkedList<>();

    Map<City, Integer> distances = new HashMap<>();
    distances.put(src, Integer.valueOf(0));
    visited.add(src);
    queue.add(src);

    City currentCity;
    while (queue.size() != 0) {
        currentCity = queue.poll();
        Set<City> cities = currentCity.getCityDistancesMap().keySet();
        for (City thisCity : cities) {
            int thisDistance = distances.get(currentCity).intValue() +
                    currentCity.getCityDistance(thisCity);
            if (!distances.containsKey(thisCity)) {
                distances.put(thisCity, thisDistance);
            } else {
                int oldDistance = distances.get(thisCity).intValue();
                if (oldDistance > thisDistance) {
                    distances.remove(thisCity);
                    distances.put(thisCity, thisDistance);
                }
            }
            if (!visited.contains(thisCity)) {
                visited.add(thisCity);
                queue.add(thisCity);
            }
        }
    }
    return distances.get(dest);
}


texts:
I'm trying to come up with an alternative to the gmean implementation in scipy, because it is awkwardly slow. To that end I've been looking into alternate calculation methods and implementing them in numpy. My only issue is that a method that in the two methods I'm implementing, the one that I feel ought to be faster is in fact much slower. I feel like this is an issue with my implementation and would love advice on improving it.

def fast_gmean(vector, chunk_size=1000):
    base, exponent = np.frexp(vector)
    exponent_sum = float(np.sum(exponent))
    while len(base) > 1:
        base = np.array_split(base, math.ceil(float(base.size)/chunk_size))
        intermediates = np.array([np.prod(split) for split in base])
        base, current_exponent = np.frexp(intermediates)
        exponent_sum += np.sum(current_exponent)
    return (base[0]**(1.0/vector.size)) * (2**(exponent_sum/vector.size))

def actually_fast_gmean(vector):
    return np.exp(np.mean(np.log(vector)))

While these both outperform scipy's gmean implementation, the second method is about 33% faster than the first.

Note: I'm testing this on arrays of approximately 5000 entries.


texts:
A challenge in the beginner book "Automate the boring stuff":

#! Python3

# Table printer
# Takes a list of lists of strings and displays in right-justified table
# assumption is inner lists contain same number items
# each inner list must be printed as a column

the_list = [["a", "bbbbbbbbb", "tttt"],
            ["d", "eeee", "ggggggggggg"],
            ["g", "hhh", "kkkkkkkkkkkkkkkk"]]

def print_table(a_list):
    """
    Prints a 2d list as a right justified table where each column represents
    an inner list
    """
    rows = len(the_list[0])
    columns = len(the_list)
    column_widths = [0 for i in range(columns)]
    # find longest string in each inner lists(or column)
    for i in range(len(column_widths)):
        longest = 0
        for item in a_list[i]:
            if len(item) > longest:
                longest = len(item)
        column_widths[i] = longest

    # store strings in list
    print_row = ["" for i in range(rows)]
    # iterate over lists to produce strings with correct formatting
    for a in range(rows):
        for i in range(columns):
            print_row[a] = print_row[a] + a_list[i][a].rjust(column_widths[i]
                                                             + 4)
    for item in print_row:
        print(item)

print_table(the_list)


texts:
I was writing some validation logic for a React-native app and thought I had so many bools flying around in my code!

Is there any way to reduce redundancy in this code or is this the best that can be done?

_validatePhone() {
    if (!validate.validatePhone(this.state.phone)) {
      this.setState({ phoneError: true });
      return false;
    }
  return true;
}

_validateName() {
    if (!validate.validateName(this.state.name)) {
      this.setState({ nameError: true });
      return false;
    }
    return true;
  }

  _validateForm() {
    this._resetErrors(); // Reset errors before validating
    if (!this._validateName()) {
      return false;
    } else if (!this._validatePhone()) {
      return false;
    }
    return true;
  }


texts: MCU (Embedded C): Use nested if/elses or use an ugly function?

texts:
I'm writing driver code for the SPI peripheral (as part of a tutorial) on a Nucleo64 (STM32F446RE). The instructor recommends writing this code:

// General macros
#define EnableStatus uint8_t
#define DISABLE      0
#define ENABLE       !DISABLE

void SPI_EnablePeripheralClock(SPI_RegDef_t *pSPIx, EnableStatus status)
{
    if (status) {
        if (pSPIx == SPI1)
            SPI1_PCLK_ENA();
        else if (pSPI == SPI2)
            SPI2_PCLK_ENA();
        // ... done for 4 SPI modules
    } else {
        if (pSPIx == SPI1)
            SPI1_PCLK_DIS();
        else if (pSPI == SPI2)
            SPI2_PCLK_DIS();
        // ... done for 4 SPI modules
}

...
// You can treat RCC->APB2ENR as the value at some address. ENA() sets a bit. DIS() clears a bit.
#define SPI1_CLK_ENA()       (RCC->APB2ENR |= (1 << 12))
#define SPI2_CLK_ENA()       (RCC->APB1ENR |= (1 << 14))
#define SPI1_CLK_DIS()       (RCC->APB2ENR &= ~(1 << 12))
#define SPI2_CLK_DIS()       (RCC->APB1ENR &= ~(1 << 14))
...
#define IO volatile

typedef struct {
    IO uint32_t CR1;        // Control Reg. 1
    IO uint32_t CR2;        // Control Reg. 2
    IO uint32_t SR;         // Status Reg.
    IO uint32_t DR;         // Data Reg.
    IO uint32_t CRCPR;      // CRC Polynomial Reg.
    IO uint32_t RXCRCR;     // RX CRC Reg.
    IO uint32_t TXCRCR;     // TX CRC Reg.
    IO uint32_t I2SCFGR;    // I2S Configuration Reg.
    IO uint32_t I2SPR;      // I2S Prescaler Reg.
} SPI_RegDef_t;
#define SPI1 ((SPI_RegDef_t*)SPI1_BASEADDR)
#define SPI2 ((SPI_RegDef_t*)SPI2_BASEADDR)

Several things I don't like about this implementation:

The chain of if-elses in the function to set or clearing one bit. It's a lot of lines-of-code to express a simple task.
It's comparing peripheral device base addresses to figure out which of the four SPI peripheral it's working with.

I rewrote it like this to address the issues:

// Assigns the boolean value b to the p'th bit position (0-based indexing) of the number `num`.
void BitAssign(volatile uint32_t *num, uint8_t p, bool b)
{
    // https://stackoverflow.com/a/47990/3396951
    b = !!b; // booleanize b (if it was previously non-zero, it is now 1 otherwise it's 0)
    *num = (*num & ~(1UL << p)) | (b << p);
}

// To be used as first argument in SPI_EnablePeripheralClock() and other functions
#define SPI1 1
#define SPI2 2
#define SPI3 3
#define SPI4 4

void SPI_EnablePeripheralClock(uint8_t SPIx, EnableStatus status)
{
    // 12, 14, 15, 13 are values provided by the datasheet
    if (SPIx == SPI1)
        BitAssign(&RCC->APB2ENR, 12, status);
    else if (SPIx == SPI2)
        BitAssign(&RCC->APB1ENR, 14, status);
    else if (SPIx == SPI3)
        BitAssign(&RCC->APB1ENR, 15, status);
    else if (SPIx == SPI4)
        BitAssign(&RCC->APB2ENR, 13, status);
}

This avoids relying on the ENA()/DIS() functions (I can remove them) and utilizes a bit-operation to perform the bit assignment. I'm unsure if  BitAssign() is a good idea since I might have to overload it for non-volatile parameters.


texts:
I recently started learning Java, algorithms, and data structures. I am trying to check if a string is palindrome. I would like a review to see where and how I could improve.

import java.util.Stack;

class Palindromer {

Stack<Character> stack = new Stack<Character>();
int top = -1;

public boolean isPalindrome(String s) {
    for (int i = 0; i < s.length(); i++) {
        stack.push(s.charAt(i));
        top++;
    }

    System.out.println("value of top is " + top);
    String returnString = "";

    while (!stack.isEmpty()) {
        returnString += stack.pop();
    }
    System.out.println(returnString);

    return returnString.equals(s);
}

}

public class PalindromeChecker {
public static void main(String[] args) {
    Palindromer palin = new Palindromer();
    if (palin.isPalindrome("BananaB")) {
        System.out.println("is palindrome");
    } else {
        System.out.println("not a palindrome");
    }
}
}


texts:
I wrote this piece of code to append index to any duplicate entry in List<T> like in the sample below.

Input

["dupe", "not dupe", "dupe", "also not dupe"]

Output

["dupe1", "not dupe", "dupe2", "also not dupe"]

But the problem is it's O(n^2) in the second loop and I'm working on a large list (30+ items). I'm very new to C# and didn't know much built-in functions, so I wanted to know is there anything I can do to optimize this?

List<string> duplicate = new List<string>(); // For storing duplicate item
IEnumerable<IGrouping<string, string>> g = header.GroupBy(i => i);

// Find duplicate and store it in duplicate
foreach (var item in g)
    if (item.Count() > 1)
        duplicate.Add(item.Key);

// Loop through duplicate to append the index
foreach (var item in duplicate) {
    int start = 1;
    for (int i = 0; i < header.Count; i++) {
        // If header[i] is a duplicate item append index to it.
        if (string.Equals(header[i], item, StringComparison.OrdinalIgnoreCase)) {
            header[i] = string.Format("{0}{1}", header[i], start);
            start++;
        }
    }
}


texts: Helper class to change property of string when serializing for Json.Net

texts:
Is there any way to simplify the following C# helper class to numerate a string for Json.Net?

internal static string CreateContact(string title)
{
    var createContact = new {Title = title};
    string output = JsonConvert.SerializeObject(createContact);
    return output;
}

[JsonProperty(PropertyName = "9")]
public string Title
{
    get
    {
        return _title;
    }
    set
    {
        _title = value;
        _title = GetTitleId(Title).ToString();
    }
}

public static int? GetTitleId(string title)
{
    //remove "."
    var titleRemoveDots = title.Replace(".", "");
    var titleLowerCase = titleRemoveDots.Trim().ToLower();
    switch(titleLowerCase)
    {
        case "dir":
            return 1;
        case "dr": case "doctor":
            return 4;
        case "mag": case "magister":
            return 5;
        case "ing":
            return 6;
        case "dipling": case "dipl":
            return 7;
        case "prof": case "professor":
            return 8;
        case "dkfm":
            return 9;
        case "prok":
            return 12;
        default:
            return null;
    }
}


texts: Simple program to detect the number of times a vowel occurs in a string

texts:
I wrote a simple program to print out any vowels found in a string, as well as the amount of times that vowel occurs.

Here is my code:

#include <iostream>
#include <string>
#include <map>

void findVowels(std::string& theString, std::map<char,int>& map);
bool vowelCount(char& temp);
std::ostream& operator<<(std::ostream& out, const std::map<char, int>& map);

int main()
{
    bool keepGoing = true;
    while (keepGoing)
    {
        std::cout << "Enter a string to see how many times vowels were used.\n";
        std::string userInput;
        std::getline(std::cin, userInput);

        std::map<char, int> theMap;
        findVowels(userInput, theMap);

        std::cout << theMap;
        std::cout << "\nWould you like to keep going? Please type Y to continue or N to exit.\n";

        char nextAction;
        std::cin >> nextAction;
        if (nextAction == 'N' || nextAction == 'n')
            keepGoing = false;
        else if (nextAction != 'Y' && nextAction != 'y')
            std::cout << "Incorrect input. Defaulting to yes.\n";
        std::cin.ignore();
    }
    std::cout << std::endl;
    system("pause");
    return 0;
}

void findVowels(std::string& theString, std::map<char, int>& theMap)
{
    int stringSize = static_cast<int>(theString.size());
    for (int i = 0; i < stringSize; i++)
    {
        if (vowelCount(theString[i]))
            theMap[theString[i]]++;
    }
}

bool vowelCount(char& temp)
{
    temp = toupper(temp);
    return (temp == 'A' || temp == 'E' || temp == 'I' || temp == 'O' || temp == 'U');
}

std::ostream& operator<<(std::ostream& out, const std::map<char, int>& theMap)
{
    std::map<char, int>::const_iterator iter = theMap.cbegin();
    std::map<char, int>::const_iterator iterEnd = theMap.cend();
    while (iter != iterEnd)
    {
        out << iter->first << " has " << iter->second << " number of occurences.\n";
        iter++;
    }

    return out;
}


texts:
I've started learning to program, and as the first program I wrote on my own I wanted to come up with a number guessing game - the below is what I got.
I'm mainly looking for a review of my Guess function, but I do have a few specific questions:

Does it make sense to have my loop variable as a function parameter?
I'm currently defining some variables (e.g. tries) outside of my function - is this an idiomatic way to do it?

import random
tries = [1]
def Guess(playing):
    number = random.randint(1,100)
    print(number)
    print("We are going to play high and low, the avabile numbers are from 1 to 100 included.")
    while playing == True:
        user_input = input("What is your number? ")
        if int(user_input) == number:
            print("You have won!")
            playing = False
        elif int(user_input) < number:
            print("You need to give a higher number")
            tries.append(1)
        elif int(user_input) > number:
            print("You need to give an lower number")
            tries.append(1)
        else:
            print("You have put an wrong number")
            playing = False
    print("It took you " + str(sum(tries)) + " turns to guess")
    still = input("Do you want to play again?")
    if still == "yes" or still == "YES" or still == "y" or still == "si":
        Guess(playing=True)
    else:
        playing=False

Guess(playing=True)


texts: Create unique string from id to build an link shortening system

texts:
I want to build my own link shortening system. Therefore I need a way to create unique strings from the record ids stored in my database table.
So far I came up with this. I wonder if you now a faster or better idea? Or are there any caveats to my method?
// generate unique alphanumeric string from id with map
function idToString($id) {
    $map = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; # 62 characters (a-z;A-Z;0-9)
    $string='';
    if ($id<62) return $map[$id]; // return immediately
    while ($id>0) {
        if ($id%62>=0) {
            $string=$string.$map[$id%62];
            $id=intval($id/62);
        }
    }
    $string=strrev($string);     // Reverse string to emulate human reading
    return $string;
}

// get integer ID back from a String
function stringToID($string) {
    $map = str_split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); # same map as above of course
    $string=strrev($string);
    $string_array=str_split($string);
    $id=0;
    foreach ($string_array as $k=>$c) {
        $id=$id+(array_keys($map, $c)[0])*pow(62, $k);
    }
    return $id;
}

echo idToString(247698); // bcBi
echo stringToID('bcBi'); // 247698


texts:
This is a client module of an Eclipse plugin. I am planning to use this code as a "good exception handling" code example in one of my papers. How does it look?

HttpURLConnection httpconn=null;
BufferedReader breader=null;
try{
    URL url=new URL(this.web_service_url);
    httpconn=(HttpURLConnection)url.openConnection();
    httpconn.setRequestMethod("GET");
    System.out.println(httpconn.getResponseMessage());
    if(httpconn.getResponseCode()==HttpURLConnection.HTTP_OK)
    {
        breader=new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
        String line=null;
        while((line=breader.readLine())!=null)
        {
            jsonResponse+=line;
        }
        //System.out.println(jsonResponse);
        //display_json_results(jsonResponse);
    }
}catch(MalformedURLException e){
    MessageDialog.openError(Display.getDefault().getShells()[0], "Invalid URL", e.getMessage());
}catch(ProtocolException e){
    MessageDialog.openError(Display.getDefault().getShells()[0], "Invalid Protocol", e.getMessage());
}
catch(IOException e2){
    Log.info("Failed to access the data"+e2.getMessage());
}
finally{
    try{
    breader.close();}catch(IOException e){
        Log.info("Failed to release resources"+e.getMessage());
    }

}


texts: For a given balance and an annual interest rate, calculate the minimum fixed monthly payment to pay off debt in a year

texts:
Interest is compounded monthly. Payment doesn't  vary from month to month.

Version 1

balance = 999999
annualInterestRate = 0.18
mRate = annualInterestRate/12
high = (((mRate+1)**12)*balance)/12
low = balance/12
guessed = False

def balanceLeft(balance,mRate,minPayment):
    monthsLeft = 12
    while monthsLeft > 0:
        unpaidBalance =  balance - minPayment
        interest = mRate * unpaidBalance
        balance = unpaidBalance
        balance += interest
        monthsLeft -= 1
    return balance

while guessed == False:
    minPayment = (high + low) / 2
    if round(balanceLeft(balance,mRate,minPayment),2) < 0:
        high = minPayment
    elif round(balanceLeft(balance,mRate,minPayment),2)> 0:
        low = minPayment
    else:
        if abs(round(balanceLeft(balance,mRate,minPayment),2) - 0) < 0.01:
            guessed = True

print('Lowest Payment: ',end='')
print(round(minPayment,2))

Version 2

annualInterestRate = 0.18
rate = annualInterestRate / 12
monthsLeftr = 12
xCoefficent = 1 + rate
ConstantTerm = 1 + rate
while monthsLeftr > 1:
    xCoefficent = (xCoefficent + 1) * ConstantTerm
    monthsLeftr -= 1

balance = 999999
monthsLeft = 12
while monthsLeft > 0:
    balance = balance * ConstantTerm
    monthsLeft -= 1
minPayment = balance / xCoefficent

print('Lowest Payment: ', end="")

I would like a comparative and overall review, please!


texts: Nested if-else within a for-loop using np.concatenate to create batches for a neural network

texts:
I am having a for-loop in python 3.5. Inside the loop, I have multiple if-else statements in which I append some information. I am using this piece of code to create batches for a neural network built in Tensorflow.

Here is my code:

for generated_lemma, classified_lemma, token_hidden, token_hidden_generator in zip(
        tokens_generated,
        tokens_classified,
        token_dnn_output,
        token_generator_output
):
    if generated_lemma.replace('#', '|') not in self.lemmas_word2vec_model:
        if classified_lemma.replace('#', '|') not in self.lemmas_word2vec_model:
            if classified_lemma == '<UNK>':
                x.append(
                    np.concatenate([
                        self.embedding_unknown_lemma,
                        self.embedding_unknown_token,
                        token_hidden,
                        token_hidden_generator
                    ]
                    )
                )
            else:
                x.append(
                    np.concatenate([
                        self.embedding_unknown_lemma,
                        self.embedding_unknown_lemma,
                        token_hidden,
                        token_hidden_generator
                    ]
                    )
                )
        else:
            x.append(
                np.concatenate([
                    self.embedding_unknown_lemma,
                    self.lemmas_word2vec_model[classified_lemma.replace('#', '|')],
                    token_hidden,
                    token_hidden_generator
                ]
                )
            )
    elif classified_lemma.replace('#', '|') not in self.lemmas_word2vec_model:
        if classified_lemma == '<UNK>':
            x.append(
                np.concatenate([
                    self.lemmas_word2vec_model[generated_lemma.replace('#', '|')],
                    self.embedding_unknown_token,
                    token_hidden,
                    token_hidden_generator
                ]
                )
            )
        else:
            x.append(
                np.concatenate([
                    self.lemmas_word2vec_model[generated_lemma.replace('#', '|')],
                    self.embedding_unknown_lemma,
                    token_hidden,
                    token_hidden_generator
                ]
                )
            )
    else:
        x.append(
            np.concatenate([
                self.lemmas_word2vec_model[generated_lemma.replace('#', '|')],
                self.lemmas_word2vec_model[classified_lemma.replace('#', '|')],
                token_hidden,
                token_hidden_generator
            ]
            )
        )

My code works fine, although it is a bit slow. Hence, I would like to know if there was a more "pythonic" way to achieve the same thing?

My aim is to improve both style and performance.


texts: Calling stored procedure with a sqlCommand

texts:
I have the following code as part of an sqlCommand which is calling a stored procedure:

Dim groupObj

If groupId = 0 Then
    groupObj = DBNull.Value
Else
    groupObj = groupId
End If

Dim siteObj

If siteId = 0 Then
    siteObj = DBNull.Value
Else
    siteObj = siteId
End If

sqlCommand.Parameters.Add(New SqlClient.SqlParameter("GroupID", SqlDbType.Decimal)).Value = groupObj
sqlCommand.Parameters.Add(New SqlClient.SqlParameter("SiteID", SqlDbType.Decimal)).Value = siteObj

I basically want to check for a condition and (if true) send a DBNull instead.  This code looks awful however - is there a way to succinct this up?


texts: Compare last modification time with specfied time

texts:
I'm writing a function in Python that compares the modification time of a file in Linux (using os.stat) with a specific time and compare the dates. If the modification date is older than the date I specified, an event should happen.

import os
import time
import datetime

# File Modification time in seconds since epoch
file_mod_time = round(os.stat(file).st_mtime)

# Time in seconds since epoch for time, in which logfile can be unmodified.
t = datetime.datetime.today() - datetime.timedelta(minutes=30)
should_time = round(time.mktime(t.timetuple()))

# Time in minutes since last modification of file
last_time = round((int(time.time()) - file_mod_time) / 60, 2)

if (file_mod_time - should_time) < args.time:
    print "CRITICAL:", file, "last modified", last_time, "minutes. Threshold set to 30 minutes"
else:
    print "OK. Command completed successfully", last_time, "minutes ago."

It is working but I have the feeling that this could be largely improved, because there are so many time conversions. Can you give me a hint on how I can make it better?


texts: Find a service and update its last ping time

texts:
I found those functions reviewing a C++14 codebase I am working on:

struct Service {
    Service(std::string id): id(id) {}
    virtual ~Service() {}

    std::string id;
    HeartbeatCheckpoint lastPing;
    HeartbeatCheckpoint lastPong;
};

std::map<std::string, Service> services;

bool Pacemaker::updatePong(const std::string& id) {
    auto found = services.find(id);
    if(found != services.end()) {
        found->second.lastPong = std::chrono::high_resolution_clock::now();
        return true;
    }
    return false;
}

bool Pacemaker::updatePing(const std::string& id) {
    auto found = services.find(id);
    if(found != services.end()) {
        found->second.lastPing = std::chrono::high_resolution_clock::now();
        return true;
    }
    return false;
}

I would like to refactor them creating a common function to remove code duplication, but I can't figure out how to pass the member variable (lastPing and lastPong).

Is there a better way to write this code?


texts:
This code is a solution for /r/daily_programmer #293.

The idea of this challenge is, you are given input in the form of colored wires:

red wire
green wire
blue wire
...

and you are then to determine if cutting the input wires in the order they are listed will cause the "bomb" to detonate or defuse.

What causes the detonation is determined by the previous wire cut.  The challenge lists a pre-determined set of colored wires for which the previous wire is not allowed to be followed by a cut of that color or the bomb will detonate.

#include <vector>
#include <fstream>
#include <iostream>

using namespace std;

#define ERROR(msg)           \
    do {                     \
        cout << msg;         \
        exit(1);             \
    } while(1)               \

/*
 * WHITE  :: !WHITE,  !BLACK
 * RED    :: !WHITE,  !RED,    !BLACK  !ORANGE, !PURPLE
 * BLACK  :: !WHITE,  !GREEN,  !ORANGE
 * ORANGE :: !WHITE,  !ORANGE, !GREEN, !PURPLE
 * GREEN  :: !RED,    !BLACK,  !GREEN, !PURPLE
 * PURPLE :: !PURPLE, !GREEN,  !WHITE, !ORANGE
 */

string color_names[] = { "white",
                         "red",
                         "black",
                         "orange",
                         "green",
                         "purple" };

#define WHITE   1 << 0
#define RED     1 << 1
#define BLACK   1 << 2
#define ORANGE  1 << 3
#define GREEN   1 << 4
#define PURPLE  1 << 5

#define COLORS       6

int color_values[] { WHITE,
                     RED,
                     BLACK,
                     ORANGE,
                     GREEN,
                     PURPLE };

int conflicts[COLORS] = { WHITE | BLACK,
                          WHITE | RED | BLACK | ORANGE | PURPLE,
                          WHITE | GREEN | ORANGE,
                          WHITE | ORANGE | GREEN | PURPLE,
                          RED | BLACK | GREEN | PURPLE,
                          PURPLE | GREEN | WHITE | ORANGE };

class Wire {

    private:
        int color_value;
        int color_conflicts;

    public:
        Wire();
        Wire(string color);
        string color_name;
        int is_conflicted(Wire wire);
};

Wire::Wire(void)
{}

Wire::Wire(string color)
{
    for (int i=0; i < COLORS; i++)
        if (!color.compare(color_names[i])) {
            color_name = color_names[i];
            color_value = color_values[i];
            color_conflicts = conflicts[i];
        }
}

int Wire::is_conflicted(Wire wire)
{
    return color_conflicts & wire.color_value;
}

class Bomb {

    private:
        Wire current_wire;
        int explode(void);
        vector<Wire> previous_cuts;

    public:
        Bomb(string initial_wire);
        int cut_wire(string wire);
        vector<Wire> get_previous_cuts();
};

Bomb::Bomb(string initial_wire)
{
    string wire(initial_wire);
    Wire current_wire(wire);
    previous_cuts.push_back(current_wire);
}

int Bomb::cut_wire(string wire)
{
    Wire new_wire(wire);
    previous_cuts.push_back(new_wire);

    if (current_wire.is_conflicted(new_wire))
        return explode();
    current_wire = new_wire;
    return 0;
}

int Bomb::explode(void)
{
    cout << "Bomb explodes\n";
    return -1;
}

int main(int argc, char *argv[])
{
    if (argc < 2)
        ERROR("Error Usage: ./bomb_defuse_challenge <input>\n");

    string bomb_fname(argv[1]);
    ifstream bomb_fh(bomb_fname);

    if (!bomb_fh.is_open())
        ERROR("Error reading bomb input\n");

    string input_wire_color;
    getline(bomb_fh, input_wire_color);
    Bomb bomb(input_wire_color);

    while (getline(bomb_fh, input_wire_color)) {
        if (bomb.cut_wire(input_wire_color) < 0)
            return 0;
    }

    cout << "Bomb defused\n";

    return 0;
}


texts: C++ - Graph implementation for data types other than int

texts:
I am learning graphs and most of the implementations that I see are meant for int. So, I decided to code an example that can take other data types such as char or float. I did see this prior to posting my example (but not prior to coding my example). The example in the link is similar to creating a Tree where a separate Node class is used to keep track of node value, left and right child. In the link, instead of left and right child, the GraphNode class keeps track of neighbors.

My code does not use that approach and instead keeps the Adjacency List completely to Graph class, similar to usual implementations meant for int type. The idea is that if anyone needs to define a custom data type, it can be coded later (So, my code does not have a counterpart for GraphNode yet). The Graph is initialized by a vector of edges. The edges are represented by std::pair of nodes/ vertices involved. I have posted my code below. I am interested in knowing if there is a way to represent adjacency list, better than a map of lists, using stl containers, and can still handle different data types. However, any reviews or improvements or suggestions are welcome:

#include <iostream>
#include <vector>
#include <list>
#include <map>

template<typename T>
void print_list(std::list<T> l)
{
    typename std::list<T>::const_iterator it;
    for(it = l.cbegin(); it != l.cend(); it++)
    {
        std::cout << *it << "\t";
    }
    std::cout << std::endl;
}

template<typename T>
class Graph
{
    //Undirected Graph
    std::map<T, std::list<T>> adj_list;
public:
    Graph(std::vector<std::pair<T, T>>);
    void add_edge(std::pair<T, T>);
    size_t size();
    void print_adj_list();
};

template<typename T>
Graph<T>::Graph(std::vector<std::pair<T, T>> edges)
{
    for(size_t i = 0; i < edges.size(); i++)
    {
        this -> add_edge(edges[i]);
    }
}

//Undirected Graph
template<typename T>
void Graph<T>::add_edge(std::pair<T, T> edge)
{
        adj_list[edge.first].push_back(edge.second);
        adj_list[edge.second].push_back(edge.first);
}

template<typename T>
size_t Graph<T>::size()
{
    std::cout << "Size of Graph(no. of vertices): " << std::endl;
    return adj_list.size();
}

template<typename T>
void Graph<T>::print_adj_list()
{
    std::cout << "The Adjacency List: " << std::endl;
    typename std::map<T, std::list<T>>::const_iterator it;
    for(it = adj_list.cbegin(); it != adj_list.cend(); it++)
    {
        std::cout << it -> first << "\t";
        print_list<T>(it -> second);
    }

}
int main()
{
    /*std::vector<std::pair<int, int>> v;
    v.push_back({1, 2});
    v.push_back({2, 8});
    v.push_back({2, 5});
    v.push_back({2, 4});
    v.push_back({3, 4});
    v.push_back({5, 9});
    v.push_back({5, 7});
    v.push_back({5, 6});
    Graph<int> g{v};*/

    std::vector<std::pair<char, char>> v;
    v.push_back({'a', 'b'});
    v.push_back({'b', 'h'});
    v.push_back({'b', 'e'});
    v.push_back({'b', 'd'});
    v.push_back({'c', 'd'});
    v.push_back({'e', 'i'});
    v.push_back({'e', 'g'});
    v.push_back({'e', 'f'});
    Graph<char> g{v};
    g.print_adj_list();
    std::cout << g.size() << std::endl;
    g.add_edge({'i', 'k'});
    g.add_edge({'f', 'k'});
    g.print_adj_list();
    std::cout << g.size() << std::endl;
    return 0;
}


texts:
I have been working the some project and I'm struggling to find the answer. Right now I'm coding with Angular and there some code that makes me write twice. There only two arrays now but if I have lots of arrays the code will be really big. The thing makes me stop always that I have to write the IDs one by one and I could not find the answer.

Please help me simplify the code even more.

$scope.allTheCont = [{
    styleClass: 'lftMn',
    theContId: 'theIdOne',
    pageNum: 'views/1.html',
    theOpn: function() {
        if ($scope.theIdOne) {
            return true
        };
    },
    imgClass: 'mainLeftImg',
    imgSrc: 'img/1.jpg',
    imgName: 'Traveling with sport',
    contClass: 'lftCnt',
    openCont: function() {
        $scope.all = false;
        $scope.theIdOne = true;
        $('.lftMn').addClass('lftMnOpnd')
        $('.lftCnt').addClass('mnCntOpnd')
        $('.mainLeftImg').addClass('mnImgOpnd')
        $location.hash('main');
        $anchorScroll();
    },
    closeCont: function() {
        $scope.all = true;
        $scope.theIdOne = false;
        $('.lftMn').removeClass('lftMnOpnd')
        $('.lftCnt').removeClass('mnCntOpnd')
        $('.mainLeftImg').removeClass('mnImgOpnd')
        $location.hash('theIdOne');
        $anchorScroll();
    }
}, {
    styleClass: 'mnRgtImg',
    theContId: 'theIdTwo',
    pageNum: 'views/2.html',
    theOpn: function() {
        if ($scope.theIdTwo) {
            return true
        };
    },
    imgClass: 'mnRgtImgs',
    imgSrc: 'img/2.jpg',
    imgName: 'Traveling with sport',
    contClass: 'mnRgtCnt',
    openCont: function() {
        $scope.all = false;
        $scope.theIdTwo = true;
        $('.mnRgtImg').addClass('mnRtOpnd')

        $('.mnRgtCnt').addClass('mnRtCntOpnd')
        $('.mnRgtImgs').addClass('mnRgtImgOpnd')
        $location.hash('main');
        $anchorScroll();
    },
    closeCont: function() {
        $scope.all = true;
        $scope.theIdTwo = false;
        $('.mnRgtImg').removeClass('mnRtOpnd')

        $('.mnRgtCnt').removeClass('mnRtCntOpnd')
        $('.mnRgtImgs').removeClass('mnRgtImgOpnd')
        $location.hash('theIdTwo');
        $anchorScroll();
    }

}]


texts: Decorator to measure execution time of a function

texts:
This decorator adds the elapsed time to a function's attributes when applied.
My concerns:

Is the code pythonic?
Could this code be useful?
Should I just use the timeit module?
Is the code easy to read and understand?

The code:
'''
:Date: 7/21/17
:Version: 1
:Authors:
    - Ricky L Wilson
'''

import datetime

def time_func(function):
  """ This decorator calculates the amount of time a function takes to execute.

  When time_func is applied to a function it records how long the function takes to
  finish and add the elapsed time to the functions attributes.

  - **parameters**
  :param function: The function you want to add the elapsed time attribute to.

  :Example:
  @time_func
  def example(name, **kwargs):
    meta = type(name, (object,), kwargs)
    return meta

  example('foo')
  print example.elapsed
  0:00:00.000052

  """
  def new_func(*args, **kwargs):
    # Start the clock.
    start = datetime.datetime.now()
    # Execute the function and record the results.
    function_result = function(*args, **kwargs)
    # Calculate the elapsed time and add it to the function
    # attributes.
    new_func.elapsed = datetime.datetime.now() - start
    # Returned the function with the added elapsed attribute
    return function_result
  return new_func


texts: Monge Array - leftmost minimum for each row

texts:
This implementation is the result of solving exercise 4-6 "Monge Arrays" from the book Introduction to algorithms.

Definition of a Monge Array:

  An m x n array A of real numbers is a Monge array if for all \$i\$,
  \$j\$, \$k\$, and \$l\$ such that \$1 \le i \lt k \le m\$ and \$1 \le j \lt l \le n\$, we have \$A[i, j] + A[k, l] \le A[i, l] + A[k, j]\$.

  Relevant parts of problem 4-6:

  d. Here is a description of a divide-and-conquer algorithm that
  computes the left- most minimum element in each row of an m x n Monge
  array A:

  Construct a submatrix A' of A consisting of the even-numbered rows of
  A. Recursively determine the leftmost minimum for each row of A'. Then
  compute the leftmost minimum in the odd-numbered rows of A. Explain
  how to compute the leftmost minimum in the odd-numbered rows of A
  (given that the leftmost minimum of the even-numbered rows is known)
  in \$O(m + n)\$ time.

  e. Write the recurrence describing the running time of the algorithm
  described in part (d). Show that its solution is \$O(m + nlog(m))\$.

I am especially interested in making my code more idiomatic and clean although any improvements to the algorithm are also welcome.

fn min(monge: &Vec<i32>, from: usize, to: usize) -> usize{

    let mut min = monge[from];

    (from + 1..to).fold(from, |m,i| {

        if(monge[i] < min){
            min = monge[i];
            i
        } else{ m }
    })
}

fn minimums(monge: &Vec<i32>, leftmost: & mut Vec<usize>, rows: usize, columns: usize, factor: usize)
{

    if rows == 1 {
        leftmost[0] = min(monge, 0, columns) % columns;
    }
    else {

        let mid = rows - (rows / 2);
        minimums(monge, leftmost, mid, columns, 2 * factor);

        let get = |i, j| (i * columns) + j;

        for row in (0..)
                       .map(|x| factor * (2 * x + 1))
                       .take_while(|&x| x < (rows - 1)) {

            leftmost[row] =  min(monge,
                                 get(row ,leftmost[row - factor]),
                                 get(row, leftmost[row + factor] + 1)) % columns;
        }

        if rows % 2 == 0 {

            let row = factor * (rows - 1);
            leftmost[row] = min(monge,
                                get(row , leftmost[row - factor]),
                                get(row, columns)) % columns;
        }

    }
}

fn main() {

    let row = 7;
    let x = vec!
    [10,17,13,28,23,
     17,22,16,29,23,
     24,28,22,34,24,
     11,13,6,17,7,
     45,44,32,37,23,
     36,33,19,21,6,
     75,66,51,53,34];

    let mut leftmost = vec![0;row];

    minimums(&x, &mut leftmost, row,5, 1);

    for x in leftmost {
        println!("{}", x);
    }

}


texts:
I'm trying to learn Javascript and I've set up a bill calculator. Most of the lines in the code are to deal with rounding. It has four main components:

Allows you to enter the bill amount and tip percentage.
Calculates the total bill divided by the number of guests.
Calculates the total tip.
Splits the bill by the number of guests.

billAmount = 134.93
const enterTipPercent = 10
const guests = ["Person1", "Person2", "Person3", "Person4"]
const noOfGuests = guests.length;
console.log('Chosen tip: ' + enterTipPercent + '%')

function splitBill() {
  var split = billAmount / noOfGuests;
  var rounding = split.toFixed(2);
  var elseIf = rounding * noOfGuests;

if (rounding == billAmount/noOfGuests) {
  console.log('Each person must pay: £' + rounding +' with no remainder');

}

else if (elseIf * noOfGuests > billAmount){
  var roundDown = Math.floor(split*100) /100;
  var remainingAmount = billAmount-roundDown*noOfGuests;
  var roundedRemainder = remainingAmount.toFixed(2);
  console.log('Each person must pay: £' + roundDown +' with £' + roundedRemainder + ' remaining');
  }
}

function calculateTip() {
  var tip = billAmount/100*enterTipPercent;
  var tipRound = tip.toFixed(2);
  return tipRound;
}

function splitTip() {

  if (calculateTip() * 10 == billAmount) {
    var tipShare = calculateTip();
    var tipDivide = tipShare/noOfGuests;
    var tipRound = tipDivide.toFixed(2);
    console.log('Each person must tip: £' + tipRound);
}
  else  {
  var tipShare = calculateTip();
  var tipDivide = tipShare/noOfGuests;
  var tipRound = Math.floor(tipDivide *100) /100;
  var tipremainder = calculateTip()-tipRound*noOfGuests;
  var tipRoundRemainder = tipremainder.toFixed(2);
  console.log('Each person must tip: £' + tipRound + ' with £' + tipRoundRemainder + ' remaining');
  }
}

splitBill();
console.log('total tip £' + calculateTip());
splitTip();const

The code I've written works fine, but I'm sure this isn't the best, or most efficient way I could have done it. Does anyone have any advice on how I can improve?


texts:
I come more from a frontend background and have been reading up on more backend approaches and algorithms while solving a TicTacToe grid to see if there are any wins normally, I'd probably use something like this

for (let i = 0; i < rows; i++) {
    if (arr[i][0] === arr[i][1] && arr[i][0] === arr[i][2]) {

but with what I've been studying, I thought it'd be better to use a map and iterate through them instead

'use strict';

const board = [
  ['x','x','x'],
  ['x','o','o'],
  ['x','x','x']
]

const matches = [
  [1,4,7],
  [2,5,8],
  [3,6,9],
  [1,2,3],
  [4,5,6],
  [7,8,9],
  [1,5,9],
  [3,5,7]
]

const solver = (board, matches) => {
  // build map
  let counter = 1;
  const map = {};

  // convert array to object
  for (let row of board) {
    for (let char of row) {
      map[counter] = char;
      counter++;
    }
  }

  for (let match of matches) {
    // create a new array with the values
    const arr = [...map[match[0]],map[match[1]],map[match[2]]];
    // check for duplicates
    const arr2 = [...new Set(arr)].join("");
    // console log if length is 1
    if (arr2.length === 1) console.log(`match found at set: ${match}`)
  }
}

solver(board, matches)

Is this efficient? Is there a better way of doing this?

It looks a lot cleaner than

if (arr[i][0] === arr[i][1] && arr[i][0] === arr[i][2])

for sure, but then again, that itself could have probably been designed more efficiently.

Is there a better way to generate the coordinates dynamically?


texts: Interface for obtaining the bounding box for a collection of elements

texts:
How could I improve this code?
I used a position interface to avoid code duplication, can it be done better?
Can I reduce the amount of code somehow?

interface PositionInterface
{
    double getPosition(PageAreaInterface pArea);
}

private double getMinPosition(Collection<PageAreaInterface> pAreas, PositionInterface pPosition)
{
    double lMinPosition = Double.MAX_VALUE;
    for (PageAreaInterface lArea : pAreas)
    {
        lMinPosition = Math.min(lMinPosition, pPosition.getPosition(lArea));
    }
    return lMinPosition;
}

private double getTop(Collection<PageAreaInterface> pAreas)
{
    return getMinPosition(
                pAreas,
                new PositionInterface()
                {
                    @Override
                    public double getPosition(PageAreaInterface pArea)
                    {
                        return pArea.getBoundingBox().getTop();
                    }
                }
    );
}

private double getLeft(Collection<PageAreaInterface> pAreas)
{
    return getMinPosition(
                pAreas,
                new PositionInterface()
                {
                    @Override
                    public double getPosition(PageAreaInterface pArea)
                    {
                        return pArea.getBoundingBox().getLeft();
                    }
                }
    );
}

private double getMaxPosition(Collection<PageAreaInterface> pAreas, PositionInterface pPosition)
{
    double lMaxPosition = Double.MIN_VALUE;
    for (PageAreaInterface lArea : pAreas)
    {
        lMaxPosition = Math.max(lMaxPosition, pPosition.getPosition(lArea));
    }
    return lMaxPosition;
}

private double getBottom(Collection<PageAreaInterface> pAreas)
{
    return getMaxPosition(
                pAreas,
                new PositionInterface()
                {
                    @Override
                    public double getPosition(PageAreaInterface pArea)
                    {
                        return pArea.getBoundingBox().getBottom();
                    }
                }
    );
}

private double getRight(Collection<PageAreaInterface> pAreas)
{
    return getMaxPosition(
                pAreas,
                new PositionInterface()
                {
                    @Override
                    public double getPosition(PageAreaInterface pArea)
                    {
                        return pArea.getBoundingBox().getRight();
                    }
                }
    );
}


texts:
I'm doing a website in CodeIgniter and I'm loading the content page via jQuery, but I don't know if this is a good practice or not. Could I improve it?

jQuery:

// Another question here: how can I group the repeated code in a function:

$(function() {

var control = '../Indoamericana/Intranet/index/Proceso/';

var loadPage = function(page){
    $(".page-content").load(page);
};

$("#gestion_directiva").click(function(event) {
    var process = 1;
    loadPage(control + process);
});

$("#gestion_calidad").click(function(event) {
    var process = 2;
    loadPage(control + process);
});

$("#gestion_academica").click(function(event) {
    var process = 3;
    loadPage(control + process);
});

Controller:

/**
* index();
*
* funcion que carga la información del proceso en la intranet
* @param String $process Identificador del proceso a cargar
* @return Vista del proceso indicado
*/

public function index($process, $idProcess){

    $data['data'] = $this->intranet_model->getProcessInfo($idProcess);
    $data['member'] = $this->intranet_model->getMembers($idProcess);
    $data['proceso'] = 'GI7';

    $route = '/Modules/Intranet/';
    $route .= $process;

    $this->load->view($route, $data);
}

View:

            <?php foreach ($data as $row): ?>
            <?php echo $row->name ?>
            <?php endforeach ?>

                Página Principal

                Intranet

                    <?php foreach ($data as $row): ?>
                    <?php echo $row->name ?>
                    <?php endforeach ?>


texts: Makefile for CGI program using SQLite library

texts:
I am developing a CGI program in C on Linux using gcc, GNU make and the SQLite library. How does my makefile look?

# Automatic Variables
# $@ file name of target
# $< name of the first prerequisite
# $? name  of all prerequisites newer than target
# $^ names of all prerequisites
# Pattern rule example - complile object files from prerequisites
# %.o: %.c
#   $(CC) -c $(CFLAGS) $< -o $@
#
# Predefined Variables
# CC compiler, default gcc
# CFLAGS compiler flags
# LDFLAGS linker flags such as -L (extra directories searched for -l)
# LDLIBS libaries such as -lfoo

CC=gcc
CFLAGS=-ansi -pedantic -Wall -Wextra -O2
LDLIBS=-ldl -lpthread
# directory of SQLite library
SQLITEDIR=sqlite

sqlfun.cgi: sqlfuncgi.o sqlite3.o
    $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS)

sqlite3.o: $(SQLITEDIR)/sqlite3.c
    $(CC) -o $@ $^ -c -Os

sqlfuncgi.o: sqlfuncgi.c
    $(CC) -o $@ $^ -c $(CFLAGS)

.PHONY: clean test
clean:
    rm -f sqlfun.cgi *.o

test:
    clear
    cppcheck --enable=all --inconclusive --std=c89 sqlfuncgi.c
    valgrind --leak-check=yes ./sqlfun.cgi test


texts: Best combination of a sum between two parameters in an array of objects

texts:
I am trying to build a simple algorithm to achieve the best combination of values based on two params in an array of objects.
The whole code is available here
First I have an array holding objects. The items which will be analyzed and packed into volumes together. All of the values are in percentages.
const nonStackableItems = [
    {
      id: 0,
      m2: 15,
      m3: 11,
      weight: 20
    },
    {
      id: 1,
      m2: 25,
      m3: 12,
      weight: 42
    },
    {
      id: 2,
      m2: 50,
      m3: 13,
      weight: 40
    },
    {
      id: 3,
      m2: 65,
      m3: 14,
      weight: 25
    }
  ];

The idea is to combine these objects into packages, respecting the maximum of 100% for each value (except for m3 in this case, as all the packages should have enough height in this first analysis).
The approach that I gave is just not good enough, as I am sorting this array by m2 then by weight, call the function and then compare the length of both, and then choose the result that creates less volumes.
This is the piece of code that does the calculations:
function nSVolHelper(arr, vol, param1, param2) {
    let newVol = {
      id: vol.length,
      m2: 0,
      m3: 0,
      weight: 0
    };
    for (let i = 0; i < arr.length; i++) {
      const validation =
        newVol[param1] + arr[i][param1] < 100 &&
        newVol[param2] + arr[i][param2] < 100;
      if (validation) {
        newVol.m2 += arr[i].m2;
        newVol.m3 += arr[i].m3;
        newVol.weight += arr[i].weight;
      }
      if (!validation) {
        return nSVolHelper(arr.slice(i), [...vol, newVol], param1, param2);
      }
    }
    vol.push(newVol);
    return vol;
  }

  function nSVol(arr, param1, param2) {
    return nSVolHelper(arr, [], param1, param2);
  }

I would like to find a way of doing this without taking as a base the order of the array, to get the finest calculation without running unnecessary code, and I get the feeling that this approach of mine is just not reliable as well.
As an example, for better understanding:
If I pass the array sorted by weight I get a create 2 volumes.
console.log(
    "call",
    nSVol(
      nonStackableItems.sort((a, b) => a.weight - b.weight),
      "weight",
      "m2"
    )

If I pass this same array sorted by m2 I get 3 volumes.
console.log(
    "call",
    nSVol(
      nonStackableItems.sort((a, b) => a.m2 - b.m2),
      "weight",
      "m2"
    )

This was the best approach that I could find, but I feel that there could be another way of thinking of this.


texts: Summing CSV files row by row using Node.js events

texts:
I need to read multiple CSV files that have the same number of rows, and compute some results for each row. For simplification purposes, and in the scope of this code review, this computation would be "sum each column of each row".

I would like to be able to do so using the fast-csv parser that triggers events on each row reading. Mostly to avoid having to load the entire file into variables and then compute what I need.

I came up with the following solution, with a dummy example to sum the values from each file. It seems to be working, but because I'm working with events, I'm not sure if there might be a case when some data could go missing, or if there's any other issue. I would appreciate any help to improve performance, functionality, maintainability, readability, etc..

Because executing the code requires an external dependency and some files, here's a Repl.it.

Here's the code if you just want to read:

const csv = require("fast-csv");
const fs = require('fs');
const EventEmitter = require('events');

const files = ['csv/file1.csv', 'csv/file2.csv'];

// Create parsers for each file
const parsers = files.map(file => csv.parseStream(fs.createReadStream(file), { delimiter: ';', headers: false }));

// Variables to hold temporary data and definitive results
const data = parsers.map(() => []);
let result = [];

// Handler for a set of the same row from all the different files
var eventEmitter = new EventEmitter();
eventEmitter.on('allRows', (rows) => {
  var sum = (r, a) => r.map((b, i) => Number(a[i]) + Number(b));
  result.push(rows.reduce(sum));
});

// Handler to display the result once all files have been read
eventEmitter.on('end', (rows) => {
  console.log("result", result);
});

// Handler for each row reading
const onDataHandler = function(row, idx) {
  data[idx].push(row);
  // When we have a row parsed for each file, we emit a signal
  if (data.reduce((acc, el) => acc && el.length > 0, true)) {
    if (data.reduce((acc, el) => acc && el[0] === null, true)) {
      // 'end' if all results have been shifted
      eventEmitter.emit('end');
    } else {
      // 'allRows' otherwise, with the first element of each file
      eventEmitter.emit(
        'allRows',
        data.reduce((acc, el) => {
          acc.push(el.shift());
          return acc;
      }, [])
      );
    }
  }
}

// We use readable to use 'flowing' mode and make sure we don't miss the last rows
parsers.forEach((parser, idx) => parser.on('readable', () => {
  onDataHandler(parser.read(), idx);
}));


texts: Using System.Security.Cryptography.Aes to generate encryption key

texts:
Is the below method a safe way of generating a random encryption key to be used with AES (SymmetricAlgorithm) in .NET?

It essentially piggybacks off of the Aes alg to create a random key, trimmed to the correct bit size.

    /// <summary>
    /// Defines AES key sizes.
    /// </summary>
    public enum KeySize
    {
        /// <summary>
        /// Key size of 128 bits.
        /// </summary>
        Aes128 = 128,

        /// <summary>
        /// Ket size of 192 bits.
        /// </summary>
        Aes192 = 192,

        /// <summary>
        /// Key size of 256 bits.
        /// </summary>
        Aes256 = 256
    }

    /// <summary>
    /// Generates an AES key.
    /// </summary>
    /// <param name="size">Specifies the desired key size.</param>
    /// <returns>AES key.</returns>
    public static string GenerateEncryptionKey(KeySize size)
    {
        using (var aes = Aes.Create())
        {
            int keySize = (int)size;

            if (aes.ValidKeySize(keySize))
            {
                aes.KeySize = keySize;
                aes.GenerateKey();

                return Convert.ToBase64String(aes.Key);
            }
            else
            {
                return null;
            }
        }
    }


texts: Looking for a better solution than a bunch of switch statements in my JavaScript

texts:
I'm calling this function from my html (and in some cases from another function in my JavaScript).  These type of switch statements are starting to litter my code.  Is there a more elegant solution to these if statements?  I wish I could pass a reference to the variables I want to modify.  I'm finally asking the question because now I have a situation where if I do it this same way, I'm going to have an ugly switch statement with hundreds of cases which I'm guessing not only looks ugly, but will hurt performance.

function incCriteriaStats(exp){
    switch (exp) {
      case "a":
        numOfA++;
        break;
      case "b":
        numOfB++;
        break;
      case "c":
        numOfC++;
        break;
      case "d":
        numOfD++;
        break;
      case "e":
        numOfE++;
        break;
      case "f":
        numOfF++;
        break;
      case "g":
        numOfG++;
        break;
    }
|


texts:
def forward_date_range(start_dt, end_dt, span_days):
    #
    # Generate tuples with intervals from given range of dates (forward)
    #
    # forward_date_range('2012-01-01', '2012-01-5', 2)
    #
    # 1st yield = ('2012-01-01', '2012-01-03')
    # 2nd yield = ('2012-01-04', '2012-01-05')
    start_dt = datetime.datetime.strptime(start_dt, '%Y-%m-%d')
    end_dt   = datetime.datetime.strptime(end_dt, '%Y-%m-%d')
    span     = datetime.timedelta(days=span_days)
    step     = datetime.timedelta(days=1)

    while start_dt + span < end_dt:
        current = start_dt + span
        yield start_dt.strftime('%Y-%m-%d'), current.strftime('%Y-%m-%d')
        start_dt = current + step
    else:
        yield start_dt.strftime('%Y-%m-%d'), end_dt.strftime('%Y-%m-%d')

def backward_date_range(start_dt, end_dt, span_days):
    #
    # Generate tuples with intervals from given range of dates (backward)
    #
    # backward_date_range('2012-01-01', '2012-01-5', 2)
    #
    # 1st yield = ('2012-01-03', '2012-01-05')
    # 2nd yield = ('2012-01-01', '2012-01-02')
    start_dt = datetime.datetime.strptime(start_dt, '%Y-%m-%d')
    end_dt   = datetime.datetime.strptime(end_dt, '%Y-%m-%d')
    span     = datetime.timedelta(days=span_days)
    step     = datetime.timedelta(days=1)

    while end_dt - span > start_dt:
        current = end_dt - span
        yield current.strftime('%Y-%m-%d'), end_dt.strftime('%Y-%m-%d')
        end_dt = current - step
    else:
        yield start_dt.strftime('%Y-%m-%d'), end_dt.strftime('%Y-%m-%d')

This is currently what I have, needless to say it looks ugly. Is there a more elegant solution, especially if it is possible to get rid of the while loop altogether? or maybe compress it into one single line?

I am currently using python3.5


texts:
My program is complete and runs, and gives me the output I expect. For example, if I enter the string "HELLO" I should get 8. Are there any improvements that can be made?

#include "stdafx.h"
#include <iostream>
#include <cctype>
#include <string>
using namespace std;

int gameScore(string word);
int letterValue(char ch);

int main()
{
    while(true)
    {
        char word[80];
        cout << "Enter a word: ";
        cin.getline(word, 80);

        if(word[0] == ' ')
            break;

        int score = gameScore(word);
        cout << "The score for '" << word << "' is " << score << "\n";
    }

    system("PAUSE");
    return 0;
}

int gameScore(string word)
{
    int total = 0;
    int length = word.length();

    for(int i = 0; i < length; i++)
    {
        total += letterValue(word[i]);
    }

    return total;
}

int letterValue(char ch)
{
    int value = 0;

    switch(ch)
    {
        case 'A': case 'a':
        case 'E': case 'e':
        case 'I': case 'i':
        case 'L': case 'l':
        case 'O': case 'o':
        case 'R': case 'r':
        case 'S': case 's':
        case 'T': case 't':
        case 'U': case 'u':
            value += 1; break;
        case 'D': case 'd':
        case 'G': case 'g':
            value += 2; break;
        case 'B': case 'b':
        case 'C': case 'c':
        case 'M': case 'm':
        case 'P': case 'p':
            value += 3; break;
        case 'F': case 'f':
        case 'H': case 'h':
        case 'V': case 'v':
        case 'W': case 'w':
        case 'Y': case 'y':
            value += 4; break;
        case 'K': case 'k':
            value += 5; break;
        case 'J': case 'j':
        case 'X': case 'x':
            value += 8; break;
        case 'Q': case 'q':
        case 'Z': case 'z':
            value += 10; break;
    }
    return value;
}


texts: Wrap pattern "using std::begin; return begin(c);" into a function

texts:
I posted a C++17 version of wrapping functions for the “two-step”, on this Answer on StackOverflow.

It’s more than just handy to have a wrapper, as I was searching for good solutions on how to use begin (etc.) in a constructor initializer list, so there was no scope to add the using declaration to, and I could not push the function definition itself down into a nested namespace.

My point (in the SO post) is to follow Eric Niebler’s advice that these should be function-call objects, not functions!

I’ve refined it for general reuse within a body of code, for ambient use within a library and available from that library for other code.

I found I needed another dummy namespace wrapper — I don’t want the use std::begin; to be declared in namespace twostep, because people who use namespace twostep; into their desired scope should get only the Begin symbol it creates, not twostep::begin née std::begin as well.  From my reading of the standard, it appears that using namespace twostep will declare all the names declared in twostep, not just those names introduced.

I kept the distinct (capitalized) names rather than replacing the originals, because trying to have the new symbol (found without ADL) turn around and do the lookup with ADL and the using std::begin; added in to local scope would be a horrid nightmare and a puzzle unto itself.

Unlike Eric’s rather lengthy code, I was able to use the new inline feature for variables to handle ODR; and I got SFINAE to work with the lambda function (Eric couldn’t when he wrote that), so it is rather simple now and has the makings of a good idiom worth keeping.

I wonder if it is possible to generate these lambdas?  Ideally I could have

inline auto Begin = detail::wrap (&std::begin);

because the code is totally boilerplate:  get the signature from the forwarded-to function, but accomplish the SFINAE as well??!

Note that I don’t really need the full power of SFINAE here:  I’m not overloading on the search for Begin; I’m targeting the specific Begin symbol I want up front because it is found as a variable, not a function.  So getting an error somewhere once it tries to instantiate that template is sufficient; however, I want a clean neat error (Begin has no operator()) rather than template spew.  ‘neat enough’ would be OK, if a wrapper is feasible.

Here is the code with two wrappers.  Once I’m certain it will be the final form, I’ll add the rest of them.

#pragma once

#include <iterator>

namespace Dlugosz::d3 {

inline namespace twostep_wrapper {
// The std:: declarations need to be in scope for the two-step functions to work,
// but we don't want them to appear as declared names in namespace twostep.  That way,
// `using namespace twostep;` will bring in Begin but not bring in begin from std.

using std::begin;
using std::end;

inline namespace twostep_inner {

inline auto Begin = [](auto&& r) ->
    decltype(begin(std::forward<decltype(r)>(r))) // using return type to do SFINAE
{
    return begin(std::forward<decltype(r)>(r));
};

inline auto End = [](auto&& r) ->
decltype(end(std::forward<decltype(r)>(r)))
{
    return end(std::forward<decltype(r)>(r));
};

} // namespace twostep_inner

} // scope wrapper

// back in namespace d3
namespace twostep = twostep_wrapper::twostep_inner;
using namespace twostep;

}


texts: Finding the sum of the digits appearing in the leaves via in-order traversal

texts:
The following text is an in-order traversal of a binary tree with 1023
  nodes. What is the sum of the digits appearing in the leaves?

How can I improve this Clojure code? It looks strange to me to have two recurs in the if.

(ns fun2)

(defn parse [in sum]
 (println "sum" sum)
 (if (> (.length in) 1)
   (let [next-char (subs in 0 1)]
     (if (.matches next-char "[0-9]")
       (recur (subs in 2) (+ sum (Integer/parseInt next-char)))
       (recur (subs in 2) sum)))))

(parse (slurp "/Users/clojure/challange2.txt") 0)

;; ans 331


texts:
I want to achieve this:

digPow(89, 1) should return 1 since \$8^1 + 9^2 = 89 = 89 * 1\$
digPow(92, 1) should return -1 since there is no \$k\$ such that \$9^1 + 2^2\$ equals \$92 * k\$
digPow(695, 2) should return 2 since \$6^2 + 9^3 + 5^4 = 1390 = 695 * 2\$
digPow(46288, 3) should return 51 since \$4^3 + 6^4 + 2^5 + 8^6 + 8^7 = 2360688 = 46288 * 51\$

I have implemented it like this:

function digPow(n, p){
  var digits = n.toString().split('');
  var result = 0;
  for(var i=0; i<digits.length; i++){
    result = result + Math.pow(digits[i], p);
    p++;
  }
  var data = result/n;
  if(result % n === 0){
  return data;
  }else{
  return -1;
  }
}


texts:
I am wanting to constantly check a URL http://www.example.co.uk/untitled.php which will either return 1 or 0 on my app.

Is the most efficient way to do it by repeatedly requesting the URL every second like this?

Function to return content of URL

-(void)getOnline{
    if(connected==0){
        NSString *uuid = @"59xxxfb6d-4659-gdsf-sfsdf";

        NSString *URL = [NSString stringWithFormat:@"%@%@", @"http://www.example.co.uk/untitled.php?=", uuid];
        NSURLSession *aSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        [[aSession dataTaskWithURL:[NSURL URLWithString:URL] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (((NSHTTPURLResponse *)response).statusCode == 200) {
                if (data) {
                    NSString *contentOfURL = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    if([contentOfURL isEqual: @"1"]){
                        //do stuff
                    }
                }
            }
        }] resume];
    }
}

Function on load to repeatedly call the function above

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(getOnline) userInfo:nil repeats:YES];


texts:
I'm trying to produce a 3D point cloud from a depth image and some camera intrinsics. The image is 640x480, and is a NumPy array of bytes. The output is a (rows * columns) x 3 array of points.

I've gotten the function to work perfectly, but it's way too slow! (takes like 2 seconds per image to process). I'm wondering if there are any optimizations I can make before giving up and writing a C module.

def create_point_cloud(self, depth_image):
    shape = depth_image.shape;
    rows = shape[0];
    cols = shape[1];

    points = np.zeros((rows * cols, 3), np.float32);

    bytes_to_units = (1.0 / 256.0);

    # Linear iterator for convenience
    i = 0
    # For each pixel in the image...
    for r in xrange(0, rows):
        for c in xrange(0, cols):
            # Get the depth in bytes
            depth = depth_image[r, c, 0];

            # If the depth is 0x0 or 0xFF, its invalid.
            # By convention it should be replaced by a NaN depth.
            if(depth > 0 and depth < 255):
                # The true depth of the pixel in units
                z = depth * bytes_to_units;

                # Get the x, y, z coordinates in units of the pixel
                points[i, 0] = (c - self.cx) / self.fx * z;
                points[i, 1] = (r - self.cy) / self.fy * z;
                points[i, 2] = z
            else:
                # Invalid points have a NaN depth
                points[i, 2] = np.nan;
            i = i + 1
    return points


texts:
This script is for a student who has never programmed before. The goal is that she can quickly start to understand what is going on and start to tinker with it.

As I am not very familiar with Python I wonder whether I am breaking any important style paradigm and whether there are things that can make the code further readable, by making it shorter or simpler.

# Define function
def npn(n):
    """ Find the next perfect number after integer n
    """
    org = n = abs(n)
    while True:
        n += 1
        # Keep track of sum of the positive divisors
        spd = 1
        # Now check (other) possible divisors.
        # Note that subset of divisors to check can be greatly reduced...
        # which will increase efficiency
        for i in range(2, n):
            # Check divisibility with the modulo operator
            if (n % i == 0):
                spd += i
        if n == spd:
            print("The next perfect number after", org, "is", n)
            break

# Get user input
print("\n", "Check what is the next perfect number after n.")
while True:
    try:
        x = int(input("Enter your n: "))
    except ValueError:
        print("n should be a postive integer!")
        continue
    if x < 8128:
        break
    print("Oh. Finding perfect numbers is hard. Choose a lower number. Plz.")

# Run function with user input
npn(x)


texts:
This is my attempt at Conway's Game of Life. It works, and it's the most complicated program I've made to date.  I'm sure it's pretty poorly done. Any ideas on how I can improve on it?

#include <iostream>
#include <cstdlib>

const int gridsize = 75; //Making this a global constant to avoid array issues.

void Display(bool grid[gridsize+1][gridsize+1]){
    for(int a = 1; a < gridsize; a++){
        for(int b = 1; b < gridsize; b++){
            if(grid[a][b] == true){
                std::cout << " *";
            }
            else{
                std::cout << "  ";
            }
            if(b == gridsize-1){
                std::cout << std::endl;
            }
        }
    }
}
//This copy's the grid for comparision purposes.
void CopyGrid (bool grid[gridsize+1][gridsize+1],bool grid2[gridsize+1][gridsize+1]){
    for(int a =0; a < gridsize; a++){
        for(int b = 0; b < gridsize; b++){grid2[a][b] = grid[a][b];}
    }
}
//Calculates Life or Death
void liveOrDie(bool grid[gridsize+1][gridsize+1]){
    bool grid2[gridsize+1][gridsize+1] = {};
    CopyGrid(grid, grid2);
    for(int a = 1; a < gridsize; a++){
        for(int b = 1; b < gridsize; b++){
            int life = 0;
        for(int c = -1; c < 2; c++){
            for(int d = -1; d < 2; d++){
                if(!(c == 0 && d == 0)){
                    if(grid2[a+c][b+d]) {++life;}
                }
            }
        }
            if(life < 2) {grid[a][b] = false;}
            else if(life == 3){grid[a][b] = true;}
            else if(life > 3){grid[a][b] = false;}
        }
    }
}

int main(){

    //const int gridsize = 50;
    bool grid[gridsize+1][gridsize+1] = {};

    //Still have to manually enter the starting cells.
    grid[gridsize/2][gridsize/2] = true;
    grid[gridsize/2-1][gridsize/2] = true;
    grid[gridsize/2][gridsize/2+1] = true;
    grid[gridsize/2][gridsize/2-1] = true;
    grid[gridsize/2+1][gridsize/2+1] = true;

    while (true){
        //The following copies our grid.

        Display(grid);     //This is our display.
        liveOrDie(grid); //calculate if it lives or dies.
        system("CLS");
    }
}


texts:
Is there any MySQL function that will optimize this code?

function get_parents() {

$ids = array();

while($id) :
    $query = "SELECT placement_id FROM referrals WHERE user_id = $id";
    $query = $this->db->query($query);
    $result = $query->row();

    if(!isset($result->placement_id)) :
        break;
    elseif(isset($result->placement_id) && $result->placement_id == 2) :
        break;
    endif;

    $id = $result->placement_id;
    array_push($ids, $id);

    if($result) :
        continue;
    endif;

    break;
endwhile;

return $ids;

}

The code above will return all parent ID of given user_id, and this will stop if nothing is found. I found this code too slow and heavy load.

My table:

relations table
| id  |   user_id |   placement_id    |
| 1   |       2   |       NULL        |
| 2   |       3   |       2           |
| 3   |       4   |       2           |
| 4   |       5   |       3           |
| 5   |       6   |       4           |
| 6   |       7   |       3           |
| 7   |       8   |       3           |
| 8   |       9   |       3           |
| 9   |       10  |       6           |
| 10  |       11  |       5           |
| 11  |       12  |       6           |
| 12  |       13  |       4           |
| 13  |       14  |       3           |
| 14  |       15  |       9           |
| 15  |       16  |       10          |

user_id is the child and parent is placement_id.


texts:
Im writing this simple program for school and using NumberFormat on all the variables seems very repetitive (Note that we were asked to use the NumberFormat method). Is there any way to clean this code so it doesn't look so cluttered?
import java.util.Scanner;
import java.text.NumberFormat;

public class CarPrice {

    public static void main(String[] args) {

        double priceInitial;
        double HST;
        double PDI_CHARGE = 0.02;

        String makeModel;

        Scanner scan = new Scanner(System.in);

        System.out.print("makeModel?: ");
        makeModel = scan.nextLine().toUpperCase();

        do {
            System.out.print("Price?: ");
            priceInitial = scan.nextDouble();
            if (priceInitial < 0) {
                System.out.println("Enter A Value  Above 0");
            } else {
                System.out.println(priceInitial);
                break;
            }
        } while (true);

        do {
            System.out.print("HST?: ");
            HST = scan.nextDouble();
            if (HST < 0) {
                System.out.println("Enter A Value  Above 0");
            } else {
                System.out.println(HST);
                break;
            }
        } while (true);

        double tax = priceInitial * (HST / 100) + priceInitial;

        double PDI = (tax + priceInitial) * PDI_CHARGE;
        double AfterPDI = PDI + tax;

        String PDI_Print = NumberFormat.getCurrencyInstance().format(PDI);
        String tax_Print = NumberFormat.getCurrencyInstance().format(tax);
        String priceInitial_Print = NumberFormat.getCurrencyInstance().format(priceInitial);
        String tax_Amount = NumberFormat.getPercentInstance().format(HST / 100);
        String AfterPDI_Print = NumberFormat.getCurrencyInstance().format(AfterPDI);

        System.out.println("Congrats! Your " + makeModel + " is " + priceInitial_Print +
                "\n Your total after " + tax_Amount + " HST is " + tax_Print +
                "\n with a PDI fee of " + PDI_Print +
                "\n making your total " + AfterPDI_Print);

    }

}


texts: Counting the number of page turns to arrive at some specified page

texts:
Here is a HackerRank challenge.  Given a book with n pages (with 1 ≤ n ≤ 105), how many page turns are needed to arrive at page p, starting from either the front or the back?  The book is laid out with page 1 on the right.

I have got following solution to the given problem.

import java.util.*;
public class Solution {

    static int solve(int n, int p){
        // Complete this function
        if(n==p)
            return 0;
        if(p%2==0){
            if(n-p==p)
                return (p-1)/2;
            else{
                if(n-p>p)
                    return p/2;
                else
                    return (n-p)/2;
            }
        }
        if(n%2==0 && p%2!=0){
            if(n-p==p)
                return (p-1)/2;
            else{
                if(n-p>p)
                    return p/2;
                else
                    return (n-p+2)/2;
                }
        }
        else

             if(n-p>p)
                    return p/2;
                else
                    return (n-p)/2;

    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int p = in.nextInt();
        int result = solve(n, p);
        System.out.println(result);
    }
}

Although it is working code, I am not satisfied with it. It seems very messy. How can I reduce branch statements in my code, or otherwise improve it?


texts:
I have this function in this fiddle

JavaScript:

var newsTicker = function (ele) {
    var eles = ele.find('ul li'),
        indexEle = 0,
        dataEle = ele.find('.ticker-post'),
        rotateChars = function (title) {
            dataEle.text('');
            indexCut = 0;
            rotateCharsTimer = setInterval(function () {
                if (dataEle.text().length == title.length) {
                    clearInterval(rotateCharsTimer);
                } else if (dataEle.text().length < title.length) {
                    text = dataEle.text().concat(title.substr(indexCut, 1));
                    dataEle.text(text);
                };
                if (title.length - 1 > indexCut) indexCut++;
                else indexCut = 0;
            }, 90);
        },
        loopLs = function () {
            loopEle = eles.get(indexEle);
            eleHref = $(loopEle).data('href');
            eleTitle = $(loopEle).data('title');
            dataEle.attr('href', eleHref);
            if (typeof rotateCharsTimer != 'undefined') {
                dataEle.fadeOut();
                clearInterval(rotateCharsTimer);
            }
            dataEle.fadeIn();
            rotateChars(eleTitle);
            if (eles.length - 1 > indexEle) indexEle++;
            else indexEle = 0;
        }
    loopLs();
    setInterval(function (){loopLs()},9400);
}

HTML:

Breaking News:

Is this the best way to do this?


texts: Reduce square root to simplest radical form

texts:
The function redsqrt(n) prints out the most reduced form of the square root of n. It calls on another function perfsq(n), which produces a list of perfect squares less than or equal to n.

from math import sqrt
def perfsq(n):
    # Returns list of perfect squares less than or equal to n
    l = [1]
    i, x = 0, 3
    while l[-1]+x <= n:
        l.append(l[i]+x) # Add x to get next perfect square
        i += 1
        x = 2*i+3
    return l
def redsqrt(n):
    # Prints most reduced form of square root of n
    if n < 0:
        print('Negative input')
        return
    if sqrt(n).is_integer():
        print(int(sqrt(n))) # Square root is an integer
        return
    # Find perfect squares that are factors of n
    l = [i for i in perfsq(n/2) if n%i==0 and i>1]
    if len(l)==0:
        print('\u221A',n) # Square root is irreducible
    else:
        a = int(sqrt(max(l))) # Coefficient
        b = int(n/max(l)) # Argument of the square root
        print(a,'\u221A',b) # Reduced square root

Examples:

redsqrt(5.7)
√ 5.7

redsqrt(100)
10

redsqrt(2000)
20 √ 5

redsqrt(2040506)
13 √ 12074


texts: Imperative and functional-programming solutions for Jumping on the Cloud challenge

texts:
Problem Statement

  Emma is playing a new mobile game that starts with consecutively
  numbered clouds. Some of the clouds are thunderheads and others are
  cumulus. She can jump on any cumulus cloud having a number that is
  equal to the number of the current cloud plus 1 or 2. She must
  avoid the thunderheads. Determine the minimum number of jumps it will
  take Emma to jump from her starting postion to the last cloud. It is
  always possible to win the game.

  For each game, Emma will get an array of clouds numbered 0 if they
  are safe or 1 if they must be avoided. For example,
  c=[0,1,0,0,0,1,0] indexed from 0...6. The number on each cloud is its index in the list so she must avoid the clouds at indexes 1
  and 5 . She could follow the following two paths:
  0 -> 2 -> 4 -> 6  or 0 -> 2 -> 3 -> 3 -> 4 -> 6 . The first path takes
  3 jumps while the second takes 4.

  Function Description

  Complete the jumpingOnClouds function in the editor below. It should
  return the minimum number of jumps required, as an integer.

  jumpingOnClouds has the following parameter(s):

  c: an array of binary integers

  Input Format

  The first line contains an integer n, the total number of clouds.
  The second line contains n space-separated binary integers
  describing clouds c[i] where 0 <= i < n.

  Output Format

  Print the minimum number of jumps needed to win the game.

  Sample Input 0

7
0 0 1 0 0 1 0

  Sample Output 0

4

  Explanation 0:  Emma must avoid c[2] and c[5]. She can win the
  game with a minimum of 4 jumps. Sample Input 1

6
0 0 0 0 1 0

  Sample Output 1

3

  Explanation 1:  The only thundercloud to avoid is c[4]. Emma can win
  the game in 3 jumps.

Imperative style Solution:

// Complete the jumpingOnClouds function below.
def jumpingOnClouds(c: Array[Int]): Int = {
    var i=0
    var length = c.length
    var jumps = 0
    while(i < length -1) {
        if(i < length-2 && c(i+2) == 0 ) i+=2
        else i+=1
        jumps +=1
    }
    jumps
}

Functional-programming style Solution using Recursion:

 def jumpingOnClouds(c: Array[Int]): Int = {
     val limit = c.length -2
     def rec(jumps: Int, index: Int): Int = {
         if (index > limit) jumps
         else {
             val jumpingOffset: Int = if(index < limit && c(index + 2) == 0 ) 2 else 1
             rec(jumps+1, index + jumpingOffset)
         }
     }
     rec(0,0)
 }


texts: Mocking the class under test with private method calls

texts:
Consider the scenario below. It covers multiple methods of my unit under test.

public class OriginalSample
{
    public bool Foo(ISomeEntity entity)
    {
        return entity.IsThatSo ? entity.IsThatSo : Bar(entity);
    }

    public bool Bar(ISomeEntity entity)
    {
        return entity.IsThatAsWell;
    }
}

[TestClass]
public class OriginalSampleTest
{
    [TestMethod]
    public void Foo_EntityWithSo_ReturnsTrue
    {
        // Arrange
        Mock<ISomeEntity> someEntityMock = new Mock<ISomeEntity>();
        mock.SetupGet(m => m.IsThatSo).Returns( false );
        mock.SetupGet(m => m.IsThatAsWell).Returns( true );

        // Act
        private bool result = _OriginalSample.Foo( someEntityMock.Object );

        // Assert
        Assert.IsTrue(result);
    }
}

However, in my production code there is a lot that I need to Mock away that is then used in more method calls. I need to find a way to test the Foo method without hitting the Bar method.

I came up with the scenario as below. However the disadvantage is that i need a interface and pass the instance in each method. I do not like this design.

Any feedback?

public interface INewSample
{
    bool Foo(ISomeEntity entity, INewSample sample);
    bool Bar(ISomeEntity entity);
}

public class NewSample : INewSample
{
    public bool Foo(ISomeEntity entity, INewSample sample)
    {
        return entity.IsThatSo ? entity.IsThatSo : sample.Bar(entity);
    }

    public bool Bar(ISomeEntity entity)
    {
        return entity.IsThatAsWell;
    }
}

[TestClass]
public class NewSampleTest
{
    [TestMethod]
    public void Foo_EntityWithSo_ReturnsTrue
    {
        // Arrange
        Mock<ISomeEntity> someEntityMock = new Mock<ISomeEntity>();
        mock.SetupGet(m => m.IsThatSo).Returns( false );

        Mock<INewSample> sampleMock = new Mock<INewSample>();
        sampleMock.Setup(m => m.Bar).Returns(false).Verify();

        // Act
        private bool result = _OriginalSample.Foo( someEntityMock.Object, sampleMock.Object );

        // Assert (that the logic tried to use the 'bar' method
        sampleMock.Verify();
    }
}


texts: "Function Buffer" to avoid triggering an event handler too frequently

texts:
If some big event handler is triggered too frequently, it will cause computer lagging.

In my example $(window).resize(), I want the function to be called after the user has completed his resize, instead of firing every time you resize by a single pixel.

So, I made this 'Function Buffer':

function FtnBuff(){
    var count=0;
    var delay = 50;
    var ftnList=[];

    this.add = function(ftn){
        if(isFunction(ftn)){
            ftnList.push(ftn);
        }else{
            return false;
        }
    }
    this.start = function(){
        count ++;
        setTimeout(checkbuff, delay);
    }
    this.setDelay = function(num){
        if(!isNaN(num)){
            delay = num;
        }
    }
    function checkbuff(){
        if(count==1){
            runFtn();
        }
        count--;
    }
    function runFtn(){
        for(var key in ftnList){
            ftnList[key]();
        }
    }
    function isFunction(obj) {
        var getType = {};
        return obj && getType.toString.call(obj) === '[object Function]';
    }
    return this;
}

Use case:

ftnbuff = new FtnBuff()
ftnbuff.add(aa)
ftnbuff.add(function(){
    bb('long time no C.')
})
$(window).resize(ftnbuff.start)

function aa(){
    console.log('This is aa.');
}
function bb(customText){
    console.log('This is bb.'+customText);
}


texts:
I decided to try my hand at a Hangman game to familiarize myself a bit with the language.
use std::io::{stdin, stdout, Write};

fn main() {
    let stdin = stdin();
    let mut stdout = stdout();

    let to_guess = String::from("BENEDICT");

    let mut letters: u128 = 0;

    loop {
        // Replace unguessed letters of to_guess by underscores
        let current = to_guess.chars().map(|x| {
            if x <= 127 as char && letters & (1 << x as u8) > 0 {
                x
            } else {
                '_'
            }
        });
        // Add spaces between letters
        let current = current
            .map(|x| x.to_string() + &' '.to_string())
            .collect::<Vec<String>>()
            .join(" ");

        println!("Current word: {}", current.trim_end());

        if !current.contains('_') {
            println!("Congratulations!");
            break;
        }

        print!("Enter new letter: ");
        stdout.flush().unwrap();

        let mut letter = String::new();
        stdin.read_line(&mut letter).expect("Invalid letter");

        if letter.trim().len() != 1 {
            println!("Use only one ASCII letter");
            continue;
        }

        let letter = letter.to_uppercase().chars().next().unwrap();

        letters |= 1 << letter as u8
    }
}

The to_guess word is hardcoded, and there is an unlimited number of guesses.
To store letters already guessed, I use an u128 and flag the corresponding bit. It should be ok since all ASCII letters are represented by u8 < 128.
Can you help me review the code, are there "Rust" things I missed?


texts: Calculating distances between nodes in graph with negative cycles

texts:
Full disclosure: this is for an online course.

The code calculates the distances between a starting node in a graph and all other nodes using the Bellman-Ford algorithm. The graph may contain negative cycles: in that case, the output should represent that distance with '-'. If there is no link between the starting node and another node it should '*'. Else, it should output the distance.

The code is working but I believe there is an overflow issue which I don't know how to solve. The constraints specify the following max values:

Nodes: 10^3;
Edges: 10^4;
Egde weights: 10^9

Testing for all logic-related corner cases led to no issues, everything was working correctly. The test this is failing is (most probably) related to overflow.

The code

void bfs(vector<vector<int> > &adj, queue<int> q, vector<bool> &shortest) {
  int size = adj.size();
  vector<bool> visited(size, false);
  while (!q.empty()) {
    int v = q.front();
    if (visited[v]) {
      q.pop();
    } else {
      q.pop();
      for (int i = 0; i < adj[v].size(); i++) {
        shortest[adj[v][i]] = true;
        q.push(adj[v][i]);
      }
    }
    visited[v] = true;
  }
}

void shortest_paths(vector<vector<int> > &adj, vector<vector<int> > &cost, int s,
  vector<double> &distance, vector<bool> &reachable, vector<bool> &shortest) {
  int size = adj.size();
  distance[s] = 0;
  reachable[s] = true;
  queue<int> negative_cycle;
  // Set initial distances and get negative cycles
  for (int i = 0; i <= size; i++) {
    for (int j = 0; j < size; j++) {
      for (int k = 0; k < adj[j].size(); k++) {
        // Edge relaxation
        if (distance[adj[j][k]] > distance[j] + cost[j][k]) {
          reachable[adj[j][k]] = true;
          if (i == size) {
            // Store negative cycles
            negative_cycle.push(adj[j][k]);
            shortest[adj[j][k]] = true;
          }
          distance[adj[j][k]] = distance[j] + cost[j][k];
        }
      }
    }
  }
  bfs(adj, negative_cycle, shortest);
}

and the main is

int main() {
  int n, m, s;
  std::cin >> n >> m;
  vector<vector<int> > adj(n, vector<int>());
  vector<vector<int> > cost(n, vector<int>());
  for (int i = 0; i < m; i++) {
    double x, y, w;
    std::cin >> x >> y >> w;
    adj[x - 1].push_back(y - 1);
    cost[x - 1].push_back(w);
  }
  std::cin >> s;
  s--;
  vector<double> distance(n, std::numeric_limits<double>::infinity());
  vector<bool> reachable(n, false);
  vector<bool> shortest(n, false);
  shortest_paths(adj, cost, s, distance, reachable, shortest);
  for (int i = 0; i < n; i++) {
    if (!reachable[i]) {
      std::cout << "*\n";
    } else if (shortest[i]) {
      std::cout << "-\n";
    } else {
      std::cout << distance[i] << "\n";
    }
  }
}

I'm using double and infinity since that is needed for the algorithm (you can read about it here). From the googling I've done, I get this shouldn't overflow since the max possible distance would be 10^4 * 10^9 = 10^13 which is still within double's span. I don't have much experience using infinity or doubles like this, and from what I've researched I couldn't trace the problem.