How to improve this session cache to search faster

First you should rename your instance members in ActiveConnections class - having methods and variables named getOne(), getTwo(), etc, are horrible because at first you'd expect them to return the int value of one, two, three (e.g., returning 1, 2, 3) but in reality they most likely won't.
You should either put a lock on your cache or use a ConcurrentMap or you will sooner or later experience race condition errors.
Your send methods should be renamed to get because you are not sending them anywhere, you are returning them.
You should consider setting a memory/element limit on your cache; ex. it should only hold 101 cached items and when this limit is reached you apply a Least Recently Used policy and remove the X amount of LRU cache items.
Your getCache(..) and addCache(..) should be renamed because you are not getting nor adding a cache, but rather a cache item.
Your getCache(..) should have ActiveConnection as the return type

If you want a kind of Sliding Expiration policy where you remove items that are older than 5 seconds there are a few things to keep in mind:

5 seconds are a very short period of time; and
You need a way to map a timestamp to a cache item. A very simple way of doing this is making a nested class, e.g., CacheItem, which only holds a timestamp and a value and your map will consist of a <string key, CacheItem value>

edit

Here is an example of a very simple cache class I wrote in C# (just for reference). For the test cases I've ran it through it works fine, but you might want to check into existing cache libraries.

public class SimpleCache
{
    public const int MAX_CACHE_SIZE = 101;
    public long CacheExpirationTicks { get; set; }
    private ConcurrentDictionary<string, CacheItem> _cache = new ConcurrentDictionary<string, CacheItem>();

    public SimpleCache() { CacheExpirationTicks = 30000; /*default*/ }

    public void Add(string key, object value)
    {
        //if the cache limit is reached we apply a LRU policy on the cache and remove half of the cache ( MAX_CACHE_SIZE / 2 ) least recently used
        if (_cache.Count == MAX_CACHE_SIZE)
        {
            foreach (var cacheItem in _cache
                .OrderByDescending(x => x.Value.LastAccessed)
                .Skip(MAX_CACHE_SIZE / 2))
            {
                CacheItem ignored;
                _cache.TryRemove(cacheItem.Key, out ignored);
            }

        }
        _cache.TryAdd(key, new CacheItem() { Value = value, LastAccessed = DateTime.Now.Ticks });
    }

    public object this[string key]
    {
        get
        {
            if (_cache.ContainsKey(key))
            {
                if ((_cache[key].LastAccessed + CacheExpirationTicks) > DateTime.Now.Ticks)
                {
                    return _cache[key].Value;
                }
                CacheItem ignored;
                _cache.TryRemove(key, out ignored);
            }
            return null;
        }
    }

    internal sealed class CacheItem
    {
        //despite of it's name, LastAccess will *AND SHOULD* only be set once. The cache will validate its item in the get and add function and remove them by itself
        public long LastAccessed { get; set; }
        public object Value { get; set; }
    }
}

And you would implement it like this

public class Program
{
    public static SimpleCache simpleCache = new SimpleCache();

    static void Main(string[] args)
    {
        DataTable dt = GetDataTableFromCSVFile("myCSV.csv");
    }

    private static DataTable GetDataTableFromCSVFile(string csv_file_path)
    {
        object obj;
        if ((obj = simpleCache[csv_file_path]) != null)
        {
            return (DataTable)obj;
        }
        else
        {
            var csvData = ExpensiveOperation();
            var key = csv_file_path;

            simpleCache.Add(key, csvData);

            return csvData;
        }
    }
}


Not sure if it counts as an answer, but the most important missing part was the following ASP.NET Core attribute:

public class AmbientContextAttribute : Attribute, IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        using (new Op(context.HttpContext.Request.GetDisplayUrl()))
        using (new Cancellation(context.HttpContext.RequestAborted))
            await next();
    }
}


Formatting big integers as hexadecimal digits separated by colons

In Go, we usually expect reasonable performance and brevity. For example,

package main

import (
    "encoding/hex"
    "fmt"
    "math/big"
)

func formatSerial(serial *big.Int) string {
    b := serial.Bytes()
    buf := make([]byte, 0, 3*len(b))
    x := buf[1*len(b) : 3*len(b)]
    hex.Encode(x, b)
    for i := 0; i < len(x); i += 2 {
        buf = append(buf, x[i], x[i+1], ':')
    }
    return string(buf[:len(buf)-1])
}

func main() {
    fmt.Println(formatSerial(big.NewInt(1234)))
    // "04:d2"
    fmt.Println(formatSerial(big.NewInt(123456)))
    // "01:e2:40"
    fmt.Println(formatSerial(big.NewInt(1234567891011121314)))
    // "11:22:10:f4:b2:d2:30:a2"
}

Output:

04:d2
01:e2:40
11:22:10:f4:b2:d2:30:a2

Benchmark: serial := big.NewInt(1234567891011121314):

BenchmarkPeterSO         3000000       552 ns/op        72 B/op      3 allocs/op
BenchmarkKissgyorgy       500000      2545 ns/op       120 B/op      7 allocs/op
Benchmark200Success        30000     40675 ns/op     40675 B/op     35 allocs/op


A method that calls multiple async tasks with error handling, done the right way?

According to my understanding your piece of software can finish in one of the following states:

Succeeded
Failed
Timed out

You are not exposing the ability to cancel it on the top level. So, it is not cancelable.
Your explicit cancellation mechanism is not needed because:

If timeout occurs at the top level then this fact will be available for all async methods, which received the CancellationToken. The built-in BCL functions will check the token's validity so you don't have to worry about it.
SendMessage and Listen are called sequentially. So if former fails then latter won't be called.
After connectAsync your IsCancellationRequested is pointless. If connectAsync succeeded then this property won't be true. If it was not succeeded then you would not reach this line because your Listen function will be aborted.

On the other hand there is one place where it could make sense to check the cancellationToken. That's inside the do-while loop because the ReadLineAsync is not cancellable.
So let's put all this together with these in mind. I've converted your code into C# 8 if you don't mind.
Listen
public async Task<string> Listen(CancellationToken ct)
{
    try
    {
        await using var _pipeClientStream = new NamedPipeClientStream(".", "MyListenPipe", PipeDirection.In, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation);
        await _pipeClientStream.ConnectAsync(ct);

        var sb = new StringBuilder();
        using var reader = new StreamReader(_pipeClientStream);
        do
        {
            ct.ThrowIfCancellationRequested();
            string line = await reader.ReadLineAsync();

            if (line == MessageFooter || line == null)
            {
                break;
            }
            sb.AppendLine(line);

        } while (true);

        return sb.ToString();
    }
    catch
    {
        return "";
    }
}

The NamedPipeClientStream is IAsyncDisposable that's why I used await using.
The StreamReader is IDisposable that's why I used using.
I've checked the CancellationToken before each ReadLineAsync because it is not cancellable.

SendMessage
public async Task SendMessage(string message, CancellationToken ct)
{
    await using var _pipeClientStream = new NamedPipeClientStream(".", "MyPipe", PipeDirection.Out, PipeOptions.Asynchronous);
    await _pipeClientStream.ConnectAsync(1000, ct);

    await using var writer = new StreamWriter(_pipeClientStream) { AutoFlush = true };
    await writer.WriteLineAsync(message.AsMemory(), ct);
    await writer.WriteLineAsync(MessageFooter.AsMemory(), ct);
}

WriteLineAsync can accept CancellationToken only if it is called with a ReadOnlyMemory or with a StringBuilder. That's why I used AsMemory.
StreamWriter is IAsyncDisposable that's why I used await using.

GetValueUsingNamedPipe
public async Task<string> GetValueUsingNamedPipe(CancellationToken ct)
{
    await SendMessage("MyMessage", ct);
    return await Listen(ct);
}

The sendMsg variable is pointless because right after the assignment it is awaited then never used.
I've removed the try-catch block because in that way the TaskCancelledException would be caught here.
So basically if you wish you can inline this method into the CheckForValue

CheckForValue
public async Task<bool> CheckForValue()
{
    const int timeout = 300;
    try
    {
        using var timeoutTokenSource = new CancellationTokenSource(timeout);
        var result = await GetValueUsingNamedPipe(timeoutTokenSource.Token);
        return (result == "WhatIWant");
    }
    catch (TaskCanceledException) //The actual type will be TimedOutTaskCanceledException
    {
        return false;
    }
    catch (Exception) // GetValueUsingNamedPipe failed for some reason
    {
        return false;
    }
}

All the explicit cancellation calls are gone, because they are not needed. The cancellation fact will be propagated all the related parties and it will manifest in a TaskCancelledException.
So it is much cleaner now. :D

I hope it helped you a bit.


Indentation
Be sure to indent your code properly. Indentation helps the reader understand where he is in the code (how deep). Some languages actually depend on correct indentation.

