texts:
Some recent discussions on this site involved the Fizz-Buzz game - I have never actually implemented this, but for the record this is what I put together:

public class FizzBuzzConverter
{
    private readonly int _fizz;
    private readonly int _buzz;

    public FizzBuzzConverter(int fizz, int buzz)
    {
        _fizz = fizz;
        _buzz = buzz;
    }

    public string Convert(int value)
    {
        if (value % (_fizz*_buzz) == 0) return "FizzBuzz";
        if (value % _buzz == 0) return "Buzz";
        if (value % _fizz == 0) return "Fizz";
        return value.ToString();
    }
}

When people implement fizzbuzz, they tend to run a loop going from 1 to 100 and outputting the results to some console. According to Wikipedia, that's not how the game plays:

  Players generally sit in a circle. The player designated to go first says the number "1", and each player thenceforth counts one number in turn. However, any number divisible by three is replaced by the word fizz and any divisible by five by the word buzz. Numbers divisible by both become fizz buzz. A player who hesitates or makes a mistake is eliminated from the game.

So I'm thinking of going that way - and since I've never actually coded anything remotely resembling AI since I tweaked some Duke Nukem 3D configuration files in 1997, I'd like to get some feedback and refactoring thoughts about this:

public class PseudoBrain
{
    private readonly FizzBuzzConverter _converter;
    public PseudoBrain(FizzBuzzConverter converter)
    {
        _converter = converter;
    }

    public virtual string Think(string lastResult, int value)
    {
        var random = new Random();
        var ai = random.Next(0, 99);

        var result = _converter.Convert(value);

        if (ai < 85)
        {
            // thinks straight most of the time.
            return result;
        }
        else
        {
            Hesitate();
            if (ai < 95) return result;

            // could be right, could be wrong. hesitant anyway.
            return lastResult == "fizz" ? value.ToString() : "buzz";
        }
    }

    private void Hesitate()
    {
        Thread.Sleep(500);
    }
}

This brain works, ..it's just a little too hesitant:

Still, it's not too dumb:

I'm sure I could tweak the percentages to come up to something decently smart enough to implement a game with 5-6 of those "brains" playing against a human player, who would win if all the brains fried before his.

How's this PseudoBrain class doing? Don't Hesitate(), just say what you Think()!


texts: Wrapping an Exception with context-management, using the with statement

texts:
Before I try to make this work, I wondered if anyone had tried this, whether it was a good idea or not, etc.

I find myself doing this a lot:

if some_result is None:
    try:
        raise ResultException
    except ResultException:
        logger.exception(error_msg)
        raise ResultException(error_msg)

I would rather try this:

if some_result is None:
    with ResultException:
        logger.exception(error_msg)

Where the __exit__() statement would always raise the exception in the context.

Would this be clearer? Is this possible?

I only ask because I imagine someone else has tried this, or at least attempted it. But I don't seem to find any common patterns for accomplishing this after doing a couple of Google searches.

UPDATE

Here's some more information on this particular issue.

I have a method that goes to a database and determines what the user's id is via their email. The problem is that if the user isn't found, it'll return None. This is okay for most calls, but when it's incorporated in higher-level methods, this can happen:

def change_some_setting(setting, email):
    user_id = user_id_by_email(email) # None
    _change_some_setting(setting, id)

Now when _change_some_setting attempts to change the setting for a user who's id is None, we get a very vague ProgrammingException from the database library.

This helps prevent that. Is there a better way?


texts: Thread-safe message queue without mutex in C

texts:
I'm trying to write a message queue implementation
so my threads can exchange data.
To keep things simple, the queue is only responsible for
sending pointers to memory. Only one thread may send messages,
and only one thread may read messages.

The struct mq_t represents a message queue.

mq_t.messages is a circular buffer of pointers.
mq_t.send is the index of the last sent message.
mq_t.recv is the index of the next message to be received.

I'd like to know some things:

Thread Safety: I didn't use a mutex or lock, but I think the code is quite thread-safe. Is this true?
In the code I use things like while (isempty(queue));. Is there a better way to handle such things, like suspending the thread until a memory change occurs?
Cross Platform: does my code rely on some non-cross platform code or undefined behaviour?
Are there other things wrong with my code (except the highly generic function names)?

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

#define null ((void*)0)
#define SIZE 2

typedef struct {
    int send;
    int recv;
    void * messages[SIZE];
} mq_t;

inline int isfull(mq_t * queue) {
    return (queue->send+1)%SIZE == queue->recv;
}

inline int isempty(mq_t * queue) {
    return queue->send == queue->recv;
}

mq_t * create(void) {
    mq_t * queue = (mq_t*)malloc(sizeof(mq_t));
    queue->send = 0;
    queue->recv = 0;
}

void send(mq_t * queue, void * message) {
    while (isfull(queue));
    int next = (queue->send+1) % SIZE;
    queue->messages[next] = message;
    queue->send = next;
}

void * recv(mq_t * queue) {
    while (isempty(queue));
    void * message = queue->messages[queue->send];
    queue->recv = (queue->recv+1) % SIZE;
    return message;
}

void destroy(mq_t * queue) {
    while (!isempty(queue));
    free(queue);
}

Test:

void * sender(void * queue) {
    send(queue, "hello, ");
    send(queue, "world");
    send(queue, "how are you?");
    printf("sent data\n");
}

void * recver(void * queue) {
    sleep(1);
    printf("received '%s'\n", recv(queue));
    printf("received '%s'\n", recv(queue));
    printf("received '%s'\n", recv(queue));
}

int main() {
    mq_t * queue = create();

    pthread_t s, r;
    pthread_create(&s, null, sender, (void*)queue);
    pthread_create(&r, null, recver, (void*)queue);
    pthread_join(s, null);
    pthread_join(r, null);

    return 0;
}

Output:

received 'hello, '
received 'world'
received 'how are you?'
sent data


texts: Managing PostgreSQL transactions for concurrency

texts:
I have a situation where I need to use PostgreSQL's serializable isolation level for transactions.  This is for a table shared among multiple concurrent PHP processes.  If the database runs into any sort of data consistency issue PDO will throw an exception.  Makes sense since it's really up to the application to decide what to do.  In my case I effectively want to lock and wait for any other concurrent process to finish.  Based on the hints returned by PostgreSQL messages it's recommended to catch the errors and just try again.

My main concern is that I'm arbitrarily retrying 5 times and hoping for no more problems.  Is there a way to write this process more resilient to concurrency issues?

public function runInTransaction(callable $callable)
{
    $success = false;
    $count = 0;
    $this->beginTransaction($isolationLevel);
    $this->exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
    try {
        while (!$success && $count < 5) {
            try {
                $callable();
                $success = $this->commit();
            } catch (\PDOException $e) {
                if ($e->getCode() == '40001') {
                    // Serialized transaction failure. Try again.
                } elseif ($e->getCode() == '25P02') {
                    // "In failed sql transaction." Rollback and try again.
                    $this->rollback();
                    $this->beginTransaction($isolationLevel);
                } else {
                    throw $e;
                }
            }
            $count++;
        }
    } catch (\Exception $e) {
        if ($this->inTransaction()) {
            $this->rollback();
        }
        throw $e;
    }
    if (!$success) {
        throw new \RuntimeException("Could not commit transaction");
    }
}


texts: Translator that translate from English to Pyglatin or from PygLatin to English

texts:
I am almost completely done with this program. Now I just need to figure out how to use tkinter to put this in a GUI but here is what I have thus far. Constructive criticism is always welcome.

another_word = " "
sentence = " "
new_list = [ ]

def global_reset(): #I had to do this function to reset the variables  because it kept adding the last sentence to the current sentence
    global sentence
    sentence = " "
    global new_list
    new_list = [ ]
    global another_word
    another_word = " "

#function to start the whole program over again if user wants to translate a new sentence
def again():
    again = input("Would you like to enter another sentence? [Y/N]")
    if again == 'Y' or again == 'y':
        choice()
    else:
        input("Press any key to exit")

def pyg_to_eng (i):
    global another_word

    original = (i)

    if len(original) > 0 and original.isalpha():
        word = original.lower()
        first = word[-3] #sets the last letter of the word minus the ay to the variable first
        word = word [0:-3] #sets the whole word minus the first letter and the ay to the variable word
        another_word = first + word #saves the first letter + the rest of the word to the variable snother_word
        return another_word #returns another_word to the input_state() function to be added to the sentence list
    else:
        print('empty')

#input function to translate a sentence from PygLatin to English
def input_state2():

    sentence = input("enter a word to be translated: ")
    list = sentence.split()
    for i in list: #for statement to cycle through each PygLatin word and translate it to English
        pyg_to_eng(i) #called the function to translate PygLatin to english for each word in the sentence.
        new_list.append(another_word) #appends each translated word to a list
    s = " "
    print (s.join( new_list )) #rejoins the list into a single sentence
    again() #function to ask if they would like to trans another sentence.

#function that translates English to PygLatin one word at a time
def eng_to_pyg (i):
    global another_word #global because it argued with me when I tried to do it without it being a global
    pyg = 'ay'

    original = (i)

    if len(original) > 0 and original.isalpha():
        word = original.lower()
        first = word[0] #saves first letter to variable
        new_word = word + first + pyg #seves word minus first letter then adds first letter and ay to the end of a single word
        another_word = new_word[1:len(new_word)] #deletes the first letter from the first of the word
        return another_word #returns another_word to the input_state() function to be assembled back to a sentence.
    else:
        print('empty')

#input function to capture an English sentence and translate it to PygLatin
def input_state():

    sentence = input("enter a word to be translated: ") #collects sentence to be translated to PygLatin
    list = sentence.split()
    for i in list: #for statement to cycle through each word in the English sentence and translate them to PygLatin
        eng_to_pyg(i) #function call to translate each word from English to PygLatin
        new_list.append(another_word) #appends each word to a list after it is translated
    s = " "
    print (s.join( new_list )) #reasembles the list into a sentence
    again() #function to ask if they would like to trans another sentence.

def choice(): #gives user option to translate from PygLatin to English or from English to Pyglatin
    choice = input("Press P to translate Eng to Pyg, Press E to translate Pyg to Eng: [P/E] ")
    if choice == 'P' or choice == 'p': #option for the user to translate     English to PygLatin
        global_reset()
        input_state()
    elif choice == 'E' or choice == 'e': #option for user to translate PygLatin to English
        global_reset()
        input_state2()

choice()


texts: Calling a function when all asynchronous calls complete

texts:
Below is a simplified version of some code I am using to execute a function after all asynchronous calls complete.  Is this a reasonable piece of code? It seems to work.  Nothing would break if DoStuff() was called twice, though that would be very inefficient.

var i = 0;
var done = function () {
    i++;
    if (i < 2) return;
    //Everything is done
    DoStuff();
};
elem1.executeAsync(function () {
    done();
});
elem2.executeAsync(function () {
    done();
});


texts:
Since train rides can be long and boring, I've decided to make use of that time and fiddle around with some good ol' C.

What I did was to create a way to enumerate words of a certain length of an arbitrary alphabet. Basically, suppose you have an alphabet

{ '0', '1' }

