texts: Fast affine transformations of many 3D points by one 3×4 matrix

texts:
I wrote a function to batch-transform 3D vectors by a single 3x4 matrix using SSE2:

struct alignas(16) Matrix3x4f
{
    union
    {
        Vector4 r[3];   // (r[0].w, r[1].w, r[2].w) contains the translation
        float   m[3][4];
    };
    // (0, 0, 0, 1) is the forth row of the full 4x4 matrix
};

struct Positions_SoA
{
    Vector4 *   xs;
    Vector4 *   ys;
    Vector4 *   zs;
};

void transform_points_SSE2(
    const Matrix3x4f& transform_,
    const Positions_SoA& inputs_,
    const int number_of_packets_,
    Positions_SoA &outputs_
    )
{
    //FIXME: woudn't this cause too much register pressure and memory loads?
    // For AVX/AVX2 we'll have to splat 8/16 values.
    const Vector4 m00 = SPLAT_X( transform_.r[0] );
    const Vector4 m01 = SPLAT_Y( transform_.r[0] );
    const Vector4 m02 = SPLAT_Z( transform_.r[0] );
    const Vector4 m03 = SPLAT_W( transform_.r[0] ); // translation X

    const Vector4 m10 = SPLAT_X( transform_.r[1] );
    const Vector4 m11 = SPLAT_Y( transform_.r[1] );
    const Vector4 m12 = SPLAT_Z( transform_.r[1] );
    const Vector4 m13 = SPLAT_W( transform_.r[1] ); // translation Y

    const Vector4 m20 = SPLAT_X( transform_.r[2] );
    const Vector4 m21 = SPLAT_Y( transform_.r[2] );
    const Vector4 m22 = SPLAT_Z( transform_.r[2] );
    const Vector4 m23 = SPLAT_W( transform_.r[2] ); // translation Z

    for( int i = 0; i < number_of_packets_; i++ )
    {
        outputs_.xs[i] = V4_ADD(
            V4_ADD(
                V4_MUL( m00, inputs_.xs[i] ),
                V4_MUL( m01, inputs_.ys[i] )
            ),
            V4_ADD(
                V4_MUL( m02, inputs_.zs[i] ),
                 m03
            )
        );

        outputs_.ys[i] = V4_ADD(
            V4_ADD(
                V4_MUL( m10, inputs_.xs[i] ),
                V4_MUL( m11, inputs_.ys[i] )
            ),
            V4_ADD(
                V4_MUL( m12, inputs_.zs[i] ),
                m13
            )
        );

        outputs_.zs[i] = V4_ADD(
            V4_ADD(
                V4_MUL( m20, inputs_.xs[i] ),
                V4_MUL( m21, inputs_.ys[i] )
            ),
            V4_ADD(
                V4_MUL( m22, inputs_.zs[i] ),
                m23
            )
        );
    }
}

The complete, runnable code is on rextester.

When I run the tests and compare the numbers with the reference (scalar) version, the results of the SSE version appear slightly wrong in half of all the cases, although the printed numbers look the same. Is that due to rounding errors? (FPU internally uses 80-bit precision, and SSE units compute with 32-bit precision.) Should I ignore those small discrepancies? Is my 'optimized' function even correct?
Why is the speedup due to SSE so small? I expected 3-3.5 speed increase, but got less than 2. Should I use AVX?
I plan to transform up to 64 points, is it still worth to use SSE/AVX?
Will performance be dominated by the cost of loading into registers?
I'm worried about the 12 shuffle/broadcast/replicate instructions.
Finally, I'll appreciate comments on my programming style, my mistakes in using SSE, a note on best practices and performance pitfalls.


texts:
I've been writing JavaScript for a couple years but nobody's ever really looked at my code.

This is a small library I wrote to check code modularity, w/ input like avg-lines . -name '*.js' (the arguments are passed straight to find) you might get:

Checked 20 files (1615 LOC):
  80% of files contain > 137 LOC
  20% of files contain 67.68% of the total LOC
  The largest file (./dist/redux.js) contains 638 LOC

index.js

import {exec} from 'child_process'

const i80 = arr => Math.ceil(arr.length * 0.8)
const sum = arr => arr.reduce((pv, [v]) => pv + v, 0)
const insertTypeOption = args =>
  /('?[-\|])/.test(args) ? args.replace(/('?[-\|])/, '-type f $&') : `${args} -type f`
const generateCommand = args => `find ${insertTypeOption(args)} | xargs wc -l`

export default args => new Promise((resolve, reject) => {
  const process = exec(generateCommand(args))
  const files = []
  const interval = setInterval(() => console.log(`checked ${files.length} files`), 3000)
  process.stderr.on('data', ::console.error)
  process.stdout.on('data', input =>
    files.push(
      ...input.split('\n').map(l =>
        l && l.match(/^ *(\d+) +(.+)$/)).filter(v => v).
        map(([, val, file]) => [parseInt(val, 10), file]).
        filter(([, filename]) => filename !== 'total')))
  process.on('close', exit => {
    clearInterval(interval)
    if (exit) reject(exit)
    files.sort(([v0], [v1]) => v0 - v1)
    if (!files.length) reject(`No files matched \`${generateCommand(args)}\``)
    else {
      resolve({
        numFiles: files.length,
        numLines: sum(files),
        avgLines: files[i80(files)][0],
        linesInequality: sum(files.slice(i80(files))) / sum(files),
        largestFileName: files.slice(-1)[0][1],
        largestFile: files.slice(-1)[0][0]})}})})

logger.js

import avgLines from './index'

const args = process.argv.slice(/node/.test(process.argv[0]) ? 2 : 1).map(v => `'${v}'`).join(' ')
const log = str => {
  let bold = false
  const newStr = str.split('**').reduce((pv, v) => (bold = !bold, `${pv}\x1b[${bold ? 1 : 0}m${v}`))
  console.log(newStr)}

export default avgLines(args).then(
  ({numFiles, numLines, avgLines: avgLines$, linesInequality, largestFileName, largestFile}) => (
    log(`Checked **${numFiles}** files (**${numLines}** LOC):`),
    log(`  **80%** of files contain > **${avgLines$}** LOC`),
    log(`  **20%** of files contain **${(linesInequality * 100).toFixed(2)}%** of the total LOC`),
    log(`  The largest file (**${largestFileName}**) contains **${largestFile}** LOC`))).
  catch(::console.error)


texts: Import function vs turning it into custom hook

texts:
I have this ProductSearchContainer.js file that it's getting too long to handle and maintain.

What it's responsible for:

Doing network requests to get a list of products
Filter that list with filters values it gets from URL query string and update state with the new filteredList
It also holds functions to simulate the length of products on each filter before you click it. For example: a color filter with Black(5) indicating that you'll get 5 products if you click on Black.
Along other functions

The file was getting too big (600+ lines) and I decide to move some pieces of logic to other files.

For each filter category (brand, price, rating, etc) I have two functions:

