texts:
Codeforces problem 831A says:

Array of integers is unimodal, if:

it is strictly increasing in the beginning;
after that it is constant;
after that it is strictly decreasing.

The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.
For example, the following three arrays are unimodal: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7], but the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6].
Write a program that checks if an array is unimodal.

I solved this using two methods in python3.5.
I was expecting method 2 to be faster than method 1 but auto-grader showed the opposite.
So, I wanted to know the reason that what makes the difference here?
Method 1
a, lst = int(input()), input().split()

lst = [int(ch) for ch in lst]

def f(m, n, flag):
    if flag == 1:
        return m < n
    elif flag == 2:
        return m == n
    else:
        return m > n

def is_modal(a, lst):
    flag = 1
    for i in range(1, a):
        if f(lst[i - 1], lst[i], flag):
            continue
        else:
            if flag == 3:
                return "NO"
            flag += 1
            if f(lst[i - 1], lst[i], flag):
                continue
            else:
                if flag == 3:
                    return "NO"
                flag += 1
                if f(lst[i - 1], lst[i], flag):
                    continue
                else:
                    return "NO"
    return "YES"

print(is_modal(a, lst))

It seems to be overly complicated to me, at first I solved it in this way but I did not like it so I tried another way, hence came at method 2.
Method 2
a, lst = int(input()), input().split()
lst = [int(ch) for ch in lst]

def is_modal(a, lst):
    i = 1
    for i in range(i, a):
        if not (lst[i - 1] < lst[i]):
            break
    else:
        return "YES"

    for i in range(i, a):
        if not (lst[i - 1] == lst[i]):
            break
    else:
        return "YES"

    for i in range(i, a):
        if not (lst[i - 1] > lst[i]):
            return "NO"
    else:
        return "YES"

print(is_modal(a, lst))

It looks cleaner and simpler but still, it came out to be slower one.
And apart from comparing these codes, any other suggestions are also welcome.


texts: Precise timing event dispatching in Java

texts:
I have coded a tool to produce precise timing events in Java. You set a value in BPM, and you receive events in your listener at the most precise timing it possibly can be with Java.
It is basic. A thread, a loop, read the bpm value, invokes the listener (lambda), compute the time to sleep to match the bpm requested, and go on.
To achieve high precision, I sleep a bit less than calculated, and then have a noop loop that does the fine grain waiting.
It works well enough for my needs (less than 0.01BPM of error more than 95% of the time), but I was curious on how I could enhance it. Specificaly :

reduce the cpu usage
reduce the memory footprint
any coding that may permit to reduce the tolerance of the unit tests (see MAX_ERRORS_RATE_ALLOWED and BPM_TOLERANCE) without generating assertion errors
more or less any comment that is relevant to the context

