texts: Generate a large block diagonal covariance matrix with exponential decay

texts:
I am implementing Kalman filtering in R. Part of the problem involves generating a really huge error covariance block-diagonal matrix (dim: 18000 rows x 18000 columns = 324,000,000 entries). We denote this matrix Q. This Q matrix is multiplied by another huge rectangular matrix called the linear operator, denoted by H.

I am able to construct these matrices but it takes a lot of memory and hangs my computer. I am looking at ways to make my code efficient or do the matrix multiplications without actually creating the matrices exclusively.

library(lattice)
library(Matrix)
library(ggplot2)

nrows <- 125

ncols <- 172

p <- ncols*nrows

#--------------------------------------------------------------#
# Compute Qf.OSI, the "constant" model error covariance matrix #
#--------------------------------------------------------------#

  Qvariance <- 1
  Qrho <- 0.8

  Q <- matrix(0, p, p)

  for (alpha in 1:p)
  {
    JJ <- (alpha - 1) %% nrows + 1
    II <- ((alpha - JJ)/ncols) + 1
    #print(paste(II, JJ))

    for (beta in alpha:p)
    {
      LL <- (beta - 1) %% nrows + 1
      KK <- ((beta - LL)/ncols) + 1

      d <- sqrt((LL - JJ)^2 + (KK - II)^2)
      #print(paste(II, JJ, KK, LL, "d = ", d))

      Q[alpha, beta] <-  Q[beta, alpha] <-  Qvariance*(Qrho^d)
    }
  }

  # dn <- (det(Q))^(1/p)
  # print(dn)

  # Determinant of Q is 0
  # Sum of the eigen values of Q is equal to p

  #-------------------------------------------#
  # Create a block-diagonal covariance matrix #
  #-------------------------------------------#

  Qf.OSI <- as.matrix(bdiag(Q,Q))

  print(paste("Dimension of the forecast error covariance matrix, Qf.OSI:")); print(dim(Qf.OSI))

It takes a long time to create the matrix Qf.OSI at the first place. Then I am looking at pre- and post-multiplying Qf.OSI with a linear operator matrix, H, which is of dimension 48 x 18000. The resulting HQf.OSIHt is finally a 48x48 matrix. What is an efficient way to generate the Q matrix? The above form for Q matrix is one of many in the literature. In the below image you will see yet another form for Q (called the Balgovind form) which I haven't implemented but I assume is equally time consuming to generate the matrix in R.


texts:
Problem: IPython's autoreload and superreload may reload modules such that obj=Obj() -> edit file & save -> isinstance(obj, Obj) == False. Sometimes even imp.reload of all involved modules doesn't absolve it.
Goal: a method with a 'fallback' on looser criterion that are as close to isinstance as possible.
Attempt:
def isinstance_ipython(obj, ref_class):
    def _class_name(obj):
        name = getattr(obj, '__qualname__', getattr(obj, '__name__', ''))
        return (getattr(obj, '__module__', '') + '.' + name).lstrip('.')
    return (isinstance(obj, ref_class) or
            _class_name(type(obj)) == _class_name(ref_class))

obj is always instance of a class, and ref_class is always a Python 3.x, non-builtin class. __qualname__ and __module__ are included to prefer longest possible name, but fallback upon shorter names via empty strings.

Any improvements to reliability of this method (i.e. reduced false positives/negatives)? Not interested in speed or readability, but they're welcome as bonus.


texts: Decorator that supplies arguments to functions

texts:
I have assignment to generate argument based decorator I wrote like this.

def my_decorator(*deco_args):
    def wrap(f):
        def wrapped_f(*func_args):
            if len(deco_args) == 1 and len(func_args) ==1:
                return f(func_args[0], deco_args[0])
            elif len(deco_args) == 2 and len(func_args) == 2:
                return f(*(deco_args+func_args))
        return wrapped_f
    return wrap

@my_decorator(2)
def pow(x, y):
    return x ** y

print pow(4) #=> 16

@my_decorator("/home", "user")
def path(*args):
   return "/".join(args)

print path("videos", "cats.png") #=> "/home/user/videos/cats.png"

Is there any better way to do this ?


texts:
I have implemented a bitarr class that does bit manipulations. I would love to know if there is any way to make the code more optimized. Any input would be much appreciated. Thank you! Note: int main() should not be modified.
    #include <iostream>
    #include <vector>
    #include <climits>
    #include <cstring>

    template<size_t NumBits>
    class bitarr
    {
    private:
        static const unsigned NumBytes = (NumBits + CHAR_BIT - 1) / CHAR_BIT;//find number of bytes to track least memory footprint
        unsigned char arr[NumBytes];
    public:
        bitarr() { std::memset(arr, 0, sizeof(arr)); } //initialize array to 0

        void set(size_t bit, bool val = true) {
            if (val == true)
            {
                arr[bit / CHAR_BIT] |= (val << bit % CHAR_BIT);//left shift and OR with masked-bit
            }
        }

        bool test(size_t bit) const {
            return arr[bit / CHAR_BIT] & (1U << bit % CHAR_BIT); //left shift and AND with masked-bit
        }
        const std::string to_string(char c1, char c2)
        {
            std::string str;
            for (unsigned int i = NumBits; i-- > 0;)
                str.push_back(static_cast<char>
                ('0' + test(i)));
            while (str.find("0") != std::string::npos) {
                str.replace(str.find("0"), 1, std::string{ c1 });
            }
            while (str.find("1") != std::string::npos) {
                str.replace(str.find("1"), 1, std::string{ c2 });
            }
            return str;
        }
        friend std::ostream& operator<<(std::ostream& os, const bitarr& b)
        {
            for (unsigned i = NumBits; i-- > 0; )
                os << b.test(i);
            return os << '\n';
        }
    };

    int main()
    {
        try
        {
            bitarr<5> bitarr;
            bitarr.set(1);
            bitarr.set(2);

            const std::string strr = bitarr.to_string('F', 'T');
            std::cout << strr << std::endl;
            if (strr != "FFTTF")
            {
                throw std::runtime_error{ "Conversion failed" };
            }
        }
        catch (const std::exception& exception)
        {
            std::cout << "Conversion failed\n";
        }
    }


texts: Finding the occurrences of all words in movie scripts

texts:
I was wondering if someone could tell me things I could improve in this code. This is one of my first Python projects. This program gets the script of a movie (in this case Interstellar) and then finds the occurrences of all words and prints out the 20 most common words in the script.

from bs4 import BeautifulSoup
import requests
from collections import Counter
import operator
import re

class MovieScript(object):
    def __init__(self, movie):
        self.movie = movie
        self.url = "http://www.springfieldspringfield.co.uk/movie_script.php?movie={0}".format(movie.replace(" ", "-"))

    def get_movie(self):
        return self.movie

    def get_text(self):
        r = requests.get(self.url)
        soup = BeautifulSoup(r.text)
        return soup

    def parse_text(self):
        text = self.get_text().findAll('div', {"class":"scrolling-script-container"})[0].text.lower()
        text = re.sub(r'\W+', ' ', text) #remove puncation from the text
        return text.split()

    def find_all_occurences(self):
        return Counter(self.parse_text())

    def get_all_occurences(self):
        sorted_occurences = sorted(self.find_all_occurences().items(), key=operator.itemgetter(1))
        return sorted_occurences

def Main():
    db = MovieScript("interstellar")
    print "The Movie: " + db.get_movie()
    all_occurences = db.get_all_occurences()
    for i in range(-1, -21, -1):
        print str(-i) + ". " + str(all_occurences[i][0]) + " -> " + str(all_occurences[i][1])

if __name__ == "__main__":
    Main()


texts:
The following function uses a cartesian system and has an agent who moves on the table like: F - forward, L - turn left, R - turn right.

The code works fine but I would like to make it more efficient:

import java.util.Scanner;

public class HelloWorld {
  public static void main (String[] args) {
      int x = 0, y = 0;                                 //initial coordinates
      int direction = 0;                                //initial direction
    Scanner scanner = new Scanner(System.in);
    System.out.print("Introduce the command: ");
    String inputString = scanner.nextLine();            //get the command

    for (int i = 0; i < inputString.length(); i++){
        char c = inputString.charAt(i);                 //breaking the string into chars
        if(c == 'l') {                                  //determining the direction
            direction++;
        } else if (c == 'r') {
            direction--;
        } else if (c == 'f') {
            if(direction < 0) {
                direction +=4;
            }
            if(direction % 4 ==0) {                     //moving forward in the wanted direction
                y++;
            } else if (direction % 4 ==1) {
                x--;
            } else if (direction % 4 == 2) {
                y--;
            } else if(direction % 4 == 3) {
                x++;
            }
        }
    }
    System.out.println("Result: ["+x+","+y+"]");
  }
}


texts:
As part of my journey in learning the Rust programming language, I decided to make a miniature cat clone (catty) in it. The following is my code, which depends on clap for argument parsing (see below). It currently only supports concatenating 1 file with possibly numbered lines (-n/--number). I tried to be as close as possible to the actual cat program for this:

#[macro_use] extern crate clap;

use std::{io, error, env, fs::read_to_string, path::PathBuf, process};

fn main() {
    process::exit(
        if let Err(err) = cli(env::args().collect::<Vec<_>>()) {
            // CLI parsing errors
            if let Some(clap_err) = err.downcast_ref::<clap::Error>() {
                eprint!("{}", clap_err);
            } else {
                eprintln!("{}", err);
            }
            1
        } else {
            0
        }
    );
}

fn cli(cli_args: Vec<String>) -> Result<(), Box<error::Error>> {
    let matches = clap::App::new("catty")
        .version(crate_version!())
        .about("A minimal clone of the linux utility cat.")
        .arg(clap::Arg::with_name("FILE")
            .help("The file to concatenate to standard output")
            .required(true))
        .arg(clap::Arg::with_name("number")
            .short("n")
            .long("number")
            .help("Numbers all output lines"))
        .get_matches_from_safe(cli_args)?;

    let file_contents = get_file_contents(matches.value_of("FILE").unwrap())?;
    let file_contents: Vec<&str> = file_contents.split("\n").collect();

    let number_lines = matches.is_present("number");

    for (i, line) in file_contents.iter().enumerate() {
        let formatted_line = if number_lines {
            format!("{:>6}  {}", i + 1, line)
        } else {
            line.to_string()
        };

        if i == file_contents.len() - 1 && line.len() > 0 {
            print!("{}", formatted_line);
        } else if !(i == file_contents.len() - 1 && line.len() == 0) {
            println!("{}", formatted_line);
        }
    }

    Ok(())
}

fn get_file_contents(passed_argument: &str) -> Result<String, Box<error::Error>> {
    let mut resolved_path = PathBuf::from(passed_argument);

    if !resolved_path.exists() || !resolved_path.is_file() {
        resolved_path = PathBuf::from(env::current_dir()?);
        resolved_path.push(passed_argument);

        if !resolved_path.exists() || !resolved_path.is_file() {
            return Err(io::Error::new(io::ErrorKind::NotFound, "The passed file is either not a file or does not exist!").into());
        }
    }

    Ok(read_to_string(resolved_path)?)
}

My Cargo.toml is as follows:

[package]
name = "catty"
version = "0.1.0"
authors = ["My Name <my@email.com>"]

[dependencies]