(ooh, binary!) and want to get all words of length 7, you'd call

enumerate("01", 7);

and have a nice array of pointers containing the strings "0000000" to "1111111". What for, you ask? Dunno. Stuff.

I've written it on my phone, so it may be a tad slimmer than the usual 80 characters. It's also not split into files for the very same reason.

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

char *translate(
  unsigned long value,
  const char *alphabet,
  size_t length
) {
  size_t base;
  char *result;

  if (!alphabet || (base = strlen(alphabet)) < 2) {
    return NULL;
  }

  if (length == 0) {
    length = 1 + floor(log(value) / log(base));
  }

  result = malloc(length + 1);

  if (!result) {
    return NULL;
  }

  memset(result, alphabet[0], length);
  result[length] = 0;

  for (int i = length - 1; i >= 0 && value > 0; --i) {
    unsigned long mod = value % base;
    result[i] = alphabet[mod];

    value -= mod;
    value /= base;
  }

  return result;
}

char **enumerate(
  const char *alphabet,
  const size_t length
) {
  size_t base;

  if (!alphabet || (base = strlen(alphabet)) < 2) {
    return NULL;
  }

  if (length == 0) {
    return NULL;
  }

  unsigned long end = pow(base, length);
  char **array = malloc((end + 1) * sizeof(char*));

  if (!array) {
    return NULL;
  }

  array[end] = NULL;

  for (int i = 0; i != end; ++i) {
    char *storage = malloc(length + 1);
    char *translated = translate(i, alphabet, length);

    if (!storage || !translated) {
      if (storage) {
        free(storage);
      }

      if (translated) {
        free(translated);
      }

      array[i] = NULL;
      goto error_cleanup;
    }

    strcpy(storage, translated);
    free(translated);
    array[i] = storage;
  }

  return array;

  error_cleanup:

  for (int i = 0; array[i] != NULL; ++i) {
    free(array[i]);
  }

  free(array);
  return NULL;
}

Example usage; simply concatenate the listings.

int main(int argc, char *argv[]) {
  if (argc < 2) {
    printf("Usage: %s <length> <alphabet>",
          argv[0]);
    exit(0);
  }

  size_t length = atoi(argv[1]);
  char *alphabet = argv[2];

  char **array = enumerate(alphabet, length);

  if (!array) {
    printf("Error while enumerating.");
    exit(1);
  }

  for (int i = 0; array[i] != NULL; ++i) {
    printf("%s\n", array[i]);

    free(array[i]);
  }

  free(array);
  exit(0);
}

What I'm most concerned about is idiomaticality (is that even a word?) of the code, since my C is rusty and self-taught, especially concerning the use of that string array. Also, is my goto used well and with good reason?


texts: Query that shows similar columns between different tables on a database

texts:
In my work, I often have to take a naive look at tables and then never see them again, and it can be difficult to see what lines up where for large databases with many columns. I wrote this, and while it works, it seems to require an unnecessary number of joins. I'm wondering if there is a better way to handle this issue or a way to cut down the code.

select A.COLUMN_NAME as 'Similar Column', y.TABLE_NAME as 'First Table', z.TABLE_NAME as 'Second Table'
from INFORMATION_SCHEMA.COLUMNS A
full outer join INFORMATION_SCHEMA.COLUMNS B
    on A.COLUMN_NAME = B.COLUMN_NAME
cross apply (
    SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE') as y
cross apply (
    SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE') as z
where y.TABLE_NAME <> z.TABLE_NAME
    and A.TABLE_NAME = y.TABLE_NAME
    and B.TABLE_NAME = z.TABLE_NAME
order by y.TABLE_NAME,z.TABLE_NAME, a.COLUMN_NAME

I also wonder if there is a way to prevent duplicate entries, in other words, Activity, RMA is the same as RMA, Activity.


texts: Checking and converting [[HH:]MM:]SS input format

texts:
I would like to use the following routine in my job submission bash script which expects the allowed walltime in the format [[HH:]MM:]SS. (Brackets indicating optionality.) For easier readability I want to convert any input value into the fixed format HH:MM:SS where the value for hours is open ended.
I think it works okay, but I am a bit worried if I have overlooked possible points where a user could make a mistake. This could lead to submitting an invalid jobscript and a lot of computation jobs not starting.
I also ask myself whether or not my code is optimal.

#!/bin/bash

#
# If there is an unrecoverable error: display a message and exit.
#

printExit ()
{
    case $1 in
        [iI]) echo INFO: "$2" ;;
        [wW]) echo WARNING: "$2" ;;
        [eE]) echo ERROR: "$2" ; exit 1 ;;
           *) echo "$1" ;;
    esac
}

#
# Test if a given value is an integer
#

isnumeric ()
{
    if ! expr "$1" : '[[:digit:]]*$' > /dev/null; then
        printExit E "Value for $2 ($1) is no integer."
    fi
}

#
# Test if a given value is a proper duration
#

istime ()
{
    local tempTime=$1
    # Split time in HH:MM:SS
    theTempSeconds=${tempTime##*:}
    isnumeric "$theTempSeconds" "seconds"
    if [[ ! "$tempTime" == "${tempTime%:*}" ]]; then
      tempTime="${tempTime%:*}"
      theTempMinutes=${tempTime##*:}
      isnumeric "$theTempMinutes" "minutes"
    fi
    if [[ ! "$tempTime" == "${tempTime%:*}" ]]; then
      tempTime="${tempTime%:*}"
      theTempHours=${tempTime##*:}
      isnumeric "$theTempHours" "hours"
    fi
    if [[ ! "$tempTime" == "${tempTime%:*}" ]]; then
      printExit E "Unrecognised format."
    fi

    theSeconds=`expr $theTempSeconds % 60`
    theTempMinutes=`expr $theTempMinutes + $theTempSeconds / 60`
    theMinutes=`expr $theTempMinutes % 60`
    theHours=`expr $theTempHours + $theTempMinutes / 60`

    printf -v theWalltime "%d:%02d:%02d" $theHours $theMinutes $theSeconds
}

theWalltime="$1"

echo "$theWalltime"

istime $theWalltime

echo "$theWalltime"

exit 0

I use the first two functions quite a lot in my script so I used them for the target function also.


texts: Inheritance and forcing methods to be called inside another method

texts:
I've written a text parser that extracts useful information from a given text. Texts are formatted different, so there are different specialized parsers. I've designed them so that they all must define the methods from the interface Parser.

class Parser:
    def parse(text):
        raise NotImplementedError

    def pre_validate(text):
        raise NotImplementedError

    def post_validate():
        raise NotImplementedError

How can I force all subclasses of Parser to call pre_validate before running parse and post_validate after calling parse?

I could solve it like this, but I don't think it's very elegant to wrap methods like this:

class Parser:
    def parse(text):
        self.pre_validate(text)
        self._parse()
        self.post_validate(text)

    def _parse(text):
        raise NotImplementedError

    def pre_validate(text):
        raise NotImplementedError

    def post_validate():
        raise NotImplementedError

Ideally I'd like to allow the subclasses to implement the method parse instead of _parse. What's the recommended way of solving this? Would it make sense to use a python decorator here?


texts:
I needed to rotate a non-square matrix in my program to transpose some spreadsheet data and decided to make a function to rotate 90, 180, or 270 degrees.

It doesn't rotate the matrix in place, but instead generates a copy and returns that. I want to go for processing efficiency, let me know what I can do better:

//Rotates the provided matrix by provided degrees counterclockwise
function RotateMatrix(matrix, degrees){
  if(degrees == 90){
    //For 90 degrees swap the height/width and swap the location of each element
    var output = GenerateMatrix(matrix[0].length, matrix.length, 0); //Swapping the width and height for non square matrices
    for(var i = 0; i < matrix[0].length; i++){
      for(var j = 0; j < matrix.length; j++){
        output[i][j] = matrix[j][i];
      }
    }
  } else if(degrees == 180) {
    //For 180 degrees, rebuild array backwards
    var output = GenerateMatrix(matrix.length, matrix[0].length, 0);
    for(var i = matrix.length - 1; i >= 0; i--){
      for(var j = matrix[0].length - 1; j >=0; j--){
        output[matrix.length - 1 - i][matrix[0].length - 1 - j] = matrix[i][j];
      }
    }
  } else if(degrees == 270) {
    //For 270 degrees, not sure how to make short description
    var output = GenerateMatrix(matrix[0].length, matrix.length, 0); //Swapping the width and height for non square matrices
    for(var i = 0; i < matrix[0].length; i++){
      for(var j = matrix.length - 1; j >=0; j--){
        output[i][matrix.length - 1 - j] = matrix[j][i];
      }
    }
  }
  return output;
}

//Generates a matrix with the requested length and width and value
function GenerateMatrix(length, width, value){
  var output = [];
  for(var i = 0; i < length; i++){
    width > 0 ? output.push([]) : output.push(value); //If matrix has 0 width
    for(var j = 0; j < width; j++){
      output[i].push(value)
    }
  }
  return output;
}


texts:
Here was my attempt at finding the most frequent integers in a list, I feel like there are better ways to do this and I spent a great deal of time coming up with this solution, so please point me in the correct direction!

'''
Created on Jan 27, 2018
Problem statement: Find the most frequently occuring integer in a list and its occurence;
    input: 1 1 2 3 2 1 2
    output: [(1,3), (2, 3)]

@author: Anonymous3.1415
'''
from collections import Counter

def integer_frequency(int_list):
    int_freq = Counter()
    for i in int_list:
        int_freq[i] += 1
    cnt = 0
    values = sorted(int_freq.values())
    values.reverse()
    for x in values:
        if x == values[0]:
            cnt += 1
        else:
            break
    return int_freq.most_common(cnt)

int_list = list(map(int, raw_input().strip().split(' ')))
most_frequent = integer_frequency(int_list)
print(most_frequent)


texts:
I'm new to this pattern and I see arguments online about different implementations. I have the following code and it seems fine to me, but I'm wondering if having to pass the DBContext into the constructor would cause any issues down the line? I'm using this with EntityFramework (RECORD_TYPE is a table brought in from EF).

I'm a little newer to unit testing as well, so I'm thinking I would have to make a mock context in my unit tests that basically return a list of RECORD_TYPE objects that I create in the mock DBContext I make.

Am I missing any ideas with this?

public interface IRepository<T> where T : class
{
    IQueryable<T> All { get; }
    T Find(int id);
    void Save();
}

public class Repository<T> : IRepository<T> where T : class
{
    private DbContext context;

    public Repository(DbContext c)
    {
        context = c;
    }

    public IQueryable<T> All { get { return context.Set<T>(); } }

    public T Find(int id)
    {
        return context.Set<T>().Find(id);
    }

    public void Save()
    {
        context.SaveChanges();
    }
}

public class RecordTypeRepository : Repository<RECORD_TYPE>
{
    public RecordTypeRepository(DbContext context)
        : base(context)
    {
    }
}


texts: Given a list of words, remove the shorter word of every pair

texts:
This is not a "please do my homework" question. I solved a problem two ways and would like to know which solution is better; better being defined by better readability, lower complexity and lower memory consumption. I'd also like to note that this is a not a homework assignment but an optional no-credit practice problem.

My CS class offers practice problems through their site. One specific question is named "removeShorterStrings." The prompt being:

  Write a method removeShorterStrings that takes an ArrayList of Strings as a parameter and that removes from each successive pair of values the shorter string in the pair. For example, suppose that an ArrayList called list contains the following values: {"four", "score", "and", "seven", "years", "ago"} In the first pair, "four" and "score", the shorter string is "four". In the second pair, "and" and "seven", the shorter string is "and". In the third pair, "years" and "ago", the shorter string is "ago". Therefore, the call: removeShorterStrings(list); should remove these shorter strings, leaving the list as follows: "score", "seven", "years". If there is a tie (both strings have the same length), your method should remove the first string in the pair. If there is an odd number of strings in the list, the final value should be kept in the list.

I have come up with the following solutions:

The "ask for permission" solution:

void removeShorterStrings(ArrayList<String> list) {
    if (list.size() != 0) {
        int isOdd = (list.size() >> 0) & 1;
        for (int i = 0; i <= (list.size() >> 1) - isOdd; i++) {
            String first = list.get(i);
            String second = list.get(i + 1);
            if (first.length() <= second.length()) {
                list.remove(i);
            } else {
                list.remove(i + 1);
            }
        }
    }
}

and the "ask for forgiveness" solution:

void removeShorterStrings(ArrayList<String> list) {
    for (int i = 0; i <= (list.size() >> 1); i++) {
        try {
            String first = list.get(i);
            String second = list.get(i + 1);
            if (first.length() <= second.length()) {
                list.remove(i);
            } else {
                list.remove(i + 1);
            }
        } catch (IndexOutOfBoundsException e) {
            break;
        }
    }
}

I come from a JavaScript/python background, so I'm unsure of what is considered "good practice" in java.

TL;DR: Which solution is better in terms of better readability, lower complexity and lower memory consumption?


texts: Javascript bar graph representation using CSS

texts:
This js was written strictly for a visualization of a graph redesign included in a stats report within our game systems. It all works properly, but I know there has to be a much neater way to organize this. I have some ideas, but I don't quite know how to approach it. Any guidance would be greatly appreciated.

    var barContainer = document.getElementById('bar-graph');
    var barCount = 15;

    for (index = 0; index < barCount; ++index) {
        var liBar = document.createElement('li');
        liBar.innerHTML = '

';
        barContainer.appendChild(liBar);
    }

    //this is for visualization. Sets height of each bar, then adds a margin to the top of each based on height, in order to keep each bar flushed with the bottom of the graph.
    var list = document.getElementsByClassName("bar");
    var percentGroup = new Array();

    for (index = 0; index < list.length; ++index) {
        var bar = list[index];
        var originalHeight = $(bar).height();
        $(bar).css( "height", originalHeight - (index * 10) );
        var barHeight = $(bar).height();
        var percentage = barHeight / originalHeight;
        percentGroup.push(percentage);
        var containerHeight = $('.graph').height();
        var marginTop = containerHeight - barHeight;
        $(bar).css('margin-top', marginTop);
        var graph = $('#bar-graph');
        var graphWidth = graph.width();
        var barWidth = $(bar).width();
        var marginRight = ( graphWidth - (barWidth * barCount) ) / ( barCount - 1 );
        $(".graph ul li").css('margin-right', marginRight);
        $(".graph ul li:nth-last-child(2)").css('margin-right', (marginRight - 1) );
    }

    //this function takes the decimal value percentages generated above, turns them into integers, and multiplies them by 100. It also creates the containers that house the percentages
    var val = document.getElementById('valContainer');

    for (index = 0; index < percentGroup.length; ++index) {
        var bar = percentGroup[index];
        bar = Math.round(bar * 100);
        var li = document.createElement('li');
        li.innerHTML = bar + '%';
        val.appendChild(li);
        $(val).css('width', (graphWidth + 4) );
        $(li).css('margin-right', marginRight);
    }


texts:
This is the knapsack problem from rosettacode.org:

  A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it and it will have to last the whole day. He creates a list of what he wants to bring for the trip but the total weight of all items is too much. He then decides to add columns to his initial list detailing their weights and a numerical value representing how important the item is for the trip.

(The list of items, together with their weight in decagrams and their value, is given in the code below.)

  Which items does the tourist carry in his knapsack so that their total weight does not exceed 400 decagrams [4 kg], and their total value is maximised?

My solution is below. This seems almost seems to be too little.  Just sort by their efficiency (value/weight) and add the most efficient item until capacity is reached.

from itertools import takewhile

ITEMS = (
    ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160),
    ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40),
    ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30),
    ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40),
    ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75),
    ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12),
    ("socks", 4, 50), ("book", 30, 10),
    )