1 to apply the active filters (get a list and the activeFilters array and it returns a filtered list for those filters.
1 to simulate the next filter length (like I explained above on the colors example)

Note: You'll see below that they rely on state variable activePriceFilters but they don't call any React Hook in their execution.

OPTION #1

My 1st thought was to turn into a custom hook. So I did. And it works (see snippet below).

function usePriceFilter(activePriceFilters) {

  function applyPriceFilter(list, activePriceFilters) {
    console.log('I will get a list and return it filtered by activePriceFilters');
  }

  function simulateNextPriceFilter(list, someTestPriceFilter) {
    console.log('I will get a list and return the length of the filtered list by price');
  }

  return [applyPriceFilter,simulateNextPriceFilter];

}

And I consume by doing:

const [applyPriceFilter,simulateNextPriceFilter] = usePriceFilter(activePriceFilters)

I mean, my custom hook is basically a higher order function but I think it still qualifies as a custom hook:

From React DOCS:

  A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.

OPTION #2

But I guess I could also turn into a regular .js file, export both functions and just do the regular import on them. Like:

import {applyPriceFilter,simulateNextPriceFilter} from './priceFilterHelpers

QUESTION:

Is there a difference in functionaly or performance between the 2 approaches? Should I favor 1 instead of the other?

I think that the custom hook's is more readable, but is there anything else I'm gaining by doing this?

function App() {

  const [activePriceFilters,setActivePriceFilters] = React.useState(['10to20','50+']);

  const [applyPriceFilter, simulateNextPriceFilter] = usePriceFilter(activePriceFilters);

  return(
    <React.Fragment>
      <button onClick={applyPriceFilter}>Apply Price Filters</button>
      <button onClick={simulateNextPriceFilter}>Simulate Price Filter</button>
    </React.Fragment>
  );

}

function usePriceFilter(activePriceFilters) {

  function applyPriceFilter(list, activePriceFilters) {
    console.log('I will get a list and return it filtered by activePriceFilters');
  }

  function simulateNextPriceFilter(list, someTestPriceFilter) {
    console.log('I will get a list and return the length of the filtered list by price');
  }

  return [applyPriceFilter,simulateNextPriceFilter];

}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id="root"/>


texts:
I made a method that I can use to avoid having to handle errors from callbacks.
What it does is, call the passed method only if the first argument is null.
So essentially it will bypass to the last method, if an error occurs.

Feedback is welcome.

/**
 * continueIf
 *
 * Returns a continuation method that only continues
 * if error is null'ish
 *
 * @param fn The function to call
 * @param args* Any number of arguments to pass after the arguments from the function
 */

function continueIf (fn) {
  var args = Array.prototype.slice.call(arguments, 1);
  var callback = arguments[arguments.length - 1];
  if (typeof callback !== 'function') {
    throw('Missing callback');
  }
  return function (err) {
    if (err) {
      return callback(err);
    }
    return fn.apply(null, Array.prototype.slice.call(arguments, 1).concat(args));
  };
};

A test case:

it('continues to f2 but not to f3', function (done) {
  var msg = 'hello';
  var msgErr = 'some error';
  function f1 (a, callback) {
    expect(a).toBe(msg);
    callback(null, a);
  }
  function f2 (a, callback) {
    expect(a).toBe(msg);
    callback(msgErr);
  }
  var dummy = jasmine.createSpy('dummy');
  f1(msg, continueIf(f2, continueIf(dummy, function (err) {
    expect(err).toBe(msgErr);
    expect(dummy).not.toHaveBeenCalled();
    done();
  })));
});


texts: R data.frame iterrative search algorithm

texts:
I have the following data frame:

set.seed(1)
SOURCE <- as.data.frame(matrix(c((1:10),
                             sample(c("20-24","25-28"), 10, replace = TRUE),
                             sample(c("10000", "20000"), 10, replace = TRUE),
                             sample(c(1, NA), 10, replace = TRUE),
                             sample(c(2, NA), 10, replace = TRUE),
                             sample(c(3, NA), 10, replace = TRUE)), nrow = 10), stringsAsFactors = FALSE)

names(SOURCE) <- c("id", "age", "income", "IS_1", "IS_2", "IS_3")
SOURCE$SUM_1 <- sample(c(1000, 10000), 10, replace = TRUE) * as.numeric(SOURCE$IS_1)
SOURCE$SUM_2 <- sample(c(1000, 10000), 10, replace = TRUE) * as.numeric(SOURCE$IS_2)
SOURCE$SUM_3 <- sample(c(1000, 10000), 10, replace = TRUE) * as.numeric(SOURCE$IS_3)

For each line I want to find additional IS group, by doing the following:

SOURCE$BUCKET <- do.call(paste, c(SOURCE[, c(4,5,6)]))
for (i in 1:nrow(SOURCE)) {
  steady <- as.vector(read.table(text = SOURCE$BUCKET[i], sep = " ", colClasses = "numeric"))
  ready <- steady[!is.na(steady)]
  SOURCE$IS_BREADTH[i] <- length(ready)
  SOURCE$PATTERN[i] <- paste0("(?=.*", ready, ")", collapse = "")
}
require("data.table")
DIMPORT <- data.table(SOURCE)

Also, I don't want my algorithm to return me the same IS group, the person is active in. So I use the following:

na.replace <- function (x) {
  ifelse(is.na(x) == TRUE,  x <- 1, x <- NA)
  return(x)
}

And here comes the iterative part:

j <- data.frame()
d <- data.frame()
for (i in 1:nrow(DIMPORT)) {
  print(i)
  Xid <- DIMPORT$id[i]
  Xage <- DIMPORT$age[i]
  Xpattern <- DIMPORT$PATTERN[i]
  Xincome <- DIMPORT$income[i]
  Xbreadth <- DIMPORT$IS_BREADTH[i]
  if (DIMPORT$IS_BREADTH[i] == 0){
    Xcategory <- "UNKNOWN"
    Xsum <- "UNKNOWN"
    j <- as.data.frame(matrix(c(Xid, Xage, Xpattern, Xincome, Xcategory, Xsum), nrow = 1))
    d <- rbind(d, j)
  } else {
    DSEGMENT <- DIMPORT[age == Xage & IS_BREADTH == Xbreadth + 1 & income == Xincome & grepl(Xpattern, DIMPORT$BUCKET, perl = TRUE)]
    if (nrow(DSEGMENT) == 0) {
      Xcategory <- "UNDETECTABLE"
      Xsum <- "UNDETECTABLE"
      j <- as.data.frame(matrix(c(Xid, Xage, Xpattern, Xincome, Xcategory, Xsum), nrow = 1))
      d <- rbind(d, j)
      } else {
      IS_vector <- c(na.replace(DIMPORT$IS_1[i]), na.replace(DIMPORT$IS_2[i]), na.replace(DIMPORT$IS_3[i]))
      DZ <- DSEGMENT[, list("1" = sum(!is.na(IS_1)) / length(id), "2" = sum(!is.na(IS_2)) / length(id), "3" = sum(!is.na(IS_3)) / length(id))] * IS_vector
      category <- paste0(names(which.max(DZ)))
      DB <- DSEGMENT[, grepl(paste0("(?=.*_", category, "$)", collapse = ""), names(DSEGMENT), perl = TRUE), with = FALSE]
      names(DB) <- c("IS", "SUM")
      DB <- DB[complete.cases(DB)]
      Xsum <- as.character(DB[, list(SPEND_PER_ID = sum(SUM) / nrow(DB))])
      Xcategory <- category
      j <- as.data.frame(matrix(c(Xid, Xage, Xpattern, Xincome, Xcategory, Xsum), nrow = 1))
      d <- rbind(d, j)
      }
  }
}

The result is fine, though the speed is about 2 lines per second in non-mockup data (127 columns). Is there any way to improve the speed?


texts: Pythonic way for double iteration (list all files with extensions)

texts:
Given a base path and a list with extensions the task is to list all files:

Two of my solutions are:

from glob import glob
from os import path

EXTENSIONS = ['*.zip', '*.jar', '*.pdf']
DOC_PATH = '/path/to/files'

# Solution1:
files = []
for ext in EXTENSIONS:
    files.extend(glob(path.join(DOC_PATH, ext)))
# works but looks very clumsy

# Solution2:
files = reduce(lambda x,y: x+y,
               [glob(path.join(DOC_PATH, ext)) for ext in EXTENSIONS])
# Also functional but looks like a misuse of reduce

Have you got any other ideas?


texts: Python function to get numbers around another number

texts:
I made a function to get a list with numbers around another number. Example: I want to get in a range of 2 numbers around 4. This will return: [2, 6]. You can set a min number and a max_number. That means when I set a min_num, the lower number should not be lower than the min number.

import sys

def get_numbers_around(number: int, min_num: int = None, max_num: int = None, _range: int = 2, on_fail_no_error: bool = False) -> range:
    if max_num is None:
        max_num = sys.maxsize

    if min_num is None:
        min_num = -sys.maxsize - 1

    diff = max_num - min_num
    if diff < _range:
        if not on_fail_no_error:
            raise ValueError(
                "Range is too small. Range is {0} big but difference between max_num and min_num is {1} big! ({0} < {1}".format(
                    range, max_num - min_num))
        else:
            return range(number - diff, number + diff)

    final_list = [number - _range, number + _range]

    if final_list[0] < min_num:
        diff = abs(min_num - final_list[0])
        final_list[0] = min_num
        final_list[1] += diff

    if final_list[1] > max_num:
        diff = abs(final_list[1] - max_num)
        final_list[1] = max_num
        final_list[0] -= diff

    return range(final_list[0], final_list[1])

print(get_numbers_around(4)) # range(2, 6)
print(get_numbers_around(4, _range=5)) # range(-1, 9)
print(get_numbers_around(0, min_num=0, max_num=1, _range=4, on_fail_no_error=True)) # range(-1, 1)
print(get_numbers_around(0, min_num=0, max_num=1, _range=4)) # ValueError

I think it is possible to optimize this code but I don't know how. Does anoyne have any idea?


texts: Jon Bentley's bitmap sort implementation

texts:
I've implemented Jon Bentley's bitmap sorting algorithm from Column 1 of his Programming Pearls book. This code supports user-defined integer range (works from Integer.MIN_VALUE to Integer.MAX_VALUE), but for now only works on a distinct set of integers.

In order to avoid overflow in the integer arithmetic, I use type-casting for intermediate results.

For anyone interested, I've also posted the full description of the algorithm and performance analysis here.

public int[] sortDistinctIntegers(int[] a, int min, int max){

    int N = (int)(((long)max-min) / 8 + 1);
    byte[] bitmap = new byte[N];

    for(int i = 0; i < a.length; i++)
        bitmap[(int)(((long)a[i]-min)/8)] |= 1 << (int)(((long)a[i]-min) % 8);

    int k = 0;
    for(int i = 0; i < N; i++){
        for(int j = 0; j < 8; j++){
            if((bitmap[i] & (1 << j)) > 0){
                a[k] = i * 8 + j + min;
                k++;
            }
        }
    }

    return a;
}

I was wondering if anyone has any comments or ideas on how to improve this code (in terms of prettification, readability and performance).


texts: Collect distances from 1 point to all others in a graph

texts:
Problem:
I have a weighted graph. I want to get distance from definite point to all other points in the graph.(and then get path to them)
I used modified dijkstra algorithm
So, here is code:
var get_path = function(graph, a) {
// declaration
let cache, i, v, queue, node, links, root,
    j, link, c, n, d, max, w, L = graph.length;

// initialization
cache = Array(L);
i = L;
while (--i >= 0) {
    v = graph[i];
    cache[v.id] = {
        id: v.id,
        distance: Infinity,
        links: v.links,
        prev: null,
    };
}
root = cache[a];
root.distance = 0;
queue = [root];

// processing
i = 0;
while (i < queue.length) {
    node = queue[i];
    links = node.links;
    j = links.length;
    while (--j >= 0) {
        link = links[j];
        c = cache[link.id];
        d = node.distance + link.weight;
        if (d < c.distance) {
            c.prev = node;
            c.distance = d;
            queue.push(c);
        }
    }
    i++;
}

return cache;
}

Graph format is:
graph = [
  {
    id: 1,
    links: [
      {
        id: 2,
        weight: 1,
      },
      {
        id: 3,
        weight: 1,
      },
    ],
  },
  {
    id: 2,
    links: [
      {
        id: 1,
        weight: 1,
      },
      {
        id: 4,
        weight: 2,
      }
    ]
  },
  {
    id: 3,
    links: [
      {
        id: 1,
        weight: 1,
      },
      {
        id: 4,
        weight: 3,
      }
    ]
  },
  {
    id: 4,
    links: [
      {
        id: 2,
        weight: 2,
      },
      {
        id: 1,
        weight: 1,
      },
      {
        id: 3,
        weight: 3,
      },
      {
        id: 5,
        weight: 1,
      }
    ]
  },
  {
    id: 5,
    links: [
      {
        id: 4,
        weight: 1,
      }
    ]
  }
]

Performance:
In my PC this algorithm works with graph of ~160 vertices and ~350 edges about 0.03-0.06ms. But I need faster!
You can measure performance on your PC here
Question:
How to make this code (function get_path()) faster? Is it possible on JavaScript? If I should change the format of graph to make algorithm faster it's not a problem.

Or I exhausted possibilities of JavaScript?


texts: JavaScript client using a REST API to edit a playlist

texts:
I wrote some Javascript code today to interface with a restful Rails app which I thought was rather awkward & took me far too long to write.

getAll(id).then((existingPlaylists) => {
for (var i = 0; i < newPlaylists.length; i++) {
  if (existingPlaylists[i] && existingPlaylists[i].id) {
    put(id, existingPlaylists[i].id, newPlaylists[i])
  } else {
    post(id, newPlaylists[i])
  }
}
if (existingPlaylists.length > newPlaylists.length) {
  for (var j = newPlaylists.length; j < existingPlaylists.length; j++) {
    del(id, existingPlaylists[j].id)
  }
}

Ideally whatever was at that API endpoint, https://example.com/video/${id}/playlists/ would be replaced by newPlaylists. But here with this API I am supposed to PUT on existing entries, POST to create and DELETE any that left in the old. Is this typical end point or have I missed some paradigm for updating this Restful endpoint?

Sorry the API is a black box to me, but perhaps I could encourage the back end developers to implement something (a batch operation pattern?) to reduce the diffing complexity on my client side?


texts:
I wrote a minimalistic thread pool using some C++11 features. I've used it on two projects so far and it has worked fine, but when I ran the code on my laptop, I believe that my thread pool might be entering some kind of dead-locked state -- occasionally the CPU activity drops to almost nothing, and the program hangs.

What are your opinions on the code?

My header file:

#include <utils/Uncopyable.h>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <functional>

/// \brief Use this class to run tasks in parallel.
class ThreadPool : private Uncopyable {
public:
    ThreadPool();
    ThreadPool( size_t threads );
    ~ThreadPool();

    /// \brief Initialize the ThreadPool with a number of threads.
    /// This method does nothing if the thread pool is already running,
    /// i.e. ThreadPool( size_t ) was called.
    void initializeWithThreads( size_t threads );

    /// \brief Schedule a task to be executed by a thread immediately.
    void schedule( const std::function<void()>& );

    /// \brief a blocking function that waits until the threads have processed all the tasks in the queue.
    void wait() const;

private:
    std::vector<std::thread>            _workers;
    std::queue<std::function<void()>>   _taskQueue;
    std::atomic_uint                    _taskCount;
    std::mutex                          _mutex;
    std::condition_variable             _condition;
    std::atomic_bool                    _stop;
};

And my implementation is as follows:

#include <utils/ThreadPool.h>
#include <chrono>

ThreadPool::ThreadPool()
    :   _workers(),
        _taskQueue(),
        _taskCount( 0u ),
        _mutex(),
        _condition(),
        _stop( false ) {}

ThreadPool::ThreadPool( size_t threads ) : ThreadPool() {
    initializeWithThreads( threads );
}

ThreadPool::~ThreadPool() {
    _stop = true;
    _condition.notify_all();
    for ( std::thread& w: _workers ) {
        w.join();
    }
}

void ThreadPool::initializeWithThreads( size_t threads ) {
    for ( size_t i = 0; i < threads; i++ ) {
        //each thread executes this lambda
        _workers.emplace_back( [this]() -> void {
            while (true) {
                std::function<void()> task;
                {   //acquire lock
                    std::unique_lock<std::mutex> lock( _mutex );
                    _condition.wait( lock, [this]() -> bool {
                        return !_taskQueue.empty() || _stop;
                    });

                    if ( _stop && _taskQueue.empty() ) {
                        return;
                    }

                    task = std::move( _taskQueue.front() );
                    _taskQueue.pop();
                }   //release lock
                task();
                _taskCount--;
            }   //while
        });
    }   //for
}

void ThreadPool::schedule( const std::function<void()>& task ) {
    {
        std::unique_lock<std::mutex> lock( _mutex );
        _taskQueue.push( task );
    }
    _taskCount++;
    _condition.notify_one();
}

void ThreadPool::wait() const {
    while ( _taskCount != 0u ) {
        std::this_thread::sleep_for( std::chrono::microseconds(1) );
    }
}


texts:
I'm looking for advice on how I could improve this. I'm using VS2015 to compile so whatever language features are supported in there is fair game!

Problem: Create a program that reads a username and a password from
the user and grants access if that username and password exists in
code. Bonus points for storing the possible usernames in a file like
so:
user1,pass
user2,pass
...

Encryption is not really a concern; I'm just getting the hang of things. Points I'd like to improve:

I'm using a placeholder vector for the user input, initialized with empty strings. It feels like there would be a more elegant way to get user input without using a holding variable?

I imagine there's a more elegant way to go through each line of the file too, again, lots of placeholder variables for data I could process in place I think.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

// Extract the contents of a user file for processing.
vector<string> get_user_list(ifstream& userfile)
{
    string line;
    vector<string> userlist;

    if (userfile.is_open())
    {
        while (getline(userfile, line))
            userlist.push_back(line);

        userfile.close();
    }
    else
        cout << "Couldn't read from file.";

    return userlist;
}

// Go through each line of the user list and extract a comma
// seperated username and pass; match against the supplied
// username and pass.
bool check_pass(vector<string> tomatch, vector<string> userlist)
{
    string fuser, fpass;
    bool match = false;

    for (string uline : userlist)
    {
        for (size_t i = 0; i < uline.size(); i++)
        {
            if (uline[i] == ',')
            {
                fuser = uline.substr(0, i);
                fpass = uline.substr(i + 1, string::npos);
                break;
            }
        }

        if (tomatch[0] == fuser && tomatch[1] == fpass)
        {
            match = true;
            break;
        }
    }

    return match;
}

int main()
{
    ifstream userfile("data/users.txt");
    vector<string> userlist = get_user_list(userfile);
    vector<string> input = { "", "" };

    cout << "Enter your username followed by your pass: ";
    cin >> input[0] >> input[1];

    if (check_pass(input, userlist))
        cout << "ACCESS GRANTED" << endl;
    else
        cout << "ACCESS DENIED" << endl;

    return 0;
}


texts: How to increase efficiency of recursion algorithm?

texts:
The question is:

Given a non-negative int n, compute recursively (no loops) the count
of the occurrences of 8 as a digit, except that an 8 with another 8
immediately to its left counts double, so 8818 yields 4. Note that mod
(%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/)
by 10 removes the rightmost digit (126 / 10 is 12).
count8(8) → 1 count8(818) → 2 count8(8818) → 4

My solution looked something like this:
public int count8(int n) {
  if(n == 0)  return 0;

  int faith = count8(n/10);
  int c = 0;
  if(n%10 == 8){
    n /= 10;
    if(n%10 == 8){
      c++;
    }
    c++;
  }
  return c + faith;
}

Is there any way I can remove the multiple if conditions and make this cleaner and more efficient?


texts: Finding the closest point to a list of points

texts:
I'm trying to find the closest point (Euclidean distance) from a user-inputted point to a list of 50,000 points that I have. Note that the list of points changes all the time. and the closest distance depends on when and where the user clicks on the point.

#find the nearest point from a given point to a large list of points

import numpy as np

def distance(pt_1, pt_2):
    pt_1 = np.array((pt_1[0], pt_1[1]))
    pt_2 = np.array((pt_2[0], pt_2[1]))
    return np.linalg.norm(pt_1-pt_2)

def closest_node(node, nodes):
    pt = []
    dist = 9999999
    for n in nodes:
        if distance(node, n) <= dist:
            dist = distance(node, n)
            pt = n
    return pt

a = []
for x in range(50000):
    a.append((np.random.randint(0,1000),np.random.randint(0,1000)))

some_pt = (1, 2)

closest_node(some_pt, a)


texts: Collection-like classes in Java - taking advantage of varargs

texts:
I quite often need to implement collection-like classes and - to make using them more comfortable - would like to take advantage of a constructor with variable arguments.

The following implementation does not work, though.

class FruitsStore
{
    private List<String> availableFruits;

    public FruitsStore(String... fruits)
    {
        this.availableFruits = Arrays.asList(fruits);
    }

    public void add(String fruit)
    {
        this.availableFruits.add(fruit);
    }

    ...
}

The following code snippet

FruitsStore store = new FruitsStore("banana", "melon");
store.add("orange");

throws the following exception

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(Unknown Source)
    at java.util.AbstractList.add(Unknown Source)
    at cz.dusanrychnovsky.FruitsStore.add(FruitsStore.java:26)
    at cz.dusanrychnovsky.FruitsStore.main(FruitsStore.java:12)

To overcome this issue, I use a constructor like this:

public FruitsStore(String... fruits)
{
    this.availableFruits = new LinkedList<String>(Arrays.asList(fruits));
}

This compiles and works fine.

Is this a good coding practice? Does it have any drawbacks? What implementation would you suggest?


texts:
Is there a better way of creating this terminal animation without having a series of conditional statements (i.e. if ... elif ... elif...)?

import sys, time
count = 100
i = 0
num = 0

def animation():
    global num
    if num == 0:
        num += 1
        return '[=      ]'
    elif num == 1:
        num += 1
        return '[ =     ]'
    elif num == 2:
        num += 1
        return '[  =    ]'
    elif num == 3:
        num += 1
        return '[   =   ]'
    elif num == 4:
        num += 1
        return '[    =  ]'
    elif num == 5:
        num += 1
        return '[     = ]'
    elif num == 6:
        num += 1
        return '[      =]'
    elif num == 7:
        num += 1
        return '[      =]'
    elif num == 8:
        num += 1
        return '[     = ]'
    elif num == 9:
        num += 1
        return '[    =  ]'
    elif num == 10:
        num += 1
        return '[   =   ]'
    elif num == 11:
        num += 1
        return '[  =    ]'
    elif num == 12:
        num += 1
        return '[ =     ]'
    elif num == 13:
        num = 0
        return '[=      ]'

while i < count:
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation())
    sys.stdout.flush()
    time.sleep(0.2)


texts:
I am trying to learn by doing. Here is the first problem that I have solved. I have actually not done it perfectly. The table header should cover both the text and the image but it is only above text. If you can help me out with the design I will be thankful.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

Food you love to eat

                I love eating food . All types of food are good for health. I like fruits in them. Fruits are good for health.


texts:
The destruction of the objects are handled by the garbage-collector metamethod.
(Does this make sense? This means that an out-of-scope object will stay visible in game until garbage collection.)

The components of the Entity Component System are not pure-data members,
but instead derived classes of a specific base class. (For example Renderable for all renderable objects, Transformable for all movable objects.)
Because of this it's not a conventional ECS, but more like a OO + ECS, but up to now it works wonders for me.

I am concerned about the use of design patterns, about the ease-of-use of the API, its scalability and error-proneness.

-- All initing must be done here
function init( instance ) -- the parameter is the engine api
    -- Save API into Engine variable for later use
    Engine = instance

    -- Create separate apis for accessing different parts of engine using the
    -- Engine passed to us
    -- And make them all global for further use.

    -- ECS - Entity component system interaction.
    ECS = Engine:CreateECSAPI()

    -- Graphics interaction.
    Graphics = Engine:CreateGraphicsAPI()

    -- Input handling.
    Input = Engine:CreateInputAPI()

    -- Setup mouse callback
    Input:AddMouseCallback( "OnMouse" )

    -- Get index of the forward renderable component.
    ForwardComponent = ECS:GetComponentIndex( "renderable_forward" )

    -- Create text with given text and font size.
    Text = Graphics:CreateTextObject( "The quick brown fox is lazy.", 40 )
    Text:SetColor( { 1, 1, 1 } )
    Text:SetPosition( { 0, 0.5 } )

    -- Create a fullscreen rectanlge as background.
    Rect = Graphics:CreateRectangle( { 1.0, 1.0 } )
    Rect:SetSize( { 2.0, 2.0 } )
    Rect:SetPosition( { 0.0, 0.0 } )

    -- Entity must be created for anything to be processed by the engine.
    -- Processed can mean rendered/updated/simulated/synchronized.
    TextEntity = ECS:CreateEntity()
    RectEntity = ECS:CreateEntity()

    -- To render something in 2D we must add a renderable to its
    -- renderable_forward component.
    TextEntity:SetComponent( ForwardComponent, Text )
    RectEntity:SetComponent( ForwardComponent, Rect )

    -- Current time
    Time = 0

    Clicks = { "next" = 1 }

end

-- If we click, it places a "Click" text there.
function OnMouse( type, x, y )
    if type == Input.Button then
        local entity = ECS:CreateEntity()
        local textobject = Graphics:CreateTextObject( "Click" )
        textobject:SetPosition( { x, y } )

        entity:SetComponent( ForwardComponent, textobject )

        local next = Clicks["next"]
        Clicks[next] = { entity, textobject }
        Clicks["next"] = next + 1
    end
end

--Called each frame
--dt is the time since last update in seconds.
--use it for frame-independent movement
function update( dt )

    -- Save current time by storing the time elapsed.
    Time = Time + dt
    local s = math.sin( Time )
    Rect.SetColor( { s, s, s } )

end


texts: Swift format string with separator every n characters where n changes

texts:
In Swift I have a string where a dash needs to be inserted after every 3 characters, if there are 4 characters or 2 characters at the end of the string they should be shown as "-xx-xx" or "-xx" respectively.

E.g "203940399345" to "203-940-399-345"
    "2039403993454" to "203-940-399-34-54"
    "20394039934546" to "203-940-399-345-46"
    "2039403993454699409399" to "203-940-399-345-469-940-93-99"

I have the following solution:

func format(_ unformatted:String) -> String {

  var formatted = ""
  let count = unformatted.characters.count

  unformatted.characters.enumerated().forEach {
    if $0.offset % 3 == 0 && $0.offset != 0 && $0.offset != count - 1 || $0.offset == count - 2 && count % 3 != 0 {
      formatted += "-" + String($0.element)
      return
    }
    formatted += String($0.element)
    return
  }
  return formatted
}

It will add a dash before each third char unless it is the first or last char or it is two from the end but only if the char count is divisible by 3 then it adds a char to the formatted string as normal.

Is there a more optimal way to achieve this formatting? What approach should I be taking with this kind of problem?


texts:
I've always been told "never use goto, there's always a better way" and for the longest time I just accepted it. Lately though, I've been running into such scenarios in which I have to repeat this bit of code every time I return early.

I personally hate repeating myself, even the littlest bit of code. So I ask, Is this use of goto really that bad? It prevents me from having to write that bit of code 3 times and sure, theoretically I could write some guard clauses (that could be combined into a single guard clause) that prevents the need for the try/catch and therefore having a single place for that bit of code, but would that actually be more readable?

public static IQueryable<T> Sort<T>(this IQueryable<T> query, String field, String direction, Expression<Func<T, Int32?>> defaultSort = null)
{
    if (String.IsNullOrWhiteSpace(field)) { goto FAILED; }

    try
    {
       // Dynamic LINQ - Field: "SomeProperty.OptionalProperty", Direction: "Desc" or "Asc"
        query = query.OrderBy(String.Format("{0} {1}", field, direction));
    }
    // NOT FOUND: Field wasn't found just return the original query.
    catch (NullReferenceException)
    {
        goto FAILED;
    }
    // NOT FOUND: Field wasn't found just return the original query.
    catch (ParseException)
    {
        goto FAILED;
    }

    return query;

    // SOMETHING FAILED: Return the original query with the optionally supplied default sort.
    FAILED:
        if (defaultSort != null)
        {
            query = query.OrderBy(defaultSort);
        }
        return query;
}


texts: Assigning book ids to certain students on registration of a new student

texts:
I have a function where I am trying to assign book ids to certain students on registration of a new student.

FOR book_id IN
   SELECT a.bookid
   FROM  books a
   WHERE  a.isdelete = false and published = true

LOOP
IF NOT EXISTS (select 1 from studentbooks where  bookid = book_id and  studentid = id) THEN
     INSERT INTO studentbooks(bookid, studentid) values (book_id::uuid, id );
END IF;

END LOOP;

I wrote something like this and it works fine for smaller set of data and under performs when we have more books to loop through. I just wanted a have a review here.


texts: Python vs Java performace: brute force equation solver

texts:
I wrote a program in Python and in Java to search for the smallest integer solution of the equation:

$$a^5+b^5+c^5+d^5=e^5$$

(expected output is \$133^5 + 110^5 + 84^5 + 27^5 = 144^5\$)

Powers and roots are either computed directly ("direct calculation" method) or computed and stored in an array ("power lookup" method). Fifth powers are looked up like n5 = fifth_power[n]. Fifth power root is computed using a binary search in array 'fifth_power`.

I am running it on NetBeans if it matters. It takes:

30 s (Python, direct)
20 s (Python, lookup)
5.6 s (Java, direct)
0.8 s (Java, lookup)

Is there a way to boost Python performance? I am not looking for better math (sieving of some kind). I am looking for better implementation of "for each combination of a,b,c,d compute some of their powers, check if the sum is a perfect power. If it is - print the result".

Is it expected that Python runs some 20 times slower than Java?

Python 3.5

from array import *
import math
import time

#PYTHON, BRUTEFORCE : ~30 s
millis1 = int(round(time.time() * 1000))
keep_searching = True
a=1
result=""
while(keep_searching):
    a+=1
    for b in range(1,a+1):
        for c in range(1,b+1):
            for d in range(1,c+1):
                sum=math.pow(a,5)+math.pow(b,5)+math.pow(c,5)+math.pow(d,5)
                root = math.pow(sum,0.2)
                e = round(root)

                e5 = math.pow(e,5)

                if(e5==sum):
                    result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(int(a),int(b), int(c),int(d), int(e))
                    keep_searching = False
                    millis2 = int(round(time.time() * 1000))

print(result)
print("Found solution in {} ms".format(millis2-millis1))

#PYTHON, PRECOMPUTE POWERS: ~20 s
millis3 = int(round(time.time() * 1000))
#fifth_power #175 is enough
size=176
fifth_power = [None] * size
for i in range(size):
    fifth_power[i]=long(math.pow(i,5))

millis4 = int(round(time.time() * 1000))

#returns  value if it is a perfect power (32 returns 2)
#returns -1 if between perfect powers, -2 if greater than max value in array, -3 if smaller than min value in array

def check_perfect_power(number, min, max, fifth_power):

    current=int((min+max)/2)
    while(max>=min):
        if(number==fifth_power[current]):
            return current
        elif(number>fifth_power[current]):
            min=current+1
            current=int((max+min)/2)
        else:
            max=current-1
            current=int((max+min)/2)

    if(min>=len(fifth_power)):
        return -2
    if(max<0):
        return -3

    return -1

keep_searching = True
a=0
result=""
while(keep_searching):
    a+=1
    for b in range(1,a+1):
        for c in range(1,b+1):
            for d in range(1,c+1):
                mymax=min(int(a*1.32)+1, size-1)
                e=check_perfect_power(fifth_power[a]+fifth_power[b]+fifth_power[c]+fifth_power[d], a, mymax, fifth_power)
                if(e>0):
                    result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(int(a),int(b), int(c),int(d), int(e))
                    keep_searching = False
                    millis5 = int(round(time.time() * 1000))

print(result)
print("Populated in {} ms, find solution in {} ms".format(millis4-millis3,millis5-millis4))


texts: Using JavaScript promises to display weather and location information

texts:
This is the first time I'm trying to use promises in JavaScript so I'm not sure if I have done it correctly, but it seems to work. The problem is that I have ended up with a "nested when" and it doesn't look that great. There probably is a nicer solution out there. I would really appreciate some feedback on how I can improve my code.

I am using the navigator.geolocation to get the position and then I'm using two different APIs to get the current weather and the address of the location.

What I would like it to look like would be something like:

$.when(getPosition())

.then(getWeather(position),getLocationName(position))

.done(displayWeather);

But it doesn't seem to work with two calls in then() like you can have in when().

This is my current solution:

var displayWeather = function(weatherData, locationData) {

  $('#userLocation').text(locationData.results[3].formatted_address);

  $('#weatherDescription').text(weatherData.currently.temperature);

  $('#temperature').text(weatherData.currently.summary);

}

var getPosition = function() {

  var deferred = $.Deferred();

  navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject);

  return deferred.promise();

};

var getWeather = function(position) {

  return $.getJSON('https://api.forecast.io/forecast/{APIKEY}/' + position.coords.latitude + ',' + position.coords.longitude + '?callback=?')
     .then(function(data) {
        return data;
    });

}

var getLocationName = function(position) {

  return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&key={APIKEY}')
    .then(function(data) {
        return data;
  });

}

$(document).ready(function() {

  $.when(getPosition())

    .done(function(position) {

      $.when(getWeather(position), getLocationName(position)).done(displayWeather);

    });

});


texts: Is this the correct approach to animation in Java?

texts:
I was fiddling with animation in Java and wrote this:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

class Main extends JFrame implements ActionListener {
    private Timer timer = new Timer(500, this);

    private Image mario1 = new ImageIcon("C:/Users/User/workspace/Game Development/src/mario.jpg").getImage();
    private Image mario2 = new ImageIcon("C:/Users/User/workspace/Game Development/src/mario2.jpg").getImage();
    private int counter = 0;
    private ArrayList<Image> scenes = new ArrayList<Image>();

    public Main() {
        setSize(500, 500);
        setVisible(true);

        addScene(mario1);
        addScene(mario2);
        timer.start();
    }

    public void actionPerformed(ActionEvent e) {
        nextScene();
    }

    public void addScene(Image image) {
        scenes.add(image);
    }

    public void nextScene() {
        counter++;
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (!(counter < 0 || counter >= scenes.size())) g.drawImage(scenes.get(counter), 100, 100, null);
    }

    public static void main(String[] args) {
        new Main();
    }
}

Is this the correct approach or is this just bad practice?


texts: Implementation of Dijkstra's algorithm to find the shortest path in graph

texts:
This is my implementation of Dijkstra's algorithm in C++.

Please clarify

Whether the class design is proper or if it needs to be improved.
I am just hard coding the vertex based on the priority of the vertex. Is there is any other way to implement it?
Please provide some suggestions to optimize the code.

class Vertex
{
public:
    int m_id;
    unsigned int m_cost;
    bool m_isVisited;

    std::map<int,unsigned int> m_edgeList; // map to store neighbour nodes and cost to reach them

    void findMinDistance(std::vector<Vertex>&);

    Vertex(int p_id)
    {
        m_id= p_id;
        if(p_id == 0)
        {
            m_cost=0;
        }
        else
        {
            m_cost=UINT_MAX; // Assigning Infinite cost
        }
        m_isVisited=false;
    }

    Vertex()
    {
    }
};

void Vertex::findMinDistance(std::vector<Vertex> &p_vertex)
{

    m_isVisited= true;
    // Looping throgh the neighbour list and update cost
    for(std::map<int,unsigned int>::iterator iter = m_edgeList.begin();
        iter!=m_edgeList.end(); iter++)
    {
        //If cost of picked neighbour is greater than current_vertex+new cost then replace cost
        if ( p_vertex.at(iter->first).m_isVisited == false && p_vertex.at(iter->first).m_cost > m_cost+(iter->second))
        {
            p_vertex.at(iter->first).m_cost=m_cost+iter->second;

            std::cout<<"\nVertex Id : "<<p_vertex.at(iter->first).m_id;
            std::cout<<"\nExisting Cost  : "<<p_vertex.at(iter->first).m_cost;
            std::cout<<"\nNew Cost : "<<p_vertex.at(iter->first).m_cost;
        }
    }
}

int main()
{
    std::vector<Vertex> l_vertex;

    for(int i=0; i<7;i++)
    l_vertex.push_back(Vertex(i)); // Push Vertex to vector container

    // updating the edges and cost to respective node
    // The below model is similar to priority queue.

    l_vertex.at(0).m_edgeList.insert(std::make_pair((l_vertex.at(5).m_id),14));
    l_vertex.at(0).m_edgeList.insert(std::make_pair((l_vertex.at(2).m_id),9));
    l_vertex.at(0).m_edgeList.insert(std::make_pair((l_vertex.at(1).m_id),7));

    l_vertex.at(1).m_edgeList.insert(std::make_pair((l_vertex.at(0).m_id),7));
    l_vertex.at(1).m_edgeList.insert(std::make_pair((l_vertex.at(2).m_id),10));
    l_vertex.at(1).m_edgeList.insert(std::make_pair((l_vertex.at(3).m_id),15));

    l_vertex.at(2).m_edgeList.insert(std::make_pair((l_vertex.at(0).m_id),9));
    l_vertex.at(2).m_edgeList.insert(std::make_pair((l_vertex.at(5).m_id),2));
    l_vertex.at(2).m_edgeList.insert(std::make_pair((l_vertex.at(3).m_id),11));
    l_vertex.at(2).m_edgeList.insert(std::make_pair((l_vertex.at(1).m_id),10));

l_vertex.at(5).m_edgeList.insert(std::make_pair((l_vertex.at(0).m_id),14));
l_vertex.at(5).m_edgeList.insert(std::make_pair((l_vertex.at(2).m_id),2));
l_vertex.at(5).m_edgeList.insert(std::make_pair((l_vertex.at(4).m_id),9));

l_vertex.at(4).m_edgeList.insert(std::make_pair((l_vertex.at(5).m_id),9));
l_vertex.at(4).m_edgeList.insert(std::make_pair((l_vertex.at(3).m_id),6));

l_vertex.at(3).m_edgeList.insert(std::make_pair((l_vertex.at(4).m_id),6));
l_vertex.at(3).m_edgeList.insert(std::make_pair((l_vertex.at(2).m_id),11));
l_vertex.at(3).m_edgeList.insert(std::make_pair((l_vertex.at(1).m_id),15));

// updating cost of each vertex by calling findMinDistance

for(std::vector<Vertex>::iterator iter = l_vertex.begin(); iter != l_vertex.end(); iter++)
{
    (*iter).findMinDistance(l_vertex);
}

for(int i=0;i<6;i++)
std::cout<<"\n\nshortest "<<i<<" "<<l_vertex.at(i).m_cost;

return 0;
}


texts: Raspberry PI controllable car (code for a 6-year old)

texts:
I've been trying to show my 6-year old daughter a way to build and create a simple toy car. We've got a 4-motor chassis kit, Raspberry PI and a motozero shield that can operate these 4 motors. We've put a power bank and a separate battery for the motors:

                                              (The green light on the right is the traffic light)

Now, as far as coding goes, I've created a simple Car class with forward, backward, forward_left, forward_right, backward_left and backward_right actions. For the demonstration purposes mostly, I've tried to be explicit and violated the DRY principle a lot.

I've also initialized an endless loop listening for keyboard inputs - F would be for forward, B for backwards and S for stop (have not decided which keys would go for those "left-ish" and "right-ish" actions yet).

from RPi import GPIO
from gpiozero import Motor, OutputDevice

class Car:
    def __init__(self):
        self.front_right = Motor(forward=24, backward=27)
        self.front_left = Motor(forward=6, backward=22)

        self.rear_right = Motor(forward=13, backward=18)
        self.rear_left = Motor(forward=23, backward=16)

        OutputDevice(5).on()
        OutputDevice(17).on()
        OutputDevice(25).on()
        OutputDevice(12).on()

    def forward(self):
        self.front_right.forward()
        self.front_left.backward()

        self.rear_right.backward()
        self.rear_left.backward()

    def backward(self):
        self.front_right.backward()
        self.front_left.forward()

        self.rear_right.forward()
        self.rear_left.forward()

    def backward_right(self):
        self.front_right.backward(1)
        self.front_left.forward(1)

        self.rear_right.forward(1)
        self.rear_left.forward(0.2)

    def backward_left(self):
        self.front_right.backward(1)
        self.front_left.forward(1)

        self.rear_right.forward(0.2)
        self.rear_left.forward(1)

    def forward_left(self):
        self.front_right.forward()
        self.front_left.backward(0.2)

        self.rear_right.backward(1)
        self.rear_left.backward(1)

    def forward_right(self):
        self.front_right.forward(0.2)
        self.front_left.backward(1)

        self.rear_right.backward(1)
        self.rear_left.backward(1)

    def stop(self):
        self.front_right.stop()
        self.front_left.stop()

        self.rear_right.stop()
        self.rear_left.stop()

if __name__ == '__main__':
    GPIO.setwarnings(False)
    GPIO.cleanup()

    commands = {
        "f": "forward",
        "b": "backward",
        "s": "stop"
    }
    try:
        car = Car()

        while True:
            command = raw_input()
            getattr(car, commands[command])()
    finally:
        try:
            GPIO.cleanup()
        except:  # ignore cleanup errors
            pass

(I've also mixed up some motors and pins on the board which led to some motors accepting "backwards" as "forward")

It is, of course, difficult to explain this kind of code to a 6-year old, since she still expects a printer to print something when I show her the Python's print() command, but, how would you change this code to make it more understandable for a kid?

I would also appreciate any points about the code organization and quality since the next step would be to control the car "via Bluetooth".


texts:
Please review the following implementation of heapsort and pay attention to the following:

Have I correctly chosen the names InputIt and BidirIt for my iterators?
Is there a way to make the initialise iterator and then advance it pattern occupy one line instead of two?
Is the it != ix - 1 comparison of iterators ok?

Here is the code:

#include <iterator>
#include <functional>

template<
    class InputIt,
    class Key = std::less_equal<
        std::iterator_traits<InputIt>::value_type
    >
>
void plunge(
    const InputIt ix, // first element of heap
    const InputIt iy, // one-past last element of heap
    const InputIt iz, // element to be plunged
    Key key = Key()   // comparison key to use (up or down)
) {
    auto ii = iz;
    auto il = ix;
    std::advance(il, 2 * std::distance(ix, ii) + 1);

    while (il < iy) {
        auto ir = il + 1;

        auto it = ir < iy && key(*ir, *il) ? ir : il;

        if (key(*ii, *it)) {return;}

        std::iter_swap(ii, it);
        std::     swap(ii, it);

        il = ix;
        std::advance(il, 2 * std::distance(ix, ii) + 1);
    }
}

template<
    typename BidirIt,
    typename Key = std::greater_equal<
        std::iterator_traits<BidirIt>::value_type
    >
>
void heapsort(const BidirIt ix, const BidirIt iy, Key key = Key()) {
    auto it = ix;
    std::advance(it, std::distance(ix, iy) / 2);

    for (; it != ix - 1; --it) {
        plunge(ix, iy, it, key);
    }

    for (it = iy - 1; it != ix - 1; --it) {
        std::iter_swap(ix, it);
        plunge(ix, it, ix, key);
    }
}


texts: Console application for providing detailed error messages

texts:
I'm writing a console application where I need to provide detailed error messages in case anything goes wrong. As a result of this, I find myself splitting up my code into many pieces and making sure that every step is handled correctly. While this certainly makes it possible to detail what exactly went wrong, it unfortunately also leads some horrific overhead on my code. Take the following code for example:

        // Open the SISS catalog on the server
        Catalog catalog = integrationServices.Catalogs[catalogName];
        if (catalog == null)
        {
            Console.WriteLine("Unable to open the SSIS catalog : " + catalogName
                + ", it does not exist on the server");
            return (int)ExitCode.Failure;
        }

        // Open the folder in the catalog
        CatalogFolder folder = catalog.Folders[folderName];
        if (folder == null)
        {
            Console.WriteLine("Unable to open the folder : " + folderName
                + ", it does not exist on the server");
            return (int)ExitCode.Failure;
        }

        // Open the project in the folder
        ProjectInfo projectInfo = folder.Projects[projectName];
        if (projectInfo == null)
        {
            Console.WriteLine("Unable to open the project : " + projectName
                + ", it does not exist on the server");
            return (int)ExitCode.Failure;
        }

        // Check if the package exists
        if (!projectInfo.Packages.Contains(packageName))
        {
            Console.WriteLine("Unable to open the package : " + packageName
                + ", it does not exist on the server");
            return (int)ExitCode.Failure;
        }

Is there any way I can make this more pretty?


texts: Python: Making bowling algorithm more pythonic

texts:
So I created an algorithm that keeps score of the amount of pins knocked down per frame. Since I am totally self taught, I am trying to see how I could make my code more efficient/more pythonic. Any advice would help. Also, is it proper to return a score or list into the init method as I did with the "overall" variable? Thanks.

class Bowling_player(object):

    def __init__(self, name, overall = 0):
        self.name = name
        self.overall = overall

    def frames(self):
        shot_one = int(input('how many pins on first shot:'))
        if shot_one == 10: # this is a strike
            shot_two_after_strike = int(input('how many pins on shot after strike:'))
            if shot_two_after_strike == 10: # you got another strike. continue the frame!
                shot_three_after_strike = int(input('how many pins on shot after two strikes:'))
                self.overall += (shot_three_after_strike + shot_two_after_strike + shot_one)
                return self.overall
            else:# you did not get another strike, frame over.
                self.overall += (shot_one + shot_two_after_strike)
                return self.overall

        elif shot_one < 10:
            shot_two = int(input('how many pins on second shot:'))
            shots = shot_one + shot_two
            if shots == 10: # this is a spare
                shot_three_after_spare = int(input('how many pins on shot after spare'))
                self.overall += (shots + shot_three_after_spare)
                return self.overall
            else: # you suck at bowling
                self.overall += shots
                return self.overall

craig = Bowling_player('craig')

craig.frames()


texts: Weather application data structures and design

texts:
Relevant files are script.ts, WeatherData.ts, index.html.

I made a simple weather 5-day forecast application using mainly TypeScript. I was wondering how I can improve my code since I originally wanted to use a data structure that I created called a "WeatherData" to store my information about the weather for each day of the week.

GitHub project

WeatherData data structure

export class WeatherData {
    date: string;
    city: string;
    country: string;
    temperature: number;
    minTemperature: number;
    maxTemperature: number;
    weather: any;
    weatherIcon: any;
}

TypeScript file concerns

The main concerns I have about the TypeScript files (script.ts, WeatherData.ts) is the fact that halfway through making my project, I realized that I didn't actually need to use a WeatherData data structure. This led to me passing in WeatherData variables in functions as well as returning WeatherData variables from functions that don't actually need to return it.

Is there a more object-oriented way I should be approaching my script.ts class in order to use data structures?
Will using a WeatherData data structure be better?
How can I format my code (maybe different classes?) such that all the functions aren't all clumped together?

HTML file concerns

First time ever making a front-end UI using HTML and I don't know what areas I should refactor. I noticed I have a lot of repeated element tags such as:

Day 0

month-day 0

Forecast

Current

Max

Min

I have 5 of these (one for each day).

Screenshot of what the UI looks like:

What type of suggestions are there to making my UI look better? I was thinking of making the jumbotron element a different color.


texts: Counting from 0 to a number and back to zero, and space-padding the result to be a given length

texts:
I completed a task: The objective was to create a method with 2 arguments: a number to count to, and how many char/numbers in the resulting string.

Result: Let's say that "number" is 5, so it will count: 01234543210 BUT it will also add spaces to the sides to complete the 2nd requirement "lenght", so if long is 15, the result would be " 01234543210 " with 2 spaces to each side (always same quantity of space each side) So i wrote this piece of code, but other coder told me that he used half the lines I did.

There were many assumptions in the code, like the fact that lenght is > than number or that if number is an odd number, lenght is odd too.

So my question would be, can this code be reduced (refactored?) (I just have one month of experience in Java, so be hard but understanding.)

public static void counter(int number, int lenght) {
    int numberFull=(number*2)+1;
    int spaceFull=lenght-numberFull;
    int space=spaceFull/2;
    for (int a=1;a<=space;++a)
        {System.out.print(" ");}
    for (int x=0;x<=number;x++)
        {System.out.print(x);}
    for (int y=number-1;y>=0;y--)
        {System.out.print(y);}
    for (int b=1;b<=space;++b)
        {System.out.print(" ");}
}


texts: Given a String, return a boolean if it is a number

texts:
Yesterday in an online interview, the interviewer asked me this question:

  If I give you a string, you have to return if a string is number or
  not. You are not allowed to use any parse function available.

This was my first online interview after a long long time, so I took way too much time in this question. I want to gather feedback about my solution and better ideas for the solution to this problem. You can ignore complex numbers for now.

public static boolean isNumber(String toTest) {
    boolean isNegativeFoundAlready = false;
    boolean isDecimalPointFoundAlready = false;
    for (int i=0; i < toTest.length(); i++) {
        if (!"0123456789-.".contains(new String(new char[]{toTest.charAt(i)}))) {
            return false;
        } else {
            if ('-' == toTest.charAt(i) && i != 0) {
                return false;
            }
            if ('-' == toTest.charAt(i) && (i == toTest.length() - 1)) {
                return false;
            }

            if ('-' == toTest.charAt(i) && isNegativeFoundAlready) {
                return false;
            }
            if ('-' == toTest.charAt(i)) {
                isNegativeFoundAlready = true;
            }
            if ('.' == toTest.charAt(i) && isDecimalPointFoundAlready) {
                return false;
            }
            if ('.' == toTest.charAt(i)) {
                isDecimalPointFoundAlready = true;
            }
            if ('.' == toTest.charAt(i) && (i == toTest.length() - 1)) {
                return false;
            }
        }
    }
    return true;
}

Test cases I ran:

    System.out.println("123 isNumber? " + isNumber("123"));
    System.out.println(".123 isNumber? " + isNumber(".123"));
    System.out.println("-.123 isNumber? " + isNumber("-.123"));
    System.out.println("-. isNumber? " + isNumber("-."));
    System.out.println(".- isNumber? " + isNumber(".-"));
    System.out.println("23.34.545 isNumber? " + isNumber("23.34.545"));
    System.out.println("- isNumber? " + isNumber("-"));
    System.out.println("-0 isNumber? " + isNumber("-0"));
    System.out.println("12$%^&*# isNumber? " + isNumber("12$%^&*#"));


texts:
I wrote a small "game" in Python for practice. I would like if someone could go over it and tell me if there is anything wrong or if there are any improvements I can make.

import time
import sys
class Creature:
    def __init__(self, name, hp, inventory):
        self.name = name
        self.hp = hp
        self.inventory = inventory
    def get_hp(self):
        return self.hp
    def get_name(self):
        return self.name
    def get_inventory(self):
        return self.inventory
    def add_item(self, item):
        self.inventory.append(item)
class Item:
    def __init__(self, name, damage, special):
        self.name=name
        self.damage=damage
        self.special=special

staff = Item("heroStaff", 2, "Nothing")
heroinv = [] # Hero inventory
Hero = Creature("A hero",100,heroinv)
print("You wake up in a dark room")
time.sleep(1)
print("1: Sleep more")
print("2: Look around")
key = input()
if key == "1":
    print("You keep sleeping. Good night")
    time.sleep(1)
    print(".")
    time.sleep(1)
    print(".")
    time.sleep(1)
    print(".")
    print("You wake up, feeling restored, you decide to look around")
time.sleep(1.5)
out = False
emptybox = False
door1key=False
while not out:
    print("")
    print("You look around and find a door, a window, and a box")
    time.sleep(1)
    print("1: Check door")
    print("2: Check window")
    print("3: Check box")
    key = input()
    if key == "1":
        time.sleep(0.5)
        print("trying to unlock door")
        time.sleep(1)
        print(".")
        time.sleep(1)
        if not out:
          for items in Hero.get_inventory():
                if items.name == "Door1Key":
                    print("CLICK!")
                    time.sleep(1)
                    print("*Door opened*")
                    time.sleep(1)
                    out = True
                    door1key=True
        if not door1key:
            print("Door Could not be opened")
            time.sleep(1)
    if key=="2":
        print("The window is locked. Can't break it")
        time.sleep(0.5)
    if key=="3":
        if not emptybox:
            time.sleep(0.5)
            print("You open the chest and find a staff(2 damage) and a key, you take them")
            key=Item("Door1Key",0,"Nothing")
            Hero.add_item(key)
            Hero.add_item(staff)
            time.sleep(2)
            emptybox = True
        else:
            print("The box is empty")
            time.sleep(0.5)

print("You step out of the room")
time.sleep(1)
print("You see an infected cat in front of you, with death in his eyes.")
time.sleep(2)
strkill="HE WANTS TO KILL YOU."
for char in strkill:
    if char==' ':
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.5);
    else:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.2);