[dependencies.clap]
version = "2.32"
default-features = false
features = ["suggestions"]

Here is what I want to know from this code review:

Is my code idiomatic rust (i.e good error handling, not overly verbose, etc)?
Is my code performant or can it be improved in some way?


texts:
I have implemented Mergesort and Quicksort in Python and have noticed that Quicksort runs two times as fast as Mergesort. Is this a property of the algorithm or is Mergesort coded inefficiently? Are there any other suggestions?

(I am aware that the timing includes the creation of the random list.)

Quicksort:

import time, random

def quicksort_benchmark(n=2**24):
    def quicksort(array, low, high):
        if low < high:
            p = partition(array, low, high)
            quicksort(array, low, p)
            quicksort(array, p+1, high)

    def partition(array, low, high):
        pivot_index = random.randint(low, high)
        pivot = array[pivot_index]
        i = low - 1
        j = high + 1

        while True:
            while True: # do while
                i += 1
                if array[i] >= pivot:
                    break

            while True:
                j -= 1
                if array[j] <= pivot:
                    break

            if i >= j:
                return j

            temp = array[i]
            array[i] = array[j]
            array[j] = temp

    start = time.time()

    # initialize array
    array = [random.randint(0, n) for i in range(0,n)]
    quicksort(array, 0, len(array)-1)

    end = time.time()
    elapsed = end - start
    return(elapsed)

Mergesort:

def mergesort_benchmark(n=2**24):
    def mergesort(m):
        if len(m) <= 1:
            return m

        left, right = [], []
        for i in range(0, len(m)):
            if i < len(m)//2:
                left.append(m[i])
            else:
                right.append(m[i])

        left = mergesort(left)
        right = mergesort(right)
        return(merge(left,right))

    def merge(left,right):
        result = []

        i, j = 0, 0

        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j += 1

        for i in range(i, len(left)):
            result.append(left[i])

        for i in range(j, len(right)):
            result.append(right[i])

        return result

    start = time.time()
    m = [random.randint(0,n) for i in range(0,n)]
    m = mergesort(m)
    end = time.time()
    elapsed = end - start
    return(elapsed)


texts:
First time poster, be gentle.

I wanted something similar to Mojo::Promise->all, except with an option to discard certain rejected (or, I guess, resolved) promises dependent on rejection value, as determined by caller.

Only using this internally, so nevermind my polluting the Mojo::Promise:: namespace.

package Mojo::Promise::Filter;
use Moose;

extends 'Mojo::Promise';

has 'promises' => (
    isa => 'ArrayRef[Mojo::Promise]',
    is => 'ro',
    required => 1,
);

has 'resolve_filter' => ( # truthy return means *DO* filter out
    isa => 'CodeRef',
    is => 'ro',
    required => 1,
    lazy => 1,
    default => sub { return sub {}; },
);

has 'reject_filter' => ( # truthy return means *DO* filter out
    isa => 'CodeRef',
    is => 'ro',
    required => 1,
    lazy => 1,
    default => sub { return sub {}; },
);

has '_promises_state_tracker' => (
    # numbered hashref whose primary keys correspond to passed promise-array's indices
    # secondary keys are flags for whether each original promise filtered
    # and whether promise resolved/rejected,
    # plus the original promise itself, e.g. :
    # { 0 => { filtered => (undef|1), ror => (undef|1), original_promise => (Mojo::Promise) } }
    isa => 'HashRef[HashRef]',
    is => 'ro',
    lazy => 1,
    builder => '_build_promises_state_tracker',
);

sub _build_promises_state_tracker {
    my $self = shift;
    my $i = 0;
    return { map { $i++ => { original_promise => $_ } } @{$self->promises} };
}

sub _resolve_or_reject_self_if_last_child {
    my $self = shift;

    my @ror = grep { $_->{ror} } values %{$self->_promises_state_tracker};
        # gather the thus-far resolved-or-rejected promises
    return unless scalar keys %{$self->_promises_state_tracker} == scalar @ror;
        # return unless we have as many ror promises as were passed in

    my @unfiltered = map { $_->{original_promise} } grep { !$_->{filtered} } values %{$self->_promises_state_tracker};
    return Mojo::Promise->all(@unfiltered)->then(sub {
        $self->resolve(@_)
    })->catch(sub {
        $self->reject(@_)
    });
}

sub filter {
    my $self = shift;

    for my $i (0 .. $#{$self->promises}) {
        $self->promises->[$i]->then(sub {
            $self->_promises_state_tracker->{$i}->{filtered} = 1
                if $self->resolve_filter->(@_);
        })->catch(sub {
            $self->_promises_state_tracker->{$i}->{filtered} = 1
                if $self->reject_filter->(@_);
        })->finally(sub {
            $self->_promises_state_tracker->{$i}->{ror} = 1;
                # ror = Resolved Or Rejected
            $self->_resolve_or_reject_self_if_last_child();
        });
    }

    return $self;
}

no Moose;

1;

Use as :

my $re_filter = qr/some special text/;
my $reject_filter = sub {
        my $v = shift;
        return 1 if ref \$v eq 'SCALAR' && $v =~ $re_filter;
    };

my $p = Mojo::Promise::Filter->new(
        reject_filter => $reject_filter,
        promises => \@promises
    );

return $p->filter;


texts: Solution to King Kohima problem in Python

texts:
King Kohima problem:

  King Kohima has reserved a new exclusive street for his executive class employees where they can build their homes. He has assigned you to plan that street. You have to decide on which plots along the street are new building allowed to be built. In order to this, you first want to calculate the number of possible ways of assigning free plots to buildings while keeping in mind this restriction – No two consecutive plots can have buildings on them. This is done to ensure a sense of free space in the arena. The street is divided in M sections. Each section corresponds to 2 plots, one on each side of the street. Find the number of possible assignments.

  Input

  In the first line you’re given M ( M ≤ 1000 ). Output In the first and only line output the result/ Example Input: 3 Output: 25 Example explanation: If we just look at the one street side and mark X as a plot where building is allowed and Y as a free plot, we have: XYX, YXY, YYX, XYY, YYY. Since the same number exists on the other side, we have 5*5 = 25 combinations.

For example, if the input is 3, then only five layouts (YYY, YYX, YXY, XYY, XYX) of the eight possible combinations (YYY, YYX, YXX, YXY, XYY, XYX, XXY, XXX) are valid.  For both sides of the street, it's 5*5=25.

Please critique this solution.

def binary(i):
    r=str(0)
    while(i):
        x=str(i%2)
        if(x=='1' and r[-1]=='1'): #two consecutive X are not possible
            return None
        else:
            r=r+str(x)
        i=i/2
    return r
m=3 #input
l=[]
for i in range(0,2**m):
    l.append(binary(i)) #converted the number to binary
print(l)
c=0 #count possible plot available
for i in l:
    if i:
        c=c+1
print(c*c) #both side of the lane


texts:
I wanted to implemented an algorithm in Python 2.4 (so the odd construction for the conditional assignment) where given a list of ranges, the function returns another list with all ranges that overlap in the same entry.

I would appreciate other options (more elegant or efficient) than the one I took.

ranges = [(1,4),(1,9),(3,7),(10,15),(1,2),(8,17),(16,20),(100,200)]

def remove_overlap(rs):
        rs.sort()
        def process (rs,deviation):
                start = len(rs) - deviation - 1
                if start < 1:
                        return rs
                if rs[start][0] > rs[start-1][1]:
                        return process(rs,deviation+1)
                else:
                        rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] < rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] > rs[start][1]])
                        del rs[start]
                        return process(rs,0)
        return process(rs,0)

print remove_overlap(ranges)


texts:
I'm a beginner at Python, and to start off my learning progress I created a simple program which will roll a dice and decides the probability of it. It would be great to have criticism on my code, like how I can improve it, make it shorter, etc.

import random

rolled = []
rolledtimes = 0;
biggest = []

freq = int(input('How many times would you like to roll the dice? '))

def roll():
    rand = random.randrange(1,7)
    return rand
def probability():
    for i in range(0,6):
        print('Calculation of probability:')
        percentage = "{:.2f}".format((count[i] / freq)*100)
        percent = str(percentage) + '%'
        print(' ', i + 1, ':', percent)
def theoretical():
    result = "{:.2f}".format((1/6)*freq)
    denominator = "{:.2f}".format(((1/6)*freq)*6)
    print('\nIn theory, each dice should roll {} out of {} times'.format(result,denominator))
def findBiggest():
    for i in range(1,7):
        biggest.append(rolled.count(i))
    print('\n', 'The most times a dice is rolled is', max(biggest), 'times')
def findSmallest():
    for i in range(1,7):
        biggest.append(rolled.count(i))
    print('\n', 'The least times a dice is rolled is', min(biggest), 'times')

for i in range(1,freq + 1):
    number = roll()
    rolled.append(number)
    rolledtimes+=1
count = [rolled.count(1),rolled.count(2),rolled.count(3),rolled.count(4),rolled.count(5),rolled.count(6)]
print('After being rolled {} times:\n\n1 is rolled {} times\n2 is rolled {} times\n3 is rolled {} times\n4 is rolled {} times\n5 is rolled {} times\n6 is rolled {} times\n'.format(rolledtimes,count[0],count[1],count[2],count[3],count[4],count[5]))

probability()
findBiggest()
findSmallest()
theoretical()

When used, it will print out something like this in the console:

How many times would you like to roll the dice? 1000
After being rolled 1000 times:

1 is rolled 180 times
2 is rolled 161 times
3 is rolled 190 times
4 is rolled 145 times
5 is rolled 162 times
6 is rolled 162 times

Calculation of probability:
  1 : 18.00%
Calculation of probability:
  2 : 16.10%
Calculation of probability:
  3 : 19.00%
Calculation of probability:
  4 : 14.50%
Calculation of probability:
  5 : 16.20%
Calculation of probability:
  6 : 16.20%

 The most times a dice is rolled is 190 times

 The least times a dice is rolled is 145 times

In theory, each dice should roll 166.67 out of 1000.00 times


texts: Generic function with same logic but different input structure

texts:
I have a data structure that looks like this:

interface Node {
  originalWeight: number;
  currentWeight: number;
}

where both properties are floats between 0 and 1.

To check if a node has been modified, I wrote a simple isNodeModified function:

isNodeModified(node: Node): boolean {
  return Math.abs(node.originalWeight- node.currentWeight) > this.EPSILON;
}

where EPSILON is my tolerance.

However, I also need to do a very similar comparison in a slightly different scenario, which was originally handled like this:

if (Math.abs(event.value - node.originalWeight) > this.EPSILON) {
  // do something
}

where event is another object with a value property.

To avoid duplication, I replaced both methods with something like the following:

isNodeModified(node: Node, event?: Event): boolean {
  let original = node.originalWeight;
  if (event) {
    original = event.value;
  }
  return Math.abs(original - node.currentWeight) > this.EPSILON;
}

So that I can call isNodeModified(node) or isNodeModified(node, event) depending on what I need.

Is there a better / cleaner solution to this problem?


texts: Shell script to parse variable definitions from Scala build file

texts:
The build.sbt text file contains versions like this:

name := "happy"
scalaVersion := "2.11.8"
sparkVersion := "2.2.0"

I wrote a Bash script to parse out the PROJECT_NAME and SCALA_VERSION from the build.sbt file:

PROJECT_NAME=$(cat build.sbt | grep "name :=" | cut -f 3 -d " " | tr -d '"')
SCALA_VERSION=$(cat build.sbt | grep "scalaVersion :=" | cut -f 3 -d " " | tr -d '"')

How can I write this more elegantly / robustly?  I'm ok with an awk or sed approach, but don't want to add an external dependency to the script.

Here's some more of the script to see how the variables are being used.

if [ "$SCALA_VERSION" = "" ]
  then
    echo "SCALA_VERSION variable cannot be empty"
    exit 1
fi

SCALA_BINARY_VERSION=${SCALA_VERSION%.*}
if [ "$SCALA_BINARY_VERSION" = "" ]
  then
    echo "SCALA_BINARY_VERSION variable cannot be empty"
    exit 1
fi

echo "Create a GitHub release"
JAR_PATH=target/scala-${SCALA_BINARY_VERSION}/${PROJECT_NAME}_${SCALA_BINARY_VERSION}-${SPARK_VERSION}_${PROJECT_VERSION}.jar
hub release create -a $JAR_PATH -m "Release v${PROJECT_VERSION}" v${PROJECT_VERSION}


texts:
I shuffle a deck of cards(with an equal number of red and black
  cards) and start dealing them face up.
  After any card you can say “stop”, at which point I pay you $1 for
  every red card dealt and you pay me $1 for every black card dealt.
  What is your optimal strategy, and how much would you pay to play
  this game ?

I'd be very happy if you could judge the quality of the code.

using namespace std;

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

    BinaryOptionPricing bop;
    int total_number_of_cards;

    sscanf_s(argv[1], "%d", &total_number_of_cards);
    cout << "Total Number of Cards = " << total_number_of_cards << endl;

    bop.set(total_number_of_cards);
    cout << "Value of the game = " << bop.get() << endl;

    return 0;
}

class BinaryOptionPricing
{

private: int red;
private: int black;
private: std::map<std::pair<int, int>, double> Cache;
private: typedef int card;
private: typedef double redValue;
private: typedef double blackValue;
private: typedef double gameValue;

private:
    double value(card red, card black)
    {
        redValue rValue;
        blackValue bValue;
        gameValue maxValue;

        if (0 == red)
            return ((double)black);
        if (0 == black)
            return (0);

        auto searchPair = Cache.find(std::make_pair(red, black));

        if (searchPair != Cache.end())
            return (searchPair->second);

        rValue= ((double)red / (red + black)) * value(red - 1, black);
        bValue = ((double)black / (red + black)) * value(red, black - 1);

        maxValue = std::max((rValue + bValue), (double)(black - red));
        Cache.insert(std::make_pair(make_pair(red, black), maxValue));

        return maxValue;
    }

public:
    double get()
    {
        return value(red, black);
    }

public:
    void set(int totalNumberOfCards)
    {
        this->red = (totalNumberOfCards/2);
        this->black = (totalNumberOfCards / 2);
    }
};


texts:
I decided to code a simple Hangman in Python today and wanted some feedback on the code since I only started programming three weeks ago.

I intentionally didn't add a lot of whitespace, it just doesn't make it any more readable for me - but feel free to give me reasons to start doing so.

Any tips and suggestions are appreciated.

import os

words = ["foobar", "gnarf", "fnord"]

current_word = 0
maximum_words = len(words)
maximum_guesses = 10
solved_words = 0

for word in words:
    current_word += 1
    current_guess = 0
    dashes = []
    for letter in word:
        dashes.append("_")
    while current_guess < maximum_guesses:
        current_guess += 1
        os.system("clear")
        print("Word {}/{}".format(current_word, maximum_words))
        print("Solved {}/{}".format(solved_words, maximum_words))
        print("Guess {}/{}".format(current_guess, maximum_guesses))
        print("\n{}\n".format(" ".join(dashes)))
        guess = input("Guess: ")
        guess = guess.lower()
        if not len(guess) == 1 or not guess.isalpha():
            current_guess -= 1
        for index, letter in enumerate(word):
            if letter == guess:
                dashes[index] = letter
        if not "_" in dashes:
            solved_words += 1
            break

The output looks something like this:

Word 1/3
Solved 0/3
Guess 5/10

f o o b a _

Guess: r

Any suggestings for a better output?


texts:
I have a 2D array class that is actually mapped to a 1D vector. For example, to obtain an element at a particular position, the code is as follows:

template <typename T>
T mat <T>::at(const size_t &row, const size_t &col) const
{
  return m_values[row*ncol() + col];
}

Here's the relevant section of the class in-context:

template <typename T>
class mat
{
private:
  std::vector <T> m_values;
  size_t m_nrow, m_ncol;
public:
  mat();

  size_t ncol() const{ return m_ncol; };
  size_t nrow() const{ return m_nrow; };

  T at(const size_t &row, const size_t &col) const;
  std::vector <T> row(const size_t &row) const;
  std::vector <T> col(const size_t &col) const;
};

m_nrow and m_ncol contain the number of rows and columns of the 2D array, respectively, while m_values contains the values of the array. They're assigned in another (long) constructor.

I now need to be able to return an entire row or column. Here's how that's currently implemented:

template <typename T>
std::vector <T> mat <T>::row(const size_t &row) const
{
  std::vector <T> tmp;
  for(size_t j=0; j < ncol(); j++)
  {
    tmp.push_back(at(row, j));
  }
  return tmp;
}

template <typename T>
std::vector <T> mat <T>::col(const size_t &col) const
{
  std::vector <T> tmp;
  for(size_t i=0; i < nrow(); i++)
  {
    tmp.push_back(at(i, col));
  }
  return tmp;
}

These implementations are easy to reason about but not particularly efficient: there's the pushing back to a temporary vector and the repeated calculation of row*ncol() in at(). Is there a more idiomatic way of doing this in C++11?


texts:
I have recently just started learning Perl, so I decided to program the classic 'Guess my Number' game. I was wondering if anyone can spot any areas for improvement.  As it's my first program, I expect there to be some unoptimized areas.

#!\usr\bin\perl
print"Welcome to guess my number!\n";
    $compNumber=int rand 100;
    while($n<6){
        print"Guess a number between 1 and 100: ";
        chomp($userNumber=<STDIN>);
        if($compNumber>$userNumber){
            print"Your guess was too low, try again.\n";
        }
        if($compNumber<$userNumber){
            print"Your guess was too  high, try again.\n";
        }
        $n++
    }
    if($compNumber==$userNumber){
        print"Well done, $compNumber was my number! You got it correct in $n guesses!";
    }
    if($compNumber!=$userNumber){
        print"Unfortunately, you couldn't guess my number in 6 guesses, it was actually ${compNumber}.";
    }


texts:
I was bored and burnt out on more serious projects.... until I saw this Computerphile video on YouTube. Now I'm inspired again. Now I feel like spending some time implementing that recursive algorithm in a little console program. Fortunately, recursion is unbearably slow in this case. So, I ended up writing a small class that implements a loop algorithm to find any \$F_n\$.

I'm just learning C#, so I'm most concerned with best practices and style. I want to get a good foundation though, so all feedback is welcome.

Particular Concerns

Is my indentation correct?
Have I named my variables horribly? (I think they smell a bit.)
Which implementation is better? I'm feeling like it's six of one or a half doz. of the other.
Should I be concerned about hitting the upper boundary of the ulong type? Fibonacci numbers grow very quickly. Is there a better representation of very large numbers?

Fibonacci

class Fibonacci
{
    private int _n;
    private ulong _value;
    private ulong _FnMinus1;
    private ulong _FnMinus2;

    public int n
    {
        get { return _n; }
        set { _n = value; }
    }

    public ulong Value
    {
        get {return _value;}
        //set { _value = value; }
    }

    public void Calculate()
    {
        if (n <= 0)
        {
            throw new ArgumentOutOfRangeException("n","Can't calculate Fn when n is less than or equal to zero.");
        }
        else if (n == 1 || n == 2)
        {
            _value = 1;
        }
        else
        {
            //initialize previous results
            _FnMinus1 = 1;
            _FnMinus2 = 1;

            for (int i = 0; i <= (n - 2) ; i++)
            {
                _value = _FnMinus1 + _FnMinus2;
                _FnMinus2 = _FnMinus1;
                _FnMinus1 = _value;
            }
        }
    }

    //constructors
    public Fibonacci(int n)
    {
        _n = n;
        Calculate();
    }

    public Fibonacci() { }

}

Implementation1

class Program
{
     static void Main(string[] args)
    {

        Fibonacci fib = new Fibonacci();
        for (int i = 1; i <= 50; i++)
        {
            fib.n = i;
            fib.Calculate();
            Console.WriteLine(fib.Value);
        }

        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
}

Implementation2

class Program
{
     static void Main(string[] args)
    {

        for (int i = 1; i <= 50; i++)
        {
            Fibonacci fib = new Fibonacci(i);
            Console.WriteLine(fib.Value);
        }

        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
}

Update: Follow up question here.


texts:
I implemented ArrayList functionality in C as follows:

#include <stdlib.h>
#include <assert.h>
#include "ArrayList.h"

struct _arraylist {
    size_t size;
    void ** data;
};

struct _arraylist *arraylist_create() {
    /* Allocate Memory */
    struct _arraylist *list = malloc(sizeof(struct _arraylist));
    assert(list != NULL);
    list->size = 0;
    list->data = calloc(2, sizeof(void *));
    assert(list->data != NULL);
    list->data[0] = NULL;
    return list;
}

void arraylist_setdata(struct _arraylist *list, void ** data, int max, int clear_data) {
    /* Sets the internal array of the arraylist */
    clear_data ? arraylist_clear(list) : NULL;
    list->data = data;
    list->size = max;
}

void arraylist_add(struct _arraylist *list, void *elem) {
    /* Adds one element of generic pointer type to the internal array */
    void ** new_data = realloc(list->data, arraylist_getsizeof(list));
    assert(new_data != NULL);
    new_data[list->size] = elem;
    arraylist_setdata(list, new_data, list->size + 1, 0);
}

void *arraylist_get(struct _arraylist *list, int index) {
    /* Gets an member of the array at an index */
    return list->data[index];
}

size_t arraylist_getsizeof(struct _arraylist *list) {
    /* Returns the size of the internal array in memory */
    return sizeof(*list->data);
}
size_t arraylist_getsize(struct _arraylist *list) {
    /* Returns the number of elements in the arraylist */
    return list->size;
}

void arraylist_remove(struct _arraylist *list, int index, int freeit) {
    /* Removes one element at and index */
    if (index > list->size - 1)
        return;
    if (list->size == 1) {
        arraylist_clear(list);
        return;
    }
    if (freeit)
        free(arraylist_get(list, index));
    for ( int i = index; i < list->size; ++i ) {
        if (i == list->size - 1)
            list->data[i] = NULL;
        else
            list->data[i] = list->data[i + 1];
    }
    void ** new_data = realloc(list->data, arraylist_getsizeof(list));
    --list->size;
    assert(new_data != NULL);
    arraylist_setdata(list, new_data, list->size, 0);
}

void arraylist_clear(struct _arraylist *list) {
    /* Clears the internal array */
    list->size = 0;
    free(list->data);
    list->data = NULL;
}

void arraylist_deallocate(struct _arraylist *list) {
    /* De-allocates the arraylist from memory
    No usage of the arraylist is allowed after this function call */
    if (list->data != NULL)
        free(list->data);
    free(list);
}

int arraylist_getindex(struct _arraylist *list, void *elem) {
    /* Looks for elem in list and returns the index or -1 if not found */
    for(int i = 0; i < list->size; ++i)
        if (elem == arraylist_get(list, i))
            return i;
    return -1;
}

I'm testing it like this:

#include <stdio.h>
#include "ArrayList.h"

int main(int argc, char const *argv[])
{
    ArrayList *list = arraylist_create();
    int i;
    for(i = 0; i < 100; ++i)
        arraylist_add(list, &i);
    for(i = 0; i < 100; ++i)
        printf("i: %d\n", *(int *)arraylist_get(list, i));
    for(i = 0; i < 100; ++i)
        arraylist_remove(list, i, 0);
    arraylist_deallocate(list);
    return 0;
}

It works fine, though realloc sometimes crash the program. Can I improve this ?


texts:
I often receive large Excel-sheets in which data has been inserted via copy and paste. Usually a lot of the cells contain whitespaces at the beginning and the end before / after the actual value.

I made a VBA-script for to get rid of these whitespaces.

' Removes whitespaces at the
' beginning and the end
' of all cell-values.

Public Sub trimCells()
    Dim lastRow As Long
    Dim lastColumn As Long
    Dim row As Long
    Dim column As Long