def item_efficiency(item):
    name, weight, value = item
    return float(value)/float(weight)

def pack_bag(item):
    name, weight, value = item
    pack_bag.max_weight -= weight
    return pack_bag.max_weight > 0
pack_bag.max_weight = 400  # static variable implementation

# pack the most efficient item until pack_bag.max_weight is reached.
pack = list(takewhile(pack_bag, reversed(sorted(ITEMS, key=item_efficiency))))

# print output
for item in pack:
    print item[0]

table = zip(*pack)
print "Total Value: %i" % sum(table[2])
print "Total Weight: %i" % sum(table[1])

I understand that this solution doesn't scale if capacity is multidimensional.  This gives the correct answer but I haven't seen any solution like it.  It could be because I am exporting a lot of the workload to sorted, reversed, and takewhile.


texts: AnimationFrameController: requestAnimationFrame made easy

texts:
I am looking for feedback on what I can improve to a tool I have been using for several months now, my AnimationFrameController. I find requestAnimationFrame an incredibly hassle and hard to control, so this controller does it for you. Are there better/more efficient ways to do this? The below is an example of how to use the code and the ES6 version of the source.

The main reason I built this is to be able to quickly throw together animation or things you can do every frame, but in the requestAnimationFrame function you get exactly one call, and you better hope it calls all animations etc... With my animationFrameController its as easy as going AF.add( myFunction ) and it will be called continuously until it gets removed (by AF.remove) or it returns false itself and cancels itself out. The animationFrame ends when no more handlers remain.

"use strict";

/*
 * AnimationFrameController 1.0
 */

class AnimationFrameController {

  constructor( autostart = true ){

    this.autostart = true;
    this.paused = true;
    this.time = 0;
    this.fps = 0;

    this.callees = [];
    this.calleesTime = [];

  }

  get time(){
    return this._time;
  }

  set time(v){
    this.fps = (v - this.time) / 1000;
    this._time = v;
    return this._time;
  }

  get paused(){
    return this._paused;
  }

  set paused(v){
    this._paused = v;
    if( this._paused === false ){
      this.loop( this.time );
    }
  }

  add( ...handlers ){

    handlers.forEach( handler => {
      if(handler instanceof Function){
        this.callees.unshift( handler );
        this.calleesTime.unshift( this.time );
      }
    });
    if(this.callees.length && this.autostart && this.paused) this.paused = false;

  }

  remove( ...handlers ){

    handlers.forEach( handler => {
      let index = -1;
      while((index = this.callees.lastIndexOf( handler )) >= 0){
        this.callees.splice( index, 1 );
        this.calleesTime.splice( index, 1 );
      }
    });
    if(this.callees.length <= 0) this.paused = true;

  }

  loop( time ){

    try {

      if( !this.paused ){

        window.requestAnimationFrame( this.loop.bind(this) );

        let delta = time - this.time;
        this.time = time;

        this.callees.map(( handler, index ) => {
          let progress = time - this.calleesTime[index];
          return handler( delta, progress ) === false ? handler : true;
        }).forEach(handler => {
          return handler !== true ? this.remove(handler) : 0;
        });

      }

    } catch(e) {

      this.paused = true;
      console.warn('An error has occurred while running the AnimationFrame.', e);

    }

  }

}

/* IMPLEMENTATION */

var AF = new AnimationFrameController;
var button = document.getElementById('clickme');
var animation = false;
var x = 0, y = 0;

button.addEventListener('click', function( event ){
  var fromX = x;
  var fromY = y;
  var toX = Math.round( Math.random() * (window.innerWidth - button.clientWidth) );
  var toY = Math.round( Math.random() * (window.innerHeight - button.clientHeight) );
  AF.remove( animation );
  AF.add(animation = function( delta, progress ){
    var now = progress / 2000;
    if( now >= 1 ){
      x = toX;
      y = toY;
      return false;
    } else {
      x = fromX + (toX - fromX) * now;
      y = fromY + (toY - fromY) * now;
    }
  });
});

AF.add(function(){
  button.style.left = x + 'px';
  button.style.top = y + 'px';
});
<input type="button" value="click me" id="clickme" style="position:absolute;" />