print("")
time.sleep(1)
print("*Infected cat engages*")


texts: Retrieving all institutions in a specified country

texts:
I'm checking each variable to prevent null exception, but still wondering can this be improve in much simpler and cleaner if you will be writing the same code? Please see the below snippet:

[AjaxOnly]
public ActionResult GetInstitutions(string parent)
{
    if (string.IsNullOrEmpty(parent))
        return Json(string.Empty, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);

    var country = _countryRespository.GetByCountryCode(parent);

    if (country == null)
        return Json(string.Empty, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);

    if (country.Institutions == null || country.Institutions.Count <= 0)
        return Json(string.Empty, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);

    var institutions = country.Institutions
        .OrderBy(i => i.Name)
        .Where(i => !i.Name.Contains("institutiontest1"))
        .Where(i => !i.Name.Contains("institutiontest2"))
        .Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() });

    return Json(institutions, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}

CountryRepository.GetByCountryCode method implementation

public Country GetByCountryCode(string countryCode)
{
    return Session.Query<Country>()
                    .Where(c => c.Iso == countryCode)
                    .FetchMany(c => c.Institutions)
                    .SingleOrDefault();
}


texts:
I'm looking for reviews about my first dockfile. I don't want to develop bad habits.

The purpose is to quickly deploy my Laravel (5.4) application. I'm going to connect it with others database containers (mognodb and mysql).