    On Error GoTo errorHandler

    ' Find() == VBA-equivalent to
    ' the find-menue in the Excel-GUI.
    ' What:="*" => Matches EVERY content.
    ' Start in the bottom-right corner &
    ' search from there through the rows
    ' upward.
    lastRow = Cells.Find(What:="*", _
                         SearchOrder:=xlByRows, _
                         SearchDirection:=xlPrevious).row
    ' Search in the last row with content for most
    ' right cell with a value.
    lastColumn = Cells(lastRow, Columns.Count).End(xlToLeft).column

    ' Go through the detected range &
    ' apply the trim-function on every cell.
    For row = 1 To lastRow
        For column = 1 To lastColumn
          Cells(row, column).Value = _
            Trim(Cells(row, column).Value)
        Next
    Next

    Exit Sub

errorHandler:
    MsgBox "Error has occurred.", _
      vbCritical, "Error!"

End Sub

I apply the trim-function on every cell-value. So I ask myself:

What is better?

Doing unnecessary executions of the trim-function or checking if it has to be applied? Checking would cost me an additional if-then.

UPDATE

The above algorithm contains an error.

Concerning a table with the following structure:

First | Second |

Alpha | Beta | Gamma |

One   |

The result would be:

lastRow: 3
lastColumn: 1

Reason: It searches in the last row for the most right column.
But what is needed is the most right column overall.

Now I determine lastRow and lastColumn this way:

lastRow = Range("A1").SpecialCells(xlCellTypeLastCell).row

lastColumn = Range("A1").SpecialCells(xlCellTypeLastCell).column


texts: Simple Go REST API that returns dummy messages

texts:
I am a learner in Go and wrote example below in a day so I would like to get some suggestions to improve it. It is a simple rest api that currently just accepts request and returns a dummy message. My main aim here is to get comments and suggestions on how I structured the flow/logic. Although it currently works fine and easy to follow (at least to me), could it be done in a cleaner/scalable way?

cmd/server.go

package main

import (
    "fmt"
    "football-api/internal/app/route"
    "log"
    "net/http"
)

type server struct {}

func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    response, err := route.Handler(r)
    if err != nil {
        w.WriteHeader(http.StatusNotFound)
    } else {
        w.WriteHeader(http.StatusOK)
    }

    w.Write([]byte(response))
}

func main() {
    fmt.Println("Server is running on port 8080 ...")

    err := http.ListenAndServe(":8080", &server{})
    if err != nil {
        log.Fatalf("Couldn't start server on :8080. [%s]", err.Error())
    }
}

internal/app/route/handler.go

package route

import (
    "errors"
    "net/http"
    "path/filepath"
)

func Handler(r *http.Request) (response string, err error) {
    switch filepath.Clean(r.URL.Path) {
    case "/":
        return Home(r), nil
    case "/comments":
        return Comments(r), nil
    default:
        return "", errors.New("route was not found")
    }
}

internal/app/route/home.go

package route

import "net/http"

func Home(r *http.Request) string {
    return "Home"
}

internal/app/route/comments.go

package route

import "net/http"

func Comments(r *http.Request) string {
    return "Comments"
}


texts: Scraping links from the first page of Google using Kivy

texts:
I'm making a scraper/web crawler using Kivy when I run the code it works but I'm not sure if what I'm doing is Pythonic because all the language I can find is about using the Kivy library. I'm unsure about putting the functions to bind the widgets to inside the build method. Is there a better way?

class MainApp(App):

    def build(self):
        root = RootWidget()
        c = CustomLayout()
        root.add_widget(c)

        search_term = TextInput(
            text='',
            size_hint=(.5, .05),
            pos=(250, 15))
        c.add_widget(search_term)

        def on_enter(self):
            scrape = Scrape(search_term.text, ['user_agent','chrome'])
            scrape.get_goog_links()
        get_links = Button(
            text='Get links',
            size_hint=(.5, .10),
            pos=(20, 20))
        root.add_widget(get_links)
        get_links.bind(on_press=on_enter)

        return root


texts: Very slow Project Euler Q3 (largest prime factor of a large number)

texts:
My code returns the correct answer for the example (highest prime of  13195 is 29), but when I test against the number in the question my code basically is too slow for my liking.

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143?

Is there anything obviously wrong with my logic or any ways to improve?

(function(){

var theNumber = 600851475143; // testing this number, sub in 13195 to verify

var getHighestPrimeFactor = function(number){
    var upto = (number / 2) % 2 == 0 ? (number/2) : Math.floor(number/2);
    var factors = [];

    for(var i = upto; i > 1; i--){
        if(number % i == 0){
            factors.push(i);
            if(isPrimeFactor(i) == true){
                console.log("high prime = " + i);
                return i;
            }
        }
    }
} // end getHighestPrimeFactor

var isPrimeFactor = function(number){
    var upto = number / 2;
    var isItPrime = true;
    for(var i = 2; i < upto; i++){
        if(number % i == 0){
            isItPrime = false;
            break;
        }
    }
    return isItPrime;
} // end isPrimeFactor

var x = getHighestPrimeFactor(theNumber);
console.log(x);

})();


texts: Removing an object which is wrapped in another object from a collection

texts:
I have Clips that can be added to or removed from any number of Lines. When I add the Clip, I put it into a ClipHolder so I can keep some bounds information with it which is specific to the Line / Clip relationship.

The trouble comes when I want to remove a Clip from the Line. I need to remove the ClipHolder in the associatedClips Set which holds the Clip, but I cannot just call associateClips.remove(Clip) (obviously as the set is holding ClipHolders, not Clips) so I am stuck iterating through the set, and searching one by one for it (see the removeClip method below.)

Within the Line class the ClipHolder class is simply an implementation detail that the user should not have to worry about. They should only have to worry about their Clips which are a separate class.

I would like to avoid burdening the users of this class with requiring them to choose a unique token to identify each instance of Clip. I think that  having a reference to the Clip should be enough. (Is this reasonable?)

Does anyone have a good way of cleaning this up?

class Line {

    .....

    private class ClipHolder{
        Clip c;
        Bounds bounds;
    }

    private TreeSet<ClipHolder> associatedClips = new TreeSet<ClipHolder>();

    public void addClip(Clip c){

        ClipHolder holder = new ClipHolder();
        holder.c = c;
        calculateBounds(holder);

        associatedClips.add(holder);
    }

    public void removeClip(Clip c){

        for (ClipHolder ih: associatedClips ) {
            if(ih.c == c){
                associatedClips.remove(ih);
                break;
            }
        }
    }
}


texts: Extracting and mangling a parameter from a MySQL configuration file

texts:
Is there a better way of doing this?

File.open( "/etc/my.cnf" ) do |f|
  f.grep( /^testdir/ ) do |line|
    test1 = line.chop.gsub(/ /,"")
    test2 = test1.sub(/.*=/, "")
    RETURN_PATH = "#{test2}/test_ups"
  end
end


texts:
I wanted to create a simple and easy to use permissions system. The ones I've found on the Internet would need to attach every permission to a route manually (e.g. Entrust).

My idea is to build a permission name out of the current action, so for example method 'store' in 'TestController' becomes 'test.store' permission.

Is it a good approach? I couldn't find anything similiar on the web.

class SecuredController extends Controller {

    /**
     * @var array
     * unguarded actions (method names)
     */
    protected $unguarded = [];

    /**
     * @var array
     * actions (method names) that need csrf token checked
     */
    protected $csrfguarded = [];

    private $permission;

    public function getCurrentPermission() {
        return $this->permission;
    }

    public function callAction($method, $parameters) {
        if(! $this->canAccessCurrentAction()) {
            return $this->accessDenied();
        }

        return parent::callAction($method, $parameters);
    }

    /**
     * @param string $action e.g. TestController@store
     *
     * @return bool
     * @throws \Illuminate\Session\TokenMismatchException
     */
    public function canAccessAction($action) {
        /**
         * split $action(e.g. TestController@store) into two parts
         * and build a permission name (e.g. test.store) and check for access
         */

        list($controller, $method) = explode('@', $action);

        if(in_array($method, $this->unguarded, true)) {
            return true;
        }

        if(in_array($method, $this->csrfguarded, true)
           && Session::token() !== Input::get('_token'))
        {
            throw new Illuminate\Session\TokenMismatchException;
        }

        if(! Auth::check()) {
            return false;
        }

        $this->permission = $this->buildPermissionName($controller, $method);

        if(Auth::getUser()->capable($this->permission)) {
            return true;
        }

        return false;
    }

    public function canAccessCurrentAction() {
        return $this->canAccessAction( \Route::getCurrentRoute()->getActionName());
    }

    public function buildPermissionName($controller, $method) {
        return strtolower(
            substr(
                $controller,
                strrpos($controller, '\\'),
                - 10 // 'controller' word
            ) . '.' . $method
        );
    }