Meaningful names
You should give your variable names which will have meaning, and will help the reader of your code understand what each one is responsible for. Names like w, t, j should not be used for any variable other than immediate throw-away variables like if for(i = 1;....

A variable name l should never ever be used, since it is too easily confused with the digit 1, so in some fonts you will never know the difference between l+=1 and l+=l...

Your code should tell a story
Try to design your code in a way that a reader will be able to follow your logic. In your code, there is an endless loop, and in the first if you check whether a mysterious j is 10, and if it is you end the game... The story starts with the ending!

A more pleasing option might be:

while number_of_turns_played < 10 do

  # play a turn...
  number_of_turns_played += 1

end

if number_of_wins > number_of_losses
  puts "You won the game"
elsif number_of_wins < number_of_losses
  puts "You lost the game"
else
  puts "The game is a draw"
end

This way the story has a beginning, and an end, and it easier to follow.

Choose your types
What is i used for? As far as I can see it can have only two values - 0 and 1, and it is used to flag the get input loop that a valid input has been received. The name i is cryptic enough - why not at least make it a boolean?

Block format conventions
It is idiomatic in ruby to use {} syntax for one liner blocks, and do end syntax for multiline blocks.
Instead of writing:

choice.each {
  |x|
  # do something
}

You should write:

choice.each do |x|
  # do something
end

Too sophisticated for your own good
Let's look at the condition you worked so hard on for being lazy:

if (com == "scissor" and human != "rock") or (human == "scissor" and computer !=1)
 v = human <=> com
else
 v = com <=> human
end

First - be consistent - on one side check com and on the other you check computer - choose!
Using esoteric operators - the "spaceship" operator (a<=>b) is used when sorting arrays, and returns -1 if a is smaller than b, 1 if a is larger than b, and 0 if they are equal. It is very rarely used, and your usage, while cute, might be very unclear for most (I know I had to double check what it returns). Is it really needed?
Assumptions - you rely on the fact that "paper" is smaller than "rock", which is smaller than "scissor", and you write your algorithm around that assumption. You are relying on an incidental fact, which might change when, say, you translate it to another language! Don't make incidental assumptions, use your code to define your rules.
When there are too many exceptions to the rule - so you found a cool rule, which is good for [almost] all your cases. That is all but two, out of six... which is four... which is just about half the cases... Which you will need to explain to anybody who reads the code, since it is not apparent from how the code is written... Maybe it is not that good a rule?

So, what would I suggest?

Say I set the choices to %w(rock paper scissors), where each choice beats the one prior to it, now I can ask:

computer_choice_idx = rand(3)
if human_choice == choices[computer_choice_idx]
  # draw!
elsif human_choice == choices[computer_choice_idx - 1]
  # computer beats human!
else
  # human beats computer!
end

Since in ruby choice[-1] returns the last element in the array ("scissors"), there is no exception! If the computer chose "rock"(id 0) and the human chose "scissors" - computer will beat human, since "scissors" == choices[-1].

In short:

Choices = %w(rock paper scissors)

puts 'Rock, paper or scissors'
draws = wins = losses = 0
10.times do
  begin
    puts "-----------------please enter rock paper or scissors-----------------"
    human_choice = gets.chomp.downcase
  end until Choices.include?(human_choice)

  computer_choice_idx = rand(3)

  puts "You chose #{human_choice}, computer choose #{Choices[computer_choice_idx]}"

  if human_choice == Choices[computer_choice_idx]
    puts "---->draw"
    draws += 1
  elsif human_choice == Choices[computer_choice_idx - 1]
    puts "---->Computer wins"
    losses += 1
  else
    puts "---->You win"
    wins += 1
  end
end
puts "wins : #{wins}\nlosses : #{losses}\ndraw:    #{draws}"
if wins > losses
  puts "You won the game"
elsif wins < losses
  puts "You lost!"
else
  puts "The game is a draw"
end

Enjoy!


Take previous element from array if condition on current element matches

This code would benefit from a previous variable...... and it would also benefit from being real code, not this hypothetical example..... This code is also really short, so it's hard to simplify more.

Still, using a foreach is better than the indexed iterator, and the logic is more obvious with named variables, rather than indexes... so:

private object[] array;
public abstract bool Condition(object o);
//...
private object FindStuff()
{
    object previous = null;
    foreach (object current in array)
    {
        if (Condition(current))
        {
            return previous;
        }
        previous = current;
    }
    throw new ItemNotFoundException();
}


Running parallel tasks until they're done

1) The library you are trying to use clearly does not fit your requirements. So why force it? Aren't you essentially just calling:

var tasks = Enumerable.Range(0, tasks).Select(i => DoWithRetries(action, retries, method));
await Task.WhenAll(tasks);

2) Fatal error is an error that your software cannot recover from. If you just swallow it in retry loop and keep going, then it is not fatal.

3) Delay duration should probably be a parameter and not a hardcoded value.

4) You can use nameof operator instead of MethodBase.GetCurrentMethod().Name.

P.S. I don't know what ThreadExecutor is and I didn't understand your use-case example, so I won't comment on those.


Few minor things:

If TaskManagerWithFeedbackDialog is not a nested class then internal is redundant and can be dropped.
TaskManagerWithFeedbackDialog has - so far - just one single static method. Until you will add more methods make it a static class. No need to create any instance.
TController instance is disposed just after task started (see it's wrapped in using). When you will invoke CloseView() you will call it on an already disposed object. Is it just a factory? Call it *Factory instead of *Controller. Is it a controller? Don't dispose it immediately but when you close the view (and check why your Dispose() method does nothing).
Why RunTask() instead of StartNew() or - better - Run() as Task and TaskFactory methods? I'd favor consistency with framework classes.
Is there a specific reason you're using Task.Factory.StartNew() instead of Task.Run()? EDIT: OK, you're with .NET 4.0.
_AsyncTaskManager (which BTW shouldn't be prefixed, it's optional for private fields and to avoid for types) is superfluous. It's just one method, it has no state and it's not persisted or passed around. You don't need a class but a simple private method.
Task has a fluid interface, you can concatenate method calls return Task.Run(...).ContinueWith(...).ContinueWith(...).
In CloseView() you wait for dispatched action to terminate but you don't actually need to wait for UI to push thread back to the pool, in WinForms you may simply use BeginInvoke() because it doesn't need EndInvoke() to be called.

Ideally you wouldn't even need continuation tasks:

Task.Factory.StartNew(() => {
    try
    {
        return taskFunc();
    }
    finally
    {
        feedBackView.CloseView();
    }
});

About exception management: you're doing right, if it's the way you want to handle errors. You close your view but AggregateException goes unnoticed. Here you may want to log such errors or to propagate them to UI thread (for example) again using BeginInvoke. See MSDN for more details.


It's better to separate the validation from the save operation and to use a constraint object to setup the rules which be applied to the entity. So you get a better separation of concern, which is one of the keys to good OOP architecture. I propose something like this:

$user = new User;
$user->setName( 'Peter' );
$user->setEmail( 'peter@email.com' );
$validator = new Validator(new UserConstrainte));
if( $validator->validate($user)){
    $databaseStuff->save($user)
} else {
    $error = $validator->getErrors()
}

I advise you to check the validator component from symfony2: https://github.com/symfony/Validator which is really well designed.


Writing a recursive factorial function in x86-64

Input Handling
At least at first glance, it looks like this doesn't handle the factorial of zero correctly. 0! is equal to 1, so fixing it is pretty trivial, by changing jne _factorial to ja _factorial:
# if it is the base case, return 1 and exit
cmp $1, %edi
ja _factorial
mov $1, %eax
ret

Since factorial isn't (at least normally) defined for negative numbers, I've treated the input as unsigned. If you want to treat it as signed, you'd use jg instead of ja.
Register Usage
mul produces a result in edx:eax, not just in eax, so you normally want to clear edx before you start doing your multiplications.
Stack Frame
I would rewrite the function a bit to use an internal function for the recursion. That internal function would use a purely register-based calling convention to avoid setting up a stack frame for every invocation.
Using Intel syntax, I'd write the code something on this general order:
; when first called, input value in edi
; and edx:eax containing 0:1
; result: factorial in edx:eax
;
internal_factorial:
    mul eax, edi
    sub edi, 1
    jz  done
    call internal_factorial
done:
    ret

Then the main routine would be something on this general order:
factorial:
    mov eax, 1    ; prepare our 64-bit result value in edx:eax
    xor edx, edx
    cmp edi, eax  ; check for (either) base case
    jbe do_ret    ; if it's not a base case, compute the factorial
    call internal_factorial
do_ret:
    ret


PHP framework building: initializer and object loader classes

As promised in the comments I would write a more extensive answer. So here it goes.

Before I start I would like to say that I think it is a perfect learning opportunity building your own framework. I have been in the process of creating my own the last year or so. I started from scratch with little knowledge of the different things, so the things I point out in this answer is a mixture of experience (from trial and error) and best practices I have learned as valuable over that year.

I think the code you have provided shows you have a basic (though bare minimum) idea of how the code should work, a good start. Everything mentioned below should be taken as my way of helping you and pointing out errors that I made and I wished somebody helped me correct sooner.

The Initializer class

First of, your Initializer class attempts to load classes by declaring the include path and extensions over and over and THEN load the class. This should only be done once. It happens because you have provided the name of the function autoload to the spl_autoloader_register. PHP then runs this function each time a class is loaded. You then make a call to spl_autoload() which is irrelevant. A call to spl_autoload_register() with no parameters is just a good, in fact it might be a little faster as it is written in highly optimized code by PHP.

I feel like the initializer class needs another name. All it is doing is setting up autoloading of classes. A more appropriate name could be Autoloader?

Now to the class itself. The class uses static methods. I think the use of static methods has it place, but it is misused here. The autoloader class should only be instantiated once, so the need for static properties is not required.

When declaring paths to directories in which your classes resides, consider using fully qualified paths as they are a little faster than their relative counterpart. When loading a lot of classes this little improvement can save you some resources. Fully qualified paths can be achieved by:

$directories = []; // An array of directories.

/*
 * Hard-coding the paths when all paths are known would be preferred.
 * The function realpath() requires executable rights on all directories used.
 */
foreach($directories as $key => $directory) {
    $directories[$key] = realpath($directory);
}

Another thing which caught my eye was the hardcoded properties. Part of the solid principle states that a class should be open for extension, but closed for modification. This can be easily achieved by providing the directories/paths and extensions used as arguments in a constructer of the class. This would allow you to easily add more directories without altering the code you have already written.

Below I have written an example of the things I have stated above. Feel free to use it, but remember this is bare minimum code.

class Autoloader {

    private $directories = [];
    private $extensions = [];

    public function __construct(array $directories, array $extensions) {
        $this->directories = $directories;
        $this->extensions = $extensions;

        $this->register();
    }

    private function register() {

        $directories = array_merge((array) get_include_path(), $this->directories);
        $extensions  = implode(',', $this->extensions);

        set_include_path(implode(PATH_SEPARATOR, $directories));

        spl_autoload_extensions($extensions);
        spl_autoload_register();

    }

}

The usage will now look like:

$directories = [
    'core/',
    'controller/',
    'model/'
];

$extensions  = [
    '.php', // Added for compatibility with other libraries.
    '.core.php',
    '.class.php'
];

/*
 * Storing the instance in a variable is
 * not required.
 */
$autoloader = new Autoloader($directories, $extensions);

The loader class

As I said in the comments one of the two biggest issues that caught my eye was the inability to instantiate a new instance. I made the same assumption that storing each instance in a static property would save a lot of resources. But the reality proved me wrong. Here is one of the issues I have encountered.

With the good intention of saving resources you store the instances, so they can be referenced. But then you have a problem when you want to delete an resource intensive instance entirely. You cannot use unset($instance), because the reference to the instance would remain in the loader and no resources would be freed.

I therefore think you should provide a way to indicate that the class SHOULD be a shared (singleton) and all classes by default are non-shared. But this would render the purpose of the class useless, as you would only wrap the way a class is instantiated and you might even limit yourself at the same time as you cannot pass arguments to the class. So what I would do is make the class able to store an array of class names that should be shared and let it keep track of them. You would then provide it with an array of shared class names once (during instantiation of the Loader itself) and when you create a new class and need it shared, you would update that array.

The second issue is that you are unable to provide arguments to the instantiated class through the loader as it is. You would have to use plain PHP which renders the loader useless. This can easily be changed, which I will show in my version/refactoring of your code.

Then there is a litte bug in your code, where you check if an instance exists. The empty keyword checks if an array or string is empty and not if an array key exists (check the documentation to see which values are considered empty). Use the isset() keyword or the more verbose (but more readable in my opinion) array_key_exists() function.

I also think the class should avoid using static methods. I know this will prevent you from using class inside other classes as easily, but the classes required by other classes (dependencies) should be provided as arguments. Read up on Dependency injection (Tutsplus). I will also provide you with some resources you can read at the end.

