texts: a Python2 to Python3 print fixer in perl

texts:
Sometimes, I'm reviewing old questions written in Python2, with no parenthesis around print statements. Or I'm changing one of my older codes, also without parenthesis around print statements.

It annoys me to do this manually, so I decided to write a little perl script to change it for me, however it looks rather ugly. And I think I'm missing some obvious regex to do this?

I don't yet write to another file, but just print to the commandline.

Note that I'm making the assumption that lines that print and are net yet ended, end with \

use strict;
use warnings;

my @filenames = @ARGV;

foreach my $filename (@filenames){
    my $print_ended = 0;
    my $concat_print = qw{};
    open my $fh, '<', $filename or die "Can't open $filename: $!";

    while (my $line = <$fh>) {

        chomp $line;
        if ($print_ended) {
            $concat_print .= $line;
            $print_ended = $line =~ /\\$/;

            if (! $print_ended) {
                (my $newline = $concat_print) =~ s/print /print(/;
                 print $newline . ")\n";
                 $concat_print = qw{};
            }
        }
        elsif ($line =~ /print /) {
            if ($line =~ /\\$/) {
                $print_ended = 1;
                $concat_print .= $line . "\n";
            }
            else {
                (my $newline = $line) =~ s/print /print(/;
                print $newline . ")\n";
            }
        }
        else {
            print $line . "\n";
        }
    }
}


texts:
My goal is to read from standard input, break up the input into words, case-insensitively, and produce a report to standard output, where each line is a word followed by a space followed by its count. The output should be sorted by words.

This is my code:

use std::collections::BTreeMap;
use std::io;
use std::io::BufRead;

fn main() {
    let mut counts: BTreeMap<String, isize> = BTreeMap::new();
    let stdin = io::stdin();
    for line_result in stdin.lock().lines() {
        match line_result {
            Ok(line) => {
                let lowercase_line = line.to_lowercase();
                let words = lowercase_line.split(|c: char| {
                     !(c.is_alphabetic() || c == '\'')
                 }).filter(|s| !s.is_empty());
                 for word in words {
                    *(counts.entry(word.to_string()).or_insert(0)) += 1;
                 }
            },
            Err(e) => {
                panic!("Error parsing stdin: {:?}", e);
            }
        }
    }
    for (key, value) in counts.iter() {
        println!("{} {}", key, value);
    }
}

My questions are:

Is BTree the proper dictionary?
I know that there is a regex crate, but I would like to stay with things in standard Rust. That said, splitting is a terrible way to break up lines because you have to filter empties. Is there a way to just match the words, rather than splitting on non-word sequences?
Is matching on the Err part of the result proper? Or should we let the script crash? Is panicking okay?
I noticed one is not allowed to say let words = line.to_lowercase().split(...) because of the infamous"borrowed reference does not live long enough"` but is there a cleaner way?
Is there a nicer way to count words in a map? I don't like the asterisk.
I wish I didn't have to do an explicit lock on stdin.

Rust has a lot of things going for it, but when I compare what I got to the much prettier Julia version of this script, namely...

counts = Dict{AbstractString, UInt64}()
for line in eachline(STDIN)
  for word in matchall(r"[a-z\']+", lowercase(line))
    counts[word] = get(counts, word, 0) + 1
  end
end
for (word, count) in sort(collect(counts))
  println("$word $count")
end

...I'm thinking I don't know Rust very well, or, that's just the way things are. I mean, I know as a systems language, it's really hard to make vectors and strings. And they tell me I will learn to love the borrow checker. :) Hopefully someone with expertise in idiomatic Rust can be of service here. I'm not expecting it to be as short as the Julia code but I do fear my Rust is not idiomatic enough.


texts: Is this a good way to track current site being reported on?

texts:
I'm trying to find an elegant and secure way to track the currently reported site. I originally just used a cookie but realized this was not very secure. I have since switched to combine the session and the cookie. It still feels a bit clumsy. Am I missing something here as far as best practices? Can this be improved on?

public static int SiteID
        {
            get
            {
                if (HttpContext.Current.Session[SITE_ID_KEY] == null)
                {
                    if (Web.CookieUtil.CookieExists(SITE_ID_KEY))
                    {
                        Guid userId = (Guid)Membership.GetUser().ProviderUserKey;
                        int siteId = Convert.ToInt32(Web.CookieUtil.GetCookieValue(SITE_ID_KEY));
                        if (Sites.ValidateSite(StateManager.AccountID.Value, siteId, userId))
                        {
                            HttpContext.Current.Session[SITE_ID_KEY] = siteId;
                        }
                        else
                        {
                            Web.CookieUtil.DeleteCookie(SITE_ID_KEY);
                            return -1;
                        }
                    }
                    else
                    {
                        return -1;
                    }
                }

                return (int)HttpContext.Current.Session[SITE_ID_KEY];
            }
            set
            {
                HttpContext.Current.Session[SITE_ID_KEY] = value;
                Web.CookieUtil.CreateCookie(SITE_ID_KEY, value.ToString(), null);
            }
        }


texts: Styles: "object initializer" vs "constructor" object creation

texts:
Question: What are peoples preferences between the two methods of creating an object (in C# in particular) and setting other fields (that may not be given values during construction)? Are either of them considered best practice? or is it down to the programmer and any styling conventions in place at the company?

My preference is absolutely for the object initializer method. It looks much cleaner and more concise to me.

Object initializer

Type T = new Type(Param1, Param2)
{
    Field1 = Value1,
    Field2 = Value2,
    Field3 = ValueFromFunction()
};

Constructor

Type T = new Type(Param1, Param2);
T.Field1 = Value1;
T.Field2 = Value2;
T.Field3 = ValueFromFunction();


texts: Creating multiple threads to process items in a listview

texts:
The goal is to pick items from a listview, do some web related task with the information and then update the UI with the returned information from the web request.

The problem is with having multiple list view items processed at once, me being a newbie to C#, i came up with this code, I'm pretty sure this is not good, i just came up with it, is there a better way to get this done ?

Dictionary<String,BackgroundWorker> worker_list = new Dictionary<String, BackgroundWorker>();
int completed_count = 0;
int total_work;

public Form1()
{
    InitializeComponent();
}

public void worker(String woker_id)
{
    WebClient client = new WebClient();
    byte[] response =
    client.UploadValues("http://google.com", new NameValueCollection() { });

    worker_list[woker_id].ReportProgress(100);

    if(completed_count != total_work){
        worker(woker_id);
    }
}

// Adding the work to the que since a thread can't access background Ui thread
private void button2_Click(object sender, EventArgs e)
{
    // preparing task list
    txtOutput.Text += "Total stuff to run" + listView1.Items.Count + Environment.NewLine + Environment.NewLine;

    // check for valid input
    int value;
    if (!int.TryParse(textBox1.Text, out value) || textBox1.Text == "0"){
        MessageBox.Show("invalid number of threads");
        return;
    }

    // create threads
    for (int i = 0; i < value; i++)
    {
        String woker_id = "bg_" + i.ToString();

        worker_list[woker_id] = new BackgroundWorker();
        worker_list[woker_id].WorkerSupportsCancellation = true;
        worker_list[woker_id].WorkerReportsProgress = true;

        // Intiial message
        txtOutput.Text += "Worker " + woker_id + " Started" + Environment.NewLine;

        worker_list[woker_id].DoWork += delegate {
            worker(woker_id);
        };

        worker_list[woker_id].ProgressChanged += delegate {
            if(completed_count == total_work) {
                return;
            }else
            {
                txtOutput.Text += "Worker " + woker_id + "is running again" + Environment.NewLine;
            }

            listView1.Items[completed_count].BackColor = Color.LightGreen;
            completed_count++;
        };

        worker_list[woker_id].RunWorkerCompleted += delegate {
            worker_list[woker_id].CancelAsync();
            worker_list.Remove(woker_id);
            txtOutput.Text += "Worker " + woker_id + " Completed | Thread count = " + worker_list.Count() + Environment.NewLine;
        };

        worker_list[woker_id].RunWorkerAsync();
    }

    // Line spacing
    txtOutput.Text += Environment.NewLine + Environment.NewLine;
}

private void Form1_Load(object sender, EventArgs e)
{
    for (int i = 1; i < 11; i++)
    {
        Random rnd = new Random();
        ListViewItem item = new ListViewItem("Item " + i);
        // Sleep Time
        item.SubItems.Add((rnd.Next(100,500) * i).ToString());
        listView1.Items.Add(item);
    }

    // setting up the total work
    total_work = listView1.Items.Count;
}

Thank you.


texts: Python script to execute Bash code inside of a Docker container

texts:
Motivation

I like using so-called online judges and competitive programming sites to practice coding (e.g. CodeWars, Exercism, HackerRank, etc.). I was thinking that it would be nice to try write my own at some point. The first step, in my mind, would be to find a simple way to allow a user to input some code and have it run inside of a sandboxed environment. I decided to try to use Python to run Bash code inside of a Docker container and display the results.

Features

Here is what I want my program to do:

Launch a text editor for the user to type some Bash code
Execute the user's Bash code inside of a Docker container
Print the standard output obtained from the command execution

Implementation

Here is a small script I wrote which seems to have the desired result:

#!/usr/bin/env python3
# -*- encoding: utf8 -*-
"""docker_run_bash.py

Example of how to run a shell script inside of a docker container.
"""

from subprocess import call
import docker
import os
import sys
import tempfile

# Get the text editor from the shell, otherwise default to Vim
EDITOR = os.environ.get('EDITOR','vim')

# Select which docker container to use (default to busybox-bash)
container = sys.argv[1] if len(sys.argv)>=2 else "blang/busybox-bash"

# Instantiate a Docker client object
client = docker.from_env(assert_hostname=False)

# Create a temporary directory
with tempfile.TemporaryDirectory(dir="/tmp") as td:

    # Create a temporary file in that directory
    tf = tempfile.NamedTemporaryFile(dir=td, delete=False)

    # Write to the temporary file
    tf.write("# Enter command to execute...".encode())

    # Flush the I/O buffer to make sure the data is written to the file
    tf.flush()

    # Open the file with the text editor
    call([EDITOR, tf.name])

    # Get the path to the mounted file on the container
    mounted_file = os.path.join("/mnt/host", os.path.basename(tf.name))

    # Execute the script
    cmd_stdout = client.containers.run(
        container,
        "/bin/bash {}".format(mounted_file),
        remove=True,
        volumes={
            td: {
                'bind': '/mnt/host',
                'mode': 'ro',
            }
        }
    )

    # Delete the file
    os.unlink(tf.name)

    # Output the results
    print("Command output:\n{}".format(cmd_stdout.decode()))

Usage

Here is how I run the command:

python docker_run_bash.py

This launches Vim for me. Here is how I might edit the buffer:

  1 # Enter command to execute...
  2 hostname
  3
~

After saving the buffer and exiting Vim I get the following output:

Command output:
309038e0dd45


texts: Run 'N' Number of PHP Scripts on shell forever in a loop

texts:
My objective is to run some 'N' number of PHP Scripts in cron.

Since these are web scrapers coded in PHP and hits database on my server, each script runs for like 1 hour and they take a lot of CPU and memory. That's why I want to run one script at a time.

My first approach was to run each script at specific hour of the day but then there are only 24 hours in a day, so I can't really go with that way.

I have prepared a Unix script which runs in an infinite loop and runs the entire script. Assuming the shell will execute one script, wait for some time and then execute the next script. This is my script 1, say.

Then there is another script, Script 2 which runs every 3 hours and checks if Script 1 is running. If Script 1 is not running it will execute Script 1.

My concerns:

Is it feasible to run like 100 PHP scripts from one Unix script? If one fails, will it fail the whole script?
Is there any better approach?

Script 1 (MasterCronCarlos.sh):

#!/bin/bash
# Description = Script to check cpu usage and if above threshold issue a linux based command.
# This Script only checks "user cpu time (us - userspace (doing userspace stuff))
#

SUBJECT="CRON Status | Jai Carlos"
TO="myemail@gmail.com"

while true
do

echo -en "Starting fresh loop of cron" | mail -s "$SUBJECT" "$TO"

    php /home/site1/public_html/scrapperM1.php
    sleep 300
    php /home/site1/public_html/scrapperM2.php
    sleep 300
    php /home/site1/public_html/scrapperM3.php
    sleep 300

    echo -en "Script completed for site1.com" | mail -s "$SUBJECT" "$TO"

    php /home/site2/public_html/scrapperM1.php
    sleep 300
    php /home/site2/public_html/scrapperM2.php
    sleep 300
    php /home/site2/public_html/scrapperM3.php
    sleep 300

    echo -en "Script completed for site2.tv" | mail -s "$SUBJECT" "$TO"

    php /home/site3/public_html/scrapperM1.php
    sleep 300
    php /home/site3/public_html/scrapperM2.php
    sleep 300
    php /home/site3/public_html/scrapperM3.php
    sleep 300

    echo -en "Script completed for site3" | mail -s "$SUBJECT" "$TO"

    php /home/site4/public_html/scrapperM1.php
    sleep 300
    php /home/site4/public_html/scrapperM2.php
    sleep 300
    php /home/site4/public_html/scrapperM3.php
    sleep 300

    echo -en "Script completed for site4" | mail -s "$SUBJECT" "$TO"

    php /home/site5/public_html/scrapperM1.php
    sleep 300
    php /home/site5/public_html/scrapperM2.php
    sleep 300
    php /home/site5/public_html/scrapperM3.php
    sleep 300

    echo -en "Script completed for site5" | mail -s "$SUBJECT" "$TO"

    php /home/site6/public_html/scrapperM1.php
    sleep 300
    php /home/site6/public_html/scrapperM2.php
    sleep 300
    php /home/site6/public_html/scrapperM3.php
    sleep 300

    echo -en "Script completed for site6" | mail -s "$SUBJECT" "$TO"

    php /home/site7/public_html/scrapperM1.php
    sleep 300
    php /home/site7/public_html/scrapperM2.php
    sleep 300
    php /home/site7/public_html/scrapperM3.php
    sleep 300

    echo -en "Script completed for site7" | mail -s "$SUBJECT" "$TO"

done

Script 2 (mastercron.sh):

#!/bin/sh

RESULT=`ps axf | grep "MasterCronCarlos.sh" | grep -v grep | awk '{print  $1}'`

if [ $RESULT -ge 0 ]; then

echo "Running"

else

echo "Not Running"

sh /home/backups/MasterCronCarlos.sh

fi;


texts:
I'm an iPhone Developer mainly, and I'm very new to web development - especially jQuery.

My task: I have three divs, which each contain a short biography about a certain person. (I have three people: liz, chris and michael). Those divs are hidden at the start of my code, because they all belong to the class profile.

I have three images which are displayed throughout, and have the IDs: (lizIMG, chrisIMG, michaelIMG). When an image is clicked, any other biographies' divs should be hidden, and the selected biography's div should be shown.

Also, I have a tooltip above each image, if a div is hidden, it will say:

  (Person Name) - Click to learn more

If a div is displayed, it will say:

  (Person Name) - Click to hide

I have fully working code, but the code is far too long for the desired task. It's quite annoying because I know exactly how I would do this in Objective-C, but not in jQuery. I'm guessing re-factoring it will involve functions, and possibly arrays?

I would like to make this shorter.

$(document).ready(function() {
  $('div.profile').hide(); // Hide all the profiles
  $('#lizIMG').click(function() {
    if ($("#lizDiv").is(":visible")) {
        $('#lizTip').text('Click to learn more');
    }
    else {
        $('#lizTip').text('Click to hide');
    }
    $('#lizDiv').slideToggle('slow');
    $('#chrisDiv').hide('slow');
    $('#chrisTip').text('Click to learn more');
    $('#michaelDiv').hide('slow');
    $('#michaelTip').text('Click to learn more');
});
$('#chrisIMG').click(function() {
    if ($("#chrisDiv").is(":visible")) {
        $('#chrisTip').text('Click to learn more');
    }
    else {
        $('#chrisTip').text('Click to hide');
    }
    $('#chrisDiv').slideToggle('slow');
    $('#lizDiv').hide('slow');
    $('#lizTip').text('Click to learn more');
    $('#michaelDiv').hide('slow');
    $('#michaelTip').text('Click to learn more');
});
$('#michaelIMG').click(function() {
    $('#lizDiv').hide('slow');
    $('#lizTip').text('Click to learn more');
    $('#chrisDiv').hide('slow');
    $('#chrisTip').text('Click to learn more');
    if ($("#michaelDiv").is(":visible")) {
        $('#michaelTip').text('Click to learn more');
    }
    else {
        $('#michaelTip').text('Click to hide');
    }
    $('#michaelDiv').slideToggle('slow');
});
$("#profiles img[title]").tooltip(); // Used to set text for the tooltips
});


texts:
Is everything alright with this code? What can I add to it?

state.h:

#pragma once

class State
{
public:
    virtual void update(float dt) = 0;

    virtual void draw(float dt) = 0;
};

state_machine.h:

#pragma once
#include <memory>
#include <stack>
#include "state.h"

using StateRef = std::shared_ptr<State>;

class StateMachine
{
public:
    void push_state(const StateRef& state);

    void push_state(State* state);

    template<class T>
    void push_state();

    StateRef pop_state();

    StateRef get_current_state() const;

    void update(float dt);
private:
    std::stack<StateRef> stack;
};

template<class T>
inline void StateMachine::push_state()
{
    push_state(StateRef(new T));
}

state_machine.cpp:

#include "state_machine.h"
#include "state.h"

void StateMachine::push_state(const StateRef& state)
{
    stack.emplace(state);
}

void StateMachine::push_state(State* state)
{
    push_state(StateRef(state));
}

StateRef StateMachine::pop_state()
{
    auto state = get_current_state();

    stack.pop();

    return state;
}

StateRef StateMachine::get_current_state() const
{
    return stack.top();
}

void StateMachine::update(float dt)
{
    if(!stack.empty())
    {
        auto state = get_current_state();

        state->update(dt);
        state->draw(dt);
    }
}

Dummy usage example:

#include <sm/state_machine.h>
#include <iostream>

struct Foo: public State
{
    void update(float dt) override
    {
        std::cout << "(updated)" << std::endl;
    }

    void draw(float dt) override
    {
        std::cout << "(drawed)" << std::endl;
    }
};

int main()
{
    StateMachine machine;

    machine.push_state<Foo>();

    machine.update(0.0f);

    machine.pop_state();

    machine.update(0.0f);

    return 0;
}

GitHub repo

How can I add and use "Controller" component? (component that handles input and etc.). Is it necessary? (MVC pattern)


texts: Function that returns another function, for a programming task

texts:
This is a task I was given for an online course. This is my solution to the problem.

Task:
Write a function called general_poly, that meets the specifications below.

For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because

1*10^3 + 2*10^2 + 3*10^1 + 4*10^0

So in the example the function only takes one argument with general_poly([1, 2, 3, 4]) and it returns a function that you can apply to a value, in this case x = 10 with general_poly([1, 2, 3, 4])(10).

def general_poly (L):
    """ L, a list of numbers (n0, n1, n2, ... nk)
    Returns a function, which when applied to a value x, returns the value
    n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
    #YOUR CODE HERE

My Code:

def general_poly (L):
    """ L, a list of numbers (n0, n1, n2, ... nk)
    Returns a function, which when applied to a value x, returns the value
    n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """

    def function_generator(L, x):
        k = len(L) - 1
        sum = 0
        for number in L:
            sum += number * x ** k
            k -= 1
        return sum

    def function(x, l=L):
        return function_generator(l, x)

    return function


texts: LeetCode: Maximum XOR of Two Numbers in an Array

texts:
Please review how clear my code is and also comment on performance.

  Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai
  < 2^31.

  Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.

  Could you do this in O(n) runtime?

  Example:

  Input: [3, 10, 5, 25, 2, 8]

  Output: 28

  Explanation: The maximum result is 5 ^ 25 = 28.

LeetCode

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TrieQuestions
{
    /// <summary>
    /// https://leetcode.com/explore/learn/card/trie/149/practical-application-ii/1057/
    /// </summary>
    [TestClass]
    public class FindMaxXorInArray
    {
        [TestMethod]
        public void XorTrieTreeTest()
        {
            int[] nums = {3, 10, 5, 25, 2, 8};
            Assert.AreEqual(28,FindMaximumXOR(nums));
        }

        //xor mean if the 0^0 == 0 and 1^1 == 0
        // so if we want maximum we want the maximum opposites
        public int FindMaximumXOR(int[] nums)
        {
            XorTrieTree tree = new XorTrieTree();
            tree.Insert(nums);
            return tree.GetMax(nums);
        }
    }

    public class XorTrieTree
    {
        private XorTreeNode _root;

        public XorTrieTree()
        {
            _root = new XorTreeNode();
        }
        /// <summary>
        /// for each one of the numbers we find we flags are set on with right shit all of the 32 bits
        /// and bitwise AND to understand if the bit is set on or off
        /// </summary>
        /// <param name="nums"></param>
        public void Insert(int[] nums)
        {
            foreach (var num in nums)
            {
                XorTreeNode cur = _root;
                for (int i = 31; i >= 0; i--)
                {
                    int bit = (num >> i) & 1;
                    if (cur.children[bit] == null)
                    {
                        cur.children[bit] = new XorTreeNode();
                    }
                    cur = cur.children[bit];
                }
            }
        }

        /// <summary>
        /// for each one of the numbers we try to understand which bits are set on.
        /// if the the bit is set on then we search for the NOT bit of that,
        /// we add the NOT bit to the temp xorValue variable, because the prefix of those two numbers are xor-ed
        /// and continue to the NOT bit next node.
        /// at the end we do max of current max and xorValue
        /// </summary>
        /// <param name="nums"></param>
        /// <returns></returns>
        public int GetMax(int[] nums)
        {
            int max = int.MinValue;
            foreach (var num in nums)
            {
                XorTreeNode cur = _root;
                int xorValue = 0;
                for (int i = 31; i >= 0; i--)
                {
                    int bit = (num >> i) & 1;
                    if (cur.children[bit == 1 ? 0 : 1] != null)
                    {
                        xorValue += (1 << i);
                        cur = cur.children[bit == 1 ? 0 : 1];
                    }
                    else
                    {
                        cur = cur.children[bit];
                    }
                }
                max = Math.Max(xorValue, max);
            }

            return max;
        }
    }

    //the root has 2 nodes  for 0 and 1
    public class XorTreeNode
    {
        public int Val;
        public XorTreeNode[] children;
        public XorTreeNode()
        {
            children = new XorTreeNode[2];
        }
    }
}


texts: Should my Json storage handle exceptions?

texts:
I made a class to conviniently serialize/deserialize data. Now I'm stuck with the following question. Should I handle exceptions (use try-catch) inside JsonStorage or inside ConfigManager and other classes that might use JsonStorage in the future?

public class JsonStorage : IDataStorage
{
    private readonly IFileSystem fileSystem;
    private readonly ILogger logger;

    public JsonStorage(IFileSystem fileSystem, ILogger logger)
    {
        this.fileSystem = fileSystem;
        this.logger = logger;
    }

    public T RestoreObject<T>(string path)
    {
        T result = default;

        try
        {
            if (!fileSystem.Path.IsPathFullyQualified(path))
                throw new ArgumentException("Invalid path.", nameof(path));

            string json = fileSystem.File.ReadAllText($"{path}.json");
            result = JsonConvert.DeserializeObject<T>(json);
        }
        catch (Exception ex)
        {
            logger.Log($"Object can't be restored. {ex.Message}");
        }

        return result;
    }

    public void StoreObject(object obj, string path)
    {
        string file = $"{path}.json";

        try
        {
            if (!fileSystem.Path.IsPathFullyQualified(path))
                throw new ArgumentException("Invalid path.", nameof(path));

            fileSystem.Directory.CreateDirectory(fileSystem.Path.GetDirectoryName(file));
            var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
            fileSystem.File.WriteAllText(file, json);
        }
        catch (Exception ex)
        {
            logger.Log($"Object can't be stored. {ex.Message}");
        }
    }
}

public static class ConfigManager
{
    private static readonly string configPath = @"SomePath\Config";

    public static BotConfig LoadConfig()
    {
        return Unity.Resolve<IDataStorage>().RestoreObject<BotConfig>(configPath);
    }

    public static void SaveConfig(BotConfig config)
    {
        Unity.Resolve<IDataStorage>().StoreObject(config, configPath);
    }
}

ConfigManager - example class that holds a path to Config.json and loads/saves it (using JsonStorage internaly).

For now I'm catching exceptions inside JsonStorage and using a logger instance to print exception messages to the console.
I don't know if there's a downside to that. Should JsonStorage have its own logger? Should it throw an exception (just like ReadAllText/WriteAllText) when something goes wrong with path/files?
Or maybe there is a good practice and some better ways to handle exceptions (in my particular case)?


texts: Permute and count between nested dictionaries

texts:
Goal:

Permute inner values between two dictionaries with matching outer key,
Save permuatations in counter,
Move to next outer key, update counter with new permutations.

Problem:

Many lookups on large dictionary (60 outer keys x 18000 inner key:value pairs) make existing code correct but slowwwww.

import collections

cnv = {'x': {'a':0, 'b':1, 'c':-1}, 'y': {'a':1, 'b':1, 'c':1}, 'z': {'a':-1, 'b':-1, 'c':-1}}
rna = {'x': {'A':1, 'B':3, 'C':5}, 'y': {'A':1, 'B':3, 'C':5}, 'z': {'A':1, 'B':3, 'C':5}}

cnv_loss_total = {}
for cell in cnv:
    cnv_gene_loss = set()
    for gene in cnv[cell]:
        if cnv[cell][gene] < 0:
            cnv_gene_loss.add(gene)
    cnv_loss_total[cell] = cnv_gene_loss

total_link_counter = collections.Counter()
for cell in rna:
    rna_gene_gain = set()
    for gene in rna[cell]:
            rna_gene_gain.add(gene)
    cell_combo = itertools.product(cnv_loss_total[cell], rna_gene_gain)
    for comboC, comboR in cell_combo:
        total_link_counter[comboC+'+'+comboR]+=rna[cell][comboR]

print (total_link_counter)
print(total_link_counter.values())

The code provides the desired output:

Counter({'c+C': 10, 'c+B': 6, 'b+C': 5, 'a+C': 5, 'a+B': 3, 'b+B': 3, 'c+A': 2, 'b+A': 1, 'a+A': 1})

There is also a memory bottleneck here:

--> 23         total_link_counter[comboC+'+'+comboR]+=rna[cell][comboR]
     24
     25 print (total_link_counter)

MemoryError:

But I intend on using much larger data (although similarly formatted data: either as a dict as dict or pandas dataframe).  How can I optimize the above code to deal with the MemorError (and hopefully shorten runtime)?


texts: HTTP download with dynamic reallocation and retries

texts:
This code is for downloading a file via winhttp lib, It's invoked by StartDownload function which tries to download n times before returning false if maximum tries exceeded. I'm worried about the dynamic realloc part in Download function, is my approach here have any flaws, or is there any improvements that can be made?

#include "HttpDownload.h"
#include <Windows.h>
#include <Winhttp.h>
#pragma comment(lib, "winhttp.lib")

bool bResults = FALSE;
HINTERNET hSession = 0, hConnect = 0, hRequest = 0;
int RepeatedTimes = 0;

void HttpDownload::CloseHandles() {
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);
}

bool HttpDownload::InitHttp() {
    if (!(hSession = WinHttpOpen(0, 0, 0, 0, 0))) return false;
    if (!(hConnect = WinHttpConnect(hSession, L"127.0.0.1", 80, 0))) return false;
    if (!(hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/file.ext", 0, 0, 0, 0))) return false;
    if (!(bResults = WinHttpSendRequest(hRequest, 0, 0, 0, 0, 0, 0))) return false;
    if (!(bResults = WinHttpReceiveResponse(hRequest, 0))) return false;
    return true;
}

bool HttpDownload::Download() {
    if (!bResults) return false;
    unsigned long dwSize = 0;
    unsigned long dwDownloaded = 0;
    void *buf;
    bool failed = false;
    int curalloc = 8192;
    unsigned char *jar = (unsigned char*)malloc(curalloc);
    int totalDownloaded = 0;
    #define failbreak failed = true; break;
    while (1) {
        dwSize = 0;
        if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) { failbreak }
        if (dwSize == 0) break;
        buf = VirtualAlloc(0, dwSize, MEM_COMMIT, PAGE_READWRITE);
        if (!buf) { failbreak }
        else {
            if (!WinHttpReadData(hRequest, buf, dwSize, &dwDownloaded)) { failbreak }
            else {
                realloc:
                if ((totalDownloaded + dwDownloaded) > curalloc) {
                    unsigned char *m = (unsigned char*)malloc(curalloc * 2);
                    curalloc = curalloc * 2;
                    memcpy(m, jar, totalDownloaded);
                    free(jar);
                    jar = m;
                    goto realloc;
                }
                memcpy((jar + totalDownloaded), buf, dwDownloaded);
                totalDownloaded += dwDownloaded;
            }
            VirtualFree(buf, 0, MEM_RELEASE);
        }
    } if (failed) return false;
    CloseHandles();
    FinalResult = (unsigned char*)malloc(totalDownloaded);
    memcpy(FinalResult, jar, totalDownloaded);
    free(jar);
    FinalDownloadedSize = totalDownloaded;
    return true;
}

bool HttpDownload::StartDownload() {
    CloseHandles();
    if (RepeatedTimes > 4) { return false; }
    RepeatedTimes++;
    bool r = InitHttp();
    if (!r) StartDownload();
    r = Download();
    if (!r) StartDownload();
    return true;
}


texts:
I would like to improve my DisjointSet class implementation in Python. I would be grateful for specific advice. I use it in online contests so it must be short, quick and reusable.

from copy import copy
class DisjointSet:

  def __init__(self, s=set()):
    self.__par = {x: x for x in s}
    self.__csz = dict.fromkeys(s, 1)
    self.__root = set(s)

  def root(self, x=None):
    if x is None:
      return(copy(self.__root))
    r = x
    while r != self.__par[r]:
      r = self.__par[r]
    while x != r:
      p = self.__par[x]
      self.__par[x] = r
      x = p
    return(r)

  def add(self, x):
    if x not in self.__par:
      self.__par[x] = x
      self.__csz[x] = 1
      self.__root.add(x)

  def connected(self, x, y):
    return(self.root(x) == self.root(y))

  def connect(self, x, y):
    rx, ry = self.root(x), self.root(y)
    if rx == ry:
      return(rx)
    if self.__csz[rx] < self.__csz[ry]:
      rx, ry = ry, rx
    self.__par[ry] = rx
    self.__csz[rx] += self.__csz[ry]
    self.__root.remove(ry)
    return(rx)

  def size(self, x=None):
    if x is None:
      return(len(self.__root))
    else:
      return(self.__csz[self.root(x)])

  def __len__(self):
    return(len(self.__par))

Simple test

from random import randint
#ds = DisjointSet(xrange(1000000))
ds = DisjointSet()
for x in xrange(1000000):
  ds.add(x)
print len(ds)
print ds.size()
for __ in xrange(1000000):
  ds.connect(randint(0, 999999), randint(0, 999999))
print ds.root(0)
print sum([ds.size(x) for x in ds.root()])
print ds.size()


texts:
Two participants, A and B, are playing the following game:

The initial set of games is a sequence of zeroes and ones.
A and B
change turns, and participant A always moves first.
During each
turn, a player removes one element from the sequence that satisfies
the following:
It is not the first or last element.
It must be
surrounded by zeroes on both sides.
The first participant who can't take
their turn loses the game.
Both participants always move optimally.

Input Format

The first line contains an integer n, denoting the number of games. The subsequent lines describe each game in the following format:

The first line before the sequence contains a single integer denoting the length of the sequence.
The second line contains the sequence, i.e. a space-separated integers denoting the respective values of the initial sequence. Each element is either zero or one.

Sample input

8
61
1 0 1 1 0 1 0 1 1 0 1 1 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 0 1 0 1 1 1 0 1
28
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
28
1 0 1 1 0 1 0 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 0 1 0 1 1
15
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
5
1 0 1 0 1
6
1 0 1 0 1 1
6
0 0 0 0 0 0
7
1 0 1 0 1 0 0

Sample Output

A
B
B
A
A
A
B
B

Graphical explanation for 5th and 7th sample inputs:

Number to be removed during each turn is marked in red.

My code:

 public class Solution {

 public enum Players {
              A { @Override public Players turn() {return B; }},
              B { @Override public Players turn() {return A; }},
              ;

    abstract public Players turn();
}

 public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int g = in.nextInt();
    Players winner = Players.B;

    for(int a0 = 0; a0 < g; a0++){
        int n = in.nextInt();
        Integer[] sequence = new Integer[n];
        for(int sequence_i=0; sequence_i < n; sequence_i++){
            sequence[sequence_i] = in.nextInt();
        }
        ArrayList<Integer> initial = new ArrayList<Integer>(Arrays.asList(sequence));
        Players current = Players.B;
        for (int i=0; i < initial.size()-1; i++) {
            if (i > 0 && initial.get(i-1) == 0 && initial.get(i+1) == 0) {
                current = current.turn();
                winner = current;
                initial.remove(i);
                i = 0;
            }
        }
    System.out.println(winner);
    }
    in.close();
   }
}

Is my code logically correct? The test data is hit but I doubt anyway...


texts:
Challenge description is here need to find the first non repeated character from the string:

Write a program which finds the first non-repeated character in a string.
Input sample:
The first argument is a path to a file. The file contains strings.
For example:
yellow
tooth

Output sample:
Print to stdout the first non-repeated character, one per line.
For example:
y
t

Please let me know can I improve my solution.
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cstring>

void findNonRepeatedChar( const std::string& record)
{
    auto pred= [&record] ( char a, char b){
                  return strchr( record.c_str(), a ) < strchr( record.c_str(), b );
                };
    std::map< char, int, decltype(pred) > stringMap(pred);
    for( auto elem : record )
    {
        auto it = stringMap.find( elem );
        if( it != std::end(stringMap) )
        {
            ++(it->second);
        }
        else
        {
            stringMap.insert( std::make_pair<char&,int>(elem, 1));
        }
    }
    for( auto elem : stringMap)
    {
        if(elem.second == 1)
        {
            std::cout<< elem.first << "\n";
            break;
        }
    }
}

void readInputFile( const char * fileName )
{
    std::ifstream inFile( fileName, std::ifstream::in );
    std::string record="tooth";

    if( !inFile.is_open())
    {
        std::cout<<"File open failed \n";
        return;
    }
    while( getline( inFile, record ) )
    {
        findNonRepeatedChar(record);
    }
}

int main( int argc, char* argv[] )
{
    if( argc < 2 )
    {
        std::cout<<"Usage:program_name input_file_name \n";
    }
    readInputFile(argv[1]);
}


texts: Reading file and print it in hex format really slow

texts:
I'm trying to read a file and print its byte in hex form, using the below code. The code those it but i think optimization can be done to make it read and print faster, because if i remove the print the timestamp is 53ms+/-,
but printing, it takes 18 minutes to read a file of 29mb.

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;

public class cOnvert {
public static void main(String[] args) {
    long startTime = System.nanoTime();
    try {
        try (RandomAccessFile aFile = new RandomAccessFile("filePath", "r")) {
            FileChannel inChannel = aFile.getChannel();
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
            String set;
            for (int i = 0; i < buffer.limit(); i++) {
                byte read = buffer.get();
                set = (String.format("%02X ", (byte) read));
                System.out.print(set);
            }
        }
    } catch (IOException ioe) {
    }
    long endTime = System.nanoTime();
    long elapsedTimeInMillis = TimeUnit.MILLISECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
    System.out.println("Total elapsed time: " + elapsedTimeInMillis + " ms");
}
}

Thank you.


texts: jQuery focus/blur pass variable cleanup challenge

texts:
Little bit of a challenge question. What I have works though I'm no JS wizard, wondering if anyone has a better/preferred way of doing what I'm doing?

Basically, I want to dynamically set a variable on focus, if it exists, and take the id/class/both of a particular form field to echo it in the tag so I can use that as a hook for styling.

If anyone fancies a little Sunday challenge here you go:

  $(function () {
    $('input').focus(function() {
      var use_id = $(this).attr('id');
      var use_class = $(this).attr('class');

      if (use_id) {
        $('body').data('use_id', 'use_' + use_id);
        $('body').addClass($('body').data('use_id'));
      }
      if (use_class) {
        $('body').data('use_class', 'use_' + use_class);
        $('body').addClass($('body').data('use_class'));
      }
    }).blur(function() {
      if ($('body').data('use_id')) {
        $('body').removeClass($('body').data('use_id'));
        $('body').removeData('use_id');
      }
      if ($('body').data('use_class')) {
        $('body').removeClass($('body').data('use_class'));
        $('body').removeData('use_class');
      }
    });
  })


texts:
I have a method which checks all of its surrounding squares and returns the number of bombs around it. But it's really long code and ugly, so can it be shorten?
final int MINE =10

for (int x = 0; x < counts.length; x++) {
    for (int y = 0; y < counts[0].length; y++) {
    if (counts[x][y] != MINE) {
    int Minesearch = 0;
    if (x > 0 && y > 0 && counts[x-1][y-1] == MINE) {//up left
        Minesearch++;
    }
    if (y > 0 && counts[x][y-1] == MINE) {//up
        Minesearch++;
    }
    if (x < counts.length - 1 && y > 0 && counts[x+1][y-1] == MINE) {//up right
        Minesearch++;
    }
    if (x > 0 && counts[x-1][y] == MINE) {//left
        Minesearch++;
    }
    if (x < counts.length - 1 && counts[x+1][y] == MINE) {//right
        Minesearch++;
    }
    if (x > 0 && y < counts[0].length - 1 && counts[x-1][y+1] == MINE) {//down left
        Minesearch++;
    }
    if (y < counts[0].length - 1 && counts[x][y+1] == MINE) {//down
        Minesearch++;
    }
    if (x < counts.length - 1 && y < counts[0].length - 1 && counts[x+1][y+1] == MINE) {//down right
        Minesearch++;
    }
    counts[x][y] = Minesearch;
    }
    }
}
}


texts: cron daily and weekly scripts for a minimal Nginx server environment

texts:
I've created the following cron for daily and weekly scripts for a minimal Nginx server environment (as part of my larger script).

The daily cronjob updates WordPress and brings back original permissions (that are changed by WordPress in its update). The weekly task clears accumulated WordPress cache, make local backups, and delete old backups.

I wonder where this script could be shortened.

cat <<-"CRON_DAILY" > /etc/cron.daily/nses_cron_daily
    for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
    for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done
    for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done
    chown www-data:www-data /var/www/html/* -R
    find /var/www/html/* -type d -exec chmod 755 {} \;
    find /var/www/html/* -type f -exec chmod 644 {} \;
CRON_DAILY
chmod +x /etc/cron.daily/nses_cron_daily

# ---------------------------------------------------------------------------------------------------- #

cat <<-"CRON_WEEKLY" >> /etc/cron.weekly/nses_cron_weekly
    for dir in /var/www/html/*/wp-content; do cd "$dir" && cd cache && rm -rf *; done;

    zip -r /root/backups/dirs/html-$(date +\%F-\%T).zip /var/www/html
    find /root/backups/dirs/* -mtime +30 -exec rm {} \;
    mysqldump -u root -pPASSWORD --all-databases > /root/backups/db/db-$(date +\%F-\%T).sql
    find /root/backups/db/* -mtime +30 -exec rm {} \;
CRON_WEEKLY
chmod +x /etc/cron.weekly/nses_cron_weekly
echo "Change DB root password in crontab."


texts:
I have a method which will merger two sorted list together. The function works, but I saw some duplicated code.

Any ideas to make the code more elegant?

class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

def MergeLists(headA, headB):
    head = tail = Node('',None)
    while headA or headB:

        # duplicated code here
        if headA is not None:
            if (headB and headA.data<=headB.data) or (headB is None):
                tail.next = headA
                tail = headA
                headA = headA.next

        if headB is not None:
            if (headA and headB.data <= headA.data) or (headA is None):
                tail.next = headB
                tail = headB
                headB = headB.next

    return head.next


texts: Create a C style char** from a C++ vector

texts:
I am dealing with some older C style APIs, like Posix execve that take a char**.  In the rest of my code, I prefer to use a fairly modern C++ style, so I have vector of std::string.  Is this the best way to handle the glue between them?

char ** strlist(std::vector<std::string> &input) {
    char** result = new char*[input.size()];
    result[input.size()] = nullptr;
    for (int i=0; i<input.size(); i++) {
        char *temp = new char[input[i].size()];
        strcpy(temp, input[i].c_str());
        result[i] = temp;
    }
    return result;
}

bool del_strlist(char ** strings, int limit=1024) {
    bool finished = false;
    for (int i=0; i<limit; i++) {
        char *temp = strings[i];
        if (temp == nullptr) {
            finished = true;
            break;
        }
        delete temp;
    }
    delete strings;
    return !finished;
}


texts: Registering layers in a web mapping library. API design

texts:
I am working on a web mapping library, that makes it possible to create a map with SVG and JavaScript. As every map shall consist of SVG and Image elements, which can be grouped in layers, which in turn can be set invisible, I need an API to reflect this functionality. I started with two classes/prototypes:

Map()                      // the map constructor
.add(object)               // method to add a layer or element

Layer()                    // the layer constructor
.add(object)               // method to add an element
.setVisibility(boolean)    // mothod to set the visibilty

Some days later I extended the Map with a method to register event handlers that I modeled after the Jquery on/off API:

Map()
.add(object)
.on(events, handler)       // method to register event handlers
.off(events)               // … and to unregsiter handlers

The trick with the events parameter is, that it is a string containing both an event and an optinal namespace to group the event handlers like click.namespace

A classmate then gave me the advice to remove the layer class completely and add "add()" and "remove()" methods that work like the on and off methods to group elements to layers. So the following API emerged:

Map()
.add(namespace, object)
.remove(namespace)
.on(events, handler)
.off(events)

What I find somehow cumbersome, is, that events describe both an event and an optinal namespace, whereas namespace only describes a namespace. So

The Question is:

How to design such an API in a simple, but still consistent way so that I can group elements and event handlers in a similar manner?


texts: Enumerating new articles whose publication start date has passed

texts:
(cn.PublishEnd == null || cn.PublishEnd < DateTime.Now)

vs

(cn.PublishEnd ?? DateTime.MinValue < DateTime.Now)

Which is more readable?
I'm inclined towards the second form, but something tells me I'm wrong.

Context:

namespace Damnation.Website.Main.Business.Extensions
{
    public static class CommunityNews
    {
        public static IEnumerable<DAL.CommunityNews> Published(this ObjectSet<DAL.CommunityNews> table)
        {
            return table.Where(cn => cn.PublishStart > DateTime.Now && DateTime.Now > (cn.PublishEnd ?? DateTime.MinValue)).OrderByDescending(cn => cn.PublishStart);
        }
    }
}

Types

DateTime PublishStart
DateTime? PublishEnd


texts:
I am trying to get a good clean way to do CSS Encapsulation in Angular JS.
The main goal of this is to use isolated components. This is what I have come up with so far.

The method I am using is something I have seen used with React Native.

You define a JavaScript object and place all your styling in the object and apply the styles to the template directly, in this case using ng-style.

JavaScript

styles = {
    background: 'green',
    color: 'black'
  };

HTML

    My Component with local CSS

My main concern is if it will scale I believe it will as you can place the styles object into a service and inject into anywhere needed.

In theory this opens the door to mixins through lodash's _.defaults, theme changes through state changes and a lot of different options.

I'm just reviewing this before I consider it a viable option.

//Component

class myComponent {
    constructor( myCSSService ) {
        this.styles = {
            background: 'black',
            color: 'white'
        };
        this.myCSSService = myCSSService;
    }
}

myComponent.$inject = [ 'myCSSService' ];

angular.module( 'myModule', [] )
    .component( 'myComponent', {
        controller: myComponent,
        bindings: {},
        template: `

            My Component with local CSS

            My Component with Injected CSS

        `,
    } );

//Style Service

class myCSSService{
  constructor( ) {
      this.styles = {
        background: 'green',
        color: 'black'
      };
  }
}

angular.module( 'myCSSModule', [] )
    .service( 'myCSSService', myCSSService );


texts: Parallel Task Queue that runs in sequence

texts:
I'm in need of a solution that runs constantly incoming requests in a per-resource sequence, but parallel in general.

The use-case:

Many clients connect to a server and start issuing work. The work of a single client needs to run in sequential order, so the downward code doesn't need to cope with concurrency, but in general all work should be run on multiple threads. I'm trusting the .NET framework a lot here, which I hope is a good thing.

I've also read into DataFlow and parallel Rx but could not find a general solution there. But hints into that direction are welcome!

class TaskGroup
{
    public int CurrentlyQueuedTasks { get { return _currentlyQueued; } }

    private readonly object _previousTaskMonitor;
    private Task _previousTask;
    private int _currentlyQueued;

    public TaskGroup()
    {
        _previousTaskMonitor = new object();
        _previousTask = Task.CompletedTask;
    }

    public void Append(Action action)
    {
        lock(_previousTaskMonitor)
        {
            Interlocked.Increment(ref _currentlyQueued);
            _previousTask = _previousTask.ContinueWith(task =>
            {
                try
                {
                    action();
                }catch(Exception)
                {
                    //TODO
                }
                finally
                {
                    Interlocked.Decrement(ref _currentlyQueued);
                }
            });
        }
    }
}


texts: Function that builds dictionary based on lambda params

texts:
I've written a method in c# that allows me to do create a dictionary from a passed in object and N lambda expressions that reference that objects properties and methods. It's working the way I want it and seems to perform well, but I'm looking for criticism and seeking to improve the code.

Here's an example usage:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Dictionary<string, object> MakeDictionary()
    {
        return DictionaryThing.Data(this, x => x.Name, x => x.Age);

        /* example return dictionary:

          Name: "Ronnie"
          Age: 29

        */
    }
}

And here's the code for DictionaryThing:

static class DictionaryThing
{

    static ConcurrentDictionary<string, Delegate> expCache = new ConcurrentDictionary<string, Delegate>();

    public static Dictionary<string, object> Data<T>(T obj, params Expression<Func<T, dynamic>>[] expressions)
    {
        var dict = new Dictionary<string, object>();

        foreach (var exp in expressions)
        {
            string name = null;
            var body = exp.Body;

            var unaryExp = body as UnaryExpression;
            if (unaryExp != null)
                body = unaryExp.Operand;

            var memberExp = body as MemberExpression;
            if (memberExp != null)
                name = memberExp.Member.Name;

            var methodCallExp = body as MethodCallExpression;
            if (methodCallExp != null)
                name = methodCallExp.Method.Name;

            if (name == null)
                throw new InvalidExpressionException(
                    string.Format("The expression '{0}' is invalid. You must supply an expression that references a property or a function of the type '{1}'.",
                        exp.Body, typeof(T)));

            var key = typeof(T).FullName + "." + name;
            var func = (Func<T, dynamic>)expCache.GetOrAdd(key, k => ((LambdaExpression)exp).Compile());

            dict[name] = func(obj);
        }

        return dict;
    }

}

My concerns are:

Is there a better way to work with the expressions that are passed in.
Can the expressions parameter be better constrained by a more appropriate type?
Is there a better way to derive the cache key?


texts: Converting an input of space delimited integers to a list

texts:
tablou = input("Enter values delimited by space: ")
b = tablou.split()

t = [] # initial  list with int() contents
for l in b:
    r = int(l)
    t.append(r)

I have to do multiple assignments which require working with lists of integers/floats.  Above is what I'm using for converting a string to a proper list of integers.  I was wondering if there's any way to optimize the code in a such way that it won't need to use memory to keep tablou, b and the final list.  I would be actually working with t

I'm not sure if I used the right terms to describe the issue, I'm still learning.


texts:
I have a controller with just a few actions, not the whole 7 RESTful actions situation. Here's what I have so far for routing:

Snip::Application.routes.draw do
  get "appointment_reminder_responses/confirmation_thanks", to: "appointment_reminder_responses#confirmation_thanks"
  get "appointment_reminder_responses/declination_thanks", to: "appointment_reminder_responses#declination_thanks"
  get "appointment_reminder_responses/:hash", to: "appointment_reminder_responses#create", as: :create_appointment_reminder_response
end

I think there certainly has to be a way to express this in a more DRY way, but but I'm not sure how that might go.


texts: Split string at index field length or just before that if there is white space

texts:
I had to write a function to split a string that goes into a field if it(the string) were too long for the field, as it would disappear and be unreadable.

How's the code lookin' ?

function splitText(instr, fieldSize) //instr = string to split into two lines, fieldSize = the width(in characters)of the field where the string will be showing
{
    if(instr.length>fieldSize) // Check if String requires splitting
    {
        //If Yes split
        var firstLine = instr.substring(0,fieldSize);
        var secondLine = instr.substring(fieldSize);
        //Check some arbitrary number of characters towards the end if there is whiye space(5) Obviously too much would not look too good on teh webSite
        var firstLeft = firstLine.substring(0,13);
        var firstRight = firstLine.substring(13);
        if(firstRight.indexOf(' ')>-1)
            {
                //If There is white space, break the line at it
               instr = firstLeft+firstRight.substr(0,firstRight.indexOf(' '))+" \n"+firstRight.substr(firstRight.indexOf(' ')+1);
            }
        else
            //else just split the string, according to the field size
            instr = instr.substring(0,fieldSize)+"\n "+instr.substring(fieldSize);
        }

    return instr;
}


texts: all combinations of all sizes less than N

texts:
I want to generate all possible combinations (without duplicates) of all sizes less or equal than \$N\$, so for example if \$N=3\$ I want to generate the following
\$\{1\},\{2\},\{3\},
\{1,2\},\{1,3\},\{2,3\},
\{1,2,3\}.\$

I created the following algorithm in Java. Is there a more optimal way to generate?

public class Main {

public static void main(String[] args) {

    int n = 3;

    for (int k=1; k <= n; k++) {
        System.out.println("of size "+k);
        List<int[]> perms = generateOfSize(k, n);
        System.out.print(perms.size()+": ");
        for(int i=0; i<perms.size(); i++){
            int[] perm = perms.get(i);
            System.out.print(perms.get(i)[0]);
            for(int j=1; j < k; j++){
                System.out.print("-"+perms.get(i)[j]);
            }
            System.out.print(", ");
        }
        System.out.println();
    }
}

public static List<int[]> generateOfSize(int k, int n){
    int[] cur = new int[k];
    List<int[]> all = new ArrayList<int[]>();

    // 1-st step - init
    for (int i = 0; i < k; i++){
        cur[i] = i;
    }

    // 2-nd step - do shifts
    do{
        int[] copy = new int[k];
        System.arraycopy( cur, 0, copy, 0, cur.length );
        all.add(copy);
    } while (doShift(cur, k, n));

    return all;
}

public static boolean doShift(int[] cur, int k, int n){
    if (cur[k-1] < n-1){
        cur[k-1] = cur[k-1] + 1;
        return true;
    }
    for(int i = k-1; i > 0; i--){
        if (cur[i] - cur[i-1] > 1) {
            cur[i-1] = cur[i-1] + 1;
            for (int j = i; j < k; j++){
                cur[j] = cur[j-1]+1;
            }
            return true;
        }
    }
    return false;
}

}


texts: File Exists Script Task for SQL Server SSIS

texts:
I have an SSIS package for SQL Server 2008. In this package, I need to verify that a file exists that matches a pattern of SomeFileName_*.txt where the wild card replaces a YYYYMMDD date. It doesn't matter what the date of the file is, just that any file matching that pattern exists. If a file does not exist, I need to fail the package before using the built in "For each file loop" task. This allows our server to alert me to the package failure.

It's a pretty simple bit of code, but it has a huge smell. I'm catching Exception. I think I'm doing it for the right reasons though. Basically, I'm saying that if any exception gets thrown, fail the script task, and thus the package. Is this a case where it's okay to catch all exceptions??? For reference, these are the possible exceptions that Directory.GetFiles can throw.

Of course, I'm pretty new to c#, so please let me know if I'm doing anything stupid. (Yes, I know I'm programming in Main, but this is short and sweet. I don't see the harm just this once...)

public void Main()
{

    try
    {
        string sourcePath = Dts.Variables["User::sourcePath"].Value.ToString();
        string searchPattern = Dts.Variables["User::searchPattern"].Value.ToString();

        string[] files = Directory.GetFiles(sourcePath, searchPattern, SearchOption.TopDirectoryOnly);
        if (files.Length > 0)
        {
            Dts.TaskResult = (int)ScriptResults.Success;
        }
        else
        {
            Dts.TaskResult = (int)ScriptResults.Failure;
            Dts.Log(string.Format("No file(s) found in '{0}' with a pattern of '{1}'.", sourcePath, searchPattern), 0, null);
        }
    }
    catch (Exception e)
    {
        Dts.TaskResult = (int)ScriptResults.Failure;
        Dts.Log(string.Format("Script Task encountered an unexpected error. Souce: {0}. Message: {1).", e.Source, e.Message), 0, null);
    }
}


texts: Fastest way for working with itertools.combinations

texts:
I need to speed up the function below:

import numpy as np
import itertools

def combcol(myarr):
    ndims = myarr.shape[0]
    solutions = []
    for idx1, idx2, idx3, idx4, idx5, idx6 in itertools.combinations(np.arange(ndims), 6):
        c1, c2, c3, c4, c5, c6 = myarr[idx1,1], myarr[idx2,2], myarr[idx3,1], myarr[idx4,2], myarr[idx5,1], myarr[idx6,2]
        if c1-c2>0 and c2-c3<0 and c3-c4>0 and c4-c5<0 and c5-c6>0 :
            solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(c1, c2, c3, c4, c5, c6)))
    return solutions

X = np.random.random((20, 10))
Y = np.random.random((40, 10))

if __name__=='__main__':
    from timeit import Timer
    t = Timer(lambda : combcol(X))
    t1 = Timer(lambda : combcol(Y))
    print('t : ',t.timeit(number=1),'t1 : ',t1.timeit(number=1))

Results:

t :  0.6165180211451455 t1 :  64.49216925614847

The algorithm is too slow for my standard use (myarr.shape[0] = 500).  Is there a NumPy way to decrease execution time of this function (without wasting too much memory)?  Is it possible to implement the problem in Cython?


texts: Product matcher refactoring regarding scopes and arrays

texts:
I know I have seen this before and I can't remember how to fix it or find where I saw how to fix it:

def product_matcher(item)
  product = []
  if !item.blank?
    product = self.products.where(:id => item.id).first
  else
    product = self.products.where(:id => token.id).first
  end
  product
end

It seems wrong to me to first set the variable to an array, then inside the scope of the each to set product to the result of the query and then at the end of the method have the variable return the product.  Since Ruby doesn't have explicit types my belief is that you don't even need the product = [] and since the result of a Ruby method is always to return you more than likely don't even need product at the end. However, due to scoping the output would be encapsulated inside the each block and the method would ultimately return nothing when called.  How do I improve this?


texts:
I asked a question on Stack OverFlow and I got an answer to my question but then I found out the program is crashing because I have 250k data points on my Excel sheet. I was wondering what I can do to make it so it won’t crash. I'm hoping I can understand what I can do to improve the code.

Sub CompareTime()

Dim ws As Worksheet

Dim lastRow As Long
Dim Count As Long
Dim test As Double

Set ws = ActiveSheet

'Find last data point
With ws
    .Columns(2).Insert
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    For Count = 5 To lastRow
        'split date
        test = .Cells(Count, 1).Value2
        .Cells(Count, 1).Value2 = Int(test)
        .Cells(Count, 1).NumberFormat = "m/d/yyyy"
        .Cells(Count, 1).Offset(0, 1).Value2 = test - Int(test)
        .Cells(Count, 1).Offset(0, 1).NumberFormat = "hh:mm AM/PM"

    Next Count
End With

End Sub


texts: A from_string() function (inverse of std::to_string)

texts:
I've been thinking of using this:

template <typename T>
inline T from_string(const std::string& s){
   std::istringstream iss;
   iss.str(s);
   T result;
   iss >> result;
   return result;
}

in my code. Then I thought "I shouldn't construct istringstreams all the time", and made it into this:

inline std::istringstream& get_istringstream(){
    static thread_local std::istringstream stream;
    stream.str("");
    return stream;
}

template <typename T>
inline T from_string(const std::string& s){
   auto& iss(get_istringstream());
   iss.str(s);
   T result;
   iss >> result;
   return result;
}

... and this builds and works (although I haven't tested it very extensively, nor ran performance tests). Would you say that "good enough" for general-purpose utility code, that is not intended to run in some tight loop? Are there other considerations I've overlooked, performance-wise (*) or usability-wise?

Perhaps I should mention my motivation here is partly how I found it strange that there's no std::from_string().

Edit: If you're concerned about the dependence on a default constructor, we can also throw in this:

template< typename T >
struct istream_traits {
    inline static T read(std::istream& is)
    {
        T x;
        is >> x;
        return x;
    }
};

template<> struct istream_traits<bool> {
    inline static bool read(std::istream& is)
    {
        is >> std::boolalpha;
        bool x;
        is >> x;
        return x;
    }
};

template<typename T>
inline T read(std::istream& is)
{
    T x = istream_traits<T>::read(is);
    return x;
}

... and then replace T result; iss >> result; with return read<T>(iss);.

(*) - Yes, I know anything with iostreams is probably not fast to begin with.


texts: Prompting for grades, with confirmation if a score higher than 100 is entered

texts:
This is an exercise from my computer programming class. This program reads in student scores from the user (input) and displays the total points earned along with a grade. I am tasked with modifying it to ask the user for confirmation when a score higher than 100 is entered. Plainly, it should not add a score greater than 100 to the accumulator without permission.

Here is the original source:

 //Lab7-2.cpp - displays the total points earned and grade
 //Created/revised by <your name> on <current date>

 #include <iostream>

 using namespace std;

 int main()
 {
 //declare variables
    int score       = 0;
    int totalPoints = 0;  //accumulator
    char grade      = ' ';

    //get first score
    cout << "First score (-1 to stop): ";
    cin >> score;

    while (score != -1)
    {
        //update accumulator, then get another score
        totalPoints += score;
    cout << "Next score (-1 to stop): ";
    cin >> score;
    }   //end while

    //determine grade
    if (totalPoints >= 315)
    grade = 'A';
    else if (totalPoints >= 280)
    grade = 'B';
    else if (totalPoints >= 245)
    grade = 'C';
    else if (totalPoints >= 210)
    grade = 'D';
    else
    grade = 'F';
    //end if

    //display the total points and grade
    cout << "Total points earned: " << totalPoints << endl;
    cout << "Grade: " << grade << endl;

    system("pause");
 return 0;
 }   //end of main function

Here is the modified source:

//Lab7-2.cpp - displays the total points earned and grade
//Created/revised by Willy Njundong on 2/14/2016

#include <iostream>

using namespace std;

int main()
{
//declare variables
int score = 0;
int totalPoints = 0;  //accumulator
char grade = ' ';
char decision = ' ';

//get first score
cout << "First score (-1 to stop): ";
cin >> score;

while (score != -1)
{
    if (score > 100)
    {                                                                //CONFIRM SCORE VALIDITY
        cout << endl << "Is score correct? (Enter y or n): ";        //IF GREATER THAN 100
        cin >> decision; cout << endl;
        if (decision != 'y' && decision != 'Y')                 //ANY CHARACTER ENTERED OTHER THAN 'Y' FOR YES
            score = 0;                                          //RESULTS IN SCORE OVER 100 BEING IGNORED (SET TO ZERO)
        else
        {                                                       //AND THEN THE
            //update accumulator, then get another score        //PROGRAM RESUMES NORMAL EVALUATION
            totalPoints += score;
            cout << "Next score (-1 to stop): ";
            cin >> score;
        }   //end if

    }
    else                                                        //THESE ARE PROCESSED WHEN SCORES
    {                                                           //ENTERED ARE 100 OR LESS
        //update accumulator, then get another score
        totalPoints += score;
        cout << "Next score (-1 to stop): ";
        cin >> score;
    }   //end if

}   //end while

    //determine grade
if (totalPoints >= 315)
    grade = 'A';
else if (totalPoints >= 280)
    grade = 'B';
else if (totalPoints >= 245)
    grade = 'C';
else if (totalPoints >= 210)
    grade = 'D';
else
    grade = 'F';
//end if

//display the total points and grade
cout << "Total points earned: " << totalPoints << endl;
cout << "Grade: " << grade << endl;

system("pause");
return 0;
}   //end of main function


texts:
I've recently started learning rust and doing cryptopals as exercise.
I coded a program that decrypts single xor cypher. The algorithm I came up with is very simple and probably not efficient, but I would like more emphasis on rust philosophy and syntax
extern crate hex;
use std::collections::HashMap;

fn main() {
    let ciphertext = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736";
    let ciphertext_bytes = hex::decode(ciphertext).unwrap();
    let xor_key = find_xor_key(&ciphertext_bytes);
    println!("{}", ciphertext_bytes.iter().map(|x|(x^xor_key) as char ).collect::<String>());
}

fn find_xor_key(ciphertext: &Vec<u8>) -> u8{

    let mut max_score = 0;
    let mut best_key = 0;
    for xor_key in 1..255{
        let xored_vec = ciphertext.iter().map(|x|x^xor_key).collect();
        let score = get_score(xored_vec);
        if score > max_score{
            max_score = score;
            best_key = xor_key;
        }
    }
    println!("{}", max_score);

    best_key
}

fn get_score(text: Vec<u8>) -> u8
{
    let ideal_frequencies: HashMap<char, f32> = [

('E', 11.1607),
('M', 3.0129),
('A', 8.4966),
('H', 3.0034),
('R', 7.5809),
('G', 2.4705),
('I', 7.5448),
('B', 2.0720),
('O', 7.1635),
('F', 1.8121),
('T', 6.9509),
('Y', 1.7779),
('N', 6.6544),
('W', 1.2899),
('S', 5.7351),
('K', 1.1016),
('L', 5.4893),
('V', 1.0074),
('C', 4.5388),
('X', 0.2902),
('U', 3.6308),
('Z', 0.2722),
('D', 3.3844),
('J', 0.1965),
('P', 3.1671),
('Q', 0.1962),

    ].iter().cloned().collect();

    for byte in text.clone(){
        let char_rep: char =  byte as char;
        if !char_rep.is_ascii(){
            return 0;
        }
    }
    let mut score = 1;
    let chars: Vec<char> = text.iter().cloned().map(|x|x as char).collect();
    let frequencies: HashMap<char, f32> = calculate_frequencies(&chars.into_iter().collect::<String>());

    for (letter, frequency) in &frequencies{
        if ideal_frequencies.contains_key(&letter) && //already checked here that it exists in the hashmap
        f32::abs(frequency - ideal_frequencies.get(&letter).unwrap()) <= 10.0{
            score += 1;
        }
    }
    score
}

fn calculate_frequencies(text: &str) ->HashMap<char, f32>{

    let mut frequencies: HashMap<char, f32> = HashMap::new();
    let mut letter_counts:HashMap<char, i32> = HashMap::new();
    let text_upper = text.to_ascii_uppercase();
    for c in text_upper.chars(){
        let count = letter_counts.entry(c).or_insert(0);
        *count += 1;
    }
    for (c, count) in letter_counts{
        frequencies.entry(c).or_insert(count as f32 / text_upper.len() as f32 * 100.0);
    }
    frequencies
}
```


texts: Printing Command Line Unicode Chess Board

texts:
Let me preface this by detailing some of my design philosophy. The intent is to view the board from the perspective of the active player. Player moves are also factored into the design. When determining move logic, all that needs to happen is comparing against '0'. For checking the whiteness or blackness of a piece, ord(c) % 265 should help by pulling the remainder and checking if it's in range(4,10) or range(10,16). Anyway, any optimizations and critique is welcome! I'm particularly interested if it involves numpy, scipy | bitwise operators.

chess.py

import numpy as np

chrs = {
    'b_checker': u'\u25FB',
    'b_pawn': u'\u265F',
    'b_rook': u'\u265C',
    'b_knight': u'\u265E',
    'b_bishop': u'\u265D',
    'b_king': u'\u265A',
    'b_queen': u'\u265B',
    'w_checker': u'\u25FC',
    'w_pawn': u'\u2659',
    'w_rook': u'\u2656',
    'w_knight': u'\u2658',
    'w_bishop': u'\u2657',
    'w_king': u'\u2654',
    'w_queen': u'\u2655'
}

def get_checkers():
    bw_row = [chrs['b_checker'], chrs['w_checker']]*4
    bw_checkers = []

    for i in range(8):
        bw_checkers.append(bw_row if i % 2 == 0 else bw_row[::-1])

    bw_checkers = np.array(bw_checkers)
    wb_checkers = bw_checkers[::-1]
    return {'W': wb_checkers, 'B': bw_checkers}

def get_board():

    def get_army(user):
        u = user.lower()
        guard = [chrs[u+'_rook'], chrs[u+'_knight'], chrs[u+'_bishop']]
        rear = guard + [chrs[u+'_king'], chrs[u+'_queen']] + guard[::-1]
        front = [chrs[u+'_pawn']]*8

        if user == 'B':
            return [rear, front]
        else:  # since white moves first
            return [front, rear]

    board = [squad for squad in get_army('B')]

    for _ in range(4):
        board.append(['0']*8)

    board += get_army('W')

    return np.array(board)

def print_board(board, checkers, user):
    chks = checkers[user]
    temp = board.copy() if user == 'W' else board.copy()[::-1]

    for i, row in enumerate(temp):
        for j, c in enumerate(row):
            print('', chks[i][j] if c == '0' else c, end='', flush=True)
        print()

if __name__ == "__main__":
    checkers = get_checkers()
    board = get_board()
    user = 'W'
    print_board(board, checkers, user)

Present Output:

White's Perspective

♜ ♞ ♝ ♚ ♛ ♝ ♞ ♜
♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟
◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻
◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼
◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻
◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼
♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖

Black's Perspective

♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖
♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼
◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻
◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼
◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻
♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟
♜ ♞ ♝ ♚ ♛ ♝ ♞ ♜


texts:
This is my first ever Python program. I thought I would make a calculator that performs 5 operations: add, subtract, divide, multiply, power. I am aware Python has its own power function, called "pow", but I have defined my own power function for practice.

I've taken the input as a single string, and then I've tried to separate the numbers from the operator in my for loop, using what little Python I currently know. Perhaps this is the section of my code that could be made cleaner, above all else?

Coming from Java, my first instinct was to use a switch statement to handle each operator case. I quickly realised Python doesn't have switch statements, but I discovered that dictionaries are apparently a good substitute. But maybe there is a better way of handling each operator case?

And obviously, I should have error handling, but let's just ignore that detail for now.

val = str(input("Calculate: "))

# get first number, second number, and operator, from string
foundOp = False # has the operator been found?
a, b = "", "" # first and second number
for char in val:
    # concatenate digits
    if char.isdigit():
        if foundOp:
            b = b + char
        else:
            a = a + char
    # skip spaces
    elif char == " ":
        continue
    # find operator
    elif not char.isdigit():
        foundOp = True
        op = char

# convert a and b into int
a, b = int(a), int(b)

# compute a ^ b
def power(a,b):
    original_a = a
    for i in range(1,b):
        a *= original_a
    return a

calc = {
    "+": a + b,
    "-": a - b,
    "*": a * b,
    "/": a / b,
    "^": power(a,b)
}

print(calc[op])


texts:
I registered a CustomMapAnnotationView and a ClusterView: the first one simply extends MKMarkerAnnotationView and overrides annotation this way:

override var annotation: MKAnnotation? {
        willSet {
        // CustomMapAnnotation is based on MKPointAnnotation
            if let c = value as? CustomMapAnnotation {
                clusteringIdentifier = "c"
                markerTintColor = UIColor.orange
                displayPriority = .defaultLow
            }
        }
    }

ClusterView is a MKAnnotationView that is used when annotations can be grouped.

 mapView.register(CustomMapAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
 mapView.register(ClusterView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)

Now the code review part.

I use CustomMapAnnotationView and ClusterView this way:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        guard !(annotation is MKUserLocation) else {
            return nil
        }

        if(annotation is CustomMapAnnotation){

            let annotationID = "c"

            var annotationView: CustomMapAnnotationView?

            if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationID) as? CustomMapAnnotationView {
                annotationView = dequeuedAnnotationView
                annotationView!.annotation = annotation
            }
            else
            {
                annotationView = CustomMapAnnotationView(annotation: annotation, reuseIdentifier: annotationID)
                annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
            }

            if let annotationView = annotationView {
                annotationView.canShowCallout = true
            }

            return annotationView

        }else{

            let clusterID = "Cluster"
            var clusterView = mapView.dequeueReusableAnnotationView(withIdentifier: clusterID)
            if clusterView == nil {
                clusterView = ClusterView(annotation: annotation, reuseIdentifier: clusterID)
            } else {
                clusterView?.annotation = annotation
            }

            return clusterView
        }
        }

This code perfectly works or at least it does what I wanted it to do.
But I'm not sure this is correct way to perform this action inside the body of this function. Any suggestion is appreciated.


texts: Matasano CryptoPals Problem 8: Detecting ECB encryption

texts:
For the Matasano CryptoPals Challenges Set 1 Problem 8, which states:

  In this file are a bunch of hex-encoded ciphertexts.

  One of them has been encrypted with ECB.

  Detect it.

  Remember that the problem with ECB is that it is stateless and deterministic; the same 16 byte plaintext block will always produce the same 16 byte ciphertext.

I have written the following Python Code. Since I'm a programmer coming from C++ to Python, some of it might be reminiscent of that transfer. Can I be more Pythonic than the code I've written? Any more suggestions?

#! /usr/bin/env python

from binascii import a2b_hex

def is_ECB_encoded(data, block_size):
  block_count = len(data)/block_size
  for i in range(block_count):
    for j in range(i+1,block_count):
      if data[i*block_size:(i+1)*block_size] == data[j*block_size:(j+1)*block_size]:
        return True
  return False

filename = '8.txt'
for line in open(filename):
  line = line.strip()
  if is_ECB_encoded(a2b_hex(line), 16):
    print line


texts:
The implementation of the algorithm which adds two number in string form with arithmetic rules.

var assert = require('assert');

var strAdd = function(lnum, rnum) {
  lnum = lnum.split('').reverse();
  rnum = rnum.split('').reverse();
  var len = Math.max(lnum.length, rnum.length),
      acc = 0,
      res = [];
  for(var i = 0; i < len; i++) {
    var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc;
    acc = ~~(subres / 10); // integer division
    res.push(subres % 10);
  }
  if (acc !== 0) {
    res.push(acc);
  }
  return res.reverse().join('');
};
assert(strAdd('1', '9') === '10');
assert(strAdd('1', '0') === '1');
assert(strAdd('5', '5') == '10');
assert(strAdd('2', '2') === '4');
assert(strAdd('20', '202') === '222');

Is there a better way(in terms of complexity) to achieve the same result?
Any style advice is appreciated.


texts: Designing unit tests for paramiko wrapper

texts:
Before I get to the question, let me note that I'm a trained scientist, not a programmer; I've done my best to self-teach what I've needed to know so far, but in the interest of making my code usable for other people in my research group, I'd like to improve my code. I spent a weekend writing actual documentation for stuff, and the next thing on the list of making this more stable is unit testing, which I think I have a basic understanding of, but have never implemented in anything I've written.

I've developed a wrapper for paramiko that allows me load scientific data from a remote host. I was curious about how to best design a unit test for other scripts that rely on this function, or if one is even necessary? If there are any security holes or performance improvements, suggestions would be very appreciated!

def get_remote_data(filepath, time=False, info=False, copy_to_local=False):
    """
    A paramiko wrapper that gets file from a remote computer. Parses
    hostname from filepath. Works only for netcdf files!

    Keyword Arguments:
    filepath         -- the path of the file with hostname.
    time             -- print time required for loading(default False)
    info             -- print some information about the file after loading
                        (default False)
    copy_to_local    -- copies file to local /tmp/remote_data/ and checks
                        if this file already exists there (default False)

    Example:
    >>> get_remote_data('pgierz@rayo3:/csys/paleo2/pgierz/GR30s.nc')
    # TODO: Find out if this is the right way to do this, and make a unit test.
    Paul J. Gierz, Sat Feb 14 14:20:43 2015
    """
    # Import stuff from your own library:
    from UI_Stuff import print_colors
    if time:
        import time
    import paramiko
    import os
    from scipy.io import netcdf
    if time:
        now = time.time()
    print "Trying to load ".ljust(40) \
          +print_colors.WARNING("{f}").format(f=os.path.basename(filepath)).ljust(100)
    if not copy_to_local:
        # We wish to split the filepath to get the username, hostname, and
        # path on the remote machine.
        user = filepath.split(':')[0].split('@')[0]
        host = filepath.split(':')[0].split('@')[1]
        rfile = filepath.split(':')[1]
        # FIXME: This function only works if .ssh/id_rsa exists
        privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
        mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(host, username=user, pkey=mykey)
        sftp = client.open_sftp()
        fileObject = sftp.file(rfile)
        file = netcdf.netcdf_file(fileObject)
        pre_s = "Loaded from "+host
    else:
        pre_s, fileObject = _copy_remote_file(file path)  # This is my own function that creates an rsync process
        file = netcdf.netcdf_file(fileObject)
    if time:
        print pre_s.ljust(40) \
        +print_colors.OKGREEN("{filepath}").format(filepath=os.path.basename(filepath)).ljust(100) \
        +" in ".rjust(0) \
        +print_colors.OKBLUE("{time}").format(time=round(time.time()-now)) \
        +" seconds"
    if info:
        s = print_colors.HEADER("#"*30+" INFO of "+os.path.basename(filepath)+" "+"#"*30)
        print s
        print "Variables: \n"
        for k, v in file.variables.iteritems():
            print k, ":  dimensions -"+str(v.dimensions)+" shape - "+str(v.shape)
        print "Dimensions: \n"
        print file.dimensions
        print print_colors.HEADER("#"*len(s))
    return file


texts: Getting a string from a range of possible paths

texts:
I have a scenario where I need to grab the first occurrence of a string from an object, but only if the match occurs in one of the path's that have been pre-defined.

{ id: 'I60ODI', description: 'some random description' }
{ foo: 'bar', description: { color: 'green', text: 'some description within text' } }

When provided either of the two objects above, I would expect the solution to return either some random description or some description within text, provided that the two possible paths are obj.description and obj.description.text. New paths might also need to be added in the future, so it needs to be easy to add them.

Here is the solution I have implemented so far, but to me it doesn't seem optimal.

// require the ramda library
const R = require('ramda');

// is the provided value a string?
const isString = R.ifElse(R.compose(R.equals('string'), (val) => typeof val), R.identity, R.always(false));
const addStringCheck = t => R.compose(isString, t);

// the possible paths to take (subject to scale)
const possiblePaths = [
    R.path(['description']),
    R.path(['description', 'text'])
];
// add the string check to each of the potential paths
const mappedPaths = R.map((x) => addStringCheck(x), possiblePaths);

// select the first occurrence of a string
const extractString = R.either(...mappedPaths);

// two test objects
const firstObject = { description: 'some random description' };
const secondObject = { description: { text: 'some description within text' } };
const thirdObject = { foo: 'bar' };

console.log(extractString(firstObject)); // 'some random description'
console.log(extractString(secondObject)); // 'some description within text'
console.log(extractString(thirdObject)); // false

I would really appreciate it if a seasoned functional programmer might provide me with some alternative approaches to implementation. Thanks.


texts:
I am currently working with this code to automate some tasks for senior staff members that are not very adept in Excel. Wondering if VBA is simply not a very quick code or if my code is clunky and slow.

For clarity, I would think with how simple this code is it could run in under a second or two. Maybe this is overzealous?

Sub Paste()

'---Paste Macro
'---2016-05-23

Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim LastRow As Long
Dim LastRow2 As Long
Dim LastColumn As Long
Dim StartCell1 As Range
Dim StartCell2 As Range
Dim rng1 As Range
Dim rng2 As Range

Set sht1 = GetWSFromCodeName("Sheet10")
Debug.Print sht1.Name
Set sht2 = GetWSFromCodeName("Sheet8")
Debug.Print sht2.Name
Set StartCell1 = Range("A2")
Set StartCell2 = Range("B2")

'Find Last Row and Column
  LastRow = sht1.Cells(sht1.Rows.Count, StartCell1.Column).End(xlUp).Row
  LastColumn = sht1.Cells(StartCell1.Row, sht1.Columns.Count).End(xlToLeft).Column
  LastRow2 = sht2.Cells(sht2.Rows.Count, StartCell1.Column).End(xlUp).Row

'Select Range And Copy into Final Formula Sheet
  sht1.Range(StartCell1, sht1.Cells(LastRow, LastColumn)).Copy Destination:=sht2.Cells(LastRow2 + 1, 2)

'Convert Text in Column C of Final Formula Sheet to Numbers to Allow Advisor Code to Apply

 Set rng1 = Range(sht2.Cells(LastRow2, 3), sht2.Cells(LastRow2 + LastRow - 1, 3))
 With rng1
    .NumberFormat = "0"
    .Value = .Value
    End With

'Copy Advisor Function down to meet with new Pasted in Data
    With sht2
        Set rng2 = .Cells(LastRow2, 1)
        End With
    With rng2
        .Copy Destination:=Range(sht2.Cells(LastRow2, 1), sht2.Cells(LastRow2 + LastRow - 1, 1))
        End With

End Sub

'---This Function allows the worksheet name to change in the workbook as it allows the
    'user to set Worksheets to codename variables. By using this function the user can input a
    'codename for a worksheet and the function will call the worksheet name of the corresponding
    'codename, allowing the user to set worksheet variables to codenames without losing
    'functionality usually associated with such variables.
'---2016-05-23

Public Function GetWSFromCodeName(CodeName As String) As Worksheet

    Dim WS As Worksheet
    For Each WS In ThisWorkbook.Worksheets
        If StrComp(WS.CodeName, CodeName, vbTextCompare) = 0 Then
            Set GetWSFromCodeName = WS
            Exit Function
        End If
    Next WS

End Function


texts:
I have a list of input, a greedy method and a dynamic programming method. I wrote a unittest script to test my two methods with input list but I don't know if I'm writing it right:

import unittest
from land_selling import Offer, Seller

class LandSellingTest(unittest.TestCase):
    offers1 = [
        Offer(0, 6, 2),
        Offer(1, 2, 4),
        Offer(3, 5, 1),
        Offer(5, 9, 3),
        Offer(7, 10, 2),
        Offer(10, 20, 5),
        Offer(34, 2, 1)
    ]
    offers2 = [
        Offer(6, 10, 4),
        Offer(1, 5, 2),
        Offer(7, 20, 3),
        Offer(2, 7, 1),
        Offer(14, 30, 2),
        Offer(3, 6, 3),
        Offer(8, 15, 2),
        Offer(20, 35, 5),
        Offer(25, 5, 3)
    ]
    offers3 = [
        Offer(17, 1, 12),
        Offer(7, 2, 10),
        Offer(17, 2, 8),
        Offer(20, 3, 6),
        Offer(3, 11, 4),
        Offer(22, 12, 2)
    ]

    // input list
    global offers_list
    offers_list = [offers1, offers2, offers3]

    // greedy output list
    global greedy_answers
    greedy_answers = [4, 3, 2]

    // dynamic output list
    global dynamic_answers
    dynamic_answers = [13, 12, 16]

    @classmethod
    def setUpClass(self):
        self.offers_list = offers_list
        self.greedy_answers = greedy_answers
        self.dynamic_answers = dynamic_answers

    def test_greedy(self):
        for offers, ans in zip(self.offers_list, self.greedy_answers):
            seller = Seller(offers)
            seller.set_up()
            self.assertEqual(len(seller.accepted_offers()), ans)

    def test_dynamic(self):
        for offers, ans in zip(self.offers_list,self.dynamic_answers):
            seller = Seller(offers)
            seller.sort_offers_by_finish()
            self.assertEqual(seller.maximum_profit(), ans)

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


texts:
I wrote a function that returns a directed graph as an adjacency matrix. The function requires two arguments: the amount of nodes and the amount of edges. At first, nodes are placed and instantly connected to the graph. When all nodes are added, random edges are created until all edges are placed.
Code:
public int[,] GenerateMatrix(int Nodes, int Edges)
    {
        if (Edges < Nodes - 1) throw new Exception("Too few edges");
        if (Edges > Nodes * (Nodes - 1)) throw new Exception("Too many edges");

        int[,] adjacencyMatrix = new int[Nodes, Nodes];

        // Gives every cell a value of zero
        for (int y = 0; y < Nodes; y++)
        {
            for (int x = 0; x < Nodes; x++)
            {
                adjacencyMatrix[x, y] = 0;
            }
        }

        int placedEdges = 0;

        for (int i = 1; i < Nodes; i++)
        {
            // produce edge between rnd(0, amountofnodes) to new node
            int fromVertex = random.Next(0, i);
            int weight = random.Next(1, 10);

            adjacencyMatrix[i, fromVertex] = weight;
            placedEdges++;
        }

        while (placedEdges < Edges)
        {
            int fromVertex = random.Next(0, Nodes);
            int weight = random.Next(1, 10);

            int targetVertex = random.Next(0, Nodes);
            while (targetVertex == fromVertex || adjacencyMatrix[targetVertex, fromVertex] != 0) //|| adjacencyMatrix[fromVertex, targetVertex] != 0)// tredje condition tar bort parallella kanter
            {
                fromVertex = random.Next(0, Nodes);
                targetVertex = random.Next(0, Nodes);
            }

            adjacencyMatrix[targetVertex, fromVertex] = weight;
            placedEdges++;
        }

        return adjacencyMatrix;
    }


texts: Improved manipulation of a 2D array for a game map

texts:
I have a 2D array (or rather, an array of arrays) representing tile maps in game. The 'world' map array holds smaller arrays representing individual map parts which I am calling 'rooms':

var worldMap = [
    [room1, room2],
    [room3, room4]
];

I have some code which takes note of the 'current' room (which will be visible on screen to the player) and calculates what map should be loaded as the 'next' room. This will be triggered when the player walks off the edge of the screen. The key variable is currentMap - this variable will be passed to the function responsible for rendering the tile map that the user can see.

My code works and suits my purposes, but I'm wondering if there is a more efficient or elegant way to write it.

JSFiddle Code

function indexOf2d(arrayParam, valueParam) {
    var index = [-1, -1];
    if (!Array.isArray(arrayParam)) {
        return index;
    }
    arrayParam.some(function (sub, posX) {
        if (!Array.isArray(sub)) {
            return false;
        }
        var posY = sub.indexOf(valueParam);
        if (posY !== -1) {
            index[0] = posX;
            index[1] = posY;
            outputA = index[0];
            outputB = index[1];
            return true;
        }
        return false;
    });
    return index;
}

function goToNextRoomDown(map, valueA, valueB) {
    var newValue = valueA + 1;
    var result = map[newValue][valueB];
    return result;
}

Please note that although I am only showing 'goToNextRoomDown', I intend for the user to be able to access maps that are above, below, left and right of their current location. I'm intending to write a function that handles all of these possibilities, rather than having four separate functions, but before I do that I'm more interested in improving what I have presented so far. I'm not asking anyone to write the code for me, so I hope this question still qualifies as on-topic.

// get the index of the currentMap within the worldMap
console.log(indexOf2d(worldMap, currentMap));
// use the index value outputs to calculate the next room 'down' the worldMap array
console.log('next room down: ' + goToNextRoomDown(worldMap, outputA, outputB));
// assign the new room as the currentMap
currentMap = goToNextRoomDown(worldMap, outputA, outputB);


texts: Auctioneer calling "Going once… going twice… sold!"

texts:
I feel like the if-else combination isn't the most optimal and I'm also not sure if I need a loop

var Auktionator = function(){
var rennt = false;

this.versteigern = function(objekt){
        if(rennt === false){
        for(var i = 1; i<=4; i++){
            if(i === 1){
                setTimeout(function(){console.log(objekt + " zum ersten")},1000*i);
            }
            else if(i === 2){
                setTimeout(function(){console.log(objekt + " zum zweiten")},1000*i);
            }
            else if(i === 3){
                setTimeout(function(){console.log(objekt + " zum dritten")},1000*i);
            }
            else if(i === 4){
            setTimeout(function(){console.log(objekt + " verkauft!")},1000*i);

        }
         rennt = true;
    }
    }
}
}


texts:
I started learning Rust today and for my first project created a simple webserver.

I don't have a clear vision about Rust programming and I tried to write it with my previous knowledge in Python and PHP.

use std::io::{Read, Write,BufReader, BufRead};
use std::net::{TcpListener, TcpStream};
use std::fs::File;
use std::path::Path;

fn main(){
    loop{
        let listener = TcpListener::bind("localhost:8000").unwrap();
        let stream  = listener.accept().unwrap().0;
        read_request(stream);
    }
}

fn read_request(stream: TcpStream){

    let mut lines = String::new();
    let mut reader = BufReader::new(stream);
    reader.read_line(&mut lines);
    let mut vec_line = lines.split_whitespace();
    let mut requested_page = vec_line.nth(1).unwrap().to_string();
    requested_page = requested_page.replace("/","");
    if requested_page == "" {
        requested_page = String::from("index.html");
    }
    let mut response = String::new();
    let path = Path::new(&requested_page);
    println!("{}",requested_page);
    let mut status = 200;
    if !path.exists(){
        response = String::from("Not Found!");
        status = 404;
    } else {
        let mut file = File::open(&requested_page).expect("Unable to open file");
        file.read_to_string(&mut response);
    }

    send_response(reader.into_inner(), &response.to_string(), status);

}

fn send_response(mut stream: TcpStream, res :&str, status :u32){
    let response = format!("{}{}{}{}","HTTP/1.1 ",status," OK\n\n",res);
    stream.write_all(response.as_bytes()).unwrap();
}


texts: Listing employees and their project tasks

texts:
My database (SQL Server 2008) looks like this:

  People 1 -- * TaskPersons * -- 1 Tasks * -- 1 Project

The GROUP BY part of the query is quite long, all because of the COUNT aggregate.  This seems to perform reasonably well.  I would like to know if there is a more concise way of writing this.

use Projects
SELECT COUNT(t.id), ppl.Name, ppl.Birthdate, ppl.Title, ppl.Role, ppl.Status, ppl.Warehouse, ppl.StartDate, ppl.SalaryBand, ppl.Salary,p.Title FROM People ppl
JOIN TaskPersons tp On tp.PersonId = ppl.Id
JOIN Tasks t ON t.Id = tp.TaskId
JOIN Projects p ON p.Id = t.ProjectId
GROUP BY ppl.Name, ppl.Name, ppl.Birthdate, ppl.Title, ppl.Role, ppl.Status, ppl.Warehouse, ppl.StartDate, ppl.SalaryBand, ppl.Salary, p.Title


texts:
I'm trying to develop a base for a blog using some of the new tags introduced in HTML5 and I want to not only make sure I'm using them correctly, but my code is also semantic.

Here is just the 'sample' document.

<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>page title</title>

        <hgroup>

Blog title

Blog tagline goes here

        </hgroup>

Top Link

Top Link

Top Link

sidebar link

sidebar link

sidebar link

Article Header

Section header

Article section content

Section header

Article section content

Section header

Article section content

            posted by user on <time datetime="2012-01-01T00:00+00:00">January 1st, 2012. 12:00pm</time>

Article Header

Section header

Article section content

            posted by user on <time datetime="2012-01-01T00:00+00:00">January 1st, 2012. 12:00pm</time>

Article Header

Section header

Article section content

            posted by user on <time datetime="2012-01-01T00:00+00:00">January 1st, 2012. 12:00pm</time>

    Page footer.

Can anyone see any misuse of the new tags or any better - cleaner way to write this?


texts:
I know there are thousands of posts and questions around the topic of Float Discrepancy. And this is not really a question but a discussion for it.

After sitting repeatedly in front of the same problem, I made the following class to handle it once and for all of our projects.  The direct value comparison is from the book The Art of Computer Programming by Donald E. Knuth. I just changed to unitys Mathf functionality.

So what is your take on the problem? Anything to add, something wrong?

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

public static class FloatDiscrepancy {
  public static float Accuracy = 0.00001f;

  public static float SqrAccuracy {
    get {
     return Accuracy * Accuracy;
    }
    private set { }
  }

  public static bool V4Equal(Vector4 a, Vector4 b){
    return Vector4.SqrMagnitude(a - b) < SqrAccuracy;
  }

  public static bool V3Equal(Vector3 a, Vector3 b){
    return Vector3.SqrMagnitude(a - b) < SqrAccuracy;
  }

  public static bool V2Equal (Vector2 a, Vector2 b){
    return Vector2.SqrMagnitude (a - b) < SqrAccuracy;
  }

  public static bool QuaternionEqual(Quaternion a, Quaternion b){
    return Quaternion.Angle (a, b) < Accuracy;
  }

  //Took the following from literature: The Art of Computer Programming by Donald E. Knuth
  public static bool approximatelyEqual(float a, float b){
    return Mathf.Abs(a - b) <= ( (Mathf.Abs(a) < Mathf.Abs(b) ? Mathf.Abs(b) : Mathf.Abs(a)) * Accuracy);
  }

  public static bool essentiallyEqual(float a, float b){
    return Mathf.Abs(a - b) <= ( (Mathf.Abs(a) > Mathf.Abs(b) ? Mathf.Abs(b) : Mathf.Abs(a)) * Accuracy);
  }

  public static bool definitelyGreaterThan(float a, float b){
    return (a - b) > ( (Mathf.Abs(a) < Mathf.Abs(b) ? Mathf.Abs(b) : Mathf.Abs(a)) * Accuracy);
  }

  public static bool definitelyLessThan(float a, float b){
    return (b - a) > ( (Mathf.Abs(a) < Mathf.Abs(b) ? Mathf.Abs(b) : Mathf.Abs(a)) * Accuracy);
  }
}