    /**
     * Override it!
     */
    public function accessDenied() {
        if(Request::ajax()) {
            return Response::make('You cannot access this!', 403);
        }

        return Response::make('You cannot access this!', 403);
    }
}

The capable method of User:

public function capable($neededPermission) {
    foreach($this->getPermissions() as $permission) {
        if(substr($permission, -1) === '*') {
            $permission = substr($permission, 0, -1);

            if(startsWith($neededPermission, $permission)) {
                return true;
            }
        }
        elseif($permission === $neededPermission) {
            return true;
        }
    }

    return false;
}


texts: Speeding up Parallel.ForEach iterating through datatable and rendering report

texts:
I am attempting to speed up the processing of 5000 rows received from the database, which I then render as a crystal report, export to a byte stream and save in a database table.

Currently I am using parallel.ForEach on a datatable. This uses 40 parallel processes that then sequentially iterates 125 (i.e 5000/40) records each of the 5000 rows.

It take approximately 5 minutes to do 5000 records at the moment. Is there any way I can speed this up?

DataTable dtBills = new DataTable("dtBills");//I used an OdbcDataAdapter to fill this with 5000 records

private void ParallelProcess()
{
    int numbills = 5000;
    int numprocesses = 40;
    int numsequential = numbills / numprocesses;

    int p=0;

    if (numbills < numprocesses)
        p = numbills;
    else
        p = numprocesses;

    Parallel.For(1, p+1, new ParallelOptions { MaxDegreeOfParallelism = 40 }, i =>
        {
            SequentialProcess(numsequential,i);

        });

}

private void SequentialProcess(int batch,int num)
{
    ReportDocument cryRpt = new ReportDocument();
    cryRpt.Load(Application.StartupPath + "\\" + "Bill.rpt");

    foreach(DataRow drow in dtBills.Rows.Cast<System.Data.DataRow>().Skip((num - 1) * batch).Take(batch).CopyToDataTable().Rows)

    {

        cryRpt.SetParameterValue(..... //here I set Crystal report Parameter values

        Stream stream = cryRpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        byte[] contents = new byte[stream.Length];
        stream.Read(contents, 0, (int)stream.Length);
        stream.Close();

        if (!string.IsNullOrEmpty(sconnstr))
        {
            using (SqlConnection sconn = new SqlConnection(sconnstr))
            {

                String qry = @"INSERT INTO ....."
                using (SqlCommand cmd = new SqlCommand(qry, sconn))
                {

                    cmd.CommandType = CommandType.Text;

                    cmd.Parameters.AddWithValue(// Set values for insert here one of which will be contents

                    cmd.Connection = sconn;

                    sconn.Open();
                    cmd.ExecuteNonQuery();
                    sconn.Close();

                }

            }
        }

    }

    cryRpt.Close();
    cryRpt.Dispose();

}


texts: Read two numbers and return a sum, in PIC24 Assembly

texts:
.data
D0:  .byte 0x04; first number
D1:  .byte 0x03; second number
.bss
R0: .space 2;result
.txt
_main:   ..
         ..
         CALL mySUB
         ..
mySUB:   ...
         ....
         return
 .end

Given above, write a program that would read the numbers (in D0 and D1) and call a subroutine, mySUB, that adds the two number and returns the result. Then your main program saves the result in R0.

My attempt at this was

.data
D0:  .byte 0x04; first number
D1:  .byte 0x03; second number
.bss
R0: .space 2;result
.txt
_main:   mov.b #D0,W1
         mov.b #D1,W2
         CALL mySUB
         mov W3,[W0]; once the subroutine returns, it comes to this line, which stores the result to R0's address
mySUB:   mov #R0,W0
         add W1,W2,W3; W3 = D0+D1
         return; return back to where it was called
 .end

I feel confident that this is the right set of instructions but need confirmation.


texts: Convert list/tuple of arguments into just arguments

texts:
I am using a library that specifically needs me to provide arguments as strings one by one. However, different combinations are possible. Right now I am using a bunch of elif:

def get_all_users(times=False, groups=False, ips=False):
    """Get a list of all users online"""
    if times and groups and ips:
        return ts3conn.exec_("clientlist", "times", "groups", "ips")
    elif times and groups:
        return ts3conn.exec_("clientlist", "times", "groups")
    elif times and ips:
        return ts3conn.exec_("clientlist", "times", "ips")
    elif groups and ips:
        return ts3conn.exec_("clientlist", "groups", "ips")
    elif times:
        return ts3conn.exec_("clientlist", "times")
    elif groups:
        return ts3conn.exec_("clientlist", "groups")
    elif ips:
        return ts3conn.exec_("clientlist", "ip")
    else:
        return ts3conn.exec_("clientlist")

But I am wondering if this could be improved.

NOTE: I tried if I could use tuples but it won't work:

stuff = (times, groups, ips)
return ts3conn.exec_("clientlist", stuff)
>>> TypeError: can only concatenate str (not "tuple") to str

Update:
Library is at: https://github.com/benediktschmitt/py-ts3/blob/v2/ts3/query_builder.py

The code raises error on function compile:

for option in options:
    res += " -" + option


texts:
Below is the current working code for an ongoing project.

I am wondering if there is anything I can do to improve the code snippet below. My main concerns lie to two area. First being that I append the answer of an input to a list called inputList and then call it in a block of conditionals. I am wondering if this in particular is a good approach. Are there any better approaches?

Secondly, similar concerns lay with how I defined the answers and dictionaries of their variants. My main purpose there is that, regardless of how you enter "yes" or "no", as long as it has those letters and in the proper order, i.e "nO" or "yES", it would be accepted. I also did it as I did so that I would not have to concern myself on checking whether or not the first letter of any of those two words are capitalised or not.

Again, my question being, is this a "solid" approach? What alternative approaches would be better for this snippet of code? Perhaps a better question would be, how can I improve this snippet?

I am also interested in seeing if I can shorten it as much as possible. Similar to how permLet() is written.

from itertools import product, zip_longest
import pylab as plot
import numpy as number
import pprint

inputFile = input('File Name: ')

def yLimits():
    yMin = int(input('Set lower limit: '))
    yMax = int(input('Set upper limit: '))
    labelLocation = number.arange(len(count))
    plot.bar(labelLocation, list(count.values()), align='center', width=0.5)
    plot.xticks(labelLocation, list(count.keys()))
    plot.xlabel('Characters')
    plot.ylabel('Frequency')
    plot.ylim(yMin, yMax)
    plot.show()

def ylimChoice():

    #returns all permutations of letter capitalisation in a certain word.
    def permLet(s):
        return(''.join(t) for t in product(*zip(s.lower(), s.upper())))

    inputList = []
    yesNo = input('Would you like to set custom ylim() arguments? ')
    inputList.append(yesNo)
    yes = list(permLet("yes"))
    no = list(permLet("no"))

    if any(yesNo in str({y: y for y in yes}.values()) for yesNo in inputList[0]):
        yLimits()
    elif any(yesNo in str({n: n for n in no}.values()) for yesNo in inputList[0]):
        labelLocation = number.arange(len(count))
        plot.bar(labelLocation, list(count.values()), align='center', width=0.5)
        plot.xticks(labelLocation, list(count.keys()))
        plot.xlabel('Characters')
        plot.ylabel('Frequency')
        plot.autoscale(enable=True, axis='both', tight=False)
        plot.show()

count = { }
with open(inputFile, 'r') as info:
    readFile = info.read()
    for character in readFile.upper():
        count.setdefault(character, 0)
        count[character] = count[character]+1

value = pprint.pformat(count)
print(value)

ylimChoice()


texts: Confirming whether a user is registered, using Optional class in Java 8

texts:
I start to learn Java 8 and I wondering is that kind of using Optional class is correct?

@Override
public Response confirmRegister(Request request) {
    return mailTokenRepository.findByToken(request.getToken()).map(mailToken -> {
        if (mailToken.getTypeToken().equals(TypeToken.REGISTER)
                && mailToken.getToken().equals(request.getToken())) {
            return Optional.ofNullable(userRepository.findOne(mailToken.getUser().getId())).map(user -> {
                user.setBlock(false);
                userRepository.save(user);
                mailTokenRepository.delete(mailToken);
                return jsonService.prepareResponseForUser(StatusMessage.SUCCESS, "SUCCESS_REGISTERED", null, null,
                        true);
            }).orElseGet(() -> jsonService.prepareErrorResponse("INCORRECT_DATA"));
        } else
            return jsonService.prepareErrorResponse("INCORRECT_DATA");
    }).orElseGet(() -> jsonService.prepareErrorResponse("INCORRECT_DATA"));

}


texts: Populate inorder successor for all nodes

texts:
Given a binary tree where each node has following structure, write a
  function to populate next pointer for all nodes. The next pointer for
  every node should be set to point to inorder successor.

struct node
{
  int data;
  struct node* left;
  struct node* right;
  struct node* next;
}

  Initially, all next pointers have NULL values. Your function should
  fill these next pointers so that they point to inorder successor.

This code is attributed to GeeksForGeeks. Looking for code review, optimizations and best practices.

public class PopulateInorderSuccessor<T> {

    private TreeNode<T> root;

    public PopulateInorderSuccessor(List<T> items) {
        create (items);
    }

    private void create(List<T> items) {
        if (items.size() == 0) {
            throw new IllegalArgumentException("There should atlease be single item in the tree");
        }

        root = new TreeNode<>(items.get(0));

        final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode<T> current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode<T>(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode<T>(items.get(right));
                    queue.add(current.right);
                }
            }
        }
    }

    private static class TreeNode<T> {
        private TreeNode<T> left;
        private T item;
        private TreeNode<T> right;
        private TreeNode<T> next;

        TreeNode(T item) {
            this.item = item;
        }
    }

    private static class TreeNodeHolder<T> {
        private TreeNode<T> treeNode;
    }

    public void populateInorderSuccessor() {
        populate(root, new TreeNodeHolder<T>());
    }

    private void populate(TreeNode<T> node, TreeNodeHolder<T> treeNodeHolder) {
        if (node != null) {
            populate(node.right, treeNodeHolder);
            node.next = treeNodeHolder.treeNode;
            treeNodeHolder.treeNode = node;
            populate(node.left, treeNodeHolder);
        }
    }

    public List<T> toInOrderList() {
        TreeNode<T> node = root;

        while (node.left != null) {
            node = node.left;
        }

        final List<T> list = new ArrayList<>();
        while (node != null) {
            list.add(node.item);
            node = node.next;
        }
        return list;
    }
}

public class PopulateInorderSuccessorTest {

    @Test
    public void testCompleteTree() {
        PopulateInorderSuccessor<Integer> pis1 = new PopulateInorderSuccessor<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        pis1.populateInorderSuccessor();
        assertEquals(Arrays.asList(4, 2, 5, 1, 6, 3, 7), pis1.toInOrderList());
    }

    @Test
    public void testLeftSkewedTree() {
        // left skewed
        PopulateInorderSuccessor<Integer> pis2 = new PopulateInorderSuccessor<Integer>(Arrays.asList(1, 2, null, 4));
        pis2.populateInorderSuccessor();
        assertEquals(Arrays.asList(4, 2, 1), pis2.toInOrderList());
    }