(You can find an ES5 version over at github if you want to try it in al older browser: https://github.com/jasperlinsen/AnimationFrameController)


texts:
I'm trying to learn to use the C++ Standard Library and some of the modern C++11 features. Can someone review my counting sort algorithm below and critique my style/algorithm/use of the STL? Thank you!

#include <algorithm>
#include <chrono>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>

const int kSize = 100000000;      // Size of container to sort
const int kRangeFrom = -1000000;  // first of range for random number generator
const int kRangeTo = 1000000;     // last of range for random number generator

// Linear time sorting algorithm for integers
template<typename InputIterator>
void counting_sort(InputIterator first, InputIterator last) {
  auto minmax_el = std::minmax_element(first, last);
  auto min = *minmax_el.first;
  auto max = *minmax_el.second;
  std::vector<std::size_t> counts(max - min + 1, 0);

  std::for_each(first, last, [&](auto x) {
    ++counts[x - min];  // Store value counts
  });

  for (auto it_c = counts.begin(); it_c != counts.end(); ++it_c) {
    auto idx = std::distance(counts.begin(), it_c);
    std::fill_n(first, *it_c, idx + min); // Store in sorted order
    std::advance(first, *it_c);
  }
}

int main() {
  std::random_device rd;
  std::mt19937 mt(rd());
  std::uniform_int_distribution<int> dist(kRangeFrom,kRangeTo);

  std::vector<int> v1(kSize);
  std::generate(v1.begin(), v1.end(), [&](){ return dist(mt); });

  std::vector<int> v2(kSize);
  std::copy(v1.begin(), v1.end(), v2.begin());

  auto first1 = std::chrono::steady_clock::now();
  counting_sort(v1.begin(), v1.end());
  auto last1 = std::chrono::steady_clock::now();

  auto first2 = std::chrono::steady_clock::now();
  std::sort(v2.begin(), v2.end());
  auto last2 = std::chrono::steady_clock::now();

  std::cout << "counting sort time: " << std::chrono::duration<double, std::milli>(last1 - first1).count() << " ms" << '\n';
  std::cout << "std::sort time: " << std::chrono::duration<double, std::milli>(last2 - first2).count() << " ms" << '\n';
  std::cout << "v1 == v2: " << std::equal(v1.begin(), v1.end(), v2.begin()) << '\n';

  return 0;
}


texts: Receive data from SQL and CSV and send it to MySQL database using Python

texts:
Details:

I have a code, which does the following:

Get data from CSV and insert it into MySQL table
Get data from SQL Server and insert it into MySQL table
Run this code every 240 seconds - to refresh the data, in order to have up to date infromation.

I'd like to know whether the code below, I am about to provide, can be improved? In terms of performance and whether the code is readable or anything can be changed.

import pyodbc
import csv
import mysql.connector
import time

#MySQL connection
MySQLdb = mysql.connector.connect(
  host="SVR",
  user="root",
  passwd="",
  database="production"
)

#SQL Sevrer
sqlServerData = pyodbc.connect(
    "Driver={SQL Server Native Client 11.0};"
    "Server=svr;"
    "Database=SQL_Server;"
    "Trusted_Connection=yes;")

input("Press Enter to continue...")

starttime=time.time()
while True:
    try:
        print("---START---")

        #MySQL cursor
        MySQLtruncateCSV = MySQLdb.cursor()
        MySQLtruncateSQL_Server = MySQLdb.cursor()
        MySQLcursor = MySQLdb.cursor()
        MySQLcursor2 = MySQLdb.cursor()

        #SQL Server Cursor
        SqlData = sqlServerData.cursor()

        #Truncate MySQL Tables
        CSVTruncate = 'Truncate CSV;'
        SQL_ServerTruncate = 'Truncate SQL_Server;'
        print("Truncate Table CSV...")
        #CSV table
        MySQLtruncateCSV.execute(CSVTruncate)
        MySQLtruncateCSV.close()
        MySQLdb.commit()
        print("Truncate Table SQL_Server...")
        #SQL_Server table
        MySQLtruncateSQL_Server.execute(SQL_ServerTruncate)
        MySQLtruncateSQL_Server.close()
        MySQLdb.commit()

        print("Receiving data from CSV...")
        print("Sending to MySQL..")
        #Insert CSV file into MySQL database
        with open('G:/Technical/Labels/Production/Data/CSVExport.csv', 'r') as f:
            data = csv.reader(f)
            next(data, None) #Skip header
            for row in data:
                MySQLcursor.execute('insert into CSV (customer_code,customer_logo, product_code,product_description,allergen_info, barcode_inner,barcode_outer) VALUES (%s,%s,%s,%s,%s,%s,%s);', row)
        MySQLdb.commit()
        MySQLcursor.close()

        print("Receiving SQL_Server data...")
        #Get data from SQL_Server
        SqlData.execute("select p.id, p.code,p.description, p.searchRef1, so.number, c.code, c.name \
             from salesorderline sol join \
             salesorder so \
             on sol.salesorderid = so.id join \
             product p \
             on sol.productid = p.id join \
             customer c \
             on so.customerid = c.id \
             where so.orderdate > dateadd(dd,-10,cast(getdate() as date));")

        print("Sending to MySQL..")
        #Send SQL_Server data into MySQL
        for x in SqlData.fetchall():
            a,b,c,d,e,f,g = x
            MySQLcursor2.execute("insert into SQL_Server (product_id, product_code, product_description, product_weight, \
                    salesorder_number, customer_code, customer_name) values (%s,%s,%s,%s,%s,%s,%s);", (a,b,c,d,e,f,g))

        SqlData.close()
        MySQLdb.commit()
        MySQLcursor2.close()
        print("---END---")
        time.sleep(240 - ((time.time() - starttime) % 240))

    except:
        print("An error has occured.. Please contact Technical")
        break


texts: How can I condense several IBAction methods in a class with a delegate?

texts:
I have the following class:

MyProtocolClass.h

#import <Foundation/Foundation.h>

@protocol MyExampleProtocol <NSObject>
@required
- (void)someRequiredMethod:(NSInteger)someValue;
@end

@interface MyProtocolClass : UIView

// interface stuff

@end

MyProtocolClass.m

#import "MyProtocolClass.h"

@interface MyProtocolClass()

@property (nonatomic,assign) id<MyExampleProtocol> delegate;

@end

@implementation MyProtocolClass

// implementation stuff

- (IBAction)fooMethod:(id)sender {
    [self.delegate someRequiredMethod:0];
}

- (IBAction)barMethod:(id)sender {
    [self.delegate someRequiredMethod:1];
}

- (IBAction)fooBarMethod:(id)sender {
    [self.delegate someRequiredMethod:2];
}

@end

And this is a fairly simple example.  The problem here is that I have a view with three buttons, and each button has it's own method, which simply calls a method on the delegate with an index to tell the delegate which button was pressed.

Surely there's a way to simplify this code and improve its readability.  A more complex view with several more interactive UI elements would quickly make this file very large if we have to add another 4 lines to the file for each interactive UI element we add to the screen.


texts: Displaying all the numbers between 200 and 600

texts:
I have to display all the numbers between 200 and 600 (both numbers inclusive) that are divisible by 8:

for($i=200;$i<=600;$i++)
{
    if($i%8==0)
        echo $i.',';
}

It reaches maximum execution time.


texts: Extending native JavaScript Promise with cancellation support

texts:
Updated, below is a more current and simple version of this. Also, if you track the progress of TC39's "ECMAScript Cancellation" proposal, this thread might be worth checking out.

I'm playing with Promise Extensions for JavaScript (prex) library and I like it a lot. Amongst other things, this library appears to be a prototype behind the current ECMA TC39 proposal for cancellation and it uses the familiar cancellation token approach, popularized by .NET Task API.
I want to extend the standard Promise class with cancellation support, similar to how it is implemented in Bluebird (i.e., with an optional oncancel callback) but using prex.CancellationToken.
Here is a draft that can be run with NodeJS:
const prex = require('prex');

class CancellablePromise extends Promise {
  constructor(executor, token) {
    if (!token) {
      // if no token supplied, just delegate to the parent class
      super(executor);
      return;
    }

    const observeCancellation = async () => {
      // prex.Deferred is similar to TaskCompletionSource in .NET
      const deferred = new prex.Deferred();

      executor(
        deferred.resolve,
        deferred.reject,
        cancelListener =>
          deferred.cancelListener = cancelListener);

      const registration = token.register(() => {
        try {
          // capture the CancelError
          token.throwIfCancellationRequested();
        }
        catch (cancelError) {
          try {
            // the token cancellation callback is synchronous,
            // and so is the executor-provided cancelListener callback
            deferred.cancelListener && deferred.cancelListener(cancelError);
            // reject here if cancelListener has not resolved/rejected it
            deferred.reject(cancelError);
          }
          catch (error) {
            // in case cancelListener throws
            deferred.reject(error);
          }
        }
      });

      try {
        return await deferred.promise;
      }
      finally {
        registration.unregister();
      }
    };

    super((resolve, reject) =>
      observeCancellation().then(resolve, reject));
  }
}

// delayWithCancellation
function delayWithCancellation(timeoutMs, token) {
  console.log(`delayWithCancellation: ${timeoutMs}`);

  return new CancellablePromise((resolve, reject, setCancelListener) => {
    token.throwIfCancellationRequested();
    const id = setTimeout(resolve, timeoutMs);
    setCancelListener(e => clearTimeout(id));
  }, token);
}

// main
async function main() {
  const tokenSource = new prex.CancellationTokenSource();
  setTimeout(() => tokenSource.cancel(), 2000); // cancel after 1500ms

  const token = tokenSource.token;

  await delayWithCancellation(1000, token);
  console.log("successfully delayed."); // we should reach here

  await delayWithCancellation(1500, token);
  console.log("successfully delayed."); // we should not reach here
}

main().catch(error => console.log(error));


texts: Javascript recursive object is defined test

texts:
I wrote the method below, and was wondering whether a better way exists/best practice tips

_objectIsDefined = function (obj, path) {
  if (typeof path !== 'undefined') {
    // if we have been given a specific object path then recursively search it
    var pathSplit = path.split("."),
      scope = undefined;
    scope = obj;
    for (i = 0; i < pathSplit.length; i++) {
      if (typeof scope[pathSplit[i]] === 'undefined') {
        return false;
      } else if (i == pathSplit.length - 1 && typeof scope[pathSplit[i]] !== 'undefined') {
        return true;
      }
      scope = obj[pathSplit[i]];
    }
    return false;
  } else if (typeof obj !== 'undefined') {
    // if we've just been given an object and no path then return whether
    // its defined or not...
    return true;
  } else {
    return false;
  }
}
 // Usage
var isDefined = _objectIsDefined(myObject);
var isDefinedDeep = _objectIsDefined(myObject, "somenested.child.property.name");


texts: Simple addition, multiplication, divison, and subtraction program

texts:
I made a post a couple of days ago asking if anyone noticed bad habits or thought of any suggestions: (First Hangman game)

I've made 2 math programs just to make sure I got it all down pat. The first one (the subject of this question) is a simple addition, multiplication, division, and subtraction program that would deal out random numbers and ask you to add, sub, multiply, or divide them.

#12/14/14
import random

def choose():
    num1, num2 = pick_numbers()
    types = input("What type would you like Add, Sub, Mutl, Div?\n> ")
    if types.upper() == "ADD":
        print("Creating your addition problem...")
        print("{} + {}".format(num1, num2))
        correct_answer = num1 + num2
        return correct_answer
    elif types.upper() == "SUB":
        print("Creating your subtraction problem...")
        print("{} - {}".format(num1, num2))
        correct_answer = num1 - num2
        return correct_answer
    elif types.upper() == "MULT":
        print("Creating your mutliplecation problem...")
        print("{} * {}".format(num1, num2))
        correct_answer = num1 * num2
        return correct_answer
    elif types.upper() == "div":
        print("Creating your divison problem...")
        print("{} / {}".format(num1, num2))
        correct_answer = num1 / num2
        return correct_answer
    else:
        print("Error: Please only choose, add, sub, mult, or div")

def pick_numbers():
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    return num1, num2

def print_problem():
    correct_answer = choose()
    while True:
        answer = input("What is your answer?\n> ")
        if(int(answer) == correct_answer):
            print("Correct! The answer was {}".format(answer))
            return False
        else:
            print("Sorry {} isn't correct.".format(answer))

def play_again():
    try_again = input("Would you like to play again?\n> ")
    if try_again.upper() == "Y":
        return True
    elif try_again.upper() == "N":
        return False
    else:
        print("Error: please choose only 'Y' or 'N'")

while True:
    print_problem()
    if not play_again():
        break

Do you still notice any bad habits or have any suggestions so I can have better structure or code organization?


texts:
I post the following code writen all by hand. Why I have the feeling that it is a western spaghetti on its own. Second, could that be written better?

    <?php
    echo $this->Form->create('mysubmit');
    echo $this->Form->input('inputs', array('type' => 'select', 'id' => 'inputs', 'options' => $inputs));
    echo $this->Form->input('Fields', array('type' => 'select', 'id' => 'fields', 'empty' => '-- Pick a state first --'));

    echo $this->Form->input('inputs2', array('type' => 'select', 'id' => 'inputs2', 'options' => $inputs2));
    echo $this->Form->input('Fields2', array('type' => 'select', 'id' => 'fields2', 'empty' => '-- Pick a state first --'));

    echo $this->Form->end("Submit");
    ?>

    <?php echo $this->Html->link("Error Results", "#"); ?>


texts:
Here is a link to the code on JSFiddle.

This is my first attempt at playing with canvas.  Before I move on doing anything else, it would be nice to have insight from somebody who knows canvas and JavaScript better than me.

Things I am looking for:

Ways to optimize animation
Ways to optimize the lazer drawing (I know I need to clear the lazers from the array every once in awhile when they are no longer within the drawing area, just haven't gotten around to it yet.)
Ways to optimize the code in general and have good code re-use.

HTML:

<canvas id="world" style="height: 300px; width: 300px;" />

JavaScript:

console.log("Game starting...");

var ship = new Object();
ship.name = "Enterprise";
ship.x = 0;
ship.y = 0;
ship.width = 50;
ship.left = false;
ship.right = false;
ship.up = false;
ship.down = false;
ship.fire = false;
ship.firerate = 5;
ship.cfirerate = 0;
var lazers = new Array();

var world = document.getElementById('world');
var cxt = world.getContext("2d");

$(document).bind('keydown', function(e) {
    if(e.keyCode==37){
        ship.left = true;
    }
    if(e.keyCode==38){
        ship.up = true;
    }
    if(e.keyCode==39){
        ship.right = true;
    }
    if(e.keyCode==40){
        ship.down = true;
    }
    if(e.keyCode==90){ //Z
        console.log("pew pew");
        ship.fire = true;
    }
});
$(document).bind('keyup', function(e) {
    if(e.keyCode==37){
        ship.left = false;
    }
    if(e.keyCode==38){
        ship.up = false;
    }
    if(e.keyCode==39){
        ship.right = false;
    }
    if(e.keyCode==40){
        ship.down = false;
    }
    if(e.keyCode==90){ //Z
        ship.fire = false;
    }
});

function createLazer(type) {
if (type == 1) {//LEFT LAZER
    cxt.beginPath();
    cxt.moveTo(125+ship.x,140+ship.y);
    cxt.lineTo(125+ship.x,130+ship.y);
    var l = new Object();
    l.type = type;
    l.x = ship.x;
    l.y = ship.y;
    return l;
}
else if (type == 2) {//RIGHT LAZER
    cxt.beginPath();
    cxt.moveTo(125+ship.x+ship.width,140+ship.y);
    cxt.lineTo(125+ship.x+ship.width,130+ship.y);
    var l = new Object();
    l.type = type;
    l.x = ship.x;
    l.y = ship.y;
    return l;
}
}

function drawWorld() {
cxt.fillStyle="#808080";
cxt.fillRect(0,0,300,300);
}
function drawLazers() {
for (x = 0; x < lazers.length; x++)
{
    cxt.beginPath();
    cxt.strokeStyle="#FF0000";
    if (lazers[x].type == 1) {
        cxt.moveTo(125+lazers[x].x,140+lazers[x].y);
        cxt.lineTo(125+lazers[x].x,120+lazers[x].y);
    }
    else if (lazers[x].type == 2) {
        cxt.moveTo(125+lazers[x].x+ship.width,140+lazers[x].y);
        cxt.lineTo(125+lazers[x].x+ship.width,120+lazers[x].y);
    }
    cxt.stroke();
    lazers[x].y = lazers[x].y - 6;

    //console.log("drawing lazer" + lazers[x].x + lazers[x].y);
}
}
function drawShip() {
if (ship.left) { ship.x = ship.x -5; }
if (ship.right) { ship.x = ship.x +5; }
if (ship.up) { ship.y = ship.y -5; }
if (ship.down) { ship.y = ship.y +5; }
if (ship.fire) {
    if (ship.cfirerate == 0) {
        lazers.push(createLazer(1));
        lazers.push(createLazer(2));
        ship.cfirerate = ship.firerate;
    }
}
if (ship.cfirerate != 0) {
    ship.cfirerate = ship.cfirerate - 1;
}

cxt.beginPath();
cxt.strokeStyle="#000000";
cxt.moveTo(125+ship.x,140+ship.y);
cxt.lineTo(150+ship.x,120+ship.y);
cxt.lineTo(175+ship.x,140+ship.y);
cxt.stroke();
}
function clear() {
cxt.clearRect(0, 0, 300, 300);
}

function gameLoop() {
drawWorld();
drawShip();
drawLazers();
}

setInterval(function() {
clear();
gameLoop();
}, 30);


texts:
I'm new to JavaScript OOP and still playing around with it. I have put together a few specific questions over specific details throughout the code that are bothering me.

I wanted my Library class constructor to be optional, the option to add a single book, multiple books or none at all, when creating the  object. Is this a good way of achieving this goal?

class Library{
  constructor(items){
    this.books = [];
    if(typeof items != 'undefined' && items instanceof Array){
      this.books.push.apply(this.books, items); // Concat two arrays
    } else if(typeof items != 'undefined') {
      this.books.push(items); // Add one element
    }
  }

  checkIn(id, renter){
    var index = this.getIndex(id);
    if(!this.books[index].available){
      this.books[index].setDefaults();
      renter.removeBook(id);
    } else {
      throw "Book Already Checked In";
    }
  }

  checkOut(id, renter){
    var index = this.getIndex(id);
    if(this.books[index].available){
      this.books[index].available = false;
      this.books[index].currentRenter = renter.name;

      // Adds current date to check out information.
      var dateFormat = require('dateformat');
      this.books[index].checkOutDate = dateFormat(new Date(),  "dddd, mmmm dS, yyyy, h:MM:ss TT");

      renter.addBook(this.books[index]); // Adds book to renter's inventory.
    } else {
      throw "Book Not Available";
    }
  }

  getIndex(id){
    for(var i = 0; i < this.books.length; i++){
      if(this.books[i].id == id) return i;
    }
    return -1;
  }
}

My Book class works, but just does not feel correct at all and looks very sloppy. Any thoughts?

class Book{
  constructor(title, pageCount, id){
    this.title = title;
    this.pageCount = pageCount;
    this.id = id;
    this.available = true;
    this.currentRenter = null;
    this.checkOutDate = null;
  }

  setDefaults(){
    this.available = true;
    this.currentRenter = null;
    this.checkOutDate = null;
  }
}

These are the only classes I did not really have any questions over. I am aware splitting these classes into two is completely unnecessary in this scenario, but I was just messing around with inheritance and never changed it back.

class Person{
  constructor(name, age, phoneNumber){
    this.name = name;
    this.age = age;
    this.phoneNumber = phoneNumber;
  }
}

class Renter extends Person{
  constructor(name, age, phoneNumber, libraryID){
    super(name, age, phoneNumber)
    this.libraryID = libraryID;
    this.books = [];
  }

  addBook(book){
    this.books.push(book);
  }

  removeBook(id){
    var index = this.getIndex(id);
    this.books.splice(index, 1);
  }

  getIndex(id){
    for(var i = 0; i < this.books.length; i++){
      if(this.books[i].id == id) return i;
    }
    return -1;
  }
}

Another general question: Am I accessing the class variables "formally"? It does not feel right setting a instance variable without a setter or returning a instance variable without a getter.


texts:
Here is my implementation of a simple 3 rotor Enigma machine in C++:

#include <iostream>
#include <cstring>
using namespace std;

char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char rotors[3][27] =
{
  "EKMFLGDQVZNTOWYHXUSPAIBRCJ",
  "AJDKSIRUXBLHWTMCQGZNPYFVOE",
  "BDFHJLCPRTXVZNYEIWGAKMUSQO"
};
char reflector[] = "YRUHQSLDPXNGOKMIEBFZCWVJAT";
char key[] = "ABC";

long mod26(long a)
{
  return (a%26+26)%26;
}

int li (char l)
{
  // Letter index
  return l - 'A';
}

int indexof (char* array, int find)
{
  return strchr(array, find) - array;
}

string crypt (const char *ct)
{
  // Sets initial permutation
  int L = li(key[0]);
  int M = li(key[1]);
  int R = li(key[2]);

  string output;

  for ( int x = 0; x < strlen(ct) ; x++ ) {
    int ct_letter = li(ct[x]);

    // Step right rotor on every iteration
    R = mod26(R + 1);

    // Pass through rotors
    char a = rotors[2][mod26(R + ct_letter)];
    char b = rotors[1][mod26(M + li(a) - R)];
    char c = rotors[0][mod26(L + li(b) - M)];

    // Pass through reflector
    char ref = reflector[mod26(li(c) - L)];

    // Inverse rotor pass
    int d = mod26(indexof(rotors[0], alpha[mod26(li(ref) + L)]) - L);
    int e = mod26(indexof(rotors[1], alpha[mod26(d + M)]) - M);
    char f = alpha[mod26(indexof(rotors[2], alpha[mod26(e + R)]) - R)];

    output += f;
  }

  return output;
}

int main ()
{
  for ( int i = 0; i < 1000000; i++) {
    crypt ("PZUFWDSASJGQGNRMAEODZJXQQKHSYGVUSGSU");
  }

  return 0;
}

Benchmark ran on a 2.66ghz Core 2 Duo for 1 million decrypts:

C++ Version:

11.64s user 0.02s system 97% cpu 11.963 total

I'm not a C++ programmer, I first wrote this in Javascript and then translated it into C++.

Whilst 1 million in ~10 seconds is OK, I feel that my implementation isn't optimal. Are there any optimisations, or micro optimisations that you could recommend to my C++ code to make it faster? Maybe I should try a different language? Any suggestions are welcome.


texts: User guesses the number generated by computer

texts:
This is my code, which chooses a random number from 0 to 10 for the user to guess.
//guess the number game
//my code
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
  unsigned int secretNumber;
  int guess;
  int maxNumber = 10;
  int maxTries = 4;
  int numTries = 1;

  srand(static_cast<unsigned int>(time(0)));
  secretNumber = (rand() % 10)+ 1;
  cout << "GUESS A NUMBER FROM 0 TO 10!!\n";
    do {
      cout << "\nGuess: \n";
      cin >> guess;

      if (guess < secretNumber)
      {
          cout << "too low:(:(!!      ";
          numTries++;
          cout << "Guesses Left: " << maxTries - numTries;
      } ***//Would it be better to add a bool in the condition?***

      else if (guess > secretNumber && guess <= maxNumber)
      {
          cout << "Too high:D:D!!      ";
          numTries++;
          cout << "Guesses Left: " << maxTries - numTries;
      }

      else if (guess > maxNumber)
      {
          cout << "Do you know how to count to 10?\n";
          cout << "Only from 0 TO 10!!  ";
          numTries++;
          cout << "Guesses Left: " << maxTries - numTries;
      }

      else {
          cout << "WOW! you GUESSED IT?! AMAZING!!!!";
          cout << "You're right! the number is " << guess;
          cout << "\nYou got it right in " << numTries << " guesses!!!";
      }

      if (numTries == maxTries)
      {
          cout << "\n\nYou LOOSE :( LOL!";
      }

  } while (guess != secretNumber && maxTries != numTries);

  return 0;
}

This is the teacher's code, which is simpler and includes a bool variable. Should my previous code be simpler, just as this one?
int main()
{
  int secretNumber = 7;
  int guess;
  int numTries = 0;
  int maxTries = 3;
  bool outOfGuesses = false;

  while (secretNumber != guess && !outOfGuesses)
  {
      if (numTries != maxTries)
      {cout << "Guess a Number: ";
      cin >> guess;
      numTries++;}

      else
      {
          outOfGuesses = true;
      }
  }

  if (outOfGuesses)
  {
      cout << "You loose!";
  }
  else
  {
      cout << "You win!";
  }
  return 0;
}

Is my code as efficient and simple as the teacher's code? //Is there a simpler way to do what I intended to do in my code?


texts: Check the equality for each subset of a string S against the target T and return a count

texts:
I wrote the following code to solve this leetcode problem:

var numDistinct = function(s, t) {
    if (!s.length) return +(!t.length);
    let res = 0;
    for (let seq of subseq(s)) res += +(t===seq);
    return res;
};
var subseq = function(a) {
    if (a.length==1) return [a[0], ''];
    let subsets = subseq(a.substr(0, a.length-1));
    let n = subsets.length;
    for (let i=0; i < n; i++) {
       subsets.push(subsets[i]+a[a.length-1]);
    }
    return subsets;
};

Obviously, this code is not efficient, as it generates each of \$2^n\$ subsets of the string s and checks each one for equality against t.

I would much appreciate it if someone could explain how to improve this solution using memoization. I am aware that there is a dynamic programming solution. I am more interested in learning how to extend this easy-to-understand solution into something more efficient by using a memo table. Any and all help would be graciously appreciated.


texts: A class that represents a key combination

texts:
For a little game of mine I have created a Key.h file that should allow representation of a key press combination. A key combination is basically some key represented by its virtual key code stored in int _keyand the state of modifier keys - shift, control, alt and windows keys. In case that key combination is used for typing, the key also stores the character that it should produce in _c.

class Key
{
private:
    bool _shift;
    bool _ctrl;
    bool _alt;
    bool _win;
    int _key;
    char _c;

public:
    constexpr Key()
        :
        _shift(),
        _ctrl(),
        _alt(),
        _win(),
        _key(),
        _c()
    {}

    constexpr Key(const Key& key)
        :
        _shift(key._shift),
        _ctrl(key._ctrl),
        _alt(key._alt),
        _win(key._win),
        _key(key._key),
        _c(key._c)
    {}

    constexpr Key(bool shift, bool ctrl, bool alt, bool win, int key, char c)
        :
        _shift(shift),
        _ctrl(ctrl),
        _alt(alt),
        _win(win),
        _key(key),
        _c(c)
    {}

    Key& operator= (Key& key)
    {
        _shift = key._shift;
        _ctrl = key._ctrl;
        _alt = key._alt;
        _win = key._win;
        _key = key._key;
        _c = key._c;
    }

    bool operator== (const Key& key) const
    {
        return (_shift == key._shift && _ctrl == key._ctrl && _alt == key._alt && _win == key._win && _key == key._key, _c == key._c);
    }

    bool operator!= (const Key& key) const
    {
        return !(*this == key);
    }
};

Are there any design flaws or some obvious things that I'm missing?


texts:
Is there a better way to write this procedure?

    public List<IDenomination> GetInventory(int[] denominations)
    {
        var inventory = new List<IDenomination>();

        foreach (var denomination in denominations)
        {
            foreach (var item in Account)
            {
                if (item.Currency == denomination)
                {
                    inventory.Add(item);
                }
            }
        }

        return inventory;
    }


texts: Scraping content from a javascript enabled website with load more button

texts:
The script I've written is able to scrape name, address, phone and web address from a webpage using python and selenium. The main barrier I had to face was to exhaust the load more button to get the more content until all are displayed. I know the way I have written xpaths in the script is fragile but they serve the purpose for now. I ran my script and found the results as I expected. I hope there will be any better way to improve the design and performance of my script. Thanks in advance for taking care of it. Here is the full code:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

driver.get("https://www.zebra.com/us/en/partners/partner-application-locator.html")
driver.find_element_by_xpath('//div[@class="ft-dropdown"]/input[@placeholder="City, State/Province, Country"]').clear()
driver.find_element_by_xpath('//div[@class="ft-dropdown"]/input[@placeholder="City, State/Province, Country"]').send_keys("Colorado, USA")

wait.until(EC.visibility_of_element_located((By.XPATH, '//a[contains(@class,"ng-binding")]')))
driver.find_element_by_xpath('//a[contains(@class,"ng-binding")]').click()

while True:
    try:
        wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'showmore-bg')))
        driver.find_element_by_class_name('showmore-bg').click()
    except Exception:
        break