I used Ubuntu as parent image because it's my development environment but I planned to change it to debian or alpine later.

# Use an official Ubuntu LTS as a parent image
FROM ubuntu:16.04

MAINTAINER name <email>

#================================= Dependencies ================================

# Install dependencies
RUN apt-get -qq update && \
    apt-get -qq install -y --no-install-recommends \
        apache2 \
        composer \
        curl \
        git \
        libapache2-mod-php7.0 \
        libssl-dev \
        libsslcommon2-dev \
        npm \
        php-curl \
        php-dev \
        php-mbstring \
        php-mysql \
        php-pear \
        php-xml \
        php-zip \
        php7.0 \
        phpunit \
        pkg-config \
        zip && \
    # Get repository for node 8 and install it
    curl -sL https://deb.nodesource.com/setup_8.x | bash && \
    apt-get -qq install -y nodejs && \
    # Remove useless package : curl
    apt-get autoremove --purge -y curl && \
    # Clean temporary apt data
    rm -rf /var/lib/apt/lists/*

# Install php dependencies
RUN pecl -q install mongodb

#================================= Php Settings ================================

# Enable Mongo driver
RUN echo "extension=mongodb.so" >> /etc/php/7.0/cli/php.ini && \
    echo "extension=mongodb.so" >> /etc/php/7.0/apache2/php.ini

#=============================== Apache Settings ===============================

# Set Apache environment variables
ENV APACHE_RUN_USER www-data
ENV APACHE_RUN_GROUP www-data
ENV APACHE_LOG_DIR /var/log/apache2
ENV APACHE_PID_FILE /var/run/apache2.pid
ENV APACHE_RUN_DIR /var/run/apache2
ENV APACHE_LOCK_DIR /var/lock/apache2

# Create Apache directories
RUN mkdir -p $APACHE_RUN_DIR $APACHE_LOCK_DIR $APACHE_LOG_DIR

# Enable 'mod_rewrite' for rewrite URL then remove 'index.php'
RUN a2enmod rewrite

# Copy Apache configuration file
COPY apache2.conf /etc/apache2/apache2.conf
COPY 000-default.conf /etc/apache2/sites-available/000-default.conf

#================================= App Download ================================

# Create App directory
RUN mkdir /var/www/app
WORKDIR /var/www/app

# Copy sources without version control
RUN git clone --branch=v2.0.1 \
    https://my_name:my_key@bitbucket.org/app/repository.git . \
    && find . -name ".git*" -type f -delete

# Add write access to storage and cache
RUN chmod -R a+w storage/ bootstrap/cache/

#========================== Download / Install Vendors =========================

# Download PHP vendors
# Clean cache
RUN composer -q install && \
    composer clear-cache

# Download CSS/JS vendors
# Compile required assets
# Clean cache and download
RUN npm -q install && \
    npm run production && \
    rm -rf node_modules && \
    npm cache clean --force

#================================= App Settings ================================

# Set .env file with relevent settings
RUN sed -i 's/APP_ENV=\S*/APP_ENV=production/' .env && \
    sed -i 's/APP_DEBUG=\S*/APP_DEBUG=false/' .env &&