    @Test
    public void testRightSkewedTree() {
        // right skewed
        PopulateInorderSuccessor<Integer> pis3 = new PopulateInorderSuccessor<Integer>(Arrays.asList(1, null, 3, null, null, null, 7));
        pis3.populateInorderSuccessor();
        assertEquals(Arrays.asList(1, 3, 7), pis3.toInOrderList());
    }
}


texts: Implementing an encryption standard over message text

texts:
I wrote the below code and tested some example files on it.  I didn't find any errors, but I still want to be thorough about this.

Also, any suggestions in improving the code?

import string
""" this implements an encryption standard over the message text
it replaces the odd place alphabets by their ordinal number plus place number increased.
it replaces the even place alphabets by their ordinal number minus place number decreased.
for example "hello" becomes "icoht" and "abc" becomes "bzf".
"""
input_filename = raw_input("Enter the input file name: ")
output_filename = raw_input("Enter the output dumping file name: ")
mode = raw_input("Do you want to encrypt or decrypt (e/d)?: ")
with open(input_filename,'r') as inputfile:
    with open(output_filename,'w') as outputfile:
        inp = inputfile.read()
        encode = lambda s: "".join(
            (chr(ord('a')+((ord(c)-(ord('a')+i+1))%26))) if ((c.isalpha()) and ((i+1)% 2 ==0))
            else
            string.ascii_lowercase[(string.ascii_lowercase.rfind(c.lower())+i+1)%26]  if ((c.isalpha()) and ((i+1)% 2 ==1))
            else
            c
            for i,c in enumerate(s.lower())
            )
        decode = lambda s: "".join(
            string.ascii_lowercase[(string.ascii_lowercase.rfind(c.lower())+i+1)%26] if ((c.isalpha()) and ((i+1)% 2 ==0))
            else
            (chr(ord('a')+((ord(c)-(ord('a')+i+1))%26))) if ((c.isalpha()) and ((i+1)% 2 ==1))
            else
            c
            for i,c in enumerate(s.lower())

            )
        if(mode.lower() == 'e'):
            outputfile.write(encode(inp))
        else :#(mode.lower() =='d'):
            outputfile.write(decode(inp))
    s = {'e':'Encoding','d':'Decoding'}
    print s.get(mode)+" Sucessfull"


texts:
I wrote a simple animation of a ball moving across the screen. I was wondering if I used the static variable correctly. If not, how could I make it non-static so I could instantiate it in the main method whilst being able to access its getter methods in the listener inner class? Also, did I use the SwingUtilities.invokeLater() method properly?

Please let me know of any improvements that I can make.

import java.awt.*;
import javax.swing.*;

public class SimpleAnimation {
    private JFrame frame;
    private int x = 5;
    private int y = 5;

    static SimpleAnimation animation;

    public static void main(String[] args){
        animation = new SimpleAnimation();
        animation.buildGUI();

        // Use i to change co-ordinates x and y to produce a moving ball on the screen.
        for(int i = 0; i <= 300; i+=1){
            animation.setCoordinates(i, i);
            animation.frame.repaint();      // JVM uses new co-ordinates in paintComponent() to repaint the ball
            try{
                Thread.sleep(10);
            }catch(InterruptedException interruptedException){
                interruptedException.printStackTrace();
            }
        }
    }

    public void buildGUI(){
        frame = new JFrame("Simple animation");
        SwingUtilities.invokeLater(
                new Runnable() {
                    @Override
                    public void run() {
                        frame.setContentPane(new DrawPanel(new BorderLayout()));
                        frame.setSize(400, 500);
                        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);
                    }
                }
        );

    }

    // GETTERS
    int getX(){
        return x;
    }

    int getY(){
        return y;
    }

    // SETTERS
    void setCoordinates(int newX, int newY){
        x = newX;
        y = newY;
    }

    class DrawPanel extends JPanel{
        public DrawPanel(LayoutManager layout){
            super(layout);
        }

        @Override
        public void paintComponent(Graphics g){
            g.setColor(Color.ORANGE);
            g.fillOval(animation.getX(), animation.getY(), 100, 100);
        }
    }
}


texts: List of word to list of index in a vocabulary

texts:
I have a dataset composed of ~700k samples. Each sample is composed of n_features features. Each feature is a word. Each feature has his own vocabulary. The size of the vocabularies range from 18 to 32000.

  np.shape(x) -> (n_samples, n_features)

Instead of having lists of features I would like to have lists of indexes corresponding to the indexes in vocabularies. This is my code:

vocs = [np.array(list(set(x[:,i]))) for i in range(np.shape(x)[1])]
x_new = [[np.argwhere(vocs[j]==x[i,j]) for j,feature in enumerate(features)] for i,features in enumerate(x)]

This code works but I wonder if there is a way to improve the performances. These 2 lines take 10min to run on my i7-7700HQ @ 2.8GHz.

Edit:

For more context, what I'm working on is natural language processing. I want to train a classifier to predict relations between words in a sentence. For this I have a conllu file which give sentences and for each word of each sentence a list of features and with which word it's related and how. These features may be the word itself, its lemma, its position in the sentence etc... I'm trying a different set of features and type of embedding and I want to test the embedding described above.


texts: Preventing SQL injection without using prepared statements

texts:
I'm learning OOP and totally new to this way of coding. I've always scripted PHP the procedurial way. Now I've written a working class, which creates a database connection and has the method to create a query which is impossible to SQL-inject by hexing the non-integer data. (I know how to use prepared statements, but i just don't want to use them because there is a slight performance penalty in my case)

Note: When hexing data the right way, its not possible to inject.Have a look at Zaffy's answer.

My questions:

What could I've done better?
Is it 'wrong' to use this class because its not good OOP (besides its function), or does it not really matter, because it works as how i want it to work? (nobody else is going to maintain the script)

And I must say, I've read multiple tutorials, but it's really difficult to fully understand howto write OOP style if you've never done before!

databaseconnection.class.php

<?php
class DatabaseConnection {
    private $data, $sql, $conn, $host, $user, $pass, $dtbs;

    public function __construct($host, $user, $pass, $dtbs) {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->dtbs = $dtbs;

        $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->dtbs);
        if ($this->conn) {
            return $this->conn;
        } else {
            return false;
        }
    }

    public function query($sql, $data) {
        $this->data = $data;
        $this->sql = $sql;
        foreach ($data as $val) {
            if (strpos($this->sql, "'%i'") !== false || strpos($this->sql, "'%s'") !== false || strpos($this->sql, '"%i"') !== false || strpos($this->sql, '"%i"') !== false) {
                echo "SQL incorrect: There can't be any quotes around the parameters, because this function does that automaticly for you";
                exit();
            }
            $pos = strpos($this->sql, '%');
            $type = substr($this->sql, $pos, 2);
            if ($type == '%i') {
                if (is_int($val)) {
                    $this->sql = substr_replace($this->sql, $val, $pos, 2);
                } else {
                    echo "Parameter incorrect: Data is not an integer value";
                    exit();
                }
            } elseif ($type == '%s') {
                if (!is_int($val)) {
                    $this->sql = substr_replace($this->sql, "UNHEX('".bin2hex($val)."')", $pos, 2);
                } else {
                    echo "Parameter incorrect: Data is an integer value";
                    exit();
                }
            } else {
                echo "Parameter incorrect: Parameter %i for integer of %s for all other types of data";
                exit();
            }
        }

        $this->query = $this->conn->query($this->sql);
        return $this->query;

    }

    public function fetch($query) {
        return $query->fetch_assoc();
    }

    public function num_rows($query) {
        return $query->num_rows;
    }

}
?>

index.php

<?php
function __autoload($class){
  require('classes/' . strtolower($class) . '.class.php');
}
require('config.php');

$sql = new DatabaseConnection(DB_HOST, DB_USER, DB_PASS, DB_DTBS);
// The DB_xxxx constants are defined in config.php
?>
<!doctype html>

<meta charset="utf-8">
<title>OOP - Object Orientated Programming</title>

<?php
$data = array(1, "Brian o'Reilly");
$query = $sql->query("SELECT * FROM users WHERE id = %i AND name = %s", $data);
if ($sql->num_rows($query) > 0) {
    while ($r = $sql->fetch($query)) {
        echo '
User ' . $r['name'] . ' has ID ' . $r['id'] . '
';
    }
} else {
    echo "
No results
";
}
?>


texts:
Given the following definition for a NODE in a linked list:

struct NODE {
int data;
NODE* next;
};

I want a function to store the nodes with odd data to a given file (each line should contain a single integer number) [use c++ classes from ]

I wrote this code but there is some problems with the output .. Where is the wrong or what is the best solution for the question??

void storeOddElements(NODE *head, char *FileName)
{
    NODE *p = head;
    int count = 0;

    ofstream fp(FileName, ios::out);
    if(!fp.is_open()) return;

    while (p != NULL)
    {
        if ((p->data % 2) == 1)
            count++;
        p = p->next;

    }

    int odd_store[count], i=0;
    while (p !=NULL) {
        if ((p->data % 2) == 0)
            p = p->next;
        else
        {
            odd_store[i] = p->data;
            p = p->next;
            i++;
        }
    }

    int temp;
    for (int z = 0; z <= i-1; z++) {
        for (int j = i+1; j <= i; j++) {
            if (odd_store[z] <= odd_store[j]) {
                continue;
            }
            else
            {
                temp = odd_store[z];
                odd_store[z] = odd_store [j];
                odd_store[j] = temp;
            }
        }
    }
    for (int x = 0; x <= i; x++) {
        fp << odd_store[x] << endl;
    }
    fp.close();
}


texts: Reduce repetition when sharing data across an application

texts:
I have a CodeIgniter 3 application. There is some data every page across the application needs to have.

This is the system I currently have.

Create a model function that will get the data I need

Class General_model extends CI_Model
{
    function data_init()
    {
        $data['session'] = $this->session->userdata('session');
        $data['foobar'] = $this->general_model->get_foobar();
        return $data;
    }
}

In every controller, I call this data in the __construct()

function __construct()
{
    parent::__construct();
    $this->load->model('general_model', '', TRUE);
    $this->data = $this->general_model->data_init();
}

I begin every controller function by getting the data in the scope of the function, which then gets passed to the view

public function index()
{
    $data = $this->data;
    $data['page_title'] = 'example';
    $this->load->view('templates/header', $data);
    $this->load->view('page/example', $data);
    $this->load->view('templates/footer', $data);
}

I feel this is not ideal. It feels repetitive and not dry to have $this->data = $this->general_model->data_init(); in every constructor and $data = $this->data; in every function.

It feels like it'd be better if I could declare $this->data = $this->general_model->data_init(); once in the application and have $this->data available to every function in every controllers. I'd also like to avoid $data = $this->data; at the start of every function, but I'd rather do that than have the additional 7 characters $this-> hundreds of times across the codebase (perhaps that is me being lazy?).

I'm not sure how to improve either of those without breaking OOP and going global, or touching CodeIgniter core classes such as CI_Model.

Is there a way to improve how I'm sharing and moving this data?


texts: Best C# implementation of IndexOfAny(string, params string[])

texts:
Follow-Up question

.Net provides String.IndexOfAny(string, char[]) but not String.IndexOfAny(string, string[]).

The existing built-in String.IndexOfAny takes an array of char and returns the lowest position of any one char from the array in a passed in string or -1 if none are found. Essentially it is the char equivalent of my naive definition.

My extension takes a string to search s and an array of strings to find targets and returns the lowest position found of any member of targets in s or -1 if none are found.

A naive implementation (using LINQ) isn't particularly efficient:

public static int IndexOfAny1(this string s, params string[] targets) =>
    targets.Select(t => s.IndexOf(t)).Where(p => p >= 0).DefaultIfEmpty(-1).Min();

My improved implementation tracks the current candidate position and restricts future searches to be before that candidate position:

public static int IndexOfAny2(this string s, params string[] targets) {
    int? curAns = null;
    foreach (var target in targets) {
        var posAns = s.IndexOf(target, 0, curAns.HasValue ? curAns.Value + target.Length : s.Length);

        if (posAns >= 0 && (!curAns.HasValue || posAns < curAns)) {
            curAns = posAns;
            if (curAns == 0) // once you're at the beginning, can't be any less
                break;
        }
    }

    return curAns ?? -1;
}

This runs up to two times faster.

Sample code to test the two methods:

Console.WriteLine($"IndexOfAny1 should be 8: {"foo bar baz".IndexOfAny1("barz", "baz")}");
Console.WriteLine($"IndexOfAny1 should be 0: {"aabbccddeeffgghh".IndexOfAny1("bbb", "hh", "aa")}");
Console.WriteLine($"IndexOfAny2 should be 8: {"foo bar baz".IndexOfAny2("barz", "baz")}");
Console.WriteLine($"IndexOfAny2 should be 0: {"aabbccddeeffgghh".IndexOfAny2("bbb", "hh", "aa")}");

Is there a better algorithm or another way to make this faster?

PS Test harness for testing random possibilities:

var r = new Random();

var sb = new StringBuilder();
for (int j1 = 0; j1 < r.Next(80,160); ++j1)
    sb.Append((char)('0'+r.Next(0, 26+52)));
var s = sb.ToString();

var listTargets = new List<string>();
for (int j1 = 0; j1 < r.Next(5, 10); ++j1)
    if (r.NextDouble() < 0.8) {
        var tLen = r.Next(4, Math.Min(s.Length - 4, 10));
        var beginPos = r.Next(0, s.Length - tLen);
        listTargets.Add(s.Substring(beginPos, tLen));
    }
    else {
        sb.Clear();
        for (int j2 = 0; j2 < r.Next(5, 10); ++j2)
            sb.Append((char)('0'+r.Next(0, 26+52)));
        listTargets.Add(sb.ToString());
    }

var targets = listTargets.ToArray();
if (s.IndexOfAny1(targets) != s.IndexOfAny2(targets))
    Console.WriteLine($"Fail on {s} containing {String.Join(",", targets)}");


texts: Computing exponential function by Taylor Series without overflow

texts:
The original question is to write a Fortran program to compute the sum of the first 20 terms in the exponential equation (for x=1,2,3,4,5):
$$\sum_{n=0}^\infty \frac{x^n}{n!} = 1 + \frac{x^1}{1!} + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \frac{x^5}{5!} + \ldots$$

My original approach was:

PROGRAM Exponential_Function

IMPLICIT NONE

INTEGER :: x,n,i
REAL :: f=0.0,fact

! Print Header
PRINT *, "           x     Sum"

Do x = 1,5,1
    Do n = 0,19,1

        ! calculate factorial
        fact =1.0
        Do i=1,n,1
            fact = fact*i
        End Do

        f=f+(x**n)/(fact)
    END Do

    PRINT *, x, f
    f=0.0
End Do

END PROGRAM Exponential_Function

The code could run, but only displayed results up to x=3:

Then, I tried another approach:

IMPLICIT NONE

INTEGER :: x,n
REAL :: f=1.0,term=1.0

! Print Header
PRINT *, "           x     Sum"

Do x = 1,5,1
    Do n = 1,19,1
        term = term * (REAL(x)/REAL(n))
        f = f + term

    END Do

    PRINT *, x, f
    term = 1.0
    f = 1.0

End Do

and it gave the right results:

           x     Sum
           1     2.71828
           2     7.38906
           3     20.0855
           4     54.5982
           5     148.413

I wonder if the second solution is the only correct solution to this question?
Is there a way to rectify the first approach to avoid the arithmetic overflow problen in Fortran?


texts: Navigational bar content built depending on login state

texts:
I created a login service which holds a boolean based on if a user is logged in or not.

 angular.module('deafApp')

    .service('LoginService', function(){

        var $this = this;

        $this.loggedIn = false;

    });

Inside my login controller (LoginCtrl), I attach the LoginService to a local scope object and on the successful login callback function I turn the loggedIn value to true like so.

angular.module('deafApp')

.controller('LoginCtrl', ['Auth', '$scope', 'LoginService', function(Auth, $scope, LoginService) {

    $scope.Login = LoginService;

    $scope.loginUser = function() {

        Auth.$authWithPassword({
            email: $scope.email,
            password: $scope.password
        }).then(function(authData) {
            console.log("Logged in as:", authData.uid);
            /*
             WHERE I CHANGE THE VALUE TO TRUE
            */
            $scope.Login.loggedIn = true;
        }).catch(function(error) {
            console.error("Authentication failed:", error);
        });
    }

}]);

I wanted to change the navigation appearance based on a user logging in, so inside my navigation controller I've attached the LoginService to a local scope object again and created a function to return true or false like so.

angular.module('deafApp')

.controller('NavCtrl', [ 'LoginService',function(LoginService){
    var $this = this;

$this.Login = LoginService;

$this.isShowing = false;

$this.showToggle = function() {
    $this.isShowing = !$this.isShowing;
};

$this.goHome = function() {
    $this.isShowing = false;
};

 /*
    THIS FUNCTION RETURNS VALUE OF LOGGED IN
 */
    $this.userLoggedIn = function() {
        return $this.Login.loggedIn;
    }

$this.navLinks = [
    {name: 'About-us', ref:'about', title: 'About DeafandHoh Page'},
    {name: 'Facts', ref: 'facts', title: 'Facts & Deaf Empowerment Page'},
    {name: 'News', ref: 'news', title: 'News Page'},
    {name: 'Products', ref: 'products', title: 'Products Page'},
    {name: 'Directory', ref: 'directory', title: 'Directory Listings Page'},
    {name: 'Resources', ref: 'resources', title: 'Resources Page'},
    {name: 'Login / Register', ref: 'login', title: 'Login & Register Page', hide: 'nav.userLoggedIn()'},
    {name: 'Profile', ref: 'profile', title: 'User Profile Page', show: 'nav.userLoggedIn()'},
    {name: 'Chatroom', ref: 'chatroom', title: 'Come Chat!', show: 'nav.userLoggedIn()'},
    {name: 'Logout', ref: 'logout', title: 'Logout', show: 'nav.userLoggedIn()'}
];

}]);

I then attached it a hide and show property to several of the navLinks which get repeated that I want to either hide when truthy and show when truthy.

{name: 'Login / Register', ref: 'login', title: 'Login & Register Page', hide: 'nav.userLoggedIn()'},
{name: 'Profile', ref: 'profile', title: 'User Profile Page', show: 'nav.userLoggedIn()'},
{name: 'Chatroom', ref: 'chatroom', title: 'Come Chat!', show: 'nav.userLoggedIn()'},
{name: 'Logout', ref: 'login', title: 'Login & Register Page', show: 'nav.userLoggedIn()'}

The HTML looks like this:

Essentially, the purpose is for a login/register nav link to disappear when a user logs in and some more unique features in the navigation to appear for logged in users.


texts: JavaScript: Repeat a function X times at I intervals

texts:
I've written a general purpose repeat function which allows you to repeat a callback function X times separated by I intervals with the option to start immediately or after the interval. It can also default to just looping infinitely, which is what setInterval does. Is there a better approach, or any improvements people can provide? Make sure to comment out all but one of the examples :)

function repeatXI(callback, interval, repeat, immediate) {
    repeat = typeof repeat == 'undefined' ? -1 : repeat;
    interval = interval <= 0 ? 1000 : interval;
    immediate = typeof immediate == 'undefined' ? false : immediate;
    var offset = immediate ? 0 : 1;
    var id = null;
    if (repeat > 0) {
        for (var i = 0; i < repeat; i++) {
            id = setTimeout(callback, interval * (i + offset));
        }
    } else {
        id = setInterval(callback, interval);
    }
    return id;
}

// Example
var someFunc = function () {console.log(1);}

// Repeats forever, 1 second apart
repeatXI(someFunc, 1000);
// Repeats 10 times, 1 second apart, beginning after 1 second
repeatXI(someFunc, 1000, 10);
// Same as above, but beginning now
repeatXI(someFunc, 1000, 10, true);


texts: Playing a sound depending on the currently displayed flash card image

texts:
I've developed a fully working flash card app for kids. It has a UIImageView that cycles through 26 cards (abcs) via a gesture click and a music button that will play a sound for each image. Right now I have this 100% working, but the sound plays in an IF statement that has added an additional 400 lines of code.

How I load each card into the UIImageView from a gesture tap:

        // if the tapped view is a UIImageView then set it to imageview
        if (gesture.view as? UIImageView) != nil {
            if segControl.selectedSegmentIndex == 0 && segControl2.selectedSegmentIndex == 0 {
                imageView.image = UIImage(named: "card\(number)")
                number = number % 26 + 1
            }
            else if segControl.selectedSegmentIndex == 0 && segControl2.selectedSegmentIndex == 1 {
                imageView.image = UIImage(named: "upper\(number)")
                number = number % 26 + 1
            }

Music button:

    if (imageView.image?.isEqual(UIImage(named: "card1")))! {
        do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: aSound))
            audioPlayer.play()
        } catch {
            print("Couldn't load sound file")
        }
    }
    else if (imageView.image?.isEqual(UIImage(named: "card2")))! {
        do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: bSound))
            audioPlayer.play()
        } catch {
            print("Couldn't load sound file")
        }
    }
    else if (imageView.image?.isEqual(UIImage(named: "card3")))! {
        do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: cSound))
            audioPlayer.play()
        } catch {
            print("Couldn't load sound file")
        }
    }

I know I could set a sound array with the sound files in it, but how would I tie it back to the card? I can't set a tag property on an asset image, can I?

I'm looking for a way to shorten the current code I have.


texts:
This program forms the reducer of a Hadoop MapReduce job. It reads data in from stdin that is tab delimited.

foo    1
foo    1
bar    1

and outputs

foo    2
bar    1

Any suggestions for improvements?