wait.until(EC.visibility_of_element_located((By.XPATH, '//div[contains(@class,"padding0")]')))
for items in driver.find_elements_by_xpath('//div[contains(@class,"padding0")]'):
    try:
        name = items.find_element_by_xpath('.//a[@class="ng-binding"]').text
    except Exception:
        name = ""
    try:
        address = items.find_element_by_xpath('.//div[contains(@class,"fullDetail-cmpAdres")]//p[@class="ng-binding"]').text
    except Exception:
        address = ""
    try:
        phone = items.find_element_by_xpath('.//div[contains(@class,"fullDetail-cmpAdres")]//p[contains(@class,"ng-scope")]').text
    except Exception:
        phone = ""
    try:
        website = items.find_element_by_xpath('.//a[contains(@class,"ng-scope")]').get_attribute("href")
    except Exception:
        website = ""

    print(name ,address, phone, website)

driver.quit()


texts:
I want to implement jquery.alphanumeric in HTML pattern, so I used a jQuery plugin from here. Can this be shortened or improved?

<input type="text" char-allow="$#*" class="alpha">
<input type="text" char-allow="+-" class="numeric">
<input type="text" char-allow="&" class="alphanumeric">

<script>
    function setAlphaNumeric(){
        $(".numeric").each(function(){
            var a = $(this).attr("char-allow"); $(this).numeric({allow:a});
        });
        $(".alpha").each(function(){
            var a = $(this).attr("char-allow"); $(this).alpha({allow:a});
        });
        $(".alphanumeric").each(function(){
            var a = $(this).attr("char-allow"); $(this).alphanumeric({allow:a});
        });
    }

