Transform DataReader to List using reflections

I can suggest a number of improvements you can make to the code:

You're calling GetSchemaTable to get column names. To simply fetch column names you don't need, there is a faster alternative:

var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();

You're not computing the result of your select query to get column names. Select extension method is lazily evaluated which means it is executed every time you call it. Instead you should materialize the query by calling ToList() or something like that (as shown above).
You should make use of expression trees to generate compile code at run-time. You can make use of such code in many ways:

Db operations are expensive. Add reflection to it, it gets worse. Expression trees help you get the benefit of reflection at native speed once you compile some logic. You should replace all reflection logic with expression trees. One example
Activator.CreateInstance<T>() uses reflection behind the scenes which is slower. Expression trees can make that case faster too. See
reader["columnName"] will be marginally slower than reader[columnIndex] though it will ultimately depend on the ADO.NET connector implementation. It is safe to assume the latter is faster. You could spit out code at run-time to cache the ordinal values of fields and use it to query the reader like shown here.

Your columnCollection.Contains(string columnName) is case-sensitive. Make it case-insensitive since property naming convention can differ from db column naming conventions.
You don't need the casting here:

(object)reader[columnName];

What you get returned from reader is already object. Just code readability matters.
You're not assigning the column value to property when reader returns DBNull. This can give rise to oddities at times. Imagine you have an unfortunately designed class like this:

class User { public User() { Property = "42"; } }

Assume your db value for Property column is DBNull. If you don't assign anything in your mapping code then the returned User object will have a default value of "42" for Property where as in db the corresponding field will be DBNull which indicates null.
As Jesse has pointed in his answer, you're using reflection code to map inside the loop. I would take it outside. But unlike him I wouldn't recommend caching in a static dictionary permanently. I would like to optimize for memory too.
You're doing double dictionary lookup in this line:

columnName = dbMappings.ContainsKey(f.Name) ? dbMappings[f.Name] : f.Name;

Use TryGetValue instead.
No need to check twice for column name like this:

if (!columnList.Contains(f.Name) && !dbMappings.ContainsKey(f.Name))
    continue;
columnName = dbMappings.ContainsKey(f.Name) ? dbMappings[f.Name] : f.Name;

In fact, no need to check for presence columns in column collection at all; just loop column collection straight away instead of property collection. Or even better, take expression route, no need of any looping, you could assign to variables statement by statement.
You're doing GetProperties twice. Instead call it once, and cache it in dictionary. So your dictionary must look like Dictionary<string, PropertInfo> rather than Dictionary<string, string>. Or make use of ordinals, so your dictionary looks like Dictionary<int, PropertyInfo>.
Since you're constraining the T to new() you can just call new T() rather than Activator.CreateInstance<T>(). This is simpler syntax.
The columnName value you use here:

(object)reader[columnName];

is obtained from property names. If there is a case difference between property name and the actual field name in the reader the lookup will be slower, depending on the implementation of ADO.NET connector. It's better to use the column name you get from the reader itself. Or even better, just use ordinals to query (i.e. indices).
Not all properties are settable. It is better to check it beforehand.
There's a deeper problem here with IDisposables. You have to use the using statement to properly dispose your connection, command and reader objects. When you leave the method which has using keyword used, your objects (especially the reader) will be disposed and hence you wont be able to operate on reader outside your method. Your alternative is to not use using at all and dispose off everything manually after you're done. This wont look good. I would rather iterate the reader in the method which initializes the reader rather than in the mapper class, and return using the yield keyword which blocks disposing off reader object until enumeration.

The gist of it (except expression trees which is too much plumbing, but I have given a reference link so that you can work on) would look like:

public class DataReaderMapper<T> where T : new()
{
    Dictionary<int, PropertyInfo> mappings;

    public DataReaderMapper(IDataReader reader)
    {
        this.mappings = Mappings(reader);
    }

    // int part is column indices (ordinals)
    static Dictionary<int, PropertyInfo> Mappings(IDataReader reader)
    {
        var columns = Enumerable.Range(0, reader.FieldCount);
        var properties = typeof(T)
                        .GetProperties()
                        .Select(prop => new
                        {
                            prop,
                            attr = prop.GetCustomAttributes(typeof(DbColumnAttribute)).FirstOrDefault()
                        })
                        .Select(x => new
                        {
                            name = x.attr == null ? x.prop.Name : ((DbColumnAttribute)x.attr).Name,
                            x.prop
                        });
        return columns
              .Join(properties, reader.GetName, x => x.name, (index, x) => new
              {
                  index,
                  prop = !x.prop.CanWrite ? null : x.prop
              }, StringComparer.InvariantCultureIgnoreCase)
             .Where(x => x.prop != null) // only settable properties accounted for
             .ToDictionary(x => x.index, x => x.prop);
    }

    public T MapFrom(IDataRecord record)
    {
        var element = new T();
        foreach (var map in mappings)
            map.Value.SetValue(element, ChangeType(record[map.Key], map.Value.PropertyType));

        return element;
    }

    static object ChangeType(object value, Type targetType)
    {
        if (value == null || value == DBNull.Value)
            return null;

        return Convert.ChangeType(value, Nullable.GetUnderlyingType(targetType) ?? targetType);
    }
}

You can call it like:

using (var reader = cmd.ExecuteReader())
{
    var mapper = new DataReaderMapper<T>(reader);
    while (reader.Read())
        yield return mapper.MapFrom(reader);
}

I believe this code is overall shorter, but personally I think you should go for expressions instead of reflection, or even better try a tried and tested ORM.

I'm passing reader object to the constructor of mapper class as well as in the MapFrom method for a reason. Designing a clean API is little difficult here considering reader form both IDataReader (the enumerable) as well as IDataRecord (the result of enumeration). The reason I pass it separately is performance. I dont cache anything, so memory management is left to client. If you don't want the mapping to happen every time you can just cache the mapper instance and dispose it off when you don't want anymore. For e.g. you could do this:

 DataReaderMapper<T> mapper;
 using (var reader = cmd.ExecuteReader())
 {
     mapper = new DataReaderMapper<T>(reader); // initialized once
     while (reader.Read())
         yield return mapper.MapFrom(reader);
 }

 using (var reader = cmd.ExecuteReader())
 {
     while (reader.Read())
         yield return mapper.MapFrom(reader); // no need of further initialization
 }

To use it at a later stage you can cache mapper in some dictionary detailing which out will be too much for now.


jQuery functions to add corresponding entries of lists

I think you could rewrite the code in a shorter way.

You can write the calculateSum# function to be generic.

This you can do by providing the selector or directly the jQuery object you need to loop and sum values.

And instead to directly write the result, you could return the computation.

Of course you could pass the result selector or jQuery element and do the job, but if you return the result, the code is more changeble in the future.

Then you create an object literal with the keys as your element selector, and the values as the result element selector.

And finally create an anonymous function to pass on jQuery document ready step $(myFuncOnDocReadyHere...), where you put all together.

If you prefer to avoid sharing the object with elements you could place it inside the on doc ready function, to keep it "private".

Here is my changes:

var summableAndResult = {
 ".pr1": "#result1",
 ".pr2": "#result2",
 ".pr3": "#result3",
 ".pr4": "#result4"
}

function calculateSum ($list) {
 var sum = 0;

 $list.each(function() {
  var value = $(this).text();
  // test isNaN only if string is not empty
  if (value.length != 0 && !isNaN(value)) {
   sum += parseFloat(value);
  }
 });

 return sum;
}

$(function(){

 for(var el in summableAndResult) {
  var sum = calculateSum($(el));
  $(summableAndResult[el]).text(sum);
 }

});
div.col, div.price {float:left}
div.col {width:25%;margin;none;}
ul {list-style-type: none;margin:0;}

Price

150

199

249

299

+

+

+

+

+

Add costs

27

20

30

39

=

=

=

=

=

Totaal


My suggestion is to not do what you are trying to do.  Why do you want to wrap PDO?

This is a common type of code review that I see here and in most cases the attempt to "wrap" a perfectly good abstraction library like PDO is misguided.

Please look at the discussion on these threads:

Class for reducing development time
PHP PDO Wrapper

Given that, let me give you some thoughts on what you do have.

Don't mix snake case and camel case in your codebase.  I know PHP is pretty bad about mixing these two, but that doesn't mean you should be.

You have a class that is doing two things - acting as a singleton and acting like a DB wrapper.  If you truly want to move forward with having a wrapper, you should at least consider moving the singleton behavior into it's own class, with the singleton managing the creation or retrieval of the Database object (or PDO object if you drop the wrapper idea).  Name that class appropriately like DatabaseSingleton, PDOSingleton, or similar.

private function __construct() {

    try {
        // Put your database information
        $this->pdo = new PDO("mysql:host=127.0.0.1;dbname=login","root","");
    } catch (PDOException $e) {
        die($e->getMessage());
    }

}

Don't just assume that PDO instantiation works.  You could be assigning a bad value to $this->pdo.
Don't put your DB credentials here in this class.  They should be in app config.
Don't use "root" for this application. Create a user in MySQL for this application, with appropriate permissions.  Don't use "" as your password, especially in combination with "root". Your MySQL server could be vulnerable.
Don't echo out application error messages to standard output.
You try-catch block is essentially useless here as it is not really doing anything and is, in fact, hiding the error from calling code which is likely in better position to determine how to recover from the failure and/or message the end user.