Now when we stitch all this together an example of the loader class could look like the following:

class Loader {

    private $instances = [];
    private $shared = [];

    /*
     * The $shared argument has a default value of an empty array. This
     * makes the argument optional. Use this if no classes should be shared.
     */
    public function __construct(array $shared = []) {
        $this->shared = $shared;
    }

    /**
     * Load an instance of the specified class.
     *
     * @param string $class
     * @param array  $arguments
     * @param bool   $singleton
     *
     * @return object
     */
    public function load($class, array $arguments = [], $singleton = false) {

        /*
         * Check if a shared instance exists.
         */
        if(array_key_exists($class, $this->instances)) {
            return $this->instances[$class];
        }

        /*
         * Create a new instance.
         * The use of the ReflectionClass gives us the ability to provide
         * an array as arguments.
         *
         * If no arguments was provided we skip the instantiation if the reflection class.
         */
        if(empty($arguments)) {
            $instance = new $class;
        }else{
            $instance = (new \ReflectionClass($class))->newInstanceArgs($arguments);
        }

        /*
         * Check if a singleton is requested or the class is marked as shared.
         */
        if($singleton === true || array_key_exists($class, $this->shared)) {
            $this->instances[$class] = $instance;
        }

        return $instance;
    }

    /**
     * Removes a class from the shared instances array.
     * Use this to free up resources used by intensive classes.
     *
     * @param string $class
     *
     * @return bool Returns TRUE of the class was removed. Returns FALSE of the class is not shared.
     */
    public function free($class) {
        if(array_key_exists($class, $this->instances)) {
            unset($this->instances[$class]);
            return true;
        }
        return false;
    }

}

Usage of this class would look like:

$shared = [
    'Foo',
    'Bar'
];

$loader = new Loader($shared);

$obj = $loader->load('Foo'); // Would be shared
$obj = $loader->load('Bar'); // Would be shared
$obj = $loader->load('BumbleBee'); // Would provide a new instance every time.
$obj = $loader->load('BumbleBee', [], true); // BumbleBee is now shared.

$loader->free('BumbleBee'); // Is not shared anymore.

Phew, that was quite a lot. I hope this isn't too overwhelming. All the things I have pointed out are issues that I have experienced as solved like shown. Every single change may not suit your framework, but they helped me.

As promised I have listed some resources you can look at. I learned a lot even though some of them isn't PHP they certainly do apply.

Most of the resources linked at the bottom of this epic answer.
Dependency injection
(Advanced) SOLID Design principle. Not all of the principles can be easily achieved, but having them in mind while coding will help you out later, I know it have for me.
Document your code . The code you have provided are relatively simple. But when you have grown into a PHP guru and others look up to your code (or yourself six months later), good documentation of the more complex code is good. Do not document every single little array look up or variable initialization, but when the code doesn't immediately reveal its purpose documentation is lovely.

Happy coding out there!


Optimizing dynamic table creation: JavaScript vs. jQuery

Well, how about

function MakeTablejQuery(rows, cols) {
    var table = $("<table/>").attr("border", 1);
    for (r = 0; r < rows; r++) {
        var row = $("<tr/>");
        for (var c = 0; c < cols; c++) {
            if (r == 0) {
                row.append($("<th/>").text("Column " + c))
            } else {
                row.append($("<td/>").text(c.toString() + r.toString()))
            }
        }
        table.append(row);
    }
    $("#placeholder").append(table);
}

MakeTablejQuery(5, 3);

And here's a more elegant version in a functional style:

Number.prototype.times = function(fn) {
    for(var r = [], i = 0; i < this; i++)
        r.push(fn(i));
    return r;
}

function MakeTablejQuery(numRows, numCols) {

    var header = numCols.times(function(c) {
        return $("<th/>").text("Column " + c);
    });

    var row = function(r) {
        return $("<tr/>").append(numCols.times(function(c) {
            return $("<td/>").text([c, r].join(""));
        }));
    };

    return $("<table/>")
            .append(header)
            .append(numRows.times(row))
            .attr("border", 1);
}

$("#placeholder").append(MakeTablejQuery(5, 3));

Also, jQuery is not about "less" code, it's about more readable code - note how the last "return" statement reads almost like an english sentence.


PHP Autoloader - For classes, traits and interfaces

First of all you should use static methods and properties only
when there is good reason to do so. Generally you should default to non-static.

$path property can be const because private static doesn't say whether it is immutable or not.
I think you shouldn't order resource files at all. You already have resource name. All you should do is match something like $resource.'.' and include file if such exists. Also if you did require_once i don't see the need to check for class_exists() etc.
I have never written autoloader but my instinct tells me that if you failed to find resource file then you should throw exception.
Altering array inside foreach is murky and its good to avoid such practices.

PS: Personally I haven't seen any php project/library utilizing hashtag comments. It might be my OCD but #...# draws all my focus so my suggestion is to use either: // for line comments and /*...*/ for block comments.

Update:
What I had in mind when writing point 2 is something like this:

    foreach(self::$resource_files as $file_key => $file)
    {
        // Check if resource matches file name
        if (strpos($file, $resource.'.') !== false ) {
            unset(self::$resource_files[$file_key]);

            require_once $file;
        }
    }


What's the fastest way to get the points I want out of a huge blob?

Prefiltering all relevant x-values with a binary search could speed up the process.

[a,A]=myFind2(mtx_region(:,1),dxLowerBound,dxUpperBound);

xpoints=mtx_region(a:A,:);
mtx_region = xpoints(     dyLowerBound < xpoints(:,2) & ...
                            dyUpperBound > xpoints(:,2), : );

Binary search on sorted arrays is already discussed here.

function [b,c]=myFind2(x,A,B)
a=1;
b=numel(x);
c=1;
d=numel(x);
while (a+1<b||c+1<d)
    lw=(floor((a+b)/2));
    if (x(lw)<A)
        a=lw;
    else
        b=lw;
    end
    lw=(floor((c+d)/2));
    if (x(lw)<=B)
        c=lw;
    else
        d=lw;
    end
end
end


With Composition/Aggregation.

first define your interface for Foo collecting all the public methods it should expose from the components:

interface Foo
{
   public function methodA();
   public function methodB();
   …
}

You could also create interfaces for the components and extend the Foo interface from those, e.g.

interface Foo extends FooBar, FooUtility
{}

Note: it's not strictly necessary to have an interface collecting the other interfaces or to have an interface for Foo at all. However, since you should program against an interface and not a concrete implementation, it's cleaner.

Then implement that in your conrete Foo implementation:

class FooImplementation implements Foo
{
   public function __construct(FooBar $fooBar, FooUtility $fooUtility)
   {
       $this->fooBar = $fooBar;
       $this->fooUtility = $fooUtility;
   }
   public function methodA()
   {
       return $this->fooBar->methodA();
   }
   public function methodB()
   {
       return $this->fooUtility->methodB();
   }
   …
}

Inject the various components through the ctor and then just have the methods on Foo delegate to the appropriate components.

You can use use a Factory or Builder to encapsulate creation of the complex Foo type. This will allow you to parametrize the subcomponents:

class FooFactory
{
    public function create($param1, $param2)
    {
        return new FooImplementation(
            new FooBar($param1),
            new FooUtility($param2)
        );
    }
}

Note that Factory and Builder are creational patterns. They may control when and how objects are created, so if you want to reuse one of the components in subsequent calls to create, you may add logic to manage the component lifecycles in the factory/builder.


Modify and import as numpy.ndarray a txt file in python

You can concatenate the replace strings after you open the file, it will give better visibility

data = file_txt_original.read()
.replace('Mean data', '-1')
.replace('Label[', '')
.replace(']', '')
.replace(' = ', ', ')


A Dockerfile for Composer (a dependency manager for PHP)

In the wrapper script,
I don't understand why you need to loop over each argument.
Wouldn't it be enough to use a case "$1" in ... without looping at all?

If you really do need to loop,
for example to make it work even if the command you want to match is not in the first position sometimes,
then I think you want to break out of the loop after finding a match. That is:

# Loop over each argument.
for argument in "$@"; do
    case "$argument" in
        # Append the argument if the command matches one we need to use `--ignore-platform-reqs` with.
        # Found using the following search: https://github.com/composer/composer/search?q=ignore-platform-reqs+path%3Asrc%2FComposer%2FCommand%2F
        # Uses `set` to update the arguments, see https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html.
        create-project|install|remove|require|update) set -- --ignore-platform-reqs "$@"
        break
        ;;

        # Otherwise just pass it on.
        *) ;;
    esac
done

Another small thing,
at the top of the Dockerfile,
I find the echo ... >> /etc/apk/repositories && apk add ... a bit curious.
Under what circumstances might that appending with echo fail?
And why not check the exit code of the other commands that follow?
It seems that either all commands should be chained with &&, or none of them.

