texts:
I wrote this code to show that my reddit post is correct.

  After the first two terms, the signs are determined as follows: If the denominator is a prime of the form 4m − 1, the sign is positive; if the denominator is a prime of the form 4m + 1, the sign is negative; for composite numbers, the sign is equal the product of the signs of its factors.

  Basically it's the harmonic series minus the non-Gaussian prime reciprocals and reciprocals which factors are an odd multiple of the non-Gaussian primes- beautifully embodying quadratic reciprocity.

This is a very, very inefficient way to calculate π. However, I believe it's the most beautiful. Which is a hard sell, because π algorithms are pretty much the most harmonious things.

This formula for π is my favorite because it clearly shows how a circle is related to the harmonic series, and how that series is related to the prime number theorem and quadratic reciprocity.
I love all algorithms for π, this is for its 'insight' it provides in relating π, primes, and quadratics.

Something to note is that swapping the logic here from n%4==1 to n%4==3 results in the sum = π/2 , and converges a bit faster.

import decimal
iters = int(input('Number of Iterations: '))
D = decimal.Decimal
decimal.getcontext().prec = 100
def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors
s = D(0)
for x in range(1, iters):
    clist = [int(i) for i in prime_factors(x)]
    plist = [n for n in clist if n%4==1]
    if len(plist)%2!=0:
        s-=1/D(x)
    else:
        s += 1/D(x)
    print(s)


texts: One instance per method call or multiple method call per instance

texts:
I have the following class designs, and I'm looking for the best practices, aligned to the OOP design principles/patterns.

The ParameterParser will be used inside a foreach block through 10 items approximately.

Any comments regarding the method body will also be appreciated, though the focus of the question is on the class design/usage.

Use the constructor to take the parameter and parse (one instance per parse)

public class ParameterParser
{
    private readonly Type _propertyType;
    private readonly string _parameter;

    public ParameterParser(Type propertyType, string parameter)
    {
        _propertyType = propertyType;
        _parameter = parameter;
    }

    public object Parse()
    {
        if (typeof(IEnumerable).IsAssignableFrom(_propertyType)
         || typeof(IEnumerable<>).IsAssignableFrom(_propertyType))
            return _parameter.Split(new[] { ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries);

        if (_propertyType.IsEnum)
            return Enum.Parse(_propertyType, _parameter);

        return Convert.ChangeType(_parameter, _propertyType);
    }
}

Parameterless constructor, multiple parsing per instance

public class ParameterParser2
{
    public object Parse(Type propertyType, string parameter)
    {
        //same code
    }
}

A helper class, static method

public class ParameterHelper
{
    public static object Parse(Type propertyType, string parameter)
    {
        //same code
    }
}

I think the first one is more likely to be the best, but I can't explain which exactly are the advantages over the others. The question is "Considering design principles, which one is the best and why? Is there any pattern which would fit the scenario?".


texts: Bash Compress Managed Directory Ignoring .git, bower_components, node_modules, etc

texts:
Fairly easy way to compress a wordpress plugin (or similar) as a zip file without including all the dependencies used to create and manage the development, but which don't belong in the final product.

#!/bin/bash
# This script zips a directory, excluding specified files, types and subdirectories.
#  while zipping the directory it excludes hidden directories and certain file types

[[ "`/usr/bin/tty`" == "not a tty" ]] && . ~/.bash_profile

DIRECTORY=$(cd `dirname $0` && pwd)

if [[ -z $1 ]]; then
  echo "Usage: managed_directory_compressor /your-directory/ zip-file-name"
else
  DIRECTORY_TO_COMPRESS=${1%/}
  ZIPPED_FILE="$2.zip"

  COMPRESS_IGNORE_FILE=("\.git" "*.zip" "*.csv" "*.json" "gulpfile.js" "*.rb" "*.bak" "*.swp" "*.back" "*.merge" "*.txt" "*.sh" "bower_components" "node_modules")
  COMPRESS_IGNORE_DIR=("bower_components" "node_modules")

  IGNORE_LIST=("*/\.*" "\.* "\/\.*"")
  if [[ -n $COMPRESS_IGNORE_FILE ]]; then
      for IGNORE_FILES in "${COMPRESS_IGNORE_FILE[@]}"; do
          IGNORE_LIST+=("$DIRECTORY_TO_COMPRESS/$IGNORE_FILES/*")
      done
      for IGNORE_DIR in "${COMPRESS_IGNORE_DIR[@]}"; do
          IGNORE_LIST+=("$DIRECTORY_TO_COMPRESS/$IGNORE_DIR/")
      done
  fi