#=================================== Cleanup ===================================

# Clean temporary Laravel data
RUN php artisan cache:clear && \
    php artisan view:clear && \
    php artisan config:cache

# Remove useless folders
RUN rm -rf /var/www/html

#================================ Run Container ================================

# Make port 80 available to the world outside this container
EXPOSE 80

# Run Apache in the background
ENTRYPOINT [ "/usr/sbin/apache2" ]
CMD ["-D","FOREGROUND"]

After building the image size is 550 MB.
And after run the container the application work like expected.

What is right, and wrong with this dockerfile? How could I optimise it?


texts: ReactiveUI and Rx background calculations with cancellation

texts:
I'm working on a WPF app which uses ReactiveUI and Rx, there's part of the
workflow that watches two data sources (ReferenceData and PredictedData properties on
a View Model) and an area of that data source (FocusArea property) which is used to show
a line graph of that data.

Sometimes there can be a lot of data (and sometimes both data sources change at the same time), and building the line graphs can take a while. So it's done on a background thread.
I'm also using the Ramer–Douglas–Peucker algorithm to approximate the graph for display (the ReduceGraphPoints method, which returns Task<List<Point>>). So the final graph is only updated when the line data for both data streams are calculated and simplified.

Once the calculation is started, the Loading property of the View Model is updated so we can mark the current graph as about-to-be-replaced