$(function(){

setAlphaNumeric();

});
</script>


texts:
I've recently started to delve into the world of windows phone 8 dev, and as a learning experience I've decided to make a stopwatch application. Now, given I've been a web guy most of my career, I've never come across UI thread locking issues, so the solution I've come up with to ensure my stopwatch class is updating the UI thread 'correctly' is (in my opinion at least) in need of a review.

So my overall questions with the below code are;

Am I doing it "right"?  I realise that can be kind of broad; I just want to make sure I'm not committing any cardinal sins of UI development.
Are there simpler approaches to what I've done?
Are there any improvements to the code that someone would suggest? I'm not sure using thread.sleep is a good idea, but when I take it out, it ends up locking the UI thread again. Hence why I'm asking for input.

My StopWatch Class:

public class StopwatchClass : IDisposable
{
    DispatcherTimer _timer;

    public int Interval { get; set; }

    public int Seconds { get; set; }
    public int Minutes { get; set; }
    public int Hours { get; set; }

    public bool IsRunning { get { return _timer.IsEnabled; } }
    public TimeSpan Elapsed { get; set; }
    public List<TimeSpan> Splits { get; set; }

    public StopwatchClass(int interval)
    {
        this.Splits = new List<TimeSpan>();

        _timer = new DispatcherTimer();
        _timer.Interval = new TimeSpan(0, 0, interval);
        _timer.Tick += timer_Tick;
    }

    void timer_Tick(object sender, EventArgs e)
    {
        this.Seconds += 1;
        if (this.Seconds == 60)
        {
            this.Minutes += 1;
            this.Seconds = 0;
        }
        if (this.Minutes == 60)
        {
            this.Hours += 1;
            this.Minutes = 0;
        }
    }

    public void Start()
    {
        _timer.Start();
    }

    public void Stop()
    {
        _timer.Stop();

    }
    public void Reset()
    {
        _timer = new DispatcherTimer();
        this.Seconds = 0;
        this.Minutes = 0;
        this.Hours = 0;
        this.Splits.Clear();
    }

    public void Split()
    {
        var timeSpan = new TimeSpan(this.Hours, this.Minutes, this.Seconds);
        this.Splits.Add(timeSpan);
    }

    public void Dispose()
    {
        _timer.Tick -= timer_Tick;
    }
}

And the WP8 button code (secondsValue is a text block on the wp8 page).

private async void startStopwatch_Click(object sender, RoutedEventArgs e)
    {
        watch.Start();

        await Task.Factory.StartNew(() =>
        {
            while (watch.IsRunning)
            {
                Thread.Sleep(1000);
                Dispatcher.BeginInvoke(() => secondsValue.Text = watch.Seconds.ToString());
            }

        });
    }


texts: Check if the jQuery library is present locally

texts:
Q.

Basically this piece of code appears in my class constructor. It's working, but it seems very confusing.

It basically checks if the jQuery library is present locally and if it's not it will try to download it.

Is there any way I can improve this? Namely avoiding re-setting vars all the time?

CODE:

//First we check if JQuery version is correct
if ( isset($versionList->$version) ) {
    $filePathFull = __DIR__ . '/versions/jquery-' . $version . '.js';
    $filePathMin  = __DIR__ . '/versions/jquery-' . $version . '.min.js';
    $this->versionLoaded = $version;

    //Now we check if the JQuery version is installed
    if ( !file_exists($filePathFull) || !file_exists($filePathMin)) {

        // They are not installed, so we will try to download and install it
        if (!self::installVersion($version)) {
            // Download failed, so we try the defaults
            $filePathFull = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.js';
            $filePathMin = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.min.js';
            $this->versionLoaded = JQuery::DEFAULT_VERSION;
        }
    }
} else {
    //Version is incorrect we go with the defaults
    $filePathFull = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.js';
    $filePathMin = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.min.js';
    $this->versionLoaded = JQuery::DEFAULT_VERSION;
}

//This is a redundant check to see if the defaults are installed
if ( !file_exists($filePathFull) || !file_exists($filePathMin) ) {

    // They are not installed, so we will try to download and install it
    if (!self::installVersion(JQuery::DEFAULT_VERSION)) {
        //Defaults are not installed so we throw an exception
        throw new Exception("Nor the version $version or the default version " . JQuery::DEFAULT_VERSION . " could be found or downloaded");
    }
}

Edit:

MORE DETAILS

A more detailed explanation...

As you correctly assumed, this is a "plugin". The plugable system requires wrapped JavaScript libraries in PHP classes that are used for a JS Dependency Manager. The JS Dependency Manager extends Composer which constrains how we handle this a bit. We have, however, freedom to chose how we wrap the JS Library.

Goals:

Avoidance of library repetition (like having 2 versions of jQuery running which causes weird JS bugs)
Automatic update of 3rd party JavaScript (directly from the repository instead of downloading and including them directly)
Caching, Minimizing and removal of dead code from JS Scripts through Google Closure Compiler
Libraries and scripts dependency management (specially regarding specific library versions such as jquery)


texts: Sorting a long string with a composite of strings and integers + symbols

texts:
The code below is to sort a file containing the following info (eg. input.txt):