  zip -r "$ZIPPED_FILE" "$DIRECTORY_TO_COMPRESS" -x "${IGNORE_LIST[@]}" # >/dev/null
  # echo zip -r "$ZIPPED_FILE" "$DIRECTORY_TO_COMPRESS" -x "${IGNORE_LIST[@]}" # >/dev/null
  echo $DIRECTORY_TO_COMPRESS "compressed as" $ZIPPED_FILE.
fi


texts: Check if a file path matches any of the patterns in a blacklist

texts:
I'm processing a list of files, and want to check the filenames against a list of regex, like:

IGNORE_FILES = [
    re.compile('^./Vendor.*'),
    re.compile('^./Pods.*'),
    …
]

def in_blacklist(file):
    return len(list(filter(lambda r: r.match(file) != None, IGNORE_FILES))) > 0

def in_whitelist(file):
    return SWIFT_FILE_REGEX.match(file) != None

def files():
    valid_files = []
    for root, dirs, files in os.walk('.'):
        for file in files:
            if in_whitelist(file) and not in_blacklist(root):
                valid_files.append("%s/%s" % (root, file))
    return valid_files

I'm looking for a smoother way to write:

len(list(filter(lambda r: r.match(root) != None, IGNORE_FILES))) == 0

I feel that it's not so easy to read, and especially with the list(..)


texts: Break text into letters (regular Unicode graphemes+language specific digraphs)

texts:
In English, "Sh" is two letters. In other languages it's considered a single letter. I'm trying to calculate the length of a string in a Unicode aware way, with this in mind. I'm imagining a function like

def count_letters(my_string, lang="en")

But here's how I would do that for just one language, using a library that has had no new versions since 2015, uniseg:

from uniseg.graphemecluster import grapheme_clusters

def albanian_digraphs(s, breakables):
    digraphs = ["Dh", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh"]
    digraphs += [d.lower() for d in digraphs]
    for i, breakable in enumerate(breakables):
        for first, second in digraphs:
            if s.endswith(first, 0, i) and s.startswith(second, i):
                yield 0
                break
        else:
            yield breakable

# from https://sq.wiktionary.org/wiki/Speciale:PrefixIndex?prefix=dh
for text in ('dhallanik', 'dhelpëror', 'dhembshurisht', 'dhevështrues', 'dhimbshëm', 'dhjamosje', 'dhjetëballësh', 'dhjetëminutësh', 'dhogaç', 'dhogiç', 'dhomë-muze', 'dhuratë', 'dhëmbinxhi', 'dhëmbçoj', 'dhëmbëkatarosh'):
    print(list(grapheme_clusters(text, albanian_digraphs)))

#['dh', 'a', 'll', 'a', 'n', 'i', 'k']
#['dh', 'e', 'l', 'p', 'ë', 'r', 'o', 'r']
#['dh', 'e', 'm', 'b', 'sh', 'u', 'r', 'i', 'sh', 't']
#['dh', 'e', 'v', 'ë', 'sh', 't', 'r', 'u', 'e', 's']
#['dh', 'i', 'm', 'b', 'sh', 'ë', 'm']
#['dh', 'j', 'a', 'm', 'o', 's', 'j', 'e']
#['dh', 'j', 'e', 't', 'ë', 'b', 'a', 'll', 'ë', 'sh']
#['dh', 'j', 'e', 't', 'ë', 'm', 'i', 'n', 'u', 't', 'ë', 'sh']
#['dh', 'o', 'g', 'a', 'ç']
#['dh', 'o', 'g', 'i', 'ç']
#['dh', 'o', 'm', 'ë', '-', 'm', 'u', 'z', 'e']
#['dh', 'u', 'r', 'a', 't', 'ë']
#['dh', 'ë', 'm', 'b', 'i', 'n', 'xh', 'i']
#['dh', 'ë', 'm', 'b', 'ç', 'o', 'j']
#['dh', 'ë', 'm', 'b', 'ë', 'k', 'a', 't', 'a', 'r', 'o', 'sh']


texts: Find the smallest number of square numbers to create n

texts:
An interview question I got -

Given int n, find the smallest number of square numbers that fit inside n.

Example:

Input: 24
Output: 3 (16 + 4 + 4)

Input: 10
Output: 2 (9 + 1)

Solution:

public class Solution{
    public static int solution(int number){
        int squareCount = 0;
        while(number> 0){
            int square = (int)Math.sqrt(number);
            squareCount++;
            number-=square*square;
        }
        return squareCount;
    }
}

Notes:

Must be Java 7
Must be in class called Solution, with a public static int solution(int number) method
Must not use any 3rd party libraries

I like this solution because it is very simple, however it does have one inefficiency. It finds the square root only to perform a squaring operation again. It would be nice if I could find the largest square number in squared form immediately, but I cant think of an efficient way to do this.


texts:
I want to create a monad which will prevent more than 10 instances of recursion (which I am implementing by preventing more than 10 instances of >>=). My >>= definition seems kind of long and messy though, so I am wondering if there is a better way to do it.

I am including a factorial function which uses this monad as an example of how it could be used.

import Control.Monad.State
type LimitState a = (State Int (Either String a))
newtype Limiter a = Limiter {getState :: (LimitState a)}

instance Monad Limiter where
    return x = Limiter $ return $ Right x
    (Limiter state) >>= f = Limiter $
        do
            increment
            newCount <- get
            if newCount >= 10
                then return $ Left "too many recursions"
                else getNextValue
        where
            increment = do
                count <- get
                put (count + 1)
            getNextValue = do
                value <- state
                getState $ case value of
                    (Left message) -> Limiter $ return $ Left message
                    (Right v) -> f v

limitedFactorial :: Int -> Limiter Int
limitedFactorial 1 = return 1
limitedFactorial n = do
    recursive <- limitedFactorial (n - 1)
    return $ n * recursive

testLimitedFactorial =
    let (aValue, _) = runState (getState $ limitedFactorial 5) 0
        (uValue, _) = runState (getState $ limitedFactorial 11) 0
    in print aValue >> print uValue


texts: Checking to see if an area of the screen changes

texts:
I'm testing some methods for checking if an area of the screen changes, can you see any problems with how I'm doing this, and is there a better way for me to do this?

the _memoryImage2 will not change in the final app, it will be a read only array that I will check the memoryImage against.

namespace ScreenShot_BoundsTest
{
    public partial class Form1 : Form
    {
        Bitmap _memoryImage1;
        Bitmap _memoryImage2;

        Color[,] _first;
        Color[,] _second;

        private string _valueX;

        public Form1()
        {
            InitializeComponent();
        }

        private void Button1Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void GetImage()
        {
            _memoryImage2 = _memoryImage1;
            CaptureScreen();
            pictureBox2.Image = pictureBox1.Image;
            if (_memoryImage1 != null) _first = Bitmap2Imagearray(_memoryImage1);

            pictureBox1.Image = _memoryImage1;
            if (_memoryImage2 != null) _second = Bitmap2Imagearray(_memoryImage2);

            var x = CompareArrays();

            _valueX = x != true ? "false" : "true";
        }

        private bool CompareArrays()
        {
            for (var i = 0; i < _memoryImage1.Width; i++)
            {
                for (var j = 0; j < _memoryImage1.Height; j++)
                {
                    if (_first == null) continue;
                    if (_second != null)
                        if (_first[i,j] != _second[i,j])
                        {
                            return false;
                        }
                }
            }
            return _first != null && _second != null;
        }

        private void CaptureScreen()
        {
            Size s;
            using (var myGraphics = CreateGraphics())
            {
                s = new Size(100, 50);
                _memoryImage1 = new Bitmap(s.Width, s.Height, myGraphics);
            }

            var memoryGraphics = Graphics.FromImage(_memoryImage1);
            memoryGraphics.CopyFromScreen(100, 100, 10, 10, s);
        }

        private static Color[,] Bitmap2Imagearray(Bitmap b)
        {
            var imgArray = new Color[b.Width, b.Height];
            for (var y = 0; y < b.Height; y++)
            {
                for (var x = 0; x < b.Width; x++)
                {
                    imgArray[x, y] = b.GetPixel(x, y);
                }
            }
            return imgArray;
        }

        private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {
            GetImage();
            Thread.Sleep(100);
        }

        private void BackgroundWorker1RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            label1.Text = _valueX;
            backgroundWorker1.RunWorkerAsync();
        }
    }
}


texts: Recursive right-to-left segmenting (tokenizing) of strings in Python

texts:
I want to segment a list of strings based on a custom list of words/forms, from right-to-left. Here I've illustrated it with made-up English examples, but the point is to segment/tokenize using a custom list of forms. (I was also wondering whether I could/should use NLTK tokenize for this, but it looked like that might be too complex for this use case).

What would be a good Pythonic way to do this (readable and efficient)? I managed to get something working, but I don't have much experience and I'm curious how this can be improved. The code below uses a recursive function to keep splitting the left element where possible, and a $ anchor in the regular expression to match the morphs only in string-final position.

phrases = ['greenhouse', 'flowering plants', 'ecosystemcollapse']
morphs = ['house', 'flower', 'system', 'collapse']

def segment(text):
    segmented_text = [match for match in re.split('(' + '|'.join(morphs) + ')' + '$', text) if match]
    if len(segmented_text) == 2:
        segmented_morphs.insert(0, segmented_text[1])
        segment(segmented_text[0])
    else:
        segmented_morphs.insert(0, segmented_text[0])

for phrase in phrases:
    segmented_morphs = []
    words = phrase.split()
    for word in reversed(words):
        segment(word)
    print(segmented_morphs)

Result (as desired):

['green', 'house']
['flowering', 'plants'] # here 'flower' should not be segmented
['eco', 'system', 'collapse']


texts:
So i'm using this for pooling my gameObjects in game. Every other script can ask for a pooled GameObject using  GetElementFromPool and normaly i'm using return to pool when GameObject is disabled.

My doubts:
1: I'm taking the last gameObject from the List<GameObject> since the list have an array in ts implementation, so taking the last object will avoid shifts i suppose. am i right?

2: Can i avoid renaming the Instantiated GameObject in Unity? Instantiate will name it "name(Clone)"

3: Of course any other suggestion is welcome

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolSystem : MonoBehaviour
{

    public static Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>();

    #region cached
    private static GameObject lastReturned;
    #endregion

    public static GameObject GetElementFromPool(GameObject g)
    {
        if (!pool.ContainsKey(g.name))
        {
            lastReturned = Instantiate(g) as GameObject;
            pool.Add(g.name, new List<GameObject>());
            lastReturned.name = g.name;
            return lastReturned;
        }

        if (pool[g.name].Count == 0)
        {
            lastReturned = Instantiate(g) as GameObject;
            lastReturned.name = g.name;
        }
        else
        {
            lastReturned = pool[g.name][pool[g.name].Count - 1];
            pool[g.name].RemoveAt(pool[g.name].Count - 1);
        }

        return lastReturned;
    }

    public static void AddToPool(GameObject g)
    {

        if (!pool.ContainsKey(g.name))
        {
            pool.Add(g.name, new List<GameObject>());
        }
        pool[g.name].Add(g);

    }

}

Reviewed version:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolSystem : MonoBehaviour
{
    public static Dictionary<string, Stack<GameObject>> pool = new Dictionary<string, Stack<GameObject>>();

    #region cached
    private static GameObject lastReturned;
    private static Stack<GameObject> lastUsedStack;
    #endregion

    public static GameObject GetElementFromPool(GameObject g)
    {
        if (pool.TryGetValue(g.name, out lastUsedStack))
        {
            if (pool[g.name].Count == 0)
            {
                lastReturned = Instantiate(g) as GameObject;
                lastReturned.name = g.name;
            }
            else
            {
                lastReturned = pool[g.name].Pop();
            }
        }
        else
        {
            lastReturned = Instantiate(g) as GameObject;
            pool.Add(g.name, new Stack<GameObject>());
            lastReturned.name = g.name;
            return lastReturned;
        }

        return lastReturned;
    }

    public static void AddToPool(GameObject g)
    {
        if (!pool.ContainsKey(g.name))
        {
            pool.Add(g.name, new Stack<GameObject>());
        }
        pool[g.name].Push(g);
    }

}


texts:
I made a simple linked list in C with the following functionalities:
Create(creates the list); Find(searches for an element in the list); Insert(inserts a value at the beginning of the list); Destroy(destroys the entire list). It only uses integers (for simplicity), and I want to know for possible errors and how to improve it in general.

The node structure:

typedef struct sllist
{
    int val;
    struct sllist* next;
}
sllnode;

The functions:

#include <stdio.h>
#include <stdlib.h>
#include "node.c"

/*
 *Creates the linked list with a single value
*/
sllnode *create(int value)
{
    sllnode *node;
    node = (sllnode *) malloc(sizeof(sllnode));

    if (node == NULL)
    {
        puts("Memory error");
        return NULL;
    }

    node->val = value;
    node->next = NULL;

    return node;
}

/*
 *Searches for an element in the list.
 *Returns 1 if its found or 0 if not
*/
int find(sllnode *head, int value)
{
    sllnode *trav = head;

    do
    {
        if (trav->val == value)
        {
            return 1;
        }
        else
        {
            trav = trav->next;
        }
    } while (trav != NULL);

    return 0;
}

/*
 *Inserts a value at the beginning of the list
*/
sllnode *insert(sllnode *head, int value)
{
    sllnode *new_node = (sllnode *) malloc(sizeof(sllnode));

    if (new_node == NULL)
    {
        puts("Memory error");
        return NULL;
    }

    new_node->val = value;
    new_node->next = head;
    head = new_node;

    return head;
}

/*
 *Destroys (i.e frees) the whole list
*/
void *destroy(sllnode *head)
{
    sllnode *temp = head;

    while (temp != NULL)
    {
        free(temp);
        temp = temp->next;
    }
    free(head);
}

int main(void)
{
    return 0;
}


texts: Fetching specific records in a RESTful application

texts:
Basically what I'm trying to achieve here is I need to fetch a set of images based on the selected folder. Is this a correct way to do it?

I'm using ZF 2.5, and have the following function in my RESTful Images controller:

public function getList()
{
        $folder_id = $this->params()->fromQuery('folder_id', 0);
        $images = $this->ImagesTable->getImages($folder_id);

         // Code for returning response
 }

This is what my table function looks like:

public function getImages($folder_id)
{
        $select = $this->tableGateway->getSql()->select();

        if(!empty($folder_id)) {
            $select->where(array('folder_id' => $folder_id));
        }

        $resultSet = $this->tableGateway->selectWith($select);

        return $resultSet->count() > 0 ? $resultSet : null;
 }


texts:
I recently did a programming challenge: given a positive number find the next palindromic number. In PHP, I decided to do something like this:

<?php

function palindromic($input) {
  while (1) {
    $number = (string) ++$input;

    if ($number == strrev($number)) {
      return $number;
    }
  }
}

I was then asked to provide test inputs for the function and to explain why, so I had (where x is a random number)

x < 10: test single digits
10 < x < 100: tests numbers with even length
100 < x < 1000: tests numbers with odd lengths
1,000,000 < x: tests a largish number

Note: we can always assume a positive number, so checking for non-positive numbers or inputs that are a different type, or asserting exceptions thrown back, etc aren't relevant to the challenge.

Apparently there were some other important numbers to test, can anyone explain what I've missed here?


texts: Approximating π via Monte Carlo simulation

texts:
Inspired by a tweet linked to me by a friend and a Haskell implementation by her for the same problem, I decided to try my hand at approximating the value of π using everything in the Haskell standard library I could find for the job. Here’s what I came up with:

module Pi where

import Data.List (genericLength)
import Control.Arrow (Arrow, (<<<), (***), arr)
import System.Random (newStdGen, randoms)

type Point a = (a, a)

chunk2 :: [a] -> [(a, a)]
chunk2 []      = []
chunk2 [_]     = error "list of uneven length"
chunk2 (x:y:r) = (x, y) : chunk2 r

both :: Arrow arr => arr a b -> arr (a, a) (b, b)
both f = f *** f

unsplit :: Arrow arr => (a -> b -> c) -> arr (a, b) c
unsplit = arr . uncurry

randomFloats :: IO [Float]
randomFloats = randoms <$> newStdGen

randomPoints :: IO [Point Float]
randomPoints = chunk2 <$> randomFloats

isInUnitCircle :: (Floating a, Ord a) => Point a -> Bool
isInUnitCircle (x, y) = x' + y' < 0.25
  where x' = (x - 0.5) ** 2
        y' = (y - 0.5) ** 2

lengthRatio :: (Fractional c) => [b] -> [b] -> c
lengthRatio = curry (unsplit (/) <<< both genericLength)

approximatePi :: [Point Float] -> Float
approximatePi points = circleRatio * 4.0
  where circlePoints = filter isInUnitCircle points
        circleRatio = circlePoints `lengthRatio` points

main :: IO ()
main = do
  putStrLn "How many points do you want to generate to approximate π?"
  numPoints <- read <$> getLine
  points <- take numPoints <$> randomPoints
  print $ approximatePi points

I’m interested in a general review, but I’m especially curious about my use of arrows: is there a better way to write lengthRatio? Are anything like both and unsplit provided anywhere in the standard library? If not, do any packages help?


texts: 73 Lines of Mayhem - Parse, Sort and Save to CSV in PHP CLI

texts:
Inside of a folder named txt I have 138 text files (totaling 349MB) full of email addresses. I have no idea (yet) how many addresses there are. They are separated from one another by line breaks. I created the following script to read all of these files into an array, dismiss the duplicates, then sort alphabetically and save in groups of 10K per csv file. It works correctly, but it has also been running for over 8 hours (dual core i3 w/ 4 gigabizzles of ram, sata 7200 hdd) which seems excessive to me. Top also tells me that my program's CPU usage is 100% and it's been like that the whole while it's been running. Give my script a looksie and advise me on where I've gone so terribly wrong.

function writeFile($fileName, $fileData)
{

    $writeFileOpen = fopen('csv/' . $fileName, 'w');
    fwrite($writeFileOpen, $fileData) or die('Unable to write file: ' . $fileName);
    fclose($writeFileOpen);

}

function openFiles()
{

    $addressList = array();
    $preventRepeat = array();

    if ($handle = opendir('txt')) {
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $newList = explode("\n", trim(file_get_contents('txt/' . $file)));
                foreach ($newList as $key => $val) {
                    $val = str_replace(array(',', '"'), '', $val);
                    if (in_array($val, $preventRepeat) || !strpos($val, '@') || !$val) {
                        unset($newList[$key]);
                    }
                    $preventRepeat[] = $val;
                }
                if (empty($addressList)) {
                    $addressList = $newList;
                } else {
                    $addressList = array_merge($addressList, $newList);
                }
                unset($newList);
            }
        }
        closedir($handle);
    } else {
        echo 'Unable to Read Directory';
    }

    $lineNum = 1;
    $fileNum = 1;
    $fileData = '"Email Address"' . "\n";

    sort($addressList);

    $lastKey = count($addressList) - 1;

    foreach ($addressList as $key => $val) {

        if ($lineNum > 10000) {

            writeFile('emailList-' . $fileNum . '.csv', trim($fileData));

            $lineNum = 1;
            $fileNum++;
            $fileData = '"Email Address"' . "\n";

        } elseif ($key == $lastKey) {

            writeFile('emailList-' . $fileNum . '.csv', trim($fileData));

            echo 'Complete';

        }

        $fileData .= '"' . trim($val) . '"' . "\n";
        $lineNum++;

    }

}