The code I have for that bit of functionally at the moment is:

this.WhenAny(me => me.ReferenceData,
            me => me.PredictedData,
            me => me.FocusArea,
            (refData, predictedData, area) => new { ReferenceData = refData.Value, PredictedData = predictedData.Value, Area = area.Value })
    .Where(x => !x.Area.IsEmpty)
    .Do(_ => Loading = true)
    .Throttle(TimeSpan.FromMilliseconds(50))
    .Select(x => Observable.FromAsync(token => Task.Run(() =>
        {
            var refPoints = x.ReferenceData.GetPointsInRange(x.Area.Range).ToList();
            var reducedRef = ReduceGraphPoints(refPoints, token);

            var predictedPoints = x.PredictedData.GetPointsInRange(x.Area.Range).ToList();
            var reducedPredicted = ReduceGraphPoints(predictedPoints, token);

            return new { ReferencePoints = reducedRef.Result, PredictedPoints = reducedPredicted.Result };
        }, token)))
    .Switch()
    .Subscribe(x =>
    {
        ReferencePoints = x.ReferencePoints;
        PredictedPoints = x.PredictedPoints;
        Loading = false;
    });

So I'm looking for feedback from any Rx experts on this. Things like the use of the Do method, and the cancellation token. Most of the methods called use
ThrowIfCancellationRequested on the token, but I'm ignoring the cancellation exception  because if it has been cancelled, then Switch() will already be watching
the next IObservable and won't care about the old one - is that the best way of doing this?


texts:
I have a 3GB gz file that I am trying to break into chunks of smaller files which are not required to be gz (I tried to make files of 10000000 lines, this is not a requirement, the chunks could be of any size), but my method is taking ages to run (about 12 minutes). I have the requirement to not use any library such as Pandas, Spark, etc. I can only use pure Python. I tried profiling my code and the write seems to be the slowest thing. Here's my code :
import gzip
import os