rango burrito apri%cot 1 -10 3.5 8 5 tesla 10 hyphen -4.7 2 bus 20 cat vul$ture m0nkey -9999999

The output should have the symbols removed and then strings and integers sorted in ascending order, but the order retaining the type of the original list. for example, the first item is a string in both input and output and the final item for example is an int.

When the script is run the output looks as follows:

$ ./sort_input.py input.txt
apricot burrito bus -9999999 -47 -10 1 2 cat 5 hyphen 8 10 m0nkey 20 rango tesla vulture 35

I've written code that looks as follows and I'm sure this can be improved a lot:

Reading the file first, then splitting on white space into an array of strings: \$O(n)\$ complexity where \$n\$ is the length of the original string

def listify(input_file):
    with open(input_file) as f:
        for line in f:
            list_of_strings = line.strip().split()

    return list_of_strings

Using the list of strings and converting it into a typed list, but removing any symbols first using the method below: \$O(n)\$ complexity for the typed list, then \$O(k)\$ for each string in that list to remove symbols - so total complexity is \$O(n)*O(k)\$.

def typed_list(untyped_list):
    """ converts an untyped list to a typed list of strings and integers """
    typed_list = []
    for item in untyped_list:
        item_without_symbol = remove_any_symbols(item)
        try:
            typed_list.append(int(item_without_symbol))
        except ValueError:
            typed_list.append(item_without_symbol)

    return typed_list

Method to remove any symbols, which I use in the function above. \$O(k)\$ complexity where \$k\$ is the length of the string:

def remove_any_symbols(s_string):
    """We take a string and remove any symbols from it. """
    acceptable_characters = string.ascii_letters + string.digits
    no_s_string_list = [c for c in s_string if c in acceptable_characters]
    if s_string.startswith("-"):
        return "-"+''.join(no_s_string_list)
    else:
        return ''.join(no_s_string_list)

I then use the typed list that's generated above to sort integers and strings separately. Then using the original list to generate a list with the same type items in their original order. \$O(n log n)\$ complexity for both sorting functions and then \$O(n)\$ for adding to the final output list.

def sort_em_up(no_symbol_list=None):
    """we take a list here, note the type, sort and then return a sorted
    list"""
    sorted_int = sorted([int(i) for i in no_symbol_list if isinstance(i, int)])
    sorted_str = sorted([s for s in no_symbol_list if isinstance(s, str)])
    final_sorted_list = []
    i = j = 0
    for item in no_symbol_list:
        if isinstance(item, int):
            final_sorted_list.append(str(sorted_int[i]))
            i += 1
        else:
            final_sorted_list.append(sorted_str[j])
            j += 1

    return ' '.join(final_sorted_list)

if __name__=="__main__":
    input_file = sys.argv[1]

    list_of_strings = listify(input_file)

    print(sort_em_up(typed_list(list_of_strings)))


texts: Need to condense the following into a looping function

texts:
I have the following code, which works as I need it to, however, it repeats itself over and over.

I'm relatively new to PHP and haven't grasped recursive functions yet. Which I've been told I'll need to understand as this function could potentially have many levels.

if ($_POST['parent'] == "None") {
        $parent = "";
    } else {
        $parent = $connection->real_escape_string($_POST['parent']);
    }

    if (!empty($parent)) {

        $query = $connection->query("SELECT * FROM pages WHERE filename='$parent'");

        while($row = $query->fetch_array()) {

            $path_arr = explode('/',$row['path_to']);
            end($path_arr);
            $key = key($path_arr)-1;

            $parent1 = $path_arr[$key];

            if (!empty($parent1)) {

                $query = $connection->query("SELECT * FROM pages WHERE filename='$parent1'");

                while($row = $query->fetch_array()) {

                    $path_arr = explode('/',$row['path_to']);
                    end($path_arr);
                    $key = key($path_arr)-1;

                    $parent2 = $path_arr[$key];

                    if (!empty($parent2)) {

                        $query = $connection->query("SELECT * FROM pages WHERE filename='$parent2'");

                        while($row = $query->fetch_array()) {

                            $path_arr = explode('/',$row['path_to']);
                            end($path_arr);
                            $key = key($path_arr)-1;

                            $parent3 = $path_arr[$key];

                            if (!empty($parent3)) {

                                $query = $connection->query("SELECT * FROM pages WHERE filename='$parent3'");

                                while($row = $query->fetch_array()) {

                                    $path_arr = explode('/',$row['path_to']);
                                    end($path_arr);
                                    $key = key($path_arr)-1;

                                    $parent4 = $path_arr[$key];

                                }
                            }
                        }
                    }
                }
            }
        }
    }

    $path_to = rtrim(ltrim($parent4.'/'.$parent3.'/'.$parent2.'/'.$parent1.'/'.$parent.'/'.$filename,'/'),'/');

As you can see there are minimal differences within the nested while loops, but I'm really not sure how to make the function loop for each level.

I was pointed to this, and while I understand what the factorial is, I still am unsure on how to refactor my code into a looping function.

Any pointers?

UPDATE

Certainly moving in the right direction of what I'm hoping to achieve with Simon André Forsberg's suggestion

However (I probably should have made this clearer in my explanation), The loop(s) determine whether a 'file' (a database entry, masquerading as a file) has a parent 'file', returns that parent 'file', then checks that parent 'file' for a parent 'file' and returns it and so on and so on until there are no more parents.

It is used to create a dynamic path directory.

like so /parent4/parent3/parent2/parent1/filename/

The line of code that follows the loops (again, I probably should have included this), is below...

$path_to = rtrim(ltrim($parent4.'/'.$parent3.'/'.$parent2.'/'.$parent1.'/'.$parent.'/'.$filename,'/'),'/');

So each level of the loop outputs to this string.

I have a feeling I may have to do this using palacsint's method of taking the working part of each loop and creating that as a function.

I may be wrong but could Simon's method output to an array? first parent in pos 0, second in pos 1, etc?

However, then the query would have to have the filename='$parent' updated to look at the last array entry.

$query = $connection->query("SELECT * FROM pages WHERE filename='$parent'");

Have I bitten off more than I can chew?


texts: Wrap a callback method in an awaitable method

texts:
I'm using a .NET library which uses a pre-async/await type of asynchronicity. That is, it provides asynchronous (non-awaitable) method with a callback parameter.

I'm trying to write awaitable extension methods which will wrap some of those methods to make it easier to use with the async/await fashion but I'm not sure if this is the right approach.

Here's an example of one of those methods:

public void OAuthGetRequestTokenAsync(string callbackUrl, Action<FlickrResult<OAuthRequestToken>> callback)
{
    CheckApiKey();
    string url = //...

    Dictionary<string, string> parameters = OAuthGetBasicParameters();
    // [Code to add parameters]

    FlickrResponder.GetDataResponseAsync(this, url, parameters, (r) =>
    {
        var result = new FlickrResult<OAuthRequestToken>();
        if (r.Error != null)
        {
            if (r.Error is System.Net.WebException)
            {
                var ex = new OAuthException(r.Error);
                result.Error = ex;
            }
            else
            {
                result.Error = r.Error;
            }
            callback(result);
            return;
        }
        result.Result = FlickrNet.OAuthRequestToken.ParseResponse(r.Result);
        callback(result);
    });
}

And here's what I came up with to provide an awaitable extension method which wraps the one above:

static class FlickrExtensions
{
    public static Task<OAuthRequestToken> OAuthGetRequestTokenAsync(this Flickr flickr,
                                                                    string callbackUrl)
    {
        var tcs = new TaskCompletionSource<OAuthRequestToken>();
        flickr.OAuthGetRequestTokenAsync(callbackUrl, r =>
        {
            if (r.HasError)
                tcs.TrySetException(r.Error);
            else
                tcs.TrySetResult(r.Result);
        });

        return tcs.Task;
    }

    // More extension methods to be added.
}

Are there any problems with my code or any downsides to this implementation?

Also, is there a better (more standard?) way to achieve this goal?


texts:
I have tried two different methods to find the sum of primes under a certain number. However both of these methods end up taking a very long time for large numbers. How can I optimise either of these two methods?

Method 1 (Sieve of Eratosthenes):

import time
import math

primes_in_range = [2]

n = int(input("Enter the range of your sieve"))

start = time.time()

for x in range(3, n+1, 2):
    primes_in_range.append(x)

d = 3

while d <= math.sqrt(n):
    if d in primes_in_range:
        for j in range(2 * d, n + 1, d):
            if j in primes_in_range:
                primes_in_range.remove(j)
    d += 2

print(sum(primes_in_range))
end = time.time()
print(end - start)

Method 2:

import time
import math

def is_prime(n):
  if n>1:
    for i in range (2, int(math.sqrt(n)) + 1):
      if (n % i) == 0:
        return False
    else:
      return True
  else:
    return False

n = int(input("Enter the range of your sieve"))

start = time.time()

total = 2

i = 3

while i < n:
    if is_prime(i):
        total += i
    i += 2

print(total)

end = time.time()
print(end -start)


texts: Implementing a cancellable "infinite" loop

texts:
I'm making a Windows service that watches a directory for new files to process them.

I hit a race condition between the file copying going on and me trying to process it. Going by a SO answer I wrote the following wait-and-retry method to make sure I can work with the file:

public static void WaitForFile(string file, CancellationToken token, int retryIntervalMillis = 200)
{
    while (!token.IsCancellationRequested)
    {
        try
        {
            using (new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))
                return;
        }
        catch
        {
            Thread.Sleep(retryIntervalMillis);
        }
    }

    throw new OperationCanceledException(token);
}

My question is: would this be a correct way to make this waiting cancellable? The token is cancelled to shut down the service, the idea is to allow for a clean (-ish) shutdown even in a case a bug means the file in question is inadvertently kept open indefinitely.

(Or if the reason the file can't be opened is some other, non-intermittent condition I haven't guarded against yet.)

For instance, is it okay to use the token this way in my method, and also expect the same token to cancel a BlockingCollection's consuming enumerator?

My intent is to base the service around the expectation it can be hard-crashed at any time, so I'm fine with an exception taking out most of the call stack leading to it.

Edit:

These are changes that I have since made to the code

const int ErrorSharingViolation = -2147024864;

public static FileStream WaitForFile(string file,
                                 CancellationToken token,
                                 FileMode mode = FileMode.Open,
                                 FileAccess access = FileAccess.Read,
                                 Action<Stream> action = null,
                                 int retryIntervalMillis = 200)
{
    while (!token.IsCancellationRequested)
    {
        try
        {
            var stream = File.Open(file, mode, access, FileShare.None);
            if (action != null)
            {
                using (stream)
                {
                    action(stream);
                }
            }
            return stream;
        }
        catch (IOException exception)
        {
            if (exception.HResult != ErrorSharingViolation)
            {
                throw;
            }
            else
            {
                Thread.Sleep(retryIntervalMillis);
            }
        }
    }
    throw new OperationCanceledException(token);
}


texts:
Ok, I am in a JavaScript class, and I have no desire for anyone to do my schoolwork, I have already done what I think is correct, I am just hoping someone can take a look and tell me if I am close, or right, or whatever. Any feedback appreciated.  Also, the instructor was very specific in saying that if it asks for a line of code, then just do a line of code- so if it appears things are missing that would be why.