openFiles();

PS. I wrote this script in haste to accomplish a task. I can understand if you wouldn't consider this script distribution worthy.

EDIT: So I arrived at work today to find my script at some point exceeded 536MB of memory and quit on fatal error. I had already increased my ini file's memory_limit parameter from 128MB to 512MB. This doesn't necessarily reflect an issue with the script itself. I just wanted to share my frustration with the task.


texts: Dijkstra implementation for large graphs

texts:
I am implementing the Dijkstra algorithm for a large graph (40k nodes, 100k arcs). For shorter paths the searchtime is under a second for larger ones (from one end to the other) it takes quite some minutes to do it. I am also drawing the path after the search, so I am using some Qt objects. How could I make it faster? I feel like I am losing time when I search the neighbors because of the map structure.

This is the class:

class PathFinder {
public:
   void findPath2(const Node & start, Node & finish);

   static PathFinder& getInstance();
   PathFinder();
   PathFinder(Gps gps);
   ~PathFinder();

   unsigned int* getPrev() const;
   void setPrev(unsigned int* prev);
   QVector<unsigned int> makePath(int target);

   GraphicNode* getTo();
   GraphicNode* getFrom();

   void setTo(GraphicNode* node);
   void setFrom(GraphicNode* node);

   class Compare
   {
   public:
      bool operator() (std::pair<Node*, int> a, std::pair<Node*, int> b)
      {
         return a.second > b.second;
      }
   };

private:
   static PathFinder* _pathfinder;
   Gps _gps;
   GraphicNode* _from;
   GraphicNode* _to;

   unsigned int* _prev;
   unsigned int* _dist;
   unsigned int _notVisited;

   bool selectedNode = false;

   Node* getMinNode();
   bool hasNotVisited();
};

This is the search function:

void PathFinder::findPath2(const Node& start, Node& finish)
{
   QVector<Node> nodes=_gps.graph().nodes();

   std::priority_queue<std::pair<Node*,int>,std::vector<std::pair<Node*, int>>,Compare> q;

   _dist[start.id()] = 0;
   for (int i = 0; i < nodes.size(); i++) {
      std::pair<Node*, int> p = std::make_pair(const_cast<Node*>(&nodes.at(i)), _dist[i]);
      q.push(p);
   }

   while (!q.empty()) {
      std::pair<Node*, int> top = q.top();
      q.pop();
      Node* minNode = top.first;
      QMap<Node*, unsigned short> nextNodes = minNode->nextNodes();

      if (*minNode == finish) {
         return;
      }
      int minNodeId = minNode->id();
      for (QMap<Node*, unsigned short>::iterator iterator=nextNodes.begin(); iterator != nextNodes.end(); iterator++) {
         Node* nextNode = iterator.key();
         int altDist = _dist[minNodeId] + nextNodes.value(nextNode);
         int nextNodeId = nextNode->id();
         if (altDist < _dist[nextNodeId]) {
            _dist[nextNodeId] = altDist;
            _prev[nextNodeId] = minNodeId;
            std::pair<Node*, int> p = std::make_pair(nextNode, _dist[nextNodeId]);
            q.push(p);
         }
      }
   }
}