class FileSplitter:

    def __init__(self):
        self.parse_args(sys.argv)

    @staticmethod
    def run():
        splitter = FileSplitter()
        #run to split the big file into smaller files
        splitter.split()

    def split(self):

        file_number = 1
        line_number = 0

        print("Splitting %s into multiple files with %s lines" % (os.path.join(self.working_dir, self.file_base_name), str(self.split_size)))

        out_file = self.get_new_file(file_number)
        a_file = gzip.open(self.in_file, 'rt')
        t = next(a_file)
        with a_file as f:
            for line in f:
                out_file.write(line)
                line_number += 1
                if line_number == self.split_size:
                    out_file.close()
                    file_number += 1
                    line_number = 1
                    out_file = self.get_new_file(file_number)

        out_file.close()

        print("Created %s files." % (str(file_number)))

    def get_new_file(self,file_number):
        """return a new file object ready to write to"""
        new_file_name = "%s.%s" % (self.file_base_name, str(file_number))
        new_file_path = os.path.join(self.working_dir, 'pychunks', new_file_name)
        print ("creating file %s" % (new_file_path))
        return open(new_file_path, 'w')

    def parse_args(self,argv):
        """parse args and set up instance variables"""
        try:
            self.split_size = 10000000
            if len(argv) > 2:
                self.split_size = int(argv[2])
            self.file_name = argv[1]
            self.in_file = self.file_name
            self.working_dir = os.getcwd()
            self.file_base_name = os.path.basename(self.file_name)
        except:
            print(self.usage())
            sys.exit(1)

    def usage(self):
        return """
        Split a large file into many smaller files with set number of rows.

        Usage:

            $ python file_splitter.py <file_name> [row_count]

        row_count is optional (default is 1000)"""

if __name__ == "__main__":
    FileSplitter.run()

To run my code I call a .py file containing this code with the name of my gz file, example : python myprogfile.py test.gz
Would you do that differently? Would you use threading (i tried but I couldn't succeed yet as I don't have experience with that)? What would you change in this code?
I don't know if it is my laptop that's too weak in terms of memory and CPU ...


texts:
I would like Autofac to instantiate components based on connection strings in the form of the URI:

autofac://assembly-name/full-class-name?param1=arg1&param2=arg2

So the following test will work:

[TestClass]
public class Locator_Should
{
    [TestMethod]
    public void Resolve()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<DiskFolder>();
        var container = builder.Build();
        var folder = container.Resolve<IFolder>(
            "autofac://LocatorTest/LocatorTest.DiskFolder?path=\\Windows");

        Assert.IsTrue(folder.Any());
    }
}

Where:

public interface IFolder : IEnumerable<string>
{
}

public class DiskFolder : ReadOnlyCollection<string>, IFolder
{
    public DiskFolder(string path)
        : base(Directory.GetFiles(path))
    {
    }
}

The library code is:

public static class AutofacLocator
{
    public static T Resolve<T>(this ILifetimeScope scope, string uri) =>
        scope.Resolve<T>(new Uri(uri));

    public static object Resolve(this ILifetimeScope scope, string uri) =>
        scope.Resolve(new Uri(uri));

    public static T Resolve<T>(this ILifetimeScope scope, Uri uri) =>
        (T)scope.Resolve(uri);

    public static object Resolve(this ILifetimeScope scope, Uri uri)
    {
        if (uri.Scheme != "autofac")
            throw new NotSupportedException("Schema not supported.");

        var factory = (Delegate)scope.Resolve(GetFactory(uri));
        return factory.DynamicInvoke(GetArguments(uri));
    }

    static Type GetFactory(Uri uri)
    {
        Func<Type[], Type> getType = Expression.GetFuncType;
        var types = GetParameters(uri)
            .Select(p => p.ParameterType)
            .Append(GetReturnType(uri));

        return getType(types.ToArray());
    }

    static object[] GetArguments(Uri uri)
    {
        var arguments = uri.Query
            .TrimStart('?')
            .Split('&')
            .Select(p => p.Split('='))
            .ToDictionary(nv => nv[0], nv => Uri.UnescapeDataString(nv[1]));

        return GetParameters(uri)
            .Select(p => Convert.ChangeType(arguments[p.Name], p.ParameterType))
            .ToArray();
    }

    static ParameterInfo[] GetParameters(Uri uri) =>
        GetReturnType(uri)
            .GetConstructors()
            .First()
            .GetParameters();

    static Type GetReturnType(Uri uri) =>
        Type.GetType($"{uri.Segments[1]}, {uri.Host}");
}


texts: Compare sequence & maps headers in fasta file

texts:
This is the perl code which compares the sequence in fasta file & maps the header. Though the code is working well, I still would like to make it more efficient. Since the files I compare has >100000 sequences it is taking huge time despite using hashes. Can you please suggest more efficient way ?

Example:

File1:
>Seq1
ABCDEFGH
>Seq2
RNADIMSEQ
>Seq6
XYZ

File2:
>Seq3
ABCDEFGH
>Seq4
RNADIMSEQ

Output:
>Seq1  >Seq3
>Seq2  >Seq4
>Seq6  Not found

The code:
 my $start_run = time();

%hash=();
open(out, ">Output.txt");
open(sbjt, "File1.fasta") or die "File not found"; #Bigger file
$count =0;
while(<sbjt>)
    {
    chomp;
    if($_ =~ m/^\w+/)
        {
            $hash{$previous} = $_  ;
            #print "$previous\n";
        }
    else
        {
        $previous = $_;
        }
    $count++ ;
    }
    close sbjt;
    #print "$hash{$previous}";

%dash=();
$previous = undef;
open(query, "File2.fasta") or die "File not found"; #smaller
while(<query>)
    {
    chomp;
    if($_ =~ m/^\w+/)
        {
            $dash{$previous} = $_  ;
            #print "$previous\n";
        }
    else
        {
        $previous = $_;
        }
    }
    close query;

foreach $key (keys %dash)
{
         foreach $temp (keys %hash)
         {
            if($hash{$temp} eq $dash{$key})
            {
                push(@new_array, $temp);
            }
            next; #added
        }
        if(scalar @new_array>0)
        {
            print out "$key\t@new_array\n";
        }
        else
        {
        print  out "$key\tNot found\n";
        }
        @new_array=();
 }

 my $end_run = time();
my $run_time = $end_run - $start_run;
print "Job took $run_time seconds\n";


texts: Tag specific Git commits based on commit message contents

texts:
I am using GNU Bash 4.3, and Git 2.1.4, to tag certain git commits based on their commit messages. Specifically, I want to tag:

as v0.0.1 the commit with message "Commit 5",
as v0.0.2 the commit with message "Commit 10",

given the following commit log:

$ git log --format=oneline --decorate
924d9120dec9f61d0f99a5155c51bad63d24b37f (HEAD, master) Commit 10
c62b2f68ea6b8ff047dd5f1e99010ebf434709ef Commit 9
feec2d76977521018ff33fd6e109530fdb69291d Commit 8
9a25b2ea11d0aa19af33761c7c81bd10d0f17949 Commit 7
c7b02e556738e7cd2a2459e07af731e5677ab090 Commit 6
1bf5b98cf90340e714bd0bd13c7721f94749fa5f Commit 5
8a9c25eda46b3424a870584e4a8a4f90f6e5aa2c Commit 4
0ecf2464ec82a3aa74abb6f6c2127315ef4c2495 Commit 3
e18bdb2ae52f2149421965ff69d96dba46cd7c0a Commit 2
cf10d47067bef60ae787e5421e32b4541bdf52be Commit 1

Here is my initial solution:

$ v=(1 2); c=(5 10); for i in 0 1; do git tag -a v0.0.${v[$i]} -m "Tag v0.0.${v[$i]}" $(git rev-parse :/'Commit '${c[$i]}); done

This clearly works as desired:

$ git log --format=oneline --decorate
924d9120dec9f61d0f99a5155c51bad63d24b37f (HEAD, tag: v0.0.2, master) Commit 10
c62b2f68ea6b8ff047dd5f1e99010ebf434709ef Commit 9
feec2d76977521018ff33fd6e109530fdb69291d Commit 8
9a25b2ea11d0aa19af33761c7c81bd10d0f17949 Commit 7
c7b02e556738e7cd2a2459e07af731e5677ab090 Commit 6
1bf5b98cf90340e714bd0bd13c7721f94749fa5f (tag: v0.0.1) Commit 5
8a9c25eda46b3424a870584e4a8a4f90f6e5aa2c Commit 4
0ecf2464ec82a3aa74abb6f6c2127315ef4c2495 Commit 3
e18bdb2ae52f2149421965ff69d96dba46cd7c0a Commit 2
cf10d47067bef60ae787e5421e32b4541bdf52be Commit 1

But it seems excessively verbose and fragile.

Questions:

Instead of separately defining three arrays (v=(1 2); c=(5 10); for i in 0 1), can I create a single array for the two independent variables (e.g. in pseudocode: vc=((1 5) (2 10))) and then determine the incrementor's value automatically upon each iteration?
Instead of using a for loop, can I use brace expansion or some other more concise and elegant approach?

I would prefer a one-liner, but I do not require a one-liner.


texts:
I have given the Mars Rover challenge a go in Python.

(edit) Here is the challenge, for those unfamiliar:

A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.

In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.

Test Input:

5 5

1 2 N

LMLMLMLMM

3 3 E

MMRMMRMRRM

Expected Output:

1 3 N

5 1 E

I am still relatively new to Python so know this is a bit basic - but I wondered if I could get some general feedback on my code for best coding practice?

class MarsRover():

    RIGHT_ROTATE = {
        'N':'E',
        'E':'S',
        'S':'W',
        'W':'N'
    }

    LEFT_ROTATE = {
        'N':'W',
        'W':'S',
        'S':'E',
        'E':'N'
    }

    def __init__(self, X, Y, direction):

        self.X = X
        self.Y = Y
        self.direction = direction

    def rotate_right(self):

        self.direction = RIGHT_ROTATE[self.direction]

    def rotate_left(self):

        self.direction = LEFT_ROTATE[self.direction]

    def move(self):

        if self.direction == 'N':
            self.Y += 1
        elif self.direction == 'E':
            self.X += 1
        elif self.direction == 'S':
            self.Y -= 1
        elif self.direction == 'W':
            self.X -= 1

    def __str__(self):

        return str(self.X) + " " + str(self.Y) + " " + self.direction

    @classmethod
    def get_rover_position(self):

        position = input("Position:")
        X = int(position[0])
        Y = int(position[2])
        direction = position[4]

class Plateau():

    def __init__(self, height, width):

        self.height = height
        self.width = width

    @classmethod
    def get_plateau_height(self):

        plateau_size = input("Plateau size:")
        height = int(plateau_size[0])
        width = int(plateau_size[2])

def main():

    plateau = Plateau.get_plateau_height()

    rover = MarsRover.get_rover_position()

    current_command = 0
    command = input("Please input directions for rover.")
    command_length = len(command)

    while current_command <= command_length - 1:

        if command[current_command] == 'L':
            rover.rotate_left()
            current_command += 1
        elif command[current_command] == 'R':
            rover.rotate_right()
            current_command += 1
        elif command[current_command] == 'M':
            rover.move()
            current_command += 1

    result = str(rover)
    print(result)

if __name__ == '__main__':

    main()