1.Write a line of code using the Location object to return the uniform resource locator (URL) of a Web page to a variable called myWebPage.

function getLocation(){
alert(document.location);}

2.Write a line of code using the Navigator object to return the Web browser name to a variable called myBrowserName.

function getLocation(){
alert(navigator.appName);}

3.Write a line of code using the Screen object to return the height of the display screen, not including operating system features such as the Windows Taskbar, to a variable called myScreenHeight

function getLocation(){
alert("Total height is : "+screen.height);}

4.Write a line of JavaScript code using the Window object and other properties to open a new Web browser window with www.google.com displaying and no menu bar

function getWindow(){
window.open('http://www.google.com','mywindow','width=400,height=200');}

That's it! Let me know if I did anything wrong, thank you!


texts: Organizing interfaces for player movement in chess game

texts:
I'm trying to figure out how to organize interfaces in my game to make future development easier, by making my code more modular.

Notice that my Rook class implements the IPlayer interface, which will move it left and right, but not up and down (I had to add that in seperate methods). My question is, should I make an interface per method of movement that I want to do (IMoveLeft, IMoveRight, IMoveUp, IMoveDown)? This makes composing future players more modular, perhaps there is a better way.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            IPlayer bob = new Person();
            IPlayer rook = new Rook();
            List<IPlayer> iPlayerList = new List<IPlayer>();
            iPlayerList.Add(bob);
            iPlayerList.Add(rook);

            foreach (var player in iPlayerList)
            {
                player.MoveLeft(1);
                player.MoveRight(1);
            }
        }
    }

    public class Person : IPlayer
    {
        public int XDistanceFromOrigin { get; set; }

        public void MoveLeft(int distanceToMove)
        {
            XDistanceFromOrigin = XDistanceFromOrigin - 1;
        }

        public void MoveRight(int distanceToMove)
        {
            XDistanceFromOrigin = XDistanceFromOrigin + 1;
        }
    }

    interface IPlayer
    {
        void MoveLeft(int distanceToMove);
        void MoveRight(int distanceToMove);
    }

    public class Rook : IPlayer
    {
        public int XDistance { get; set; }
        public int YDistance { get; set; }

        public void MoveLeft(int distanceToMove)
        {
            XDistance = XDistance - 1;
        }

        public void MoveRight(int distanceToMove)
        {
            XDistance = XDistance + 1;
        }

        public void MoveUp(int distanceToMove)
        {
            YDistance = YDistance + 1;
        }

        public void MoveDown(int distanceToMove)
        {
            YDistance = YDistance - 1;
        }
    }
}


texts:
Below is the representation and user interface fib_sequence for generating a Fibonacci sequence:

empty_rlist = None
#Representation - start
#Constructor
def rlist(first, rest):
    return (first, rest)

#Selector
def first(s):
    return s[0]

def rest(s):
    return s[1]

#Representation - end

def fib_sequence(k):
    prev, curr = 1, 0
    def generate_sequence(prev, curr, k):
        if k == 0:
           return empty_rlist
        elif k == 1:
           return (curr, empty_rlist)
        else:
           return rlist(curr, generate_sequence(curr, prev+curr, k - 1))
    return generate_sequence(prev, curr, k)

Program output:

>python -i fibonacci_sequence.py
>>> fib_sequence(0)
>>> fib_sequence(1)
(0, None)
>>> fib_sequence(2)
(0, (1, None))
>>> fib_sequence(3)
(0, (1, (1, None)))
>>> fib_sequence(4)
(0, (1, (1, (2, None))))
>>> fib_sequence(5)
(0, (1, (1, (2, (3, None)))))

The above program provides representation as (element, restOfTheList).

We have this sequence containers in Python:

>>> tuple =  (1, 2, 3, 4)
>>> r = range(1,5)
>>> str = '1234'

Is the representation of the aforementioned Python sequence containers same as the above representation of the Fibonacci sequence abstraction?

If no, can we make the representation of the Fibonacci sequence abstraction better, basically to forward this sequence for further processing by sequence processing functions like map() filter() sum() etc.?


texts: 2-D Kalman Filtering in Python using Numpy

texts:
I am practicing Kalman filtering and wrote a short python class that uses Numpy to calculate the 2-D kalman filter for position and velocity along the X axis: assume that the object is only moving along the X-axis since it's on a flat ground.

The following code is syntactically correct and when executed looks like functionally correct.  The printed distance approaches the measured distance, since in the loop, it's assumed the object is stationary.

Please have a look at the below and let me know if it's the correct implementation of a 2-D kalman filter?

note I have set process errors and observation errors to zero for now.

import numpy as np

class KalmanFilter(object):

    def __init__(self, delta_t,
                 initial_position,
                 initial_velocity,
                 acceleration,
                 calc_error_in_position,
                 calc_error_in_velocity,
                 obs_error_in_position,
                 obs_error_in_velocity):

        self.obs_Error = 0.
        self.w = 0.
        self.q = 0.

        self.I = np.array([[1, 0], [0, 1]])
        self.A = np.array([[1, delta_t], [0, 1]])
        self.B = np.array([[.5 * (delta_t**2), delta_t]])

        self.previous_state = np.array(
            [[initial_position], [initial_velocity]])
        self.predicted_state = self._calculate_predicted_state(acceleration)

        self.measured_state = np.zeros((2, 1))

        self.previous_P = np.array([
            [calc_error_in_position**2,
                (calc_error_in_position * calc_error_in_velocity)],
            [(calc_error_in_position * calc_error_in_velocity),
             calc_error_in_velocity**2]
        ])

        self.R = np.array([
            [obs_error_in_position**2,
                (obs_error_in_position * obs_error_in_velocity)],
            [(obs_error_in_position * obs_error_in_velocity), obs_error_in_velocity**2]
        ])

    def _adjust_measured_observation(self, observed_position, observed_velocity):
        obs_X = np.array([[observed_position], [observed_velocity]])
        self.observed_state = self.I * obs_X + self.obs_Error

    def _calculate_predicted_state(self, acceleration):
        self.predicted_state = (
            self.A * self.previous_state) + (self.B * acceleration) + self.w

    def _calculate_predicted_covariance(self):
        self.P = (self.A * self.previous_P * self.A.T) + self.q

    def _update_predicted_convariance(self):
        self.previous_P = np.array(
            (self.I - (self.kalman_gain * self.I)) * self.P)

    def _calculate_kalman_gain(self):
        self.kalman_gain = (self.P * self.I.T) / \
            ((self.I * self.P * self.I.T) + self.R)

    def _calculate_current_position(self):
        self.current_state = self.previous_state + \
            (self.kalman_gain * (self.observed_state - (self.I * self.previous_state)))
        self.previous_state = np.array(self.current_state)

    def get_current_position(self, observed_position, observed_velocity, acceleration):
        self._calculate_predicted_state(acceleration)
        self._calculate_predicted_covariance()
        self._calculate_kalman_gain()
        self._adjust_measured_observation(observed_position, observed_velocity)
        self._calculate_current_position()
        self._update_predicted_convariance()

        return self.previous_state[0][0]

if __name__ == '__main__':
    kf = KalmanFilter(1, 1.5, .5, .1, .3, .4, .3, .8)
    for i in range(20):
        print(kf.get_current_position(2.5, .8, .1))


texts:
let's say I want to create a 'utils' package with several functions
working on files and folders. I want to do it once properly so I can use
them in all my personal projects without feeling to re invent the wheel
each time.
I also want to learn 2 items by the way:

exception handling, already read a lot about EAFP vs LBYL, I think       the following function suits well to EAFP.
unit tests with pytest tool, it seems simple enough to start with.

My function is:

def removeanything(src):
    """
    remove files or folders
    """
    try:
        os.remove(src)
        print('File is removed')
    except IsADirectoryError:
        shutil.rmtree(src)
        print('Folder is removed')
    except FileNotFoundError:
        print('File/folder is not existing')
    except PermissionError:
        print('Not allowed to suppress this file')

Do you have any comment to do regarding my exception handling? Did I forget one or more exceptions?

To go ahead, I have written this test function for pytest:

from pathlib import Path
import utils
#import pytest

def test_removeanything(tmp_path):
    d = tmp_path / '.tmp_dir'
    d.mkdir()
    f = d / '.tmp_file'
    f.touch()

    # Test permission
    d.chmod(mode=0o555)
    utils.removeanything(f)
    assert Path.exists(f)

    # Test file deletion
    d.chmod(mode=0o777)
    utils.removeanything(f)
    assert not Path.exists(f)

    # Test folder deletion
    utils.removeanything(d)
    assert not Path.exists(d)

As I am pretty newbie at testing, I would like to know if I include all reasonable things to assert for my function? Are there other way to do it more properly?
Is there a way to assert if expected error has been indeed raised by my function?

Thanks!


texts: Determining a value given the coordinates for numbers arranged in a triangular fashion

texts:
Numbers are being stacked in the following manner:

7
4 8
2 5 9
1 3 6 10

The x-axis is horizontal and the y-axis is vertical. With that in mind, here are a few examples of the values and their coordinates:

2, 3 (coordinate) ==> 8 (value)
2, 2 (coordinate) ==> 5 (value)

I need to write a function \$fn(x, y)\$ which accepts a coordinate \$(x, y)\$ and returns the corresponding value. \$x\$ and \$y\$ can be any value between 1 and 100000 and I can only use standard python library.

Here is my brute force-ish attempt at solving this:

import time

def profile_it(fn, *args):
    start = time.time()
    result = fn(*args)
    end = time.time()
    print('{0} --> {1} in {2}sec(s)'.format(args, result, end-start))

def answer(x, y):
    result = 0
    max_limit = 100000
    x = max(min(x, max_limit), 1)
    y = max(min(y, max_limit), 1)
    counter = 1
    not_finished = True
    while not_finished:
        x_cord = 0
        y_cord = counter + 1
        for step in xrange(counter):
            result += 1
            x_cord += 1
            y_cord -= 1
            if x == x_cord and y == y_cord:
                return str(result)
        counter += 1

if __name__ == '__main__':
    profile_it(answer, 3, 2)
    profile_it(answer, 5, 10)
    profile_it(answer, 100, 100)
    profile_it(answer, 1000, 1000)
    profile_it(answer, 10000, 10000)

The above solution works reasonably well for smaller inputs. However, it takes too long to compute the result for larger inputs as evident from the following results:

(3, 2) --> 9 in 0.0sec(s)
(5, 10) --> 96 in 0.0sec(s)
(100, 100) --> 19801 in 0.0sec(s)
(1000, 1000) --> 1998001 in 0.148000001907sec(s)
(10000, 10000) --> 199980001 in 15.5760002136sec(s)

I'm sure there is a lot of room for improvement in my code. I'm looking for pointers on what kind of an algorithm I should use to solve this problem in a quicker fashion.

Based on some reading, I've attempted to use memoization using an OrderedDict to keep track of values that were computed, so for subsequent calls, I'm not re-calculating the values from scratch. However, that increased the time to solve this by a lot so I've discarded that approach.