Lastly, I have very minimal experience with Docker,
but I'm wondering if instead of multiple RUN commands,
wouldn't it be better to put them in a single shell script,
and RUN that script instead.
(That's not a recommendation, just a general wondering...)


Displaying a leader board from a text file and calculating points

Since you are using all the elements of data,  You can turn:

print(template.format(data[0], data[1], data[2], data[3], data[4]))

into this:

print(template.format(*data))

See here for some details.


Evaluating a tic-tac-toe board using a C-style for loop in Rust

I'm going to start with the tough love... both your C and Rust code are unreadable. Nested loops with goto statements is the definition of spaghetti code, and that tends to be the least understandable and unmaintainable type of code. The good news is that you are here, asking for feedback, which is the right direction! ^_^

I'm going to mark suggestions with [universal] if they are just general programming ideas, not specific to Rust.

Rust uses a 4 space indent, not 2.
Ranges don't have spaces. Use 0..20 instead of 0 .. 20.
Don't use the libc crate for random numbers, use the dedicated rand crate. This allows you to not need any unsafe code.
[universal] Always use a random number function for ranges. You should not use the modulus operator % as it can introduce sampling bias, preventing you from having a uniform distribution. In Rust, you can use gen_range.
Use _ when you want to ignore unused variables, like the index value of a loop:

for _ in 0..10 { }

[universal] Program-wide constants like N are terrible names. Give them better names that convey meaning and usage:

const BENCHMARK_ITERATIONS: usize = 50000000;

const SIZE_OF_ROW: usize = 3;
const SIZE_OF_BOARD: usize = SIZE_OF_ROW * SIZE_OF_ROW;

Don't specify the type of a variable when it can be inferred:

let mut board = [0; SIZE_2]; // no `: [i32; SIZE2] on the left

n += determine_result(&board); // no `as usize`

Use iterators instead of manually incrementing an array index. This has improved performance, and prevents you from duplicating the length variable everywhere:

for space in board.iter_mut() {
    *space = 0;

[universal] Declare variables with the minimal scope needed to do the job. For example, your board is only used inside the loop:

for i in 0..10 {
    let mut board = [0; SIZE_2];

Use iterator adapters, like map or fold, instead of doing all the work yourself. These have higher semantic meaning, allowing other programmers to instantly know you are transforming a sequence or reducing it down to a single value. It also allows your code to avoid some mutability.
[universal] Extract out functions, such as one to generate a board. This allows the mutability of the board to be constrained to a very small area.
I'd create a newtype for Board, or at the very least a type alias. This allows you to have higher concepts as opposed to just an array.
There's no need for explicit return statements at the end of a function.
[universal] Extract out more functions. determine_result has too much going on in it, and breaking them out into functions makes the code way easier to reason about. Functions for "row winners" or "column winners" are identifiable.
[universal] There's no reason to use an i32 for 3 values, that's massive overkill.
The absence of a value isn't really just another value, and you should use Option instead.

All together now:

src/main.rs

extern crate rand;
extern crate itertools;

use rand::{StdRng, Rng, SeedableRng};
use itertools::Itertools;

const SIZE_OF_ROW: usize = 3;
const SIZE_OF_BOARD: usize = SIZE_OF_ROW * SIZE_OF_ROW;

type Board = [Option<Piece>; SIZE_OF_BOARD];

#[derive(Debug, Copy, Clone, PartialEq)]
enum Piece {
    X,
    O,
}

// If every item in an iterator is the same, that value is
// returned. If there are no items or not all items are equal, returns
// None.
fn all_the_same<I>(mut iter: I) -> Option<I::Item>
    where I: Iterator,
          I::Item: PartialEq + ::std::fmt::Debug
{
    let initial_value = match iter.next() {
        Some(v) => v,
        None => return None,
    };

    while let Some(value) = iter.next() {
        if initial_value != value {
            return None
        }
    }

    Some(initial_value)
}

fn flatten<T>(opt: Option<Option<T>>) -> Option<T> {
    match opt {
        Some(inner) => inner,
        None => None,
    }
}

fn column_winner(board: &Board) -> Option<Piece> {
    (0..3).filter_map(|col| {
        flatten(all_the_same(board.iter().skip(col).step(3)).cloned())
    }).next()
}

fn row_winner(board: &Board) -> Option<Piece> {
    board.chunks(3).filter_map(|row| {
        flatten(all_the_same(row.iter()).cloned())
    }).next()
}

fn top_left_diagonal_winner(board: &Board) -> Option<Piece> {
    flatten(all_the_same(board.iter().step(4)).cloned())
}

fn top_right_diagonal_winner(board: &Board) -> Option<Piece> {
    flatten(all_the_same(board[2..7].iter().step(2)).cloned())
}

fn determine_result(board: &Board) -> Option<Piece> {
    column_winner(board)
        .or_else(|| row_winner(board))
        .or_else(|| top_left_diagonal_winner(board))
        .or_else(|| top_right_diagonal_winner(board))
}

const BENCHMARK_ITERATIONS: usize = 50000000;

fn generate_board<R>(mut rng: R) -> Board
    where R: Rng
{
    let mut board = [None; SIZE_OF_BOARD];
    for space in board.iter_mut() {
        *space = match rng.gen_range(0, 3) {
            1 => Some(Piece::X),
            2 => Some(Piece::O),
            _ => None,
        };
    }
    board
}

fn main() {
    let mut rng = StdRng::from_seed(&[0]);

    let total =
        (0..BENCHMARK_ITERATIONS)
        .map(|_| generate_board(&mut rng))
        .map(|board| determine_result(&board))
        .map(|winner| {
            match winner {
                Some(Piece::X) => 1,
                Some(Piece::O) => 2,
                None => 0,
            }
        })
        .fold(0, |acc, val| acc + val);

    println!("{}", total);
}

Cargo.toml

[package]
name = "tictactoe"
version = "0.1.0"
authors = ["A. Developer <a.developer@example.com>"]

[dependencies]
rand = "*"
itertools = "*"


To build on @Jesse C. Slicer's comment above: interfaces are for defining contracts, whereas abstract classes are meant to add some base implementation code.  An abstract class without any implementation code does not add anything an interface does not already provide.  Even worse, it blocks inheriting from other (potentially useful) classes.

Relationships can be defined either way.

You are free to provide an abstract class to callers which takes care of some of the base functionality, or you can extract an abstract base class during a later re-factoring pass if you like, but your API should still stick to the interfaces as much as possible.


What could be bad from using this form of dependancy injection?

General impression

You are not actually injecting any of the dependencies into UserProfile, you are
injecting a service provider that has to locate the dependencies.

It may feel like dependency injection but it really isn't.

What you are doing here is, basically, creating spaghetti code.

Suggested improvements

My question would be: What is the UserProfile responsible for?

Your UserProfile class depends on a View, ORM and FormBuilder class.
It is in control of retrieving the user from the DB, outputting a header and
outputting the user in the view body. The FormBuilder does not even seem to be used.

There are several ways this could be cleaned up, for now I'll use "classic" MVC.

Assuming (based on the function name) that this class is primarily a View, it
should only need the user Data and your ViewCreator to function. Your router
would call the Controller that would retrieve the Model and pass it on to your
View.

The suggestion below completely removes the service locator from the picture.
Please note that the code is written for clarity in conveying the message, it is
not meant to be 100% working or correct (especially the static call syntax in the controller).

namespace \foo\bar;

class Router
{
    function get()
    {
        $url = $this->getExplodedUrl();

        // get view object
        $viewsDir = __DIR__ . '/../path/to/views/dir'; //@TODO: Read this from a config file
        $view =  new ViewCreator($viewsDir)

        // get orm object
        $db   =  new Orm(new \Pdo('...'))

        // get form builder object
        $formBuilder = new FormBuilder('...');

        // IF URL matches, and controller + method exists.
        return (new $controller)->$method($url, $db, $view, $formBuilder);
    }
}

class UserController
{
    public function showUserProfile($args, $db, $view)
    {
        // extract username & id from current url. i.e. dev.foo.com/john/11
        list($userName, $id) = $args;
        $select = UserRecord::fetchUserFromDb($db, [$userName, $id]);
        UserProfile::showUserProfile($view, ["select"=>$select]);
    }
}

class UserProfile
{
    /**
     * Display a given User with a given View
     */
    public function showUserProfile($view, $viewData)
   {
     // get view object, for loading templates
     $view::header();   // ~ require  .. view/header.php
     $view::body($viewData);
   }
}

class User
{
    /**
     * Get a given User from a given Database
     */
    public function fetchUserFromDb($db, $user)
    {
         // DATABASE QUERY.
         $users = $db->table("users");

         // SELECT username, age, country from users where username = $username AND id = $id;
         $select = $users->read(["username, age, country", $user]);

         return $select;
    }
}

Things could be cleaned up even further by not initiating classes from the router
but injecting them into the router from your delivery mechanism/root/index.php/etc.

Further Suggestions

You say you're not well versed in any framework but what you seem to be doing
here is very similar to the way Silex works, which uses Pimple (which was
mentioned in the comments to your question). The learning curve is quite flat so
it could be worth the effort of seeing how Silex does things.

If studying an entire framework takes too much of an effort I would strongly
suggest you take a look at PHP-DI to
observe the way a Dependency Injector should work.


PHP design pattern factory input for products and quotes

Flexible approach

First defining an ultimate abstraction of the factory
Implement it with product type - class mapping
Creating an entry point to register and use the factory

interface IProductFactory {

    function createProduct($type);
}

class DefaultProductFactory implements IProductFactory {

    private $_mappings;

    public function __construct(array $mappings = array()) {
        $this->_mappings = $mappings;
    }

    public function addMappings(array $mappings) {
        $this->_mappings = array_merge($this->_mappings, $mappings);
    }

    public function createProduct($type) {
        if (!isset($this->_mappings[$type])) {
            throw new \Exception("Cannot create product of type " . $type);
        }

        $class = $this->_mappings[$type];

        //can be passed to a DI container to instantiate if needed

        return new $class();
    }
}

class ProductFactory {

    private static $_factory;

    public static function setCurrent(IProductFactory $factory) {
        $this->_factory = $factory;
    }

    public static function getCurrent() {
        return $this->_factory;
    }
}

ProductFactory::setCurrent(new DefaultProductFactory(array(
    "solution1" => "Solution1Product",
    "solution2" => "Solution2Product",
    "solution3" => "Solution3Product",
    "solution4" => "Solution4Product",
    "solution5" => "\\\\In\\\Some\\\\Other\\\\Namespace\\\\Solution5Product",
    )));

$solution1 = ProductFactory::getCurrent()->createProduct('solution1');

print $solution1->calculatePrice("02/25/1982", "male", 100000);


Extracting all the data from a table out of a javascript encrypted website

Your code is getting better from script to script and there is less things to point out. I would improve a couple of things only:

the way you get the data - I think you can use the "by tag name" locators with a nested list comprehension:

list_rows = [[cell.text for cell in row.find_elements_by_tag_name('td')]
             for row in tab_data.find_elements_by_tag_name('tr')]

you can use a Select class to select an option from a select dropdown:

from selenium.webdriver.support.select import Select

results_count = Select(driver.find_element_by_id("ctl00_body_MedicineSummaryControl_cmbPageSelection"))
results_count.select_by_visible_text("All")


Unnecessary #includes:

You don't need <cstdlib> and <iomanip> for this program. Those can be removed.

Avoid using namespace:

using namespace in a source file for such a tiny program is fine, but don't make it a habit. Prefer to qualify the names with the namespace prefix (std::) when practical. Read a longer discussion here.

Open the stream on declaration and let the destructor close it:

Instead of explicitly calling open() in your file, use the parameterized constructor to make your code more concise and direct:

std::ifstream file("in.txt");

Also, no need to explicitly close at the end of main(). The destructor will close the file automatically when the scope of declaration is exited.

Be sure to always check that the file was opened successfully! If it fails, you should at least print a message to let the user know about the problem.

Use the return value of getline() instead of eof():

The canonical line reading loop in C++ is:

while (std::getline(file, line))
{
}

That can simplify you program quite significantly. You can still test specific error states with the methods bad(), fail() and eof(). See the documentation for std::ifstream.

Incorrect use of string::find():

You have misinterpreted the return value of std::string::find(). This method returns the position of the first character of the first match. If no matches were found, the function returns std::string::npos.

Which means that testing it as in if (temp.find(delimet)) will probably not work as you intended, since the return value is not a boolean.

The correct usage is:

if (str.find(substring) != std::string::npos) { /* found the substring */ }

Also note that "member - modal" is not the same as "member-modal". find() will look for an exact match, including spaces, so your implementation will only find something in the input file if you replace the search string to match the contents of the file down to each space. A more flexible implementation could be achieved using C++ regular expressions.

Be more thoughtful about variable naming:

Names line temp and delimet convey little meaning.

temp should at the very least be named line, as that is what the variable holds (a line from the file).

delimet sounds like a misspelled "delimiter", so delimiter would be better. Other options include needle, for searching a needle in a haystack, target, for the target of the search, wanted_string, and the list goes on...

Properly indent main():

Code inside main() is not properly indented to convey nesting into the function. Proper indentation is very important for code readability, so that must be fixed.

Summing up:

This is my suggest implementation, based on the original code and applying the above changes:

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

int main()
{
    // Alway check after opening to make sure the
    // file existed and was opened successfully.
    //
    std::ifstream file("in.txt");
    if (!file.is_open())
    {
        std::cerr << "Failed to open file!\n";
        return -1;
    }

    // Since this is a read-only variable,
    // also mark is as `const` to make intentions
    // clear to the readers.
    //
    const std::string needle = "member-modal";

    // Main reading loop:
    //
    std::string haystack;
    while (std::getline(file, haystack))
    {
        if (haystack.find(needle) != std::string::npos)
        {
            std::cout << haystack << "\n";
            // Prints
            //  Phil Jankins
            // once
        }
    }
}


template<typename T>
std::shared_ptr<T> GetComponent(std::shared_ptr<Entity> entity) {
    return std::shared_ptr<T>((T*)entity->component_map_.at(T::kTYPE).get());
}

Noooo. This is a misuse of shared_ptr's constructor (trying to create a brand-new shared_ptr to manage an object that is already managed), and will lead to double-free bugs or worse. What you meant was to cast the existing smart pointer to your desired smart pointer type:

template<typename T>
std::shared_ptr<T> GetComponent(std::shared_ptr<Entity> entity) {
    std::shared_ptr<Component> ptr = component_map_.at(T::kTYPE);
    return std::static_pointer_cast<T>(ptr);
}

This is a moderately obscure corner of smart-pointer-land, and you shouldn't be expected to know it; but now that you see it, I bet you're smacking your forehead in disgust. :)

By the way, I see no reason to provide static const kTYPE = -1 in the base class; doesn't that just counterproductively move the diagnosing of several kinds of typo-bugs from compile-time to run-time?

Also, note that std::map is not a hashmap; it's a tree-map. If you really want a hashmap (or if you don't care), and you're using C++11 or later, you should switch to std::unordered_map.

  What about having the static ID of components and using that to map the components in the entity? Any better solutions?

C++11 has a feature designed specifically for this use-case, although I personally have zero experience with it — it's spelled std::type_index. What you're looking for is a std::unordered_map<std::type_index, std::shared_ptr<Component>>.


You can use a sub-query:

declare @tbl table (
    id          INT,
    effective   DATE,
    points      INT)

INSERT INTO @tbl
VALUES
    (1, '1/1/2015', 123),
    (1, '2/1/2015', 234),
    (1, '3/1/2015', 345),
    (2, '4/1/2015', 123),
    (2, '5/1/2015', 234),
    (2, '6/1/2015', 345)

select * from @tbl t1
where effective = (select max(effective) from @tbl t2 where t1.id = t2.id)


Don't using namespace std - especially if you're going to define a max() function in the global namespace (why not just use std::max() anyway?  That's what it's for!).

Where do the values in arr and rodMax come from?  Do their lengths have to agree?  If so, make that obvious in the code (e.g. use std::array, so that we can use arr.size() to count the members).


Query for finding collection entries matching an arbitrary set of URLs

I haven't used MongoDB, but I have a few suggestions based on experiences with optimization and other databases.

Index hashes of the URLs and search for those instead. Using a simple MD5 hash would probably speed up searching with the cost of dealing with false positives (unlikely but possible).
Store every URL as a top-level object and add a redirectsTo attribute. This alleviates the need to index or search the redirects collections. While now you need to perform two queries--one for the original URLs and another for the redirected URLs--this could end up being faster if only a small percentage of URLs are redirects.

Here's some psuedocode to clarify what I mean:

all = []
found = model.find({'url': {$in: urls}})...
redirects = []
for each item in found
    if item.redirectsTo
        redirects += item.redirectsTo
    else
        all += item
redirected += model.find({'url': {$in: redirects}})...
for each item in redirected
    all += item

Update your question with the higher-level problem you're trying to solve. I often find that when I'm trying to optimize slow task T to solve problem P, the better approach is to rethink P.


Json should be put in a separate file.
myfile.json
{   "cost":0,
   "timespan":"2020-07-07T03:00:00Z/2020-07-07T03:15:00Z",
   "interval":"TM",
   "value":[      {         "id":"/subscriptions/hjhkjhjljkjknlkjjlkj/Groups/jhkjhjkhjs/providers/Micro/virtualMachines/jhjkhkjhjkhkhljkl/providers/MicInsights/metrics/Percentage CPU",
         "type":"Microsoft.Insights/metrics",
         "name":{
            "value":"Percentage CPU",
            "localizedValue":"Percentage CPU"

},
         "displayDescription":"The percentage of allocated compute units that are currently in use by the Virtual Machine(s)",
         "unit":"Percent",
         "timeseries":[            {               "metadatavalues":[

],
               "data":[                  {
                     "timeStamp":"2020-07-07T03:00:00Z",
                     "average":2.4659375

},
                  {
                     "timeStamp":"2020-07-07T03:01:00Z",
                     "average":2.974375

},
                  {
                     "timeStamp":"2020-07-07T03:02:00Z",
                     "average":2.90265625

},
                  {
                     "timeStamp":"2020-07-07T03:03:00Z",
                     "average":1.72484375

},
                  {
                     "timeStamp":"2020-07-07T03:04:00Z",
                     "average":1.1275

},
                  {
                     "timeStamp":"2020-07-07T03:05:00Z",
                     "average":0.05640625

},
                  {
                     "timeStamp":"2020-07-07T03:06:00Z",
                     "average":0.05515625

},
                  {
                     "timeStamp":"2020-07-07T03:07:00Z",
                     "average":0.055

},
                  {
                     "timeStamp":"2020-07-07T03:08:00Z",
                     "average":0.28765625

},
                  {
                     "timeStamp":"2020-07-07T03:09:00Z",
                     "average":0.0546875

},
                  {
                     "timeStamp":"2020-07-07T03:10:00Z",
                     "average":0.054375

},
                  {
                     "timeStamp":"2020-07-07T03:11:00Z",
                     "average":0.05734375

},
                  {
                     "timeStamp":"2020-07-07T03:12:00Z",
                     "average":0.0553125

},
                  {
                     "timeStamp":"2020-07-07T03:13:00Z",
                     "average":0.05609375

},
                  {
                     "timeStamp":"2020-07-07T03:14:00Z",
                     "average":0.0528125

}

]

}

],
         "errorCode":"Success"

}

],
   "namespace":"Microsoft/virtualMachines",
   "resourceregion":"eastus8"
}

myfile.py
with open("myfile.json") as file_obj:
    formatted_response = json.load(file_obj)

Use descriptive identifiers for variables.
formatted_response_value = formatted_response['value']

Unnecessary double for loop
formatted_response_value = formatted_response['value']
timeseries = formatted_response_value[0]["timeseries"]   #please name something descriptive at all places.
data = q[0]["data"]
average = list(map(lambda x:x["average"], g))[-1] #or [entry["average"] for entry in g][-1]


At first glance, the double for loop seems to be very time consuming. Since you're using the numpy arrays, there is a way to get rid of it:

x = np.arange(array.shape[0])
y = np.arange(array.shape[1])
intensity = intensitymap.astype(int)
array[:, :, 0] = red[x + intensity, y]
array[:, :, 1] = green[x, y + intensity]
array[:, :, 2] = blue[x + intensity, y - intensity]

By the way, I would recommend you to use the numba JIT compiler. This will let you write pure python code. It is under active development now, and this is optimized for numpy arrays.


Query that shows similar columns between different tables on a database

A common-table-expression (See CTE) will help you here quite nicely..

with columns as (
    select C.COLUMN_NAME,
           C.TABLE_NAME
    from INFORMATION_SCHEMA.COLUMNS C
    inner join INFORMATION_SCHEMA.TABLES T on T.TABLE_NAME = C.TABLE_NAME
    where T.TABLE_TYPE = 'BASE TABLE')
select C.COLUMN_NAME as 'Similar Column',
       C.TABLE_NAME as 'First Table',
       D.TABLE_NAME as 'Second Table'
from columns C
inner join columns D
   on C.COLUMN_NAME = D.COLUMN_NAME
  and C.TABLE_NAME < D.TABLE_NAME
order by C.TABLE_NAME, D.TABLE_NAME, C.COLUMN_NAME

The above query reduces the complexity of the column/table table joins, and reuses the result. Further, by using < instead of <> on the table-name anti-join, it removes your duplicates.


Security of simple client/server desktop app

The important thing you want to enforce is that only the same local user can see the hello world.

You're relying at least on the inability of any random user to

listen in on someone else's sockets.
read another user's files
otherwise learn the secret
execute random python code in your server
And the inability for a remote attacker to connect to your socket.

1, 2 and 4 depend how well you've secured your system (no privilege elevation or random suid files lying around). 4 also depends on the security of flask and the rest of your python stack.

Five can be broken, depending on how your firewall is configured (someone could use connection tracking to get your socket forwarded, even though it is bound to localhost). You'd be better off using unix domain sockets.

The second is broken, because you chmod the file only after you've written to it. That gives a window for the attacker to open the file. In fact the attacker could even write to the file and execute arbitrary commands, which is why you should never use os.system, and you should use urlparse to build the url.

The third is broken in two ways:

the secret appears in the process list
the server won't take the same time to compare strings that are mostly right and mostly wrong. The attacker can guess the length of the secret, and guess the secret letter by letter (timing attack).


OK, first, for the most straightforward optimization.  Use a StringBuilder.

The way your code currently works, it creates length - str.Length intermediate strings.  Besides creating lots of unnecessary garbage, you're copying longer and longer strings over and over again to add one character each time.

If you use a StringBuilder instead, you can avoid most of those copies.
You could try something like...

using System.Text;

...

private string ExpandString(string str, int length)
{
    if (length <= str.Length) return str.Substring(0, length);
    var result = new StringBuilder(str);
    for (var i = str.Length; i < length; i++)
    {
        result.Append(str[i % str.Length]);
    }
    return result.ToString();
}

(I don't particularly like the StringBuilder starting with a copy of str already in it. I'm literally just replacing the String.)

But you're also copying one character at a time. While this isn't as big an issue as the concatenation, you can do better by inserting as many whole copies of str as you can.

private string ExpandString(string str, int length)
{
    // BTW, you already know how big the result should be, so just
    // tell the StringBuilder its capacity to prevent unneeded resizes.
    // Side benefit: if the result is too long, you'll find out fairly quickly.
    var result = new StringBuilder(length, length);

    var wholeCopies = length / str.Length;
    for (var i = 0; i < wholeCopies; ++i)
    {
        result.Append(str);
    }

    // now append the last chunk, a possibly-zero-length prefix of `str`
    result.Append(str, 0, length % str.Length);

    return result.ToString();
}

Note that the short-string optimization has been removed. You can add it back in if you really really want to micro-optimize, but at this point, it's not gaining you nearly as much as it was.


Remove sorted
From the docs: numpy.unique returns the sorted unique elements of an array.
You can simply remove the call to sorted:
b = np.unique(sorted(a))

# produces the same result as

b = np.unique(a)

List comprehension
In most cases you can and should avoid this pattern of list creation:
result = []
for i in a:
    result.append((b == i) * 1)

It can be replaced by a concise list comprehension and directly passed to np.array:
result = np.array([(b == i) * 1 for i in a])

# or directly return it (if applicable)
return np.array([(b == i) * 1 for i in a])

List comprehensions are more pythonic and often faster. Generally, not mutating the list object is also less error-prone.

There might be a better way to map lambda x: (uniques == x) * 1 over the input array a. Here's a discussion on the topic on StackOverflow: Most efficient way to map function over numpy array. Seems like using np.vectorize should be avoided for performance reasons.
Using map might be similiar to the list comprehension performance-wise (I did not properly test performance here):
def convert_listcomp(a):
    uniques = np.unique(a)
    return np.array([(b == i) * 1 for i in a])

def convert_map(a):
    uniques = np.unique(a)
    return np.array(list(map(lambda x: (uniques == x) * 1, a)))


Design

The design of this class is confusing.  Perhaps Timeshift shouldn't be a class at all, at least not like this.  This …

Timeshift.new(time, timeshift).add_time

… is problematic, because:

You have used "time shift" both as the duration to add (timeshift) and as the class representing the summation operation (Timeshift).
What does .add_time do?  Why is it called .add_time rather than, say, .add_duration?  How about just .add?
What should be the result of

t = Timeshift.new(time, timeshift)
puts t.add_time
puts t.add_time

Should it print "11:57 AM" twice, or should it print "11:57 AM" then "11:59 AM"?  There is no intuitively correct behaviour, I think.
It's not obvious, other than from thoroughly reading the code, what the inputs and outputs are supposed to be.  (time should be "HH:MM AM" format with a 12-hour clock; timeshift is the number of minutes.)  The inputs and outputs should be documented in a comment.

The class is designed to have a constructor and one public method (.add_time).  Whenever that is the case, chances are that the code shouldn't be a class at all, and should be just a function instead, like add_time("11:55 AM", 2).  (Actually, you have two public methods — .add_minutes was accidentally exposed as a public method due to a copy-and-paste error!)

Another problem is that validation of the constructor's arguments is deferred to .add_time.  Failing earlier would make debugging easier.

Bugs

> Timeshift.new('11:55 AM', 5).add_time
=> "12:0 AM"                               # Expected: "12:00 PM"

> Timeshift.new('11:55 AM', -55).add_time
=> "11:55 AM"                              # Expected: "11:00 AM"

> Timeshift.new('12:00 am', 0).add_time
=> "Not a valid time entered"              # Expected: "12:00 AM"

Implementation

The instance variables at the top (@time, @timeshift, etc.) aren't doing anything.  You don't need to "declare" instance variables like that in Ruby.  Furthermore, you're keeping way more state information than necessary, with so many variables.

It's not really idiomatic to name your methods .get_something in Ruby.  (The naming convention is .something for getters and .something=(value) for setters.)
What's more, using getter methods purely for their side-effects is unorthodox.

Clock arithmetic is much simpler if you convert everything into minutes first, then convert the result back into hours and minutes.

Suggested solutions

As a simple function:

def add_time(hh_mm_ampm, minutes)
  unless parts = /\A(1[0-2]|0[1-9]):([0-5]\d)\s*(AM|PM)\Z/i.match(hh_mm_ampm)
    raise ArgumentError.new("Not a valid time in HH:MM AM/PM format: #{hh_mm_ampm}")
  end
  hh, mm, am_pm = parts.captures

  # Sum, as minutes since midnight
  time_of_day = 60 * hh.to_i + mm.to_i + minutes
  time_of_day += (12 * 60) if am_pm.upcase == 'PM'
  time_of_day %= (24 * 60)

  # Output formatting
  am_pm = (time_of_day < 12 * 60) ? 'AM' : 'PM'
  hh = (time_of_day / 60).to_i % 12
  hh = 12 if hh == 0
  mm = time_of_day % 60
  sprintf('%02d:%02d %s', hh, mm, am_pm)
end

As a class:

class ClockTime
  def initialize(hh_mm_ampm)
    unless parts = /\A(1[0-2]|0[1-9]):([0-5]\d)\s*(AM|PM)\Z/i.match(hh_mm_ampm)
      raise ArgumentError.new("Time not in HH:MM AM/PM format: #{hh_mm_ampm}")
    end
    hh, mm, am_pm = parts.captures
    @time_of_day = 60 * hh.to_i + mm.to_i
    @time_of_day += (12 * 60) if am_pm.upcase == 'PM'
  end

  def add(minutes)
    @time_of_day = (@time_of_day + minutes) % (24 * 60)
    self
  end

  def to_s
    # Left as an exercise for you
    sprintf(...)
  end
end


I just moved things around to make it a bit more readable. You can use the map function instead of each. The signature of map is as follows:

element in array
index of element
the array itself

I've added those parameters in the coffee script, but you could have easily done without them for a cleaner look. I assumed that self is some kind of global variable or variable available to the inner scope of the map.

See the Mozilla article on map. It's fantastic!

objCollector = allRows.map (element, index, context) ->
  tag = $(element)

  text = tag.find('span.lnk').text()
  link = tag.find('a').first().attribs.href

  {
    source: self.source
    url: self.baseUrl + link
    host: text
  }


Password Trainer v1.0 - Helping you learn a new password

password_attempt = raw_input(...)

When dealing with passwords, you want to try and minimize the amount of information any bypasser can see on the screen.

Python offers the getpass module to ease such inputs:

import getpass

password_attempt = getpass.getpass(...)

As such, you should also avoid printing plain passwords and attempts.


Flattening a nested record to its leaves

I think this is good usage of tree-seq. It's intended for walking trees, right? If your settings will have ragged depth it's probably the cleanest approach.

The only main cleanup I see is that this predicate can be pointfree if you want:

#(and (map-entry? %)
      (not (associative? (second %))))