(use '[clojure.string :only [split]])
(def reducer (atom {}))

(defn update-map [map key]
  (merge-with + map {key 1}))

(doseq [line (line-seq (java.io.BufferedReader. *in*))]
  (let [k (first (split line #"\t"))]
    (swap! reducer update-map k)))

(doseq [kv @reducer]
  (println (format "%s\t%s" (first kv) (second kv))))


texts: Skip invalid record and avoid execution break for invalid record

texts:
Here is the pseudo code used inside a Rails controller:

defined_hash_10000_records.each do |data|
    account = Account.where(account_identifier: params[:account_id]).first
    program = Program.where(program_identifier: data[:id]).first
    unless participant_account.present? || utility_program.present?
      # this is just a logger method defined in the second file.
      failure_msg('participant account is #{account.inspect} & utility program is #{program.inspect}')
      next
    end
    sub = Subscription.where(account_id: account.id, program_id: program.id)
end

It is working fine and I would like to know if it can be further improved.

Focus to improve the following line (conditions will help to bypass in case record not found instead of break the execution):

unless participant_account.present? || utility_program.present?
      # this is just a logger method defined in the second file.
      failure_msg('participant account is #{account.inspect} & utility program is #{program.inspect}')
      next
    end


texts: Pick what maintenance check required for game

texts:
I have a Python script that plays Airline Manager 2 (on Facebook) for me. So far it can depart flights and buy fuel when the price is good. I would like the program to also automatically plan maintenance for aircraft. The following code will only be run when a check is due (one of the four checks will have the value 0.)

When an A-Check is due (hours till A-Check == 0,) the A-Check must be performed. Same goes for other checks. The twist is this: B-Checks also cover A, C covers A & B, and a D-Check covers all other checks. If an A-Check is required, I would like a B-Check to be performed if the B would run out before the A is needed again. There is no point in doing a B-Check if 2 hours later a C-Check would need to be done. In that case I might as well just do a C-Check (which also covers the B-Check.)

Examples

A-Check required; B-Check has 600 hours before another check is required; perform an A-Check.
The above sentence can be written as A,B,C,D=0,600,2000,10000 -> A-Check (C & D-Checks are set to their maximum values so they don't affect the result.)
A-Check required; B-Check has 200 hours left; perform a B-Check (because the B-Check would need to be done in another 200 hours anyway, so the A-Check would be covered now, then in another 200 hours with the B-Check, wasting 300 hours of A-Check.)
The above sentence can be written as A,B,C,D=0,200,2000,10000 -> B-Check (C & D-Checks are set to their maximum values so they don't affect the result.)
A,B,C,D=200,0,1300,9500 -> B-Check, which also covers the A-Check
A,B,C,D=200,0,700,9500 -> C-Check, because the C-Check would need to be done before the next B-Check (if a B-Check was performed.)

Rules

A-Checks should be performed every 500 hours
B-Checks should be performed every 1,000 hours and also covers A-Checks
C-Checks should be performed every 2,000 hours and also covers both A-Checks and B-Checks
D-Checks should be performed every 10,000 hours and covers all other checks as well

The code I have currently (that works):

The program takes input of the current hours left on each check (a, b, c & d.) It prints output of what check should be performed (a, b, c & d.)

# Input (hours till each check)
a = 0
b = 590
c = 400
d = 9900

amax = 500
bmax = 1000
cmax = 2000
dmax = 10000

if a == 0:
    if d - amax < 0:
        print "d"
    elif c - amax < 0:
        print "c"
    elif b - amax < 0:
        print "b"
    else:
        print "a"

elif b == 0:
    if d - bmax < 0:
        print "d"
    elif c - bmax < 0:
        print "c"
    else:
        print "b"

elif c == 0:
    if d - cmax < 0:
        print "d"
    else:
        print "c"

elif d == 0:
    print "d"

There is a lot of repetition in this code. I'm looking for a simpler version that does not compromise on readability.


texts: PHP - Deliberate loose == check and assigning to if statement

texts:
if ($v->getMedical()) {
    $visitorHasMedical = $v->getMedical()->getMedCon() == true; // $visitorHasMedical will be false if "falsey" i.e. empty string or NULL
} else {
    $visitorHasMedical = false;
}

Where getMedical() is a OneToOne Doctrine relationship that might not exist.

Does this snippet read OK? Firstly, I'm deliberately doing a loose == check as this could be NULL or empty string.

Secondly, is assigning $visitorHasMedical to what is essential an if statement OK?


texts:
I have an m*n matrix where every element is unique. From a given starting point I have to move to the smallest point in a relative direction (e.g. up, down, left, right) and then have to repeat the process again. When all other surrounding points have a value that is greater than the existing one I have to stop and print the position from start. Suppose I have a 5x5 matrix:

1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

and starting point is (2,2) then the output will be 13,8,3,2,1.
I have solved this problem my way, but the problem is its complexity. I do not think my solution is efficient. Can anyone suggest to me a better solution?

N.B: Except scanner pkg, I am not allowed to import any other pkg. Here is my code:

import java.util.Arrays;
import java.util.Scanner;
public class DirectionArray {
public static void main(String [] args) {
        Scanner in = new Scanner(System.in);
        int row = in.nextInt();
        int col = in.nextInt();
        int[][] ara = new int[row][col];
        int[] ara2 = new int[4];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                ara[i][j] = in.nextInt();
            }
        }
        System.out.println("Give starting point(x) ");
        int x= in.nextInt();
        System.out.println("Give starting point(y) ");
        int y= in.nextInt();
        int sx=x;
        int sy =y;
        int [] fx={+1,-1,0,0};
        int [] fy={0,0,+1,-1};
        int p=0;
        int l=0;
        int v=0;
        int r=0;
        int [] result=new int[row*col] ;
        int min=ara[x][y];
        boolean swap=true;
        for(int i=0;i<(row*col)-1;i++) {
            for (int k = 0; k < 4; k++) {
                int nx = x + fx[k];
                int ny = y + fy[k];

                if (nx >= 0 && nx < row && ny >= 0 && ny < col) {
                    if (min > ara[nx][ny]) {

                        ara2[p] = ara[nx][ny];
                        p++;
                        // x = nx;
                        //y = ny;
                    }

                }

            }
            p=0;
            while(swap) {
                swap=false;
                r++;

                for (int q = 0; q < ara2.length-r; q++) {
                    if(ara2[q]>ara2[q+1]){
                    int temp = ara2[q];
                        ara2[q]=ara2[q+1];
                        ara2[q+1]=temp;
                        swap=true;
                    }
                }
            }
           // Arrays.sort(ara2);

                for(int j=0;j<ara2.length;j++) {
                    if(ara2[j]!=0)
                    {
                        v=ara2[j];
                        result[l]=v;
                        l++;
                        break;
                    }
                }
               // System.out.println(v);
                min=v;
            for(int o=0;o<ara2.length;o++) {
                ara2[o]=0;
            }
                for(int m=0;m<row;m++){
                    for(int n=0;n<col;n++){
                        if(ara[m][n]==v) {
                            x = m;
                            y = n;
                        }
                    }
                }

        }

        System.out.print(ara[sx][sy]+" ");
        for(int i=0;i<result.length;i++) {
            if(result[i]!=0) {
                System.out.print(result[i] + " ");
            }
            if(result[i]==0) {
                break;
            }
        }
    }
}


texts: Table of Tribonacci sequence using NumPy and PANDAS

texts:
What I am trying to accomplish is calculate the Tribonacci numbers and the ratio. I can do this in Excel easy like this.

So I tried do the same using Python 3 now.
It works and gives such output.

But would you be so kind to review the code and see what obvious mistakes you see in it and advise on what is a better approach as I do not want to continue coding if my logic to tackle such problem is fundamentally flawed somewhere.

Priorities for me are execution time and readability I guess

What would you have done differently and why?
I know it may look like a mess.
From what I heard using exec and eval (code as string) are the bad ideas and also that function calls are expensive?

I don't like my code at all especially how next() is used so many times but hopefully you can see how I was thinking trying to replicate the Excel spreadsheet

To run the code you need numpy and pandas

import pandas as pd
import numpy as np

column_names = ["Number sequence", "Ratio"]
column_counter = len(column_names) -1
header_columns = ['']
while column_counter >= 0:
    column_counter = column_counter - 1
    header_columns.append(column_names[column_counter])

tribonacci_numbers = [0,1]
tribonacci_counter = 19 #Reach
while tribonacci_counter -1 >= 0:
    tribonacci_counter = tribonacci_counter - 1
    tribonacci_numbers.append(sum(tribonacci_numbers[-3:]))
tribonaccis_list_length = len(tribonacci_numbers)-1

index_builder = 1
rows = []
while index_builder <= tribonaccis_list_length:
    try:
        index_builder = index_builder + 1
        rows.append((["Number: "+str(index_builder),tribonacci_numbers[index_builder],tribonacci_numbers[index_builder]/tribonacci_numbers[index_builder-1]]))
    except IndexError:
        continue

def get_row():
    the_row = [x for x in rows]
    row_counter = 0
    while row_counter <= len(the_row):
        try:
            row_counter = row_counter + 1
            yield (the_row[row_counter])
        except IndexError:
            continue

a = get_row()
def therow():
    for q in a:
        yield q

datas = np.array([
header_columns,
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow())])

df = pd.DataFrame(data=datas[1:,1:],index=datas[1:,0],columns=datas[0,1:])
print(df)

If you want to provide an example that does the same and produces a Pandas dataframe like this it would be very useful for me to study your code.


texts:
Just started out on Java and I would like to know your opinions on this calculator I made, took me 30 minutes so you can be rough.

import java.util.Scanner;
public class Java101 {

    public static void main(String[] args) {

        System.out.println(" Welcome to Java Calculator v0.1 \n");
        Scanner Scan = new Scanner(System.in);

        System.out.println("\n Please enter two numbers");
        int xe;
        int xo;
        System.out.print("\n First number: ");
        xe = Scan.nextInt();
        System.out.print("\n Second number: ");
        xo = Scan.nextInt();

        System.out.println("\n Select between (*,/,+,-)\n Type out the character in a single letter: ");
        String Operation = Scan.next();
        String EO = "You have selected ";

                switch (Operation) {

        case "*": System.out.println(EO + "* \n Your Result: "+( xe * xo )); break;
        case "/": System.out.println(EO + "/ \n Your Result: "+ ( xe / xo )); break;
        case "+": System.out.println(EO + "+ \n Your Result: "+ ( xe + xo ));break;
        case "-": System.out.println(EO + "- \n Your Result: "+( xe - xo )); break;
        default: System.out.println("\n Please select a valid character"); }

        //Close
        Scan.close();
        System.out.println(" Closing Application ");
    }
}


texts: Distributing points uniformly in a unit circle

texts:
I have been working on a code to distribute randomly generated points uniformly in a circle of radius 1 centered at origin. I have tried two variations of the code, yet they both yield one major problem.

Even for as many as 500 points, there is a particular region (quadrant 1, (0,1) on X Axis, and about (0,0.5) on Y axis) which is literally empty and it seems like that is a gaping hole in an otherwise perfectly well distributed points in the circle (the points seems to be distributed uniformly in the region outside this). The following are the two codes I tried out:

#include<iostream>
#include<random>
#include<time.h>
#include<fstream>
#define pi atan(1)*4
using namespace std;
int main()
{
    int N;  cin>>N;
    double X,Y,x,y,a,b;
    srand(time(NULL));
    for(int i=0; i<N; i++)
    {
        do
            {   X=(double)rand()/(double)RAND_MAX;
                Y=(double)rand()/(double)RAND_MAX;
                x=sqrt(X);
                y = 2*(pi)*Y;
                a=x*cos(y);
                b=x*sin(y);
            }while(((a*a)+(b*b))<=1);
    }
    return 0;
}

The second code is:

#include<iostream>
#include<random>
#include<time.h>
#include<fstream>
#define pi atan(1)*4
using namespace std;
int main()
{
    int N;  cin>>N;
    double X,Y,x,y,a,b;
    random_device R;
    mt19937 G(R());
    uniform_real_distribution<double> D(0,1);
    for(int i=0; i<N; i++)
    {
        do
            {
                X=D(G);     Y=D(G);     //uniform real distribution in (0,1)
                x=sqrt(X);
                y = 2*(pi)*Y;
                a=x*cos(y);
                b=x*sin(y);
            }while(((a*a)+(b*b))<=1);

    }
    return 0;
}

What is the possible reason for the problem I'm facing?

Update: For some reason, all points started getting generated at the boundary if I use ((aa)+(bb)<1) in the do-while loops. The problem I mentioned earlier has ((x * x)+(y * y)<1) which is clearly wrong, my bad.
I replaced the do-while of ((a * a)+(b * b)<1) with a goto as follows

A:
X=D(G);     Y=D(G);     //uniform real distribution in (0,1)
x=sqrt(X);
y = 2*(pi)*Y;
a=x*cos(y);
b=x*sin(y);
if((a*a)+(b*b)>1)
{  gota A:   }

and now it seems to be working fine. What could be the reason that goto makes it work but do-while does not?