texts:
I am really excited that I just wrote my Haskell maze solution in bfs.  This is my very first haskell (and I still haven't tried to build a maze in haskell so that maze is hard coded xD)

ANY suggestions all super welcome!!!

maze = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 2, 2, 2, 2, 2, 2, 2, 0],
        [0, 2, 0, 0, 0, 0, 0, 0, 0],
        [0, 2, 2, 2, 0, 2, 2, 2, 0],
        [0, 0, 0, 2, 0, 2, 0, 2, 0],
        [0, 2, 2, 2, 0, 2, 0, 2, 0],
        [0, 2, 0, 0, 0, 2, 0, 2, 0],
        [0, 2, 2, 2, 2, 2, 0, 2, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0]]
start = (7, 7)
end = (1, 7)

validPosition x y maze = (x >= 0) && (y >= 0) && (length maze) > y && (length (maze !! 0)) > x
getNode x y = if (validPosition x y maze) then Just ((maze !! y) !! x) else Nothing
getNeighborNode x y closed = filter (\(i, j) -> (getNode i j) == (Just 2) && (elem (i,j) closed) == False) [(x+a, y+b) | (a,b) <- [(0,-1),(0,1),(1,0),(-1,0)]]

bfsSolver ((i,j):xs) closed meta
    | ((i,j) /= end) = (bfsSolver (xs++neighbors) (closed++[(i,j)]) (meta++[((a,b), (i,j)) | (a,b)<-neighbors]))
    | otherwise = (constructPath (i,j) meta [])
    where neighbors = (getNeighborNode i j closed)

constructPath (i,j) meta route
    | (length points) > 0 = (constructPath (head points) meta (route++[(i,j)]))
    | otherwise = route++[(i,j)]
    where points = [(x,y) | ((a,b),(x,y)) <- meta, (a,b) == (i,j)]

-- bfsSolver [start] [] []


texts: Which is the better way to return a new instance of a boost intrusive_ptr

texts:
Unlike most(?) smart pointers, boost::intrusive_ptr has a non-explicit constructor. Given that, one could write

typedef boost::intrusive_ptr<Foo> FooPtr;

FooPtr MyFactory()
{
    return new Foo(a, b, c);
}

Or one could write

FooPtr MyFactory()
{
    return FooPtr(new Foo(a, b, c));
}

The latter is more consistent with how the code would have to be written if FooPtr were another kind of smart pointer, like shared_ptr or unique_ptr. The former is more concise. I personally prefer concise as long as it doesn't lead to trouble for readers and maintainers later. I'm wondering whether the former case is "too" concise?


texts:
I've built a simple class RequestHandler that does exactly what I want without any extras I won't be utilizing. When needed I will expand. I'm passing this object to my Router class, to route URls to the correct controller. I will also take any suggestions!

How is the readability?

Good idea to make it a singleton? There will always be 1 request to process at a time.

What about dependency injection? I didn't utilize dependency injection with this class. How else would I get the URI without using $_SERVER['REQUEST_URI'] or any other similar $_SERVER variable. So I don't see why I would inject it, while there are no other ways.

class RequestHandler
{
    private $rawUri;
    private $cleanUri;
    private $method;
    private $controller;
    private $action;
    private $params = [];

    public function __construct()
    {
        $this->rawUri   = $_SERVER['REQUEST_URI'];
        $this->cleanUri = preg_replace(['#/+#', '(\.\./)'], '/', trim($this->rawUri, '/'));
        $this->method   = $_SERVER['REQUEST_METHOD'];

        $this->parseUri();
    }

    private function parseUri()
    {
        //parse "/controller/action/param1/param2/..." format
        $parts = explode('/', $this->cleanUri);
        $parts = array_filter($parts);

        sort($parts);

        if ($parts) {
            $this->controller = ucfirst(array_shift($parts)) . 'Controller';
            $this->action     = array_shift($parts);
            $this->params     = ($parts) ? $parts : null;
        }
    }

    public function getRawUri()
    {
        return $this->rawUri;
    }

    public function getCleanUri()
    {
        return $this->cleanUri;
    }

    public function getMethod()
    {
        return $this->method;
    }

    public function getController()
    {
        return $this->controller;
    }

    public function getAction()
    {
        return $this->action;
    }

    public function getParams()
    {
        return $this->params;
    }
}


texts: Register script security and optimization

texts:
function RegisterN() {
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if (isset($_POST["password"],$_POST["password1"]) && $_POST["password"]!=$_POST["password1"]) { # Check if password and password1 are same
    echo "Your password confirmation is not equal to your password or it missing.";
        } else if(!$_POST["email"]){ # Check if email is present
        echo "Please enter your email.";
            } else if (!$_POST["password"]){ # Check if password is present again
            echo "Please enter your password";
                } else if (!$_POST["password1"]){ # Check if password1 is present again
                echo "Please enter your second password";
    } else {
     if (strlen ($_POST["password"])>25 || strlen ($_POST["password"])<6) # check password length max 25, min 6
        {
          echo "Password must be between 6 and 25 characters";
        } else {
        $dbh = new Database(); # Open database
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); # Small SQL injection security

            $stmt = $dbh->prepare('SELECT email FROM members WHERE email=?'); # Check if email exists
            $stmt->bindParam(1, $_POST['email'], PDO::PARAM_INT);
            $stmt->execute();
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if( ! $rows)
            { # No email found - moving on - If all set - let's register :)
                $email = $_POST['email'];
                $password = $_POST['password'];

                $hash_cost_log2 = 8;
                $hash_portable = FALSE;

                require("includes/PasswordHash.php"); # Hash password lib

                $hasher = new PasswordHash($hash_cost_log2, $hash_portable); # Hashing the password
                $hash = $hasher->HashPassword($password);
                if (strlen($hash) < 20)
                    fail('Failed to hash new password');
                unset($hasher);

                    $STH =$dbh->prepare("INSERT INTO members (email,password) VALUES (:email, :password)"); # Registering new user
                    $STH->bindParam(':email', $email);
                    $STH->bindParam(':password', $hash);
                    $STH->execute();

    echo "Account created successfully.";
    header('Refresh: 2; url=index.php'); # Redirect to index.php in 2 seconds

        } else { # email found - closing database - register fail
            $dbh=null;
            echo('Email already exists.');
            }
            $dbh=null; # Closing database after register
            }
            }
} else {
echo"Invalid Token."; # If user access the page without POST
} }

I want to know if I can make it more secure.  Before I made the script, I checked other scripts to see how they work, and what security measures they use.

What the script does:

Check if request comes from POST
Check if all fields ware filled ( It's being checked by JS as well, but that can be "cracked" )
Check if email already exists
Hash password
Finally register

In addition, I saw that other scripts are far smaller than mine.  Does that happen because they use frameworks?

Update  : OOP implemented ( http://pastebin.com/0DKVxrDK ) for check email and register


texts:
I made a preg_match to get my results and it works fine but I think it can be done with simple lines instead of repeating the code

$input = array('http://example.com/blue-bloods-s10e13-more-text/','http://example.com/charmed-2018-s02e11-more-text/','http://example.com/dynasty-2017-s03e11-more-text/','http://example.com/magnum-p-i-2018-s02e14-more-text/','http://example.com/fresh-off-the-boat-s06e13-more-text/','http://example.com/hawaii-five-0-2010-s10e14-more-text/','http://example.com/american-housewife-s04e13-more-text/','http://example.com/love-us-s01e13-more-text/');

    foreach ($input as $value ){
preg_match('/http:\/\/example.com\/([^`]*?)-s([0-9]{2})e([0-9]{2})/', $value, $matches);

$name = $matches[1];
$cname = preg_replace('/-us/', '', $name);
$cname1 = preg_replace('/-/', ' ', $cname);
$cname2 = preg_replace('/([0-9]{4})$/', '', $cname1);
$cname3 = preg_replace('/\s$/', '', $cname2);

echo $cname3."<br>";
}

The output is exactly like what I want

blue bloods
charmed
dynasty
magnum p i
fresh off the boat
Hawaii five 0
american housewife
love


texts:
This is a follow-up to

Quicksort function

Like the previous code, this does not optimize for containers with large numbers of duplicate elements. How can I improve this code, particularly with iterators?

template<typename C>
void insertion_sort(C low, C high) {
    for (auto i = low; i < high; ++i) {
        for (auto j = i; j != low && *j < *(j-1); --j) {
            std::swap(*j, *(j-1));
        }
    }
}

template<typename C, typename I>
I partition(C& c, I low, I high) {
    auto p = *low;
    I i = low;
    I j = high;
    while (true) {
        while (i+1 != std::end(c) && *(++i) < p) {
            if (i == high) {
                break;
            }
        }
        while (p < *(--j)) { }
        if (i >= j) {
            break;
        }
        std::swap(*i, *j);
    }
    std::swap(*low, *j);
    return j;
}

template<typename C, typename I>
void sort(C& c, I low, I high) {
    if (high <= low+15) {
        insertion_sort(low, high);
        return;
    }
    I p = partition(c, low,high);
    sort(c, low, p);
    sort(c, p+1,high);
}

template<typename C>
void sort(C& c) {
    if (std::begin(c) == std::end(c)) {
        throw std::out_of_range("no size");
    }
    if (c.size() == 1) {
        return;
    }
    std::random_shuffle(std::begin(c), std::end(c));
    sort(c, std::begin(c), std::end(c));
}


texts: Recursive spinlock for C using ASM, revision #1

texts:
Precursor for this revision here in code-review:

Recursive spinlock for C using ASM

Improvements have been made thanks to forsvarir.

Now I am trying to optimize this lock so it becomes more practical.

The code in question.

#define gate_Gate volatile int
#define gate_Pass volatile int

extern inline void
gate_Enter
(gate_Gate *gate, gate_Pass *pass)
{
    asm volatile (
        "jmp gate_Enter_check\n"
        "gate_Enter_wait:\n"
        "pause\n"
        "gate_Enter_check:\n"
        "cmp %[lock], %[pass]\n"     // Skip if pass >= lock
        "jge gate_Enter_skip\n"
        "mov %[lock], %%eax\n"       // Spinlock start
        "cmp %[gate], %%eax\n"       // Check if locked without lock cmd
        "je gate_Enter_wait\n"  // If locked, wait.
        "lock xchg %%eax, %[gate]\n" // Lock seems to be free, now we attempt to take it.
        "test %%eax, %%eax\n"
        "jnz gate_Enter_wait\n" // Spinlock end
        "gate_Enter_skip:\n"
        "add %[lock], %[pass]\n"     // Checkin pass
        : [gate] "=m" (*gate), [pass] "=m" (*pass)
        : [lock] "r" (1)
        : "eax"
    );
}

extern inline int
gate_Leave
(gate_Gate *gate, gate_Pass *pass)
{
    if (*pass <= 0) {
        // Signal underflow for debugging.
        return -1;
    }
    asm volatile (
        // Cleaner solution thanks to forsvarir/stackoverflow
        "add %[checkout], %[pass]\n"
        "jnz gate_Leave_skip\n"
        "mov %[unlock], %[gate]\n"
        "gate_Leave_skip:\n"
        : [gate] "=m" (*gate), [pass] "=m" (*pass)
        : [unlock] "r" (0), [checkout] "r" (-1)
        : "eax"
    );
    return 0;
}

// Example use. Like forsvarir pointed out, we have to be careful and keep pass on the stack.
void exampleUse(int count, gate_Pass pass)
{
    int underflow;
    printf("pass=%d, gate=%d\n", pass, gate);
    gate_Enter(&gate, &pass);
    if (count == 3) {
        // pass = 0; // force deadlock.
    }
    if (count < 5) {
        printf("Count = %d\n", count);
        exampleUse(++count, pass);
    }
    underflow = gate_Leave(&gate, &pass);
    if (!underflow) {
        printf("pass=%d, gate=%d\n", pass, gate);
    } else {
        printf("underflow detected\n");
    }
}
gate_Pass pass = 0;
exampleUse(0, pass);

The question

The intent of this code is a lock that allows recursion and does so efficiently.

Is there a point for this optimization? Am I right to assume that "lock" operator is very expensive and this approach is justified and right?
Is my attempt to early? Locking is hard to test. For this reason I strongly believe that spotting an error is a valid candidate for an answer.
Finally if all is well, there is always something to improve. This is a code review! Feel free to review the code as you see fit.


texts: Is this C++11 seqlock implementation correct?

texts:
My code: https://ideone.com/DZeIZv

#include <atomic>

template <class T> class Seqlock {
    std::atomic<int> seq_;
    T val_;

public:
    Seqlock(T value = T())
        : val_(value) {
    }

    // concurrent calls are NOT allowed
    void store(T value) {
        const int seq0 = seq_.load(std::memory_order_relaxed);
        seq_.store(seq0 + 1, std::memory_order_relaxed);

        std::atomic_thread_fence(std::memory_order_release);

        val_ = value;
        std::atomic_thread_fence(std::memory_order_release);

        seq_.store(seq0 + 2, std::memory_order_relaxed);
    }

    // concurrent calls are allowed
    T load() const {
        for (;;) {
            const int seq0 = seq_.load(std::memory_order_relaxed);
            if (seq0 & 1) {
                // cpu_relax()
                continue;
            }

            std::atomic_thread_fence(std::memory_order_acquire);

            T ret = val_;
            std::atomic_thread_fence(std::memory_order_acquire);

            const int seq1 = seq_.load(std::memory_order_relaxed);
            if (seq0 == seq1) {
                return ret;
            }
        }
    }
};

Is this seqlock implementation correct across all architectures, at least when T is an integral type? Can it be improved?

References I was following:

https://elixir.bootlin.com/linux/latest/source/include/linux/seqlock.h
https://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
https://github.com/rigtorp/Seqlock/


texts: Return value related to file content header

texts:
I have an attachment uploading feature in my web app.

File can have type- image/png or image/jpg or image/jpeg or application/pdf

For images, I need to return Photo, for pdf Document.

Documents will be only pdf, but images can be extended to images/ico, etc.

Now my code looks like this.

getAttachmentType(attachmentTypeHeader: string): string {
    if (
        attachmentTypeHeader === 'image/png' ||
        attachmentTypeHeader === 'image/jpg' ||
        attachmentTypeHeader === 'image/jpeg'
    ) {
        return 'Photo';
    }
    if (attachmentTypeHeader === 'application/pdf') {
        return 'Document';
    }
}

How I can make it check like image/*?


texts:
What I'm trying to do: implement the Vigenère cipher in Ruby. I already have a working version, but I want to make sure it is efficient and well-designed.

module Crypto
  # Vigenère cipher encryption and decryption abstraction
  module Vigenere
    LETTERS = ('a'..'z').to_a.freeze
    private_constant :LETTERS

    module_function

    # Encrypts a string
    #
    # @param string [String] the string that will be encrypted
    # @param key [String] the key that will be used to encrypt the string
    #
    # @return [String] the encrypted string
    def encrypt(string:, key:)
      key = make_key(length: string.length, key: key)

      string.length.times.map { |i|
        p = LETTERS.find_index(string[i])
        k = LETTERS.find_index(key[i])

        LETTERS[(p + k) % 26]
      }.join
    end

    # Decrypts an encrypted string
    #
    # @param string [String] the encrypted string that will be decrypted
    # @param key [String] the key that will be used to decrypt the string
    #
    # @return [String] the decrypted string
    def decrypt(string:, key:)
      key = make_key(length: string.length, key: key)

      string.length.times.map { |i|
        c = LETTERS.find_index(string[i])
        k = LETTERS.find_index(key[i])

        LETTERS[(c - k + 26) % 26]
      }.join
    end

    # Repeats a word until it matches a certain length
    #
    # @param length [Integer] the length of the word being encrypted/decrypted
    # @param key [String] the word that will be repeated
    #
    # @return [String] the word in its new form
    def make_key(length:, key:)
      i = 0
      length.times do
        i = 0 if i == key.length
        break if key.length == length

        key << key[i]
        i += 1
      end

      key
    end

    private_class_method :make_key
  end
end

I do have some specific questions:

1. private_class_method

This is the best way I found to define a private method in a module, but it feels weird to me. Isn't there a better way to do that? My first implementation was this:

module Crypto
  class Vigenere
    class << self
      def encrypt # ...
      def decrypt # ...

      private

      def make_key # ...
    end
  end
end

which was fine for me. But then I read this rule on the Ruby Style Guide repository. So I switched to using module, but it doesn't feel right to use private methods in this structure. Am I wrong?

2. reseting a counter (index)

Take a look at this snippet of code:

def make_key(length:, key:)
  i = 0
  length.times do
    i = 0 if i == key.length
    break if key.length == length

    key << key[i]
    i += 1
  end

  key
end

Defining a counter (i) and manually incrementing it... looks awkward, doesn't it (at least in the Ruby world)? Is there a better way to do this?

3. valid multi-line block with curly braces?

Now take a look at this snippet:

string.length.times.map { |i|
  p = LETTERS.find_index(string[i])
  k = LETTERS.find_index(key[i])

  LETTERS[(p + k) % 26]
}.join

I know most Ruby developers tend to use curly braces only for one-line blocks and do-end for multi-line blocks, but this time it seems okay using curly braces with a multi-line block, since I'm chaining #join right after. What would you do:

1. use do-end, store it in a variable and invoke #join after that

new_letters = string.length.times.map do |i|
  p = LETTERS.find_index(string[i])
  k = LETTERS.find_index(key[i])

  LETTERS[(p + k) % 26]
end

new_letters.join

2. what I did (use curly braces even with multi-line block and chain #join)

And of course, if you have any other observations, please share.


texts:
I have two optional strings, any of them can be None. I want to create their combination with a delimiter between them if they both exist.
I expect to be able to come with a more concise and nicer solution.
val seq = (Some("abc"), None)
val none = (None, None)
val both = (Some("abc"), Some("x"))

def concat(s: (Option[String], Option[String])): Option[String] = {
  s match {
    case (Some(a), Some(b)) => Some(a + ", " + b)
    case (a, None)          => a
    case (None, b)          => b
  }
}

concat(seq)
concat(none)
concat(both)

Can this be rewritten somehow in a more elegant way? The input can be changed from Tuple to Seq if desired.


texts:
I'm just writing a small unittest to test for a hypothetical library and object, as a way of predefining the behavior, perhaps both as an acceptance test and for unittesting as well. As I'm writing this, I'm wondering about the value of BDD constructs.

import unittest

def pv(data, rate):
    '''simple reference implementation for present value of a cash flow'''
    return sum(v/((1+rate)**i) for i, v in enumerate(data))

class CashFlowTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.data1 = [-10,1,2,3,4,5,6,7,8,9,10]
        cls.rate1 = .05
        cls.cf1 = CashFlow(cls.data1, rate=cls.rate1)
    def test_PV(self):
        self.assertEqual(pv(self.data1, self.rate1), self.cf1.PV)

Such an object then might be created like this:

import numpy as np

class CashFlow(object):
    def __init__(self, data, rate):
        self.data = numpy.array(data) if isinstance(data, (list, tuple)) else data
        self.rate = rate
    def present_value(self):
        rates = np.ones_like(self.data) + self.rate
        return (self.data/(rates**np.arange(len(self.data)))).sum()
    PV = property(present_value)

I would intend to write more unittests for other aspects of cashflows and various ways of handling cashflows, for example, IRR's, number of periods per year/rate, etc...

So I just ran this until the test passed, and went ahead and saved it. Thoughts? Criticisms? Is it bad to calculate both sides of the test? Should I use assertAlmostEqual() since there could be rounding errors?


texts: Array inside array (comment system with 2 levels)

texts:
I have a comment system on 2 levels (like Blizzard http://eu.battle.net/sc2/en/blog/7935264/#c-7257875753), it's working fine but my code is a bit dirty :

// $datacoms array from mysql_query
foreach($datacoms as $com){
    if(!$com->parent_id){
        $level_id = $com->id;
        // include the view (display the comment)

        foreach($datacoms as $com){
            if($com->parent_id == $level_id){
                // include the view (display the comment)
            }
        }
    }
}

Any better way to do it ?


texts: Simple Example of an Iterable and an Iterator in Java

texts:
I was a TA for a first-year Java programming course this year. As a very simple example of iterables/iterators, I wrote the following code for the students. I am curious if any styling or other improvements can be made.

import java.util.NoSuchElementException;
import java.util.Iterator;

public class Range implements Iterable<Integer> {
    private int start, end;

    public Range(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public Iterator<Integer> iterator() {
        return new RangeIterator();
    }

    // Inner class example
    private class RangeIterator implements
                    Iterator<Integer> {
        private int cursor;

        public RangeIterator() {
            this.cursor = Range.this.start;
        }

        public boolean hasNext() {
            return this.cursor < Range.this.end;
        }

        public Integer next() {
            if(this.hasNext()) {
                int current = cursor;
                cursor ++;
                return current;
            }
            throw new NoSuchElementException();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    public static void main(String[] args) {
        Range range = new Range(1, 10);

        // Long way
        Iterator<Integer> it = range.iterator();
        while(it.hasNext()) {
            int cur = it.next();
            System.out.println(cur);
        }

        // Shorter, nicer way:
        // Read ":" as "in"
        for(Integer cur : range) {
            System.out.println(cur);
        }
    }
}


texts:
I've designed a class ObjectPicker that can be given objects and weights. Objects can be picked randomly out of the ObjectPicker, with heavier weighted objects having a higher chance of being selected.

The pick() method is designed to be recursive and provide \$O(\log n)\$ speed. What I'm not sure about is the defaulting that's currently in place. I'm wondering if there is a better way to handle it. However, I would appreciate any feedback you are willing to provide beyond the specific.

class ObjectPicker:
    """
    An object that stores other objects with weights, and is able to
    pick out one stored object, with a higher chance for higher weighted
    objects.
    """

    def __init__(self):
        """
        Initialize the Object Picker object. Create the instance variable
        bucket for storing objects.
        """
        self.bucket = []

    def add(self, item, weight=1):
        """
        Add an item to the bucket, with given weight.
        :param item: Object to be stored.
        :param weight: Weight given to the object to determine odds.
        """
        if self.bucket:  # If there is anything in the bucket.
            total = self.bucket[-1][-1]  # Get the end number of the last item.
        else:  # If the bucket is empty.
            total = 0  # End number is 0.

        # Object stored in Tuple.
        # (Object, Weight, Starting Num, Ending Num)
        self.bucket.append((item, weight, total, total + weight))

    def pick(self, choice=-1, storage=None):
        """
        Pick an object from the bucket recursively,
        taking weight into account.
        :param choice: Number of choice.
        :param storage: Storage Object to choose from.
        """
        if not storage:  # If no storage is given.
            if not self.bucket:  # If bucket is empty.
                return None  # Return None.
            else:
                storage = self.bucket  # Storage is bucket
                total = storage[-1][-1]  # Get final weight.

        if choice < 0:  # If choice is < 0,
            # Randomly choose a number to represent the choice.
            choice = random.random() * total

        # Start binary search in middle of storage object.
        index = len(storage) // 2
        start, end = storage[index][2:]

        # If the choice is lower, recursively search left half.
        if choice < start:
            return self.pick(choice, storage[:index])
        # If the choice is higher, recursively search right half.
        elif choice > end:
            return self.pick(choice, storage[index + 1:])
        # Otherwise, choice is in number spread and return object.
        else:
            return storage[index][0]


texts:
I want to change (for better performance) or optimize my code, especially for and while loops, maybe with lambdas or list comprehensions.

def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    alphabet2 = alphabet[:]

    def removeDupsBetter(L1, L2):
        L1Start = L1[:]
        for e in L1:
            if e in L1Start:
                L2.remove(e)
        return ''.join(str(e) for e in L2)

    return removeDupsBetter(lettersGuessed, alphabet2)

def hangman(secretWord):
    '''
    secretWord: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many
      letters the secretWord contains.

    * Ask the user to supply one guess (i.e. letter) per round.

    * The user should receive feedback immediately after each guess
      about whether their guess appears in the computers word.

    * After each round, you should also display to the user the
      partially guessed word so far, as well as letters that the
      user has not yet guessed.

    Follows the other limitations detailed in the problem write-up.
    '''
    intro = str(len(secretWord))
    lettersGuessed = []
    guess = str
    mistakesMade = 8
    wordGuessed = False

    print 'Welcome to the game, Hangman!'
    print ('I am thinking of a word that is ') + intro + (' letters long.')
    print ('------------')

    while mistakesMade > 0 and mistakesMade <= 8 and wordGuessed is False:
        if secretWord == getGuessedWord(secretWord, lettersGuessed):
            wordGuessed = True
            break
        print ('You have ') + str(mistakesMade) + (' guesses left.')
        print ('Available letters: ') + getAvailableLetters(lettersGuessed)
        guess = raw_input('Please guess a letter: ').lower()
        if guess in secretWord:
            if guess in lettersGuessed:
                print ("Oops! You've already guessed that letter: ") + getGuessedWord(secretWord, lettersGuessed)
                print ('------------')
            else:
                lettersGuessed.append(guess)
                print ('Good guess: ') + getGuessedWord(secretWord, lettersGuessed)
                print ('------------')
        else:
            if guess in lettersGuessed:
                print ("Oops! You've already guessed that letter: ") + getGuessedWord(secretWord, lettersGuessed)
                print ('------------')
            else:
                lettersGuessed.append(guess)
                mistakesMade -= 1
                print ('Oops! That letter is not in my word: ') + getGuessedWord(secretWord, lettersGuessed)
                print ('------------')

    if wordGuessed == True:
        return 'Congratulations, you won!'
    elif mistakesMade == 0:
        print ('Sorry, you ran out of guesses. The word was ') + secretWord


texts: Memoizing decorator with retries, part 2

texts:
A while ago I asked this question Memoizing decorator that can retry and then promptly forgot about it. I more recently saw Python decorator for retrying w/exponential backoff and wanted to add backoff, but figured I should improve what I already have first. I have taken some of the suggestions of the original, but really I've just completely reimagined it (and if I do say so myself, rather cleverly too). My biggest issue with this is that I'm not sure that my current distinction between "exceptions that get suppressed but not remembered" and "exceptions that get remembered" seems like it might be a bit confusing - is there a friendlier interface here?

import functools
from types import MappingProxyType as FrozenDict

class Memoizer:

    def __init__(self, retry_times=0, suppressed_exceptions=tuple(), capture_exceptions=False):
        self.retry = retry
        self.retry_times = retry_times
        self.suppressed_exceptions = suppressed_exceptions
        self.capture_exceptions = capture_exceptions

    def __call__(self, function):
        d = {}

        @functools.wraps(function)
        def wrapper(*args, **kwargs, __forget=False):
            key = (args, FrozenDict(kwargs))
            if key not in d or __forget:
                i = self.retry_times
                while i > 1:
                    try:
                        d[key] = function(*args, **kwargs)
                    except self.suppressed_exceptions:
                        continue
                    except Exception as e:
                        if self.capture_exceptions:
                            d[key] = e
                            break
                        raise
                    else:
                        break
                    i -= 1
                else:
                    # If we didn't already break out, the last attempt shouldn't suppress exceptions
                    d[key] = function(*args, **kwargs)

            return d[key]

        return wrapper


texts:
Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.
Examples:
Input:
arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}
k = 3

Output:
3 3 4 5 5 5 6

Input:
arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}
k = 4

Output:
10 10 10 15 15 90 90

Looking for code-review, best practices, and optimizations.
public class MaxOfSubArrays {

    private MaxOfSubArrays() { }

    public static List<Integer> maxList(int[] a, int k)   {
        if (k <= 0) {
            throw new IllegalArgumentException("The value of k should atleast be 1.");
        }

        final Deque<Integer> deque = new ArrayDeque<Integer>();
        final List<Integer> result = new ArrayList<Integer>();

        int i;
        for (i = 0; i < k; i++) {
            while (!deque.isEmpty() && a[deque.peek()] <= a[i]) {
                deque.removeFirst();
            }
            deque.addLast(i);
        }

        for (; i < a.length; i++) {
            result.add(a[deque.peek()]);

            while (!deque.isEmpty() && deque.peek() <= i - k) {
                deque.removeFirst();
            }

            while (!deque.isEmpty() && a[deque.peek()] <= a[i]) {
                deque.removeFirst();
            }

            deque.addLast(i);
        }

        result.add(a[deque.peek()]);
        return result;
    }
}

public class MaxOfSubArraysTest {

    @Test
    public void test1() {
        int[] a1 = {1, 2, 3, 4, 5, 6};
        List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(3, 4, 5, 6));
        assertTrue(list1.equals(MaxOfSubArrays.maxList(a1, 3)));
    }

    @Test
    public void test2() {
        int[] a2 = {6, 5, 4, 3, 2, 1};
        List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(6, 5, 4, 3));
        assertTrue(list2.equals(MaxOfSubArrays.maxList(a2, 3)));
    }

}


texts: Excel VBA Filtering: AODB vs Autofilter vs SQLite

texts:
I have an Excel sheet with data in about 100,000 rows, 16 columns. I have to extract data (one value from the 1 row I find) from this table a few thousand times. I have been using Autofilter to extract this value, but have also tried AODB/SQL statements to see if I can improve the speed of the queries.

The data is sorted by column 1. When I use Autofilter, it takes on average 0.3 seconds to get my value, no matter the location of the value. AODB takes between 0.1 to 0.6 seconds to find the value, depending on where the value is in the table (if the value is near the top of the table, it takes 0.1 seconds, while if the data is near the end of the table it can take up to 0.6 seconds). I had expected the AODB to be much faster than Autofilter, but it seems that on average they are about the same.

When I import this data into SQLite and use a tool such as SQLiteStudio, the query returns the value in less than 0.01s!

Can I change anything in my code to to speed up the Queries in VBA?

Codes are below. AODB method:

Sub AODB_method()
'Freeze Screen and other options to run code faster
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayStatusBar = False
Application.EnableEvents = False

 Dim cn As ADODB.Connection
 Dim rs As ADODB.Recordset
 Dim vv As Double
 Dim Time2 As Double

Time2 = Timer

Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset

With ThisWorkbook
    If Application.Version < 12 Then
        cn.ConnectionString = _
          "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & .FullName & ";" & _
          "Extended Properties=Excel 8.0"
    Else
        cn.ConnectionString = _
          "Provider=Microsoft.ACE.OLEDB.12.0;" & _
          "Data Source=" & .FullName & ";" & _
          "Extended Properties=Excel 8.0"

     End If

     cn.Open

    Set rs = cn.Execute("SELECT [Cl] FROM [Table1$] WHERE [Wind]=150 AND [Weight]=200000 AND [Altitude] = 20000 AND [ISA] = 0")

    vv = rs.Fields(0).Value

    rs.Close
    cn.Close
End With

'Turn Options on again
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayStatusBar = True
Application.EnableEvents = True

Debug.Print "Connection Time: " & Timer - Time2
End Sub

Autofilter method:

Sub Autofilter_method()

'Freeze Screen and other options to run code faster
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayStatusBar = False
Application.EnableEvents = False
Dim vv As Double
Dim Time2 As Double

Time2 = Timer

With ThisWorkbook.Worksheets("Table1")
        .AutoFilterMode = False
        With .Range("A1:H1")
            .AutoFilter
            .AutoFilter Field:=4, Criteria1:=0
            .AutoFilter Field:=2, Criteria1:=200000
            .AutoFilter Field:=3, Criteria1:=20000
            .AutoFilter Field:=1, Criteria1:=-150

        End With

    End With

vv = Range("H" & finallastrow("Table1", "H")).Value

'Turn Options on again
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayStatusBar = True
Application.EnableEvents = True

Debug.Print "Connection Time: "; Timer - Time2
End Sub

Some Notes:

I am using Excel 2013. The Jet OLEDB provider seemed faster but I can't get the value to be saved in variable vv (I get an error).
When Wind is -150 (Column1, -150 is near the top of the table), the AODB query runs in 0.1s, while a wind value of +150 takes 0.6 seconds.

Thanks for your help!


texts:
I am having this problem with my code.  I have variables firstnumber and secondnumber, as well as operand and result. Then I am using the string.Split to know whether it's an operator or a number.

After that I have used a while loop if a.Length is over 2 and if it is, I declared an double numbers which is a[i]. i is 3 and gets + 2 every time the while loop executes.

Then I declared a variable called operands which is a[b].  b = 4 and gets + 2 every time the loop executes. Then I want to compare the string operands and the string operator, to see if it is +, -, * or / in the end I have put an if statement, so that if a[i] == null, then the while loop breaks and the result is printed.

I know my code is messy, and I have probably done many things wrong here, so I would really appreciate every word of advice I can get.

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

namespace ConsoleApplication1
{
 class Calculator
 {
     static void Main(string[] args)
     {
        Console.WriteLine("This is a calculator. enter the numbers this way: Example(4 + 3)");
        Console.WriteLine("!Use space between numbers!");
        start : string s = Console.ReadLine();
        overagain:  string [] avgränsare = { " " };
        string[] a = s.Split(avgränsare, StringSplitOptions.RemoveEmptyEntries);

        while (a.Length > 2)
        {
            int i = 3;
            int b = 4;
            double numbers = double.Parse(a[i]);
            i = i + 2;
            b = b + 2;

            double firstnumber = double.Parse(a[0]);
            string operand = a[1];
            double secondnumber = double.Parse(a[2]);
            double result = 0;
            string operands = a[b];
            goto overagain;

                if (a[i] == null)
                {
                  Console.WriteLine(result);
                  break;
                }
            }

        Console.WriteLine("Do you want to continue?");
        s = Console.ReadLine().ToLower();
        if (s == "y")
        {
            goto start;
        }
        else
        {
        }

        }
    }
 }


texts:
I'm super new to PHP and I'm trying to get a functional login system together. This is the code I have:

class/user.php

<?php
 class Users {
     public $username = null;
     public $password = null;
     public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";

     public function __construct( $data = array() ) {
         if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
         if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
     }

     public function storeFormValues( $params ) {
        //store the parameters
        $this->__construct( $params );
     }

     public function userLogin() {
         $success = false;
         try{
            $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
            $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

            $stmt = $con->prepare( $sql );
            $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
            $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
            $stmt->execute();

            $valid = $stmt->fetchColumn();

            if( $valid ) {
                $success = true;
            }

            $con = null;
            return $success;
         }catch (PDOException $e) {
             echo $e->getMessage();
             return $success;
         }
     }

     public function register() {
        $correct = false;
            try {
                $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
                $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                $sql = "INSERT INTO users(username, password) VALUES(:username, :password)";

                $stmt = $con->prepare( $sql );
                $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
                $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
                $stmt->execute();
                return "Registration Successful
 Login Now";
            }catch( PDOException $e ) {
                return $e->getMessage();
            }
     }

 }

?>

login.php

<?php
    include_once("config.php");
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
    <form method="post" action="">
        <input type="text" maxlength="30" required autofocus name="username" />
        <input type="password" maxlength="30" required name="password" />
        <input type="submit" name="login" value="Log me in" />
    </form>
<?php
} else {
    $usr = new Users;
    $usr->storeFormValues( $_POST );

    if( $usr->userLogin() ) {
        echo "Welcome";
    } else {
        echo "Incorrect Username/Password";
    }
}
?>

register.php

<?php
    include_once("config.php");
?>

<?php if( !(isset( $_POST['register'] ) ) ) { ?>
    <form method="post">
        <input type="text" id="usn" maxlength="30" required autofocus name="username" />
        <input type="password" id="passwd" maxlength="30" required name="password" />
        <input type="password" id="conpasswd" maxlength="30" required name="conpassword" />
        <input type="submit" name="register" value="Register" />
    </form>

<?php
} else {
    $usr = new Users;
    $usr->storeFormValues( $_POST );

    if( $_POST['password'] == $_POST['conpassword'] ) {
        echo $usr->register($_POST);
    } else {
        echo "Password and Confirm password not match";
    }
}
?>

I am really keen to know how this code is structured, as I used information from several different tutorials combined to create it. Any input would be appreciated.


texts:
I have this middleware to log the number of queries, the time spent on each view and some errors and tracebacks.

This will be called on each request, so I had to put a 75ms timeout. I don't like it, but I feel like using async request for this is unnecessary, I don't care about the host response.

What do you think? Can I improve this in any way?

import sys
import traceback
import os
import json
import time
import requests
from django.conf import settings

CUSTOM_LOG_AGENT_HOST = 'http://localhost:9875'
CUSTOM_LOG_AGENT_HEADERS = {}
CUSTOM_LOG_AGENT_TIMEOUT = 0.0075

class SimpleMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        self.customLogAgent = {}

        request.start_time = time.time()
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        response = self.get_response(request)
         # Code to be executed for each request/response after
        # the view is called.

        total = time.time() - request.start_time
        self.customLogAgent['queries'] = connection.queries
        self.customLogAgent['time'] = int(total * 1000)
        try:
            url = getattr(settings, 'CUSTOM_LOG_AGENT_HOST', CUSTOM_LOG_AGENT_HOST)
            headers = getattr(settings, 'CUSTOM_LOG_AGENT_HEADERS', CUSTOM_LOG_AGENT_HEADERS)
            timeout = getattr(settings, 'CUSTOM_LOG_AGENT_TIMEOUT', CUSTOM_LOG_AGENT_TIMEOUT)

            requests.post(url, headers=headers, json=self.customLogAgent, timeout=timeout)
        except requests.exceptions.RequestException as e:
            print(e)
        print(json.dumps(self.customLogAgent, indent=4))

        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        self.customLogAgent['view_func'] = view_func.__name__
        self.customLogAgent['view_kwargs'] = view_kwargs
        self.customLogAgent['url'] = request.get_full_path()

    def process_exception(self, request, exception):
        ltype, lvalue, ltb = sys.exc_info()
        error = {}
        error['type'] = ltype.__name__
        error['message'] = str(lvalue)
        error['line'] = ltb.tb_lineno
        error['traceback'] = ''.join(traceback.format_tb(ltb))
        self.customLogAgent['error'] = error
        return None


texts: Generating a Postgres query dealing with creating a time series

texts:
I want to sum the number of my published publications model in a given interval and return a time series. (related SO)

The main challenge is that I want the code to respect the time zone passed to it. This seems to be only relevant when it comes down to aggregate the publications over days as different timezones would lead to different results (e.g. a post around midnight could belong to either day depending on the time zone).

My current (most likely working) code is covered by two methods that look like this:

def publications_time_series_relation(start_date, end_date, interval, organization_id, time_zone_offset)
  if interval == 'day'
    per_day(start_date, end_date, interval, organization_id, time_zone_offset)
  else
    Publication.select(
      %{date_trunc('#{interval}',
      published_at::timestamptz) as time,
      count(published_at)})
               .published
               .where.not(published_at: nil)
               .where(organization_id: organization_id)
               .where(%(published_at BETWEEN
          timestamptz '#{start_date}' AND
          timestamptz '#{end_date}'))
               .group('1')
               .order('time').limit(LIMIT)
  end
end

def per_day(start_date, end_date, interval, organization_id, time_zone_offset)
  Publication.select(
    %{date_trunc('#{interval}',
      published_at::timestamptz at time zone interval '#{time_zone_offset}')::timestamptz as time,
      count(published_at)})
             .published
             .where.not(published_at: nil)
             .where(organization_id: organization_id)
             .where(%(published_at BETWEEN
          timestamptz '#{start_date}' AND
          timestamptz '#{end_date}'))
             .group('1')
             .order('time').limit(LIMIT)
end

It looks very clumsy to me. I was hoping to find a way to not have to deal with days differently than other intervals.


texts: Returning the length of the File in B/KB/MB

texts:
The method length() in File returns the length of a file in Bytes, this code transforms that into b/kb/mb as can be seen in the Windows Explorer

I ended up with the code below, let me know if it can be optimized or the logic can be improved.

public static String getFileSize(File file) {
    String modifiedFileSize = null;
    double fileSize = 0.0;
    if (file.isFile()) {
        fileSize = (double) file.length();//in Bytes

        if (fileSize < 1024) {
            modifiedFileSize = String.valueOf(fileSize).concat("B");
        } else if (fileSize > 1024 && fileSize < (1024 * 1024)) {
            modifiedFileSize = String.valueOf(Math.round((fileSize / 1024 * 100.0)) / 100.0).concat("KB");
        } else {
            modifiedFileSize = String.valueOf(Math.round((fileSize / (1024 * 1204) * 100.0)) / 100.0).concat("MB");
        }
    } else {
        modifiedFileSize = "Unknown";
    }

    return modifiedFileSize;
}


texts:
I am implementing a Point in polygon algorithm.

Inputs:

M, N: size of the matrix
poly: a list of tuples that represent the points of polygon.

Output:

A mask matrix which is ones everywhere, except the point in the polygon should be 0.

import numpy as np
import cv2

def getABC(x1, y1, x2, y2):
    A = y2 - y1
    B = x1 - x2
    C = A*x1 + B*y1
    return (A, B, C)

def polygon(M, N, poly):
    out = np.ones((M, N))*255

    n = len(poly)
    for i in range(M):
        intersection_x = i
        intersection_y = []

        # check through all edges
        for edge in range(n + 1):
            v1_x, v1_y = poly[edge % n]
            v2_x, v2_y = poly[(edge + 1) % n]

            A1, B1, C1 = getABC(v1_x, v1_y, v2_x, v2_y)
            A2 = 1
            B2 = 0
            C2 = i

            # find intersection
            det = A1*B2 - A2*B1
            if (det != 0):
                tmp = (A1 * C2 - A2 * C1)/det
                if tmp >= min(v1_y, v2_y) and tmp <= max(v1_y, v2_y):
                    intersection_y.append(tmp)

    intersection_y = list(set(intersection_y))
    print intersection_y

    if len(intersection_y) == 1:
        intersection_y.append(intersection_y[0])

    for k in range(1, len(intersection_y), 2):
        out[intersection_x, intersection_y[k - 1]:intersection_y[k]] = 0

    return out

poly = [(10,20), (10,40), (30,20), (30,40)]

out = polygon(100,100, poly)

cv2.imwrite("out.png", out)

Is this the optimal algorithm? I use a scanning line, find the intersection with edges and make all the point between the intersections to be zero.


texts:
In order to avoid the user having to explicitly prefix a script with sudo or su --command, I wrote the following:

import sys
import os

if os.getuid():
    root = "/usr/bin/sudo"
    if not os.path.exists("/usr/bin/sudo"):
        root = "/bin/su --command"
    command = "{} {}".format(root, sys.argv[0])
    command = command.split()
    retcode = subprocess.call(command)
    if retcode:
        print("something wrong happened")
else:
    action_that_needs_admin_rights()

It feels like a hack to me, so am looking forward to better approaches.


texts: Would this linked list be considered clean if written in an hour-long interview?

texts:
If you were interviewing me, and saw this code written in a little under an hour, would you consider me as a candidate for a position at your company if you knew I had 2 years of C++ experience?

#include <stdlib.h>
#include <cassert>

/*! \class Node to be used in likned list like constructors
 */
template <typename T>
class node
{
private:
  T data;
  node * next;

public:
  /*! \brief Default constructor
   * Initialize next pointer to NULL and let data's default constructor
   * be called
   */
  node() :
    next(NULL)
  {}

  /*! \brief Parametered constructor
   * Initialize next pointer to NULL and set data to t
   */
  node(T t) :
    data(t),
    next(NULL)
  {}

  /*! \brief Copy constructor
   */
  node(const node & other) :
    data(other.data),
    next(other.next)
  {}

  /*! \brief Destructor
   */
  ~node()
  {}

  /*! \brief Assignment operator
   */
  node & operator=(const node &other)
  {
    data = other.data;
    next = other.next;

    return (*this);
  }

  /*! \brief Set the next pointer
   */
  void set_next(node *next_node)
  {
    next = next_node;
  }

  /*! \brief Set the nodes data
   */
  void set_data(T t)
  {
    data = t;
  }

  /*! \brief Get the nodes data
   */
  T get_data() {
    return data;
  }

  /*! \brief Get the nodes next pointer
   */
  node * get_next()
  {
    return next;
  }

  /*! \brief Equivalence operator
   */
  bool operator==(const node &other)
  {
    return (data == other.data && next == other.next);
  }

  /*! \brief Not equivalence operator
   */
  bool operator!=(const node &other)
  {
    return (data != other.data || next != other.next);
  }
};

/*! \class Linked List
 */
template <typename T>
class linked_list
{
private:
  node<T> * head;

public:
  /*! \brief Default constructor
   * Initialize head pointer to NULL
   */
  linked_list() :
    head(NULL)
  {}

  /*! \brief Parametered constructor
   * Initialize head to a node
   */
  linked_list(node<T> &n) :
    head(&n)
  {}

  /*! \brief Copy constructor
   */
  linked_list(const linked_list & other) :
    head(other.head)
  {}

  /*! \brief Destructor
   */
  ~linked_list()
  {}

  /*! \brief Assignment operator
   */
  linked_list & operator=(const linked_list &other)
  {
    head = other.head;

    return (*this);
  }

  /*! \brief Get the head node pointer
   */
  node<int> * get_head()
  {
    return head;
  }

  /*! \brief Equivalence operator
   */
  bool operator==(const linked_list &other)
  {
    return (head == other.head);
  }

  /*! \brief Not equivalence operator
   */
  bool operator!=(const linked_list &other)
  {
    return (head != other.head);
  }
};

void unit_test_linked_list()
{
  // Default constructor
  linked_list<int> l0;
  assert(!l0.get_head());

  // Parametered constructor
  node<int> n(5);
  linked_list<int> l1(n);
  assert(l1.get_head()->get_data() == 5);

  // Copy construtor
  linked_list<int> l2(l1);
  assert(l2 == l1);

  // Assignment and equivalence
  l0 = l2;
  assert(l2 == l1);
  assert(l2 == l0);
  assert(l1 == l0);
}

void unit_test_node()
{
  // Default constructor
  node<int> n;
  assert(!n.get_next());

  // Parameterd constructor and assignment operator
  n = node<int>(5);
  assert(!n.get_next() && n.get_data() == 5);

  // Copy constructor equivalence operator and not equivalent operator
  node<int> m(n);
  assert(n.get_data() == m.get_data() && n.get_next() == m.get_next());
  assert(!(m != n) && m == n);

  // Setters and getters
  m.set_data(6);
  m.set_next(&n);
  assert(m.get_data() == 6 && m.get_next()->get_data() == 5);
  assert(m.get_next()->get_next() == NULL);
}

int main()
{
  unit_test_node();
  unit_test_linked_list();
}


texts:
Someone on SO asked how to fill in the NA's with row means. His example code was:

cancer1 <- read.table("cancer.txt", stringsAsFactors = FALSE, quote='', header=TRUE,sep='\t')

Since he didn't provide the data I think we can simulate it with:

cancer1 <- data.frame(a=rep(c(1,2,3,NA),10),b=rep(c(1,2,3,4),10), c=seq(1,40,1))

Just bear in mind that the example data is an arbitrary simulation.

My answer was:

for(i in 1:nrow(cancer1)){
  for(n in 1:ncol(cancer1)){
    if(is.na(cancer1[i,n])){
        cancer1[i,n]  <-  mean(t(cancer1[i,]), na.rm = T)# or  rowMeans(cancer1[i,], na.rm=T)
    }
    }
}

I know that this can be vectorized and otherwise improved, but I'm just not sure how.


texts: How to connect a propery class/object with a collection (its database class)?

texts:
I'm struggling with organizing my code regarding 'best practise'. In particular how I link a class with its collection class.

I've 2 classes:

class car
{
    private $color;
    private $model;
    private $speed;

    public function getColor() {}
    public function setColor() {}
    public function getModel() {}
    public function setModel() {}
    public function getSpeed() {}
    public function setSpeed() {}
}

class carLoader
{
    public function loadAllCars()
    {
        // load all cars from the database
        ...

        // iterate through the result and create an object for each car
        $allCars = array();
        foreach ($result as $carName => $carData) {
            $allCars[$carName] = $this->createCar($carData);
        }

        return $allCars;
    }

    private function createCar(array $carData)
    {
        $car = new Car();

        $car->setColor($carData['color']);
        $car->setModel($carData['model']);
        $car->setSpeed($carData['speed']);

        return $car;
    }
}

Now I have an array with all car objects. So far so good. However, I am not sure whats the best approach to save manipulated properties in the database. Or in other words, how to connect the property class 'car' to the database because (as far as I've learned) it should NOT contain any database queries but only the properties.

One solution I came up with is to add a collection function which holds an object of a new 'collection' class. So my solution would look like:

class car
{
    private $color;
    private $model;
    private $speed;

    private $collection;

    public function getColor() { return $this->color; }
    public function setColor() { return $this->getCollection()->saveColor($value); }
    public function getModel() { return $this->model; }
    public function setModel() { return $this->getCollection()->saveModel($value); }
    public function getSpeed() { return $this->speed; }
    public function setSpeed() { return $this->getCollection()->saveSpeed($value); }

    public function getCollection()
    {
        return $this->collection;
    }

    public function setCollection($collection)
    {
        $this->collection = $collection
}

class carLoader
{

    public function __construct(DbManager $pdo)
    {
        $this->pdo = $pdo;
    }

    public function loadAllCars()
    {
    // load all cars from the database
    ...

    // iterate through the result and create an object for each car
    $allCars = array();
    foreach ($result as $carName => $carData) {
        $allCars[$carName] = $this->createCar($carData);
    }

    return $allCars;
    }

    private function createCar(array $carData)
    {
        $car = new Car();

        $car->setColor($carData['color']);
        $car->setModel($carData['model']);
        $car->setSpeed($carData['speed']);
        $car->setCollection($this-getCollection());

        return $car;
    }

    private function getCollection()
    {
        if ($this->carCollection === null) {

            $this->carCollection = new CarCollection($this->pdo);
        }

        return $this->carCollection;
    }
}

class carCollection()
{
    public function __construct(DbManager $pdo)
    {
        $this->pdo = $pdo;
    }

    public function getCollection()
    {
        // logic to save the data in the database
    }
}

Is this a 'good' way to do it if I do need to work with the array of car objects? How else should I save new values (color, speed, model) in the database?

Thank you very much


texts: Displaying Singapore bus arrival times using a Go template

texts:
I am wondering whether my template usage in main.go could be better. For example in other code I notice:

var views = template.Must(template.ParseGlob("static/*.tmpl"))

Defined outside main, hence the templates are loaded on process start. And then in the handler:

views.ExecuteTemplate(w, "passwordprompt.tmpl", map[string]interface{}{})

In my own code, I am wondering if it is worth applying the same practice. Is it possible with functions & the code below?

func handleIndex(w http.ResponseWriter, r *http.Request) {
    funcs := template.FuncMap{
        "nameBusStopID": func(s string) string { return bs.nameBusStopID(s) },
        "getenv":        os.Getenv,
    }

    t, err := template.New("").Funcs(funcs).ParseFiles("templates/index.html")

    if err != nil {
        log.WithError(err).Error("template failed to parse")
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    arriving, err := busArrivals(r.URL.Query().Get("id"))
    if err != nil {
        log.WithError(err).Error("failed to retrieve bus timings")
    }

    t.ExecuteTemplate(w, "index.html", arriving)
}

Please feel free to critique all the code.


texts: Spatial parametric scaling in agent-based model

texts:
I’m running a simple agent-based disease spread model on a 2D lattice, where disease transmission in a population depends on each individual’s chance of avoiding infection at every time step, which decreases with the local density of the infected and transmission rate.

import numpy as np
import random
from math import *
from scipy.signal import fftconvolve
import matplotlib.pyplot as plt

plt.ion()
plt.show()

''' Landscape parameters ''' # slightly unusual setup
L = 10.
nx = 100
dx = L/nx
hs = 0.5 * dx  # half-step
ulist = np.linspace(hs, L-hs, nx)

''' Epidemiological parameters '''
alpha = .1  # spatial scale used for convolution when approx. local densities
delta = .5  # transmission rate

''' Infection kernel '''  # kernel function is a bivariate Gaussian with zero covariance
i, j = ulist.reshape(nx,1), ulist.reshape(1,nx)
ii = np.minimum(i-ulist[0], L-i+ulist[0])
jj = np.minimum(j-ulist[0], L-j+ulist[0])

# bivariate Gaussian: [functional form][1]
norm_constant = 1/(2*pi*alpha**2)
xmu = (ii-0)/alpha; ymu = (jj-0)/alpha
rhs = np.exp(-.5 * (xmu**2 + ymu**2))
z = norm_constant * rhs

ker = np.roll(z, np.int(nx//2-1), 0)
ker = np.roll(ker,np.int(nx//2-1), 1)

''' Infection function '''
def infect2(ido_, idx_):  # ido: "healthy" individuals; idx: "infected" individuals
    og = np.zeros((nx,nx))
    np.add.at(og, (idx_[:,0], idx_[:,1]), 1)  # tally the local number of infected

    dd = fftconvolve(og, ker, mode='same')  # 2D convolution

    dx_lo = dd[ido_[:,0], ido_[:,1]] # density of infected local to the "healthy" individuals
    transmit = 1-np.exp(-delta  * dx_lo)
    mask = np.random.random(len(ido_)) > transmit
    ido_new = ido_[mask]
    idx_new = np.vstack((idx_, ido_[~mask]))
    return ido_new, idx_new, dd

''' Population distribution '''
ido = np.random.randint(nx, size=(19999,2)).astype(np.int)
idx = np.array([[np.floor(nx/2), nx-np.ceil(.5*nx)]]).astype(np.int)

''' Simulation '''
for t in range(15):
    print 't=', t
    plt.cla()
    ido, idx, dd = infect2(ido, idx)

    plt.plot(ulist[ido[:,1]], ulist[ido[:,0]], 'ko', alpha=.1)
    plt.plot(ulist[idx[:,1]], ulist[idx[:,0]], 'ro', alpha=.3)
    print len(idx)
    plt.xlim([0., L]); plt.ylim([0., L])
    plt.axes().set_aspect('equal')
    plt.draw()
    time.sleep(0.01)

    if len(ido) == 0: break

Increasing lattice resolution by setting nx=200 appeared to also change the resulting dynamics. I tried to fix this by spatially scaling the transmission rate setting delta = .5 /dx**2, I'm not sure about the reasoning behind this scaling method but it did make the results closer to those under nx=100. How can I further improve on the similarity between systems under different spatial resolutions? And what would be the mathematical/numerical justifications for those fixes?


texts:
Purpose

Validate if a number is an Armstrong Number.

An Armstrong Number is a number

  such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 33 + 73 + 13 = 371.

Strategy

Calculate the remainder and quotient of the candidate value.
While the quotient is greater than 0 and the digit sum is not greater than the candidate value, calculate the new remainder, the new quotient, and add remainder raised by 3 to the digit sum.

Implementation

public class ArmstrongNumberValidatorImpl implements ArmstrongNumberValidator {
    @Override
    public boolean isArmstrong(final long candidate) {
        if (candidate < 0) {
            throw new IllegalArgumentException("candidate value must be non-negative");
        }

        long remainder = candidate % 10;
        long quotient = candidate / 10;
        long digitSum = Math.multiplyExact(Math.multiplyExact(remainder, remainder), remainder);
        while (quotient > 0 && digitSum <= candidate) {
            remainder = quotient % 10;
            quotient = quotient / 10;
            digitSum += Math.multiplyExact(Math.multiplyExact(remainder, remainder), remainder);
        }

        return (0 == quotient && digitSum == candidate);

    }
}


texts:
I implemented a simple class container for hdf5 files in matlab.

The situation is as follows. Measurement data is saved in hdf5 format together with a lot of meta data. I want to provide a tool to easily load the table of data to browse though the name and then only load the necessary data with as little overhead (mostly code length wise for the user, but of course also performance) for the user as possible. I came up with this easy solution.

The used Dataformat only delivers data with groupdepth of 1.

classdef h5 < handle
    properties(Access = private)
        % container for the actual values, if empty this means that the
        % value has not been loaded yet. Induvidual fields get loaded
        % during access
        val

        % name of all the fields, this get loaded during construction
        name = {}

        filename
        pfad
    end

    methods
        %% constructor
        function o = h5(pfad)
            info = h5info(pfad);
            o.filename = info.Filename;
            o.pfad = pfad;

            % Add the possible fields to the name array
            for element = info.Datasets'
                o.name{end+1} = element.Name;
            end

            for group = info.Groups'
                for element = group.Datasets'
                    o.name{end+1} = [group.Name(2:end) '/' element.Name];
                end
            end

            o.val = cell(size(o.name));
        end

        %% show the possible values
        function disp(o)
            fprintf('h5 file loaded from %s with the fields:\n\n',o.filename);

            for name = o.name
                fprintf('%s\n',name{1});
            end
        end

        %% get the dataset
        function out = get(o,name)
            pos = strcmp(name,o.name);

            % Does the dataset exist?
            if sum(pos) == 0
                warning('Dataset doesn''t exist')
                out = [];
                return
            end

            % Did we already load it?
            if isempty(o.val{pos})
                o.val{pos} = h5read(o.pfad,['/' o.name{pos}]);
            end

            out = o.val{pos};
        end
    end
end

Do you see any obvious oversights on my sight with this or anything I should change?


texts:
Obviously, you have to test mapping code somehow, even (or especially) if you use AutoMapper. Is there any way to make it less verbose?

[Test]
public void Map_Always_SetsSimpleProperties()
{
  var auctionPlace = fixture.Create<string>();
  var submissionCloseDateTime = fixture.Create<DateTime>();
  var quotationForm = fixture.Create<string>();
  var quotationExaminationDateTime = fixture.Create<DateTime>();
  var envelopeOpeningTime = fixture.Create<DateTime>();
  var envelopeOpeningPlace = fixture.Create<string>();
  var auctionDateTime = fixture.Create<DateTime>();
  var applExamPeriodDateTime = fixture.Create<DateTime>();
  var considerationSecondPartDate = fixture.Create<DateTime>();

  var doc = fixture.Create<Notification223>();

  doc.AuctionPlace = auctionPlace;
  doc.SubmissionCloseDateTime = submissionCloseDateTime;
  doc.QuotationForm = quotationForm;
  doc.QuotationExaminationTime = quotationExaminationDateTime;
  doc.EnvelopeOpeningTime = envelopeOpeningTime;
  doc.EnvelopeOpeningPlace = envelopeOpeningPlace;
  doc.AuctionTime = auctionDateTime;
  doc.ApplExamPeriodTime = applExamPeriodDateTime;
  doc.ConsiderationSecondPartDate = considerationSecondPartDate;

  var sut = CreateSut();

  var actual = sut.Map(doc);

  Assert.That(actual.AuctionPlace, Is.EqualTo(auctionPlace));
  Assert.That(actual.SubmissionCloseDateTime, Is.EqualTo(submissionCloseDateTime));
  Assert.That(actual.QuotationForm, Is.EqualTo(quotationForm));
  Assert.That(actual.QuotationExaminationDateTime, Is.EqualTo(quotationExaminationDateTime));
  Assert.That(actual.EnvelopeOpeningTime, Is.EqualTo(envelopeOpeningTime));
  Assert.That(actual.EnvelopeOpeningPlace, Is.EqualTo(envelopeOpeningPlace));
  Assert.That(actual.AuctionDateTime, Is.EqualTo(auctionDateTime));
  Assert.That(actual.ApplExamPeriodDateTime, Is.EqualTo(applExamPeriodDateTime));
  Assert.That(actual.ConsiderationSecondPartDate, Is.EqualTo(considerationSecondPartDate));
}


texts: A scalable function for get boundary vertices in a graph

texts:
Given a community division I need a list of vertices that have edges in more than one community, i.e., boundary vertices.

I've tried this:

import igraph
import time

if __name__ == "__main__":
    g = igraph.Nexus.get("condmatcollab2005")

    tic = time.clock()
    cl = g.community_fastgreedy()
    membership = cl.as_clustering().membership
    print "community time: "+str(time.clock() - tic)

    # --> Do I need to leave this part more faster =======
    tic = time.clock()
    boundary = []
    visited = set()
    for vertex in g.vs():
        if vertex.index in visited: continue
        for neighbor in g.neighbors(vertex.index):
            if membership[vertex.index] != membership[neighbor]:
                boundary.append(vertex.index)
                visited.add(vertex.index)
                if neighbor not in visited:
                    boundary.append(neighbor)
                    visited.add(neighbor)
                break
    print "boundary time: "+str(time.clock() - tic)

This implementation is very slow. I don't if there is a faster way or more cleaner to do this.

E.g., maybe there is a faster way by using the cl.as_clustering() object or other data structure more efficient.

I need some help with optimizing my code.


texts: Looping over a bidimensional array and extract data to a new one

texts:
I have a bidimensional array like this:

const bArray =
[ [ 'Hello World',
    'Hi everybody',
    'How are you?'
  ],
  [ { text: 'Hola Mundo',
      from: [Object],
      raw: '' },
    { text: 'Hola a todos',
      from: [Object],
      raw: '' },
    { text: 'Cómo estás?',
      from: [Object],
      raw: '' },
  ]
]

And I need to get as a result, only one array that should look like this:

[
 { en: 'Hello World',
   es: 'Hola Mundo' },

 { en: 'Hi everybody',
   es: 'Hola a todos' },

 { en: 'How are you?',
   es: 'Cómo estás?' },
]

This is how I do it:

let val1 = bArray[0].map(tuple => tuple);
let val2 = bArray[1].map(tuple => tuple);

let result = val1.reduce((arr, v, i) => arr.concat({"en" : v, "es" : val2[i].text}), []);

And now in the result variable, I have only one array with the result showed before.

My question?

Is there any improved way in which I can get the same result but with fewer lines of code? I mean, something like a combination of map with reduce, filter or concat in only one or two lines of code.


texts:
I have been unable to find any other way to update a user config file than the following method.

public class SettingServices : ISettingServices
{
    public UserSetting GetUserSetting()
    {
        XmlSerializer reader = new XmlSerializer(typeof(UserSetting));
        StreamReader file = new StreamReader(UserConfig);
        UserSetting settings = new UserSetting();
        settings = (UserSetting)reader.Deserialize(file);
        return settings;
    }
    public void CreateUserSetting(UserSetting userSetting)
    {
        XmlSerializer writer = new XmlSerializer(typeof(UserSetting));
        StreamWriter file = new StreamWriter(UserConfig);
        writer.Serialize(file, userSetting);
        file.Close();
    }
    public void UpdateUserSetting(UserSetting userSetting)
    {
        UserSetting currentSettings = GetUserSetting();
        UserSetting newSetting = new UserSetting();
        newSetting.Name = (userSetting.Name == null) ? currentSettings.Name : userSetting.Name;
        newSetting.ViewChangeLog = (userSetting.ViewChangeLog == null) ? currentSettings.ViewChangeLog : userSetting.ViewChangeLog;
        newSetting.PrimaryRowColor = (userSetting.PrimaryRowColor == null) ? currentSettings.PrimaryRowColor : userSetting.PrimaryRowColor;
        newSetting.SecondaryRowColor = (userSetting.SecondaryRowColor == null) ? currentSettings.SecondaryRowColor : userSetting.SecondaryRowColor;
        newSetting.Font = (userSetting.Font == null) ? currentSettings.Font : userSetting.Font;
        CreateUserSetting(newSetting);
    }
    private static string UserConfig
    {
        get
        {
            string configDirectory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CVS\\ICMQuery").LocalPath;
            return new Uri(configDirectory + "\\" + System.Environment.UserName + ".config").LocalPath;
        }
    }
}

Can someone please show me the light. I would preferably like to be able to update singular elements within the UserSetting class without destroying and rewriting the file every time I have to update it.


texts:
How do I improve speed of this code? The problem definition is "Find the sum of all the multiples of 3 or 5 below N".

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 -optc-O2 #-}
import qualified Data.ByteString.Lazy as L
import Control.Monad (forM_)

readInt :: L.ByteString -> Int
readInt !s = L.foldl' (\x c -> 10 * x + fromIntegral c - 48) 0 s

main :: IO ()
main = do
    -- don't need number of inputs, since it is read lazily.
    (_:ls) <- L.split 10 `fmap` L.getContents
    -- length ls <= 10^5
    forM_ ls $ \ l ->
        print $ f . readInt $ l

-- n <= 10^9
f :: Int -> Int
f n = go 0 0
  where
    go i !a | i == n = a
            | i `mod` 3 == 0 || i `mod` 5 == 0 = go (i+1) (a+i)
            | otherwise         = go (i+1) a


texts: Finding sessions associated with an IP address using PDO

texts:
Originally Posted on Stack Overflow

First of all I want to say that I'm new to PDO. I did tried it once but since I found the oop solution complicated and even impossible (SELECT * FROM table_name) I decided to use PDO.

But I'm not sure if I do it right, so I'd like to take criticism about what I've done. I'm "translating" the mysqli stmt to pdo. Here's an example from one thing I've "translated":

// Client IP has been defined previously,
// But for the example:
$ip     = '3ffe:1900:4545:3:200:f8ff:fe21:67cf';
$sql_ip = inet_pton($ip); // IPV6

try {
    $stmt = $pdo->prepare('SELECT * FROM sessions WHERE s_ipv4 = :s_ipv4 OR s_ipv6 = :s_ipv6');
    $stmt->bindParam(':s_ipv4', $sql_ip);
    $stmt->bindParam(':s_ipv6', $sql_ip);
    $stmt->execute();

    if ($stmt->rowCount() === 0) {
        // No rows
    } else {
        // Do something
    }
} catch (Exception $exception) {
    die ($exception->getMessage());
}

unset($stmt);

Am I doing it right?


texts: Validating only attributes that are present in a form

texts:
I want to skip validations based on attributes. If certain attributes are not in form so I do not want to validate them.

Currently, if I post them from one form which has 1 field, it still validates other 9 fields and show me errors that it cant be blank.

If I check from big form which has 10 fields, it passes successfully.

The below code did trick for me but my main intention is to refactor so it will fullfil its purpose as i stated above.

Code is:

validates :teacher_number, presence: true, if: "teacher_number && teacher_number.blank?"
  validates :title, presence: true, if: "title && title.blank?"
  validates :name, presence: true, if: "name && name.blank?"
  validates :gender, presence: true, if: "gender && gender.blank?"
  validates :location, presence: true, if: "location && location.blank?"
  validates :dob, presence: true, if: "dob && dob.blank?"
  validates :contact_mobile, presence: true, if: "contact_mobile && contact_mobile.blank?"
  validates :contact_home, presence: true, if: "contact_home && contact_home.blank?"
  validates :street, presence: true, if: "street && street.blank?"
  validates :city, presence: true, if: "city && city.blank?"
  validates :state, presence: true, if: "state && state.blank?"
  validates :zip_code, presence: true, if: "zip_code && zip_code.blank?"
  validates :country, presence: true, if: "country && country.blank?"
  validates :teacher_number, uniqueness: {scope: :school_id}, if: "teacher_number && teacher_number.blank?"
  validate  :teacher_number_existance, :on => :create, if: "self.teacher_number && self.teacher_number.blank?"
  validate  :school_existance, :on => :create, if: "self.teacher_number && self.teacher_number.blank?"

I simply wants to do something like:

before_validation :skip_validations

def strip_validations
    [:teacher_number, :title, :name, :gender, :location, :dob, :contact_mobile, :contact_home, :street, :city, :state, :zip_code, :country].each do |attr|

      errors.add("Teacher", " #{attr} can't be blank") if attr && attr.blank?

    end
  end

But above code does not work for my cases. Any good work around?


texts: Best way to get two columns from a table

texts:
Basically I have taken over a project and found a table that has the following video and video title fields in it (why they didn't create a separate linked table is beyond me):

[VIDEOURL]
[VIDEOTITLE]
[COUKVIDEO1URL]
[COUKVIDEO2URL]
[COUKVIDEO3URL]
[COUKVIDEO4URL]
[COUKVIDEO1TITLE]
[COUKVIDEO2TITLE]
[COUKVIDEO3TITLE]
[COUKVIDEO4TITLE]

Can this query be improved to get a single list of titles and urls from the above fields:

SELECT
    t.VIDEOURL,
    t.VIDEOTITLE
FROM
(
    SELECT VIDEOURL, VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    UNION
    SELECT [COUKVIDEO1URL] AS VIDEOURL, [COUKVIDEO1TITLE] AS VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    UNION
    SELECT [COUKVIDEO2URL] AS VIDEOURL, [COUKVIDEO2TITLE] AS VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    UNION
    SELECT [COUKVIDEO3URL] AS VIDEOURL, [COUKVIDEO3TITLE] AS VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    UNION
    SELECT [COUKVIDEO4URL] AS VIDEOURL, [COUKVIDEO4TITLE] AS VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
) t
WHERE t.VIDEOURL != ''
AND t.VIDEOTITLE != ''


texts:
I just started learning programming in Python and decided to write a game of hangman to try and learn more about how certain things worked. Any constructive criticism would be greatly appreciated.

import random
print('let\'s play hangman')
#set words
first = ['t','e','s','t']
second = ['t', 'e', 's', 't', 'e', 'd']
third = ['t', 'e', 's', 't', 'i', 'n', 'g']
fourth = ['r', 'a', 'n', 'd', 'o', 'm']
fifth = ['g',  'e',  'n',  'e',  'r',  'a',  't',  'e']
#set list of possible answers
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
#set a couple of varibles
answer = []
end = 0
right = 0
wrong = 0
endCheck = 0
alreadyGuessed = 0
#randomly pick a word
random=random.randint(1, 5)
if random == 1: words = first
if random == 2: words = second
if random == 3: words = third
if random == 4: words = fourth
if random == 5: words = fifth
#set varible length to the number of letters in the word
length = len(words)
#figure out what number must be reached in order to declare winner
for loop in range(length):
    end = end + loop
#set answer to as many asterisks as there are letters in the word
for marker in range(length):
    answer.append('*')
#start the main loop and end if win or lose
while wrong < 5 and endCheck != end:
    #print the answer withe asterisks in place of unknown letters
    print ('The word is ', end = '')
    for word in range(length):
        print(answer[word], '', end='')
    print('')
    #start loop to get answer and check if already guessed
    while alreadyGuessed < 1:
        #get guess
        letter = str(input('What is your guess? '))
        #make sure guess is in lowercase
        letter = str.lower(letter)
        #convert guess into ascii number and set to 0 for a, 1 for b...
        guess = ord(letter) - 97
        #check if letter already guessed
        if alphabet[guess] == ['*']:
            print('You already guessed that letter, try again')
            alreadyGuessed = 0
        #otherwise set letter to guessed and continue
        else:
            alphabet[guess] = ['*']
            alreadyGuessed = 1
    #reset guessed tracker
    alreadyGuessed = 0
    #if guess is right enter it into answer at correct spot and mark this
    turn as a right guess
    for marker2 in range(length):
        if words[marker2] == letter:
            answer[marker2] = letter
            endCheck = endCheck + marker2
            right = right + 1
    #check if entire word has been guessed
    if endCheck == end:
        print('You guessed it right before getting a hangman! You win!')
        print ('The word was ', end = '')
        for word in range(length):
            print(answer[word], end='')
    #check if a right letter was guessed this turn
    if right > 0 and endCheck != end:
            print('You got one right! no hangman for you this turn')
    #check if a wrong letter was guessed this turn
    if right == 0:
        print('You missed it this turn!')
        wrong = wrong + 1
        print ('number missed =',  wrong)
    #check if to many wrong guesses were made
    if wrong == 5:
        print('You got a hangman!')
    #reset right guesses to 0 before next turn
    right = 0
    #skip a space between turns
    print ('')


texts: Node.js script and systemd service to update CloudFlare on IP address change

texts:
I've created a simple Node script to read the IPv6 addresses of an interface and update a CloudFlare hostname with those addresses. I've designed it so that it can be activated via an instantiated systemd service that detects when the IP address changes.

Here is the script:

#!/usr/bin/env node

const os = require('os');
const Cf = require('cloudflare4');
const request = require('request-promise');
const argv = require('yargs')
  .usage('Usage: $0 -c [configuration file]')
  .alias('c', 'config')
  .demandOption(['c'])
  .describe('c', 'path to configuraiton file')
  .alias('i', 'interface')
  .describe('i', 'Override the interface declared in the configuration file')
  .boolean('s')
  .default('s', false)
  .describe('s', 'skip updating of host')
  .help('h')
  .alias('h', 'help')
  .argv;

const config = require(argv.c);
if (argv.i) {
  config.interface = argv.i;
}

const cf = new Cf({
  email: config.email,
  key: config.key,
});

const IPv4 = {
  name: 'IPv4',
  type: 'A',
  locator: getIPv4Address,
};

const IPv6 = {
  name: 'IPv6',
  type: 'AAAA',
  locator: getIPv6Address,
};

updateAddressesByFamily(IPv6);
updateAddressesByFamily(IPv4);

function updateAddressesByFamily(family) {
  const remoteAddressPromise = cf.zoneDNSRecordGetAll(config.zone, {
    type: family.type,
    name: config.name,
  });
  const localAddressPromise = family.locator();
  Promise.all([remoteAddressPromise, localAddressPromise]).then((result) => {
    const [remoteAddresses, localAddresses] = result;
    logAddresses(remoteAddresses.map(a => a.content), `Remote ${family.name} Addresses`);
    logAddresses(localAddresses, `Local ${family.name} Addresses`);

    const staleAddresses = remoteAddresses.filter(address => !localAddresses.includes(address.content));
    logAddresses(staleAddresses.map(a => a.content), `Stale ${family.name} Addresses`);

    const newAddresses = localAddresses.filter(address => !remoteAddresses.map(a => a.content).includes(address));
    logAddresses(newAddresses, `New ${family.name} Addresses`);

    const removalPromises = argv.s ? [] : staleAddresses.map(address => cf.zoneDNSRecordDestroy(config.zone, address.id));

    const additionPromises = argv.s ? [] : newAddresses.map(address => cf.zoneDNSRecordNew(config.zone, {
      type: family.type,
      name: config.name,
      content: address,
      ttl: 1,
    }));

    return Promise.all([...removalPromises, ...additionPromises]);
  }).then(() => {
    console.log(`Successfully updated ${family.name} addresses`);
  }).catch((error) => {
    console.error(`Unable to update ${family.name} addresses: ${error}`);
  });
}

function getIPv4Address() {
  const options = {
    uri: 'https://ipinfo.io/json',
    json: true,
  };
  return request.get(options).then(response => [response.ip]);
}

function getIPv6Address() {
  const networkInterface = os.networkInterfaces()[config.interface];
  if (!networkInterface) return Promise.reject(`Unknown interface ${config.interface}`);
  const addresses = networkInterface.filter(x => x.family === IPv6.name && x.scopeid === 0).map(x => x.address);
  return Promise.resolve(addresses);
}

function logAddresses(addresses, label) {
  if (label) {
    console.log(`${label}: `);
  }
  console.log(`\t${addresses.sort().join(',\n\t')}`);
}

Here is the systemd service file:

[Unit]
Description=Update CloudFlare with latest IP addresses from %I
BindsTo=sys-subsystem-net-devices-%i.device
After=sys-subsystem-net-devices-%i.device
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/ddns-cloudflare -c /path/to/config.json -i %I

[Install]
WantedBy=multi-user.target


texts: Menu Model class using Model-View-Presenter

texts:
The following code is for my Object Oriented Programming class. My program simulate the cashier's machine to order food. The code uses Model View Presenter. This class is the model.

I have an ArrayList to hold the possible order possible. The View uses it to create JButtons.

I have an ArrayList to hold data to know what is ordered.

I am wondering if I followed Model-View-Presenter correctly.
Is this class holding too much responsibility.

public class MenuModel {
    // ArrayList hold MenuItem
    private ArrayList<MenuItem> menuItems;
    // Textfile name
    private String fileName = "Menu.txt";
    // Use to read textfile
    private MenuReader menuReader;
    // Data to keep menu's price and the menu's order
    //Keep for what was ordered
    private ArrayList<MenuItem> order;
    //Listeners
    private ArrayList<ChangeListener> listeners;
    private Formatter formatter;

    /**
     *
     * @param file name
     */
    public MenuModel(String f){
        listeners = new ArrayList<ChangeListener>();
        formatter = new Formatter();
        order = new ArrayList<MenuItem>();
        fileName = f;
        menuItems = new ArrayList<MenuItem>();
        menuReader = new MenuReader(fileName, '|', menuItems);
        menuReader.read();
    }

    public void addChangeListener(ChangeListener listener){
        listeners.add(listener);
    }
    // update the menu & price
    public void add(MenuItem menuItem){
        order.add(menuItem);
        ChangeEvent event = new ChangeEvent(this);
        for(ChangeListener lister : listeners)
            lister.stateChanged(event);
    }
     /**
      *
      * @return Menu Order Size
      */
    public int size(){
        return menuOrder.size();
    }

    // clear price and menu
    public void clear(){

        order.clear();
        ChangeEvent event = new ChangeEvent(this);
        for(ChangeListener lister : listeners)
            lister.stateChanged(event);

    }
    // Text to be sent to the screen
    public String display(){
        StringBuilder sb = new StringBuilder();
        sb.append(formatter.formatHeader());
        Iterator<MenuItem> iter = getItems();
        while(iter.hasNext())
            sb.append(formatter.formatOrder(iter.next()));

        sb.append(formatter.formatFooter());
        return sb.toString();
    }
    // Possible order available
    public ArrayList<MenuItem> getMenuItem(){ return menuItems; }
    // Get what was ordered
    public ArrayList<MenuItem> getOrderList(){ return order; }
    /**
     *
     * @return String filename
     */
    public String getFileName(){ return fileName; }

    public Iterator<MenuItem> getItems(){
        return new Iterator<MenuItem>(){
            private int current = 0;
            @Override
            public boolean hasNext(){
                return current < order.size();
            }
            @Override
            public MenuItem next() {
                 return order.get(current++);
            }
            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }
}


texts: One-time pad encryption using letter shifting

texts:
This program asks the user to input a List of words. It then returns a list of encrypted words, and a second list which specifies the numerical shifts used to encrypt those words. The idea was obtained from https://www.khanacademy.org/computing/computer-science/cryptography/crypt/v/one-time-pad

import random

def rotate_letter(letter, number):
    if letter == ' ':
        return letter
    if letter.islower():
        start = ord('a')
    elif not letter.islower():
        start = ord('A')

    normal_shift = ord(letter) - start
    new_letter = start + (normal_shift + number) % 26
    return chr(new_letter)

def avoid(letter):
    avoid = ' ,!?¿,*+-%/@1234567890'
    for i in avoid:
        if i == letter:
            return False
    return True

def rotate_word(word):
    new_word = ''
    random_series = []
    for letter in word:
        if avoid(letter):
            random_number = random.randint(1,26)
            new_letter = rotate_letter(letter, random_number)
            new_word += new_letter
            random_series.append(random_number)
        else:
            new_word += letter
    return (new_word, random_series)

def shift(words):
    index = 0
    encrypted_words = []
    random_shifts = []
    while index < len(words):
        (new_word, random_series) = rotate_word(words[index])
        encrypted_words.append(new_word)
        random_shifts.append(random_series)
        index += 1
    return (encrypted_words, random_shifts)

def get_input():
    words = []
    while True:
        user = (input('Input words to encrypt. Done when ready \n' ))
        if user == 'Done' or user == 'done':
            return words
        words.append(user)

def start():
    words = get_input()
    encrypted_words = []
    random_shifts = []
    (encrypted_words, random_shifts) = shift(words)
    print('UNENCRYPTED WORDS', words)
    print('ENCRYPTED WORDS', encrypted_words)
    print('RANDOM SHIFTS', random_shifts)

start()


texts:
The HexToString function returning maximum of 16kb even for sources greater than 16KB

string HexStringToString(string HexString)
        {
            string stringValue = "";
            for (int i = 2; i < HexString.Length / 2; i++) // Starting from position too just to avoid the 0x Hex Code that messes stuff up
            {
                try
                {
                    string hexChar = HexString.Substring(i * 2, 2);
                    int hexValue = Convert.ToInt32(hexChar, 16);
                    stringValue += Char.ConvertFromUtf32(hexValue);
                }
                catch (Exception ExCon)
                {
                    //continue; //Forcing application to ignore anomaly in the file being processed
                    MessageBox.Show(ExCon.ToString());
                }
            }
            return stringValue;
        }


texts:
I have the following spaghetti update method and I would like to improve its coding style.

This takes an incoming PUT query for a survey object and updates it accordingly.

update: function(req, res) {
  var slug = req.body.slug
    , errors = {}
    , surveyDiff = req.body.diff;

  surveyDiff.slug = slug;

  // Certains fields are not supposed to be updated, therefore they need to be removed before performing the update.
  var forbiddenFields = [ 'telerivetId', 'telerivetProjectId',
                          'votoId', 'votoApiKey', 'campaign', 'country' ];

  forbiddenFields.forEach(function(forbiddenField) {
    if (surveyDiff.hasOwnProperty(forbiddenField))
      delete surveyDiff[forbiddenField];
  });

  if (Object.keys(surveyDiff).length > 1)
    // We need to verify that the user is logged and is the author of the current survey.
    Session.getUser(req.cookies.logged.token, function(err, user) {
      var updateSurvey = function(surveyDiff) {
        // Once all verifications are done, we can safely update the survey.
        Survey.update({ slug: slug, user: user.phoneNumber }, surveyDiff)
          .exec(function(err, surveys) {
            if (!err)
              res.json({ success: true, survey: surveys[0] });
            else
              res.json({ success: false });
          });
      };

      // The order property correspond to a parent model called SurveyGroup, therefore this one is updated separately
      if (!surveyDiff.hasOwnProperty('order'))
        updateSurvey(surveyDiff);

      else
        Survey.findOne({ slug: slug }).exec(function(err, survey) {
          SurveyGroup.update({ id: survey.surveyGroup }, { order: surveyDiff.order },
            function(err, surveyGroup) {
              console.log('update survey group', err, surveyGroup);
              delete surveyDiff.position;

              if (!err) updateSurvey(surveyDiff);
              else res.json({ success: false });
            });
        });
    });

  else res.json({ success: false });
}

This code is running on node.js using sails.js and waterline.js.


texts: Web service getting value using LINQ from queue table in SQL database

texts:
As a test of my C# skills, I have been asked to create a simple web service which will take a message from a queue table in a SQL database and send it to a web application when a button is pressed on the application.  I have never written a web service before so I am going in a little blind here so was after some advise on whether I had done this correct or not.

The stored procedure usp_dequeueTestProject gets a value from the top of the list in a table and then deletes the row in that table.  At the moment I do not have this being archived anywhere, would it be better practice to instead of delete this, to just mark it as sent instead?

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
    [WebMethod]
    public string GetDataLINQ()
    {
        try
        {
            TestProjectLinqSQLDataContext dc = new TestProjectLinqSQLDataContext();
            var command = dc.usp_dequeueTestProject();
            string value = command.Select(c => c.Command).SingleOrDefault();
            return value;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }
}

I've opted for using LINQ for starters, I am not sure if this is the best way to do it or not?  I am only passing through the one string as well... In reality I guess you would normally want to send more than one field, such as datetime sent, message type etc, but wasn't sure what data type to use for this? I have seen this done using a Strut, but wasn't sure if this was correct?  Any guidance would be greatly appreciated.


texts: trying out possible combinations of varying formula with recursion

texts:
I wrote a program in c what looks for integer solutions of different formulas. The program asks the user for a dimension which defines the formula. For example, the formula of the third dimension has three variables, the formula of the second dimension has two variables. The formulas look similar to the following:

dim     formula
2       a + b
3       a + b + c
4       a + b + c + d

and so on. Next step, the program asks the user for a maximum value of all the variables. For a given dimension, 3 for instance, the code could look like:

for(int a = 1; a <= max; a++)
{
    for(int b = 1; b <= max; b++)
    {
        for(int c = 1; c <= max; c++)
        {
            do_sth();
        }
    }
}

Of course, this would be a bad algorithm. It checks each possible combination up to 6 times, just in different order. The better alternative would be:

for(int a = 1; a <= max; a++)
{
    for(int b = 1; b <= a; b++)
    {
        for(int c = 1; c <= b; c++)
        {
            do_sth();
        }
    }
}

To make that work for all dimensions, I had to find a way to stack multiple loops depending on the users input. I wrote a recursive loop function:

int number[100];
int dim, max;

void loop(int depth)
{
    for(number[depth] = 1; number[depth] <= number[depth-1]; number[depth]++)
    {
        if(depth == dim - 1)
        {
            do_sth();
        }
        else
        {
            loop(depth+1);
        }
    }
}

int main(void)
{
    printf("Enter a dimension: ");
    scanf("%d", &dim);
    printf("Enter a maximum value: ");
    scanf("%d", &max);
    for(number[0] = 1; number[0] <= max; number[0]++)
    {
        loop(1);
    }
}

Notes:

It is not important, what do_sth() does. It builds the actual formula I don't want to show here.
To be able to calculate the runtime, I wrote a program what calculates the number of combinations to try. I posted it on this question.

My code works fine but I would like to know if there's a better way to do this.


texts: Script to check zero crossings to check if microphones phases are aligned

texts:
I have 'n' microphones placed in square fashion and I want to make sure that all the channels must be aligned in time exactly the same if the signal is equidistant from all the 'n' microphones i.e. in the center of the square.

I have written this script to do the difference in zero crossing timings for only two signals (.wav file) and if the difference is above some precision then print that and bail out.

from scipy.io import wavfile
import numpy as np
import argparse

parser = argparse.ArgumentParser(description='diff the zero crossing of two files')
parser.add_argument('-f1', '--file_name_1', help='provide first file name')
parser.add_argument('-f2', '--file_name_2', help='provide second file name')
parser.add_argument('-p', '--precision', help='precision to compare against', type=float, default=0.0001)

args = parser.parse_args()
print(args)
files = []
files.append(args.file_name_1)
files.append(args.file_name_2)

sampling_rates = []
signals = []
for file in files:
  fs, signal = wavfile.read(file)
  signal = signal / max(abs(signal))                        # scale signal
  sampling_rates.append(fs)
  signals.append(signal)
  assert min(signal) >= -1 and max(signal) <= 1
  print 'fs           ==> ', fs, 'Hz'                       # sampling rate
  print 'len(signal)  ==> ', len(signal), 'samples'

sampsPerMilli = 0
#files should have same sampling rates and length
prev_rate = sampling_rates[0]
for rate in sampling_rates[1:]:
  cur_rate =  rate
  sampsPerMilli = int(rate / 1000)
  if prev_rate != cur_rate:
    print("rates doesn't match %d %d"% (prev_rate, cur_rate))
    exit(0)
  cur_rate = rate

#signal length also should be same
prev_length = len(signals[0])
for signal in signals[1:]:
  cur_length = len(signal)
  if prev_length != cur_length:
    print("length of signals doesn't match for %d %d"% (prev_length, cur_length))
    exit(0)
  cur_length = prev_length

zccs = []
for signal in signals:
  zcc = []
  DC = np.mean(signal)
  newSignal = signal - DC
  for i in range(1, int(len(newSignal))):
    if((newSignal[i] * newSignal[i-1]) < 0):
      #print("crossing at %f seconds"% ((i/sampsPerMilli) * 0.001))
      zcc.append((i/sampsPerMilli) * 0.001)
  zccs.append(zcc)

for a, b in zip(zccs, zccs[1:]):
  if len(a) != len(b):
    print("length doesn't match %d %d"% (len(a), len(b)))
    for c, d in zip(a, b):
      if c-d > args.precision:
        print("precision %f c %f d %f exceeded"% (args.precision, c, d))
        exit(0)

Is there any better approach or can this script be improved?