; =
(every-pred map-entry? (comp not associative? second))

On the other hand, I don't see a huge need for records here at all, as opposed to maps.

Nested maps will de/serialize fine as-is with EDN (or JSON if there's nothing crazy in them)
They're idiomatic across the Clojure community
Define a clojure.spec spec for them if you want
Records don't give you type safety anyway, and you're not using any of their class-abilities like extending protocols.
Records are a bit faster if you're building thousands, but that doesn't look like the case here


Algorithm

You could actually skip looking up the maximum element in the range. This is because it gets cancelled anyways:
 $$y = {{e^{x - x_{max}}} \over {\Sigma e^{x - x_{max}}}} ={ {e^x \over e^{x_{max}}} \over {{{1} \over {e^{x_{max}}}}\Sigma e^x}} = {{e^x} \over {\Sigma e^x}} $$

Also, currently the results are stored in place, i.e. the original input data will be lost. This might not always be wanted, so maybe accept an iterator to write the results to?

static_assert vs. SFINAE

I personally like the SFINAE approach more in this case, because it's easier to introduce another overload if needed (e.g. for iterators over associative containers) and you get immediate error reporting. That said, if the decision is final that you won't ever need another overload, static_assert works fine.

iterator value_type

Well, if the container is nicely conforming to standard library guidelines, you'll be fine with using std::iterator_traits<It>::value_type. For custom containers, this might not be the case, though - for those cases you could use decltype(*beg) instead.


How do I shorten my Rust code to get integer values from regex named capture groups?

regex::Captures provides a handy implementation of Index<&str>. This lets you pull named matches out with caps[name]. Combine that with a few std APIs and you can write the same code like this:

use regex::Regex;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let re = Regex::new(concat!(
        r"^\s+(?P<qrw1>\d+)\|(?P<qrw2>\d+)",
        r"\s+(?P<arw1>\d+)\|(?P<arw2>\d+)",
    ))
    .unwrap();
    let names = ["qrw1", "qrw2", "arw1", "arw2"];
    let buffer = " 0|1 2|3\n 4|5 6|7\n 8|9 10|11\n";

    let mut maximums = [0i32; 4];

    for caps in buffer.lines().filter_map(|line| re.captures(line)) {
        for (&name, max) in names.iter().zip(&mut maximums) {
            *max = std::cmp::max(*max, caps[name].parse()?);
        }
    }
    for (&name, max) in names.iter().zip(&maximums) {
        println!("max {}: {:.2}", name, max);
    }

    Ok(())
}
```


adding properties together from list of objects using LINQ

You can use the Sum function

public int HintsUsed => questions.Sum(q => q.hintsUsed);

By using an expression bodied member (since C# 6.0), you can even get rid of the get and the return keywords plus a few braces.

The code above is equivalent to

public int HintsUsed
{
    get
    {
        return questions.Sum(q => q.hintsUsed);
    }
}

Most of the LINQ-to-Objects functionality is provided by the Enumerable Class.


overall and good stuff

This is pretty good.  I definitely wouldn't call the code dirty.  Good stuff:

The indentation is good
putting double quotes around variable substitutions is a best practice
using $() for command substitution is the best practice also
the #! is good
providing meaningful output to the user is nice
the variable names are ok

suggestions

I get putting rm -r out; mkdir out on one line sounds good because they're related, but it doesn't help the readability here.  If you want to tie them together so that the mkdir doesn't run unless rm succeeds then you could do rm -r out && mkdir out.  Otherwise I'd put them on two lines.  Breaking up things with blank lines, as you've already done, is enough to make clear which things belong together.
for f in src/*.md certainly works most of the time, but will break if there's any white space in a filename.  Fixing this involves using find.  This answer is part of a duped question, but it may be a bit easier to follow.
Having f and filename as variables is a bit confusing.  For something this short it is pretty harmless which is why I said they were ok above.  If you want to tweak this f might make more sense as fullpath or fqfn.  And filename might be better as basename or base.
add if ! which pandoc... near the top to catch if pandoc is missing.

if ! which pandoc > /dev/null; then
        echo you need pandoc
        exit 1
fi

further reading

shellcheck is handy.  You can run it locally or in your CI pipeline or manually paste something into their site.
bash best practices by Yaroslav Tkachenko is a nice quick read on bash best practices.
google shell style guide is even more in-depth with best practices.
env is good for portability but this is rarely an issue with bash.  It might become a more current problem if Apple dumps bash after adopting zsh as the default.


Implementing the CutHill-McKee Algorithm

Regarding readability, it is generally a good practice to avoid using unnecessarily shortened forms like adjcncy, as it is only two characters short of adjacency. Also using R for result_queue is discouraged in general (subjective opinion).

If there is no constraint on it being pure python, you may try Cython to get speeds closer to that of C, without moving too far away from the python syntax.


Is it correct to extend a bean class and write a class which holds logic to populate the bean we extend?

I would declare variables on separate lines.

private long liveCount, daemonCount;

From Code Complete, 2nd Edition, p761:

  Use only one data declaration per line

  [...]

  It’s easier to modify declarations because each declaration is self-contained.

  [...]

  It’s easier to find specific variables because you can scan a single
  column rather than reading each line. It’s easier to find and fix
  syntax errors because the line number the compiler gives you has
  only one declaration on it.

The code has a temporal coupling here:

public void run() throws Exception{
    extractMetrics();
    recordToBean();
}

A maintainer easily can change the order of the called methods which brokes it. See: Clean Code by Robert C. Martin, G31: Hidden Temporal Couplings, p302
For this:

// Here to avoid code redundancy I feel it's correct to extend
// the  ThreadMetricsBean class
// Am I wrong ??

It's hard to say that which would be better without knowledge about clients and typical/possible usages of these classes. You might be able to remove redundancy in the following way too:

class ThreadMetricsExtractor {
    private final ThreadMetricsBean bean = new ThreadMetricsBean();

    public void run() throws Exception {
        storeMetrics();
    }

    private void storeMetrics() {
        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        final int liveCount = threadMXBean.getThreadCount();
        final int daemonCount = threadMXBean.getDaemonThreadCount();
        bean.record(liveCount, daemonCount);
    }
}

I've found that composition usually leads better design, cleaner and testable code than inheritance. A reference:  Effective Java, Second Edition, Item 16: Favor composition over inheritance.
The throws Exception is unnecessary here, as far I see nothing throws any checked exception inside the run method:

public void run() throws Exception{
    extractMetrics();
    recordToBean();
}

You could use integers here:

this.liveCount = threadMXBean.getThreadCount();
this.daemonCount = threadMXBean.getDaemonThreadCount();

Both called methods returns int, so liveCount and daemonCount could be ints too.


Dominion card game - how can I take advantage of interfaces?

Is there any reason why View itself can't be a template?

template <typename T> class View {
public:
  View(const std::vector<T>& items, int window_starty, int window_startx);
  virtual ~View() { }

  const T& CurrentItem() const;
  // ...
  const std::vector<T>& items_;
  // ...
};

View<Card> hand_view = new View<Card>(hand, starty, startx);


Optimize bash script that concatenates output

do ... done is a compound command; every subcommand shares the file descriptors; so teeing the the loop has the same effect as teeing each subcommand.
Two subsequent invocations of echo can be combined together.
cat $file is a dreaded UUOC.
A basename invocation can be avoided by changing directory to $FOLDER.
ls is absolutely unnecessary. The shell already globbed the *.csv.

Summing up,

    chdir "$FOLDER"
    for file in *.csv; do
        echo -n "$file" "|" | sed -r ...
        head -1 "$file"
    done | tee $LOGFILE

does the same job.


If you can use extra space :

# O(n) running time / O(n) memory
def get_pair_count(nums, target_sum):
    count = {}
    for num in nums:
        count[num] = count.get(num, 0) + 1

    total_double = 0
    for num in nums:
        complement = target_sum - num
        if complement in count:
            total_double += count[complement]
            if complement == num:
                total_double -= 1
    return total_double // 2

source : http://www.geeksforgeeks.org/count-pairs-with-given-sum/

If you can't use more space you could try this version I just made (at your own risk)

 # O(n log n) running time / O(1) memory
def get_pair_count_no_extra_memory(nums, target_sum):
    nums.sort()
    start = 0
    end = len(nums) - 1
    total = 0

    while start < end:
        current_sum = nums[start] + nums[end]
        if current_sum == target_sum:
            start_count = 1
            end_count = 1
            special_case = False
            if nums[start] == nums[end]:
                special_case = True

            while start+1 < len(nums) and nums[start] == nums[start+1]:
                start_count += 1
                start += 1
            while end-1 >= 0 and nums[end] == nums[end-1]:
                end_count += 1
                end -= 1

            if special_case:
                total += ((start_count - 1) * start_count) // 2
            else:
                total += start_count * end_count
            start += 1
            end -= 1
        elif current_sum < target_sum:
            start += 1
        else:
            end -= 1

    return total


Username, Password and UserType Validation

Here are some observations:

you first iterate all rows in Credentials and then select the Password yet again - why not just select the pasword?
seems like your password is plain-text - BAD idea - hash your password together with a  salt please
don't concat strings to get SELECT queries - use parameters instead
you are using C#/ASP.NET so why don't you use the provided login mechanisms?
you return a string "A" if the login succeeds and the error message if not - this is IMO bad design - return a simple struct/class with more information instead


Really not much to review, here. I think you did a pretty good job. There are a few points I'd like to make, though:

Indents in Javascript (at least as far as I've seen) are four spaces, not two.
When you're continuing a line, you indent twice; this applies to things like where you defined scales.
Use || in place of | wherever possible. Functionally identicaly, but it's a free little performance boost at no cost. Oops! turns out that's wrong. Thanks to @Flambino for pointing that out. I was just thinking in terms of logical operators, not bitwise ones. However, I would recommend using Math.floor instead of it; it's clearer.
Rather than using array[array.length] = ..., use array.push(...). Much cleaner.
You never seem to handle negative numbers. See below for how you could do that without changing lots of your code.

One big point: Your toWords function should do everything itself. You shouldn't have to call chunkify, then map, then map again, then filter, etc. etc. Wrap all that in a function and you'll be golden. Plus, that lets you do fancy stuff like handle negative numbers -- for example, this (should) do the trick:

function toWords(n) {
    var asString =  chunkify(n).map(toWords).map(scalify).filter(notEmpty).reverse().join(", ");
    if (n < 0) {
        asString = "negative " + asString;
    }
    return asString
}

Anyway, that's about it! Nicely written.


This doesn't look very linq-ish and clean yet. You mixed the algorithm with console output. Everything inside a single method. That needs separation.

Start by creating two extension methods giving you the numbers for the calculations:

public static IEnumerable<T> PrimaryDiagonal<T>(this IEnumerable<T[]> values)
{
    return values.Select((x, i) => x[i]);
}

public static IEnumerable<T> SecondaryDiagonal<T>(this IEnumerable<T[]> values)
{
    return values.Reverse().Select((x, i) => x[i]);
}

Now you can calculate whatever you want:

var nums = new[]
{
    new [] { 11, 2, 4 },
    new [] { 4, 5, 6 },
    new [] { 10, 8, - 12 }
};

var primarySum = nums.PrimaryDiagonal().Sum();
var secondarySum = nums.SecondaryDiagonal().Sum();


Is there a redundancy between the two functions of adding a start node and an end node to my graph?

You can use the built-in getattr function to extract an attribute by name. Likewise the setattr function to set attributes.
This means you can pass the name of the attribute to a private function, unifying the code:
def _find_nodes_with_no(pred_succ: str, nodes: List[Node]) -> List[Node]:
    """ Find nodes with either no predecessors, or no successors. """

    if pred_succ not in ("predecessors", "successors"):
        raise ValueError("pred_succ must be either 'predecessors' or 'successors'")

    return [node for node in nodes if not getattr(node, pred_succ)]

Your add_start and add_end functions can thus be written to pass the appropriate names:
def add_start(graph: Graph):
    info = ("create_start_node", "predecessors", "successors")
    _add_outer_node(graph, info)

def add_end(graph: Graph):
    info = ("create_end_node", "successors", "predecessors")
    _add_outer_node(graph, info)

Then in _add_outer_node you can do things like:
cmeth, main_links, back_links = info
create_method = getattr(Node, cmeth)
new_node = create_method(graph)

# ...

outer_nodes = _find_nodes_with_no(main_links, graph)

One thing I do question it your "manual" connection of both the predecessor and successor links. It seems like you want those to be reflexive, so why not create an add_predecessor method that automatically creates the reciprocal link? Likewise with add_successor?


You seem to have a lot of counts of things. towns_visited is a good example. This implies to me that in your game, you would have a variety of towns to be visited. Perhaps, having an empty set for which towns you have visited, and instead of towns_visited, just use a count of that set. Every time you visit a town, add it to the set. The same would apply to houses. Every time you buy a house, add the specific house object to a list and that would take care of houses and what you do with them. I'm assuming you know the difference between a list and a set.


The ActiveSupport::Cache is not mandatory in Memcached, there are a cache in memory if you use the :memory_store ( http://api.rubyonrails.org/classes/ActiveSupport/Cache/MemoryStore.html )

config.cache_store = :memory_store

Maybe can be a good start to implement your own Cache in memory


Achieve a dataframe from a dynamic list of lists

Reviewing line-by-line:

cutoffmatrix <- c(0, 0.005, 0.01, 0.015)

If this is a vector, why call it a matrix? I would just call it just cutoffs.

for(i in 1:length(cutoffmatrix)){
    test <- list()
    co <- cutoffmatrix[i]
    assign(paste("TC", i, sep = ""), calcs("TC", co))
}

The use of 1:length(cutoffmatrix) in a for loop is a common mistake. You'll probably agree that, by design, the code in the loop will be executed length(cutoffmatrix). Well, that's not exactly always the case. In particular, when cutoffmatrix is empty: cutoffmatrix <- c(). You would want the loop to be executed length(cutoffmatrix) i.e. zero times. However, in this unfortunate case, 1:length(cutoffmatrix) would evaluate to 1:0 i.e. c(1, 0). Instead of zero iteration, you'll have two and likely cause an error. Instead of 1:length(cutoffmatrix), you should use seq_along(cutoffmatrix) or seq_len(length(cutoffmatrix)). Both seq_along and seq_len will do the right thing when their input is empty or zero respectively.

The use of assign to dynamically create objects is, excuse my word, an abomination. I'll try to show you a couple reasons why. Via your loop, you have managed to create four objects: TC1, TC2, TC3, TC4 which you later use in your code:

l_TC <- list(TC1, TC2, TC3, TC4)

What would happen if instead of 4 objects, you had 2000 objects? Do you see yourself typing l_TC <- list(TC1, TC2, TC3, TC4, ..., TC2000)? No. Maybe you will find about the get or mget function so you can do:

l_TC <- mget(paste("TC", seq_along(cutoffmatrix), sep = ""))

But wait. This is still abominable. For one reason, you could be creating thousands of such objects and "polluting" your environment with similar objects. Why not put them all into a single object? Also imagine someone coming across TC1 in your environment and searching for "TC1" through your code to find where it got created: no luck. Finally, having to use mget to indirectly refer to the TC* objects is a bit complex, no? And you have to remember that the objects are labelled 1 through length(cutoffmatrix)...

So what is the alternative? Do not create length(cutoffmatrix) objects but just one object: a list containing length(cutoffmatrix) items. How? Use lapply or Map:

l_TC <- lapply(cutoffvec, calcs, site = "TC")

Look how shorter this is! And in the following, 1) your code will only use l_TC to refer to those 4 or 2000 objects stored within 2) Someone stumbling upon l_TC in your environment will see exactly where it was created in your code. By all means, please never use assign again and erase that function from your memory!

Next:

library(plyr)
df_TC <- ldply (l_TC, data.frame) #transform lists of lists into dataframe

So this converts the lists into data.frames and rbinds everything together. You do not really need plyr for that. You can first turn the lists into data.frames by doing lapply(l_TC, as.data.frame). And you can do the binding using do.call(rbind, ...), so:

df_TC <- do.call(rbind, lapply(l_TC, as.data.frame))

But before doing that: Why do you need to convert the list items to data.frames, then bind? Could you instead rewrite calcs so that it returns a data.frame? And better, could calc take a vector of cutoffs instead of a single value and return a data.frame with length(cutoffs) rows?

final <- rbind(df_TC, df_DC)
final <- cbind(final, cutoffmatrix)

Instead of having to add cutoffmatrix, could calcs already include a cutoff item in its output list?

namelist <- c("TC", "TC", "TC", "TC", "DC", "DC", "DC", "DC")
final <- cbind(final, namelist)

This code has a baked-in assumption that there are four cutoffs. If you were to modify cutoffmatrix so its length is not four, then this would break. Instead, you could do:

namelist <- rep(c("TC", "DC"), each = length(cutoffmatrix))

Still, not great. Similar to above, the best would be if calcs could include a site = site item in its output list.

Last. What if instead of two sites "TC" and "DC" you had many more websites to use? How could you modify your code so you do not have to write "TC" or "DC" more than once and have to rely on creating too many objects? Maybe use some of the concepts I have shown you? Good luck!


Raku multiplication using prompt and say

To tighten your code a bit, you can declare my $a and assign in the same line:
my $a = prompt "enter number: ";
my $b = 34;
my $c;
$c = ($a * $b);
say  "$a multiplied by  $b is $c";

The above seems to solve your question, however a user might not respond with the proper input. If a user replies to the prompt with Hello you'll get an ungraceful error:
Cannot convert string to number: base-10 number must begin with valid digits or '.' in '⏏Hello' (indicated by ⏏) in block <unit> at Pedr_Ap_Glyn.p6 line 7

You can add a Type declaration to obviate this issue:
my Int $a = prompt "enter number: ";

...which, if an Int is not returned, will error with the message:
Type check failed in assignment to $a; expected Int but got [WHAT RAKU GOT IS HERE] in block <unit> at Pedr_Ap_Glyn.p6 line 5

Maybe a different pre-declared Type is more useful for your case:
my Numeric $a = prompt "enter number: ";

...which will work with non-Integer input (e.g. 3.14159265).
Or you could declare your own Type subset (below, "PosInt"):
subset PosInt of Int where * > 0;
my PosInt $a = prompt "enter number: ";

...which will only accept Ints greater that zero. Above are just a few options that the Raku language offers--and that you may wish to take advantage of.


The following examples show that there is something wrong in your code :

print(BoyerMoore('azertyuiop', 'zertyuio' ))  #  1 - fair enough
print(BoyerMoore( 'zertyuio' , 'azertyuiop')) # -1 - so far so good
print(BoyerMoore('azertyuiop', 'azertyuiop')) #  0 - ok
print(BoyerMoore('abcdefgiop', 'iop'))        # -1 - looks wrong to me
print(BoyerMoore('iop'       , 'abcdefgiop')) # -1 - ok (just wanted to check that arguments were in the right order)


Processing names and meanings from .txt files

I would start from the declaration of main. You are throwing an exception from it but no other class will handle it. You should put your Scanners inside a try-catch and handle the exception properly.

I would also recommend reading everything from the files at once and use that collection of data in your code logic. A Scanner locks the file until it's finished with it.

Furthermore, you don't have to call System.out.println(...) just for the sake printing a new line. Use the \n escape sequence for doing the same

System.out.println("This program allows you to search through the \ndata from the Social Security Administration \nto see how popular a particular name has been \nsince 1890.\n");

The rest is just a search function to find the meaning based on the name and gender. I recommend creating a name Baby class with name and gender attributes and use a Hashtable<Baby, String> to search for the meaning. The class can be as simple as

class Baby{
    private String name;
    public String Name(){
        return name;
    }

    private boolean gender;
    public boolean Gender(){
        return gender;
    }

    public Baby(String name, boolean gender){
        this.name = name;
        this.gender = gender;
    }
}

The time complexity of searching a value from a Hashtable is close to O(1) while a typical looping mechanism is O(n). The speed becomes n times slower as the size of the collection increases.

You also have a lot of duplicate code in the two while statements. To resolve that I'd recommend extracting out the if-else logic outside and calling a common function with a single loop. Something like

bool foundMatch = findMatch(...);
if(foundMatch) {
  findMatch(...) // with different params now
}
else {
  // print error message
}

Solving with Constraints

Given the constraints for the solution, I'd solve it as below

public static void main(String[] args){
    Scanner consoleInput = new Scanner(System.in);

    // Welcome message
    System.out.println("This program allows you to search through the \ndata from the Social Security Administration \nto see how popular a particular name has been \nsince 1890.\n");

    // Receive user input
    System.out.print("Name: ");
    String inputName = consoleInput.next();
    System.out.print("Gender: ");
    String inputGender = consoleInput.next();

    consoleInput.close(); // Closed as not needed anymore

    try (Scanner namesScanner = new Scanner(new File("names.txt"));
            Scanner meaningsScanner = new Scanner(new File("meanings.txt"))) {

        String foundMatch = findMatch(inputName, inputGender, namesScanner);
        if(!foundMatch.equals("")){
            System.out.println(foundMatch);
            System.out.println(findMatch(inputName, inputGender, meaningsScanner));
        } else{
            System.out.println("\""+ inputName + "\" not found.");
        }

    } catch (FileNotFoundException ex){
        System.out.println("File Not Found");
    }
}

private static String findMatch(String name, String gender, Scanner fileScanner){
    while(fileScanner.hasNextLine()){
        String currentLine = fileScanner.nextLine();

        // Split it to a String array and check the first two values
        String contents[] = currentLine.split(" ");
        if(name.equalsIgnoreCase(contents[0]) && gender.equalsIgnoreCase(contents[1])){
            return currentLine;
        }
    }
    // if no returns occured till the end of the file
    return "";
}

Please note that

The Scanners should be closed once you're done using them. Using Try-with-resources statement is a better alernative (as recommended in the comments). You don't have to worry about the Scanners being closed. The try block functions like a using from C# and releases all resources after the block itself is finished. The defined resources must implement the java.io.Closeable interface for this functionality and the Java project must use Java SE 7 or above.
Both name matching operations can be handled by the same function. The significance of positive matches is handled by the calling function. This also enforces Single Responsibility Principle (SRP) and improves code maintainability
Use equalsIgnoreCase(...) instead of equals() to avoid using toLowerCase() on all strings
return is called immediately from the function on the first match to avoid redundant checks

Now if you'll be very strict and won't accept the use of a String array. You can replace it by extracting the first and second values using substring(...) function on the first two whitespaces


Given a vector and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum

Normally, we'd use the vector's index type (std::vector<int>::size_type, i.e. std::size_t) for the return values.  But unfortunately we're required to return negative values when the search fails, so I'd recommend a pair of std::ptrdiff_t instead.  And the question specifically asks for ints, so I'd just insert a comment explaining that were limited to arrays of up to INT_MAX elements (the O(n²) scaling probably reduces the practical range, anyway).

I don't see anywhere that says there can't be negative numbers present - if that's specified, then it would have been wise to quote that part.  As it is, you've introduced a bug - because we're not storing numbers larger than sum into com, the index calculation it - com.begin() + 1 will be incorrect by the amount of omitted large numbers (also, where does the +1 come from? - did you misread zero-based indices in the question?).

The vector com could grow to (in the worst case) the same size as the input vector.  That's quite a lot of extra storage.  It might be more efficient to leave the >= sum elements in place, and just search the beginning half of the input vector (no extra storage needed).

That looks like the following (making a few other simplifications, such as using an iterator instead of count, and reducing the scope of the find result):

static std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    for (auto it_b = list.begin();  it_b != list.end();  ++it_b) {
        if (auto it_a = std::find(list.begin(), it_b, sum - *it_b);  it_a != it_b) {
            return {it_a - list.begin(), it_b - list.begin()};
        }
    }
    return {-1, -1};
}

We still have a pretty inefficient algorithm - it's O(n²), where n is the length of list, because for every element in list, we perform a linear search for its complement.  We can reduce that, at the cost of reintroducing extra storage, by maintaining a set of seen values.  That may seem little different to the present approach of maintaining a vector, but the advantage is that search scales much better with size.  What we actually need is a map, as we'll want to note the corresponding index to return as result; the best choice is std::unordered_map:

  Unordered map is an associative container that contains key-value pairs with unique keys. Search, insertion, and removal of elements have average constant-time complexity.

That gives us:

    std::unordered_map<int, int> seen; // value -> index

    for (auto it_b = list.begin();  it_b != list.end();  ++it_b) {
        if (auto it_a = seen.find(sum - *it_b);  it_a != seen.end()) {
            return {it_a->second, it_b - list.begin()};
        } else {
            seen[*it_b] = it_b - list.begin();
        }
    }

Modified code

#include <unordered_map>
#include <utility>
#include <vector>

static std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    std::unordered_map<int, int> seen; // value -> index

    for (auto it_b = list.begin();  it_b != list.end();  ++it_b) {
        if (auto it_a = seen.find(sum - *it_b);  it_a != seen.end()) {
            return {it_a->second, it_b - list.begin()};
        } else {
            seen[*it_b] = it_b - list.begin();
        }
    }
    return {-1, -1};
}

And a very simple test program:

#include <iostream>
int main()
{
    auto const [a, b] = findTwoSum({ 1, 3, 5, 7, 9 }, 12);
    std::cout << a << ',' << b << '\n';
}


Frequency analysis for simultaneous dice rolls - follow-up

Found a solution without foreach

@single_sum_of_eyes = sort{$a <=> $b} keys %count;
    for($j = 0; $j<scalar @single_sum_of_eyes; $j++)
    {
        push(@frequency,$count{$single_sum_of_eyes[$j]});
    }
    for($i=0; $i<scalar @frequency; $i++)
    {
    printf "\n\t$single_sum_of_eyes[$i]\t\t\t $frequency[$i]\t\t%g", ($frequency[$i]/$number_of_rolls)*100;
    }
    print "\n";