texts: LRU cache design using dict and doubly linked list

texts:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

  get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
  set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

This problem can be easily solved by using collections.OrderedDict. But I'd like to do the practice by using dict and doubly linked list. Can anyone help me check the following code?

class LRUCache:
    # dictionary + doubly linked list
    class Node:
        def __init__(self, key, value):
            self.prev = None
            self.key = key
            self.value = value
            self.next = None

    # @param capacity, an integer
    def __init__(self, capacity):
        self.capacity, self.dict = capacity, {}
        self.head, self.tail = self.Node('head', 'head'), self.Node('tail', 'tail') # dummy head node and dummy tail node
        self.head.next = self.tail
        self.tail.prev = self.head

    # @return an integer
    def get(self, key):
        if key not in self.dict:
            return -1
        else:
            self.insertNodeAtFirst(self.unlinkNode(self.dict[key]))
            return self.dict[key].value

    # @param key, an integer
    # @param value, an integer
    # @return nothing
    def set(self, key, value):
        if key in self.dict:
            self.insertNodeAtFirst(self.unlinkNode(self.dict[key]))
            self.dict[key].value = value
        else:
            if len(self.dict) >= self.capacity: # remove the least recently used element
                del self.dict[self.unlinkNode(self.tail.prev).key]
            self.dict[key] = self.Node(key, value)
            self.insertNodeAtFirst(self.dict[key])

    def unlinkNode(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev
        node.prev = None
        node.next = None
        return node

    def insertNodeAtFirst(self, node):
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node


texts:
How does it look?  Comments, code correctness, etc.

//Function Prototypes
void buildArray(int anArray[]);

void printArray(int anArray[], int start, int end);
void sortArray(int start, int end, int masterArray[], int tempArray[]);
void mergeArray(int start, int split, int end, int masterArray[], int tempArray[]);

void bruteCount(int masterArray[]);

//Globals BAD, but gets the job done here
long long INVERSIONS_SORT = 0;
long long INVERSIONS_BRUTE = 0;
const int size = 100000;

void main() {
  int masterArray[size];
  int tempArray[size];

  buildArray(masterArray);

  bruteCount(masterArray);
  cout << "Inversion from Brute: " << INVERSIONS_BRUTE << endl;
  cin.get();

  sortArray(0, size - 1, masterArray, tempArray);
  cout << "Inversions from Sort: " << INVERSIONS_SORT << endl;

  cin.get();
}

//Builds an array from a txt file
void buildArray(int anArray[]) {
  ifstream dataFile;
  dataFile.open("integerArray.txt", ios::in);

  for (int i = 0; i < size; i++)
    dataFile >> anArray[i];
}

//Prints the entire array
void printArray(int anArray[], int start, int end) {
  for (int i = start; i <= end; i++)
    cout << anArray[i] << " ";

  cout << endl;
}

//Recursive function to split the array into sub arrays for merging
void sortArray(int start, int end, int masterArray[], int tempArray[]) {
  int split = (start + end) / 2;

  if (start < end) {
    sortArray(start, split, masterArray, tempArray);
    sortArray(split + 1, end, masterArray, tempArray);
    mergeArray(start, split, end, masterArray, tempArray);
  }

}

//Master function to marge two arrays into the correct order, and track the number of inversions
void mergeArray(int start, int split, int end, int masterArray[], int tempArray[]) {
  int leftCount = start; //Counter for left array
  int rightCount = split+1; //Counter for right array
  int tempCount = start; //Counter for temporary array

  while ((leftCount <= split) && (rightCount <= end)) { //When there are still values in both arrays
    if (masterArray[leftCount] <= masterArray[rightCount]) { //If value of left array is lower
      tempArray[tempCount] = masterArray[leftCount];
      leftCount++;
    }
    else {
      tempArray[tempCount] = masterArray[rightCount];  //If value of right array is lower
      INVERSIONS_SORT = INVERSIONS_SORT + (split + 1 - leftCount);  //If value of the right array is lower, add how many left array values are higher (number of inversions) and add to count
      rightCount++;
    }
    tempCount++;
  }

  //Cleanup when either array is done
  if (leftCount > split) {
    for (int i = rightCount; i <= end; i++) {
      tempArray[tempCount] = masterArray[i];
      tempCount++;
    }
  }
  else {
    for (int i = leftCount; i <= split; i++) {
      tempArray[tempCount] = masterArray[i];
      tempCount++;
    }
  }

  //Copy back into master array
  for (int i = start; i <= end; i++)
    masterArray[i] = tempArray[i];

}

//Counts the number of inversions via brute force, here to check to see if MergeSort method is working correctly
void bruteCount(int masterArray[]) {
  int i, j;

  for (i = 0; i < size-1; i++)
    for (j = i + 1; j < size; j++)
      if (masterArray[i] > masterArray[j])
        INVERSIONS_BRUTE++;
}


texts: Check if a given string can be a palindrome by altering some character without using a library function

texts:
I was asked in an interview to write code to check if a given string is a palindrome or can be a palindrome by altering some character without using library function.

My logic is to:

Compare 1st char with remaining chars. If it exists, remove both from array using removeElement().
If it does not exist in the char array, then use removeFirstElement() to remove the first element 1 time only.
chackPotentialPalindrom() returns true if a String can be a palindrome, otherwise false.

package package1;

import java.util.Scanner;

public class Palindrom {
    static int  temp=0;
    static char[] cArr;
        static boolean chackPotentialPalindrom(char[] cAr){
            cArr=cAr;
            if(cArr!=null){
                char current=cArr[0];
                for(int i=1;i<cArr.length;i++){
                    if(current==cArr[i]){
                        cArr=removeElement(i);
                        chackPotentialPalindrom(cArr);
                        break;
                    }
                    }
                if(cAr.length==2){
                if(cAr[0]==cAr[1]){
                    cArr=null;
                }}
                if(temp==0 && cArr!=null){
                    temp=1;
                    cArr=removeFirstElement(cArr);
                    chackPotentialPalindrom(cArr);
                    }
                }
            if(cArr==null){
                return true;
            }else{
                return false;
            }
        }
        static char[] removeFirstElement(char[] cAr){
            cArr=cAr;
            if(cArr!=null){
            if(cArr.length >1){
            char[] cArrnew=new char[cArr.length-1];
            for(int j=1,k=0;j<cArr.length;j++,k++){
                cArrnew[k]=cArr[j];
            }
            return cArrnew;
            } else {
                return null;
            }
                } else {
                    return null;
                }
        }
        static char[] removeElement(int i){
            if(cArr.length>2){
            char[] cArrnew=new char[cArr.length-2];
            for(int j=1,k=0;j<cArr.length;j++,k++){
                if(i!=j){
                    cArrnew[k]=cArr[j];
                }else{
                    k-=1;
                }
            }
            return cArrnew;}
            else{
                return null;
            }
        }
        public static void main(String[] args) {
            Scanner scn=new Scanner(System.in);
            while(true){
                temp=0;
            String s=scn.next();
            char[] arr=s.toCharArray();
            System.out.println(chackPotentialPalindrom(arr));
            }
        }
    }

Any tips to optimize this code?
I could not write this in an interview as they have given a pen and paper to code.
It took 3 hrs for me to write this. Can I be a developer?


texts:
I'm currently trying to process a corpus of a million patent text files, which contain about 10k non-unique words on average. My current data pipeline works as follows:

Load the patent texts as strings from a local sqlite database table
Tokenize¹ each document and save the results in a new table
Create a dictionary containing all unique words in the corpus
Train an tfidf model with the tokenized documents

¹Tokenization means taking a document text (string) as input and returning a list containing every word in the document (duplicates allowed). Words tend to be separated by spaces, special characters, numbers etc., the regex in my code has served quite well for this purpose.

In my data pipeline, I identified the tokenize function as my bottleneck, the relevant part is provided in my MWE below:

import re
import urllib.request
import time

url='https://raw.githubusercontent.com/mxw/grmr/master/src/finaltests/bible.txt'
doc=urllib.request.urlopen(url).read().decode('utf-8')

PAT_ALPHABETIC = re.compile(r'[^\W\d]+')

def tokenize(text):
    matches=PAT_ALPHABETIC.finditer(text)
    for match in matches:
        yield match.group()

def preprocessing(doc):
    tokens = [token for token in tokenize(doc)]
    return tokens

start_time = time.time()
preprocessing(doc)
print("--- %s seconds ---" % (time.time() - start_time))


texts:
I have two dates, example :

date1 = "4-02-2017".to_date
date2 = "4-02-2017".to_date + 29

I try to get array of date by each week with this :

(date1..date2).select{|x| Date::DAYNAMES[x.wday] == Date::DAYNAMES[date1.wday] }

Rersult :

[Sat, 04 Feb 2017,
 Sat, 11 Feb 2017,
 Sat, 18 Feb 2017,
 Sat, 25 Feb 2017,
 Sat, 04 Mar 2017]

Is there a better way to solve the case other than the way as above?


texts:
In what way can I improve this? Be that performance, readability, etc.
I'm thinking implementing NumPy would improve performance.
Usage: Calculate* the nth factorial of n 1s in a row.
*No need for a precise calculation. Magnitude and leading digits is enough.
Examples:
2nd factorial of 11. (11 x 9 x 7 x 5 x 3 x 1)
3rd factorial of 111. (111 x 108 x 105....)
...
import multiprocessing
import argparse
import datetime
import math

parser = argparse.ArgumentParser(
    formatter_class=argparse.HelpFormatter,
    description="Calcs x factorial",
    usage=""
)

parser.add_argument("-n", "--number", type=int)

args = parser.parse_args()

def first_n_digits(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

def getones():
    if args.number == 1 :
        print(1)
        exit()

    num = ""
    for _ in range(0, args.number) :
        num += "".join("1")
    return int(num)

def getlog(send_end, i, threads, num):
    inc = int(num/threads)
    inc -= int(inc%args.number)
    start = num-inc*i

    end = num-inc*(i+1) if i < threads-1 else 0

    output = 0
    for j in range(start, end, -args.number):
        if j > 0:
            output += math.log10(j)

    send_end.send(output)

def main():
    num = getones()
    threads = multiprocessing.cpu_count() if getones()/multiprocessing.cpu_count() > multiprocessing.cpu_count() else 1
    jobs = []
    pipe_list = []
    for i in range(threads):
        recv_end, send_end = multiprocessing.Pipe(False)
        p = multiprocessing.Process(target=getlog, args=(send_end, i, threads, num))
        jobs.append(p)
        pipe_list.append(recv_end)
        p.start()
    i = 0
    for proc in jobs:
        proc.join()
        i+=1
    result_list = [output.recv() for output in pipe_list]

    magnitude = int(sum(result_list))
    normalized = 10**(sum(result_list)-magnitude)

    fnd = str(first_n_digits(normalized, 3))
    print("{}.{}{}e{}".format(fnd[0], fnd[1], fnd[2], magnitude))

if __name__ == '__main__':
    start = datetime.datetime.now()
    main()
    end = datetime.datetime.now()
    print(end-start)
```


texts:
I've started learning Haskell by following along the CIS 194 Course from UPenn.
In the first lessons there is talk about wholemeal programming and certain ways idiomatic Haskell code looks like.
Now, I think that my style is still far away from being idiomatic and I don't think I've grasped what wholemeal means.
To see how far away, I'd like some comments on code from the third assignment because that's where I struggled most (until now).

So, how far away from being idiomatic is the code? How's efficiency?

Exercise 1: skips :: [a] -> [[a]]

The nth list in the output should contain every nth element from the input list.  For example, skips "hello!" == ["hello!", "el!", "l!", "l", "o", "!"].

skips :: [a] -> [[a]]
skips list =
  let pos 1 l = l
      pos i lst =
        let tmp = drop (i-1) lst
        in case tmp of
            [] -> []
            x:xs -> x : (pos i xs)
      tmpSkps i acc lst = if i == (length lst)+1
                          then acc
                          else tmpSkps (i+1) ((pos i lst):acc) lst
  in reverse (tmpSkps 1 [] list)


texts: Building an index of items from an iterable-of-tuples

texts:
Is there a more conventional / standard / easy-to-read way of building an index of tuples from an iterable than this:

# -----------------------------------------------------------------------------
def build_index(itable_tup):
    """
    Return an index for an iterable container of tuples, all the same length.
    The last element in each tuple is treated as the payload value
    that is to be indexed, and the preceeding elements as a hierarchy
    of indices by which it is to be indexed.
    The index itself is a nested default-dictionary with len(tup)
    levels of nesting, containing a list at the innermost level
    to hold the payload.
    >>> idx = build_index((('a','b', 1), ('a','c', 2)))
    >>> import json
    >>> print(json.dumps(idx, sort_keys=True))
    {"a": {"b": [1], "c": [2]}}
    This function is a bit of an exercise in making use of the
    functional programming capabilities that come with Python,
    so the  implementation is a little more terse and opaque
    than it might otherwise be...
    For each tuple in iter_tup, we construct a slot in the index
    using the lazy initialisation capability that is provided by
    the collections.defaultdict class. All but the last element
    in the tuple are used for indexing. The last element is the
    payload which gets added to the inner list after the structure
    has been initialised. The basic capability is provided by
    the nested defaultdict data structure returned from the idx_ctor
    function, which in turn is built with the aid of the higher
    order lambda function (_partial(_dedict, ctor)).
    All this is plugged together using calls to functools.reduce,
    which is used to construct the custom index data structure; to
    add each tuple to the index, as well as to iterate over the
    input.
    """
    _dedict   = collections.defaultdict
    _chain    = itertools.chain
    _repeat   = itertools.repeat
    _reduce   = functools.reduce
    _partial  = functools.partial
    _getitem  = operator.getitem

    # Peek ahead to determine the tuple length (& reconstitute the iterator).
    iter_tup  = iter(itable_tup)
    try:
        first_tup = iter_tup.__next__()
    except StopIteration:
        return {}
    idx_depth = len(first_tup) - 1
    iter_all  = _chain([first_tup], iter_tup)

    # Create a constructor for a custom index data structure.
    idx_ctor = _reduce(lambda ctor, _: _partial(_dedict, ctor),
                       _repeat(None, idx_depth), list)

    # This function adds a sigle tuple to the custom index data structure.
    def _add_tup_to_idx(idx, tup):
        """
        Add a sigle tuple to the custom index data structure.
        """
        _reduce(_getitem, tup[:-1], idx).append(tup[-1])
        return idx

    # This iterates over all tuples adding each to the index in turn.
    return _reduce(_add_tup_to_idx, iter_all, idx_ctor())


texts: Python script that make my .bash_aliases file MUCH more readable and clear

texts:
My .bash_aliases file contains several aliases.
In the beginning, when I wanted to see the aliases, I print the .bash_aliases file,
The output wasn't readable at all, so I created a python script to make it better.
To call my python script, I use the alias print_aliases_manual
What is the most pythonic way to write the following script?
Here is my python script:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

with open('/home/pi/.bash_aliases', 'r') as f:
    lines = f.readlines()

    for line in lines:
        if r'##' in line:
            print(f'{bcolors.HEADER}{bcolors.UNDERLINE}{bcolors.BOLD}{line}{bcolors.ENDC}')
        elif r'#' in line:
            print(f'{bcolors.WARNING}{line}{bcolors.ENDC}')
        elif r'alias' in line:
            drop_alias = line.replace('alias', '')
            new_line = drop_alias.replace('=', '   ')
            print(f'{bcolors.OKGREEN}{new_line}')
        else:
            print(f'{line}')

Here is my bash_aliases file:
### Aliases list divided by category:

## General commands:
alias cdd="cd /home/pi/Desktop/speedboat/"
alias dc="sudo docker-compose"
alias pm2="sudo pm2"

## Cellular related commands:
alias pc="ping -I wwan0 www.google.com"
alias qmi="sudo qmicli -d /dev/cdc-wdm0 -p"

## AWS relaeted commands:
alias dlogs="sudo docker logs -f iot_service"

## Git commands:
alias gp="sudo git pull"
alias gc="sudo git checkout"

## scripts to run when deleting speedboat directory is needed:

# copying files to Desktop
alias stodtop="sudo -E sh /home/pi/Desktop/speedboat/scripts/copy_files_to_desktop.sh"
# copying files from Desktop
alias sfromdtop="sudo -E sh /home/pi/Desktop/speedboat/scripts/copy_files_from_desktop_to_speedboat.sh"

## verifications test and updates scripts
# run speedboat verifications tests
alias sinsta="sudo sh /home/pi/Desktop/speedboat/scripts/installation_verification.sh"
# run local unittests
alias slocalt="sudo sh /home/pi/Desktop/speedboat/scripts/run_local_unittest.sh"
# pull os updates from git and execute
alias supdate="sudo sh /home/pi/Desktop/speedboat/scripts/updates-speedboat.sh"

## speedboat start and stop scripts (dockers and PM2)
alias startr="sudo sh /home/pi/Desktop/speedboat/scripts/start_speedboat.sh"

alias stopr="sudo sh /home/pi/Desktop/speedboat/scripts/stop_speedboat.sh"

## AWS related scripts:

alias secrl="sudo sh /home/pi/Desktop/speedboat/scripts/ecr-login.sh"

alias slog="sudo sh /home/pi/Desktop/speedboat/scripts/log_register.sh"

## Command to run speedboat aliases manual:
alias print_aliases_manual="python3 /home/pi/Desktop/speedboat/verification/test_verification_speedboat/colored_aliases_manual.py"


texts: Greasemonkey script for filtering out results from experteer.com

texts:
I've written a GM script to filter some results from Experteer.com results: specifically, many of the rows are "only for Premium members" and don't allow you to click through or see details, so I've written the script to hide those results from cluttering the display.

I'm very much a newbie to JavaScript and cobbled together this script after a lot of googling, so it's quite possibly horrific in several ways, please show me better ways in those cases.

The code follows with some notes on my reasoning:

// ==UserScript==
// @name        ExperteerNoPremium
// @namespace   abiteasier.in
// @description Removes the annoying "only for Premium members" rows from Experteer results
// @include     https://eu.experteer.com/goal/position/*
// @include     https://eu.experteer.com/search/jobs
// @version     0.3
// @grant       none
// ==/UserScript==

var remove_premium_rows = function () {
    var result_rows = document.body.querySelectorAll('.search-result-body');

    for (var i = 0; i < result_rows.length; i++) {
        var row = result_rows[i];

The two different pages included in @include above have the "only for premium" text in different columns, but they both have a td with class="search-result-job-action" which is in both cases two columns before the one we need, hence the selection and double nextElementSibling calls:

        var company_cell = row.querySelector('.search-result-job-action').nextElementSibling.nextElementSibling;

        var premium_only_re = /only\s+for\s+Premium\s+Members/i;
        if (premium_only_re.test(company_cell.textContent)) {
            row.style.display = 'none';
        }
    }
};

remove_premium_rows();

The results page also has a few Ajax controls which update the results table and I would like the pruning to happen on these new results as well. Since Mutation events seem to be discouraged by everyone, I went with a very hacky way of monkeypatching the function that does the Ajax updates itself, adding the remove_premium_rows as a callback:

unsafeWindow.ajaxUpdater = function () {
    new Ajax.Updater('result', '/desire/refine_matches',
            {asynchronous:true, evalScripts:true, method: 'get',
                parameters:Form.serialize($('matches')),
                onComplete: remove_premium_rows});
}

That's it, the code as above works for my purposes, but I would like to know in what it can be improved to adhere with standard practices.


texts: Time and Space Complexity of Prime factorization

texts:
I have written a function that prints all the prime factors for a given number. Here is my code

static void printPrimeFactorization(int number) {
    if (number <= 1 || isPrime(number)) { // If given number is already prime, no more factors for it
      System.out.println(number);
      return;
    }
    // check divisibility of given number starting from 2 to nextPrime(that is less than given number)
    for (int nextPrime = 2; nextPrime < number; nextPrime = getNextPrimeNumber(nextPrime)) {
      while (number % nextPrime == 0) { // check divisibility, until number is not divisible
        System.out.println(nextPrime);
        number = number / nextPrime;
        if (isPrime(number)) {
          System.out.println(number);
          return;
        }
      }
    }
  }

For brevity I am not writing the isPrime() and  getNextPrimeNumber() here

I am learning to calculate time complexity, and space complexity.
What is the exact time complexity of my code above starting from for loop having while loop in it

I guess Time complexity is O(log n) - Logarithmic time - as the total number of iterations is <= n/2 Correct me if my understanding is wrong
Space complexity is O(1) - constant time - As no extra space used other than simple variable assignments.

UPDATE:

static boolean isPrime(int number) {
    if (number == 0 || number == 1) {
      return false;
    }
    for (int i = 2; i <= Math.sqrt(number); i++) {
      if (number % i == 0) {
        return false;
      }
    }
    return true;
  }

static int getNextPrimeNumber(int number) {
    while (!isPrime(++number)) {
    }
    return number;
  }


texts: App.yaml configuration for Google App Engine

texts:
I wonder if the following configuration is correct and the handlers are in the right order:

application: myAppName
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /
  static_files: website/index.html
  upload: website/index.html

- url: /
  static_dir: website

Inside the website folder I have the following:

images_folder
favicon.ico
index.html

One more thing: do I need to handle favicon.ico separately like this:

- url: /favicon\.ico
  static_files: static/favicon.ico
  upload: static/favicon\.ico

or maybe:

- url: /favicon.ico
  static_files: static/favicon.ico
  upload: static/favicon.ico


texts:
I am busy creating a basic php mailer script to post to _self and email to a address.

Is the script secure?

How can I avoid someone clicking on submit the whole time, to spam the mailbox, with minimal extra code

<?php
//Mail header removal
function remove_headers($string) {
   $headers = array(
   "/to\:/i",
   "/from\:/i",
   "/bcc\:/i",
   "/cc\:/i",
   "/Content\-Transfer\-Encoding\:/i",
   "/Content\-Type\:/i",
   "/Mime\-Version\:/i"
 );
$string = preg_replace($headers, '', $string);
return strip_tags($string);
}

$to      = "email@tosendto.com";
$subject = "Sent from site";

$uname    = remove_headers($_POST['fname']);
$uemail   = remove_headers($_POST['femail']);
$umessage = remove_headers($_POST['fmessage']);
$umessage = "Name : " . $uname . " Email : " . $uemail . " Message : " . $umessage;

if(isset($_POST['submit']))
{
   mail($to, $subject, $umessage, "From: page@website.com");
}

?>

Message

  <form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">

Your Name:

<input type="text" size="20" name="fname">

Your Email:

<input type="text" size="20" name="femail">

Your Message:

<textarea name="fmessage" rows="4" cols="20"></textarea>

<input type="submit" name="submit" value="Send Message">
  </form>
  <?php if(isset($_POST['submit']))
  {
   echo "
Sent. We will be in contact shortly.
";
  } ?>


texts: AutoResetEventAsync, am I missing something?

texts:
So I wrote an asynchronous version of AutoResetEvent:

public sealed class AutoResetEventAsync {
    private readonly Task<bool> falseResult = Task.FromResult(false);
    private readonly ConcurrentQueue<Handler> handlers = new ConcurrentQueue<Handler>();
    private readonly Task<bool> trueResult = Task.FromResult(true);
    private int isSet;

    public AutoResetEventAsync(bool initialState) {
        this.isSet = initialState ? 1 : 0;
    }

    public void Set() {
        this.isSet = 1;

        Handler handler;

        // Notify first alive handler
        while (this.handlers.TryDequeue(out handler))
            if (handler.TryUnsubscribe()) {
                handler.Invoke();
                break;
            }
    }

    public Task<bool> WaitAsync() {
        return this.WaitAsync(CancellationToken.None);
    }

    public Task<bool> WaitAsync(TimeSpan timeout) {
        if (timeout == Timeout.InfiniteTimeSpan)
            return this.WaitAsync();

        var tokenSource = new CancellationTokenSource(timeout);
        return this.WaitAsync(tokenSource.Token);
    }

    public Task<bool> WaitAsync(CancellationToken cancellationToken) {
        // Short path
        if (this.TryReset())
            return this.trueResult;

        if (cancellationToken.IsCancellationRequested)
            return this.falseResult;

        // Wait for a signal
        var completionSource = new TaskCompletionSource<bool>(false);

        var handler = new Handler(() => {
            if (this.TryReset())
                completionSource.TrySetResult(true);
        });

        // Subscribe
        this.handlers.Enqueue(handler);

        if (this.TryReset()) {
            // Unsubscribe
            handler.TryUnsubscribe();
            return this.trueResult;
        }

        cancellationToken.Register(() => {
            // Try to unsubscribe, if success then the handler wasn't invoked so we could set false result,
            // else the handler was invoked and the result is already set.
            if (handler.TryUnsubscribe())
                completionSource.TrySetResult(false);
        });

        return completionSource.Task;
    }

    private bool TryReset() {
        return Interlocked.CompareExchange(ref this.isSet, 0, 1) == 1;
    }

    private sealed class Handler {
        private readonly Action handler;
        private int isAlive = 1;

        public Handler(Action handler) {
            this.handler = handler;
        }

        public void Invoke() {
            this.handler();
        }

        public bool TryUnsubscribe() {
            return Interlocked.CompareExchange(ref this.isAlive, 0, 1) == 1;
        }
    }
}

In my application it works well.

The question is: am I missing some concurrency issue?

I tested concurrent invocation of WaitAsync method, so, maybe you could suggest a better test scenario?


texts:
I am a C# developer, dont know much about vc++ or c++, never used it, for some reasons i have decided to use a c++ dll in my app for downloading content from the web.

I dont want to use WebClient.

I want it to download html content by providing Url of the resource, the dll will return the string response.

this is the code i have till now, source

#include <iostream>
#include <string>

#include <stdlib.h>
#include <winsock.h>//dont forget to add wsock32.lib to linker dependencies

using namespace std;

#define BUFFERSIZE 1024
void die_with_error(char *errorMessage);
void die_with_wserror(char *errorMessage);

int main(int argc, char *argv[])
{
    string request;
    string response;
    int resp_leng;

    char buffer[BUFFERSIZE];
    struct sockaddr_in serveraddr;
    int sock;

    WSADATA wsaData;
    char *ipaddress = "208.109.181.178";
    int port = 80;

    request+="GET /test.html HTTP/1.0\r\n";
    request+="Host: www.zedwood.com\r\n";
    request+="\r\n";

    //init winsock
    if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
        die_with_wserror("WSAStartup() failed");

    //open socket
    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        die_with_wserror("socket() failed");

    //connect
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family      = AF_INET;
    serveraddr.sin_addr.s_addr = inet_addr(ipaddress);
    serveraddr.sin_port        = htons((unsigned short) port);
    if (connect(sock, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0)
        die_with_wserror("connect() failed");

    //send request
    if (send(sock, request.c_str(), request.length(), 0) != request.length())
        die_with_wserror("send() sent a different number of bytes than expected");

    //get response
    response = "";
    resp_leng= BUFFERSIZE;
    while (resp_leng == BUFFERSIZE)
    {
        resp_leng= recv(sock, (char*)&buffer, BUFFERSIZE, 0);
        if (resp_leng>0)
            response+= string(buffer).substr(0,resp_leng);
        //note: download lag is not handled in this code
    }

    //display response
    cout << response << endl;

    //disconnect
    closesocket(sock);

    //cleanup
    WSACleanup();
    return 0;
}

void die_with_error(char *errorMessage)
{
    cerr << errorMessage << endl;
    exit(1);
}

void die_with_wserror(char *errorMessage)
{
    cerr << errorMessage << ": " << WSAGetLastError() << endl;
    exit(1);
}

The instructions with the code says, code will end an http download 'early' if the download is anything slower than instant.

Please suggest better code, or modifications, which can be perfect for use in a Fast Crawler.


texts:
I am setting different RadioGroup like this:

fragment.setT1RadioGroup((RadioGroup)fragView.findViewById(rowids[0]).findViewById(R.id.t1_radiogroup));
fragment.setT2RadioGroup((RadioGroup)fragView.findViewById(rowids[1]).findViewById(R.id.t1_radiogroup));
fragment.setT3RadioGroup((RadioGroup)fragView.findViewById(rowids[2]).findViewById(R.id.t1_radiogroup));
fragment.setT4RadioGroup((RadioGroup)fragView.findViewById(rowids[3]).findViewById(R.id.t1_radiogroup));
fragment.setT5RadioGroup((RadioGroup)fragView.findViewById(rowids[4]).findViewById(R.id.t1_radiogroup));
fragment.setT6RadioGroup((RadioGroup)fragView.findViewById(rowids[5]).findViewById(R.id.t1_radiogroup));
fragment.setT7RadioGroup((RadioGroup)fragView.findViewById(rowids[6]).findViewById(R.id.t1_radiogroup));
fragment.setT8RadioGroup((RadioGroup)fragView.findViewById(rowids[7]).findViewById(R.id.t1_radiogroup));
fragment.setT9RadioGroup((RadioGroup)fragView.findViewById(rowids[8]).findViewById(R.id.t1_radiogroup));
fragment.setT10RadioGroup((RadioGroup)fragView.findViewById(rowids[9]).findViewById(R.id.t1_radiogroup));

For refactoring purpose could I reduce the size of this code? How?


texts: JavaScript / Express error handling w/ promises

texts:
So I'm wondering how to properly handle errors in JavaScript when utilizing promises. I'm currently throwing errors for everything so that I can break out of the promise - if I can't find something, if there was a missing param, an operation failed, etc.

It seems wrong to be throwing an exception for everything like this, but this is the best thing I've come up with so far after much thought. I am sure to catch all of my thrown errors in the routes which passes them on to my middleware.

Is there a better way?

// SERVICE / MODEL LOGIC
getUserByEmail() {
  if (!this._model.email) {
    throw new VError('Missing email.');
  }

  return UserModel.findOne({ email: this._model.email }).exec()
    .then((result) => {
      if (!result) {
        throw new VError(errors.NOT_FOUND, 'Could not find user.');
      }

      return result;
    })
    .catch((error) => {
      throw new VError(error, 'Could not find user.');
    });
}

// ROUTE
router.get('/users/:email', (req, res, next) => {
  const model = new UserModel({ email: req.params.email });

  res.setHeader('Content-Type', 'application/json');
  return new UserService(model).getUserByEmail()
    .then(result => res.status(200).send(result))
    .catch(error => next(error));
});

// MIDDLEWARE
const errorHandling = (error, req, res, next) =>
  res.status(VError.info(error).status || 500).send(error.message);


texts: Refactoring this legacy application to a cleaner state (continued)

texts:
This is continued from here:

Refactor a legacy application to a less-unwieldy state

I am refactoring a legacy application. I DO NOT have the ability to change the Permissions, CustomerReport or the ListItems classes. They are in external dlls that are given to me. I realize that the ref usage is dumb and it makes NO SENSE. I am going to work with my peers to follow better practices.

This whole class looks ugly and mind you I have refactored some of it out into methods but it still is too large and unwieldy.

The code is used to return a TreeViewItem in VB. We are rewriting the front end into C# and I am using an API call to get the data from this service. So what I need is to hand the front end something reusable for every call to this report service.

I am mainly focused on cleaning up the AssembleNodes method, but any and all help is great.

public class ReportService : IReportService
{
    private readonly Permissions _permissions;

    public ReportService()
    {
        _permissions = new Permissions();
    }

    public IList<Node> GetFor(string userGroup)
    {
        var listItems = new List<ListItem>();
        //Yes this is silly since statusReturn is never used
        var statusReturn = _permissions.GetReportsForUserGroupName(userGroup, ref listItems);
        return AssembleNodes(listItems);
    }

    public IList<Node> GetFor(int userKey)
    {
        var listItems = new List<ListItem>();
        //Yes this is silly since statusReturn is never used
        var statusReturn = _permissions.GetReportsForUser(userKey, ref listItems);
        return AssembleNodes(listItems);
    }

    //I want to refactor this method down more
    private static List<Node> AssembleNodes(IList<ListItem> listItems)
    {
        var nodes = new List<Node>();
        if (!listItems.Any()) return nodes;
        var initialReportType = listItems[0].value;
        var initialCrs = listItems[0].key;
        var parent = AssembleNode(initialReportType);
        var child = AssembleNode(initialCrs, parent);
        foreach (var item in listItems)
        {
            var customerReport = (CustomerReport) item.dataObject;
            var grandChild = AssembleGrandChild(child, customerReport);
            if (item.value.Equals(initialReportType))
            {
                if (!item.key.Equals(initialCrs))
                {
                    initialCrs = item.key;
                    parent.Children.Add(child);
                    child = AssembleNode(item.key, parent);
                    child.Children.Add(grandChild);
                }
                    child.Children.Add(grandChild);
            }
            else
            {
                initialReportType = item.value;
                initialCrs = item.key;
                parent.Children.Add(child);
                nodes.Add(parent);
                parent = AssembleNode(item.value);
                child = AssembleNode(item.key, parent);
                grandChild = AssembleGrandChild(child, customerReport);
                child.Children.Add(grandChild);
            }
        }
        parent.Children.Add(child);
        nodes.Add(parent);
        return nodes;
    }

    private static Node AssembleNode(string value, Node parent = null)
    {
        return parent.IsNotNull() ?
            new Node(parent) { Text = value, Value = value } :
            new Node { Text = value, Value = value };
    }

    private static Node AssembleGrandChild(Node child, CustomerReport customerReport)
    {
        return new Node(child)
        {
            Text = customerReport.FileName,
            Value = customerReport.ReportKey.ToString(),
            Title = customerReport.Description
        };
    }
}

I really want to refactor this to a better state; any suggestions?


texts: A "map" function that alternates between two mapping functions

texts:
I am trying to solve following problem in Haskell using recursion:

  Define a recursive function funkyMap :: (a -> b) -> (a -> b) -> [a] -> [b] that takes as arguments two functions f and g and a list xs, and applies f to all elements at even positions [0, 2..] in xs and g to all elements at odd positions [1, 3..] in xs.

Example: funkyMap (+10) (+100) [1, 2, 3, 4, 5] = [(+10) 1, (+100) 2, (+10) 3, (+100) 4, (+10) 5].

I came up with following solution:

h1 p q [] = []
h1 p q ((cnt, val) : xs) = (if odd cnt then (q val) else (p val) ) : h1 p q xs

funkyMap f g xs = h1 f g ( zip [0..] xs)

If I try funkyMap (+10) (+100) [1, 2, 3, 4, 5] I get [11,102,13,104,15] which is expected.

Also funkyMap (+100) (+2) [1] gives [101]

and funkyMap (+100) (+2) [] gives []

Please review this solution and let me know your feedback.


texts: Finding the longest repeated substring in a string

texts:
After optimising my code it still seems pretty brute force and I am looking for ideas to fundamentally improve it.

I have tried improving performance by:

Avoiding creating substrings as much as possible - using while loop to compare string instead.
Intelligently anticipating ends ie. start + shift + max < str.length() - 1
use int instead of Integers

Is there anything obvious I have missed? I have found a few  alternatives solutions on the internet and would love to hear an opinion how they are different/better/worse to my implementation:

Princeton http://introcs.cs.princeton.edu/java/42sort/LRS.java.html
Boyer–Moore string search algorithm
Or any of the other string search implementations (the most notable can be found on wikipedia)

And before I forget this is my code:

 public static String findLongestRepeatedSubString(String str) {
    int max = 0;
    String result = "";
    for (int start = 0; start + max < str.length() - 1; start++) {
        for (int shift = 1; start + shift + max < str.length() - 1; shift++) {
                int length = 0;

                // While characters match count the length
                while(str.charAt(start + length) == str.charAt(start + shift + length) // matching characters
                        && start + shift + length < str.length() - 1){ // hasn't reached the end yet
                    length++;
                }

                // If the length is larger - update the new max size
                if (length > max ) {
                    max = length;
                    result = str.substring(start, start + length + 1);
                }
        }
    }

    return result;
}


texts: An idiom to use the same view function to create or edit an object?

texts:
Here is the skeleton of my (first!) Django app:

# models.py
class Task(models.Model):
    description = models.CharField(max_length = 200)
    ...

# forms.py
class AddTaskForm(forms.ModelForm):
    class Meta:
        model = Task

I then created two views using AddTaskForm: one to create a new instance, the other to edit an existing one.  I was able to refactor those two views (and the function they call) into one, but I'm not sure I got the best possible result...

# urls.py:
(r'^yata/add_task/$',              'yata.views.edit'),
(r'^yata/(?P<task_id>\d+)/edit/$', 'yata.views.edit'),

# views.py
def edit(request, task_id = None):
    t = get_object_or_404(Task, pk=task_id) if task_id else None
    if request.method == 'POST':
        form = AddTaskForm(request.POST, instance=t)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/yata/')
    else:
        form = AddTaskForm(instance = t)

    # Either the form was not valid, or we've just created it
    d = {'form': form}
    if task_id:
        # The template needs the id to decide if the form's action
        # is .../add_task or .../{{id}}/edit
        d['id'] = t.id
    return render_to_response('yata/edit.html', d,
        context_instance=RequestContext(request))

And here is the corresponding part of the template:

# edit.html
{% if id %}
    <form action="/yata/{{ id }}/edit/" method="post">
{% else %}
    <form action="/yata/add_task/" method="post">
{% endif %}
{{ form.as_p }}
<input type="submit" value="Save!" />
</form>

Is there a better Django idiom to handle this 'add or create' issue?
Or can this be considered a correct way?


texts:
How can I make the following checksum algorithm more pythonic and readable?

items = {1:'one', 2:'two', 3:'three'}
text = "foo" # This variable may change on runtime. Added to allow the execution
number = 1 # This variable may change on runtime. Added to allow the execution

string = text + items[number] + " " + "trailing"
if items[number] == "two": string=text
string = [ord(x) for x in string]
iterator = zip(string[1:], string)
checksum = string[0]
for counter, (x, y) in enumerate(iterator):
    if counter % 2:
        checksum += x
        checksum += 2 * y
    else:
        checksum += x * y
checksum %= 0x10000

print("Checksum:", checksum)

The thing called salt by everyone here is fixed and won't change ever. Also, the code is into a bigger function.

This code as-is must return this:

Checksum: 9167


texts:
I'm implementing the following function for signed integer numbers: given endpoints of a closed interval lo and hi, and inputs x (in [lo..hi]) and dx, I'd like to compute the "reflected sum":
if x + dx is still in [lo..hi] then that's it; otherwise the underhanging or overhanging portion is "folded back" onto the result (shown as y below). Basically, x is "bouncing around" in the interval.

                             overhang
                             /--\
                     dx
                 -------------->
--------[-------|-------|---]---|------
       lo       x       y   hi  x + dx
                        <---

Because this is for a hardware circuit, I am doing this using Clash's sized Signed integer type and width-extending addition, otherwise it is normal Haskell code.

My current implementation is the following:

bounce :: (KnownNat n, KnownNat k, (k + 1) <= n) => (Signed n, Signed n) -> Signed n -> Signed k -> (Signed n, Bool)
bounce (lo, hi) x dx
    | under > 0 = (lo + under, True)
    | over > 0 = (hi - over, True)
    | otherwise = (resize new, False)
  where
    new = add x dx
    under = resize $ resize lo - new
    over = resize $ new - resize hi

Things I don't like about this implementation:

There is a lot of noise about bit widths (all the resize calls)
Overall, it is not immediately obvious by just looking at the code what it does. It feels like it's doing a lot of seemingly ad-hoc arithmetic operations that "just happen" to work.

I am looking for improvements that come from the structure of the problem, not "oh you should rename x to theNumberThatIsBouncingAround because one-letter variable names bad".


texts: Promise-based fixed delay poller with timeout

texts:
I have the following functions for polling some function periodically with a timeout

export function promiseTimeout(ms: number): Promise<NodeJS.Timer> {
  return new Promise<NodeJS.Timer>((resolve) => {
    return setTimeout(resolve, ms);
  });
}

export function poll(predicate: () => boolean, delayMS: number, timeoutMS: number): Promise<void | NodeJS.Timer> {
  const fixedDelayPoller: Promise<void> = new Promise<void>(async (): Promise<void> => {
    while (!predicate()) {
      await promiseTimeout(delayMS);
    }
  });
  return Promise.race([promiseTimeout(timeoutMS), fixedDelayPoller]);
}

I'm new to Typescript and Promises so I'm curious if there is a more idiomatic or flexible way for this to be written.  For example, should there be parameters for a callback to be called after the timeout?  Or would that be handled by the caller calling poll(x, y, z).then(onFulfilled)?  Further, should this function return a boolean rather than a possible void, false in the case of timeout and true otherwise?


texts: Mean shift image processing algorithm for color segmentation

texts:
I'm implementing a version of the mean shift image processing algorithm for color segmentation in Python/NumPy.

I've written a pure NumPy version of the actual mean shifting per pixel (which I imagine is where the majority of time is taking). It slices an array of RGB values to work on out of the parent image, then creates lower bound and higher bound RGB reference arrays and generates a boolean masking array for the pixels to use for averaging then averages.

Any further optimizations? I suspect vectorizing the x/y for loops might give a speed up but for the life of me, but I haven't figured out how. (Some how generating an array of each pixel grid to work on and then generalizing the mean shift to take array input?) gL is grid length. gS is gL squared - the number of pixels in grid.

for itr in xrange(itrs):
    if itr != 0:
        img = imgNew
    for x in xrange(gL,height-gL):
        for y in xrange(gL,width-gL):
            cGrid = img[x-gSmp:(x+gSmp+1),y-gSmp:(y+gSmp+1)]
            cLow,cUp = np.empty((gL,gL,3)),np.empty((gL,gL,3))
            cLow[:] = [img[x,y][0]-tol,img[x,y][1]-tol,img[x,y][2]-tol]
            cUp[:] = [img[x,y][0]+tol,img[x,y][1]+tol,img[x,y][2]+tol]
            cBool = np.any(((cLow < cGrid) & (cUp > cGrid)),axis=2)
            imgNew[x,y] =  np.sum(cGrid[cBool],axis=0)/cBool.sum()


texts:
This actually belongs to a larger interview question. But here it is just the "tally up" part:

var i, a, tally = {}, arr = [1, 3, 7, 9, 3, 1, 6, 3, 3, 2, 11, 2];

for (i = 0; i < arr.length; i++) {
    a = arr[i];
    tally[a] = (tally[a] || 0) + 1;
}
console.log(tally);

I had some feeling the interviewers were not impressed or pleased (or maybe they didn't understand it), when I said I would use the line tally[a] = (tally[a] || 0) + 1; instead of using if... else or the ternary operator to do it.


texts:
I want to allow anyone that has never coded to make classes depending on my template with little to no knowledge of Python.

These classes need to do 2 things:

Inherit from other classes similar to them.
Contain variables, updating values if they have been changed or keeping them if not.

For the sake of simplicity I don't want to have super() on these new classes, as I'm trying to not frighten newcomers with things they can't understand yet. Here's how I did it:

class Template(object):

    def __init__(self):
        self.value = "hello"
        self.other_value = "bonjour"
        self.constant_value = 42
        current_class = self.__class__
        inits = []
        while (current_class.__name__ != "Template"):
            inits.append(current_class.init)
            current_class = current_class.__bases__[0]
        for i in reversed(inits):
            i(self)

    def init(self):
        pass

    def info(self):
        print self.value
        print self.other_value
        print self.constant_value
        print ""

class Deep(Template):
    def init(self):
        self.value = "howdy"
        self.other_value = "salut"

class Deeep(Deep):
    def init(self):
        self.value = "hi"

class Deeeep(Deeep):
    def init(self):
        self.value = "'sup"

very_deep = Deeeep()
not_so_deep = Deep()
very_deep.info()
not_so_deep.info()

This outputs :

sup
salut
42

howdy
salut
42

Which is exactly what I want, but it looks really weird, obfuscated and non-Pythonic. Any ideas for improvements?


texts:
I was working on a timer code in pure JavaScript and would like to know any pointers to improve:

Features

Start/ Stop/ Reset on click of a button.
Set limit to clock.
Update class name for warning and error based on threshold timer.

JSFiddle

function timer() {
  var time = {
    sec: 00,
    min: 00,
    hr: 00
  };
  var finalLimit = null,
    warnLimit = null,
    errorLimit = null;
  var max = 59;
  var interval = null;

  function init(_hr, _min, _sec) {
    time["hr"] = _hr ? _hr : 0;
    time["min"] = _min ? _min : 0;
    time["sec"] = _sec ? _sec : 0;
    printAll();
  }

  function setLimit(fLimit, wLimit, eLimit) {
    finalLimit = fLimit;
    warnLimit = wLimit;
    errorLimit = eLimit;
  }

  function printAll() {
    print("sec");
    print("min");
    print("hr");
  }

  function update(str) {
    time[str] ++;
    time[str] = time[str] % 60;
    if (time[str] == 0) {
      str == "sec" ? update("min") : update("hr");
    }
    print(str);
  }

  function print(str) {
    var _time = time[str].toString().length == 1 ? "0" + time[str] : time[str];
    document.getElementById("lbl" + str).innerHTML = _time;
  }

  function validateTimer() {
    var className = "";
    var secs = time.sec + (time.min * 60) + (time.hr * 60 * 60);
    if (secs >= finalLimit) {
      stopTimer();
    } else if (secs >= errorLimit) {
      className = "error";
    } else if (secs >= warnLimit) {
      className = "warn";
    }
    var element = document.getElementsByTagName("span");
    document.getElementById("lblsec").className = className;
  }

  function startTimer() {
    init();
    if (interval) stopTimer();
    interval = setInterval(function() {
      update("sec");
      validateTimer();
    }, 1000);
  }

  function stopTimer() {
    window.clearInterval(interval);
  }

  function resetInterval() {
    stopTimer();
    time["sec"] = time["min"] = time["hr"] = 0;
    printAll();
    startTimer();
  }

  return {
    'start': startTimer,
    'stop': stopTimer,
    'reset': resetInterval,
    'init': init,
    'setLimit': setLimit
  }
};

var time = new timer();

function initTimer() {
  time.init(0, 0, 0);
}

function startTimer() {
  time.start();
  time.setLimit(10, 5, 8);
}

function endTimer() {
  time.stop();
}

function resetTimer() {
  time.reset();
}
span {
  border: 1px solid gray;
  padding: 5px;
  border-radius: 4px;
  background: #fff;
}
.timer {
  padding: 2px;
  margin: 10px;
}
.main {
  background: #efefef;
  padding: 5px;
  width: 200px;
  text-align: center;
}
.btn {
  -webkit-border-radius: 6;
  -moz-border-radius: 6;
  border-radius: 6px;
  color: #ffffff;
  font-size: 14px;
  background: #2980b9;
  text-decoration: none;
  transition: 0.4s;
}
.btn:hover {
  background: #3cb0fd;
  text-decoration: none;
  transition: 0.4s;
}
.warn {
  background: yellow;
}
.error {
  background: red;
}

      00
    : 00
    : 00

  <button class="btn" onclick="startTimer()">Start</button>
  <button class="btn" onclick="endTimer()">Stop</button>
  <button class="btn" onclick="resetTimer()">Reset</button>


texts: Memoization for calculating minimal traversal distance within a positive matrix

texts:
The code below is for calculating the minimal traversing distance from the top left point of the matrix to the bottom right point of the matrix.

GitHub

Here is the core functionality. Please note that y is a global variable keeping track of the memoization.

def findLeastPath(matrix, row=0, column=0, path=[], sum_=0):
        row_max = matrix.shape[0]
        column_max = matrix.shape[1]

        if column == column_max - 1 and row == row_max - 1:
            y[row][column] = matrix[row][column]
            return matrix[row][column] + sum_
        else:
            current_cost = matrix[row][column]
            path.append((row, column, current_cost))
            if column == column_max - 1:
                if y[row+1][column] != 0:
                    y[row][column] = current_cost + y[row+1][column]
                    return current_cost + y[row+1][column]
                else:
                    down = findLeastPath(matrix, row + 1, column, path, sum_ + current_cost)
                    y[row][column] = current_cost + y[row+1][column]
                    return down
            elif row == row_max - 1:
                if y[row][column+1] != 0:
                    y[row][column] = current_cost + y[row][column + 1]
                    return current_cost + y[row][column + 1]
                else:
                    right = findLeastPath(matrix, row, column + 1, path, sum_ + current_cost)
                    y[row][column] = current_cost + y[row][column + 1]
                    return right
            else:
                if y[row][column + 1] != 0:
                    right = y[row][column + 1] + current_cost
                else:
                    findLeastPath(matrix, row, column + 1, path, sum_ + current_cost)
                    right = y[row][column + 1] + current_cost
                if y[row + 1][column] != 0:
                    down = y[row + 1][column] + current_cost
                else:
                    findLeastPath(matrix, row + 1, column, path, sum_ + current_cost)
                    down = y[row+1][column] + current_cost
                if y[row + 1][column + 1] != 0:
                    diagonal = y[row + 1][column + 1] + current_cost
                else:
                    findLeastPath(matrix, row + 1, column + 1, path, sum_ + current_cost)
                    diagonal = y[row+1][column+1] + current_cost

                min_val = min(right, down, diagonal)

                y[row][column] = min_val

                return min_val


texts:
I have three ways of reordering a list (think baseball order) and I am sure you can come up with more.  What is a the best way?

For example if input is list is 1,2,3,4 and current is 3 then the output should be 3,4,1,2.
Another example list: 1,2,3,4 and current 4 output is 4,1,2,3.

public void reOrder(List<String> list, String current) {

        if (list.size() > 1) {
            for (int i = 0; i < list.size(); i++) {
                String host = list.remove(0);
                if (host.equals(current)) {
                    list.add(0, host);
                    break;
                }
                list.add(host);

            }
        }
    }

   public void reOrder2(List<String> list, String current) {

        if (list.size() > 1) {
            int indexOfWorkingHost = list.indexOf(current);
            if (indexOfWorkingHost != -1) {
                for (int i = 0; i < indexOfWorkingHost; i++) {
                    list.add(list.remove(0));
                }
            }
        }
    }

public void reOrder3(List<String> list, String current) {

    if (list.size() > 1) {
        List<String> tmpServers = new ArrayList<String>();
        tmpServers.addAll(list);
        for (String host : tmpServers) {
            if (host.equals(current)) {
                break;
            }
            String first = list.remove(0);
            list.add(first);
        }
    }
}


texts: Sum of left and right nodes (individually) in a Binary Search Tree

texts:
I have written a program which calculates the sum of all the left nodes and the sum of right nodes in a Binary search tree.

I have used BFS to traverse the tree. The code is as follows:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class SumLeftRightNodes {

/**
 * This class represents the individual nodes of the binary tree
 * Each node has a left, right pointer of type Node
 * and Value to hold the value
 * @author Aneesh
 *
 */
static class Node {
    Node left;

    Node right;

    int value;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node value=" + value + "";
    }

}

/**
 * This function inserts an element into the binary tree
 * @param node
 * @param value
 */
public static void insert(Node node, int value) {
    if (value < node.value) {
        if (node.left != null) {
            insert(node.left, value);
        } else {
            System.out.println("  Inserted " + value + " to left of "
                    + node.value);
            node.left = new Node(value);
        }
    } else if (value > node.value) {
        if (node.right != null) {
            insert(node.right, value);
        } else {
            System.out.println("  Inserted " + value + " to right of "
                    + node.value);
            node.right = new Node(value);
        }
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Node root = new Node(5);
    System.out.println("Binary Tree Example");
    System.out.println("Building tree with root value " + root.value);
    insert(root, 1);
    insert(root, 8);
    insert(root,-2);
    insert(root, 6);
    insert(root, 3);
    insert(root, 9);
    insert(root,-3);
    insert(root,-1);

    System.out.println("sum of all left and right nodes is as follows\n");
    sumOfLeftandRightNodes(root);
}

public static void sumOfLeftandRightNodes(Node root) {
    // TODO Auto-generated method stub
    long leftSum = 0, rightSum = 0;

    Queue<Node> nodes = new LinkedList<Node>();

    //add the root to the Queue
    nodes.add(root);

    List<Node> leftNodes = new ArrayList<Node>() , rightNodes = new ArrayList<Node>();

    while (!nodes.isEmpty()){

        //BFS traversal
        Node temp = nodes.poll();

        //if left child is present then add the value of the node to the left Count
        if (temp.left!=null){
            leftSum += temp.left.value;
            leftNodes.add(temp.left);
            nodes.add(temp.left);
        }
        //if right child is present then add the value of the node to the right Count
        if (temp.right!=null){
            rightSum += temp.right.value;
            nodes.add(temp.right);
            rightNodes.add(temp.right);
        }
    }

    System.out.println("left = "+leftNodes+" \nRight Nodes = "+rightNodes);
    System.out.println("left sum ="+leftSum+"\nRight sum="+rightSum);
}

}

Any suggestion and improvements are welcome. If there is an easier method to this problem then I would like to know.


texts: Building tree from edges puzzle with performance requirement

texts:
I'm working on a puzzle and have solved it, but my code is not fast enough to get the maximum score (if the code is faster than a certain achievable threshold, one gets awarded the maximum score). I have tried multiple approaches but it seems I can't figure it out. My Java code is appended at the end.

The puzzle is as follows: Input is a number >= 1 of lines of two integers separated by a space which represent edges in a graph. This graph is a tree with 0 as root. We have to calculate the "value" of the graph defined as:
Each node initially has value 1. If a node has children, they each increase its value by their value +1. The final value of a node it its new value + values of all it's children. So:

node value =  1 + (# of children) + (sum of children's values).

The value of the graph is the sum of values of its nodes.
Then print the value modulo 1234567.

Examples:

0 1
2 1
2 3

has value 16.

1 0
2 0
1 3
1 4

has value 17.

Here's my code, if someone has any idea where I'm being inefficient, thanks for the help!

public static void main (String[] args) {

    Scanner stdin = new Scanner(System.in);
    Stack<Tuple> allNodes = new Stack<>();
    List<Integer> input = new ArrayList<>();

    //add all input to input list
    while (stdin.hasNext()) {
        input.add(stdin.nextInt());
    }

    allNodes.push(new Tuple(0, -1));
    int index, childIndex, child, parent, iterator = 0;

    //search input for known nodes from parents and add them to allNodes
    while (input.size() > 0) {
        parent = allNodes.get(iterator++).id;
        while ((index = input.indexOf(parent)) >= 0) {
            //check whether index is even or odd
            childIndex = (index%2 == 0) ? index+1 : index-1;
            child = input.get(childIndex);

            allNodes.push(new Tuple(child, parent));

            input.remove(index);
            if (index > childIndex) { input.remove(childIndex); }
            else { input.remove(index); }
        }
    }

    int[] values = new int[allNodes.size()];
    Tuple currentNode;

    //compute values
    while (allNodes.size() > 1) {
        currentNode = allNodes.pop();
        values[currentNode.parent] += ++values[currentNode.id]+1;
    }
    values[0]++;

    int sum = 0;
    for (int i=0; i<values.length; i++) {
        sum += values[i];
    }

    System.out.println(sum%1234567);
    stdin.close();
}

public static class Tuple {

    int id;
    int parent;

    public Tuple (int id, int parent) {
        this.id = id;
        this.parent = parent;
    }
}


texts: Return lambda expression based on parameters

texts:
This function returns a lambda expression based on the parameters sent. I am sure there is a better way to do this.

    [NonAction]
    private Expression<Func<ScheduleItemDto, bool>> Where(Guid siteGuid, Guid? eventGuid, MonthOfYear month, int year, bool? closed)
    {
        Expression<Func<ScheduleItemDto, bool>> notAdminExpression = x => x.Active == true;
        Expression<Func<ScheduleItemDto, bool>> baseExpression = x => x.SiteGuid == siteGuid && x.Date.Month == (int)month + 1 && x.Date.Year == year;
        Expression<Func<ScheduleItemDto, bool>> eventExpression = x => x.EventGuid == eventGuid;
        Expression<Func<ScheduleItemDto, bool>> closedExpression = x => x.Closed != null;
        Expression<Func<ScheduleItemDto, bool>> notClosedExpression = x => x.Closed == null;
        Expression<Func<ScheduleItemDto, bool>> resultExpression = x => true;

        switch (closed)
        {
            case null:
                if (eventGuid == null)
                {
                    resultExpression = baseExpression;
                }
                else
                {
                    resultExpression = Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, eventExpression.Body), baseExpression.Parameters[0]);
                }
                break;

            case true:
                if (eventGuid == null)
                {
                    resultExpression = Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, closedExpression.Body), baseExpression.Parameters[0]);
                }
                else
                {
                    Expression<Func<ScheduleItemDto, bool>> exp = Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, closedExpression.Body), baseExpression.Parameters[0]);
                    resultExpression = Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(exp.Body, eventExpression.Body), exp.Parameters[0]);
                }
                break;

            case false:
                if (eventGuid == null)
                {
                    resultExpression = Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, notClosedExpression.Body), baseExpression.Parameters[0]);
                }
                else
                {
                    Expression<Func<ScheduleItemDto, bool>> exp = Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, notClosedExpression.Body), baseExpression.Parameters[0]);
                    resultExpression = Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(exp.Body, eventExpression.Body), exp.Parameters[0]);
                }
                break;
        }

        if (!AccessControl.HasAccess(Permissions.DashboardAdministrator))
        {
            return Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(resultExpression.Body, notAdminExpression.Body), resultExpression.Parameters[0]);
        }

        return resultExpression;
    }


texts:
The fourth project, continuing my C++ saga with terrible post names. :P

  An approximate value of pi can be calculated using the series given
  below:

  $$ \pi \approx 4 \left[ 1 - \dfrac{1}{3} + \dfrac{1}{5} - \dfrac{1}{7} +
 \dfrac{1}{9} - \cdots + \dfrac{\left( -1\right)^n}{2n + 1} \right] $$

  Write a C++ program to calculate the approximate value of pi using
  this series.  The program takes an input \$ n \$ that determines the
  number of terms in the approximation of the value of pi and outputs
  the approximation.  Include a loop that allows the user to repeat this
  calculation for new values \$ n \$ until the user says she or he wants
  to end the program.

Also, I am required to use a for loop at least once in my code.

pi.cpp:

/**
 * @file pi.cpp
 * @brief Calculates pi for the given number of terms
 * @author syb0rg
 * @date 10/3/14
 */

#include <iostream>
#include <limits>
#include <cctype>
#include <cmath>

/**
 * Makes sure data isn't malicious, and signals user to re-enter proper data if invalid
 */
void getSanitizedDouble(long double &input)
{
    while (!(input = std::cin.peek()) && input != '\n')
    {
        if (std::isalpha(input) || std::isspace(input)) std::cin.ignore(); // ignore alphabetic and space characters from input
    }
    while(!(std::cin >> input) || input < 0)
    {
        std::cin.clear(); // clear the error flag that was set so that future I/O operations will work correctly
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skips to the next newline
        std::cout << "Invalid input.  Please enter a positive number: ";
    }
}

int main()
{
    long double num = 0.;
    char again = '\0';
    do
    {
        long double pi = 0.;

        // get input for height, re-read input if not a positive number
        std::cout << "Enter the number of terms to approximate π: ";
        getSanitizedDouble(num);

        for(auto i = 0; i < num; i++)
        {
            pi += std::pow(-1, i) / (2 * i + 1);
        }
        pi *= 4;

        std::fprintf(stdout, "Approximated value of π for %Lg terms: %Lg\n", num, pi);

        std::cout << "Run the program again (y/N): ";  // signify n as default with capital letter
        std::cin.get();  // absorb newline character from previous input
        std::cin.get(again);
        again = std::tolower(again);
    } while (again == 'y');
}


texts: Scanning directories and caching paths to an array

texts:
What am I trying to do

I'm trying to scan a disk and save (cache) all the paths of files and directories into an array so that I could perform a quick file/directory search later on.

Implementation

I'm using a Node.js module called walkdir.

cacheDisk () {
  let searchDir = 'C:/'
  let cache = []

  let options = {
    "max_depth": 5,       // only recurse down to max_depth. if you need more than no_recurse
    "track_inodes": true  // should be used with max_depth to prevent infinite loop. On windows or with hardlinks some files are not emitted due to inode collision.
  }

  let paths = walkdir(searchDir, options, (path) => {
    cache.push(path)
  })
  .on('end', () => {
    console.log(cache)
    this.findItem(cache)
  })
},

findItem (cache) {
  let filename = 'file_1.txt'
  const matches = cache.filter(element => element.includes(filename))
  console.log(matches)
}

Questions / Problems:

FYI: I only need it to work in the latest Chrome (it's an Electron app)

Is using cache.push(path) a good way (performance-wise) to save paths to the array or is the module already doing it for me and I'm just repeating this action on every iteration? It takes about 30 seconds and 500-800 MB of RAM on a core i7 to finish that caching operation for my ssd with 1 million paths

Is using cache.filter(element => element.includes(filename)) a good / safe way to find an element in an array that can potentially be ~10,000,000 paths in length?

When I'm trying to scan disk's root (e.g. C:/) I get 2 slashes after the disk letter in every path (e.g. C:\\Program Files\test). But when I'm scanning something like C:/test/ everything is fine. I guess that's Node's doing? How do I avoid that? (do I just replace all \\ with \ in all the paths afterwards?)


texts:
Given a binary tree, return the sum of values of its deepest leaves.

  Constraints:

  The number of nodes in the tree is between 1 and 10^4. The value of
  nodes is between 1 and 100.

Please review for performance and style

using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/deepest-leaves-sum/
    /// </summary>

    [TestClass]
    public class DeepestLeavesSumTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            var root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.left.left = new TreeNode(4);
            root.left.right = new TreeNode(5);
            root.left.left.left = new TreeNode(7);
            root.right = new TreeNode(3);
            root.right.right = new TreeNode(6);
            root.right.right.right = new TreeNode(8);
            DeepestLeavesSumClass deepest = new DeepestLeavesSumClass();
            Assert.AreEqual(15, deepest.DeepestLeavesSum(root));
        }
    }

    public class DeepestLeavesSumClass
    {

        int maxDepth = 0;
        int sum = 0;
        public int DeepestLeavesSum(TreeNode root)
        {
            if (root == null)
            {
                return 0;
            }
            DFS(root, 0);
            return sum;
        }

        private void DFS(TreeNode root, int depth)
        {
            if (root == null)
            {
                return;
            }
            if (maxDepth < depth + 1)
            {
                maxDepth = depth + 1;
                sum = root.val;
            }
            else if (depth + 1 == maxDepth)
            {
                sum += root.val;
            }
            DFS(root.left, depth + 1);
            DFS(root.right, depth + 1);
        }
    }

}


texts:
Is there a way to improve this SQL query?  It involves multiple cross join and joins.

I have 3 tables, and I want to compute the cardinal product:

table N:
    N
    -
    4

table sums:
    i   S
    -----------
    1   22
    2   26
    3   22

table mults:
    i   j   M
    -------------------
    1   1   122
    1   2   144
    1   3   119
    2   1   144
    2   2   170
    2   3   141
    3   1   119
    3   2   141
    3   3   126

Here is a fiddle.

SELECT  ((N.n*M1.m)-(S1.s*S2.s)) / (SQRT((N.n*M2.m)-(pow(S1.s,2))) * SQRT((N.n*M3.m)-(pow(S2.s,2))))
FROM N
CROSS JOIN sums as S1
CROSS JOIN sums as S2
JOIN mults as M1
     ON M1.i = S1.i
     AND M1.j = S2.i
JOIN mults as M2
     ON M2.i = S1.i
     AND M2.j = S1.i
JOIN mults as M3
     ON M3.i = S2.i
     AND M3.j = S2.i;


texts: Block same instance of a program for running again

texts:
I am implementing a library (Linux) and I created some functions to block new instances of a running program and I was wonder if there are some better improvements for it.

Here is a program which describes what I am trying:

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

#define SECONDS 20

static char *program_path = NULL;

char *my_strtok         ( char *const msg, const char *const ch );
void block_new_instance ( const char *const instance );
void clean_instance     ( void );

int main ( int argc, char *argv[] )
{
    if ( argc != 1 )
    {
        printf( "\n\t*** Arguments are NOT allowed. ***\n" );
        exit( EXIT_FAILURE );
    }

    block_new_instance( argv[ 0 ]  );
    sleep( SECONDS );
}

void block_new_instance( const char *const instance )
{
    char prog_name[ strlen( instance ) + 1 ];
    memset( prog_name, '\0', sizeof( prog_name ) );
    strcpy( prog_name, instance );
    char *buffer = my_strtok( prog_name, "/" );
    struct flock file_lock;
    char *dir = getenv( "HOME" );

    if ( dir == NULL || dir[0] != '/' )
    {
        fprintf( stderr, "Wrong Directory, getenv(): %s (%d)\n", strerror( errno ), errno );
        exit( EXIT_FAILURE );
    }

    program_path = calloc( sizeof ( *program_path ), strlen( dir ) + ( strlen( buffer )  + sizeof ( "/" ) ) );
    if ( program_path == NULL )
    {
        printf( "Error, malloc()\n" );
        exit ( EXIT_FAILURE );
    }

    memcpy( program_path, dir, strlen( dir ) );
    memcpy( program_path + strlen( dir ), "/", sizeof( "/") );
    memcpy( program_path + ( strlen( dir ) + strlen( "/" ) ), buffer, strlen( buffer ) );

    int file_desk = open( program_path, O_RDWR | O_CREAT, 0600 );
    if ( file_desk < 0 )
    {
        fprintf( stderr, "open: %s (%d)\n", strerror( errno ), errno );
        exit( EXIT_FAILURE );
    }

    file_lock.l_start   = 0;
    file_lock.l_len     = 0;
    file_lock.l_type    = F_WRLCK;
    file_lock.l_whence  = SEEK_SET;

    if ( fcntl( file_desk, F_SETLK, &file_lock ) < 0 )
    {
        fprintf( stderr, "%s is already running\n", buffer );
        exit( EXIT_FAILURE );
    }
    atexit( clean_instance );
}

char *my_strtok( char *const msg, const char *const ch )
{
    char *ret = NULL;
    char *tmp = strtok( msg, ch );
    while ( tmp != NULL )
    {
        ret = tmp;
        tmp = strtok( NULL, ch );
    }

    if ( ret == NULL )
    {
        return NULL;
    }
    return ret;
}

void clean_instance( void )
{
    unlink ( program_path );
    free   ( program_path );
}

Possible Outputs are:

  *** Arguments are NOT allowed. **

or:

  Program is already running

I would like to know which improvements are needed?


texts: CSV parsing program that creates distinct header rows with transaction rows underneath

texts:
My code reads in the data using DictReader, then creates a header row that contains my composite key (PEOPLE_ID, DON_DATE), and then adds various values that are distinct to each section.  The output looks like this:

-01- PEOPLE_ID, DON_DATE, etc...
-02- dataline
-02- dataline
-01- ...
etc...

I'm looking to possibly simplify or streamline this code, and then could use advice on how to implement robust error-handling throughout.  Here is my program:

#!/usr/bin/python
# pre_process.py
import csv
import sys

def main():
    infile = sys.argv[1]
    outfile = sys.argv[2]
    with open(infile, 'rbU') as in_obj:
        reader, fieldnames = open_reader(in_obj)
        reader = sorted(reader, key=lambda key: (key['PEOPLE_ID'],
                                                 key['DON_DATE']))
        header_list = create_header_list(reader)
        master_dict = mapData(header_list, reader)
        writeData(master_dict, outfile, fieldnames)

def open_reader(file_obj):
    reader = csv.DictReader(file_obj, delimiter=',')
    return reader, reader.fieldnames

def create_header_list(dict_obj):
    p_id_list = []
    for row in dict_obj:
        if (row['PEOPLE_ID'], row['DON_DATE']) not in p_id_list:
            p_id_list.append((row['PEOPLE_ID'], row['DON_DATE']))
    return p_id_list

def mapData(header_list, dict_obj):
    master_dict = {}
    client_section_list = []
    for element in header_list:
        for row in dict_obj:
            if (row['PEOPLE_ID'], row['DON_DATE']) == element:
                client_section_list.append(row)
        element = list(element)
        element_list = [client_section_list[0]['DEDUCT_AMT'],
                    client_section_list[0]['ND_AMT'],
                    client_section_list[0]['DEDUCT_YTD'],
                    client_section_list[0]['NONDEDUCT_YTD']
                    ]
        try:
            element_list.append((float(client_section_list[0]['DEDUCT_YTD']) +
                                 float(client_section_list[0]['NONDEDUCT_YTD'])
                                 ))
        except ValueError:
            pass

        element.extend(element_list)
        element = tuple(element)
        master_dict[element] = client_section_list
        client_section_list = []
    return master_dict

def writeData(in_obj, outfile, in_fieldnames):
    with open(outfile, 'wb') as writer_outfile:
        writer = csv.writer(writer_outfile, delimiter=',')
        dict_writer = csv.DictWriter(writer_outfile,
                                     fieldnames=in_fieldnames,
                                     extrasaction='ignore')

        for k, v in in_obj.iteritems():
            writer_outfile.write(' -01- ')
            writer.writerow(k)
            for i, e in enumerate(v):
                writer_outfile.write(' -02- ')
                dict_writer.writerow(e)

def getReconTotals(infile):
    pass

if __name__ == '__main__':
    main()


texts: Long-to-string and string-to-long while checking characters within a xlate table

texts:
I am attempting to come up with a better method for doing this:
public static String longToPlayerName(long name) {
    int i = 0;
    char[] nameCharacters = new char[12];
    while (name != 0L) {
        long ll = name;
        name /= 37L;
        nameCharacters[11 - i++] = playerNameXlateTable[(int) (ll - (name * 37L))];
    }
    return new String(nameCharacters, 12 - i, i);
}

public static long playerNameToInt64(String s) {
    long l = 0L;
    for (int i = 0; (i < s.length()) && (i < 12); i++) {
        final char c = s.charAt(i);
        l *= 37L;
        if ((c >= 'A') && (c <= 'Z')) {
            l += (1 + c) - 65;
        } else if ((c >= 'a') && (c <= 'z')) {
            l += (1 + c) - 97;
        } else if ((c >= '0') && (c <= '9')) {
            l += (27 + c) - 48;
        }
    }
    while (((l % 37L) == 0L) && (l != 0L)) {
        l /= 37L;
    }
    return l;
}

I can't seem to come up with a better way. Any ideas would be excellent!


texts: Retry storing HTTP response into a variable until specific code

texts:
I want to keep trying to get response until its code is 200 or unknown yet. In first case it should be stored in response variable. In another case I should raise any kind of exception.

  response = nil
  1.times do
    response = begin
      http.request request
    rescue Net::ReadTimeout
      puts "Net::ReadTimeout"
      retry
    end
    case response.code
    when "503"
      puts "servers are busy at #{Time.now}?"
      sleep 5
      redo
    when "200"
      "ok"
    else
      fail "#{response.code} at '#{request.path}'"
    end
  end

The 1.times thing is taken from SO.


texts:
I had to write a program that would complete an arithmetic progression based on the users input. The user would provide the third term in the series, the third from the last term, and the sum of all the terms in the series. The program would display the total number of terms are in the series and then the series itself. I already submitted it but I am hoping to get some general feedback.

Example: 3, 8, 55

Program output:

10

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

#include <iostream>
#include <vector>

int main() {
    int thirdTerm;
    int thirdLastterm;
    int sum;
    int total;
    int constantNumber = 1;
    int a = 0;
    std::vector<int> vSeries;

    while (std::cout << "Please enter the third term in the series: " && !(std::cin >> thirdTerm)) {
        std::cin.clear(); //clear bad input flag
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
        std::cout << "Invalid input; please re-enter.\n";
    }
    while (std::cout << "Enter the third from the last term in the series: " && !(std::cin >> thirdLastterm)) {
        std::cin.clear(); //clear bad input flag
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
        std::cout << "Invalid input; please re-enter.\n";
    }
    while (std::cout << "Please enter the sum of the series: " && !(std::cin >> sum)) {
        std::cin.clear(); //clear bad input flag
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
        std::cout << "Invalid input; please re-enter.\n";
    }

    do {
        a = 0;
        vSeries.clear();
        vSeries.push_back(thirdTerm - (2 * constantNumber));
        vSeries.push_back(thirdTerm - (1 * constantNumber));

        do {
            total = 0;
            vSeries.push_back(thirdTerm + (a * constantNumber));
            a++;
            for (int i = 0; i < vSeries.size(); i++) {
                total += vSeries[i];
            }
        } while (total < sum);

        constantNumber++;

        if (constantNumber > 100000) {
            std::cout << "There doesn't appear to be a solution based on the input - exiting program.";
                return 0;
        }

    } while (vSeries[vSeries.size() - 3] != thirdLastterm || total != sum);

    std::cout << "\nNumber of terms in the series: " <<  vSeries.size() << std::endl;
    for (int i = 0; i < vSeries.size(); i++) {
        if (i == 0)
            std::cout << vSeries[i];
        else
            std::cout << "," << vSeries[i];
    }

    return 0;
}


texts:
I just finished rewriting my Router class. Any input would be much appreciated.

The class routes URLs based on a site.com/class/method/param/param/etc syntax.

One thing I've done differently is created a mechanism for basic templates to be loaded directly without the need for a controller. I often find pages such as /about/ do not require additional methodology, and setting up really basic controllers just seems like a waste of time. Therefore, I have created a check for templates such as _about.php in the views folder, with the underscore denoting that it can be loaded directly.

The class also currently assumes an error class or template.

class Router{

    public static function getPath($uri = null){
        // set default uri
        $uri = is_null($uri) ? $_SERVER['REQUEST_URI'] : $uri;

        // remove possible query string
        $uri = preg_replace('/\?(.*)/', '', $uri);

        return explode('/',trim($uri,'/'));
    }

    public static function getQuery($uri = null){

        // set default uri
        $uri = is_null($uri) ? $_SERVER['REQUEST_URI'] : $uri;

        // get query string
        $query = substr($uri, strpos($uri,'?') + 1);

        // parse into array
        $q = array();
        parse_str($query,$q);

        return $q;
    }

    public static function follow($uri = null){

        $path = self::getPath($uri);

        // get controller and method, or set defaults of root and index
        $controller = ($path[0] == "") ? 'root' : $path[0];
        $method = ((count($path) > 1) && ($path[1] != "")) ? $path[1] : null;

        // see if controller is a static page, only possible if no method specified
        if(is_null($method) && file_exists(APPLICATION_DIR . '/views/_' . $controller . '.php')){
            include APPLICATION_DIR . '/views/_' . $controller . '.php';
        }
        else if(file_exists(APPLICATION_DIR . '/controllers/' . $controller . '.php')){ // see if controller exists
            // load controller class
            include_once APPLICATION_DIR . '/controllers/' . $controller . '.php';

            // if method is empty or doesn't exist, it defaults to "index"

            if(is_null($method) || !method_exists($controller,$method)) {
                $method = "index";
            }

            if(method_exists($controller, $method)){
                $c = new $controller();
                $c->$method();
            }
            else{
                self::follow('e404');
            }
        }
        else{
            self::follow('e404');
        }

    }

}


texts: Extracting values from refs pointing to form inputs

texts:
I have a form component with multiple refs pointing to form inputs. On submit, those inputs' values need to be passed the into form callback, structured as an object.

Currently, it's achieved like this:

class MyComponent extends React.Component {
    render() {
        return (
            <form onSubmit={() => this.onSubmit()}>
                <input ref="firstName">
                <input ref="lastName">
                <input ref="age">
                <input ref="sex">
            </form>
        );
    }
    onSubmit() {
        let firstName = this.refs.firstName.value.trim();
        let lastName = this.refs.lastName.value.trim();
        let age = this.refs.age.value.trim();
        let sex = this.refs.sex.value.trim();

        this.props.onSubmit({
            firstName,
            lastName,
            age,
            sex
        });
    }
}

These lines let firstName = this.refs.firstName.value.trim(); look like a code duplication to me. Could they be rewritten into something more elegant? ES2015 answers are welcome.


texts:
I have this short Python script for making images brighter:

import skimage.io
import math
import sys

def square_root_filter(input_image_file_name, output_image_file_name):
        image_data = skimage.io.imread(input_image_file_name)
        image_data_height = len(image_data)
        image_data_width  = len(image_data[0])

        for row_index in range(image_data_height):
                for column_index in range(image_data_width):
                        channel = image_data[row_index][column_index]

                        r = float(channel[0])
                        g = float(channel[1])
                        b = float(channel[2])

                        r /= 255.0
                        g /= 255.0
                        b /= 255.0

                        r = math.sqrt(r)
                        g = math.sqrt(g)
                        b = math.sqrt(b)

                        channel[0] = int(255 * r)
                        channel[1] = int(255 * g)
                        channel[2] = int(255 * b)

        skimage.io.imsave(output_image_file_name, image_data)

def main():
        square_root_filter(sys.argv[1], sys.argv[2])

if __name__ == "__main__":
        main()

Output

(I tested it only with Python 3.5. Also, it will take some time to do its work.)

I am not a professional Python programmer, so please tell me anything that will make the code better.


texts:
I have the following code where I try to manage user roles in teams:

Teams have entries, an entry has a creator. This creator is member of a team and has a specified role. Moderators may delete all entries, users may only delete their own entries. Here is how I implemented this:

public class TeamMember implements TeamRole {
    public String rank = "rank: Member";
    @Override
    public boolean deleteEntry(AbstractUser requester, Team team, Entry entry) throws IllegalAccessException {
        if(requester.getUid().equals(entry.getCreator().getUid())) {
            team.delete(entry);
            System.out.println("Member "  + requester.getName() +  " deleted own entry: " + entry.toString() + "from " + team.toString());
            return true;
        }
            throw new IllegalAccessException("Team members can only delete their own entries!");
    }

Moderator:

public class TeamModerator implements TeamRole {
    public String rank = "rank: Moderator";
    @Override
    public boolean deleteEntry(AbstractUser requester, Team team, Entry entry) throws IllegalAccessException {
        team.delete(entry);
        System.out.println("Moderator " +  requester.getName() + " deleted entry: "  + entry.toString() +  "from " + team.toString());
        return true;
    }

Team:

public class Team {
    private List<Entry> entries;
    private Map<AbstractUser, TeamRole> memberPerms;
    private String id;
    private String name;

public TeamRole findPermissionsForUser(AbstractUser user) {
    return memberPerms.get(user);
}
}

And the method that handles the request:

@RequestMapping(value = "/rest/entries/delete/userid/{userId}/teamid/{teamId}/entryid/{entryId}")
    public ResponseEntity<Team> deleteEntry(@PathVariable String userId, @PathVariable String teamId, @PathVariable String entryId) {
        Optional<Team> team = Repository.findTeamById(teamId);
        Optional<AbstractUser> user = Repository.findUserById(userId);
        Optional<Entry> entry = Repository.findEntryById(teamId, entryId);
        if (!(team.isPresent())) {
            return new ResponseEntity("team not found", HttpStatus.BAD_REQUEST);
        }
        if (!(user.isPresent())) {
            return new ResponseEntity("user not found", HttpStatus.BAD_REQUEST);
        }
        if (!(entry.isPresent())) {
            return new ResponseEntity("entry not found", HttpStatus.BAD_REQUEST);
        }
        return EntryService.deleteEntry(user.get(), team.get(), entry.get());

    }

The service that does the delete:

public class EntryService {
    public static ResponseEntity<Team> deleteEntry(AbstractUser requester, Team team, Entry e) {
        try {
            team.findPermissionsForUser(requester).deleteEntry(requester, team, e);
            return new ResponseEntity(team, HttpStatus.OK);
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
            return new ResponseEntity(e1.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

This is just a MVCE which does not contain user authentication, it trustst that the passed userid is correct.
I think that this is not a good implementation, how would you model this?


texts: Removing a specific character and its neighbors from a string

texts:
Assume we have an string that contains the character 'c'. This character can be located anywhere within the string. The exercise is to remove 'c', and the characters that, if they exist, are on its immediate left or right. I have devised an algorithm, assuming that 'c' = '*'. Its flowchart can be found here and the code is as follows:

In C#:

class Program
{
    static void Main(string[] args)
    {
        string input = Console.ReadLine();

        Console.WriteLine(RemoveAsterix(input));
        Console.ReadKey();
    }

    static string RemoveAsterix(string myString)
    {
        if (!(myString.Contains('*')))
        {
            throw new Exception("You need an asterix!");
        }

        List<char> myStringSplit = myString.ToCharArray().ToList();

        if (myStringSplit[0] == '*')
        {
            myStringSplit.RemoveRange(0, 2);

        }

        if (myStringSplit[myStringSplit.Count - 1] == '*')
        {
            myStringSplit.RemoveRange(myStringSplit.Count - 2, 2);

        }

        for (int i = 1; i < myStringSplit.Count - 1; i++)
        {
            if (myStringSplit[i] == '*')
            {
                myStringSplit.RemoveRange(i - 1, 3);
                break;
            }
        }

        return new string(myStringSplit.ToArray());

    }
}

And in Python:

def RemoveAsterix(myString):
    myStringList = list(myString)

    if '*' not in myString:
        raise ValueError("String must contain asterix")

    if myStringList[0] == '*':
        del myStringList[0:2]

    if myStringList[-1] == '*':
        del myStringList[-2:]

    for i in range(1, len(myStringList) - 2):
         if myStringList[i] == '*':
             del myStringList[i-1:i+2]
             break;

    return ''.join(myStringList)

def Main():
    print(RemoveAsterix(input("Enter a string: ")))

Main()

Please also review my algorithm.


texts: Return the repeated number and the missing number

texts:
Input:

Array of n integers, containing numbers in the range [1,n].

Each integer appears once except A which repeats twice and B which is missing.

Output:

Return A and B.

Example:

Input:[3 1 2 5 3]

Output:[3, 4]

A = 3, B = 4

My approach:

public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public ArrayList<Integer> repeatedNumber(final List<Integer> A) {

   //O(n) solution
   //Store the count of all the numbers appearing in the list
   int [] count = new int[A.size()];

   int rep_num = 0,miss = 0;

   //Increase the count at the index location
   for( int i = 0; i < A.size(); i++ )
    {
        int ind = A.get(i);
        count[ind - 1]++;

        //
        if(count[ind - 1] == 2)
            {
                rep_num = ind;
                break;
            }
    }

    //If the count has not been updated, then the number is missing in the array
    for(int i = 0; i < count.length; i++ )
        {
            if(count[i] == 0)
                miss = i+1;

        }

    ArrayList<Integer> num = new ArrayList<Integer>();
    num.add(rep_num);
    num.add(miss);

    return num;

}
}

I have the following questions:

How can I further optimize my code?
Is there any better way to solve this question (i.e. using a better data structure, lesser lines of code)?

Question asked on: interviewbit.com


texts: Passing parameters by reference? Let me fix that for you

texts:
I've implemented a code inspection that verifies whether a procedure has parameters that are implicitly passed by reference - in VBA a parameter is passed ByRef unless it's explicitly specified ByVal.

Here is the implementation in question:

[ComVisible(false)]
public class ImplicitByRefParameterInspection : IInspection
{
    public ImplicitByRefParameterInspection()
    {
        Severity = CodeInspectionSeverity.Warning;
    }

    public string Name { get { return "Parameter is passed ByRef implicitly"; } }
    public CodeInspectionType InspectionType { get { return CodeInspectionType.CodeQualityIssues; } }
    public CodeInspectionSeverity Severity { get; set; }

    public IEnumerable<CodeInspectionResultBase> GetInspectionResults(SyntaxTreeNode node)
    {
        var procedures = node.FindAllProcedures().Where(procedure => procedure.Parameters.Any(parameter => !string.IsNullOrEmpty(parameter.Instruction.Value)));
        var targets = procedures.Where(procedure => procedure.Parameters.Any(parameter => parameter.IsImplicitByRef)
                                                && !procedure.Instruction.Line.IsMultiline);

        return targets.SelectMany(procedure => procedure.Parameters.Where(parameter => parameter.IsImplicitByRef)
            .Select(parameter => new ImplicitByRefParameterInspectionResult(Name, parameter.Instruction, Severity)));
    }
}

Would there be a better way to do this? Here is the ImplicitByRefParameterInspectionResult class (gosh that's a long name!):

[ComVisible(false)]
public class ImplicitByRefParameterInspectionResult : CodeInspectionResultBase
{
    public ImplicitByRefParameterInspectionResult(string inspection, Instruction instruction, CodeInspectionSeverity type)
        : base(inspection, instruction, type)
    {
    }

    public override IDictionary<string, Action<VBE>> GetQuickFixes()
    {
        return !Handled
            ? new Dictionary<string, Action<VBE>>
                {
                    {"Pass parameter by value", PassParameterByVal},
                    {"Pass parameter by reference explicitly", PassParameterByRef}
                }
            : new Dictionary<string, Action<VBE>>();
    }

    private void PassParameterByRef(VBE vbe)
    {
        if (!Instruction.Line.IsMultiline)
        {
            var newContent = string.Concat(ReservedKeywords.ByRef, " ", Instruction.Value);
            var oldContent = Instruction.Line.Content;

            var result = oldContent.Replace(Instruction.Value, newContent);

            var module = vbe.FindCodeModules(Instruction.Line.ProjectName, Instruction.Line.ComponentName).First();
            module.ReplaceLine(Instruction.Line.StartLineNumber, result);
            Handled = true;
        }
        else
        {
            // todo: implement for multiline
            throw new NotImplementedException("This method is not [yet] implemented for multiline instructions.");
        }
    }

    private void PassParameterByVal(VBE vbe)
    {
        if (!Instruction.Line.IsMultiline)
        {
            var newContent = string.Concat(ReservedKeywords.ByVal, " ", Instruction.Value);
            var oldContent = Instruction.Line.Content;

            var result = oldContent.Replace(Instruction.Value, newContent);

            var module = vbe.FindCodeModules(Instruction.Line.ProjectName, Instruction.Line.ComponentName).First();
            module.ReplaceLine(Instruction.Line.StartLineNumber, result);
            Handled = true;
        }
        else
        {
            // todo: implement for multiline
            throw new NotImplementedException("This method is not yet implemented for multiline instructions.");
        }
    }
}

Any comment is welcome.


texts: Find sequence by adding 5 or multiplying by 3

texts:
I wrote this little JavaScript function that starts with the number 1 and continually either adds 5 or multiplies by 3. This function tries to find a sequence of additions and multiplications that find that number.

Keep in mind, this function does not necessarily find the shortest sequence of operations.

I am looking for a review of my code and possible ways to make it more optimized. I'm also open to suggestions about how I can go about having this function find the shortest sequence of operations.

My code:

function findSequence(goal) {
  function find(start, history) {
    if (start == goal)
      return history;
    else if (start > goal)
      return null;
    else
      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
  }
  return find(1, "1");
}

Test:

print(findSequence(178));

Output:

((((((((((((((1 + 5) + 5) + 5) + 5) + 5) + 5) + 5) + 5) + 5) + 5) + 5) * 3) + 5) + 5)