public function query($sql, $parameters = array()) {

This method is poorly named. Perhaps something like prepare_and_execute is more descriptive of what is happening here.
You are performing no validation whatsoever for the data passed.  You need to verify that $sql is (at a minimum) a non-zero length string and that you have an array passed for $parameters.  Your code could break if those conditions aren't met, so you need to fail out of the method (possibly with INvalidArgumentException being thrown) before you ever get to the point of trying to prepare a statement. You should have parameter type-hinting and/or validation as the first thing that happens in ANY publicly accessible method.
This method has removed user's ability to do any parameter type enforcement in their bindings.
This method rally only considers happy path.  What if prepare fails (right now you silently just return the object with no indication to caller that something went wrong). Same with bindValue and execute().  To reinforce the point about pointlessness of this wrapper.  You have now written a number of lines of code here to make working with PDO less flexible, more fragile, and less transparent to the caller.

        $this->results = $this->query->fetchAll(PDO::FETCH_ASSOC);
        $this->count = $this->query->rowCount();
        $this->lastId = $this->query->lastInsertId();

This is just odd.  In what scenario would a single query have both a result set and an insert ID?

I know that people may like the natural language interfaces like you are trying to achieve with select(), where(), etc. methods. There are a number of good libraries out there that can give you this functionality, and I guarantee you those methods in those libraries contain a lot more code in them to address all the data validation and edge cases you are missing (like what if I want to OR my WHERE filters).  How much benefit are you really getting from this functionality?

Is this:

$result = $database->select('*')->from('table')->where(["column = 'abc'"])

Really easier to read and understand than:

$sql = "SELECT * FROM table WHERE column = 'abc'";

What happens when you need to perform join, order by, limit, etc.?  With your current class, you just end up having to revert to using raw SQL anyway because your current implementation is very basic in terms of functionality.

By the way defaulting to (or even allowing) SELECT * is something you ought to think twice about.  SELECT * is bad.  SELECT * can quietly break your applications when there are schema changes. SELECT * can suck up a lot more bandwidth in transmission than is required for any given piece of logic to execute. SELECT * makes it difficult for someone only looking at code to understand what sort of data is being made available to them.

The last(), first(), row() methods are ill-conceived.  These concerns should really be addressed by LIMIT clauses in SQL.  Why do you need to retrieve and store every row from a table if you are only interested in row X?


Method that reserves a reservable entity and charges the user

Brandon Keepers has a really good tip in his talk Why our code smells.

  Write a top level decription of your class without using the words "and" or "or".

If you can't do that then there is a risk that your class might be doing to much. Since ActiveModel and AR and ActionController gives models and controllers such superpowers it's easy to fall into the trap of making godlike objects.

So when you have a method which has an AND in the description then you have definitely have a code smell.

The first major code smell here is @reservable.status != Reservable::STATUS[:available] this is just a leaky class with the internals hanging out like loose wires. Fortunately it's really easy to fix:

class Reservable
  def available?
    status == Reservable::STATUS[:available]
  end
end

But an even better way would be to crack out the awesomeness of ActiveRecord::Enum, as it will take care of the wiring for you:

class Reservable
  enum status: [:available, :reserved]
end

This gives use reservable.available?, .reserved?, .reserved! etc.

One good pattern to refactor the above would be Service objects. Service objects are dirt simple plain old ruby objects that just do one job - tops. Most service objects just have a single public method - often #call

So lets see if we can start splitting this up into distinct tasks.

# Reserves a reservable
class ReservationService

  def initialize(user:, reservable:)
    @user = user
    @reservable = reservable
  end

  def call
    unless @reservable.available?
      raise Reservable::UnavailableError.new(object: @reservable)
      return false
    end
  end
end

# Charges a user for services rendered
class ReservationChargingService

  attr_reader :transaction

  def initialize(charge, user){
    @charge = charge
    @user = user
  }

  def call(amount, payment_type)
    # @todo charge user for amount
    # @todo return true / false or a status code for the payment
  end
end

This gives us nice detached pieces which can be tested in isolation - which is really nice since testing methods with DB transactions can be problematic.

Then in your controller you can boil things down a bit:

def reserve

  Reservable.transaction do
    begin
    @reserved = ReservationService.new(
                    user: @user,
                    reservable: @reservable
                ).call
    @charged = ReservationChargingService.new(
                    user: @user,
                    reservable: @reservable
               ).call
    raise ActiveRecord::Rollback unless @reserved && @charged
    rescue Reservable::UnavailableError
      raise ActiveRecord::Rollback, 'Reservable not available.'
    end
    rescue ActiveRecord::RecordInvalid
      raise ActiveRecord::Rollback, 'Validation error'
    end # @todo rescue other errors?
  end

  if @reserved && @charged
     render json: @reservable.current_use
  else
     errors = [@charged.transaction, @reservable]
                 .reject(&:valid?).map { |o| o.errors.full_messages }
     render json: { errors: errors }, status :unprocessable_entity
  end
end

As you can see here you want to delegate as much work to services as possible. Also prefer using ActiveModel::Errors instead of creating error hashes in your controller.

Our controller only has to deal with two contingencies here two which is really good: either the complete transaction passes and we return a success object or we return a errors hash.


Groovy: find all elements in a list equal to the max element

How you've done it for the simple example is exactly how I would do it.  I may use groupBy if I was dealing with a more complex object.

    List v = [ 1,2,3,4,5,5 ]
    def max = v.max()
    def results = v.groupBy {it}.get(max)
    assert [5,5] == results


Tortoise and hare cycle detection algorithm using iterators in Python

# -*- coding: utf-8 -*-

from __future__ import print_function
from itertools import islice,cycle,chain

def detect_cycle(iterable):

    class animal(object):

Putting classes inside function is usually not all that helpful. Also, the name doesn't really suggest what this class does.

        '''Holds the iterator and keeps the last value returned by the iterator'''
        def __init__(self,iterable):
            self.it = iter(iterable)

I'd do something like iter, just because it isn't a really obvious abbreviation

            self.value = next(self.it) #get the first value

        def next(self):
            self.value = next(self.it)
            return self.value

        def __iter__(self):
            return self

    tortoise = animal(iterable)
    hare = animal(islice(iter(iterable),None,None,2))  #two steps at a time

You end up create two iterators from the same iterable. That might be problematic as you can't be sure those two iterators are independent.

    while True:
        if next(tortoise) == next(hare):
            break

You get most of the benefit of iterators when you can use for loops. In this case, I might use a for loop with itertools.izip.

    hare = tortoise #put hare in the place of tortoise
    tortoise = animal(iterable) #start tortoise from the very beginning
    mu = 0
    while True:
        if hare.value == tortoise.value:
            break
        next(hare)
        next(tortoise)
        mu += 1

You do this basic thing three times. You loop through both iterators, until they match. Write a function that takes the two iterators, does that and then returns the count of them.

    lamb = 0
    tortoise_val = tortoise.value #save the value of tortoise as the object is reassigned to hare
    hare = tortoise
    while True:
        next(hare)
        lamb += 1
        if hare.value == tortoise_val: #check AFTER the first step by hare
            break

    print('mu: {}'.format(mu))
    print('lamb: {}'.format(lamb))


This seems quite fine, in no small part thanks to the use of using (...) { ... } blocks to manage resources.

Use prepared statements

The biggest improvement would be to use prepared statements for inserting the records. See the example in the docs.

A small bug

You have a small bug in the line counting:

    if (fields.Length != 2)
    {
        Console.WriteLine("Invalid Input on line:" + ln);
        continue;
    }
    ln++;

Since you only increment the counter after the check on fields.length,
the line number will be correct for the first invalid line,
and off by one for the next invalid line, off by 2 for the one after,
and so on.
In other words, to keep the count correct, you need to do it before the if.

Use the var keyword consistently

You used the var keyword almost everywhere, except here:

using (StreamReader sr = new StreamReader(@"c:\Temp\test.csv"))

You can simplify with var sr = ...


Knuth's algorithm M that produces mixed-radix numbers

Below is a more idiomatic to Haskell version that still follows your original imperative logic. I know elsewhere on SO you have been shown how to do this efficiently and functionally. I did this to show what could be done if the design requirements remained in place.

This version is 52 lines long with all of the whitespace you see. The original was 84 lines after whitespace between the functions was added.

The entire takeInput design using State was not needed. As shown, map read . words is sufficient. If you are concerned about poor input then a version could quickly be put in place using reads but without State.

case replaces the if usage. This is more idiomatic in my experience and is still very readable. You get pattern matching along the way too.

Note that nowfill was replaced by newListArray and the entire CountList was discarded as unneeded. If it was valuable then fillArray could still use CountList without the need for nowfill. The entire function could be about two lines if Applicative style was used. But that would definitely veer pretty far from the straight forward imperative style.

visit was updated to move the putStrLn call outside of the recursion and uses a helper function instead of the old if/else style. Again, the same exact logic just using a more idiomatic layout.

The calls to uncurry could be removed if m5 and algorithmM0 took tuples instead of separated arguments. This does lend it a more functional flavor but I did not want to disturb the function types where possible.

There are no cute tricks in this code. It is pretty reasonable for even a beginner level Haskell developer to read and understand I think. A C coder unfamiliar with the language would have more difficulty following this version than the original I suspect.

import Data.Array.IO

type AlgoArray = IOArray Int Int -- allows for experimentation with IOUArray or others

lenarr :: AlgoArray -> IO Int  -- simplified type
lenarr arr = getBounds arr >>= return . snd

fillArray :: [Int] -> IO (AlgoArray, AlgoArray)
fillArray ns = do  -- could be Applicative style: (,) <$> newListArray <*> newArray
    x <- newListArray (0, lcount) (2:ns)
    y <- newArray (0, lcount) 0
    return (x, y)
    where
      lcount = length ns

visit :: AlgoArray -> Int -> IO ()
visit x i = lenarr x >>= visit' x i >> putStrLn ""
    where
      visit' x i c
        | i > c     = return ()
        | otherwise = readArray x i >>= putStr . show >> visit' x (i + 1) c

maj :: AlgoArray -> AlgoArray -> Int -> IO (AlgoArray, Int)
maj m a j = do
    valaj <- readArray a j
    valmj <- readArray m j
    maj' valaj valmj
    where
      maj' valaj valmj
        | valaj == (valmj - 1) = writeArray a j 0 >> maj m a (j - 1)
        | otherwise            = return (a, j)

m5 :: AlgoArray -> Int -> IO (AlgoArray, Int)
m5 a 0 = return (a, 0)
m5 a j = readArray a j >>= writeArray a j . (+1) >> return (a, j)

algorithmM0 :: AlgoArray -> AlgoArray -> IO ()
algorithmM0 m a = do
    visit a 1
    v <- lenarr m >>= maj m a >>= uncurry m5
    case v of
      (_, 0)  -> return ()
      (a', _) -> algorithmM0 m a'

algorithmM :: IO ()
algorithmM = getLine >>= fillArray . takeInput >>= uncurry algorithmM0
    where
      takeInput = map read . words

main :: IO ()
main = algorithmM


Cumulative sum of the smallest neighbors in the previous row in a Numpy array

first, your problem is example of dynamic programming. Here some tips how to approach problem in python
your solution calculate each table cell separately. But function min_parent() use data only from previous row, so you can calculate row by row (and numpy is designed to fast operations on vectors)
i am using like you range <j - 1 : j + 2) but check if task don't need <j - 1, j + 2>

Example code

assert(w >= 2) # if not, you should handle w == 1 in special way

def vectorized_solution(arr, h):
    sum_arr = arr.copy()
    for i in range(1, h):
        parent = sum_arr[i - 1, :]
        sum_arr[i, 0] += min(parent[0], parent[1])
        sum_arr[i, 1:-1] += np.minimum.reduce([parent[0:-2], parent[1:-1], parent[2:]])
        sum_arr[i, -1] += min(parent[-2], parent[-1])
    return sum_arr


Deleting/sending to trash files with Python

There are some things that can be improved here

Divide your code into functions, don't put everything in the global namespace!
Use a if __name__ == '__main__' guard.
It's not bad to give your code a little more space in the sake of readability, a few blank lines would help make this code look better.

Read PEP8#blank-lines for more details.
Don't use == or is for False, True comparison

See PEP8#programming-recommendations.

while os.path.exists(file) is False:

You can rewrite to a more idomatic while not os.path.exists(file):
Naming is important

file = input("Type the file path")

This is a path, so rename it to path = ...

for i, j, k in os.walk(file):

You could name those to what they represent:

for folder, subfolder, files in os.walk(path):


Return consistent types

Both functions may return different types. For example combos may return an array or undefined. It would be better to return consistent type from all execution paths.

Input validation

The sum function does some input validation, checking if its parameter is an array. But this is too late. It's better to do input validation as close to where you receive the input as possible.

Also, there's no need to require nonempty input. If the input is empty, your algorithm will correctly return 0 as sum or empty array for combos, and that's all well.

Algorithm

In the current algorithm it's inefficient that the sums of arrays are recomputed every time you add a new element, when you could easily know the sums so far. It would be better to use that knowledge and avoid unnecessary recomputations.

To avoid creating results that are duplicates, your algorithm would need a substantial rewrite, which is off-topic here.


Need to clean up my code and add the ability to resize the image

You can use PHP's getimagesize() function to get the MIME type.

<?php
include '../../inc/config.php';

if(!isset($_REQUEST['image'])) die('Nenhuma imagem definida!');

$size = isset($_REQUEST['size']) ? $_REQUEST['size'] : 'full';
$image = $_REQUEST['image'];

$img_hash = $PDO->prepare("SELECT url FROM missionary_photos WHERE hash = :hash");
$img_hash->bindValue(':hash', $image);
$img_hash->execute();
$img_hash = $img_hash->fetchAll(PDO::FETCH_ASSOC);
$img_url = SITE_URL.$img_hash[0]['url'];

$info = getimagesize($img_url);
header('Content-type: '.$info['mime']);

readfile($img_url);


Parsing user name and password from binary in Erlang + Cowboy

Your approach is necessary because of the need to extract the length of the Username field before using it to extract the Username field itself. However, you needn't use bitstring anywhere because you're only sending whole bytes, not bitfields. You can change all occurrences of bitstring to binary instead, and with that change you also no longer need to specify the length of Username in bits, so you no longer need LU2 and can just use LengthUser directly:

-define(LOGIN, 1).

websocket_handle({binary, <<?LOGIN:8,LengthUser:8, Rest/binary>>}, Req, State) ->
    <<Username:LengthUser/binary, Password/binary>> = Rest,
    %% Do the actual logging in...

And finally, note that by convention, Erlang comments on a line by themselves at the current indentation level start with %%, not %. Single % should be used only for end-of-line comments. Not sure about other editors but the emacs erlang-mode indents comments this way, so if an emacs user worked on your code your comments might get wildly indented if the emacs developer auto-indented the buffer and didn't check everything afterwards.


You code looks fine to me. I'll just make some random comments.

You can split long lines like this for the sake of readability:

$numberOfCores = Get-WmiObject -class win32_processor numberOfCores |
    Select-Object -ExpandProperty numberOfCores

This comment is confusing to me:

# Remove the elements we are going to be replacing

You are removing <httpHandlers> but adding back <httpRuntime>. Was that intentional or a bug?

Why remove and create a new <processModel>? Why not just update the attributes in the original node? You would save on a few lines of code.

What happens if these nodes already have some attributes set? If you blow away the nodes, you will blow away those attributes. Was that intentional?

Why do you suddenly change style when creating <system.net>? Why not continue using CreateElement and so on?

In most places, you cast to [void] to get rid of the return values. In one place you use Out-Null. It's best to be consistent. Personally I would go with Out-Null since it is more the PowerShell way, and I think it looks nicer.

If you like, you can use the Select-Xml cmdlet instead of SelectNodes. Something like this:

$node = $machineConfig | Select-Xml /configuration/system.web

If you are going to overwrite the original file, it might be a good idea to make a copy of the original first. Add a timestamp to the filename or something.

It might be overkill in this case, but I would be inclined to make the code data-driven. That is, put all the changes to be done in a list at the top of the code and walk through the list in the code making the changes. That way people could see at a glance what the script does without having to read through all the code.


Polymorphic components for graphics and program state

The point of the Module approach is that you don't manage any state globally. Instead, each component (Module) manages its own state internally and you just express how they are connected together.

To give a simple example, let me first implement the standard type classes for Module:

{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import Prelude hiding ((.), id)
import Control.Applicative
import Control.Arrow
import Control.Category
import Control.Monad
import Control.Monad.State
import Control.Monad.Trans
import Control.Monad.IO.Class
import Data.Void

-- Module
----------------------------------------------------------------------------------------
newtype Module m a b =
    Module { runModule :: a -> m (b, Module m a b) }

instance (Monad m) => Category (Module m) where
    id = Module $ \x -> return (x, id)
    (Module g) . (Module f) = Module $ \x -> do
        (u, f') <- f x
        (v, g') <- g u
        return (v, g' . f')

mkGen :: (Monad m) => (a -> m b) -> Module m a b
mkGen f = let m = Module $ \x -> do
                    y <- f x
                    return (y, m)
           in m

instance (Monad m) => Arrow (Module m) where
    arr f = mkGen (return . f)
    first (Module f) = Module $ \(x, y) -> do
        (r, m) <- f x
        return ((r, y), first m)

instance (Monad m) => Functor (Module m a) where
    fmap f (Module k) = Module $ \x -> do
        (y, k') <- k x
        return (f y, fmap f k')

instance (Monad m) => Applicative (Module m a) where
    pure x = let m = Module $ \_ -> return (x, m)
              in m
    (Module f) <*> (Module k) = Module $ \x -> do
        (h, f') <- f x
        (y, k') <- k x
        return (h y, f' <*> k')

The above functions allow creating modules and combining them together in various ways.

Now one of the main functions is to step a module with no input/output, producing its next state:

step :: (Monad m) => Module m () () -> m (Module m () ())
step (Module k) = liftM snd (k ())

For example, in your case you'd have a counter module, that keeps an internal state:

counter :: (Monad m) => Module m () Int
counter = let m i = Module $ \_ -> return (i, m (i + 1))
           in m 0

And a state-less module that just prints what it gets and has no output

render :: (MonadIO m, Show a) => Module m a ()
render = mkGen (liftIO . print)

Their combination is a module with no input or output, and stepping them prints the counter each time:

main :: IO ()
main = do
    let m = counter >>> render
    step m >>= step >>= step
    return ()


Multiple dice roll game with multiple players

I can't yet comment, so a couple little things.
1. Your print statements are way too long. In your if statement those 4 prints can be one. And why the breaks in your intro statement (let + ' + s)?
2. Your logic gets a little messy in the case of a tie, though I suppose it will print both statements.
3. You may already know this, but you cannot concatenate strings with objects or integers in Python, and due to dynamic typing, it can be hard to keep track of thing.

This whole program could be produced in 2 functions. A function called win, which takes a variable winningPlayer, and a function called Roll for the dice. That would take care of your infinite loop as well.
NOTE: I'm bad with dynamic types. There are probably unnecessary casts to strings here, but I'm just showing the concept.

import random
import time
import sys
#Rolls the dice when players are wrong
def Roll(rollNum):
    print("The Dice rolled..." + str(rollNum))
    print("both wrong, rolling again...")
    reRoll = random.randint(1,6)
    time.sleep(1)
    return reRoll
#Generic function for what the winner and loser do; not player specific
def Win(winner, loser, prz):
    print("The Dice rolled..." + str(diceNumber) + "\n" + str(winner).upper() + "Wins\n" + str(loser) + " must " + str(prz))
#Copied from your code
print("lets play dice of destiny")
play1 = input("Player 1 name?")
play2 = input("Player 2 name?")
prize = input("What does the loser have to do?")
#slightly condensed your code
print("Hi " + play1 + " & " + play2 + ", let's roll the dice of destiny.")
#moved this to a more appropriate place
diceNumber = random.randint(1,6)
play1Num = int(input(play1 + " choose a number 1-6."))
play2Num = int(input(play2 + " choose a number 1-6."))
#changed while loop to roll the dice every time both are wrong
while play1Num != diceNumber and play2Num != diceNumber:
    diceNumber = Roll(diceNumber)
    play1Num = int(input(play1 + " choose a number 1-6."))
    play2Num = int(input(play2 + " choose a number 1-6."))
#Applies the win method to both players; an array would be a better approach
if play1Num == diceNumber:
    Win(play1, play2, prize)
elif play2Num == diceNumber:
    Win(play2, play1, prize)
#Array implementation of win (with more than 2 players, would be best done using *args in win)
players = [play1Num, play2Num]
for item in players
    if diceNumber == item:
        players.remove(item)
        Win(item, players[1], prize)


Before we comment on the speed issue, perhaps we should talk about the multithread correctness of step(from:to:). You are referencing memory and index. You appear to be updating the same memory from all of your threads. That is not thread-safe. Your don’t want multiple threads updating the same memory reference. If you temporarily turn on the thread sanitizer (known as TSAN, found in “Product” » “Scheme” » “Edit Scheme...” (or press ⌘+<) and then choose the “Diagnostics” tab), it may well warn you of this problem.

Let’s assume for a second that we get the thread-safety question behind us. The multithreaded performance concerns include:

Make sure you are striding to ensure that there is enough work on each thread, to ensure that the parallelism benefits are not outweighed by thread management overhead. That having been said, you are striding already with sufficient work on each thread, so that’s unlikely to be the problem here, but it often plagues naive parallelism attempts.
You may want to use concurrentPerform rather than just dispatching a bunch of blocks to a global queue and using a dispatch group to determine when they finished. The concurrentPerform will spin up the correct number of threads appropriate for your hardware, whereas if you write your own dispatching to concurrent queues, you might suboptimize the solution (e.g. you can exhaust the limited number of worker threads if you’re not careful).

In your case, the benefit of concurrentPerform will likely not be material, but it’s the first thing to consider when writing code that is effectively parallelized for loops. See https://stackoverflow.com/a/46499306/1187415 and https://stackoverflow.com/a/39949292/1271826 for introductions to concurrentPerform.
The key issue here is that one needs good algorithm design to minimize memory contention issues, cache sloshing, etc.

But let’s assume that you are really accessing/updating different index values through something not shared in your code snippet and are updating adjacent memory addresses. That can still result in problems. See below.

You said:

  I believe memory (and “recipe”) are going to need separate instances per “stride”. It's not clear to me exactly how that is slowing things down...

Yes, that’s likely the issue in this case. When writing multithreaded code, you have to be sensitive to the memory locations updated by parallel threads. For example, consider the following that adds the numbers between 0 and 100 million, updating an array of four values as it goes along, in parallel:

var array = Array(repeating: 0, count: 4)

DispatchQueue.global().async {
    DispatchQueue.concurrentPerform(iterations: 4) { index in
        for i in 0 ..< 100_000_000 {
            array[index] += i
        }
    }
    ...
}

Optimized for speed, that takes roughly 1.3 seconds on my machine (almost 3× slower than singled-threaded implementation). The issue in this contrived example is that we have multiple threads updating memory addresses very close to each other. You end up having CPU cores “sloshing” memory caches back and forth as the four threads are all trying to update the same block of memory.

For illustration purposes, consider the same code, except that instead of updating items right next to each other, I space them out by padding the array, grabbing the items at index values of 0, 1000, 2000, and 3000 (reducing CPU cache misses):

var array = Array(repeating: 0, count: 4 * 1000)

DispatchQueue.global().async {
    DispatchQueue.concurrentPerform(iterations: 4) { index in
        let updatedIndex = index * 1000
        for i in 0 ..< 100_000_000 {
            array[updatedIndex] += i
        }
    }
    ...
}

This is deliberately not touching much of the array, just updating four values. This looks absurd (and is not advisable) and one wouldn’t be faulted for assuming that this is far less efficient with all of that wasted memory. But it is actually 5× faster, taking roughly 0.25 seconds on the same machine.

That’s obviously an absurd example, but it illustrates the problem. But we can make it far more efficient like so:

var array = Array(repeating: 0, count: 4)

let synchronizationQueue = DispatchQueue(label: "sync")
DispatchQueue.global().async {
    DispatchQueue.concurrentPerform(iterations: 4) { index in
        var value = synchronizationQueue.sync { array[index] }
        for i in 0 ..< 100_000_000 {
            value += i
        }
        synchronizationQueue.async { array[index] = value }
    }
    ...
}

Even with the extra synchronization code to make sure that I have thread-safe interaction with this array, it’s still now another 5× faster, taking 0.05 seconds. If you can minimize updates to the same block of memory, you can have a material impact on performance, starting to enjoy the benefits of parallelism.

Bottom line, you have to be very careful about how multiple threads update shared memory blocks and balance workloads between the threads. It can have a considerable impact on performance.


Several odd elements in this code.

Pointless variables

These variables look pointless:

        var fullPath = e.FullPath;
        var changeType = e.ChangeType;

You could use e.FullPath and e.ChangeType where you need it, the extra local variables don't seem to have any purpose.

Garbage not filtered out soon enough

It's very strange to execute this code every time a file is created:

        _extensionList.RemoveAll(r => string.IsNullOrEmpty(r.Trim()));
        _ignoreList.RemoveAll(r => string.IsNullOrEmpty(r.Trim()));

Why do you need to filter out the garbage every time instead of doing it just once?

Even better: how did garbage every enter these lists? It would be better to prevent that, and organize your code in a way that it's impossible to enter garbage into these lists.

Lastly, the result of r.Trim() will never be null, so the null-check is pointless.

Why not use a Set ?

Instead of putting the extensions and ignored extensions into lists, it would be better to use sets instead. It will it a lot more efficient to check if they contain an element or not, without the need for lambdas.

Exception handling

The try block is to large. It's better to limit the scope of try blocks, to make it easier to see the piece of code where an operation might fail.

Instead of catching a generic Exception, it's better to catch the most specific kind of exception that can be thrown.


Extracting pattern and simplifying testing

One option would be to create a generic method that accepts delegates to the methods:

var combined = Combine(_builder.Build, _formatter.Format, _loader.Load, _selector.Select);
return combined(i);

The implementation would look like this:

public static Func<T1, T5> Combine<T1, T2, T3, T4, T5>(
    Func<T1, T2> f1, Func<T2, T3> f2, Func<T3, T4> f3, Func<T4, T5> f4)
{
    return input =>
    {
        var r1 = f1(input);
        var r2 = f2(r1);
        var r3 = f3(r2);
        var r4 = f4(r3);
        return r4;
    };
}

The implementation would need to have overloads for different number of delegates.

Also, I'm not completely sure whether this actually improves the situation. Your original code is very straightforward, this code is harder to understand, because it's not immediatelly clear what does Combine() do.


You created a working calculator. Let me suggest some improvements for the next program version.

First some formal aspects:

Read and follow the Java code conventions: e.g. variables and fields should begin lower-case, closing braces should be placed on their own line. We Java programmers are REALLY used to these conventions, so programs that don't follow them confuse us and lead to mis-interpretations.
Use an IDE that can automatically maintain a proper code indentation (the "switch" line is out of alignment).
Use spacing consistently (insert a space after an opening parenthesis or not?).
You can omit comments like //Close if the next line does exactly this, explicitly. Every reader of your program will see that you are closing your resource, even without your comment.
Use variable names like "operation" (good example), and avoid names like "xe", "xo", or "eo". A variable name should clearly tell what its content means.
Don't declare variables some lines before you use them (like you did with xe and xo). To me, that looks like old-fashioned C language from the 1970s.

So, a formally-improved version might be:

import java.util.Scanner;

public class Java101 {

    public static void main(String[] args) {
        System.out.println(" Welcome to Java Calculator v0.1 \n");
        Scanner scanner = new Scanner(System.in);

        System.out.println("\n Please enter two numbers");
        System.out.print("\n First number: ");
        int firstNumber = scanner.nextInt();
        System.out.print("\n Second number: ");
        int secondNumber = scanner.nextInt();
        System.out.println("\n Select between (*,/,+,-)\n Type out the character in a single letter: ");
        String operation = scanner.next();

        String eo = "You have selected ";

        switch (operation) {
        case "*":
            System.out.println(eo + "* \n Your Result: "+ ( firstNumber * secondNumber ));
            break;
        case "/":
            System.out.println(eo + "/ \n Your Result: "+ ( firstNumber / secondNumber ));
            break;
        case "+":
            System.out.println(eo + "+ \n Your Result: "+ ( firstNumber + secondNumber ));
            break;
        case "-":
            System.out.println(eo + "- \n Your Result: "+ ( firstNumber - secondNumber ));
            break;
        default: System.out.println("\n Please select a valid character");
        }

        scanner.close();
        System.out.println(" Closing Application ");
    }
}

Then regarding structure:

Don't do everything in the main() method. At least separate user interface and algorithmic tasks.
Run your program and have a critical look at the inputs and outputs. Some outputs are unnecessary, some info could be added. E.g. of the three input elements (two numbers and operation), why do you just repeat the operation in the result output?
Your program is procedural. Your next step should be to learn about object orientation. Then your application might get structured into a Calculator and  a CalculationTask class with methods like readTask(), compute() and printResult().


Python script to store nd array into images

Instead of:

ensure_directory_exist(image_path)

use the built-in os.makedirs:

os.makedirs(image_path, exist_ok=True)

Iterate over the images themselves (rather than their indexes) and so avoid the lookup img_array[i, 0] on each iteration:

for i, img in enumerate(img_array[:, 0, :, :]):
    name = "img{}.png".format(i)
    imsave(os.path.join(image_path, name), img)


Are these set-uid scripts/binaries secure?

Both of your programs are insecure. The problem is that I can set PYTHONPATH to anything I like before executing the program. I can set it to something so that it loads my own usb module which can execute whatever code I like. At that point, I'm executing code as the root user and can do whatever I please. That's why set-uid doesn't work on scripts, and your binary C program wrapper doesn't change that at all.

For more information see: https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts

In your case, what you should be doing is changing the permissions so that your user has access to the USB device you are supposed to be controlling. That way you don't need to run the script as another user. That's what this portion of the script you are using is referring to:

# If you have a permission error using the script and udev is used on your
# system, it can be used to apply the correct permissions. Example:
#  $ cat /etc/udev/rules.d/51-usbpower.rules
#  SUBSYSTEM=="usb", ATTR{idVendor}=="067b", MODE="0666", GROUP="plugdev"

Discussion of how to adjust your system to give you permission to access the USB device is out of scope for this site. I'm also not really an expert on that. So you may need to ask elsewhere for that.


Creating a struct-of-arrays database with encapsulating interface c++

There is a lot missing from this question, but there is enough code to be able to tell that a lot that could be improved.  Here are some ideas for improving your code.
Use all of the required #includes
All of the #includes for this code are missing in the description.  I believe the required list is this:
#include <complex>
#include <cstdint>
#include <memory>
#include <vector>

Provide complete code to reviewers
This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.  There is a bit of that in your question, so we'll start from there.
Start with the desired interface
It's usually very useful to start by imagining how we'd like to use the code before implementing the interface.  It appears that there exists some external source of orbital data (I'm guessing TLE) which this code is supposed to read and parse (not shown) and then provide storage and access methods.  First, rather than two separate classes, OrbitalDataBase and OrbitalAccessor, it seems clear to me that there should rather be a single OrbitalDataBase and that the accessor should be a member function.  That leads to the first simplification:
std::complex<double> coef(uint32_t ith_orbital, uint32_t i) const {
    return m_orbital_coefs[ith_orbital * nbas * number_of_lm_pairs_per_orbital[ith_orbital] + i];
}

Don't write this->
Within member functions this-> is redundant. It adds visual clutter and does not usually aid in understanding.
Use more whitespace for clarity
It's very difficult to parse the OrbitalDataBase constructor because it's all run together with very little whitespace.  I'd modify it to look more like this:
struct OrbitalDataBase {
  OrbitalDataBase(std::shared_ptr<FEMDVR> a_radial_grid, std::shared_ptr<AngularGrid> a_angular_grid)
      : nbas(a_radial_grid->getNbas())
      , number_of_lm_pairs_per_orbital()
      , m_orbital_coefs()
{
    m_orbital_coefs.reserve(a_radial_grid->getNbas() * a_angular_grid->getNumChannels());
}

Don't explicitly invoke implied constructors
The constructor, reformatted as above, reveals that the default and implied constructors for number_of_lm_pairs_per_orbital and m_orbital_coefs are explicitly called.  This is both unnecessary and unhelpful.  Simply omit those two lines.
Prefer const references to smart pointers
If you are passing in data, such as the FEMDVR and AngularGrid in this code, that are used but not altered, this implies const.  Further, if we are not sharing ownership, which appears to be the case here, these should be references rather than std::shared_ptr.
OrbitalDataBase(const FEMDVR& a_radial_grid, const AngularGrid& a_angular_grid)
    : nbas(a_radial_grid.getNbas())
{
    m_orbital_coefs.reserve(nbas * a_angular_grid.getNumChannels());
}

Understand modern use of inline
Based on how you're using it, it appears that you are abusing the inline keyword to get an effect that the compiler is already going to provide without it.  That is the inline specifier for functions used to be a request to the compiler to optimize by putting the code inline rather than creating an explicit function call.  However, this was only ever a suggestion, and the changing semantics of inline for C++17 and beyond are likely to lead to trouble unless very carefully used.  The reason is that, starting with C++17, it tells the compiler that multiple defifinitions are allowed, but if they differ in any way, invoking the function is undefined behavior.  For these reasons, you're better off omitting inline in most cases.
Rethink your data structures
Right now getting a value back uses this rather complex form:
std::complex<double> coef(uint32_t ith_orbital, uint32_t i) const {
    return m_orbital_coefs[ith_orbital * nbas * number_of_lm_pairs_per_orbital[ith_orbital] + i];
}

This is very cache unfriendly because it has to look up one value from number_of_lm_pairs_per_orbital and then use that to index into another vector.  It may make things more clear and give better performance if instead you defined a struct or class that encapsulated both.  The obvious would be this:
struct Orbital {
    std::vector<std::complex<double>> m_orbital_coefs;
};

Then OrbitalDataBase could use std::vector<Orbital> as its only data member, since the number of coefficients is m_orbital_coefs.size() and nbas is now m_orbital_coefs.size().
Even simpler might be this:
using Orbital = std::vector<std::complex<double>>;


Get all the PDF files from FTP server in different folders

Verify the return values of all the ftp_chdir() calls. Otherwise, you might be way off, fetching the wrong stuff.

Excessive nesting is a problem. As in most programming tasks, here you have one goal, and many things that can go wrong along the way. You want to return early if an error occurs. A general pattern to follow is:

if (OK1 != ($result1 = operation1(…))) {
    return null; # or however you want to indicate failure
}
if (empty($result2 = operation2(…))) {
    return $result2; # nothing more to do
}
$retval = array('something involving' => $result2);
return $retval;

Note that all calls to functions that can fail occur within a if condition. The handler for the exceptional case follows immediately, and usually involves bailing out. Then the success codepath is linear and doesn't need to be nested.


First : I recommend you to change this line in your code in order to anybody can use it easily without changing or editing it.

set SaveDest=C:\Users\ME\Desktop\Wallpaper\%dte%.jpg

by those lines :

set WallpaperFolder=%userprofile%\Desktop\Wallpaper
If not exist "%WallpaperFolder%" MD "%WallpaperFolder%"
set SaveDest=%WallpaperFolder%\%dte%.jpg

Second : If you want to hide the output of the console you can redirect it to NUL

for example : reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d %savedest% /f>nul

And this line too : timeout /t 1 /nobreak>nul

Third : Refer to How to force Windows desktop background to update or refresh

You can write it simply by this line and avoid the loop : RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters 1, True

So, the whole code can be written like this :

@if (@a==@b) @end /*
@echo off
Title Download NASA images to use as Windows wallpaper
color 0A & Mode 70,3
Set BaseUrl=https://apod.nasa.gov/apod/
set yr=%date:~8,2%
set mn=%date:~3,2%
set dy=%date:~0,2%
set dte=%yr%%mn%%dy%
set WallpaperFolder=%userprofile%\Desktop\Wallpaper
If not exist "%WallpaperFolder%" MD "%WallpaperFolder%"
set SaveDest=%WallpaperFolder%\%dte%.jpg
Set Url=%baseUrl%ap%dte%.html

setlocal
for /f "delims=" %%I in ('cscript /nologo /e:jscript "%~f0" "%Url%"') do (
    echo %%I
    set LastImg=%%I
)

set ImgUrl=%BaseUrl%%LastImg:~6%

bitsadmin.exe /transfer GETWALLPAPER "%ImgUrl%" "%SaveDest%"
echo(
echo        Please wait a while ... Update  UserSystemParameters
reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d "%savedest%" /f>nul
Timeout /t 1 /nobreak>nul
RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters 1, True
goto :EOF

JScript */
function fetch(url) {
    var xhr=WSH.CreateObject("Microsoft.XMLHTTP");
    var dom=WSH.CreateObject('htmlfile');
    xhr.open("GET",WSH.Arguments(0),true);
    xhr.setRequestHeader('User-Agent','XMLHTTP/1.0');
    xhr.send('');
    while (xhr.readyState!=4) {WSH.Sleep(25)};
    dom.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
    dom.write(xhr.responseText);
    return dom;
}
var dom=fetch(WSH.Arguments(0));
var link=dom.getElementsByTagName('IMG');
WSH.Echo(link[0].src);


Plotting points representing many events on a canvas

Optimising for performance.

Javascript has a way encouraging people to write code that is terribly inefficient.

You are lucky the problem is one that can get a lot of benefit from just some minor changes.

Memorize (binning) is not going to help, it will actually significantly decrease performance and massively increase your memory load. The crazy thing is you are already binning all the data in your code.

First the rendering

var paintDotS = function(pointX, pointY, color) {
        context.fillStyle = color;
        context.fillRect(pointX, pointY, 1, 1);
};

You are only plotting single pixels. For javascript to draw a pixel via the fillRect method there are 100's of CPU cycles needed, and all you do is set a single 32bit word.

To render pixels write them directly to a pixel buffer. When all the pixels have been rendered move the pixel buffer to the canvas.

var imageData = ctx.getImageData(0,0,ctx.canvas.width,ctx.canvas.height);
var dat32 = new Uint32Array(imageData.data.buffer);

The variable dat32 holds each pixel as a 32bit integer. The channel order is from high byte Alpha to low byte Red. Eg to write a yellow you would assign an array item dat32[index] = 0xFF00FFFF;

To write a pixel at a coord x,y

 const w = 300;  // the canvas width in pixels
 dat32[x + y * w] = colour;

Loops and function calls

A big performance killer is the context change required when you call a function. This is compounded if the function being called is indirectly called from another. Many times that calling function does a lot of vetting to ensure nothing goes wrong so more cpu cycles used for no reason.

The arrays iteration methods, forEach, Map, etc are agonisingly slow when compared to standard loops.

your code

var paintDotsAtOnce = function(plotColors) {
    plotColors.forEach(function(plotColor){
        if(plotColor.plotDot) {
           memoized(plotColor.pointX, plotColor.pointY, plotColor.color);
        }
    });
};

Array.forEach calls a function, that starts, then maintains the iteration, (first context change) it calls your iterator function (second context change), your iterator calls the memoized function (third context change) it makes a memory assignment and then calls your paintDots function (fourth context change).

Remember you are just setting 1 32bit word and you are already 4 levels deep into the call stack, each needs to create closures and context, and the memoize need to allocate memory. You paint the pixel and the whole process need to be undone.

Memory and Objects.

Creating objects is slow, like snail pace slow.

Your code

for (var i = 0; i < dataAsNumbers.length; i++) {
    x = dataAsNumbers[i][paramX];  // 1st copy x
    y = dataAsNumbers[i][paramY];  // 1st copy y
      // 1st object
    pointX = getPointOnCanvas({  // 4th copy of x in the function return
        value: x           // 2nd copy of x
        ratio: ratio
    });                    // 3rd copy of x in the function
      // 2nd object
    pointY = getPointOnCanvas({ // 4th copy of y in the function return
        value: y,          // 2nd copy of y
        ratio: ratio
    });                    // 3rd copy of x in the function
      // 3rd object
    toPlotColors.push({
        pointX: pointX,    // 5th copy of x
        pointY: pointY     // 5th copy of y
    });
}
paintDotsAtOnce(toPlotColors);

var getPointOnCanvas = function(params) {

    var value = params.value;
    var ratio = params.ratio;

    return Math.floor(ratio * value);
};

You could not have found a worse way to do this. remember you are writing 1 32Bit pixel, but you create x,y coordinates, then copy x to an object, which you pass to a function in which creates another copy, you return the computed value and store it in yet another copy. Then do it again for y. And once y is done you make yet another copy to be pushed to an array as a reference (even more memory used) (remember that memorize will also be making a copys).

X and y should be immediate, on the heap and then forgotten, no variables need be created, no object constructed, no allocation requests made.

The performance rewrite.

Move one 32Bit word to an array of pixels for each item in dataAsNumbers.

const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
const dat32 = new Uint32Array(imageData.data.buffer);
const w = canvas.width;
const color = 0xFFFFFFFF; // white
for (var i = 0; i < dataAsNumbers.length; i++) {
     dat32[(dataAsNumbers[i][paramX] * ratio | 0) +
           (dataAsNumbers[i][paramY] * ratio | 0) * w] = color;
}
ctx.putImageData(imageData, 0, 0);

Your code did not show where plotColor and plotDot came from. But they should be handled in the same way as above, without making function calls or creating objects. Everything is immediate and on the heap, and not making  allocation requests.

The beauty is that it is also has binned the data for you as the pixel array. You can make a copy and next time you need that data set just dump the pixel array to the canvas, in less than 1 ms


Convert a mix of latin 1 and UTF-8 to proper UTF-8

A useful idea, and very well implemented.

I'd re-write this condition:

while (!(index < buflen))

as

while (buflen <= index)

Apart from that, I found the code very readable.

It's a good idea to store the received data as int rather than converting to char immediately (though I do worry somewhat about using a signed type in code_point - perhaps its arguments should be narrowed to unsigned char?).

Another minor nit: it's not necessary to assign to buf[3] in the else case, although I see it might aid debugging.

I was never able to get an error return from the program (I tried closing stdout using >& in Bash, and also tried redirecting to /dev/full), but always got an exit status of 0.  That surprised me, as the code looks correct.


I am learning how to properly use Java parameters and arguments

Even with this simple example, there are a few things I can comment on.

Class names start with a capital letter.  ParamsAndArgs, not paramsAndArgs.

When parameters are passed to a method, those parameters should have values.  In your code, you're passing the doSomething method two parameters that have no values and aren't used in the doSomething method.  They're set in the doSomething method.

While naming a method doSomething is okay when you're not sure what the method does, you should change the name to something meaningful, like getInput, once you know what the method does. Generally methods are named with a verb, noun combination (get, Input).

Here's your code, reworked to be a more accurate example of parameters and arguments.
import java.util.Scanner;

public class ParmsAndArgs {

    static String name, feeling;

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        getInput(scan);
        System.out.println("Hello, " + name + ". I am feeling " +
                feeling + " too.");
        scan.close();
    }

    private static void getInput(Scanner scan) {
        System.out.println("What is your name?");
        name = scan.nextLine();
        System.out.println("How are you today?");
        feeling = scan.nextLine();
    }

}


Parse numbers from text based on relative position to certain substrings

As long as there are just a small number of patterns (and they hardly change) you can use a CASE to find the start position of the digits you want to extract and then simply extract the following n characters if they're digits:

CREATE FUNCTION fnExpectedBlend
    (
        @Item VARCHAR(30)
    )
RETURNS NUMERIC(15, 6)
AS
    BEGIN
        DECLARE @Pos INT

        SET @Pos =
        CASE-- PATINDEX plus length of search string
           WHEN PATINDEX('%BIO[0-9]%', @Item) > 0 THEN PATINDEX('%BIO[0-9]%', @Item) +3 -- PATINDEX plus length of search string
           WHEN PATINDEX('E[0-9]'    , @Item) > 0 THEN PATINDEX('E[0-9]'    , @Item) +1
           WHEN PATINDEX('NL[0-9]%'  , @Item) > 0 THEN PATINDEX('NL[0-9]%'  , @Item) +2
           WHEN PATINDEX('MG[0-9]%'  , @Item) > 0 THEN PATINDEX('MG[0-9]%'  , @Item) +2
           -- easy to extend with additional codes
        END;

    -- assuming there's up to 2 digits, otherwise add another WHEN
    RETURN ISNULL(CAST(CASE WHEN SUBSTRING(@Item, @Pos, 2) LIKE '[0-9][0-9]'
                            THEN SUBSTRING(@Item, @Pos, 2)
                            ELSE SUBSTRING(@Item, @Pos, 1) -- first character is always a digit
                       END AS NUMERIC(15,6)) / 100, 0)
END


One way to avoid using constant strings is to use the char.IsLetterOrDigit method, just restrict the values mod 92 and add to 33 to get all printable characters to 125:

enum Password_Options
{
    ALPHANUM,
    ALL
}
RNGCryptoServiceProvider rProvider = new RNGCryptoServiceProvider();
private string CreatePassword(int length, Password_Options options)
{
    StringBuilder res = new StringBuilder();
    byte[] random = new byte[1];
    using (rProvider)
    {
        while (0 < length--)
        {
            char rndChar = '\0';
            do
            {
                rProvider.GetBytes(random);
                rndChar = (char)((random[0] % 92) + 33);
            } while (options == Password_Options.ALPHANUM && !char.IsLetterOrDigit(rndChar));
            res.Append(rndChar);
        }
    }
    return res.ToString();
}

According to MSDN you should always dispose of the rng provider after using it.  One way is with a using block.


You code looks nice, my main problem with it is naming:

Don't use single letters as member names, unless they are trivial. I couldn't figure out what l and r stand for until I read your code a couple of times (length? range?).

Even more so, don't ever use the letter l as a variable name - it is much too similar to 1, and is notoriously known to obfuscate code.

Don't re-use too familiar names for different purposes - partition is a well known method in ruby enumerables. Using this name for your code, especially when it involves arrays is very confusing. Don't do that. Call it reorder_partition or pivot_partition.

Expressiveness goes a long way - a[l], a[r] = a[r], a[l] works perfectly, but is hard to read, a much more readable way would be if you had a helper method swap(a, l, r). Even better might look to implement it into Array a.swap!(l, r)

Use the power of ruby - instead of l..r-1, use non-inclusive range operator - l...r

So, my version may look a little more verbose, but I believe it is much more readable. It did teach me a lot about quicksort :-)

def quicksort(array, min=0, max=array.length-1)
  if min < max
    index = reorder_partition(array, min, max)
    quicksort(array, min, index-1)
    quicksort(array, index+1, max)
  end
end

def reorder_partition(array, left_index, right_index)
  middle_index = (left_index + right_index)/2
  pivot_value = array[middle_index]

  array.swap!(middle_index, right_index)

  less_array_pointer = left_index

  (left_index...right_index).each do |greater_array_pointer|
    if array[greater_array_pointer] <= pivot_value
      array.swap!(greater_array_pointer, less_array_pointer)
      less_array_pointer+=1
    end
  end

  array.swap!(less_array_pointer, right_index)

  return less_array_pointer
end

class Array
  def swap!(a,b)
    self[a], self[b] = self[b], self[a]
    self
  end
end


Speech Recognition Part 2: Classifying Data

Most of your comments aren't that great. Commenting about PEP8 compliance shouldn't be needed, and saying you're instantiating an object before doing it duplicates the amount we have to read for no actual gain.
os.path.join is much better at joining file locations by the OSes separator than '{}/{}'.format. Please use it instead.

An alternate to this in Python 3.4+ could be pathlib, as it allows you to extend the path by using the / operator. I have however not tested that this works with the functions you're using.

Here's an example of using it: (untested)

DATA_DIR = pathlib.PurePath('raw_data')

...

os.remove(DATA_DIR / 'All.wav')

You should move chunk out of the for loop, making it a function argument may be a good idea too.
Making a function to infinitely read your wf may ease reading slightly, and giving it a good name such as cycle_wave would allow people to know what it's doing. As it'd work roughly the same way as itertools.cycle. This could be implemented as:

def cycle_wave(wf):
    while True:
        data = wf.readframes(chunk)
        if data == b'':
            wf.rewind()
            time.sleep(1)
            data = wf.readframes(chunk)
        yield data

For your spec_filename you can use re.match to get a single match, rather than all numbers in the file name. You also don't need to use str on the object as format will do that by default.
Rather than removing a file from your directory, to then search the directory, you can instead remove the file from the resulting list from glob.glob. Since it returns a normal list, you can go about this the same way you would otherwise.

One way you can do this, is as followed:

files = glob.glob('D:/*')
try:
    files.remove('D:/$RECYCLE.BIN')
except ValueError:
    pass

If you have multiple files you want to remove you could instead use sets, and instead use:

files = set(glob.glob('D:/*')) - {'D:/$RECYCLE.BIN'}

All of this together can get you:

import glob
import sys
import os
import shutil
import wave
import time
import re
from threading import Thread

import scipy.io.wavfile
import pyaudio

DATA_DIR = 'raw_data'
LABELED_DIR = 'labeled_data'
answer = None

def cycle_wave(wf):
    while True:
        data = wf.readframes(chunk)
        if data == b'':
            wf.rewind()
            time.sleep(1)
            data = wf.readframes(chunk)
        yield data

def classify_files(chunk=1024):
    global answer
    join = os.path.join

    p = pyaudio.PyAudio()
    files = set(glob.glob(join(DATA_DIR, '*.wav'))) - {join(DATA_DIR, 'ALL.wav')}
    for filename in files:
        wf = wave.open(filename, 'rb')
        stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),
                        rate=wf.getframerate(),
                        output=True)

        for data in cycle_wave(wf):
            if answer is not None:
                break
            stream.write(data)

        # don't know how to classify, skip sample
        if answer == '.':
            answer = None
            continue

        # sort spectogram based on input
        spec_filename = 'spec{}.jpeg'.format(re.match(r'\d+', filename)[0])
        os.makedirs(join(LABELED_DIR, answer), exist_ok=True)
        shutil.copyfile(
            join(DATA_DIR, spec_filename),
            join(LABELED_DIR, answer, spec_filename)
        )

        # reset answer field
        answer = None

        #stop stream
        stream.stop_stream()
        stream.close()

    #close PyAudio
    p.terminate()

if __name__ == '__main__':
    join = os.path.join
    try:
        # exclude file from glob
        files = set(glob.glob(join(DATA_DIR, '*.wav'))) - {join(DATA_DIR, 'ALL.wav')}
        num_files = len(files)
        Thread(target = classify_files).start()
        for _ in range(0, num_files):
            answer = input("Enter letter of sound heard: ")
    except KeyboardInterrupt:
        sys.exit()

But I've left out proper handling of streams, in most languages, that I've used streams in, it's recommended to always close the steam. In Python it's the same. You can do this normally in two ways:

Use with, this hides a lot of the code, so it makes using streams seamless. It also makes people know the lifetime of the stream, and so people won't try to use it after it's been closed.

Here's an example of using it:

with wave.open('<file location>') as wf:
    print(wf.readframes(1024))

Use a try-finally. You don't need to add an except clause to this, as if it errors you may not want to handle it here, but the finally is to ensure that the stream is closed.

Here's an example of using it:

p = pyaudio.PyAudio()
try:
    stream = p.open(...)
    try:
        # do some stuff
    finally:
        stream.stop_stream()
        stream.close()
finally:
    p.terminate()

I'd personally recommend using one of the above in your code. I'd really recommend using with over a try-finally, but pyaudio doesn't support that interface. And so you'd have to add that interface to their code, if you wanted to go that way.


Python: Function to Find 2 Closest Points Among [x,y] Coordinates

If there are duplicate points in your list, and the closest point turns out to be one of these points, this line of code will remove all of the duplicates:
x_points_2 = [x for x in x_points if x != closest_xpoint_1]

So, instead of returning the 2 closest points, it may return just one of the closest, and some other nearby point.

Finding the n-smallest, n-closest, etc is usually best done using Python's heapq.nsmallest(n, iterable, key=None) function.

Return a list with the n smallest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key)[:n].
[This function] perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function. Also, when n==1, it is more efficient to use the built-in min() and max() functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap.

Example: a closest n points function, with n defaulting to 2:
import heapq

def closest_points(list_of_tuples, x_value, n=2):
    return heapq.nsmallest(n, list_of_tuples, lambda pnt:abs(pnt[0] - x_value))

Example:
>>> closest_points([(4, 6), (2, 5), (0, 4), (-2, 3)], 6)
[(4, 6), (2, 5)]


Let's count the number of times you're writing get.

if (people.getImages() != null && people.getImages().size() > 0 && people.getImages().get(0).getUrl() != null) {
    Url thumbUrl = people.getImages().get(0).getUrl().getThumb();
    // do something with the thumbUrl
}

5 times inside the if-condition and 4 times inside the block. That's a bit too much. Remember the Law of Demeter.

In your case I would do:

if (people.hasImage(0)) {
     Url thumbUrl = people.getImage(0);
}

The idea is to hide some logic inside the people object.

It also seems like people.getImages() is a Collection, which makes me think that it is a bad idea to ever let that be null. An empty collection is better than a null collection.

As for your main question, I believe Heslacher says it all:

An avoided exception is always better then a handled exception

This applies especially to NullPointerException and ArrayIndexOutOfBoundsException (and all other RuntimeExceptions).

Also, you should always catch the most-specific Exception possible. Never catch Exception. But then again, never catch NullPointerException. Fix your code to not cause one in the first place.

Related previous Code Review answers about exceptions:

Rethrowing exception just as an information

https://codereview.stackexchange.com/questions/45637/exception-handling-with-instanceof-rather-than-catch/45639#45639


Some general remarks:

Don't use namespace std;, see for example Why is “using namespace std;” considered bad practice?.
Don't put all the code into main(). Computing the determinant in a separate
function increases the overall clarity of the program and makes it easier to add
test cases. In addition, that gives you a function which can be reused in other
programs.
Swapping two values can be done in C++ simply with std::swap.
return 0; at the end of the main program can be omitted.

At some places your code does unnecessary work:

If the diagonal element a[i][i] is zero then all subsequent rows
with array[j][i] != 0 are swapped with the ith row. It suffices to
swap one row with a non-zero leading element.
When swapping rows i and j, it suffices to swap the elements starting
at column i because the preceding elements are not used anymore.
Similarly, when adding a multiple of row i to row j, it suffices to
update elements starting at column i + 1, because all values of column
i will not be read anymore.

As already said in the comments, the Gaussian elimination is faster than the
Laplace expansion for large matrices (\$ O(N^3) \$ vs \$ O(N!) \$ complexity).
However, the “pivoting” (i.e. which rows to swap if an diagonal element is zero)
can be improved. A common choice is “partial pivoting”:

  In partial pivoting, the algorithm selects the entry with largest absolute value from the column of the matrix that is currently being considered as the pivot element. Partial pivoting is generally sufficient to adequately reduce round-off error. ...

Using a (nested) std::vector for the matrix storage makes it
easier to pass it an argument to another function.
In addition, it allows to swap two rows in constant time with vector::swap.

Putting it all together, the determinant function could look like this:

#include <vector>
#include <cmath>

double determinant(std::vector<std::vector<double>> &matrix) {
    int N = static_cast<int>(matrix.size());
    double det = 1;

    for (int i = 0; i < N; ++i) {

        double pivotElement = matrix[i][i];
        int pivotRow = i;
        for (int row = i + 1; row < N; ++row) {
            if (std::abs(matrix[row][i]) > std::abs(pivotElement)) {
                pivotElement = matrix[row][i];
                pivotRow = row;
            }
        }
        if (pivotElement == 0.0) {
            return 0.0;
        }
        if (pivotRow != i) {
            matrix[i].swap(matrix[pivotRow]);
            det *= -1.0;
        }
        det *= pivotElement;

        for (int row = i + 1; row < N; ++row) {
            for (int col = i + 1; col < N; ++col) {
                matrix[row][col] -= matrix[row][i] * matrix[i][col] / pivotElement;
            }
        }
    }

    return det;
}


Printing multiplication table to 12 × 12

The multiplication table is missing formatting. I realise that, and will add it some time later, if I can figure out how to compare two values.

Comparing two values isn't that complicated, once you know how to do it. It is however extremely inefficient if you do it over and over again. Your best bet would be to hook into the printing of the number and print spaces if there are no hundreds or tens.

I managed to do a little proof-of-concept for this, which I am sure can be optimized further. The idea is the following:

Before the loop that prints the number of 100's, set a temporary flag on another cell
If the loop is entered, reset the temporary flag at the end
Outside the loop, go to temporary flag and if it is set, print a space. Clear the flag and go back to the cell.

The unformatted and unoptimized version of this enhanced "print the number" code is as follows:

        >++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]
        <<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>
        [+[-<+>]>+>>]<<<<<]>[-]>>

>>>+<<<[

    [x>++++++[-<++++++++>]<.<<+>+>[-]]

>>>-<<<]>>>[++++++++++ ++++++++++ ++++++++++ + . [-]]<<<

<

>>>+<<<[
    [y<[->-<]++++++[->++++++++<]>.[-]]
>>>-<<<]>>>[++++++++++ ++++++++++ ++++++++++ + . [-]]<<<

<<++++++[-<++++++++>]
        <.[-]<<[-<+>]                               print number gotten off SO

I have marked the loop where the 100's are printed with x and the loop for the 10's with y, to make it easier for you to see the changes I did.

  I realise it doesn't work for multiplication tables of 16 or higher, due to BF cell sizes being only 8 bits, or up to 255. The value 16 * 16 would result in 256, setting the value of the cell to be 0. Is this unavoidable? Or is there a trick to it?

There are some different possible solutions to this:

Use a Brainfuck interpreter that supports higher values (Disclaimer: That's my project)
Print value of cell as number for any sized cell
Use bit-width conversions
Perform the multiplication differently. This would involve a completely different approach of storing each individual digit in its own cell and doing the multiplication on a more detailed level, by looping over the digits and multiplying. I won't go into much more detail about this as it would require a lot of work.

I am unfortunately only experienced with using a Brainfuck interpreter that supports higher values. I don't know at all how the Bit-width conversions work, or how you are gonna do the number printing then.

  Does it make sense? (Considering it's Brainfuck, it shouldn't make sense...)

  Do my "comments" make sense?

Surprisingly much sense, yes. For a Brainfuck developer your code is quite easy to follow and your comments are helpful.

  Are there redundant commands that I can remove/reduce?

There are two places in your code where I am, without doing over-analysis, able to find optimization possibilities: How you structure your memory, and how you print the numbers.

When structuring the memory, think about which places you need to go, and in which order. Currently you have positioned the space (value 32) at index 0 on the tape, and yet it is one of the most accessed values. Positioning that closer to the "inner number", will allow you to go to it more easily.

The printing of the number is a common algorithm found at Stack Overflow, which is fine. But I have realized that it is a bit inefficient for printing multiple numbers, as it goes from value 0 to value 48 (ASCII value for '0') multiple times, and resets to 0 every time. It would be better to initialize a '0' into a cell and re-use that cell multiple times, without resetting it.


Code organization

The add_first_word() closure passes information via three nonlocal variables, which makes the code hard to understand.

I find it dissatisfying that the first word needs to be handled as a special case.  Instead, I would recommend using ' '.join(…) to help you add spaces conditionally.  That seems especially appropriate, considering that you also used .split().

It seems that you are using ui_util as a namespace rather than as a real class.  I would recommend just using the module for namespacing.  Furthermore, consider hiding or getting rid of the chunk_word() helper, in which case you would just have a word_wrap() function.

Naming

str is the name of a built-in type.  Avoid re-appropriating this conventional usage as a variable name.  I suggest renaming the parameter as text.

lines_final is an awkward variable name.  It implies that there is something wrong with lines.  I would say that if you split the text on explicit line breaks, then what you get is "paragraphs".

Style

In Python, parentheses around if conditions are extraneous, and therefore unconventional.

PEP 8, the official style guide, says:

  Pet Peeves

  Avoid extraneous whitespace… immediately inside parentheses, brackets or braces.

You wrote:

return [ word[i:i+length] for i in range(0, len(word), length) ]

Suggested solution

I think that it would make sense to convert this function into a generator.  Instead of accumulating all of the output in a lines_final list, you can just yield each line as it fills up.  (If the caller really needs a list, then use list(word_wrap(…)).)

Once you eliminate the special case as mentioned above, the code becomes much simpler.

def word_wrap(text, width):
    for paragraph in text.splitlines():
        line_len, line_buf = 0, []
        for word in paragraph.split():
            # If appending the word would cause overflow, flush the line.
            if line_len + len(line_buf) + len(word) > width:
                yield ' '.join(line_buf)
                line_len, line_buf = 0, []
            # If just this word alone would overflow, break it by force.
            while len(word) > width:
                yield word[:width]
                word = word[width:]
            line_buf.append(word)
            line_len += len(word)
        if line_buf:
            yield ' '.join(line_buf)

Example usage:

for line in word_wrap("…", 12):
    print(line)


I'm confused by the phrase “one way hash value” and so is probably whoever specified this requirement. In cryptography, a one-way hash function has a well-defined meaning.

  Let \$\Sigma\$ be an alphabet, for example, \$\Sigma=\{\mathtt{0}, \mathtt{1}\}\$. A family of functions \$(f_k)_{k\in\mathbb{N}}\$ with
  $$f_k: \Sigma^k \times \Sigma^* \to \Sigma^k$$
  is a family of one-way hash functions if and only if for each \$k\in\mathbb{N}\$, the \$f_k\$ is computable by a polynomial-time algorithm and for every probabilistic polynomial-time algorithm \$\mathcal{A}\$, given random \$K\in\Sigma^k\$ and \$h\in\Sigma^k\$, the output \$m^*=\mathcal{A}(K,h)\$ will satisfy \$f_k(K,m^*)=h\$ only with probability negligible in \$k\$.

  \$K\$ is called key or salt. It should be chosen randomly but need not be kept secret.

It is unknown whether such functions exist at all but there are some functions for which it hasn't been proved yet that they are not one-way functions.

If your function should compute such a cryptographic hash, I recommend that you look into one of the existing cryptographic hash function even though I doubt that you're supposed to implement one of these. (Although returning the result as a string would be meaningful in this context because for \$k>64\$, you usually cannot return the hash as an integer.) MD5 and SHA1 are two classical examples of cryptographic hash functions that are reasonably straight-forward to implement. The collision resistance (which is  a stronger requirement than the one-way property) of both of them is known to be broken in theory. (Both are also only specified for fixed \$k\$ which means that the above definition doesn't really apply.)

Since I see the word “hash table” in your code, I suspect that instead of a cryptographic hash function, they wanted to see a “simple” hash function that is fast to compute and has low probability of collisions but is not collision-resistant against malicious attackers. Again, have a look at algorithms other people already invented.

The Fowler-Noll-Vo hash function gives good hashes and is easy to implement. It can also be parametrized on the length of the result. I would recommend the FNV-1a variant as your go-to hash function unless you have reasons to chose differently.
Jenkins' one-at-a-time hash function is equally easy to implement and will probably be faster because it only uses additions and bit-wise operations as opposed to multiplications.
Weinberger's PJW hash function is known for its use in the UNIX ELF format and for being mentioned in the Red Dragon Book.
The lose-lose hash function is the one you've actually implemented. It's name should give you a hint. To your rescue, it was once used as an example by Kernighan and Ritchie.

There are numerous other hash functions and the literature / internet is full of comparisons between them. As you can imagine, while there are clearly better and less good functions available, there is also a lot of personal preference involved in deciding which function to use.

Even if you're planning to use the hash as index for a hash table, don't take the hash modulo the table size in the hash function itself. This will needlessly limit its usefulness. Whoever uses the function should be responsible for wrapping the computed hash into the table size.


AI agent fails when aligned with its target

⚔ A.I. vs. Physics

To solve this, you need to think a bit about the physics of your simulation, because it creates a problem for your A.I.

The funny thing is, you solved it by just altering the vectors a bit, but you seem to not understand why, so let us change that!

 May the force be with you

To put it simply: when you put two vectors on the same axis perfectly aligned, all that will happen is that the stronger force (i.e. greater vector) wins. Applying that to your simulation: when you align the agents on the same axis, the force of attraction towards the green agent wins over the repulsion from the red agent, forcing it ever closer towards it. I assume we all know what happens when the distances become zero, and you inevitably divide by zero? If you don't know: you can't. Other languages would panic, and Javascript just gives back NaN. Doing arithmetic with NaN will always yield NaN so the program still crashes somewhere down the line.

So that is the problem. But why did your "hack" fix it, and how do you embrace the fix as a proper solution?

 Solution

This is where the A.I. comes in. Think about it as if you were the blue agent: if you were walking straight towards an obstacle you are not allowed to touch, what would you do? I presume you would pick a direction, and turn into that direction to avoid the obstacle. Your agent is not as smart as you, so it does nothing and keeps its direction. When you added a tiny offset to its target vector, you decided it should change direction, albeit in a clunky way.

I propose you add a "preference" to the blue agent, deciding which direction to turn when it is perfectly aligned on some axis. You can use your fix, but I would personally prefer a solution to be more deliberate:

const degreesToRadians = degrees => degrees * (Math.PI / 180);
const rotate = (x, y, radians) => [
  x * Math.cos(radians) - y * Math.sin(radians),
  x * Math.sin(radians) + y * Math.cos(radians)
];

const preference = degreesToRadians(15);
const inProximity = lengthObstacle < 60;
const aligned = vectorTargetX === 0 || vectorTargetY === 0;

if (inProximity && aligned) {
  [agentX, agentY] = rotate(agentX, agentY, preference);
}
```


Advent of Code 2017 Day 6 (part 1) in Functional Programming (FP)

Explanation

Algorithm

First we have to break down witch steps we have to do:

split bank string to an array
change all string values to a number
reallocate

reallocationRoutine

The algorithm above would look like this in JavaScript:

const reallocationRoutine = pipe (
    split (' '),                    // split number by space
    map (Number),                   // cast String to a number
    reallocation ([]) (0)           // reallocate with initial values
)

reallocationRoutine ('0 2 7 0')     // will return 5

Pipe is a kind of function composition.

reallocation

  I used loops and mutate variables inside my functions

You can avoid muting loops and variables by writing recursive functions. The cool thing about recursive functions is that the logic can be broken down into small steps:

we need the first index of the biggest number
we need the biggest number itself
if our store (memoryBanks) includes the current state (input)

we return the current cycleCount

else we call reallocation again, but there for we need to:

update the memoryBanks with the current input
increment the cycleCount
and redistribute the input

So it can looks like:

const reallocation = memoryBanks => cycleCount => input => {
    const firstIndexOfMax = input.indexOf(Math.max(...input))
    const max = input[firstIndexOfMax]
    return contains(memoryBanks, input)
        ? cycleCount
        : reallocation
            ( memoryBanks.concat ([input]) )
            ( increment (cycleCount) )
            ( redistribute (input) (firstIndexOfMax) (max) )
}

I used the ternary operator for conditions. The reason why is much more than only because it is shorter.
A if should always have an else and the ternary operator forces you to.

redistribute

Instead of putting the entire logic in redistribute, I wrote a function calledloop that traverses an array for a certain number of steps (steps) and a function (fn) on the current index of the passed array (xs) for each step. So we can create a more generic solution - one of the main ideas of FP.

const loop = fn => xs => index => steps =>
    steps <= 0
        ? xs
        : loop
            ( fn )
            ( changeArrayValueOnIndex(index, fn(xs[index]), xs) )
            ( getNextIndex(xs, index) )
            ( steps - 1 )

redistribute is a special form of loop where we increment each index we reaches and modify the passed input xs so, that the start value gets set to 0

const redistribute = xs => index =>
    loop (increment) (changeArrayValueOnIndex(index, 0, xs)) (getNextIndex(xs, index))

Working Example

Overall, the code is longer than the imperative solution, but only because I've encapsulated a lot of logic into its own function like increment and loop. However, these are now functions that we could reuse in our next project and, in addition, we can test everything much easier :)

// helper functions
const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)))

const map = fn => arr =>
    arr.map(fn)

const split = delimiter => str =>
    str.split(delimiter)

const arrayIsEqual = ys => xs =>
    xs.length === ys.length
        ? xs.every((x, index ) => ys[index] === x)
        : false

const contains = (xss, ys) =>
    xss
      .map(arrayIsEqual(ys))
      .some(bool => bool)

const getNextIndex = (arr, index) =>
    arr[index + 1] != undefined ? index + 1 : 0

const increment = x =>
    x + 1

const changeArrayValueOnIndex = (index, value, array) =>
    [].concat(array.slice(0, index), value, array.slice(index + 1))

// functions for businesslogic
const loop = fn => xs => index => steps =>
    steps <= 0
        ? xs
        : loop
            ( fn )
            ( changeArrayValueOnIndex(index, fn(xs[index]), xs) )
            ( getNextIndex(xs, index) )
            ( steps - 1 )

const redistribute = xs => index =>
    loop (increment) (changeArrayValueOnIndex(index, 0, xs)) (getNextIndex(xs, index))

const reallocation = memoryBanks => cycleCount => input => {
  const firstIndexOfMax = input.indexOf(Math.max(...input))
  const max = input[firstIndexOfMax]
  return contains(memoryBanks, input)
    ? cycleCount
    : reallocation
        ( memoryBanks.concat([input]) )
        ( increment(cycleCount) )
        ( redistribute (input)(firstIndexOfMax)(max) )
}

const reallocationRoutine = pipe(
    split (' '),
    map (Number),
    reallocation ([]) (0)
)

console.log('0 2 7 0:', reallocationRoutine('0 2 7 0'))
console.log('2 8 8 5 4 2 3 1 5 5 1 2 15 13 5 14:', reallocationRoutine('2 8 8 5 4 2 3 1 5 5 1 2 15 13 5 14'))


Efficiency and techniques for Matrix class that inherits from Python's list

This review will focus on using Python more effectively.  I will pull some examples from your Matrix class, and show those recast in a more Pythonic fashion.
Pep8
But before we start, you should consider formatting your code in accordance with pep8.  This is important when sharing code, as the consistent style makes it much easier for other programmers to read your code.  There are various tools available to assist in making the code pep8 compliant.  I use the PyCharm IDE which will show pep8 violations right in the editor.
No Semi Colons
On the same front, lose the semi colons, they are very rarely (never really) needed in Python.
Iterate directly
Python has many great ways to iterate. In general if you find yourself looping on an integer, like in the following code, there is a good chance you are doing it wrong. It is generally better to iterate on the data structure itself.  This example:
def __add__(self, M):
    res = Matrix(self);
    for row in range(self.nrow()):
        dumrow = [self[row][col] + M[row][col] for col in
                  range(self.ncol())];
        res[row] = dumrow;
    return res

Can be reduced to:
def __add__(self, M):
    return Matrix([[sum(x) for x in zip(*rows)] for rows in zip(self, M)])

Note that the lengths of the rows or columns are not even looked at in this code.  The underlying iterators take care of those details.
zip() is transpose
This hand coded transpose:
def transpose(self):
    return Matrix(
        [[row[i] for row in self] for i in range(self.ncol())]);

can be recast to:
@property
def transpose(self):
    return Matrix(map(list, zip(*self)))

zip() does the transpose, and the map(list(...)) converts the tuples from zip to lists. And...
@property make for a cleaner interface
Instead of:
def nrow(self):
    m = len(self);
    return m

Consider this instead:
@property
def nrow(self):
    return len(self)

It does two things:

Removes unneeded intermediate values
Use the @property decorator to allow calculated value to be returned without the need for the ().  This can provide a cleaner api.

Full Listing
class Matrix(list):

    def __init__(self, the_list):
        super().__init__(the_list)

    @property
    def nrow(self):
        return len(self)

    @property
    def ncol(self):
        return len(self[0])

    def get_dim(self):
        return self.nrow, self.ncol

    def __add__(self, M):
        return Matrix(
            [[sum(x) for x in zip(*rows)] for rows in zip(self, M)])

    def __mul__(self, M):
        return multiplication(self, M)

    def __rmul__(self, M):
        return multiplication(M, self)

    def add_rows(self, rows):
        super().extend(rows)

    def append(self, row):
        try:
            sum(row)  # Check if all numbers
            if len(row) < self.ncol:
                row.extend([0] * (self.ncol - len(row)))
            elif len(row) > self.ncol:
                [row.pop() for i in range(len(row) - self.ncol)]
            super().append(row)
        except:
            raise AssertionError('Elements in row must be mumbers')

    @property
    def transpose(self):
        return Matrix(map(list, zip(*self)))

    def show(self):
        print("Printing matrix: ")
        for i in self:
            print(i)


Using an extension method for a small helper task that (ab)uses the fact that the object is not dereferenced

You might want to look into code contracts instead, which allows you to write:

Contract.Requires<ArgumentNullException>(smtpServer != null);

This expresses clearly what you are trying to do, and has the added advantage of allowing additional static checking by the code contracts tool to check the code that calls your method for possible violations of the contract.


Bash script to validate a MySQL database

Prefer portable shell

There's no reason to use Bash [[ where [ will do, unless you already depend on other Bash features (such as arrays).  This will of course increase the number of places where you must:

Quote parameter expansions

In expansions like $(basename -s .sql $1), don't forget the quotes:

[[ $(basename -s .sql "$1") =~ ${release_format} ]]
# I removed `&& return 0 || return -1` - see next item

Let exit status flow naturally

The Bash manual says:

  When executed, the exit status of a function is the exit status of the last command executed in the body.

This means that adding return $? to the end of every function adds no value, as do constructs such as && return 0 || return -1 - just let success/fail flow through.

Put credentials in a separate file

Don't put user and password in the script (particularly if you want to put it into a version control server).  Instead, require each user to provide their credentials in a (non-world-readable) file.  If you're particularly diligent, you could fail the script if the permissions on the credentials file are too permissive.

Don't invoke ls just to check existence

# true if the first argument exists
one_exists()
{
    test -e "$1"
}

ensureRollback() {
     test -n "$1" && one_exists "${rollbacks}/$(toTicket ${1})"*
}