I am also getting the following error when I run the code:

     94         if command[current_command] == 'L':
---> 95             rover.rotate_left()
     96             current_command += 1
     97         elif command[current_command] == 'R':

AttributeError: 'NoneType' object has no attribute 'rotate_left'

Is anyone able to shed some light on why the 'rover' object is of NoneType?

Thanks in advance.


texts: Multi threaded Producer Consumer with bounded buffer

texts:
I've developed the following multi-threaded code and would like a review. It is supposed to be implementing the Producer-consumer problem as defined here.

I have multiple consumers and one producer. I would like to know whether there are any problems with my use of concurrency and also if you have any suggestions on how to better implement the solution. I don't have a lot of experience with concurrent programming and am trying to improve.

package consumerproducer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class ConsumerProducer1 {

    private static int QUEUE_SIZE = 10;

    private Deque<Integer> queue = new ArrayDeque<Integer>(QUEUE_SIZE);

    public synchronized boolean addWorkItem(Integer i) {
        if (queue.size() < QUEUE_SIZE) {
            queue.addLast(i);
            return true;
        } else {
            return false;
        }
    }

    public synchronized Integer getWork() {
        if (queue.size() > 0) {
            return queue.removeFirst();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        new ConsumerProducer1().go();
    }

    public void go() {
        ConsumerThread ct = new ConsumerThread();
        ct.start();
        ConsumerThread ct2 = new ConsumerThread();
        ct2.start();
        ProducerThread pt = new ProducerThread();
        pt.start();
    }

    class ConsumerThread extends Thread {
        public void run() {
            while(true) {
                Integer work = getWork();
                if (work == null) {
                    Thread.yield();
                } else {
                    System.out.println("Thread: " + this.getId() + " received work: " + work);
                }
            }
        }
    }

    class ProducerThread extends Thread {
        private List<Integer> retryList = new ArrayList<Integer>();
        public void run() {
            while(true) {
                Integer currWork;
                if (retryList.size() == 0) {
                    currWork = (int) (Math.random() * 100);
                    System.out.println("Thread: " + this.getId() + " generated new work: " + currWork);
                } else {
                    currWork = retryList.remove(0);
                    System.out.println("Thread: " + this.getId() + " retrying old work: " + currWork);
                }
                if (!addWorkItem(currWork)) {
                    System.out.println("Thread: " + this.getId() + " could not add work (because buffer is probably full): " + currWork);
                    retryList.add(currWork);
                    Thread.yield();
                } else {
                    System.out.println("Thread: " + this.getId() + " added work to queue: " + currWork);
                }
            }
        }
    }
}


texts:
I like Markov chains. Last time I used one, I made one that generates words. This time, I made one that generates sentences, given a set of words and valid connections. This time, it's not weighted and it's reading from a JSON file, so the code is a bit simpler:

require 'json'

data = JSON[ARGV[0]]
CONNECTIONS = data['connections']
WORDS = data['words']

sentence = []
current_pos = 'start'
until current_pos == 'end'
  current_pos = CONNECTIONS[current_pos].sample
  sentence << WORDS[current_pos].sample
end
puts sentence.join(' ')

If we use this as the input data:

{
  "connections": {
    "start": ["article"],
    "article": ["adjective", "noun"],
    "adjective": ["adjective", "noun"],
    "noun": ["verb", "end"],
    "verb": ["article"],
    "end": []
  },
  "words": {
    "article": ["the"],
    "noun": ["dog", "cat", "penny", "truck"],
    "verb": ["ate", "stole", "helped", "cuddled"],
    "adjective": ["red", "big", "fluffy", "honorable"],
    "end": [""]
  }
}

which gives some fantastic word salad like:

the fluffy penny ate the truck stole the penny cuddled the cat stole the big cat
the red red dog helped the honorable honorable fluffy big big red big cat stole the truck

And, my personal favorite so far:

the fluffy honorable cat stole the dog

I'm looking for tips on:

Efficiency -- I think this is about as good as it'll get, but any suggestions are great.
Usability -- I like word salad. I want to share it with everyone. To that end, I want to make this as easy and simple-to-use as possible.
Readbility -- Because I like word salad (it's very nutritious) I want people to easily understand how to make it. Again, I think this is about as it's gonna get, but any suggestions are great.


texts:
I have a piece of code that checks if two strings are anagrams. I would like this to be as pythonic as possible.

def are_two_string_anagram(string1, string2):
    if len(string1) != len(string2):
        return False

    def char_count(string):
        char_count = {}
        for s in string:
            char_count[s] = char_count.get(s, 0) + 1
        return char_count

    chr_count = char_count(string1)
    chr1_count = char_count(string2)
    return chr_count == chr1_count

string1 = "mary"
string2 = "yram"
print(are_two_string_anagram(string1, string2))

string1 = "albert"
string2 = "abelrt"
print(are_two_string_anagram(string1, string2))

string1 = "something"
string2 = "anotherus"
print(are_two_string_anagram(string1, string2))


texts:
First time working with any type of graph traversal. The algorithm determines whether a path exists between two nodes using breadth first searching (BFS). The BFS method returns a tuple; indicating whether a match has been found and the length between the two nodes. I implemented it this way since it's part of a private member and wont be seen externally. When the result is seen as part of the HasPath method I modeled it after the Try-Pattern similar to TryParse(...).
The local function EnqueueNonVisitedChildrenNodes is declared as such since it would make no sense to call it anywhere else. It too uses a tuple to simplify its invocation.
Am I properly using the tuple type? Is there anything that could be improved with code structure?
using System.Collections.Generic;
using System.Diagnostics;
[DebuggerDisplay("Name = {Name}, ChildCount = {Children.Count}")]
public class Node
{
    public string Name { get; }
    public List<Node> Children { get; } = new List<Node>();
    public bool Visited { get; set; }

    public Node(string Name)
    {
        this.Name = Name;
    }

    public Node(string name, IEnumerable<Node> children)
    {
        Name = name;

        foreach (var node in children)
        {
            AddChild(node);
        }
    }

    public void AddChild(Node node)
    {
        Children.Add(node);
    }
}

The implemented algorithm.
public class PathAlgorithm
{
    Node Start { get; }
    Node End { get; }

    public PathAlgorithm(Node start, Node end)
    {
        Start = start ?? throw new ArgumentNullException(nameof(start));
        End = end ?? throw new ArgumentNullException(nameof(end));
    }

    public bool HasPath(out int length)
    {
        bool hasPath;
        (hasPath, length) = BreadthFirstSearch(Start);

        return hasPath;
    }

    public (bool, int) BreadthFirstSearch(Node root)
    {
        if (root == null)
        {
            return (false, 0);
        }

        Queue<(Node, int)> searchQueue = new Queue<(Node, int)>();
        root.Visited = true;
        searchQueue.Enqueue((root, 0));

        while (searchQueue.Any())
        {
            (Node node, int length) = searchQueue.Dequeue();
            if (node == End)
            {
                return (true, length);
            }

            EnqueueNonVisitedChildrenNodes(searchQueue, (node, length));
        }

        return (false, 0);

        void EnqueueNonVisitedChildrenNodes(Queue<(Node, int)> queue, (Node node, int length) foo)
        {
            foreach (var n in foo.node.Children)
            {
                if (!n.Visited)
                {
                    n.Visited = true;
                    searchQueue.Enqueue((n, foo.length + 1));
                }
            }
        }
    }
}


texts: Google App Script sheet that moves row to correct sheet

texts:
I've got this code to loop through each cell in Column A and check the cell value. If the value matches the if criteria it moves the entire row to the correct Sheet and then replaces the Column A cell with an X. This makes a call to the server for every cell and I'm curious if there is a way for me to optimize it similar to what Google has documented as Best Practices. The Cache service is confusing me.

Here is a copy of the spreadsheet I'm working on. The code has a menu execution under Move Row.

function moveToQA() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var columnNumberToWatch = 1;
  var targetSheet = ss.getSheetByName("QA ");

  for( var i = 3; i >= 3; i++ ) {
    var cell = sheet.getRange(i,1);
    var cellValue = cell.getValue();
    if (cellValue == "Captures Sent " || cellValue == "QA In Progress " || cellValue == "Recapture Completed ") {
      var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
      sheet.getRange(cell.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
      cell.setValue("X");
    }
    else if (cellValue != "") {
      continue;
    }
    else if (cellValue == "" || cell == lastRow) {
      break;
    }
  }
}


texts: Exercise 1-22 from K and R: line folding

texts:
I'm currently learning C with K&R, i'm right now in the exercise 1-22, but it's a little... hard to understand (at least for me). It says:

  Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long line, and if there are no blanks or tabs before the specified column.

I've done this:

#include <stdio.h>

void seccionar(char to[], char from[])
{
     int a = 0,b = 0, i = 0;
     int max = 0;

     while(from[i] != '\0'){
                   if(max <= 80)
                          to[a] = from[i];
                   if(max == 80){
                          if(to[a] == ' ')
                          to[a] = '\n';
                          else {
                               for(;to[a] != ' '; --a)
                                          ++b;
                               to[a] = '\n';
                               max = 0;
                               a = a + b;}
                               b = 0;
                               }
                   ++a;
                   ++i;
                   ++max;}
     to[a] = '\0';
}
int getline(char s[])
{
    int c, i;

    for(i=0; (c=getchar()) != EOF; ++i){
             s[i] = c;
             if(c == '\n')
             break;}
    ++i;
    s[i] = '\0';
    return i;
}
int main()
{
    char from[10];
    char to[10];
    while(getline(from) > 1){
                       seccionar(to, from);
                       printf("%s", to);}
    return 0;
}

Does this matches with the exercise?


texts:
I'm writing a program to convert integers to Roman numerals (naively -- it doesn't know how to do the subtraction trick yet). What I have is functional, but it is not "Good Ruby".

VALUES = [
  ["M", 1000],
  ["D", 500],
  ["C", 100],
  ["L", 50],
  ["X", 10],
  ["V", 5],
  ["I", 1],
]

def romanize n
  roman = ""

  VALUES.each do |pair|
    letter = pair[0]
    value = pair[1]
    roman += letter*(n / value)
    n = n % value
  end
  return roman
end

Perhaps a hash makes more sense than the array of arrays, but the way I update n, order matters. Passing in pair to the block is dumb, but passing letter, value didn't work in the way I expected.


texts: Cross-Database Query Without Casting to List

texts:
I am trying to do a cross-database query without having to enumerate the variable t.

public List<Models.MCMessageCenter> GetMsgCtrsWithReloInfoByUserId(Guid userId)
{
    var t = GetMessageCentersByUserId(userId).ToList();

    List<Models.MCMessageCenter> result;

    using (var ctx = new TEDREntities())
    {
        result = (from n in t
                 join m in ctx.UserAccounts.AsNoTracking() on n.UserId equals m.UserAccountId
                 select new Models.MCMessageCenter
                 {
                     Id = n.Id,
                     MessageTitle = n.MessageTitle,
                     CreatedDate = n.CreatedDate,
                     UserId = n.UserId,
                     Name = m.FirstName + " " + m.LastName,
                     RelatedEntityId = n.RelatedEntityId
                 }).ToList();
    }

t could be very large so I don't want to enumerate it by turning it into a list.  Is there a better, more efficient way to perform a cross database query?

Whenever I attempt to keep t as IQueryable, I get an error like "can't query two datasources at once."  I can get the exact message if anyone needs.