The full project (maven) with very few dependencies is here: https://github.com/sebpiller/metronom
Here is the loop doing the computation:
    // https://github.com/sebpiller/metronom/blob/develop/src/main/java/ch/sebpiller/tictac/TicTac.java
    private void loopUntilStopped() {
        long n;
        int i=0;
        while (!stopped) {
            // ok, then tick and wait exactly the correct amount of time
            n = System.nanoTime(); // memorize last boom

            ///// Notify of tick
            ticTacListener.beat(i++ % 4 != 0, bpm);

            // next loop bpm
            bpm = bpmSource.getBpm();

            if (bpm <= 0) {
                // shutdown as soon as the bpm return 0
                stopped = true;
            } else {
                // compute next tick nanos:
                long nanosBetweenTicks = (long) (60_000_000_000d / bpm);

                /// How much time did we need to sleep until next boom
                long sleepNanos = n + nanosBetweenTicks - System.nanoTime() - __JAVA_CORRECTION_NANOS;

                if (sleepNanos < 0) {
                    LOG.warn("missed tic! ({}ns)", sleepNanos);
                    i++; // erf... let's hope we miss only one tick
                } else {
                    sleepInterrupted(sleepNanos / 1_000_000, (int) (sleepNanos % 1_000_000));

                    /* Just in  case this lady was really early this time...
                       fine tuning of the slept time: just loop doing nothing until we are close from the goal */
                    // this is where all the precision is really obtained... this wonderful, but empty loop !
                    while(System.nanoTime()<n + nanosBetweenTicks) /* no body here! */;
                }
            }
        }

A parameterized unit test checks the precision of the implementation here, and run the test with various tempo: https://github.com/sebpiller/metronom/blob/develop/src/test/java/ch/sebpiller/tictac/TicTacTest.java (the test should take about 10 minutes to complete in his current form)
Bonus: any specific advice regarding the execution of this code on an ARM32v7 board (RPi4)
Thank you in advance !


texts: Variadic function to find the first matching (string) argument in a larger array

texts:
Playing around with parsing a data buffer I wrote a small search function to find the first complete match out of a set of (string) arguments.

The (simplified) buffer class with the find function:

// buffer_simple.hpp
#pragma once

#include <cstddef>
#include <utility>

template <typename T, size_t S>
class buffer {
public:
    constexpr buffer() {}
    template <size_t Si>
    constexpr buffer(const T (&arr)[Si]) {
        for (size_t i = 0, l = (S < Si ? S : Si); i < l; ++i) {
            values[i] = arr[i];
        }
    }

    /**
     * Find the first matching array in a larger array and return the argument index and buffer end index of the match.
     * @param   str One or many strings to search for
     * @returns std::pair<argument index, end of match index in buffer>
     */
    template <size_t... SS>
    constexpr std::pair<int, size_t> find_first(const T (&...str)[SS]) const {
        size_t matching[] { (SS - 1)... }; // Amount of remaining 'characters to match'
        for (size_t i = 0; i < S; ++i) { // Loop over the dataset
            int mi = 0;
            ((matching[mi++] = (str[(SS - 1) - matching[mi]] == values[i]) ? (matching[mi] - 1) : ((str[0] == values[i]) ? (SS - 2) : (SS - 1) )), ...); // Nasty pseudo loop for width first search
            for (mi = 0; mi < sizeof...(SS); ++mi) { // See if we have any full matches
                if (matching[mi] == 0) return { mi, i };
            }
        }
        return { -1, 0 };
    }

    constexpr T& operator[](const size_t i) { return values[i]; }
    constexpr const T& operator[](const size_t i) const { return values[i]; }
private:
    T values[S] {0};
};

An example use case:

#include <iostream>
#include "buffer_simple.hpp"

buffer<char, 256> b { "find mefind me:gehoehgioewghowieanother string:" };

int main () {
    const auto result = b.find_first("find me:", "bla", "another string:");
    // switch (result.first) {
    // case 0:
    //     break;
    // case 1:
    //     break;
    // case 2:
    //     break;
    // }
    std::cout << "Result index: " << result.first << ", offset: " << result.second << std::endl;
}

This will return:

Result index: 0, offset: 14

Despite the extremely nasty fold expression this actually works. During runtime that is. As a test I tried declaring the buffer and search result constexpr and things blew up with GCC reporting an Array out of bounds error. I'm curious to see which other pitfalls might be lurking.


texts: Symfony controller that registers a user via HTTP-POST

texts:
This is the code I have written for one of my API routes. I feel like my controller is too big and the function does too much. What can I do to make my adhere to SOLID principles and be more maintainable/readable?

/**
 * @Route("/registration", name="registration")
 * @Method({"POST"})
 * @throws UniqueConstraintViolationException
 * @param Request $request
 * @return JsonResponse
 */
public function registrationAction(Request $request, UserPasswordEncoderInterface $encoder)
{
    // Build base response
    $response = [
        "success"   => false,
        "message"   => "",
        "user_id"   => null,
        "errors"    => []
    ];

    // Put blanks for keys not present in the request
    // This is so we can validate this using Symfony's validator class
    foreach(self::REQUIRED_KEYS as $key) {
        if (!array_key_exists($key, $request->request->all())) {
            $request->request->set($key, "");
        }
    }

    // Get validator and build array of constraints
    $validator = Validation::createValidator();
    $constraint = new Assert\Collection([
        "username"  => new Assert\NotBlank(['message' => "Username is required."]),
        "email"     => [
            new Assert\Email(["message" => "Email must be a valid email address."]),
            new Assert\NotBlank(["message" => "Email is required."])
        ],
        "address1"  => new Assert\NotBlank(['message' => "Address1 is required."]),
        "city"      => new Assert\NotBlank(['message' => "City is required."]),
        "state"     => new Assert\NotBlank(['message' => "State is required."]),
        "zip"       => new Assert\NotBlank(['message' => "Zip is required."]),
    ]);
    $constraint->allowExtraFields = true;

    $errors = $validator->validate($request->request->all(), $constraint);

    // If there are errors, return the errors as a response
    // If there are no errors, register the user and return the ID
    if (count($errors) > 0) {
        foreach($errors as $e) { $response['errors'][] = $e->getMessage(); }
        $response['message'] = "Submitted user failed validation.";
    } else {
        $user = new User($request->request->all());
        $encodedPassword = $encoder->encodePassword($user, 'password');
        $user->setPassword($encodedPassword);

        $em = $this->getDoctrine()->getManager();
        try {
            $user->setEnabled(true);
            $em->persist($user);
            $em->flush();
            $response['success'] = true;
            $response['user_id'] = $user->getId();
        } catch (UniqueConstraintViolationException $e) {
            preg_match('/(?<=Duplicate entry \')[^\']*/', $e->getMessage(), $matches);
            $response['message'] = "Unique constraint violation exception";
            $response['errors'][] = sprintf('%s already exists in the database.', $matches[0]);
        }
    }

    return new JsonResponse($response);
}

My initial hunch is that I should put this into a service and break it up. But it seems like I would just be copying and pasting this code into class.


texts: Calculate the first passage time of a sequence consisting of prices

texts:
I want to calculate the hitting time of a sequence of prices. I define a log price corridor by for forming a double barrier, up_threshold and down_threshold.
When one of the barriers is touched, I note the time and reset the barriers around the last price

My script looks as follows:
import pandas as pd

def speed(prices: pd.DataFrame, threshold: float=0.05):
   times = []
   up_threshold, down_threshold = threshold, -threshold
   returns = (prices['Price'] / prices['Price'].shift(1)).apply(np.log)
   cum_returns = returns.cumsum(axis=0)
   for cum_return in cum_returns:
      if -threshold < cum_return < threshold:
         # this possibility will probably occur the most frequently
         continue
      elif cum_return > threshold:
         times.append(cum_return)
         up_threshold += threshold
         down_threshold += threshold
      else:
         times.append(cum_return)
         up_threshold -= threshold
         down_threshold -= threshold

if __name__ == '__main__':
    prices = np.random.random_integers(10, 25, 100)
    prices = pd.DataFrame(prices, columns=['Price'])
    speed(prices=prices, threshold=0.05)

How can I improve this script? Is it wise to also use an apply function for the cum_returns-part? The speed of the script is important. Thanks in advance


texts: Finding numbers with odd frequency in an array

texts:
Below is my Code, I want to know ways to improve it.
const findOdd = (A) => {

  newObj={};

  A.filter((cur,index) =>{
    return A.indexOf(cur)===index;
  }).forEach((cur) =>{
    newObj[cur] = 0
    for(let i = 0; i<A.length; i++) if(cur === A[i]) newObj[cur] +=1;
  });

  const keys = Object.keys(newObj)
  key = keys.filter(cur => newObj[cur] % 2 !== 0)

  return parseInt(key[0]);
}

Test Case :
A = [1,1,2,-2,5,2,4,4,-1,-2,5]
Output = -1
Edit : I am trying to create a list of distinct elements at first then add them to an object with key as elements and value as their frequency, then finally finding the keys with odd frequencies.


texts:
I have implemented a simple class for managing in-memory caching. I have written two classes, one for adding a cache and another for getting a cache. Can anyone please review the code for adding a cache?

  class cache_add_manager {
      constructor() {
         this.data_type_memory_size = {
           STRING : 2,
           NUMBER : 8,
           BOOLEAN : 4
       };
      }

get_meta_data_obj_size() {
    let meta_size = this.data_type_memory_size.NUMBER * 4; // For memory_size, usage_count, expiration_time and time_of_caching
    return meta_size;
}
    // This fuction calculates memory used by an object
get_object_size(obj) {
    let memory_size = 0;
    let data_type_memory_size = this.data_type_memory_size;

    if(typeof obj === "number") {
        memory_size += data_type_memory_size.NUMBER;
    }
    else if(typeof obj === "string") {
        memory_size += data_type_memory_size.STRING * obj.length;
    }
    else if(typeof obj === "boolean") {
        memory_size += data_type_memory_size.BOOLEAN;
    }
    else if(typeof obj === "object" && Array.isArray(obj))    {
        obj.forEach((singleObj) => {
            memory_size += get_object_size(singleObj);
        });
    }
    else if(typeof obj === "object" && !Array.isArray(obj))  {
        let keys = Object.keys(obj);
        keys.forEach((key) => {
            memory_size += data_type_memory_size.STRING *
           key.toString().length;
            memory_size += get_object_size(obj[key]);
        });
    }

    memory_size += this.get_meta_data_obj_size();

    return memory_size;
};

/* this function adds value to given key.
   It takes caches and memory as parameters. Caches is existing cache
   object and memory is object containing max memory limit of cache
   and memory used till now
*/
add_cache(key, value, caches, memory) {

    let message = "";

    let memory_limit = memory.memory_limit;
    let memory_used = memory.memory_used;
    try {
        let cache = {};
        if(memory_used > 0 && cache['memory_size'])
            memory_used = memory_used - cache['memory_size'];

        let memory_size = this.get_object_size(value);

        if(memory_size + memory_used > memory_limit) {
            var returned_obj = this.remove_least_used_caches(caches,
            memory_used, memory_limit);
            memory_used = returned_obj.memory_used;
        }

        cache['value'] = value;
        cache['memory_size'] = memory_size;
        cache['usage_count'] = 0;
        cache['time_of_caching'] = new Date().getTime();

        memory_used += memory_size;

        memory.memory_limit = memory_limit;
        memory.memory_used = memory_used;
        caches[key] = cache;

        message = key + " added successfully";
    } catch(e) {
        message = e;
    }

    console.log(message);

    return {
        caches : caches,
        memory : memory
    }
};
/*
    this function removes object from cache in case cache max memory
    size limit is being crossed while adding new key. Least recently
    used approach is followed.
*/
remove_least_used_caches(caches, memory_used, memory_limit) {
    let keys = Object.keys(caches);

    keys.sort((key1, key2) => {
        return caches[key1].usage_count - caches[key2].usage_count;
    });

    keys.forEach((key) => {
        let memory_size = caches[key].memory_size;
        delete caches[key];

        if(memory_size)
            memory_used = memory_used - memory_size;

        if(memory_used < 0)
            memory_used = 0;

        if(memory_used < memory_limit)
            return true;
    });

    return {
        memory_used : memory_used
    };
  }
 }

let cache_add_manager_obj = new cache_add_manager();
/* lets suppose we have data object having all required parameters.*/
let returned_obj = cache_add_manager_obj.add_cache(data.key,
      data.value, data.caches, data.memory);


texts: Simple C++ program that calculates the measures of a sphere

texts:
I have another home work from school and would like to see if I am on the right path to learning C++.

We have to do the calculation of the measures of a sphere. I did it two ways:

Just calculating everything at the main
Using a function

#include "stdafx.h"
#include "iostream"
#include <cmath>

double *calcSphereMesures(double r);

double *calcSphereMesures(double r)
{
const double PI = 3.1416;
double d, area, circumference, volume;
double results[4];

d = 2*r;
circumference = PI * d;
area = (4 * PI * pow(r,2));
volume = (4 * PI * pow(r,3))/3;

results[0] = area;
results[1] = circumference;
results[2] = volume;
results[3] = d;
return results;
}

int main()
{
double r;
std::cout << "Please enter the radius of a circle: ";
std::cin >> r;
double *results = calcSphereMesures(r);

std::cout << "\n**************************************" << "\n"
<< "* Area and Circumference of A Sphere *" << "\n"
<< "**************************************" << "\n"
<< "\nRadius: " << r << "\n"
<< "Diameter: " << results[3] << "\n"
<< "Area: " << results[0] << "\n"
<< "Circumference: " << results[1] << "\n"
<< "Volume: " << results[2];
return 0;
}

I tried to check all the tips that were given to me the last time. Is that still bad code? What can I improve here and remember for future exercises?


texts: A switch case statement that returns a timespan

texts:
I have a switch case statement containing enum values as cases. These enum values are time units. Now I want to generate a timespan by using an enum value and a long value so like this:

2 (long) Minutes (Enum value)
1 (long) Year (Enum value)

... and so on.
This is the switch-case statement:
private const double yearValue = 365.2425;

public TimeSpan ResetTimeSpan
            {
                get
                {
                    switch (ResetTimeUnitEnumValue)
                    {
                        case TimeUnit.Seconds:
                            return new TimeSpan(0,0,0, (int)ResetTime);
                        case TimeUnit.Minutes:
                            return new TimeSpan(0, 0, (int)ResetTime, 0);
                        case TimeUnit.Hours:
                            return new TimeSpan(0, (int)ResetTime, 0);
                        case TimeUnit.Days:
                            return new TimeSpan((int)ResetTime, 0, 0, 0);
                        case TimeUnit.Months:
                            return new TimeSpan((int)(ResetTime * (yearValue / 12)), 0, 0, 0);
                        case TimeUnit.Years:
                            return new TimeSpan((int)(ResetTime * yearValue), 0, 0, 0);
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
            }

But I don't like it and it feels very double. Could anyone review this and refactor it, since I'm not able to see it.


texts:
I am trying to get my dictionary to iterate seven times after the dateTime is found. I want to iterate through the next week of objects in my dictionary pagesInRange. I figured out how to do it, but I am sure this is not good code. I am wondering if someone could point me in the direction of what I can do to improve this code.

I could not figure out how to iterate through the range I want, so instead I iterate through the entire dictionary and have a bunch of it statements to find the values I am looking for. Here is my code. I know I can use a switch statement to improve the code, but I wondering if there is a way given the first value to iterate over the next seven values.

Console.WriteLine("Please enter a date in the following formate MM/DD/YYYY");
string date = Console.ReadLine();
DateTime dt = Convert.ToDateTime(date);
DateTime end1 = dt.AddDays(1);
DateTime end2 = dt.AddDays(2);
DateTime end3 = dt.AddDays(3);
DateTime end4 = dt.AddDays(4);
DateTime end5 = dt.AddDays(5);
DateTime end6 = dt.AddDays(6);

int i = 0;
foreach (var pair in pagesInRange)
{
    if (pair.Key.ToString("d")==date)
    {
        Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
    } else if (pair.Key == end1)
    {
        Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
    }
    else if (pair.Key == end2)
    {
        Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
    }
    else if (pair.Key == end3)
    {
        Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
    }
    else if (pair.Key == end4)
    {
        Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
    }
    else if (pair.Key == end5)
    {
        Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
    }
    else if (pair.Key == end6)
    {
        Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
    }
}


texts: Retrieve index of HTML element within parent

texts:
I have a function I've been using for years that retrieves the index of an HTML element within its parent element, or, if a second argument is passed to it, the index of an HTML element within the collection of elements of the same name in that parent:

var childindex=function(node){
    var index=0;
    while(node.previousSibling){
        if(arguments.length==childindex.length||node.previousSibling.nodeName.toLowerCase()==arguments[1])index++;
        node=node.previousSibling;
    }
    return index;
}

However, in a recent overhaul of my JavaScript library, I went over all these old functions to try to improve upon them and this is what I came up with to replace the above:

let childindex=(node,...selectors)=>
        Array.from(selectors.length?node.parentNode.querySelectorAll(`:scope>${selectors.join(",:scope>")}`):node.parentNode.children).indexOf(node);

I'm pretty happy with the result, especially as it gives me the added ability to get the index of the element within any collection of selectors by passing each selector as a new argument and also ignores text nodes even when no additional arguments are passed to it.

I'm wondering, though, if anyone can see anywhere I can improve on it further, either in efficiency or conciseness of code.

Here's a working example to show it in action:

(()=>{
    let item=document.getElementById("getthis"),
        childindex=(node,...selectors)=>
            Array.from(selectors.length?node.parentNode.querySelectorAll(`:scope>${selectors.join(",:scope>")}`):node.parentNode.children).indexOf(node);

    //Gets index of `item` within all child elements of

    console.log(childindex(item)); // 5
    //Gets index of `item` within all child
 elements of

    console.log(childindex(item,"article")); // 3
    //Gets index of `item` within all child elements of
 with .class
    console.log(childindex(item,".class")); // 2
    //Gets index of `item` within all child
 &  elements of

    console.log(childindex(item,"header","article")); // 4

})();


texts:
I had a somewhat interesting issue.  I had to take an array and turn it into a string with a set of delimiters; then later on take that string and turn it back into an array, splitting at the same delimiters.  The twist was the string could be contain anything (including the delimiters).

I feel like I over-engineered the solution, and am wondering what you guys can come up with as alternatives.

Here is my solution.  escapedImplode turns an array into a string, and escapedExplode turns that string back into its corresponding array.  The testEscapedIE function is a little test scaffolding to see if your solution works.

function escapedImplode ($glue, $array, $escapeChar = '\\')
{
    $array = array_map(function ($item) use ($escapeChar, $glue) {
        $item = str_replace($escapeChar, $escapeChar . $escapeChar, $item);
        $item = str_replace($glue, $escapeChar . $glue, $item);

        return $item;
    }, $array);

    return implode($glue, $array);
}

function escapedExplode ($delimiter, $string, $escapeChar = '\\')
{
    $characters = str_split($string);

    $isEscaped = false;

    $parts = array();
    $buffer = '';

    for ($i = 0; $i < count($characters); $i++)
    {
        $char = $characters[$i];

        // If is escaped, just add to the buffer and continue
        if ($isEscaped)
        {
            $buffer .= $char;
            $isEscaped = false;
            continue;
        }
        // If is a delimiter, which isn't escaped, set state and continue
        else if ($char == $escapeChar)
        {
            $isEscaped = true;
            continue;
        }

        // If not escaped and is the delimiter, break here
        if ($char == $delimiter)
        {
            $parts[] = $buffer;
            $buffer = '';
            continue;
        }

        // Doesn't match another special case, tack onto buffer
        $buffer .= $char;
    }

    // Add whatever is in the buffer to end of parts
    $parts[] = $buffer;

    return $parts;
}

function testEscapedIE ()
{
    $tests = array(
        array('test', 'cool', 'awesome'),
        array('some/thing', 'cool', '/isbrewing/'),
        array('with\\/asdf', '//other//', '\\/collness\\/'),
        array('////','//\\//','\\//\\//\\','\\\\'),
    );

    foreach ($tests as $test)
    {
        $imploded = escapedImplode('/', $test);
        $exploded = escapedExplode('/', $imploded);

        echo 'Testing: ' . implode(', ', $test) . ' -- ';
        echo $imploded . ' -- ';
        echo implode($exploded, ', ') . ': ';

        echo $test === $exploded ? 'Pass' : 'Fail';

        echo "
\n";
    }
}

testEscapedIE();


texts: Creating instances of a logger class for various logging levels

texts:
I provide a class to use but for convenience I want the class to implement some instance methods as static methods. This was fast and concise but it feels smelly, probably because I'm modifying the class after I create an instance of it. Is this ok?

  const logLevel    = !args['v'] || args['v'] === true ? 0 : parseInt(args['v']);
  const chalk       = new Chalk.constructor({enabled: useColor});
  const nameLength  = args['format-name-length'] || 25;

  class Logger{
    constructor(name='', _stdout=stdout, _stderr=stderr){
      this._name = this._getPaddedName(name);
      this._stdout = _stdout;
      this._stderr = _stderr;
      this.error.bind(this);
      this.info.bind(this);
      this.warn.bind(this);
    }
    error(level, ...args){
      if(level <= logLevel){
        this._print(this._stderr, args, 'red', level);
      }
    }
    info(level, ...args){
      if(level <= logLevel){
        this._print(this._stdout, args, 'blue', level);
      }
    }
    warn(level, ...args){
      if(level <= logLevel){
        this._print(this._stderr, args, 'yellow', level);
      }
    }
    _getLogId(color, level){
      return chalk[color](
        moment().format("YYYY:MM:DD h:mm:ss")
        + ` ${this._name}`
        + ` [${level}]: `
      );
    }
    _getPaddedName(name){
      let nameArray = name.split('')
        .slice(0, nameLength);
      if(nameLength > name.length){
        nameArray = nameArray
          .concat(new Array(nameLength - name.length).fill(null));
      }
      let ellipsis = nameArray.slice(nameLength - 3)
        .reduce((prev, next)=>!!(prev || next), false);
      return nameArray
        .slice(0, nameLength - 3)
        .map(char=>char || '-')
        .concat(ellipsis ? ['.', '.', '.'] : ['-', '-', '-'])
        .join('');
    }
    _format(arg, color, level){
      let logId = this._getLogId(color, level);
      return util.format(arg)
        .replace(/^/, logId)
        .replace(/(\r?\n)/g, `\n${logId}`)
        .replace(/((?:\r?\n)?$)/, '\n');
    }
    _print(stream, args, color, level){
      args.forEach(arg=>{
        if(arg !== ''){
          stream.write(this._format(arg, color, level));
        }
      });
    }
  }

  let defaultLogger = new Logger('logger');

  Logger.error = defaultLogger.error.bind(defaultLogger);
  Logger.info = defaultLogger.info.bind(defaultLogger);
  Logger.warn = defaultLogger.warn.bind(defaultLogger);

  return Logger;


texts:
I am quite new to Go but have found it to be very useful for my use case (game server).

I have a routine that encrypts/decrypts the game packets which was written in C++ which can be seen here and here as DecryptDirect.

My current Go code:

type Crypto struct {
    nkey         [256]byte
    buf          [256]byte
    i, j, iR, jR byte
    prev         byte
    iRounds      int
}

func (c *Crypto) setup() {
    c.iR, c.jR = 0, 0

    k := len(c.nkey)

    for i := 0; i < 256; i++ {
        c.buf[i] = byte(i)
    }
    var j byte = 0
    for i := 0; i < 256; i++ {
        j += byte(c.buf[i]) + c.nkey[i%k]
        c.buf[i], c.buf[j] = c.buf[j], c.buf[i]
    }
}

func (c *Crypto) reset() {
    c.setup()
    c.prev = c.getRandom()
}

func (c *Crypto) getRandom() byte {
    c.iR = (c.iR + 1) & 0xFF
    c.jR = (c.jR + c.buf[c.iR]) & 0xFF
    c.buf[c.iR], c.buf[c.jR] = c.buf[c.jR], c.buf[c.iR]

    result := c.buf[(c.buf[c.iR]+c.buf[c.jR])&0xFF]
    return result
}

func (c *Crypto) Init(a int, b int, rounds int) {
    secret := fmt.Sprintf("%05d_%05d_%05d", a+10, b+10, a+b)
    copy(c.nkey[:], secret)
    c.iRounds = rounds
    c.reset()
}

func (c *Crypto) Decrypt(dst, src []byte) {
    var i, j int

    src_size := len(src)

    var plain byte
    var seqX2, seqM2 [2]byte
    // to be improved
    seqX := make([]byte, src_size)
    seqM := make([]byte, src_size)

    for i = 0; i < src_size; i++ {
        xiRounds := 0

        for j = 0; j < c.iRounds; j++ {
            seqX2[xiRounds] = c.getRandom()
            seqM2[xiRounds] = c.getRandom()
            xiRounds++
        }

        // last m_iRounds-1 rounds
        plain = src[i]
        seqX[i] = seqX2[c.iRounds-1]
        seqM[i] = seqM2[c.iRounds-1]

        for j = c.iRounds - 1; j > 0; j-- {
            if seqM[i] <= plain {
                plain -= seqM[i]
            } else {
                seqM[i] = ^seqM[i] & 0xFF
                seqM[i]++
                plain += seqM[i]
            }
            plain ^= seqX[i]
        }
        // first round
        if seqM2[0] <= plain {
            plain -= seqM2[0]
        } else {
            seqM2[0] = ^seqM2[0] & 0xFF
            seqM2[0]++
            plain += seqM2[0]
        }
        plain ^= c.prev ^ seqX2[0]
        dst[i] = plain
        c.prev ^= plain
    }

    c.reset()
}

Any improvements made here can speed up the server much because the Decrypt function gets called quite a lot. Any ideas and examples for improvements would be much appreciated.


texts: Error handling to restart Word from Excel inside a loop

texts:
I'm often opening, from Excel, all Word documents inside a folder.

And sometimes during the treatments, Word crash without throwing an error.

So I've added a bit of error handling to restart Word and reopen the doc I was working on.

I'm just wondering if I'm doing it properly, or if I should go further like :

Test the error number
If it's 462 : The remote server machine does not exist or is unavailable, go to RestartWord
If it's something else, show the error message

It may also not be only Error 462, but I don't have any other examples for this.

My code :

Private Sub Update_Word_DocMs_In_Folder(ByVal FolderToScan As String, _
                                            ByVal PathTxtWithInfo As String)
Dim oW As Object, NewFile As String
'''Boolean to detect if it was the initial launch
Dim NormalWordLaunch As Boolean
NormalWordLaunch = True
Set oW = OpenOrReopen("Word.Application", NormalWordLaunch)

On Error GoTo RestartWord
    NewFile = Dir(FolderToScan & "*.docm")
    Do While NewFile <> vbNullString
'''ErrHdl: Jump back here after re-creating a Word's instance
ReOpenWordFile:
        Call OpenWordDocAndApplyTreatment(oW, FolderToScan & NewFile, PathTxtWithInfo)
        NewFile = Dir()
    Loop
    oW.Quit
On Error GoTo 0

Set oW = Nothing
Set oDoc = Nothing
Exit Sub
RestartWord:
    If Err.Number <> 462 Then
        MsgBox Err.Number & vbCrLf & Err.Description, vbCritical + vbOKOnly, "Error not handled"
        DoEvents
        Resume
    Else
        Set oW = OpenOrReopen("Word.Application", NormalWordLaunch)
        '''ErrHdl: If this isn't the initial launch go back to the loop
        If Not NormalWordLaunch Then Resume ReOpenWordFile
    End If
End Sub

Function to handle creating an app instance :

Function OpenOrReopen(ByVal ClassName As String, NormalLaunch As Boolean) As Object
    Set OpenOrReopen = Nothing
    On Error Resume Next
    '''Check if there is already an instance
    Set OpenOrReopen = VBA.GetObject(, ClassName)
    On Error GoTo 0

    If OpenOrReopen Is Nothing Then
        '''If there isn't any instance, create one
        Set OpenOrReopen = VBA.CreateObject(ClassName)
    Else
        '''If detected instance is visible, create a new one
        If OpenOrReopen.Visible Then Set OpenOrReopen = VBA.CreateObject(ClassName)
    End If
    '''Set instance to be hidden
    OpenOrReopen.Visible = False
    OpenOrReopen.Options.UpdateLinksAtOpen = False

    '''For ErrHdl: Change boolean the 1st time
    If NormalLaunch Then NormalLaunch = False
End Function

Code for treatment :

Sub OpenWordDocAndApplyTreatment(WordApp As Object, _
                                 ByVal FileFullName As String, _
                                 ByVal PathTxtWithInfo As String)
    Dim oDoc As Object
    Set oDoc = WordApp.Documents.Open(FileFullName)
    With oDoc
        Do While .ReadOnly
            DoEvents
        Loop
        '''Some treatment to update doc's properties
        WordApp.Run "Properties_Updating.Properties_Update", PathTxtWithInfo
        DoEvents
        .Save
        .Close
    End With 'oDoc
End Sub


texts:
Trying to find the median of two sorted arrays in O(log(m+n)) or better. I believe this is O(log(m+n) or O(log(m)) or O(n).

var findMedianSortedArrays = function(nums1, nums2) {
  let ar = []
  let len = nums1.length + nums2.length
  let half;

  if (len % 2 === 0) {
    half = len / 2
  } else {
    half = Math.ceil(len / 2)
  }
  for (let i = 0, r1 = 0, r2 = 0; i <= len; i++) {
    if (r1 >= nums1.length || nums1[r1] > nums2[r2]) ar[i] = nums2[r2++]
    else ar[i] = nums1[r1++]
    if (!nums1[i] && nums1.length === r1) {
      ar = ar.concat(nums2.slice(r2))
      return median(ar, len)
    }
    if (!nums2[i] && nums2.length === r2) {
      ar = ar.concat(nums1.slice(r1))
      return median(ar, len)
    }
    if (half === i) {
      return median(ar, len)
    }
  }

  function median(arr, len) {
    if (len % 2 === 0) {
      let half = len / 2
      return median = (arr[half - 1] + arr[half]) / 2
    } else {
      let half = Math.ceil(len / 2)
      return median = arr[half - 1]
    }
  }
}

console.log(findMedianSortedArrays([1, 4], [2, 3, 5, 6]))


texts: 1-D intersection of lines given begin and end points

texts:
I have a fairly basic question here: I want to find if two lines on a 1-D plane intersect. I know of two simple ways to solve this, but I wanted to know if Python has a more elegant way to solve this.

x = [1, 10] # 1 = begin, 10 = end
y = [15, 20]
z = [5, 12]

#Method 1: Works. Is quick. Lots of typing.
def is_intersect_1(a, b):
    bool_check = False
    if a[0] <= b[0] <= a[1] or \
    a[0] <= b[1] <= a[1] or \
    b[0] <= a[0] <= b[1] or \
    b[0] <= a[1] <= b[1]:
        bool_check = True
    return bool_check

is_intersect_1(x,y) # False
is_intersect_1(x,z) # True

#Method 2: Quicker to write. Simpler to read. Uses more memory and is slower.

def is_intersect_2(a, b):
    bool_check = False
    if set(range(a[0], a[1]+1)).intersection(set(range(b[0], b[1])):
        bool_check = True
    return bool_check

is_intersect_2(x,y) # False
is_intersect_2(x,z) # True


texts: When one property is calculated from another

texts:
I've got a class with a property TotalCost, which is calculated by some simple math of two other properties, CostOfFood and NumberOfPeople.  The code works the way I want it to, but I was wondering if this is a satisfactory method in the long run of application development, a bad idea to have one property that depends on another all together (I'm pretty sure this is the case, but sometimes it makes sense to), or if the informed reader would deem it acceptable.  Helpful hints are in the comments.

class DinnerParty
{
    private int numberOfPeople;
    public int NumberOfPeople
    {
        get { return numberOfPeople; }
        set
        {
            numberOfPeople = value;
            //TotalCost property is updated when more people are added to the party
            TotalCost =CalculateFoodCost(value);
        }
    }
    private decimal totalCost;

    public decimal TotalCost
    {

        get { return totalCost; }
        private set
        {
            totalCost = value;
        }
    }

    private decimal costOfFood;
    public decimal CostOfFood
    {
        get { return costOfFood; }
        set
        {
            costOfFood = value;
            //TotalCost property is updated when CostOfFood changes
            //directly below line was my initial idea
            //TotalCost = value * NumberOfPeople was my initial thought
            //before overloading the CalculateFoodCost method

            //this calls the CalculateFoodCost version that takes a decimal
            TotalCost = CalculateFoodCost(value);
        }
    }
    private decimal CalculateFoodCost(int costOfFood)
    {
        //the int coming in as a parameter is the 'value' of the NumberOfPeople property
        return this.costOfFood * NumberOfPeople;

    }
    private decimal CalculateFoodCost(decimal costOfFood)
    {
        return this.costOfFood * NumberOfPeople;
    }

    public DinnerParty()
    {
        //so food cost is never 0
        CostOfFood = 10;
    }
}

Testing

DinnerParty d = new DinnerParty();
d.NumberOfPeople = 1;
Console.WriteLine(d.TotalCost);//output = 10
d.CostOfFood = 2;
Console.WriteLine(d.TotalCost);//CostOfFood changed, output =2
d.NumberOfPeople = 2;
Console.WriteLine(d.TotalCost);//output=4;
d.CostOfFood = 3;
Console.WriteLine(d.TotalCost); //output =6


texts: String Calculator kata in JavaScript using TDD

texts:
I'm looking for some advice in TDD for my implementation of the String Calculator kata described by Roy Osherov. Any advice regarding refactoring, structuring and polishing of the code is welcome. Still a novice at JS, so please go easy on me.

I have implemented the first 5 rules excluding the delimiter rule.
I intend to do this kata everyday as a practice to get better.

The rules for the kata can be found here :
http://osherove.com/tdd-kata-1/

Tests :

// StringCalculator-spec.js
describe("String Calculator",  function(){
    var calculator;

    beforeEach(function() {
      calculator = new StringCalculator();
    });

    it("should return zero when '' is passed", function(){
      expect(calculator.add('')).toEqual(0);
    });

    it("should return the number itself when a single number is passed", function(){
      expect(calculator.add('1')).toEqual(1);
    });

    it("should return the sum of the numbers if two are given", function(){
      expect(calculator.add('1,2')).toEqual(3);
    });

    it("should return the sum of an unknown amount of numbers", function(){
      // creates a random array
      randomArray = (length, max) => [...new Array(length)]
      .map(() => Math.round(Math.random() * max));
      // creates a random number between 1 and 100
      randy = Math.floor((Math.random() * 100) + 1);
      res = randomArray(randy,randy);
      // sums up an array
      sum = res.reduce((pv, cv) => pv+cv, 0);
      // converts the array to a string
      arg = res.join();
      expect(calculator.add(arg)).toEqual(sum);
    });

    it("should allow \\n in between the input number string", function(){
      expect(calculator.add("1\n2,3")).toEqual(6);
    });

    it("should not allow negative numbers", function(){
      expect( function(){ calculator.add("-1,2,3"); } ).toThrow(new Error("negatives not allowed"));
    });
  });

Code :

// StringCalculator.js
function StringCalculator(){
    }
    StringCalculator.prototype.add = function(string_numbers) {
      this.number = string_numbers;
      if (this.number.includes('-')) {
        throw new Error('negatives not allowed');
      }
      // replaces \n with ,
      numbers = this.number.replace(/(\r\n|\n|\r)/gm,",");
      if (numbers == '') {
        return 0;
      } else if(numbers.length === 1) {
        return (parseInt(numbers));
      } else {
        res = numbers.split(',');
        var total = 0;
        var arrayLength = res.length;
          for (var i = 0; i < res.length; i++) {
            total = total + parseInt(res[i]);
          }
          return total;
      }
    };


texts:
guys.
The code below is spring security web adapter. I do not like configure(HttpSecurity) method that generates security confirmation policy.
Any ideas to do it more readable and clear?

/**
* Spring security configuration
*
* @author Eugene Ustimenko
* @date Nov 5, 2014
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier ("loginService")
private ILoginService loginService;

@Override
protected void configure (AuthenticationManagerBuilder auth)
  throws Exception {

auth.userDetailsService(loginService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure (HttpSecurity http) throws Exception {

final RequestMatcher csrfRequestMatcher = new RequestMatcher() {

  private RegexRequestMatcher requestMatcher = new RegexRequestMatcher("/login/*", null);

  @Override
  public boolean matches (HttpServletRequest request) {

    return requestMatcher.matches(request);
  }
};
http.csrf()
    .requireCsrfProtectionMatcher(csrfRequestMatcher)
    .and().authorizeRequests().antMatchers("/admin/**").access("hasRole('ADMIN')")
    .and()
    .formLogin().loginPage("/login").failureUrl("/login?error")
    .usernameParameter("username").passwordParameter("password")
    .and()
    .logout().logoutSuccessUrl("/")
    .and()
    .csrf()
    .and()
    .exceptionHandling().accessDeniedPage("/403");
}

@Bean
public PasswordEncoder passwordEncoder () {

  final PasswordEncoder encoder = new BCryptPasswordEncoder();
  return encoder;
}

@Bean (name = "auth")
@Override
public AuthenticationManager authenticationManagerBean () throws Exception {

  return super.authenticationManagerBean();
}
}


texts: Space efficient revision history storage with diffs

texts:
I've written a tool to store a files history more efficiently by only generating diffs and storing them whereas whole file would otherwise have to be stored. I would like to to hear about ways to improve readability and otherwise make this code more "ruby" or suggestions for test-cases to improve robustness. I also feel like the swap case could be expressed as a insertion/deletion combinations, but maybe it's more readable to leave it as is. Here is the Diff class:

class Diff
  attr_reader :a, :b, :diff

  def initialize(a,b)
    @a = a
    @b = b
    @diff = {} # {line_number => {type: +/-/~, content: text}}
    a = a.split("");
    b = b.split("");
    a_pos = 0
    b_pos = 0
    while (a+b).length > 0
      if a[0] == b[0]
        a.shift
        a_pos += 1
        b.shift
      else
        i = 1
        loop do
          if a[i] == b[0]
            @diff[a_pos] = {type: "-", content: a[0..i-1].join}
            a = a[i..-1]
            a_pos += a[0..i].length
            break
          elsif b[i] == a[0]
            @diff[a_pos] = {type: "+", content: b[0..i-1].join}
            b = b[i..-1]
            break
          elsif a[i] == b[i]
            a_pos += i
            @diff[a_pos] = {type: "~", content: [a.shift(i), b.shift(i)]}
          end
          i = i+1
          break if a[i] == b[0] || b[i] == a[0] || a[i]==b[i]
        end
      end
      if a.empty? && !b.empty?
        @diff[a_pos] = {type: "+", content: b.join}
        break
      elsif b.empty? && !a.empty?
        @diff[a_pos] = {type: "-", content: a.join}
        break
      end
    end
  end

  def self.apply(a, diff_hash)
    a = a.split("")
    Hash[diff_hash.diff.sort.reverse].each do |line, diff|
      case diff[:type]
      when "-"
        a = a[0..line-1]+a[line+diff[:content].length..-1]
      when "+"
        a.insert(line-1, diff[:content]) # line-2
      when "~"
        a = a[0..line-2]+a[line+diff[:content][0].length-1..-1]
        a.insert(line-1, diff[:content][1])
      end
    end
    return a.join
  end
end


texts:
Write a method equals that takes as parameters two stacks of integers
  and returns true if the two stacks are equal and that returns false
  otherwise. To be considered equal, the two stacks would have to store
  the same sequence of integer values in the same order. Your method is
  to examine the two stacks but must return them to their original state
  before terminating. You may use one stack as auxiliary storage.

I'm pretty new to stacks and queues, and data structures in general. I'd like to know if there are other ways I can do this that are easier or better for when I'm dealing with stacks in the future. Also, is my code readable? Does everything "make sense"? And can my code be easily optimized?

public boolean equals(Stack<Integer> s1, Stack<Integer> s2) {
    Queue<Integer> q1 = new LinkedList<Integer>();
    Queue<Integer> q2 = new LinkedList<Integer>();
    boolean equal = true;

    while (!s1.isEmpty() && !s2.isEmpty()) {
        int firstNum = s1.pop();
        int secondNum = s2.pop();
        q1.offer(firstNum);
        q2.offer(secondNum);
        if (firstNum != secondNum) {
            equal = false;
        }
    }

    // used to preserve stack structure
    if (s1.isEmpty() && !s2.isEmpty()) {
        while(!s2.isEmpty()) {
            q2.offer(s2.pop());
        }
        equal = false;
    }

    if (s2.isEmpty() && !s1.isEmpty()) {
        while(!s1.isEmpty()) {
            q1.offer(s1.pop());
        }
        equal = false;
    }

    // add back to stack using s -> q -> s
    // for both stacks
    while (!q1.isEmpty()) {
        s1.push(q1.remove());
    }
    while (!s1.isEmpty()) {
        q1.offer(s1.pop());
    }
    while (!q1.isEmpty()) {
        s1.push(q1.remove());
    }

    while (!q2.isEmpty()) {
        s2.push(q2.remove());
    }
    while (!s2.isEmpty()) {
        q2.offer(s2.pop());
    }
    while (!q2.isEmpty()) {
        s2.push(q2.remove());
    }

    return equal;
}


texts: Codechef COOKMACH solution, exceeding time limit

texts:
I'm stuck on Codechef problem COOKMACH, which asks for the minimum number of operations needed to transform integer A into integer B, where each operation can be either doubling the number or halving it (rounding down). 1 ≤ A ≤ 107 and  1 ≤ B ≤ 107, and B is an integer power of 2.

In eclipse, the code runs in time, but when it is run in Codechef, the time limit is exceeded.

Is there anything that can be improved in code below?

BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(b.readLine());// no. of test cases
while(T>0){
    StringTokenizer s=new StringTokenizer(b.readLine());
    int count=0;
    int A =Integer.parseInt(s.nextToken());
    int B=Integer.parseInt(s.nextToken());
    if(A%2!=0){
        if(A<B){
            while(A!=1){
                A=(A-1)/2;
                count=A;
            }
            while(A<B){
                A=A*2;
                count++;
            }
        }
        else{
            while(A!=B){
                A=(A-1)/2;
                count++;
            }
        }
    }
    else{
        if(A<B){
            while(A!=B){
                A=A*2;
                count++;
            }
        }
        else{
            while(A!=B){
                A=A/2;
                count++;
            }
        }
    }
    T--;
}
}
}


texts: What is a better approach for operating on an arbitrary map value in Scala?

texts:
Coming from an imperative background, I have written the following code in Scala.  I need to attempt to find a value in a map.  If the value exists, I need to pass the value to another function and return the result, otherwise I need to return None.

def foo(index: Int): Option[FooBar] = {
  val mylookup: Map[Int, String] = this.generateMap()
  var out: Option[String] = None

  if (mylookup.containsKey(index)) {
    out = Some(mylookup(index))
  } else if (mylookup.containsKey("static_value")) {
    out = Some(mylookup("static_value"))
  }

  if (!out.getOrElse("").isEmpty) {
    return this.doSomeCall(out.get).makeFooBar()
  } else {
    return None
  }
}

I don't feel like this is the best way to accomplish this in Scala.  Any ideas on how to approach this using the idiomatic nature of the language?


texts: Better way to un-define a set of defines based on version numbers in C++?

texts:
In a header I have something like:

#define OPENGL_TARGET_VERSION_MAJOR 4
#define OPENGL_TARGET_VERSION_MINOR 0

#define OPENGL_TARGET_VERSION ( OPENGL_TARGET_VERSION_MAJOR * 10 \
                              + OPENGL_TARGET_VERSION_MINOR * 1 )

And then a lot of checks like:

#if OPENGL_TARGET_VERSION < 44
    #ifdef GL_VERSION_4_4
        #undef GL_VERSION_4_4
    #endif
#endif

#if OPENGL_TARGET_VERSION < 43
    #ifdef GL_VERSION_4_3
        #undef GL_VERSION_4_3
    #endif
#endif

#if OPENGL_TARGET_VERSION < 42
    #ifdef GL_VERSION_4_2
        #undef GL_VERSION_4_2
    #endif
#endif

#if OPENGL_TARGET_VERSION < 41
    #ifdef GL_VERSION_4_1
        #undef GL_VERSION_4_1
    #endif
#endif

...

Is there any way I could avoid repeating these checks for every version-number?


texts:
I have a task that I am trying to complete and would appreciate direction, to know which is the most efficient path to take for future requirements.

Use Case: A background process that determines if a specific database is broken. This task will be run every two minutes as we must know ASAP if there is a problem with the database.

My Solution: Opening a connection with said database, if the conenction is refused - an email is then sent notifying the appropriate individuals.

Here is the method I built to determine the DB state:

    public bool DatabaseConnection()
    {
        bool statusUp = true;

        using (var databaseConnection = new SqlConnection(ConfigData.ConnectionStrings.DatabaseConnectionString))
        {
            try
            {
                databaseConnection.Open()
            }
            catch (SqlException ex)
            {
                const string message = "Could not establish a connection with Database.";
                Log.DatabaseStatusDown(message, ex);
                statusUp = false;
            }
            finally { databaseConnection.Close(); }
        }

        return statusUp
    }

I am aware that the Using statement leverages the IDisposable class and will auto-dispose the connection, but I wanted to be extra cautious and included the finally statement out of paranoia.

If anyone could please give me criticism, suggestions, recommendations or really anything that can help me improve this code I would greatly appreciate it. I am also open to different ideas on how I can determine if a DB is broken.


texts:
I have a json file - WorkflowNames.json with contents as -
["ImportOrder", "ValidateOrder", "ProcessOrder", "ArchiveOrder"]

My C# code to read this json file is -
private Dictionary<string, bool> GetWorkflowNames()
{
  var appDataFolder = ConfigurationMgr.GetAppPath("App_Data");
  var jsonFilePath = Path.Combine(appDataFolder, "WorkflowNames.json");
  JArray workflowNames = (JArray)JsonConvert.DeserializeObject(System.IO.File.ReadAllText(jsonFilePath));

  var workflowNamesDictionary = new Dictionary<string, bool>();
  foreach (JToken workflowName in workflowNames)
  {
    workflowNamesDictionary.Add(workflowName.ToString(), false);
  }

  return workflowNamesDictionary;
}

My code runs fine. But because this is my first attempt to read data from a json file, I am not sure about these -

As a json standard, any data in json file should be represented as key value pair. If I have just an array to read from json file, is it okay to declare as above?
Is there any better way, can I improve/simplify above C# code?

Thanks a lot!


texts: Ruby function to join array with commas and a conjunction

texts:
Should take an array such as ['dog', 'cat', 'bird', 'monkey']  and return 'dog, cat, bird and monkey'.

Looking for a more elegant solution.

def self.english_join(array)
  return nil if array.nil?
  return array[0] if array.length == 1
  return array[0..-2].join(', ') + " and " + array[-1] if array.length > 1
end


texts:
I have a c# application which displays the names of assessments and the zone which they are performed upon, separated by a comma and a space. For instance:

assessment1, Firewall
mom's assessment, LAN

When the user selects on of these assessments, I need to separate the assessment name from the zone name. I also need to replace any single quotes in the string by two single quotes so I can query my database without issues (this i cannot change, it has to be done because no SQLiteParameters are used in the function that queries my database).

This is how I do this currently (note that _view.SelectedAssessment is the entire string of both the assessment name and zone):

string zone = _view.SelectedAssessment.Substring(_view.SelectedAssessment.IndexOf(", ") + 2);
string assessmentName = _view.SelectedAssessment.Substring(0, _view.SelectedAssessment.Length - zone.Length - 2);

Is there a better way to do this? Any improvements?


texts: Python AES-CBC implementation using AES-ECB

texts:
I am looking for ways to make this code more "pythonic" and any issues with my implementation. This was designed to solve Crytopal's Challenge 10. This challenge requires recreating the AES-CBC cipher using a library-provided AES-ECB function. PKCS7 padding is also used to align bytes to block boundaries.

from Cryptodome.Cipher import AES

def xor(in1, in2):
    ret = []
    for i in range(0, max(len(in1), len(in2))):
        ret.append(in1[i % len(in1)] ^ in2[i % len(in2)])
    return bytes(ret)

def decrypt_aes_ecb(data, key):
    cipher = AES.new(key, AES.MODE_ECB)
    return cipher.decrypt(data)

def encrypt_aes_ecb(data, key):
    cipher = AES.new(key, AES.MODE_ECB)
    return cipher.encrypt(data)

def pkcs7(val, block_size=16):
    remaining = block_size - len(val) % block_size
        if remaining == block_size:
            remaining = 16
    ret = val + chr(remaining).encode() * remaining

    return ret

def unpkcs7(val, block_size=16):
    pad_amount = val[-1]
    if pad_amount == 0:
        raise Exception
    for i in range(len(val) - 1, len(val) - (pad_amount + 1), -1):
        if val[i] != pad_amount:
            raise Exception
    return val[:-pad_amount]

def decrypt_aes_cbc(data, key, iv = b'\x00' * 16, pad=True):
    prev_chunk = iv

    decrypted = []

    for i in range(0, len(data), 16):
        chunk = data[i : i + 16]
        decrypted += xor(decrypt_aes_ecb(chunk, key), prev_chunk)
        prev_chunk = chunk

    if pad:
        return unpkcs7(bytes(decrypted))
    return bytes(decrypted)

def encrypt_aes_cbc(data, key, iv = b'\x00' * 16, pad=True):
    if pad:
        padded = pkcs7(data)
    else:
        padded = data

    prev_chunk = iv

    encrypted = []

    for i in range(0, len(padded), 16):
        chunk = padded[i : i + 16]
        encrypted_block = encrypt_aes_ecb(xor(chunk, prev_chunk), key)
        encrypted += encrypted_block
        prev_chunk = encrypted_block

    return bytes(encrypted)


texts:
Working on below find first bad version problem, post my code in Python 2.7, any smarter ideas for better time complexity, any code bug or code style advice are highly appreciated. My major idea is divide and conquer like a binary search.

Problem,

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Source code,

def isBadVersion(number):
    if number == 0:
        return False
    else:
        return True
# 0 means good, 1 means bad
def find_first_bad_index(numbers):
    start = 0
    end = len(numbers)-1
    if isBadVersion(numbers[start]) == True:
        return start
    if isBadVersion(numbers[end]) == False:
        raise Exception('all good')
    while start <= end:
        mid = start + (end-start)/2
        if isBadVersion(numbers[mid]) == True:
            if start == end:
                return end
            else:
                end = mid
        else:
            start = mid + 1

if __name__ == "__main__":
    print find_first_bad_index([0,0,0,1,1,1,1,1])
    print find_first_bad_index([0,0,0,0,0,0,0,1])


texts: Select fields from a form by ID or Xpath and fill its value

texts:
I'm writing a program/tests in C# using Selenium and Chrome web driver. Everything works well, however I would like to simplify the code and make it object-oriented. I thought about extracting some parts of the code to different classes, and perhaps refactor the area of driver.FindElement... by using it only one time with different arguments.

Any suggestions?

private static void FillingForms(IWebDriver driver)
{

    driver.FindElement(By.XPath("//*[@id='payoutMethods']/label[1]")).Click();
    driver.FindElement(By.Id("SignUpButton")).Click();
    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
    driver.FindElement(By.Id("accountType_Company")).Click();
    driver.FindElement(By.Id("txtCompanyName")).SendKeys("Albertos Example");

    var mySelectElm = driver.FindElement(By.Id("ddlBusinessOrganization"));
    var mySelect = new SelectElement(mySelectElm);
    mySelect.SelectByText("Trust Company");

    driver.FindElement(By.Id("txtCompanyURL")).SendKeys("www.examplewebsite.com");
    driver.FindElement(By.Id("txtContactPersonFirstName")).SendKeys("11 Name");
    driver.FindElement(By.Id("txtContactPersonLastName")).SendKeys("11 Last Name");

    var email = Guid.NewGuid().ToString("n").Substring(0, 5);
    driver.FindElement(By.Id("txtEmail")).SendKeys(email + "@gmail.com");
    driver.FindElement(By.Id("txtRetypeEmail")).SendKeys(email + "@gmail.com");
    driver.FindElement(By.Id("datepicker")).Click();

    var mySelectElm1 = driver.FindElement(By.XPath("//*[@id='ui-datepicker-div']/div/div/select[2]"));
    var mySelect1 = new SelectElement(mySelectElm1);
    mySelect1.SelectByText("1988");

    driver.FindElement(By.XPath("//*[@id='ui-datepicker-div']/table/tbody/tr[2]/td[3]/a")).Click();
    driver.FindElement(By.Id("PersonalDetailsButton")).Click();

}


texts: Time and Space Complexity of Leetcode Problem #31. Next Permutation

texts:
The question is as follows: Given a collection of distinct integers, return all possible permutations. Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Here is my backtracking solution for the problem, where I added the num_calls variable to keep track of the number of times that the backtrack function is called recursively.

class Solution:
    def permute(self, nums):
        answer = []
        num_calls = []

        def backtrack(combo, rem):
            if len(rem) == 0:
                answer.append(combo)
            for i in range(len(rem)):
                num_calls.append(1)
                backtrack(combo + [rem[i]], rem[:i] + rem[i + 1:])

        if len(nums) == 0:
            return None
        backtrack([], nums)
        print(len(num_calls))
        return answer

I can't make sense of any of the answers that I have seen thus far for the time and space complexity of this solution.

Some people say its worst case O(n * n!), but looking at the len of num_calls doesn't verify this claim.

For example, for:

test = Solution()
print(test.permute([1, 2, 3]))

length of num_calls = 15, which != n * n! = 3 * (3*2*1) = 18

, for:

test = Solution()
print(test.permute([1, 2, 3, 4]))

length of num_calls = 64, which != n * n! = 4 * (4*3*2*1) = 96.

, and for:

test = Solution()
print(test.permute([1, 2, 3, 4, 5]))

length of num_calls = 325, which != n * n! = 5 * (5*4*3*2*1) = 600

Can someone please explain this in a simplified and easily understandable manner?


texts: Is this code an efficient implementation of Reservoir Sampling?

texts:
I posted this an answer this to a question about drawing a random line from a file too large to put into memory. I hacked the below code together. In essence, this is what Reservoir Sampling does, in pseudo-code:
Scan over the 'tape'
    Put the first 'n' samples in a reservoir(of size n)
    // samples are lines of a document, numbers, whatever
    After the first 'n' :
        Pick a random number between 1 and NumberOfLinesCounted
        if the number is between 1 and n
            replace an existing line with a 1/n chance

Here is the code designed to scan over a document, with said sampling method:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

public class reservoirSampling {

    public static void main(String[] args) throws FileNotFoundException, IOException{
        Sampler mySampler = new Sampler();
        List<String> myList = mySampler.sampler(10);
        for(int index = 0;index<myList.size();index++){
            System.out.println(myList.get(index));
        }
    }
}

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class Sampler {

    public Sampler(){}
    public List<String> sampler (int reservoirSize) throws FileNotFoundException, IOException
    {
        String currentLine=null;
        //reservoirList is where our selected lines stored
        List <String> reservoirList= new ArrayList<String>(reservoirSize);
        // we will use this counter to count the current line number while iterating
        int count=0;

        Random ra = new Random();
        int randomNumber = 0;
        Scanner sc = new Scanner(new File("Open_source.html")).useDelimiter("\n");
        while (sc.hasNext())
        {
            currentLine = sc.next();
            count ++;
            if (count<=reservoirSize)
            {
                reservoirList.add(currentLine);
            }
            else if ((randomNumber = (int) ra.nextInt(count))<reservoirSize)
            {
                reservoirList.set(randomNumber, currentLine);
            }
        }
        return reservoirList;
    }
}

I'm using something very similar on a project I am on at the moment (i.e. the code is close enough I can transfer any changes easily by hand).
Is this a) efficient, and b) actually reservoir sampling (with equal odds of any line being drawn)?


texts: Creating a file of md5 hashes for all files in a directory in PowerShell

texts:
I have been trying to write the md5 hashes for all files in a directory and its subdirectories to a file. Ideally, replicating the output of the Unix command find . -type f -exec md5sum {} + (i.e. two columns: lowercase hashes and relative file paths [with forward slashes] separated by a space and terminated only by a line feed).

With a lot of help from Mark Wragg, LotPings and others on stackoverflow, the following command appears to compute md5 hashes for all files in a directory and its subdirectories (including those files without file extensions and those with square brackets in the filename).

(Get-FileHash -Algorithm MD5 -LiteralPath (Get-ChildItem -Recurse -File).fullname | ForEach-Object{"{0} {1}" -f $_.Hash.ToLower(),(Resolve-Path -LiteralPath $_.Path -Relative)} | Out-String) -replace '\r(?=\n)' -replace '\\','/' | Set-Content -NoNewline -Encoding ascii $ENV:USERPROFILE\Desktop\hashes.txt

The two uses of -LiteralPath seems to help with filenames containing square brackets and (Get-ChildItem -Recurse -File).fullname gets the full path of all nested files, including those without file extensions. The rest is just formatting.

Can any one tell me where I can find more information about .fullname? I've tried searching for it on Google but without any luck.

I had used Get-ChildItem "*.*" -Recurse, which gives full file paths but only for files with dots in the filename. Whereas, Get-ChildItem "*" -Recurse doesn't always give the full path for some reason (and returns both files and folders). Compare:

Get-ChildItem "*.*" -Recurse | foreach-object { "$_" }

Get-ChildItem "*" -Recurse | foreach-object { "$_" }

The order of entries in the hashes file won't be the same as those from the Unix command but compare-object in PowerShell appears to ignore the order of lines, e.g. (https://serverfault.com/questions/5598/how-do-i-diff-two-text-files-in-windows-powershell)

compare-object (get-content oldHashes.txt) (get-content newHashes.txt)

or

diff (cat oldHashes.txt) (cat newHashes.txt)


texts: Remove specific consecutive element in array

texts:
I'm trying to reduce consecutive elements of array to one, but not for all values like:

{3,0,0,0,3,3,3,0,0,0} => {3,0,3,0}

but for specific one, in my example 0:

{3,0,0,0,3,3,3,0,0,0} => {3,0,3,3,3,0}

so only zeros (the threes are intact) are reduced.

I have Java String working code I wrote:

public static String removeConsecutive(String str, char remove) {
    char[] chars = str.toCharArray();

    int current = 0;
    int result  = current;
    while (current < chars.length) {
        if (chars[current] == remove) {
            // keep the first occurrence
            chars[result++] = chars[current++];

            // ignore the others
            while (current < chars.length && chars[current] == remove) {
                ++current;
            }
        } else {
            chars[result++] = chars[current++];
        }
    }

    return new String(chars, 0, result);
}

and it does the trick:

public static void main(String[] args) {
    System.out.println(removeConsecutive("000300300030303330000", '0'));
}

outputs: 0303030303330

Can anyone suggest any improvements, since it think the code is not perfect. It's doesn't have to be String in use, but with any other array.


texts: Function to convert from const char * to char**

texts:
I made an adapter function to convert a const char * to char ** splitting the words in the initial string at each white space (leading, consecutive and trailing white spaces should be ignored).

#include <iostream>
#include <vector>
#include <cctype>

void str2arg(const char * str, std::vector<char*> & arg, std::string & memory) {
  arg.clear();
  memory.clear();
  bool copied_first_char = false;
  for ( size_t i = 0; str[i]!='\0'; ++i) {
    if (isspace(str[i])) {
      if (copied_first_char) {
        if (!isspace(str[i+1])) {
          memory += '\0';
        }
      }
    } else {
      copied_first_char = true;
      memory += str[i];
    }
  }
  if (memory.back()!='\0') memory += '\0';
  //from now on, memory should't be touched!
  for ( size_t i = 0; i < memory.length(); ++i ) {
    if (i==0 or memory[i-1]=='\0') arg.push_back(&memory[i]);
  }
}

int main() {
  std::vector<char*> av;
  std::string m;
  str2arg("   this is  a test   string   ", av, m);

  std::cout << "argc=" << av.size() << "  argv=" << av.data() << std::endl;
  for (auto i: av) std::cout << i << ".\n";
  return 0;
}

Basically the function takes the original C-string, a std::vector that will hold the pointers to the words, and a std::string for automated memory management.

In the first part of str2arg() I copy the chars from the original string substituting white spaces with the termination char '\0'. Then I push the char* into the vector looking at the positions of '\0'.

Of course both the vector and the string passed to str2arg() must then be used as read-only variables.

This looks fair, but I'm not totally proud of it...


texts: Print all nodes at k distance from the root in a binary tree iteratively

texts:
I am solving this interesting coding challenge of

  printing all nodes at K distance from the root of a binary tree in a iterative fashion

Will be great to get review regarding how this code can be improved in a better way.

public class NodesAtKDistanceFromRoot {

    private final static Node EMPTY_MARKER = new Node(-1, null, null);

    public static void print(Node root, int level) {

        if (root == null) {
            return;
        }

        Deque<Node> queue = new ArrayDeque<>();
        int d = 1;
        queue.add(root);
        queue.add(EMPTY_MARKER);
        boolean found = false;

        while (!queue.isEmpty()) {

            Node current = queue.remove();

            if (current.equals(EMPTY_MARKER)) {
                // encountered empty marker which means all the nodes of a given level is visited
                d++;
                if (d == level) {
                    found = true;
                    break;
                } else {
                    queue.add(EMPTY_MARKER);
                }
            } else {
                if (current.left != null)
                    queue.add(current.left);

                if (current.right != null)
                    queue.add(current.right);
            }
        }

        // print the nodes for the given level
        if (found) {
            while (!queue.isEmpty()) {
                Node current = queue.remove();
                System.out.println(current.val);
            }
        }
    }

}

Code in Github: https://github.com/Ramblers-Code/CodeKata/blob/master/src/main/java/kata/tree/NodesAtKDistanceFromRoot.java


texts:
I am trying to simply present a table in HTML that is stored in a MySQL database. I would like to use Object Oriented PHP to access and fetch the data for the table. I have spent some time learning the different elements and have tried to put together a generic template I can use to access the tables in the database.

Questions:

Is there anything wrong with the code below?
Is there a better way to do this?
Are there any redundancies in the code? Is a more generally preferred/standard way of doing this? I've seen foreach and while being used...

    field1
    field2
    field3
    field4
    field5

<?php
require_once 'db_config.php';
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sth = $dbh->prepare("SELECT * FROM a_temp");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
?>
<?php foreach($result as $index => $row) : ?>

    <?php echo $row[field1]; ?>
    <?php echo $row[field2]; ?>
    <?php echo $row[field3]; ?>
    <?php echo $row[field4]; ?>
    <?php echo $row[field5]; ?>

<?php endforeach;?>


texts: condensed nearest centroid classifier in numpy

texts:
This is my attempt to write a numpy-optimized version of a nearest centroid classifier to classify some images from the MNIST data set of handwritten digits. I am somewhat new to numpy and was surprised by how succinctly this code could be written with the help of broadcasting and vectorized operations, but was wondering if I was still missing some possibly important improvements.

So first, the starting data are a set of 10000 training images and 1000 test images, each of which are represented as a vector of 784 pixels (corresponding to a 28x28 grayscale image). Normally these would be actual MNIST images of handwritten digits, but for simplicity, here are some "dummy" data:

import numpy as np

train_data = np.random.randint(256, size=(784, 10000), dtype="uint8")
test_data = np.random.randint(256, size=(784, 1000), dtype="uint8")

Note that the way the data is (would be, if it was the real data) arranged is such that the first tenth of each data set is a 0, the next tenth is a 1, and so on through 9 (this is important for how the data gets processed below).

Now, to process the data, I compute the mean for each digit in the training set, classify each image in both the training and test sets, and then compute and output both the training and test accuracies:

train_means = np.mean(train_data.reshape(784, 10, 1000), axis=2)

train_classes, test_classes = (np.argmin(np.sum(np.square(data[:,:,np.newaxis] - train_means[:,np.newaxis,:]), axis=0), axis=1) for data in (train_data, test_data))

train_acc, test_acc = (np.mean(np.equal(classes, np.repeat(np.arange(10), classes.size // 10))) for classes in (train_classes, test_classes))
print("training accuracy: {}\n testing accuracy: {}".format(train_acc, test_acc))

How can the above code be improved in terms of (1) efficiency, (2) memory, and (3) style / simplicity?

For instance, one concern I have is that the subtraction data[:,:,np.newaxis] - train_means[:,np.newaxis,:] creates a (784, 10000, 10) array, which is more memory than I need to use. Could I avoid allocating this much memory while not sacrificing any efficiency (and ideally any simplicity of code)?

Another concern is the comprehension I use to apply the procedures to both the training data and testing data. Would that be encouraged or considered convoluted (or maybe this is just irrelevant personal preference)?

Also: in general, is the code too condensed?


texts: Use of die() in flow control - proper and sensible?

texts:
Designed for OpenCart, vQmod places or replaces bits of code based on XML files.

The following three versions of the code achieve the same goal, which is to replace nearly ALL of a specific page.

The offset parameter tells the vqmod how many lines of code to remove, including and following the search code.

It seems to me that the one that simply uses die() following the footer() is the most sensible because it leaves room for core file length change and isn't referencing a non-existent vQmod offset, but is there anything wrong with doing it that way?

    <operation info="Block users from checking out">
        <search position="replace" offset="963"><![CDATA[
<?php echo $heading_title; ?>
]]></search>
        <add><![CDATA[
<?php echo $heading_title; ?>

Order will be processed after the food shipment has arrived.

&nbsp;

Shopping carts are automatically saved, so please just set the contents of your shopping cart to match your desired order.

Remember that prices are approximate and item availability is not guaranteed.

            <?php echo $footer;?>]]>
        </add>
    </operation>

But what if the next core update has a longer file? We could also just die() at the end of the code we place:

    <operation info="Block users from checking out">
        <search position="replace"><![CDATA[
<?php echo $heading_title; ?>
]]></search>
        <add><![CDATA[
<?php echo $heading_title; ?>

Order will be processed after the food shipment has arrived.

&nbsp;

Shopping carts are automatically saved, so please just set the contents of your shopping cart to match your desired order.

Remember that prices are approximate and item availability is not guaranteed.

            <?php echo $footer;
            die();?>]]>
        </add>
    </operation>

Another option is to increase the offset to a number that seems likely to encompass any likely increases to line numbers in the (near) future:

    <operation info="Block users from checking out">
        <search position="replace" offset="1000"><![CDATA[
<?php echo $heading_title; ?>
]]></search>
        <add><![CDATA[
<?php echo $heading_title; ?>

Order will be processed after the food shipment has arrived.

&nbsp;

Shopping carts are automatically saved, so please just set the contents of your shopping cart to match your desired order.

Remember that prices are approximate and item availability is not guaranteed.

            <?php echo $footer;?>]]>
        </add>
    </operation>


texts:
I've just wrote this class for an image slider (it cross-fades rather than sliding, so a class rename may be beneficial). It's my first proper attempt at JavaScript OOP. Can anyone see any real issues with this?

// Wrapper is the container element, in this case $('#sliderWrap').
// images is an array of the images.

function ImageSlider(wrapper, images){

    // Elements.
    this.elem = wrapper;
    this.images = images;
    this.top = this.elem.find('#topImage');
    this.bottom = this.elem.find('#bottomImage');
    this.next = this.elem.find('#nextBtn');
    this.prev = this.elem.find('#prevBtn');

    this.lastImage = images.length - 1;
    this.currImage = 1; // This is 1 as the first iteration is rendered in the HTML.
    this.interval;
    this.fadeTime = 400;
    this.sliderDelay = 4000 + this.fadeTime;

    var self = this;

    this._init = function(){

        $(window).on('load', function(){
            self.elem.css('height', self.top.height());
            self.next.show();
            self.prev.show();
            self._animate();
            self._startInterval();
            self.next.click(function(){
                clearInterval(self.interval);
                self._animate(true);
                self._startInterval();
            });

            self.prev.click(function(){
                clearInterval(self.interval);
                self._animate(false);
                self._startInterval();
            });
        });
    }

    /**
     * @param next boolean. True next, false prev
     */

    this._animate = function(next){
        if(typeof next == 'undefined') {
            next = true;
        }

        if (next) {
            self.nextImage();
        } else {
            self.prevImage();
        }
    }

    this.nextImage = function(){
        self.currImage++;

        this.top.fadeOut(self.fadeTime, function(){
            self.bottom.addClass('active');
            self.top.attr('src', self.images[self.currImage - 1]).show();

            if (self.currImage > self.lastImage) {
                self.currImage = 0;
            }

            self.bottom.removeClass('active');

            self.bottom.attr('src', self.images[self.currImage]);
        });
    }

    this.prevImage = function(){

        var minusTwo = self.currImage - 2;

        switch (minusTwo){
            case -1:
                minusTwo = self.lastImage;
                break;
            case -2:
                minusTwo = self.lastImage - 1;
                break;
        }

        self.bottom.attr('src', self.images[minusTwo]);
        self.top.fadeOut(self.fadeTime, function(){
            self.bottom.addClass('active');

            var plusOne = minusTwo + 1;
            if (plusOne > self.lastImage){
                plusOne = 0;
            }

            self.top.attr('src', self.images[minusTwo]).show();
            self.bottom.attr('src', self.images[plusOne]);
            self.bottom.removeClass('active');
            self.currImage--;
            if(self.currImage < 0){
                self.currImage = self.lastImage;
            }
        });
    }

    this._startInterval = function(){
        self.interval = setInterval(function(){
            self._animate();
        }, self.sliderDelay);
    }

    this._init();
}

The HTML markup to go with this is.

I think the only really relevant CSS is the active class, which basically puts the bottomImage on top of the topImage (z-index wise).


texts:
I am using the following script to read search terms from a file and then search those terms in google (each search result in it's own tab).
from selenium import webdriver

browser = webdriver.Chrome()

# first tab
browser.get('https://google.com')

with open("google-search-terms.adoc") as fin:
    for line_no, line in enumerate(fin):
        line = line.strip()
        line = line.replace(' ', '+')
        line = line.replace('&', '%26')
        browser.execute_script(
            "window.open('https://www.google.com/search?q="+line+"');")

How can I make this code better?


texts: A menu option that receives input from users and then performs actions

texts:
Please review my FindMovie and AddMovie methods.

public static boolean FindMovie(String movietofind, String[] ArrayMovie) {
    movie Movieobject = new movie();

    for (String ArrayMovie1 : ArrayMovie) {
        if (ArrayMovie1.equals(movietofind)) {
            return true;
        }
    }
    return false;
}

public static void AddMovie(int i, String[] ArrayMovie, String[] UserRating, int[] UserReview) {
    int addmovie, userrating;
    boolean Movie1;
    String MPAA;
    Scanner console = new Scanner(System.in);

    System.out.println("Please give me the name of the movie you want to add.");
    String Movie = console.next();

    Movie1 = FindMovie(Movie, ArrayMovie);
    if (Movie1 = false) {
        System.out.println("Do you want to add this movie to the collection? Please select 1 for Yes or 2 for No");
        addmovie = console.nextInt();
        if (addmovie == 1) {
            ArrayMovie[i] = Movie;

            System.out.println("What is the type of MPAA rating of the movie?");
            System.out.println("Please enter G, PG, PG13, or R");
            MPAA = console.next();
            UserRating[i] = MPAA;

            System.out.println("What is your rating for movie?");
            System.out.print("please choose 1, 2, 3, 4, or 5");
            userrating = console.nextInt();
            UserReview[i] = userrating;

        } else if (addmovie == 2) {
        }
    }
}


texts: Implementing an asynchronous mutex in C#

texts:
I wrote a simple synchronization primitive that I can use with async operations on an external REST service so that I don't call it twice from different threads and have one call fail due to not having the latest state. Despite obvious limitations of that design decision I think this should solve my problem...

struct DumbAsyncMutex
{
    int busy;

    public async Task WithMutexAsync(Func<Task> t)
    {
        while (Interlocked.CompareExchange(ref busy, 1, 0) != 0)
        {
            await Task.Delay(100);
        }

        try
        {
            await t();
        }
        finally
        {
            while (Interlocked.CompareExchange(ref busy, 0, 1) != 1)
            {
                throw new Exception("Releasing the mutex failed - but this should never happen");
            }
        }
    }
}

Of course this is a hack... did I just overlook a better way to do this using the standard framework?


texts: Remove every line that include and follows the second occurrence of a given pattern

texts:
From a file, I am trying to remove every line that include and follows the second occurrence of a given pattern in Bash (Mac OSX). Note, that a file may have only one match of the given pattern (and so nothing need to be removed).

Here an example of file

bar
second
third
fourth
bar
sixth

and here is a code that does the job

# Find the index of the second occurrence
i=$(grep -nrH ${pattern} ${file} | awk -F':' '{if (NR==2)print $2}')

# If there was a second occurrence, then remove everything that followed it
if [[ ${i} != "" ]];then
    head -n $(( ${i} - 1 )) ${file} > tmp && mv tmp ${file};
fi

The resulting file is

bar
second
third
fourth

Is there a more elegant or faster solution?


texts: Binary search optimization: Kernighan & Ritchie 3-1

texts:
The problem I am trying to solve can be described as take binarysearch0 and rewrite it as binarysearch1 such that binarysearch1 uses a single test inside the loop instead of two. The code I used to do this is seen below. Please let me know if you think I accomplished the task, and what I can do better.

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

void printdata(int *v, int n)
{
    int i = 0;
    for (i = 0; i < n; ++i) {
        printf("%3d", v[i]);
    }
    putchar('\n');
}

int binarysearch0(int x, int *v, int n)
{
    int low, high, mid;

    low = 0;
    high = n - 1;
    while (low <= high) {
        mid = (low + high) / 2;
        if ( x < v[mid])
            high = mid -1;
        else if (x > v[mid])
            low = mid + 1;
        else
            return mid;
    }
    return -1;
}

int binarysearch1(int x, int *v, int n)
{
    int low, high, mid;

    low = 0;
    high = n - 1;
    while (low <= high && v[(mid = (low + high) / 2)] != x ) {
        mid = (low + high) / 2;
        if ( x < v[mid])
            high = mid -1;
        else
            low = mid + 1;
    }
    return (v[mid] == x) ? mid : -1;
}

int main(int argc, char *argv[])
{
    int v[10][10] = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
                      {10,11,12,13,14,15,16,17,18,19},
                      {20,21,22,23,24,25,26,27,28,29},
                      {30,31,32,33,34,35,36,37,38,39},
                      {40,41,42,43,44,45,46,47,48,49},
                      {50,51,52,53,54,55,56,57,58,59},
                      {60,61,62,63,64,65,66,67,68,69},
                      {70,71,72,73,74,75,76,77,78,79},
                      {80,81,82,83,84,85,86,87,88,89},
                      {90,91,92,93,94,95,96,97,97,99}
                    };

    int i = 0;
    for (i = 0; i < 10; ++i) {
        int search = 0;
        (i == 0) ? (search = 1000) : (search = v[i][0] + rand()%10);
        if(binarysearch1(search, v[i], 10) > -1) {
            printf("%d was found in the data: %14s", search, " ");
            printdata(v[i], 10);
        } else {

            printf("%d was NOT found in the data: %10s", search, " ");
            printdata(v[i], 10);
        }
        putchar('\n');
    }
    return 0;
}


texts: A fast and (Ideally) thread safe object pool in C

texts:
I have a helper struct called Scratch, that is a calculation 'Scratch Pad'.  Generally, I need only one of these objects, but if I have nested calculations I'll need one scratch per level of nesting.  And if I want to make the calculation thread safe then each thread will need one or more Scratch objects.

For simple cases a singleton Scratch object works fine and I'm able to achieve 38 steps per second.  If I change from using the singleton to just instantiating a Scratch object each time I drop to 10 steps per second.

Using a non thread safe version of the Pool below (commenting out the mutex locks and unlocks) got me just about back up to 35-38ish steps per second.  But the thread safe version as listed below knocks me down to 16 steps per second.  So, in order to make threading worth it, I'd have to overcome that initial performance blow.

I guess theoretically two cores should be able to almost breakeven and 3 or more should be able to make the lock cost worth it, but I haven't tried that yet.

Any suggestions, comments, criticisms greatly appreciated.

typedef struct Pool {
    Scratch** scratches;
    int n;
    int i;
    pthread_mutex_t mutex;
} Pool;

Pool* pool_;

Pool* AEPoolCreate() {
    Pool* pool = (Pool*)malloc(sizeof(Pool));
    pool->scratches = (Scratch**)malloc(sizeof(Scratch*));
    pool->scratches[0] = AEScratchCreate();
    pool->n = 1;
    pool->i = 0;
    pthread_mutex_init(&pool->mutex, NULL);
    return pool;
}
Scratch* AEPoolGet(Pool* pool) {
    pthread_mutex_lock(&pool->mutex);
    if (pool->i == pool->n) {
        pool->n *= 2;
        printf("[ Pool ===================== ]\n");
        printf("   increased to a size of %d\n", pool->n);
        printf("[ =========================== ]\n\n");
        pool->scratches = (Scratch**)realloc(pool->scratches, sizeof(Scratch*)*pool->n);
        for (int i=pool->i;i<pool->n;i++)
            pool->scratches[i] = AEScratchCreate();
    }
    Scratch* scratch = pool->scratches[pool->i++];
    pthread_mutex_unlock(&pool->mutex);
    return scratch;
}
void AEPoolPut(Pool* pool, Scratch* scratch) {
    pthread_mutex_lock(&pool->mutex);
    scratch->cp = 0;
    scratch->vp = 0;
    scratch->sp = 0;
    pool->i--;
    pool->scratches[pool->i] = scratch;
    pthread_mutex_unlock(&pool->mutex);
}

Here is the Scratch object as requested:

// Scratch =
typedef struct Scratch {
    Obj* stack;
    byte sp;
    byte cp;
    byte vp;
} Scratch;
Scratch* AEScratchCreate() {
    Scratch* scratch = (Scratch*)malloc(sizeof(Scratch));
    scratch->stack = (Obj*)malloc(sizeof(Obj)*10);
    scratch->cp = 0;
    scratch->vp = 0;
    scratch->sp = 0;
    return scratch;
}
void AEScratchRelease(Scratch* scratch) {
    if (scratch == 0) return;
    free(scratch->stack);
    free(scratch);
}

// Dim =====
typedef union {
    long n;
    double x;
    void* p;
} Dim;

// Obj =====
typedef struct {
    Dim a;
    Dim b;
    Dim c;
    //  byte type;
} Obj;


texts: Representing IPv6 addresses with PHP per RFC 5952

texts:
I wrote the following function in PHP to represent IPv6 addresses as short as possible:

function ipv6_compress($ip){
    // Shorten first group of zeros
    if(substr($ip, 0, 4) == 0000) $ip = substr_replace($ip, '0', 0, 4);
    // Shorten full groups of zeros
    $ip = str_replace('0000:', '0:', $ip);
    // Remove leading zeros
    $ip = preg_replace('/:0{1,3}(?=\w)/', ':', $ip);
    // Remove longest extra group of zeros per [RFC 5952](http://tools.ietf.org/html/rfc5952)
    if(strpos('::') !== false) return $ip; // But don't if a :: is already present as entered
    $pos = strpos($ip, '0:0:0:0:0:0:0:');
    if($pos !== false) return $ip = substr_replace($ip, '::', $pos, 14);
    $pos = strpos($ip, '0:0:0:0:0:0:');
    if($pos !== false) return $ip = substr_replace($ip, '::', $pos, 12);
    $pos = strpos($ip, '0:0:0:0:0:');
    if($pos !== false) return $ip = substr_replace($ip, '::', $pos, 10);
    $pos = strpos($ip, '0:0:0:0:');
    if($pos !== false) return $ip = substr_replace($ip, '::', $pos, 8);
    $pos = strpos($ip, '0:0:0:');
    if($pos !== false) return substr_replace($ip, '::', $pos, 6);
    $pos = strpos($ip, '0:0:');
    if($pos !== false) return substr_replace($ip, '::', $pos, 4);
    return $ip;
}

I attempt to adhere to RFC 5952.

Do I violate the standard in any way?
Can I do anything more efficiently?

As you can probably tell, I am not concerned with validating the addresses.


texts: Adding fade to jquery background position animate

texts:
I've just implemented a background animate on some social media icons where the image goes from grey to color on :hover.

I wanted to know if there's a better way to write the following but also implement a fade, so as the background animates, it's also fading in on hover.

    <script type="text/javascript">

$(function(){
    $('#facebook')
        .css( {backgroundPosition: "0 0"} )
        .mouseover(function(){
            $(this).stop().animate({backgroundPosition:"(-63px 0px)"}, {duration:150})
        })
        .mouseout(function(){
            $(this).stop().animate({backgroundPosition:"(0 0)"}, {duration:150})
        })
    $('#twitter')
        .css( {backgroundPosition: "0 0"} )
        .mouseover(function(){
            $(this).stop().animate({backgroundPosition:"(-63px 0)"}, {duration:150})
        })
        .mouseout(function(){
            $(this).stop().animate({backgroundPosition:"(0 0)"}, {duration:150})
        })
});
</script>


texts: Better paradigms for posting JSON from a table?

texts:
With a table based interface where users can update the rows by pressing a button. Perhaps there is a better way of doing this, without pressing a button, i.e. post on textarea/row change (could be a selectbox column). My requirement is that it's the LEAST amount of JavaScript possible, without being cryptic.

For example, could the code here be improved (assume an uptodate Firefox/Chrome browser), ideally without changing the HTML?

$(document).ready(function () {
$('button').click(function () {
    var row = $(this).parent().parent();
    row.css("background-color", "red");
    var id = row.children(':nth-child(1)').text();
    var note = row.find('textarea').val();
    var data = {
        json: JSON.stringify({
            id: id,
            note: note
        })
    };

    $.ajax({
        url: "/echo/json/",
        type: "POST",
        data: data,
        contentType: "application/json"
    }).done(function (d) {
        console.log(d);
        row.css("background-color", "green");
    });
});
});

I want less code for the JavaScript and I was thinking how much effort if would be to remove the jQuery dependency entirely. Ashamedly it took me a long time to write that jQuery!


texts: Read file into list when class is instantiated in Python 2.7

texts:
I would like to read a file into a list when I create the class below. Once the list is ready, I would like to access it outside the class in order to process more code based on the list which now contains my file. Can the code be improved upon?

class ReadFile(object):
    def __init__(self, filename):
        self._data = []
        self.localdir = 'C:\\Users\\User\\Documents'
        self.filename = filename
        self.filepath = os.path.join(self.localdir, self.filename)
        self.read_data()

    def read_data(self):
        try:
            with open(self.filepath, 'rU') as c:
                rows = csv.reader(c)
                for row in rows:
                    self._data.append(row)
        except Exception as ex:
            print(ex)

    def get_data(self):
        return self._data

def main():
    new = ReadFile('myfile.csv')
    new_data = new.get_data()

    for i in new_data:
        print(i)        # etc... more code will follow

if __name__ == '__main__':
    main()


texts: Creating a database, a table within the database and inserting some values into it in one go

texts:
I've written a script which creates a new database, a table within the database, insert some values into it and fetch the values in one go. The way I've created the script below to achieve what I just said seems not to be an ideal way as there are too many repetitions in there. To be specific this two functions create_database() and connect() are almost identical. Moreover, I had to use mycursor = conn.cursor() twice within main function.
import mysql.connector

def create_database():
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd = "",
      database=""
    )
    return mydb

def connect(databasename):
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd = "",
      database=databasename
    )
    return mydb

def store_data(item_name,item_link):
    mycursor.execute("INSERT INTO webdata (item_name,item_link) VALUES (%s,%s)", (item_name,item_link))
    conn.commit()

if __name__ == '__main__':
    db_name = "newdatabase"
    conn = create_database()
    mycursor = conn.cursor()
    try:
        mycursor.execute(f"CREATE DATABASE {db_name}")
    except mysql.connector.errors.DatabaseError:
        pass
    conn = connect(db_name)
    mycursor = conn.cursor()
    mycursor.execute("DROP TABLE if exists webdata")
    mycursor.execute("CREATE TABLE if not exists webdata (item_name VARCHAR(255), item_link VARCHAR(255))")
    store_data("all questions","https://stackoverflow.com/questions/tagged/web-scraping")
    mycursor.execute("SELECT * FROM webdata")
    for item in mycursor.fetchall():
        print(item)

What it prints (expected result):
('all questions', 'https://stackoverflow.com/questions/tagged/web-scraping')