This is the structure of the node, it contains a map to its neighbors with the weight as the value (x and y are coordinates for drawing it later on, don't mind those):

class Node {
private:
   unsigned short _id;
   double _y;
   double _x;
   QMap<Node*, unsigned short> _nextNodes;
   bool _visited = false;

public:
   Node();
   Node(unsigned short id, double longitude, double latitude);

   unsigned short id() const;
   double y() const;
   void setY(double y);
   double x() const;
   void setX(double x);

   bool operator==(const Node& other);
   void addNextNode(Node* node, unsigned short length);

   QMap<Node*, unsigned short> nextNodes() const;
};


texts: Xamarin.Forms Use Plugin or DependencyService

texts:
I am working on Xamarin forms project that targets three platforms (Android, iOS, UWP), and I was wondering which better to use Plugins or it's better to use DependencyService

https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/introduction/

if my Example I need to retrieve some data from each platform like Version, DeviceName, OS ...etc

I created interface

public interface IAppVersion
    {
        string GetAppVersion();
        string GetDeviceName();
        string GetOS();
        string MailEOL();
        int GetOSMajorVersion();
    }

and start to implement my interface in each platform

[assembly: Dependency(typeof(VersionDroid))]
namespace CrewBriefingForms.Droid
{
    public class VersionDroid : IAppVersion
    {
        public static bool FormsInitialized = false;
        public string GetAppVersion()
        {
            Context context = Forms.Context;
            string version = context.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName;
            return version;
        }

        public string GetDeviceName()
        {
            return Build.Model;
        }

        public string GetOS()
        {
            return "Android SDK: " + Build.VERSION.Sdk + " " + Build.VERSION.SdkInt.ToString();
        }

        public int GetOSMajorVersion()
        {
            return (int)Build.VERSION.SdkInt;
        }

        public string MailEOL()
        {
            return System.Environment.NewLine;
        }
    }
}

what I find plugin do the same job, should I go for using a plugin or implement my own code

and one more question according to code review should I create many interfaces as my interface name called Version and I ask for more than the version


texts: Check for boolean values in an object and convert them to numbers

texts:
I have got a an object that has values true and false for certain keys.I need to find which keys has got a boolean value and convert them to 1 and 0 respectively.Please find the code below.I wanted  to check for keys in an object that has got boolean values and then convert them to numbers.Im a noob in Javascript and i got some help from fellow programmers in SO.This works but im sure there is a better way of doing this.

    var obj ={
    "label":'test',
    "tel":123456,
    "settings": {
      "playback": false,
      "attachfile": true,
    },
    "setTime":true,
    "setDay":false,
    "arrSettings" :[
        'Testing',
        {"playback": false,"attachfile": true},
        {"playback": false,"attachfile": true},
        123456789
    ]
}

function changeBooleanToNumber(o){

    for(var key in o){

        if(/^boolean$/i.test(typeof o[key])){
            o[key] = Number(o[key]);
        }

        if (Object.prototype.toString.call(o[key]) === '[object Object]'){

           changeBooleanToNumber(o[key]);

        }
        else if( Object.prototype.toString.call( o[key]) === '[object Array]' ) {

            for(var i=0;i<=o[key].length-1;i++){

                if(Object.prototype.toString.call(o[key][i]) === '[object Object]'){
                     changeBooleanToNumber(o[key]);
                }

            }

        }

   }
}

changeBooleanToNumber(obj);


texts:
I'm normally a C# developer, but I've started to learn F# and I want to make sure I'm writing code in a functional way that suits the language. I've quickly pieced this together with my knowledge from reading Functional Programming for the Real World and various material from the Web.

Please look and provide feedback on style, layout or anything you want (Program.fs is where the meat is):

// DataUtils.fs
module DataUtils

open System.IO
open System.Runtime.Serialization.Json
open System.Text

let GetJsonFromObject<'T> (obj:'T) =
    use ms = new MemoryStream()
    (new DataContractJsonSerializer(typeof<'T>)).WriteObject(ms, obj)
    Encoding.Default.GetString(ms.ToArray())

let GetObjectFromJson<'T> (json:string) : 'T =
    use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(json))
    let obj = (new DataContractJsonSerializer(typeof<'T>)).ReadObject(ms)
    obj :?> 'T

// Web.fs
module Web

open System
open System.Net
open System.IO

let GetJsonFromWebRequest url =

    let req = WebRequest.Create(new Uri(url)) :?> HttpWebRequest
    req.ContentType <- "application/json"

    let res = req.GetResponse () :?> HttpWebResponse
    use stream = res.GetResponseStream()
    use sr = new StreamReader(stream)
    let data = sr.ReadToEnd()
    data

// Model.fs
module Model

open System.Runtime.Serialization

[<DataContract>]
type exchangeRate = {
    [<field: DataMember(Name = "to")>]
    toCurrency:string;
    [<field: DataMember(Name = "rate")>]
    rate:decimal;
    [<field: DataMember(Name = "from")>]
    fromCurrency:string }

// Program.fs
module Program

open System
open Model

let getExchangeRate fromCurrency toCurrency =
    let url = String.Format("http://rate-exchange.appspot.com/currency?from={0}&to={1}", fromCurrency, toCurrency)
    let json = Web.GetJsonFromWebRequest url
    let rate:exchangeRate = DataUtils.GetObjectFromJson json
    rate

let rec displayExchangeRate currencies =
    match currencies with
    | [] -> []
    | (a, b)::tl ->
        let r = getExchangeRate a b
        printfn "%s -> %s = %A" a b r.rate
        displayExchangeRate tl

let currencies = [
    ("GBP", "EUR")
    ("GBP", "USD")
    ("EUR", "GBP")
    ("EUR", "USD")
    ("USD", "GBP")
    ("USD", "EUR") ]

displayExchangeRate currencies |> ignore

printfn "Press any key to exit"
let input = Console.ReadKey()

As you can see it's not doing an awful lot at the moment, just getting some exchange rates from a REST service and displaying them. The next step would be to add exchange rates to the database. I'd normally use Entity Framework for this, but given that Functional Programming is partly about reducing the amount of state that is held, is EF even the way to go?


texts: Helper methods for working with the WPF Dispatcher

texts:
I've written the following small helper class for use in my WPF applications. It comes up from time to time that I need to display message boxes, or otherwise interact with the UI from a non UI thread.

public static class ThreadContext
{
    public static InvokeOnUiThread(Action action)
    {
        if (Application.Current.Dispatcher.CheckAccess())
        {
            action();
        }
        else
        {
            Application.Current.Dispatcher.Invoke(action);
        }
    }

    public static BeginInvokeOnUiThread(Action action)
    {
        if (Application.Current.Dispatcher.CheckAccess())
        {
            action();
        }
        else
        {
            Application.Current.Dispatcher.BeginInvoke(action);
        }
    }
}

Here is a small example of how this might be used.

public static MyFunction()
{
    ThreadContext.InvokeOnUiThread(
        delegate()
        {
            MessageBox.Show("Hello world!");
        });
}

This works, but declaring the delegate the way I do seems overly verbose.

Is there anyway to make the syntax less verbose while still allowing for arbitrary functions to be passed? Is there anything else that you would suggest to improve this solution -- including an entirely different solution?


texts:
I figured it's about time to jump into some Haskell, so here's a first attempt at an oddly specific SVG parser:

import System.Environment
import Text.ParserCombinators.Parsec

parseFile fname = parseFromFile (manyTill (try tag) (try readEnd)) fname

tag = do manyTill anyChar . try $ lookAhead tagStart
         char '<'
         name <- many $ noneOf " "
         props <- tagContents
         char '>'
         junk
         return (name, props)

tagContents = do props <- manyTill property . try . lookAhead $ char '>'
                 junk
                 return props

property = do spaces
              name <- many1 $ noneOf "="
              string "=\""
              val <- manyTill anyChar $ char '"'
              junk
              return (name, val)

junk = optional . many $ oneOf "\n\r\t\\/"

readEnd = do optional $ string "</svg>"
             junk
             eof
tagStart = do char '<'
              tagName

tagName = string "rect"
          <|> string "polygon"
          <|> string "polyline"
          <|> string "circle"
          <|> string "path"
          <|> string "g"
          <|> string "svg"

Before anyone asks, one of the objectives for this program (other than learning) is that it should accept invalid SVGs (for example, a partial SVG or one that has been saved as an rtf), which is why I'm making liberal use of try, and cherry-picking tags.

As implied by the title, this is my first non-tutorial attempt at Haskell, so give me all the style pointers you can muster (and highlight anything that signals a broken understanding on my part).

I'd also appreciate pointers on how to cherry-pick properties (and not just tags). I've tried writing property as

property = do manyTill anyChar . try $ lookAhead tagName
              name <- many1 $ noneOf "="
              string "=\""
              val <- manyTill anyChar $ char '"'
              junk
              return (name, val)

and defining propName as

propName = string "points"
           <|> string "x"
           <|> string "y"
           <|> string "r"
           <|> string "d"
           <|> string "cx"
           <|> string "cy"
           <|> string "width"
           <|> string "height"
           <|> string "transform"

This seems like it should work since it's basically how I got tag jumping to the next desired tag, but it gives me unexpected input errors.

Edit The Second:

import System.Environment
import Text.ParserCombinators.Parsec

type TagName = String
type Property = (PropName, Value)
type PropName = String
type Value = String

parseFile fname = parseFromFile (manyTill (try tag) (try readEnd)) fname

tag :: GenParser Char st (TagName, [Property])
tag = do manyTill anyChar . try $ lookAhead tagStart
         name <- tagStart
         props <- tagContents
         char '>'
         junk
         return (name, props)

tagContents :: GenParser Char st [Property]
tagContents = do props <- manyTill property . try . lookAhead $ char '>'
                 junk
                 return props

property :: GenParser Char st (PropName, Value)
property = do manyTill anyChar . try $ lookAhead propName
              name <- many1 $ noneOf "="
              string "=\""
              val <- manyTill anyChar $ char '"'
              junk
              return (name, val)

junk = many $ oneOf "\n\r\t\\/{} "

tagStart :: GenParser Char st TagName
tagStart = do char '<'
              name <- tagName
              return name

readEnd = do optional $ string "</svg>"
             junk
             eof

tagName = oneStringOf ["rect", "polygon", "polyline", "circle", "path", "g", "svg"]
propName = oneStringOf ["points", "x", "y", "r", "d", "cx", "cy", "width", "height", "transform"]

oneStringOf :: [String] -> GenParser Char st String
oneStringOf = choice . map (try . string)

Added try to the definition of oneStringOf


texts: Passing data from one promise to another using then

texts:
I'm trying to get an object with ratings and titles properties:
{
  ratings: [3, 5],
  titles: ['Movie1', 'Movie2']
}

from the following two functions:
const getMovies = () => {
  return new Promise((resolve) => {
    resolve([
      {
        movieId: 1,
        rating: 3
      },
      {
        movieId: 2,
        rating: 5
      }
    ]);
  });
};

const getTitle = (movieId) => {
  return new Promise((resolve, reject) => {
    switch (movieId) {
      case 1:
        resolve({ title: "Movie1" });
        break;
      case 2:
        resolve({ title: "Movie2" });
        break;
      default:
        reject(new Error("404 - movie not found"));
    }
  });
};

I'm avoiding async/await, so trying to get that result using then.
Here is my approach:
const result = {}

getMovies()
  .then((movies) => {
    result.ratings = movies.map(({rating}) => rating)
    return Promise.all(movies.map(({ movieId }) => getTitle(movieId)));
  })
  .then((titles) => {
    result.titles = titles.map(({title}) => title)
    console.log(result)
  })
  .catch(console.log)

Can I do this in a better way withou having to nest then inside then? I don't like the use of a external variable to gather my result, but I don't like the nested thens in this other approach:
getMovies()
  .then((movies) => {
    Promise.all(movies.map(({ movieId }) => getTitle(movieId)))
      .then((titles) => {
        console.log({
          ratings: movies.map(({rating}) => rating),
          titles: titles.map(({title}) => title),
        })
      })
      .catch(console.log)
  })
  .catch(console.log)

How can I improve this using then and not async/await?


texts: Reuse MongoDB connection in Express application

texts:
So I think the title is pretty straightforward. I implement a client for MongoDB and I want to include it anywhere in my app and share the connection (not create it always or close it always).

So my question is, what are the downsides of this implementation? I've noticed that if I don't explicitly call disconnect the app never finishes / closes. Am I doing something wrong here? What are your suggestions to increase the re-usability and quality of my code? Thanks!

const mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient,
    dbName = 'ppl',
    collection = 'pp',
    mongoUrl = `mongodb://ip-and-port/${dbName}`;
let db;

class Mongo {
    static connect() {
        return new Promise((resolve, reject) => {
            MongoClient.connect(mongoUrl, (err, database) => {
                if (err) { reject(err); }
                db = database;
                resolve();
            });
        });
    }

    static disconnect() {
        return new Promise((resolve, reject) => {
            try {
                db.close();
                resolve();
            } catch (error) {
                reject(error);
            }
        })
    }

    static insertMany(data) {
        return new Promise((resolve, reject) => {
            try {
                const col = db.collection(collection);
                col.insertMany(data, (err, returns) => {
                    resolve({
                        err,
                        results: returns.insertedCount
                    });
                });
            } catch (error) {
                reject(error);
            }
        });
    }
}


texts:
So I have encountered a problem with asking user for input to be exact what is the best way to ask yes/no, for example accepting y / n and why is if i == no or i == c_n:  not working? What are other mistakes or bad practices that I'm doing here?
i = input('yes/no: ')
success = "Success"
exit = "EXIT"
error = 'ERROR'
yes = 'yes'
c_y = 'y'
c_n = 'n'
no = 'no'

if i.lower().strip() == yes:

    i = input('Continue: ').lower().strip()
    if i == yes or i == c_y:
        print('{}'.format(success))
    if i == no or i == c_n:
        print('{}'.format(exit))
else:
    print('{}'.format(error))

Solution to my problem:
success = "Success"
exit = "EXIT"
error = 'ERROR'
yesAnswers = ['yes', 'y', 'sure!', ''];
noAnswers = ['no', 'n', 'nope']

answer = input('Yes/No or Enter: ').lower().strip()

if answer in yesAnswers:
    print(success)
elif answer in noAnswers:
    print(exit)
else:
    print(error)

Full code:
class characters:

    def __init__(self, title, character_name, power_score, biography):
        self.title = title
        self.character_name = character_name
        self.power_score = '| ' + 'Power score - ' + power_score + ' -\n'
        self.biography = biography

    def title_name(self):
        print('{} {}'.format(self.title,self.character_name))

    def characters_data(self):
        print('{} {} {} {}'.format(self.title, self.character_name, self.power_score, self.biography))

B_Cider = characters('Barbarian', 'Cider', '4854', 'Not much is known about this character')
L_Cido = characters('Lord', 'Cido', '7910', 'Not much is known about this character' )

# Y(Height) of ascii-art
z = 12
for x in range(z):
    print("-" * (z-x) + "*" * x + " " * x + "-" * (z-x))
# ...............

answer = input('Are you ready to play? (Yes/No or Enter) : ').lower().strip()
first_selection = "Do you want to be a Hero? (Yes/No or Enter) : "
not_Ahero = "\nYou have selected not to be a hero\n____\nYour characters profile:"
Ahero = "\nYou have selected to be a hero\n____\nYour characters profile:"
error = 'ERROR'
yesAnswers = {'yes', 'y', 'sure!', 'yea', 'yeah', 'ye', 'si', ''}
noAnswers = {'no', 'n', 'nope', 'nah', 'not'}

if answer in yesAnswers:
    answer = input(first_selection).lower().strip()
    if answer in yesAnswers:
        print(Ahero)
        print(characters.characters_data(B_Cider))
    if answer in noAnswers:
        print(not_Ahero)
        print(characters.characters_data(L_Cido))
else:
    print(error)


texts: Show number of pages next to Flickr threads

texts:
This is a userscript that simply adds the number of pages that a thread has next to its title for Flickr interface. (FWIW it's not really done because the script is only loaded at page load, but not reloaded on subsequent AJAX calls that the user may make).

I'm far from being a seasoned JS developer, so I'm looking for guidelines to potentially bring the script to state-of-the-art JS standards.

Example of questions that I'm not sure about:

Should I use promises?
Is the workflow done well?
Is the inline CSS/HTML evil in this case?
Should I omit jQuery?
Am I making too many jQuery calls? (i.e. should I just make one query and find the next rows through siblings or something similar?)

Any pointers are appreciated! (this is also my first userscript, so feedback about the userscript itself is also appreciated)

// ==UserScript==
// @name        Flickr - Number of pages in a thread
// @namespace   flickr_
// @description This user script is simply displaying the number of pages in a thread on the main page of the group
// @include     http*://*flickr.com/groups/*
// @version     1
// @grant       none
// @run-at      document-start
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// ==/UserScript==

var api_key = 'fe753c0dd6068fb6c74cb70458b1b9a0';
var POSTS_PER_PAGE = 100;

function call_flickr(method, params, callback) {
    'use strict';
    var url = "https://api.flickr.com/services/rest?";
    params.api_key = api_key;
    params.format = 'json';
    params.nojsoncallback = 1;
    params.method = method;
    $.get(url, params, function (data) {
        callback(JSON.parse(data));
    });
}

function number_of_pages(data) {
    'use strict';
    var url = '/groups/' + data.topics.path_alias + '/discuss/';
    data.topics.topic.forEach(function (topic) {
        var pages_number = Math.ceil(topic.count_replies / POSTS_PER_PAGE);
        var link = url + topic.id + '/';
        var last_link = link + 'page' + pages_number;
        var current_element = $('a[href=' + link + ']');
        if (pages_number > 1) {
            current_element.after(' ' + pages_number + '');
        }
    });
}

function threads_list(data) {
    'use strict';
    var group_id = data.group.id;
    var params = {};
    params.group_id = group_id;
    call_flickr('flickr.groups.discuss.topics.getList', params, number_of_pages);
}

function main() {
    'use strict';
    var params = {};
    params.url = document.URL;
    call_flickr('flickr.urls.lookupGroup', params, threads_list);
}

main();


texts: Fibonacci sequence and quadratic equation using functions

texts:
I know this code works, but is it correct to define them as functions or should I use something else?

import math

def Fibonnacci_sequence():
    i=int(input("How many numbers of the fibonnacci sequence do you want to see: "))
    a = 1
    b = 1
    n = 1
    print(a)
    print(b)
    n = n + 1
    while n < i:
        c = a + b
        print(c)
        n = n + 1
        a = b
        b = c

def Fib_seqnum():
    i=int(input("What number of the fibonnacci sequence do you want to know: "))
    a = 1
    b = 1
    n = 1
    n = n + 1
    while n < i:
        c = a + b
        n = n + 1
        a = b
        b = c
    print(c)

def solve_qaudratic():
    a=float(input("Enter A: "))
    b=float(input("Enter B: "))
    c=float(input("Enter C: "))
    d = (b*b) - 4*a*c
    if d < 0:
        print("No real roots")
    elif d == 0:
        x = -b/(2*a)
        print("equal roots" (x))
    else:
        x = math.sqrt(d)
        i = (-b -x)/(2*a)
        o = (-b +x)/(2*a)
        print("X1 = " (i))
        print("X2 = " (o))

print("Welcome to maths")
print("PRESS 1 TO LOOK AT THE FIBONNACCI SEQUENCE")
print("PRESS 2 TO SOLVE A QUADRATIC")
print("PRESS 9 TO EXIT")
answer=int(input("Enter Choice: " ))
if answer==1:
    Fibonnacci_sequence()
elif answer==2:
    solve_qaudratic()
elif answer==3:
    Fib_seqnum()
elif answer==9:
    exit()
else:
    print("WHAT?!")


texts: Calculate sum of all the items in array list?

texts:
I am setting the sum total of all the items in an array to a text view in android.The values contained in the array are all currency values.

@Override
        public void afterTextChanged(Editable s) {

            int id = 0;

            id = (int) itemtotal.getTag();
            String itemTot = itemtotal.getText().toString();

            if (id >= 0 && id <= totals.size()) {
                totals.set(id - 1, itemTot);

                double[] doubleList = new double[totals.size()];
                double newsum = 0.0d;
                for (int i = 0; i < totals.size(); ++i) {
                    doubleList[i] = Double.parseDouble(totals.get(i));
                    newsum += (double) Math.round((doubleList[i]) * 100.0) / 100.0;
                }
                textViewSum.setText(((double) Math.round((newsum * (0.02) + newsum) * 100.0) / 100.0) + "");//set total text to sum
                textViewVat.setText(((double) Math.round((newsum * (0.02)) * 100.0) / 100.0) + "");
            }
        }

So I am basically calculating the sum total and the vat which is 2%.

The code is pretty straightforward, but I am interested in any possible improvement.


texts:
I recently developed code that can run as a function parameter but I'm not quite sure how vulnerable it is to hacks and/or cheats.
Also, is there anything I could improve?

const h1 = document.getElementById('hi')

world = "world";

function testCode(codeEntered) {
    var code = codeEntered;
  var run = code *= 1;
  return(run);
}
<button onclick="testCode(h1.textContent = world)">
Test
</button>

<h1 id="hi">
Hello
</h1>


texts: Eloquent Javascript exercise: find average age from ancestors array per century

texts:
I solved an exercise from the book "Eloquent Javascript". I want to share with you guys the solution. The exercise is from chapter 5. Summing up, I have to find the average age from the ancestors array per century. Here is my solution:

var ancestry = JSON.parse(require('../resources/ancestry'))

//Top-down approach, functions are defined after their use
//Necessary side-effect in function to print the output
function printAverageAgePerCentury(ancestry){
    var averageAgePerCentury = getAverageAgePerCentury(ancestry);
    Object.keys(averageAgePerCentury).forEach(function(century){
        console.log(century.concat(": ").concat(averageAgePerCentury[century]))
    })
}

function getAverageAgePerCentury(ancestry){
    var agesPerCentury = getAgesPerCentury(ancestry);
    return agesPerCentury.reduce(function(averageAgePerCentury, agePerCentury){
        if(averageAgePerCentury[agePerCentury.century]){
            averageAgePerCentury[agePerCentury.century] = [average(averageAgePerCentury[agePerCentury.century].concat(agePerCentury.age))];
            return averageAgePerCentury;
        } else {
            averageAgePerCentury[agePerCentury.century] = [agePerCentury.age];
            return averageAgePerCentury;
        }
    }, {})
}

function getAgesPerCentury(ancestry){
    return ancestry.map(function(person){
        return {
            century : whichCentury(person),
            age : person.died - person.born
        }
    })
}

function average(array){
    function plus(a,b){ return a + b}
    return array.reduce(plus) / array.length
}

function whichCentury(person){
    return Math.ceil(person.died / 100)
}

//--------------------------------//

printAverageAgePerCentury(ancestry);

What do you think about the top-down approach? Do you prefer the opposite? Where functions are defined before their use.
Is possible to make this solution more readable, more elegant?
What could you do to make it better?


texts: Converting a wrapper object to a value object

texts:
I have ChannelWrapper and Channel Value Object. I want to convert each and every field of ChannelWrapper to Channel Value Object.

public class ChannelWrapper extends BaseWrapper implements APIWrapper<Channel>,
        APIUnwrapper<Channel> {

    @XmlElement
    private Long id;

    @XmlElement
    private User user;

    @XmlElement
    private Tenant tenant;

// Getter Setters
    @Override
    public Channel unwrap(HttpServletRequest arg0, ApplicationContext arg1) {
    // TODO Auto-generated method stub
    return null;
    }

    @Override
    public void wrapDetails(Channel model, HttpServletRequest request) {

    this.id = model.getId();
    this.user = model.getUser();
    this.tenant = model.getTenant();

    }

    @Override
    public void wrapSummary(Channel model, HttpServletRequest request) {
    wrapDetails(model, request);

}

Channel Value Object:

public class Channel {

    private Long id;
    private User user;
    private Tenant tenant;
    //getter setters   }

Converter:

Channel channel = new Channel();
channel.setId(channelWrapper.getId());
channel.setUser(channelWrapper.getUser());
channel.setTenant(tenant);

Is this the best way to create a converter?

Any other general comments are appreciated.


texts: Converting Java int-based amount to Coin metrics

texts:
I was tasked with writing a method which would take in an int (for amount in coins) and then convert the coins, accordingly, by counting how many quarters, dimes, nickels, and pennies were located in the amount. Afterwards, it would return a String which stated each count of individual coin.

public class Coins {

    private static final int QUARTER_VALUE = 25;
    private static final int DIME_VALUE = 10;
    private static final int NICKEL_VALUE = 5;
    private static final int PENNY_VALUE = 1;

    public static String convert(int amount) {
        int currentAmount = amount;
        int quarters = 0;
        int dimes = 0;
        int nickels = 0;
        int pennies = 0;

        String quarterUnit = new String();
        String dimeUnit = new String();
        String nickelUnit = new String();
        String pennyUnit = new String();

        if (amount != 0) {
            quarters = amount / QUARTER_VALUE;

            currentAmount =
                     amount - (quarters * QUARTER_VALUE);

            dimes = currentAmount / DIME_VALUE;

            currentAmount =
                     amount - (quarters * QUARTER_VALUE) - (dimes * DIME_VALUE);

            nickels = currentAmount / NICKEL_VALUE;

            currentAmount =
                     amount - (quarters * QUARTER_VALUE)
                     - (dimes * DIME_VALUE) - (nickels * NICKEL_VALUE);

            pennies = currentAmount / PENNY_VALUE;
        }

        if (quarters == 1) {
            quarterUnit = " quarter";
        }

        else if (quarters > 1 || quarters == 0){
            quarterUnit = " quarters";
        }

        if (dimes == 1) {
            dimeUnit = " dime";
        }

        else if (dimes > 1 || dimes == 0) {
            dimeUnit = " dimes";
        }

        if (nickels == 1) {
            nickelUnit = " nickel";
        }

        else if (nickels > 1 || nickels == 0) {
            nickelUnit = " nickels";
        }

        if (pennies == 1) {
            pennyUnit = " penny";
        }

        else if (pennies > 1 || pennies == 0) {
            pennyUnit = " pennies";
        }

        StringBuilder conversion = new StringBuilder();

        return conversion.append(quarters)
                         .append(quarterUnit)
                         .append("\n")
                         .append(dimes)
                         .append(dimeUnit)
                         .append("\n")
                         .append(nickels)
                         .append(nickelUnit)
                         .append("\n")
                         .append(pennies)
                         .append(pennyUnit)
                         .append("\n")
                         .toString();
    }

    public static void main(String[] args) {
        String conversionString = convert(89);

        System.out.println(
              new StringBuilder().append("Converted amount equates to: ")
                                 .append("\n"));

        System.out.println(conversionString);
    }
}

Here's the output:

Converted amount equates to:

3 quarters
1 dime
0 nickels
4 pennies

Is there a more efficient (fewer lines of code or a better OO style) way to implement this?


texts: Python unit testing for a Stack data structure

texts:
I am completely new to unit testing. I read this chapter in Dive Into Python 3, and decided to give it a try on a basic data structure: a stack.

Here is the stack code (taken from "Problem Solving with Algorithms and Data Structures using Python"):

class Stack:
     def __init__(self):
         self.items = []

     def isEmpty(self):
         return self.items == []

     def push(self, item):
         self.items.append(item)

     def pop(self):
         return self.items.pop()

     def peek(self):
         return self.items[len(self.items)-1]

     def size(self):
         return len(self.items)

Here is my testing code:

import unittest

class StackTester(unittest.TestCase):

    def test_stack_init(self):
        s = Stack()
        self.assertEqual(0, s.size())

    def test_push1_size(self):
        item = 5
        s = Stack()
        s.push(item)
        self.assertEqual(1, s.size())

    def test_push1_items(self):
        s = Stack()
        s.push(5)
        self.assertEqual([5], s.items)

    def test_push2_size(self):
        s = Stack()
        s.push(5)
        s.push(6)
        self.assertEqual(2, s.size())

    def test_push2_items(self):
        s = Stack()
        s.push(5)
        s.push(6)
        self.assertEqual([5,6], s.items)

    def test_push2_pop1_size(self):
        s = Stack()
        s.push(5)
        s.push(6)
        s.pop()
        self.assertEqual(1, s.size())

    def test_push2_pop1_value(self):
        s = Stack()
        s.push(8)
        s.push(9)
        self.assertEqual(9, s.pop())

    def test_push2_pop2_size(self):
        s = Stack()
        s.push("Glob")
        s.push("Blob")
        s.pop()
        s.pop()
        self.assertEqual(0, s.size())

    def test_push2_pop2_value(self):
        s = Stack()
        s.push("Glob")
        s.push("Blob")
        s.pop()
        self.assertEqual("Glob", s.pop())

    def test_isEmpty_init(self):
        s = Stack()
        self.assertEqual(True, s.isEmpty())

    def test_isEmpty_push1(self):
        s = Stack()
        s.push(5)
        self.assertEqual(False, s.isEmpty())

    def test_isEmpty_push1_pop1(self):
        s = Stack()
        s.push(1)
        s.pop()
        self.assertEqual(True, s.isEmpty())

    def test_peek_push1(self):
        s = Stack()
        s.push(88)
        self.assertEqual(88, s.peek())

    def test_peek_push3_pop1(self):
        s = Stack()
        s.push(7)
        s.push(889)
        s.push(3)
        s.pop()
        self.assertEqual(889, s.peek())

    def test_pop_empty(self):
        s = Stack()
        self.assertRaises(IndexError, s.pop)

    def test_peek_empty(self):
        s = Stack()
        self.assertRaises(IndexError, s.peek)

if __name__ == '__main__':
    unittest.main()

Am I leaving anything out? Is 16 tests for a stack overkill? What are the best practices for something like this?


texts:
Want to show you part of code that I wrote to process search request. User commit search by articles (codes) of products. The goal is to allow user write his search request to textarea element in any possible way: in a row, in a column or separated by any separator (comma, space, semicolon etc.).

<?php
include("db.php"); // Including connection to MySQL

if(!empty($_POST['codes'])){ // Checking user's input from textarea not empty

    $codes = $_POST['codes']; // Moving user's input to variable
    preg_match_all("/\d{6}/", $codes, $codes_array); // Taking all elements that matches regular expression and adding them to the array

    $codes_array = array_unique($codes_array[0]); // Removing duplicates from the array

    if(!empty($codes_array)){ // Checking array not empty

        $codes_list = ""; // Creating new variable

        foreach ($codes_array as $key => $value) { // Processing our array
            $codes_list .= $value . "|"; // Adding values and separator to previously created variable to use it in MySQL query
        }

        $codes_list = rtrim($codes_list, "|"); // Removing last separator from string
        $codes_add = " AND `code` REGEXP '^({$codes_list})$'"; // Creating new variable with part of MySQL query and our elements from the array
    } else {
        $codes_add = ""; // Creating empty variable if our array was empty
    }
}

$query = "SELECT * FROM `table` WHERE `status` = '0'" . $codes_add; // Generating MySQL query string
$result = mysqli_query($link, $query); // Making a request to MySQL
?>

My friend said that it contains vulnerabilities for SQL-injection because I do not filter user's input. But my logic based on a statement that user's input filters at the line with preg_match_all. I'm sure that nothing but elements that consist of 6 digits will be included to the array.

Anyway I want that someone who have an experience with PHP and vulnerabilities took a look at this code and share his opinion about potential risks of using it. Thank You.


texts: Parsing Long Excel Report Files for Predefined Results

texts:
I work as an IT intern in a multinational and I was given a tedious task of combing through a 2500+ long multi-column excel report file in search of inactive servers.

Here's a sample row from that file:

Then, I got another excel file but this time with just the DB Codes (80+ of them).

My task was:

Go through the big report file
Find the company by its DB Code
Check if the server is active or not active, and if not active flag it for a decommission

Of course, as you might expect, I was told to return the results in a spreadsheet in the following format:

Full name: Acme Inc. | Code: ACM | Active?: no | Decomm?: yes

Fulln name:, Code:, etc. are column headers. Here, they are just for readability.

If I were to do it manually, I'd most probably die of boredom. But! There's Python, right?

So, I exported some of the columns from the report into a tab delimited file and drafted this:

def read_file_to_list(file_name):
    with open(file_name, 'r') as file_handler:
        stuff = file_handler.readlines()
    return [line[:-1] for line in stuff]

def make_dic(file_name):
    with open(file_name, 'r') as f:
        rows = (line.replace('"', "").strip().split("\t") for line in f)
        return {row[0]:row[1:] for row in rows}

def search(dic, ou_codes):
    counter = 1
    with open("output.txt", "w") as output:
        #writing a header
        output.write("Full name\tCode\tActive?\tDecomm?\n")
        for k, v in dic.items():
            for code in ou_codes:
                if v[0] == code:
                    #writing back line by line to a tab delimited file
                    outputline = "{}\t{}\t{}\t{}\n".format(k, *v,
                    "yes" if v[1] == "no" else "no")
                    output.write(outputline)

                    print("{}. Full name: {} | Code: {} | Active?: {} | Decomm?: {}".format(counter, k, *v, "yes" if v[1] == "no" else "no"))
                    counter += 1

decomm_codes = read_file_to_list('t1.txt')
all_of_it = make_dic('t2.txt')

search(all_of_it, decomm_codes)

That spits out:

1. Full name: Random, Inc | Code: RNDM | Active?: yes | Decomm?: no
2. Full name: Acme Inc.| Code: ACM | Active?: no | Decomm?: yes
3. Full name: Fake Bank, Ltd.  | Code: FKBNK | Active?: yes | Decomm?: no

Is there a way refactor the search method?

Finally, here's the contents of the decomm_codes.txt and big_report.txt files.

decomm_codes.txt:

RNDM
ACM
FKBNK

big_report.txt:

"Random, Inc"   RNDM    yes
Acme Inc.   ACM no
"Fake Bank, Ltd. "  FKBNK   yes


texts: Optimize the split of a String from console

texts:
I have to read a String from console, so I used the tokenizer to split it and add each token in a position on arrayList, is there a way to improve the operation of split?

while ((currentLine = bufferedReader.readLine()) != null ) {
            StringTokenizer string = new StringTokenizer(currentLine, " ");
            while (string.hasMoreTokens()) {
            arrayList.add(string.nextToken());
            }
}


texts:
I'm playing with async/await, but I have yet to discover a standard method to safely cancel an intensive task. I have tested the following, and it works exactly as intended, though I remain unsure if a standard method exists.

abstract class PageLoader<TPage, TElement> where TPage : Page
{
    private TPage page;
    private Task loader;
    private volatile bool mode;
    private volatile int token;

    public PageLoader(TPage page)
    {
        if (page == null)
        {
            throw new ArgumentNullException("page");
        }

        this.page = page;
        this.mode = true;
    }

    protected TPage Page => page;
    protected bool Mode => mode;

    public void Load(TElement[] items)
    {
        if (!page.Dispatcher.HasThreadAccess)
        {
            throw new InvalidOperationException("The current thread is not authorized.");
        }

        if (loader != null)
        {
            throw new InvalidOperationException("The loader requires reset.");
        }

        if (items == null)
        {
            throw new ArgumentNullException("items");
        }

        int value = token;

        mode = true;
        (loader = new Task(() => AutoLoad(value, items))).Start();
    }

    public async Task<bool> Set(bool retainMode)
    {
        if (!page.Dispatcher.HasThreadAccess)
        {
            throw new InvalidOperationException("The current thread is not authorized.");
        }

        if (mode)
        {
            mode = false;

            if (loader != null)
            {
                await loader;
                loader = null;
                token++;
            }

            if (retainMode)
            {
                mode = true;
            }

            return true;
        }

        return false;
    }

    protected void Commit(Entry entry)
    {
        if (entry == null)
        {
            throw new ArgumentNullException("entry");
        }

        DispatchedHandler handler = () =>
        {
            if (entry.Token == token)
            {
                AutoCommit(entry);
            }
        };

        var action = page.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, handler);
    }

    protected abstract void AutoLoad(int token, TElement[] items);
    protected abstract void AutoCommit(Entry entry);

    protected class Entry
    {
        public readonly int Token;
        public readonly TElement Element;
        public readonly object Data;

        public Entry(int token, TElement element, object data)
        {
            Token = token;
            Element = element;
            Data = data;
        }
    }
}

Tested with:

class GridViewLoader : PageLoader<MainPage, int>
{
    public GridViewLoader(MainPage page) : base(page) { }

    protected override void AutoLoad(int token, int[] items)
    {
        foreach (int item in items)
        {
            if (!Mode)
            {
                break;
            }

            // (Intensive process per item..)

            Commit(new Entry(token, item, null));
        }
    }

    protected override void AutoCommit(Entry entry)
    {
        GridViewItem item = new GridViewItem()
        {
            Content = entry.Element.ToString()
        };

        Page.gridView.Items.Add(item);
    }
}

Usage:

private GridViewLoader gridViewLoader;

private async void queryBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
    if (!await gridViewLoader.Set(false))
    {
        return;
    }

    gridView.Items.Clear();

    int[] selection;

    // (Do stuff..)
    selection = new int[] { 1, 2, 3 };

    if (selection != null)
    {
        gridViewLoader.Load(selection);
    }
}


texts:
I wrote a function that recursively walks a given directory.

module WalkDir (walkDir) where

import System.Directory (doesDirectoryExist, getDirectoryContents)
import System.FilePath ((</>))

walkDir :: FilePath -> IO [FilePath]
walkDir r = contents >>= fmap concat . traverse helper
    where contents = fmap (r </>) . filter ((&&) . (/=) "." <*> (/=) "..") <$> getDirectoryContents r
          helper x = do e <- doesDirectoryExist x
                        if e then walkDir x else return [x]

However, I have several concerns with this function. For starters, it is slow and it does not print out results until they have all been collected (not as lazy as it should be). My best guess is that this is because of the constant concatenations.

Additionally, the use of do-notation in helper seems clunky. This is where I'd love it if if were just a function because I could just use >>= with no do required. Alternatively if there were a GHC extension equivalent to LambdaCase for if statements that would also work.


texts: Implementing the Hashable Protocol in Swift with the DJB hash function

texts:
A while back I made a custom String struct (see github repo) because of the difficulties in dealing with Mongolian Unicode rendering when using Swift String or NSString (see this question and the accepted answer for more details). The struct is an array of UInt32 so that it represents a string of Unicode scalar values.

The most difficult part (see here and here for my StackOverflow questions at the time) was making it conform to the Hashable Protocol so that it could be used as a Dictionary key.

For all that I can tell, everything has been working fine. However, since there was not a lot of documentation and guidance available about implementing the Hashable Protocol, I wanted to make sure that I did it right. Here is the relevant code:

struct ScalarString: SequenceType, Hashable, CustomStringConvertible {

    private var scalarArray: [UInt32] = []

    // ...

    // hashValue needed to implement Hashable protocol
    var hashValue: Int {
        get {

            // DJB Hash Function
            var hash = 5381

            for(var i = 0; i < self.scalarArray.count; i++)
            {
                hash = ((hash << 5) &+ hash) &+ Int(self.scalarArray[i])
            }

            return hash
        }
    }

}

// Hashable also needs struct to conform to Equatable protocol
func ==(left: ScalarString, right: ScalarString) -> Bool {

    if left.length != right.length {
        return false
    }

    for var i = 0; i < left.length; ++i {
        if left.charAt(i) != right.charAt(i) {
            return false
        }
    }

    return true
}


texts: I made basketball program using Java that runs on console

texts:
I made a simple console basketball game using Java.
/*
 * Java Basketball
 * by Clint
 * 2020.07.08 | 3:59AM
 * This Java program let's the player play basketball in console.
 */

import java.util.Random;
import java.util.Scanner;

public class Basketball {

    static String[] shoot = {"1 POINT!", "2 POINTS!", "3 POINTS!", "MISSED!"};
    static String player;

    public static void main(String[] args) {
        System.out.println("WELCOME TO JAVA CONSOLE BASKETBALL\n" +
                "how to play:\n" +
                "press \"s\" or type \"shoot\" to shoot the basketball.\n");

        while (true) {
            shootBall();
        }
    }

    public static void shootBall() {
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);

        int shot = random.nextInt(shoot.length);
        System.out.print("SHOOT: ");
        player = scanner.nextLine();

        switch (player) {
            case "s", "S", "shoot", "Shoot", "SHOOT" -> System.out.println(shoot[shot] + "\n");
            default -> System.out.println("SHOOT THE BALL PROPERLY.\n");
        }
    }
}

ps: ik that there's while (true) in my code, but it's the thing that I know so far that keeps the programme running. I'm open for suggestions on how to improve my coding.


texts: Copy two properties from one array item to matching index in another array

texts:
I have two IEnumerable objects called items and newItems.  I need to update the Did and KeyDid property of each element in items with the matching Did and KeyDid from newItems.  I can't just call items = newItems; since other things have a reference to items.  Here's my code:

T[] arrItems = items as T[] ?? items.ToArray();
if (arrItems.Length != newItems.Count())
    throw new Exception("Item counts do not match.");

//Copy Did and KeyDid from old items to newItems
int i = 0;
foreach (T newItem in newItems)
{
    T oldItem = arrItems[i++];
    oldItem.Did = newItem.Did;
    oldItem.KeyDid = newItem.KeyDid;
}

I'm interested in a more concise way to do this, perhaps using a single LINQ expression.  Any ideas how to improve this code in terms of readability, clearness, conciseness, or overall coolness?


texts: Displaying text extracted from XML using PHP simplexml

texts:
I have this xml file and i am parsing it with php simplexml.

My XML file looks like this:

<?xml version="1.0" encoding="UTF-8"?>

<noticias>
    <noticia url="noticia-1">
        <titulo>título da notícia 1</titulo>
        <desc>plain text.</desc>
        <texto>plain text.</texto>

        <in>Publico</in>
    </noticia>
    ...
</noticias>

In my php page i parse it like this:

$file = 'xml/noticias.xml';
if(file_exists($file)) {
    $xml = simplexml_load_file($file);
    foreach($items as $item) {
        $titulo = htmlentities($item->titulo, ENT_QUOTES, 'utf-8');
        $desc = htmlentities($item->desc, ENT_QUOTES, 'utf-8');
        $url = htmlentities($item['url'], ENT_QUOTES, 'utf-8');

        if(strlen($titulo) < 3) {$titulo = 'T&iacute;tulo em falta';} else {$titulo = $titulo;}
        if(strlen($desc) < 3) {$desc = 'Descri&ccedil;&atilde;o em falta';} else {$desc = $desc;}
        if(strlen($url) < 3) {$h3 = '
'.$titulo.'
';} else {$h3 = '
'.$titulo.'
';}

        ?>

                        <?php echo $h3; ?>

<?php echo $desc; ?>

        <?php
    }
}
else {
    // do something... throw error message
}

Is this ok? i mean, i escape values when i get from xml. Is it ok to do it like this or should i escape values on echo? is there any danger to leave as i have?

other thing... i have the xml files protected with htaccess. right now, they can only be edited directly. no scripts to edit them.


texts:
I'm trying to implement a queue data structure in C++ using a circular array.
Please give recommendations on how I can improve this code.
Also, is my array growth strategy good? I'm doubling the array when the buffer is full.
(Try to remain in C++ 11 because, well that's a restriction I have to follow atm).
Sorry for the lack of comments in advance LoL (this is a rushed implementation).
#include <iostream>
#include <utility>

template <typename T>
class Queue {
public:
    Queue() : data(nullptr), len(0), front(0), cap(0)
    {
    }

    ~Queue()
    {
        this->Clear();
    }

    Queue(const Queue& rhs) : Queue()
    {
        if (rhs.data) {
            this->data = new T[rhs.cap];
            this->cap = rhs.cap;
            this->len = rhs.len;
            this->front = rhs.front;

            for (size_t i = 0; i < len; ++i) {
                this->data[i] = rhs.data[i];
            }
        }
    }

    Queue(Queue&& rhs) : data(rhs.data), cap(rhs.cap), len(rhs.len), front(rhs.front)
    {
        rhs.data = nullptr;
    }

    Queue& operator=(Queue rhs)
    {
        swap(*this, rhs);
        return *this;
    }

    size_t GetLength() const { return len; }
    const T& GetFront() const { return data[front]; }

    void Enqueue(const T& val)
    {
        if (len == cap) {
            size_t oldCap = cap;

            if (cap == 0) cap = 1;
            cap *= 2;

            T* newBuff = new T[cap];

            for (size_t i = 0; i < len; ++i) {
                size_t idx = (front + i) % oldCap;
                newBuff[i] = data[idx];
            }

            front = 0;
            data = newBuff;
        }

        data[(front + len) % cap] = val;
        ++len;
    }

    T Dequeue()
    {
        T val = std::move(data[front]);

        front = (front + 1) % cap;
        --len;
        return val;
    }

    void Clear()
    {
        delete[] data;
        data = nullptr;
        this->cap = this->len = this->front = 0;
    }

    friend
    std::ostream& operator<< (std::ostream& out, const Queue& q)
    {
        out << "Queue{";
        for (size_t i = 0; i < q.len; ++i) {
            size_t idx = (q.front + i) % q.cap;
            out << q.data[idx];
            if (i < q.len - 1) out << ", ";
        }

        out << "}";

        return out;
    }

    friend
    void swap(Queue& lhs, Queue& rhs)
    {
        std::swap(lhs.data, rhs.data);
        std::swap(lhs.len, rhs.len);
        std::swap(lhs.cap, rhs.cap);
        std::swap(lhs.front, rhs.front);
    }

private:
    T* data;
    size_t len;
    size_t cap;
    size_t front;
};

int main()
{

    Queue < int > a;
    a.Enqueue( 5 ); // add 5
    a.Enqueue ( 6 ); // add 6
    std::cout << a; // prints Queue{5, 6}

    a.Clear(); // empties the Queue
    std::cout << a; // prints Queue{}
}
```


texts:
I'm looking for feedback on the readability of my code and opinions on the pick_best algorithm. I do this stuff for fun when I have time, and never get a chance to have anyone else look at it. Hopefully, I can use this site to improve my coding.

from itertools import permutations
from random import randint
class TTT:
    def __init__(self):
        self.game_grid = [0 for x in range(9)]
        self.winning_matrix = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))

    def game_state(self, grid):
        '''Prints current game state'''
        print "\n\n\n0 1 2 \n3 4 5 \n6 7 8 \n"
        for square in range(9):
            if square%3==0: print
            print ['.', 'O', 'X'][grid[square]],
        print

    def check_game(self, grid):
        '''Checks game state for a winner or tie'''
        for row in self.winning_matrix:
            total = sum([grid[x] for x in row])
            if abs(total) == 3:
                return self.winner_is(total)
        return self.winner_is(total)

    def winner_is(self, total):
        '''Establishes which player wins in current node'''
        return total/3 if abs(total)==3 else 0

    def pick_best(self):
        '''A non-recursive minimax style function utilizing itertools.permutations'''
        avail_squares = [pos for pos, x in enumerate(self.game_grid) if x==0]
        score = {x:0 for x in avail_squares}    #keeps minimax score for current game state
        for perm in permutations(avail_squares): #thank you itertools
            player = -1 #start with computer player
            node = list(self.game_grid) #node is a copy of the current game state
            for square in perm:
                node[square]=player #makes a move in the permutation
                state_score = self.check_game(node) #checks to see if anyone won
                if state_score:
                    ''' if there is a winning play in this node,
                        a score based off the depth of the play is added
                        to the total score of the possible move.
                        Then we break out of the current permutation'''
                    score[perm[0]] += (10**(len(perm)-perm.index(square)))*-1*state_score
                    break
                player *= -1 #swaps to the next player in the node
        return max(score, key=lambda x: score[x]) #returns square with highest score

    def player_choice(self):
        start = raw_input("Would you like to start? (Y/N) ")
        print start
        if start.upper() == 'Y':
            return False, 1
        elif start.upper() == 'N':
            return False, -1
        else:
            print "Please choose (Y)es or (N)o"
            return True, 0

    def pick_a_spot(self):
        move = raw_input("Where would you like to move 0-8? ")
        if move.isdigit() and 0<=int(move)<9:
            m = int(move)
            if self.game_grid[m] == 0:
                return False, m
        return True, 9

    def play(self):
        '''A very basic game play interface to test algorithm.'''
        invalid = True
        while invalid:
            invalid, player = self.player_choice()
        if player == -1:
            self.game_grid[randint(0,8)]=-1
            player = 1
        self.game_state(self.game_grid)
        while 0 in self.game_grid and self.check_game(self.game_grid)==0:
            if player == 1:
                invalid = True
                while invalid:
                    invalid, move = self.pick_a_spot()
                self.game_grid[move]=1
                player = -1
            else:
                move = self.pick_best()
                player = 1
                self.game_grid[move]=-1
            self.game_state(self.game_grid)

if __name__=='__main__':
    TTT().play()


texts:
There are multiple Project Euler problems (e.g. 7, 10) that deal with prime numbers. I decided make a reusable solution that could be used for most of them.

I wrote a method to generate an infinite* prime number sequence, which would enumerate lazily (that is - computing only when requested), using yield return. At this point I can use the whole power of LINQ, MoreLINQ, and any other IEnumerable extension method.

It doesn't perform great though - finding prime numbers below 2 million takes over a second. I don't think I can use a sieve as I don't know the upper bound. What could be done to improve it? Any other non-performance improvements?

*The sequence isn't really infinite, only up to 263-1 or until an OutOfMemoryException.

The prime sequence generator:

class PrimeSequenceGenerator : ISequenceGenerator
{
    public IEnumerable<long> GetSequence()
    {
        var primeCache = new List<long>();
        long curentNumber = 2;
        while (true)
        {
            var isPrime = true;
            var currentRoot = Math.Sqrt(curentNumber);
            foreach (var cachedPrime in primeCache)
            {
                if (curentNumber % cachedPrime == 0)
                {
                    isPrime = false;
                    break;
                }
                if (cachedPrime > currentRoot)
                {
                    break;
                }
            }
            if (isPrime)
            {
                primeCache.Add(curentNumber);
                yield return curentNumber;
            }
            curentNumber++;
        }
    }
}

An interface for all my sequence generators:

interface ISequenceGenerator
{
    IEnumerable<long> GetSequence();
}

Usage:

var generator = new PrimeSequenceGenerator();

// Euler problem 7 - Find the 10001st prime.
var problem7Solution = generator.GetSequence().ElementAt(10001 - 1);

// Euler problem 10 - Find the sum of all primes below two million.
var problem10Solution = generator.GetSequence().TakeUntil(x => x > 2000000).SkipLast(1).Sum();


texts:
I've just begun creating a class to get User information, and I'd like for it to be improved.

The global variable $oConni is the database connection.

class UserInfo {

public $id, $oConni;

public function __construct($id, $oConni) {
    $this->id = $id;
    $this->oConni = $oConni;
}

public function getInfo() {
    $userInfo = array();
    $cSQL = "SELECT name, last_name, email, use_gravatar, pic_profile FROM users WHERE id = ?";
    $stmt = $this->$oConni->prepare($cSQL);
    $stmt->bind_param('i', $this->$id);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($name, $lastName, $email, $gravatar, $picProfile, $admin);
    if ($stmt->fetch()) {
        $userInfo['name'] = $name;
        $userInfo['lastName'] = $lastName;
        $userInfo['email'] = $email;
        $userInfo['gravatar'] = $gravatar;
        if($gravatar == 1){
            $size = 500;
            $grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?s=" . $size;
            $userInfo['picProfile'] = $grav_url;
        }else if(strpos($picProfile, 'http') === 0 || strpos($picProfile, 'https') === 0){
            $userInfo['picProfile'] = $picProfile;
        }else{
            $pic = 'http://www.example.com/'.$picProfile.'?id='.RAND(0,999999);
            $userInfo['picProfile'] = $pic;
        }
    }
    $stmt->close();

    return $userInfo;
}
}
$userInf = new UserInfo($cmntUser, $oConni);
$userData = $userInf->getInfo();
print_r($userData);


texts:
I populate a ListView with Items. Each Item has data attached to its .Tag property.

Over time, I have needed to handle many cases where something would be null or missing or corrupt or whatever.

And so was born this beast:

private void PlayRecording()
{
    if (list.Items.Count >= 1)
    {
        if (list.SelectedItems.Count >= 1)
        {
            if (((Item)list.SelectedItems[0].Tag).Attachments.Count >= 1)
            {
                if (((Item)list.SelectedItems[0].Tag).Attachments[0].AudioStreams.Count >= 1)
                {
                    if (((Item)list.SelectedItems[0].Tag).Attachments[0].AudioStreams[0].AudioStream != null)
                    {
                        byte[] recording = ((Item)list.SelectedItems[0].Tag).Attachments[0].AudioStreams[0].AudioStream;

                        if (recording != null)
                        {
                            using (MemoryStream memoryStream = new MemoryStream(recording))
                            {
                                if (memoryStream != null)
                                {
                                    soundPlayer.Stream = memoryStream;
                                    soundPlayer.Play();

                                    AudioState = AudioStates.Playing;
                                }
                                else status.Text = "The Memory Stream returned is null. The stream may be corrupt or non-existent.";
                            }
                        }
                        else status.Text = "Notes is unable to play the recording.";
                    }
                    else status.Text = "The selected item's Audio Stream is null. The recording may be corrupt or missing.";
                }
                else status.Text = "The selected item does not contain any recordings to play.";
            }
            else status.Text = "The selected item does not contain any attachments.";
        }
        else status.Text = "You haven't selected an item in the list.";
    }
    else status.Text = "There are no items in the list.";
}

Yeah, sure, I could just get rid of the if's and else's and replace ((Item)list...) with Item item = list... and wrap it all in a single Try{}Catch{}, but I really do hate using Try{}Catch{} unless there is something I am not expecting. And to be honest, using Try{} Catch{} makes me feel lazy and like I'm not doing it properly.

Is there any way I can improve this code and make it a little smaller (while still handling all of the cases where I would need to convey a message)?


texts:
I am working on a hobby project implementing a card game server with scotty and websockets.

The implementation of the game itself is more or less done. Now i am working on the server and I have an idea on how to structure it. Since I have never seen this approach anywhere, I am unsure whether I am missing something or there are problems I will probably run into.

The basic idea is to have a separate thread for each game and the server itself only handles the creation of games and users joining.

The types look something like this:

newtype ServerState = ServerState (TVar (Map GameID Game))

data Game = Game
    { threadID :: ThreadId
    , putEvent :: TMVar Event
    }

data Event = UserAction UserID Action
           | UserJoin User

data User = User { name :: String
                 , getAction :: IO Action
                 , putMessage :: Message -> IO ()
                 }

Each game thread would run in a loop, waiting for events (from the users or the Server), update the gamestate and send the new state to the users.

The scotty server looks something like this:

        post "/newgame" $ do
            gameID <- liftAndCatchIO $ createGame state
            json gameID

createGame :: ServerState -> IO GameID
createGame (ServerState var) = do
    gameID <- newGameID
    game   <- newGame
    atomically $ modifyTVar var (Map.insert gameID game)
    return gameID

newGame :: IO Game
newGame = do
    mvar   <- newEmptyTMVarIO
    thread <- forkIO $ gameThread mvar-- start game thread
    return Game { threadID = thread, putEvent = \e -> atomically (putTMVar mvar e) }

and websocket connections get handled like this:

wsServer :: ServerState -> ServerApp
wsServer (ServerState var) pending = do
    connection <- acceptRequest pending
    msg        <- receiveData connection
    case decode msg of
        Nothing -> sendClose connection ("invalid join request" :: Text)
        Just j  -> do
            let user = .., gameID = ..
            game <- Map.lookup gameID <$> readTVarIO var
            case game of
                Just g  -> putEvent game $ UserJoin User
                Nothing -> return ()

I already tested this with 1-2 games and it worked fine, but there is still a lot of work to do and i would like to know whether this approach is a dead end or will get complicated.


texts:
I'm trying to teach myself some Cython. To do so, I use Project Euler #10:

  The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
    2 Find the sum of all the primes below two million.

My Cython code is:

from libcpp.vector cimport vector
from libcpp cimport bool

SOLL = 142913828922

def run(unsigned long top = 2000000):

    cpdef unsigned long ist = 2
    cdef vector[bool] pos
    pos.resize(top, True)
    top //= 2

    # reduced_prime is (prime - 1)/2, since all primes (except 2) are uneven
    cpdef unsigned long reduced_prime, ind, prime

    for reduced_prime in range(1, top):
        if pos[reduced_prime]:
            prime = reduced_prime*2 + 1

            for ind in range(prime + reduced_prime, top, prime):
                pos[ind] = False

            ist += prime

    return ist

which needs about .19s to run. The following C++ code only needs .01s:

#include <vector>
#include <iostream>

int main() {
    unsigned long top = 2000000;
    unsigned long ist = 2;

    std::vector<bool> pos(top, 1);
    top /= 2;

    for (unsigned long reduced_prime = 1; reduced_prime < top; reduced_prime++) {
        if (pos[reduced_prime]) {
            unsigned long prime = reduced_prime*2 + 1;

            for (unsigned long ind = prime + reduced_prime; ind < top; ind += prime) {
                pos[ind] = 0;
            }

            ist += prime;
        }
    }

   std::cout << ist << std::endl;
}

Therefore I'm under the impression my Cython code is suboptimal.

For the off-chance it matters, Cython code was compiled with:

  cython src/e010.pyx -3 --cplus -o src/e010.cpp
  g++ -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.2mu src/e010.cpp -o src/e010.so

C++ code was compiled by:

  g++ e10.cpp -O2 -o e10

Timings are taken with time on Ubuntu 12.04.


texts:
I was reading the book Algortihms to Live By and was inspired by it to take a shot at simulating How to pair socks from a pile? (sans the efficiently part at the moment).

import random
from operator import add

def get_pair_of_socks(num_of_socks):
    return random.sample(range(num_of_socks), num_of_socks)

def index_to_pull_sock_from(bag_of_socks: list):
    return random.randint(a=0, b=len(bag_of_socks) - 1)

def attempt_counts_matching_socks(num_of_socks_to_consider):
    # Keep attempt counts in this list.
    attempt_counts = []

    # Generate pairs of random socks.
    socks = get_pair_of_socks(num_of_socks_to_consider) + get_pair_of_socks(num_of_socks_to_consider)

    while len(socks) != 0:
        # Pick one pair from the bag..
        first_pair = socks.pop(index_to_pull_sock_from(socks))

        # Pick a second pair..
        random_pick = index_to_pull_sock_from(socks)
        second_pair = socks[random_pick]

        # We did an attempt..
        attempt_count = 1

        # If they matched, perfect. We will never enter this block.
        # Otherwise loop until you do find the match..
        while second_pair != first_pair:
            # Increment the attempt_count whenever you loop..
            attempt_count = attempt_count + 1
            random_pick = index_to_pull_sock_from(socks)
            second_pair = socks[random_pick]

        # Remove the second matching pair from the bag..
        socks.pop(random_pick)

        # Keep the number of attempts it took you to find the second pair..
        attempt_counts.append(attempt_count)

    return attempt_counts

num_of_iterations = 1000
pair_of_socks = 10

# Initalise a list of length `pair_of_socks`
attempt_counts_so_far = [0] * pair_of_socks

for _ in range(num_of_iterations):
    # Get attempt counts for 1 iteration..
    attempt_counts_single_iteration = attempt_counts_matching_socks(pair_of_socks)

    # Add the attempt counts aligned by index. We will be dividing by the total number of iterations later for averages.
    attempt_counts_so_far = list(map(add, attempt_counts_so_far, attempt_counts_single_iteration))

average_takes = list(map(lambda x: x / num_of_iterations, attempt_counts_so_far))
print(average_takes)
# [18.205, 16.967, 14.659, 12.82, 11.686, 9.444, 7.238, 4.854, 2.984, 1.0]


texts: Safely log-in and save login info into session

texts:
I would like to ask if this code is safe for user to log-in (save ID to session) and check if user is log-in when visiting site (Dashboard).

@ll.route('/login', methods=['GET', 'POST'])
def LogIn():
  if request.method == 'GET':
     return render_template('login')
  elif request.method == 'POST':
     ....Checking password, hashing.....
     session.pop('User', None)
     session['User'] = id_User

     return redirect(url_for('LogINR.Dash'))
  else:
     return 'Method Not Allowed', 405

@ll.route('/dash')
def Dashboard():
  if g.User:
    return render_template('dash.html')
  return redirect(url_for('LogINR.LogIn'))

@mod.before_request
def before_request():
    g.User = None
    if 'User' in session:
        g.User = session['User']


texts:
This is the K&R Exercise 1-14 of C. The exercise ask you to print a histogram of the frequencies of different characters in input. How can I improve my code? The main doubt is the part when I have to increase letters in the array.

#include <stdio.h>
#include <ctype.h>

int main()
{
    int ch,
        nwhite,
        nother;

    int num[10] = {0};
    int lett[26] = {0};

    nwhite = nother = 0;

    while ((ch = getchar()) != EOF)
    {
        if (isdigit(ch))
            ++num[ch-'0'];
        else if (isalpha(ch))
        {
            if(ch >='A' && ch <= 'Z')
                ch = tolower(ch);

            if(ch >= 'a' && ch <= 'k')
                ++lett[ch-'a'];
            else if(ch >= 'l' && ch <= 'v')
                ++lett[ch-'l'];
            else if(ch >= 'w' && ch <= 'z')
                ++lett[ch-'w'];
        }

        else if (ch == ' ' || ch == '\n' || ch == '\t')
            ++nwhite;
        else
            ++nother;
    }

    putchar('\n');

    printf("Numbers|");
    for(int i = 0; i <= 10; ++i)
    {
        for(int j = 0; j < num[i]; ++j)
            putchar('*');
    }
    putchar('\n');

    printf("Letters|");
    for(int i = 0; i <= 10; ++i)
    {
        for(int j = 0; j < lett[i]; ++j)
            putchar('*');
    }
    putchar('\n');

    printf("White spaces|");
    for(int i = 0; i <= nwhite; ++i)
    {
        if(nwhite - i > 0)
            putchar('*');
    }
    putchar ('\n');

    printf("Others|");
    for(int i = 0; i <= nother; ++i)
    {
        if(nother - i > 0)
            putchar('*');
    }
    putchar ('\n');

    return 0;
}