Reading SQL query from a resource, with error logging

The most unforgivable aspect of this code is that it rethrows a degraded exception.  The original type of the exception (likely an IOException) and the stack trace information are lost when you throw new Exception(…).

Two acceptable approaches are:

Log the failure (if a non-null logger was passed).  Then re-throw the original exception.

 public static string GetSqlQuery(string namespaceAndFileNameWithExtension, ILogger logger)
 {
      try
      {
           using(var stream = typeof(EmbeddedResourceUtility).GetTypeInfo().Assembly.GetManifestResourceStream(namespaceAndFileNameWithExtension))
           using(var reader = new StreamReader(stream, Encoding.UTF8))
           {
                return reader.ReadToEnd();
           }
      }
      catch (Exception exception)
      {
           logger?.Error($"Failed to read query file {namespaceAndFileNameWithExtension}.{Environment.NewLine}{exception.HResult}: {exception.Message}");
           throw;
      }
 }

Throw a custom exception, wrapping the original exception.

 public static string GetSqlQuery(string namespaceAndFileNameWithExtension)
 {
      try
      {
           using(var stream = typeof(EmbeddedResourceUtility).GetTypeInfo().Assembly.GetManifestResourceStream(namespaceAndFileNameWithExtension))
           using(var reader = new StreamReader(stream, Encoding.UTF8))
           {
               return reader.ReadToEnd();
           }
      }
      catch (Exception exception)
      {
           throw new EmbeddedResourceException($"Failed to read query file {namespaceAndFileNameWithExtension}", exception);
      }
 }

In this case, requiring an ILogger just isn't worth it.  The caller has all of the information in the EmbeddedResourceException, and can log it if it wants.

I recommend the second approach, because it respects the principle of separation of concerns.


PHP validation class for username, email, and password

Well, your class is good and does what it is supposed to do, except in validalidatecheckbox() (you are using variables that doesn't exist).

Also I would do this changes:

Remove this code (it's unused):

private $password,
    $repeatPassword,
    $username,
    $email;
Change this to constants, so you can use it elsewhere:

private static $minPassword = 7,
    $confirmPassword,
    $minUsername = 3,
    $maxUsername = 14,
    $validEmail;

So your class should look like this:

class Validation
{
    const MIN_PASSWORD_LENGTH = 7;
    const MIN_USERNAME_LENGTH = 3;
    const MAX_USERNAME_LENGTH = 14;

    // rest of your code

Also, I strongly recommend you to check PSR-1 and PSR-2 to make your code look standard-like.


Alternative: Rx
Creating your own producer/consumer solution is not always easy and is one option but you could also use the tools that are already there. One such tool are the Reactive Extensions (NuGet-Package: System.Reactive). It can be very helpful in your scenario.
I requires two parties

an observable and
an observer

Your not yet real observables are the POCO objects that implement the INotifyPropertyChanged interface. You can turn them into observables with helper factories that can derive an IObservable from the PropertyChanged event pattern.
class Person : INotifyPropertyChanged, IObservable<EventPattern<PropertyChangedEventArgs>>
{
    private readonly IObservable<EventPattern<PropertyChangedEventArgs>> _observable;

    private string _name;

    public Person()
    {
        _observable =
            Observable
                .FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                    handler => PropertyChanged += handler,
                    handler => PropertyChanged -= handler
                );
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
        }
    }

    public IDisposable Subscribe(IObserver<EventPattern<PropertyChangedEventArgs>> observer)
    {
        return _observable.Subscribe(observer);
    }
}

Now you only need a task to process a collection of them. You can create it in many different ways so here is just one of them. I created an observable from an array of persons that I Merge into a single observable that I want to watch. I'd like this to be processed either every ten items or every two seconds (there are also other options). Then each batch is processed with the ForEachAsync loop.
var persons = new[]
{
    new Person { Name = "John"},
    new Person { Name = "Tom" }
};

var savePersonBatchTask =
    persons
        .Merge()
        .Buffer(timeSpan: TimeSpan.FromSeconds(2), count: 10)
        .Where(batch => buffer.Count > 0)
        .ForEachAsync(batch =>
        {
            Console.WriteLine($"New batch arrived: {batch.Count}");
        });

You can test this simulation by creating another loop that modifies the person's name 27 times.
for (int i = 0; i < 27; i++)
{
    foreach (var person in persons)
    {
        person.Name = i.ToString();
    }
}

await savePersonBatchTask;

The output will look like this
New batch arrived: 10
New batch arrived: 10
New batch arrived: 10
New batch arrived: 10
New batch arrived: 10
New batch arrived: 4

There is a lot more it can do and all that is explained very nicely on Introduction to Rx.

Review
And I also have a couple of comments about your code...

private readonly Queue<Tuple<string, object>> _saveOrders

You can simplify this and make it easier to use by using strong tuples with named properties. All you need is to throw away the Tuple type and let the compiler derive the tuple for you.
 private readonly Queue<(string FileName, object Item)> _saveOrders = ..;

later in code you also don't need it anymore
saveOrders.Enqueue((fileName,item));

Your while loop will become simpler too because tuples can be deconstructed into variables:
while (_saveOrders.Count > 0)
{
    var (fileName, item) = _saveOrders.Dequeue();
    if (_saveOrders.All(o => o.FileName != fileName))
    {
        await SaveHelper.TrySaveToAppData(fileName, item);
    }
}


Using Func instead of helper methods in a class

This is a perfect use case for an extension method. It gives maximum readability to your business code, and makes the method available on any DateTime object.

//Test
class Program
{
    static void Main(string[] args)
    {
        Console.Write(DateTime.Today.MostRecent(DayOfWeek.Saturday));
        Console.Read();
    }
}
//Extensions
public static class DateTimeExtensions
{
    public static DateTime MostRecent(this DateTime date, DayOfWeek dayOfWeek)
    {
        var day = date.Date;
        while (day.DayOfWeek != dayOfWeek)
            day = day.AddDays(-1);
        return day;

    }
}


Is this a good way to limit the occurrence of OutOfMemoryException?

Based on your comments it looks like your code is actually some sort of library used by different clients in different environments. If that's the case I would rather let clients define the batch size they want rather than writing tricks around memory management on your own.

If you do need to manage the memory - I would suggest to reduce the frequency of GC.GetTotalMemory calls, e.g. check it once per 1000 rows or so. Bear in mind that since your component is not the only one in the application it may turn out that application has already consumed 1GB of RAM thus causing you to reduce the batch size to minimum.


Check fragment for exclude show same fragment again

In this line:

.replace(R.id.main_activity_fragment_container, fragment, fragment.getClass().getSimpleName()+"|"+fragment.getArguments())

you can reuse the newFragmentTag variable:

.replace(R.id.main_activity_fragment_container, fragment, newFragmentTag)

This way you don't have to perform the same string concatenation twice, which is sort of the purpose of variables & methods in the first place.
Try to use getSupportFragmentManager() if you're using AppCompatActivity.
Since you're going to replace the fragment in R.id.main_activity_fragment_container anyways, there's no need to check the back stack. Just check if there are any fragments in the container before checking its tag.

Below is how I would rewrite the code in my style (you don't have to follow this):

FragmentManager fManager = getSupportFragmentManager();
String newFragmentTag = fragment.getClass().getSimpleName() + "  |  " + fragment.getArguments();

Fragment currentFragment = fManager.findFragmentById(R.id.main_activity_fragment_container);
if (currentFragment != null && currentFragment.getTag().equals(newFragmentTag)) {
    Log.w(TAG, "Fragment is already displayed");
    return;
}

fManager
    .beginTransaction()
    .replace(R.id.main_activity_fragment_container, fragment, newFragmentTag)
    .addToBackStack(fragment.toString())
    .commit();


Here is anoted version of your code

from tkinter import *
from time import sleep
from random import randrange

# lowercase tkinter suggest you are using python3, in this case
# inheriting (object) is not needed anymore to create newstyle
# class
class alien(object):
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width=400, height=400)
        self.canvas.pack()
        self.map = [[1, 0, 0, 1, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [1, 0, 0, 1, 0]]
        self.x = 0
        self.y = 0
        for row in range(len(self.map)):
            for column in range(len(self.map[row])):
                color = "green"
                #since 0 evaluate to False, you can drop '== 1'
                if self.map[row][column] == 1:
                    color = "black"
                self.canvas.create_rectangle(50 * row , 50 * column , 50 * row + 50, 50 * column + 50,
                    outline=color, fill=color)
        self.creature = self.canvas.create_rectangle(50 * self.x, 50 * self.y, 50 * self.x + 50, 50 * self.y + 50,
            outline="red", fill="red")
        #this call overrides the previous 'canvas.pack'. Remove first.
        self.canvas.pack(fill=BOTH, expand=1)
        self.root.after(0, self.animation)
        self.root.mainloop()

    def animation(self):
        #see below for further explanations on animations.
        while True:
            i = randrange(1, 5)
            print(i)
            #note: randrange ouput from 1 to 5 (included)
            #thus i = 5 is not handled in your switch (might be on purpose)
            if i == 1:
                y = -1
            elif i == 2:
                y = 1
            elif i == 3:
                x = -1
            elif i == 4:
                x = 1
            # after you switch, either x or y (or both) are not
            # initialized
            sleep(0.025)
            # self.x and self.y are never updated
            print(self.x, self.y)
            # move is a relative command (expect delta x,delta y)
            # if self.x,self.y is your creature absolute position,
            # you might want to use 'coords' on (self.x, self.y)
            # or 'move' on (x,y)
            # in addition, your "*50" factor has disapeared.
            self.canvas.move(self.creature, self.x, self.y)
            # it is good practice to use 'update_idletasks' instead
            # of 'update' to avoid race conditions. By the way
            # the use of one of them is seldom required (see below)
            self.canvas.update()
alien()

Regarding how you handle the animation, it could be profitable to run your simulation in the python mainloop. What you does now is to provide your own mainloop (while True: [...] sleep(0.025) [...] canvas.update()). This can work, but will fail as soon as you will want to add interactivity to your application (other widgets, or react to events on canvas). This will not work because the execution path is stuck in alien.animation. The solution there would be to rely on tkinter mainloop and to beg for alien.animation to be repeatedly called.

def animation(self):
    #while True:  no longer needed
        i = randrange(1, 5)
        #[...]
        elif i == 4:
            x = 1
        #sleep(0.025) becomes
        self.root.after(25, animation)
        print(self.x, self.y)
        self.canvas.move(self.creature, x*50, y*50)
        #self.canvas.update() no longer needed


In radixSort you assume that std::iterator_traits<Iterator>::value_type is a signed 32bit int.

Instead you should check whether it's an integral type and alter the algorithm a bit based on its properties:

template <typename Iterator>
void radixSort(Iterator begin, Iterator end)
{
    using value_type = typename std::iterator_traits<Iterator>::value_type;

    static_assert(std::numeric_limits<value_type>::is_integer, "Wrong type");

    for (auto i = 0; i < std::numeric_limits<value_type>::digits; ++i)
    {
        std::stable_partition(begin, end,
            [&](value_type& value)
        {
             return !(value & (1 << i));
        });
    }

    if(std::numeric_limits<value_type>::is_signed){
        std::stable_partition(begin, end,
            [&](value_type& value)
        {
             return value < 0;
        });
    }

}

Besides that all your algorithms use the standard std::less comparator. you should let the user supply a comparator (a mapping function for radixSort) for types that don't have a default std::less.


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

The only option is this one:

// ...
while (score != -1) {
    if (score > 100) {
        cout << endl << "Is the score correct? (Enter 'y' or 'n'): ";
        cin >> decision; cout << endl;
        if (decision != 'y' && decision != 'Y') score = 0;
    }

    totalPoints += score;
    cout << "Next score ('-1' to stop): ";
    cin >> score;
}   //end while
// ...

It can't be more efficient using given circumstances.


Maintaining users in a Dovecut user database

In this code:

while [[ -z "$USERNAME" ]]; do
    echo -n "Please enter username: "
    read "USERNAME"
done

What if the variable USERNAME is not empty when this code is reached?
For example, the environment might be dirty by misbehaving scripts,
and USERNAME might already be set to garbage, and the script will not prompt the user.

echo -n is not recommended because it's not portable. Use printf instead.

There's no need to quote USERNAME when reading into it.

The equivalent code, safer and better:

USERNAME=
while [[ -z "$USERNAME" ]]; do
    printf "Please enter username: "
    read USERNAME
done

Do similarly for the other loops too.

This will fail if PASSWORD contains spaces:

USERPASS="$(doveadm pw -p $PASSWORD -s SHA512-CRYPT)"

To make it safe, quote it:

USERPASS="$(doveadm pw -p "$PASSWORD" -s SHA512-CRYPT)"

It would be better to indent the function bodies. For example:

list_users () {
    if [[ -f "$USERDB" ]]; then
        awk -F: '/./'' {print $1} ' "$USERDB"
    else
        echo "User database not exist or have been moved to another directory!"
        exit 1
    fi
}

This is especially helpful in the case of longer functions.

The quotes are strange and confusing in this awk:

        awk -F: '/./'' {print $1} ' "$USERDB"

It would be better simply this way:

        awk -F: '/./ {print $1}' "$USERDB"


You have a public static property UserName that can be set by anyone, anywhere in your code. You didn't detail the usage of this property.

If it's the logon form that should update it and it will never update again, have your Program class set this field.

If it's another class that updates this field, maybe this property doesn't belong here.

You have some code that is duplicated, so there must be a way to do better.

From my point view, you are doing many different things in your Main method, maybe you could put these operations in separate methods : Init, Login, Start.

Use using

You put the Presenter for MainForm in the Tag Property, which I think belongs to a specific property. That way the MainForm can control who has access to it, otherwise any object that has an access to the MainForm can recover the Tag and therefore the Presenter. Another problem is that the Tag property is an object, so you will have to convert it every time you want to use it.

So, all together that would become :
using System;
using System.Windows.Forms;
using WindowsFormsApp.Presenters;
using WindowsFormsApp.Views;
using Autofac;
using DbContexts;
using Serilog;

namespace WindowsFormsApp
{
    internal static class Program
    {
        public static IContainer Container { get; private set; }
        public static string UserName { get; private set; }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Init();
            Login();
            Start();
        }

        private void Init()
        {
            var builder = new ContainerBuilder();
            builder.Register(c => new MyContext());
            Container = builder.Build();

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.RollingFile("log-{Date}.txt")
                .CreateLogger();
            Log.Information("Application Started");

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
        }

        private void Login()
        {
            using (loginForm = new LoginForm())
            {
                var results DialogResult.None;
                do
                {
                    results = loginForm.ShowDialog();
                    if (results == DialogResult.Cancel)
                        System.Environment.Exit(1);
                } while (results != DialogResult.OK);
                //Since we logged on correctly, we can update UserName (I guess)
                UserName = loginForm.ValidatedUserName;
            }
        }

        private void Start()
        {
            using (var mainFormView = new MainFormView())
            {
                mainFormView.Presenter = new MainFormPresenter(mainFormView);
                Application.Run(mainFormView);
            }
        }
    }
}


this code returns environment varibles or passed enverionment variable with values

Some notes:

Indent with 4 spaces (PEP8)
Use underscore_names for function and variables.
Use meaningful names for functions (specially) and variables.
Be concise in docstrings.
Don't write for index in range(iterable): but for element in iterable:.
Don't write variable = sys.argv in the middle of the code, use it directly as an argument.
Use an import for each module.

I'd write (Python 3.0):

import sys
import os

def print_environment_variables(variables):
    """Print environment variables (all if variables list is empty)."""
    if not variables:
        for index, (variable, value) in enumerate(sorted(os.environ.items())):
            print("{0}: {1}".format(variable, value))
    else:
        for variable in variables:
          value = os.environ.get(variable)
          if value:
              print("{0}: {1}".format(variable, value))
          else:
            print("Variable does not exist: {0}".format(variable))

print_environment_variables(sys.argv[1:])

But if you asked me, I would simplify the function without second thoughts, functions are more useful when they are homogeneous (that's it, they return similar outputs for the different scenarios):

def print_environment_variables(variables):
    """Print environment variables (all if variables list is empty)."""
    variables_to_show = variables or sorted(os.environ.keys())
    for index, variable in enumerate(variables_to_show):
        value = os.environ.get(variable) or "[variable does not exist]"
        print("{0}: {1}={2}".format(index, variable, value))


It is said that "a method should do one thing, and it should do that one thing well". Your iterateData method is being used to do two separate things, depending on the parameter you send it.
If your ArrayUnsortedList is this class (which really could use a code review itself) then I don't really understand why you are using it. The way I see it is that you could use a regular ArrayList.
What you are referring to as "class variables" are static variables. It would be better to use them as instance variables. Currently you can't have two ContextFreeGrammar objects at once, each with it's own state. Remove the static keyword and *create an instance of ContextFreeGrammar to properly use it as an instance (which is a lot better practice, although you might not have learned about such things yet. If you haven't learned about it yet, you should ask your teacher about it)
Only create a new Random object once. Random objects are meant to be re-used. When they are initialized, they get a random seed set depending on the system clock time. Repeatedly creating a Random object gives a loss in randomness.
Instead of your current iterateData method, consider using one method such as int calculateTotalWeight(List<Production> list, String nonTerminal) and one String determineExpression(List<Production> list, String nonTerminal, int weightRandom). Determining such an important behavior of your method by sending it a true/false value makes your code harder to understand. You don't need to pass seven variables to the method when it only uses two or three.


Is there more elegant way than using if - else to append or update the data array in a React app?

Note that you do the same thing if the array is empty or if the last item's localeDate doesn't match - you can combine those two paths.

You only want to update the existing object if the last item exists and its date matches, so I'd first set a flag for that, which can be done concisely via optional chaining.

Then, .map looks a bit verbose when all items of the array are unchanged except for one - you could consider using .slice instead to take all but the last item, spread them into a new array, then add the changed object as the last item.

useEffect(() => {
    // update item if date matches
    const changeExistingItem = data[data.length - 1]?.date === localeDate;
    const updatedData = changeExistingItem
        ? [...data.slice(0, data.length - 1), { ...data[data.length - 1], round }]
        : [...data, { round, date: localeDate }];
    setData(updatedData);
}, [round]);

Also see that you can use shorthand property names to keep things concise: { someProp: someProp simplifies to { someProp in modern Javascript.

As a side note: always use const to declare variables, whenever possible. When you use let, you're warning readers of the code that you may be reassigning that variable name in the future, which results in more cognitive overhead.


Follow Up post: Proper handling of exceptions in MVP

I can follow the reasoning behind the catch and rethrow even if I might not fully agree with it - without a fuller understanding of what you would like to achieve I will not try to offer an alternative.

The only comments I can see at the moment are:

HouseKeeping
InsertAccount() still has a return value even though it is never used.  It can/should be removed.

Don't Repeat Yourself (DRY)
If you have a lot of calls to database, you do not want to have to repeat the exception handling (logging) code in each of them.

At the simplest level you can have a member in the data service that takes in an Action, executes it and handles any exceptions

private void ExecutNonQuery(Action nonQueryAction) {
    try {
       nonQueryAction();
    }
    catch (SqlException) {
        throw new Exception("DataBase related Exception occurred");
    }
    catch (Exception) {
        throw new Exception("Exception occurred");
    }
}

public void InsertAccount(IBankAccount ba)    {
  ExecuteNonQuery(()=> {
         string insertStatement = @"IF NOT EXISTS (SELECT ac_no FROM BankAccount WHERE ac_no=@ac_no) BEGIN INSERT INTO BankAccount (ac_no, emp_id, ac_name, bank_name, ac_type," +
                              "ent_date, ent_by, remarks, file_no, status) VALUES (@ac_no, @emp_id, @ac_name, @bank_name, @ac_type, @ent_date, @ent_by, @remarks, @file_no, @status) END";

        //...
  });
}

As I said, this is a minimal version.  The next level is to refactor out the common code for connection and command creation (a bit more work but it can be done).

MessageService
As I said, I favour the MessageService approach but with one caveat.  It is not obvious from the code if MessageService.ShowErrorMessage() is a static method on a static class (equivalent to the call the MessageBox) or if MessageService is a property of the class containing SaveBankAccount().  If a static, you still have the problem with the unit tests as a MessageBox is still shown each time.


Get random direction based off of location and previous direction

First of all, using i and j as variable names when dealing with 2D-arrays is just crazy in my personal opinion. Using x and y makes it so much clearer to know which is which.

Then, use an enum:

public enum Direction {
    LEFT, UP, RIGHT, BOTTOM;

    public Direction opposite() {
        switch (this) {
            case LEFT: return RIGHT;
            case RIGHT: return LEFT;
            case UP: return BOTTOM;
            case BOTTOM: return UP;
            default: throw new IllegalStateException();
        }
    }
}

This is probably the most useful enum there is. I don't know how many versions of it I have. Also note that you can add dx and dy values to this enum (UP for example is dx = 0 and dy = -1). This tends to reduce a lot of code duplication.

Now that we have an enum we can return that instead of those int things.

Also, we can use Java's EnumSet class to handle a collection of enums. This class is optimized to use a long (BitSet object for longer enums) and bitmasks, sort of like you seem to already be doing.

Once we have a nice EnumSet to use, then we can either create an array of it and grab a random item from the array, or we can use the iterator of it to iterate over random.nextInt(size) items (not the cleanest and fastest solution perhaps, but it should be faster than creating an array).

Random random = new Random();
private Direction nextDirection(final int y, final int x, final int rowLimit, final int columnLimit, final Direction previous) {
    EnumSet<Direction> directions = EnumSet.allOf(Direction.class);
    if (x == 0) {
        directions.remove(Direction.LEFT);
    }
    if (x == columnLimit) {
        directions.remove(Direction.RIGHT);
    }
    if (y == 0) {
        directions.remove(Direction.UP);
    }
    if (y == rowLimit) {
        directions.remove(Direction.BOTTOM);
    }
    directions.remove(previous.opposite());

    Iterator<Direction> it = directions.iterator();
    for (int i = 0; i < random.nextInt(directions.size()); i++) {
        it.next();
    }
    return it.next();
}

Or, if you would like the array approach:

Direction[] options = directions.toArray(new Direction[directions.size()]);
return options[random.nextInt(options.length)];


Function to determine the direction of an arrow

The test for if(changeType === 'no-change') { is redundant and not needed as it will fall through if the other tests fail and return null anyways.

You could also break the statement up returning the result as needed and falling through if they fail for null.

const getArrowDirection = (dir, type) => {
    if (type === "positive") {
        if (dir === "increasing") { return "up-arrow" }
        if (dir === "decreasing") { return "down-arrow" }
    }else if (type === "negative") {
        if (dir === "increasing") { return "down-arrow" }
        if (dir === "decreasing") { return "up-arrow" }
    }
    return null;
}

Assuming that you have given all possible values you can make assumptions and reduce the code further

const getArrowDirection = (dir, type) => {
    if (type !== 'no-change') {
        if (type === "positive") { return dir === "increasing" ? "up-arrow" : "down-arrow" }
        return dir === "increasing" ? "down-arrow" : "up-arrow";
    }
    return null; // returning null is not the best. Returning undefined would
                 // be better and would not need this line
}

You can use an object as a lookup using the combined strings.

const getArrowDirection = (() => {
    const directions = {
        positiveincreasing: "up-arrow",
        negativedecreasing: "up-arrow",
        positivedecreasing: "down-arrow",
        negativeincreasing: "down-arrow",
    };
    return (dir, type) => directions[type + dir] ? directions[type + dir] : null;
})();


Fetch and display products from a SOAP call

Have you considered using a template engine vs. writing old-style PHP spaghetti code?

if(!$oSessionHash->HasError){

Reverse this conditional to get rid of the huge section of code within this conditional (whihc is actually not even closed with the code shown.  So something like:

if($oSessionHash->HasError) {
    // die, exit, redirect or similar
}
// rest of code, now no longer in a conditional.

This strategy of existing early from scripts/function/methods will help you write much less fragile code.

A number of stylistic concerns:

Drop the whole $o*, $a*, $s* variable naming (which looks like you are trying to infer variable type in name).  Your variables should have meaningful and specific names which convey their meaning. Also, if you use a good IDE, you won't need this.
Your spacing around assgniment operators, flow control structures, etc. is wildly inconsisten, making your code hard to read.  If you are strating in PHP, I would recommend getting to know the PSR-1 and PSR-2 coding standards as well as other PSR recommendations which are most widely accetped ways of writing code in the profession PHP development community. A good IDE will be able to help you enforce these styles.
Don't split your define across two lines unnecessarily like you are.

Why not perform logout immediately after your API call response is returned, rather than wait until after displaying results?

This code is very happy path oriented.  What happens if API doesn't respond? What if it responds with an error code? What if it returns empty result set?


Return row count from mysqli prepared statement

You should definitely not be mixing procedural and object-oriented syntax.
Although it works with un-mixed syntax, the process is working harder than it needs to and delivering more result set data than you intend to use.
I would add COUNT(1) or COUNT(*) to the sql like this:
$sql = "SELECT COUNT(1) FROM notifications WHERE viewed='0' AND user_to = ?";
$query = $this->con->prepare($sql);
$query->bind_param("s", $userLoggedIn);
$query->execute();
$query->bind_result($count);
$query->fetch();
return $count;

Assuming the sql is not broken due to syntax errors, this will always return a number.


Haskell: downpair :: (Monad m) => m (a, b) -> (m a, m b) implementation

(return . fst =<<) can be replaced by fmap fst. Your definition then becomes

downpair = fmap fst &&& fmap snd


The best pattern to start "OOP" in JavaScript is the Revealing Pattern:

var revealed = function(){
   var a = [1,2,3];
   var abc = function(){
     return (a[0]*a[1])+a[2];
   }

   return {
      name: 'revealed',
      abcfn: abc
   }
}();

From here.

Then read this book.

And learn RequireJS, which will increase the modularity of your code and will load your JS files on demand.

I see you are using JS for create HTML elements.  To help you with this, take a look at UnderscoreJS templates and Mustache.


Web Scraping Dynamically Generated Content Python

Combined imports

from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import TimeoutException

should be

from selenium.common.exceptions import (
    ElementNotInteractableException,
    NoSuchElementException,
    ElementClickInterceptedException,
    TimeoutException,
)

Input-in-static

This:

job_title = input('Enter your desired position: ').replace(' ', '+')

creeps me out. I don't know a lot about scrapy, but see if you can initialize job_title in the constructor instead of as a static. What if this class were to be imported once and used twice, each with a different job title?

Hard-coded paths

This:

'C:\Users\leagu\chromedriver.exe'

should be pulled out into a constant, or better yet, an environmental parameter, command-line argument or configuration file parameter. Surely a user of yours who downloads your script will not be named leagu.

XPath

/html/body/main/div[2]/div/div[1]/div[3]/div/div/a

is extremely fragile and opaque. I loaded the remote.co search results, and a better selector - mind you, this is CSS and not XPath - is

div.card > div.card-body > div.card > div.card-body > a.card

You should not start from the root element, and you should attempt to use classes and IDs where possible. This markup is kind of a mess and so meaningful paths are hard to form.

Swallowing exceptions

You do this:

    except TimeoutException:
        self.log("Timeout - Couldn't load the page!")

but then continue with the rest of the method? Would you not want to re-throw, or at least return?

Non-guaranteed close

This:

self.driver.close()

will be skipped if there is any uncaught exception. First of all, I don't think the driver should be closed in parse, or else the class effectively can only support one invocation of parse. Implement __enter__ and __exit__, and call driver.close() in __exit__. Have the instantiator of ScrapeRemote use it in a with-block.


As philomory said in a comment, this is a neat demonstration of some of Ruby's features, but also a horribly complex way of saying a + b.

In it's most basic formulation, you could just do:

puts gets.chomp.to_f + gets.chomp.to_f

Of course, this leaves out a lot of the stuff your code is currently doing (like telling the user what they're supposed to input). So let's see if we can get all the same functionality, but with a different structure.

First, though, a few notes on your current code (apart from the metaprogramming):

Don't overwrite arguments just to avoid a new variable. You pass let (a symbol) to define_method, but then use it to store the user's chosen number. So now you have a variable named let, presumably short for "letter", which has nothing to do with letters - now it's a floating point number. You have the contents (the input), but you've overwritten its label. Or, you have the answer, but you've forgotten the question, to paraphrase Hitchhiker's Guide.

Besides conflating the concepts of name and value, it's also impractical. You wouldn't, for instance, be able to print something like "You entered a = 23", because you no longer know both the letter and the entered value.
This is redundant

let = Float(gets.chomp)
sum += let.to_f

You create a Float from the input. And then you call to_f on that float - but it's already a float. Either use Float(...) to get a number, or use the .to_f on a string. The latter is the conventional approach, but the former will complain if the input isn't numeric, so that's probably the one you'll want to use here:

sum += Float(gets.chomp)

And we've avoided overwriting let too.
But speaking of code complaining: You might want to be more specific in your exception handling. Your current rescue block doesn't distinguish between the sorts of errors that might arise. It's one thing to complain to the user if their input is bad, but what if the error is about something else? For instance, if I run your code in my editor, it'll run without an interactive terminal. So gets immediately returns nil, which causes a NoMethodError since chomp isn't a method on nil. And since gets returns immediately, the script goes into a retry-loop, spewing "Something went wrong. Try again." as fast as it can until I kill it.

Obviously, this isn't how the script is meant to be run, but it goes to show how telling the user to "try again" isn't always a solution. Your code just assumes it's always the user's fault, and if it tries enough times, the problem will get fixed. But the error could also be a mistake in the code, like writing get instead of gets - that'd also cause the script to loop indefinitely, even though there's nothing the user can do to salvage things.

Now, for alternative approaches: While define_method is a really neat Ruby feature, it's not called for in this case. But a generalized method for getting a float as user input would be useful. Then you can use that for the rest of the code. For instance, the script could be:

def read_float(prompt)
  puts prompt
  Float(gets.chomp)
rescue ArgumentError # only rescue this type of error
  puts "Please enter a number"
  retry
end

puts %w(a b).reduce(0) { |sum, var| sum + read_float("Enter #{var}") }

Yes, I'm being a little clever with the reduce and everything. A more straight-forward and instantly readable way would be to say:

a = read_float("Enter a")
b = read_float("Enter b")
puts a + b

which is about as to-the-point of "A + B = C" as you can get.


This question is probably not appropriate for stackoverflow, since it requires mainly code review.

First of all, there is a logics problem with your while loop. Changing | to & reduces the number of loops considerably.

Furthermore you should not use dataframes, if you can use a matrix.

my.sampling1<-function(days, status, s.length, s.freq, iter){
    start<-Sys.time()

    #build the data frame
    ddd<-data.frame(days=days, positive=status)

#length of each sample
    j<-s.length

#Buld the sample space
    monitor.ss<-matrix(nrow=dim(ddd)[1]-j+1, ncol=j+1)
    n.row<-dim(ddd)[1]-j+1

    #Create the elements of sample space: each row of the monitor.ss is an element of the sample space
    for (i in 1:j){
        monitor.ss[,i]<-i:(n.row-1+i)
    }
    rm(i)

    #adds if the each of the possible samples of the sample space at least one event was observed or not
    monitor.ss[,j+1]<-apply(monitor.ss,1,function(x) {
        r.low<-range(x,na.rm=T)[1]
        r.high<-range(x,na.rm=T)[2]
        return(as.numeric(sum(ddd$positive[r.low:r.high])>0))})

suc.list<-rep(NA, iter) #Initiate a vector to keep track of successes

    #Now the sampling takes place

    k<-s.freq #number of samples drawn from the sample space
    for (i in 1:iter) { #for each iteration

        #do not convert to data.frame
        sampling.start<-monitor.ss

        k.t=0 #controller to break the while loop
        suc<-0

        #use & to stop the loop if one condition is not fullfilled, second condition changed because a matrix is used instead of a data.frame
        while (k.t<=k & !is.null(nrow(sampling.start))) { #breaks the while loop if k reaches the specified limit (k=s.freq) or if the reduction of the sample space (see below) does not leave any elements in the sample space
            #set.seed(k.t*i) #use set.seed to test if results are identical
            s<-sampling.start[sample(nrow(sampling.start),1),] #samples the first trial
            suc<-suc+s[j+1] #adds up if there is a success or not ( a tleast one event in the sample was observed)
            sampling.start <- sampling.start[apply(sampling.start, 1, function(x) !any(x %in% as.numeric(s[1:j]))),] #sample space reduction: Elements of the sample space that intersect with the sample that was just selected are removed from the sample space before the next sampling occurs
            k.t<-k.t+1 #controller for the wile loop
        }

        suc.list[i]<-(suc/k.t)

    }
    print(Sys.time()-start)
    message("")
    #hist(suc.list, breaks=sqrt(iter))
    return(suc.list)
}
kkk<-data.frame(days=1:100,positive=rbinom(100,1,0.05))
res1<-my.sampling1(kkk$days, kkk$positive, s.length=3, s.freq=5, iter=20)

This is already faster. To make it even more efficient, I would try to avoid apply inside the loop (could an algebraic operation be used instead?) and try to vectorize. Furthermore you can tidy up. There are some unnecessary assignments inside the function.


CoffeeScript implementation of A* algorithm

I am not an expert on the A* algorithm. I'm suggesting changes based on the
Rules of Clarity, Simplicity, and Economy and the code you provided,
not on an extensive knowlege of graph traversal methods.

Extensive documentation inline is tricky to read. Consider using a standardized
docstring format like those in docco or codo for detailed
inline docs.

###
  returns the goal node or null if path not found. Reconstruct path by
  following the goalNode.src until null

  @param [Object] start The node to start searching from
  @param [Object] options The options object

  @option [Function] neighbors Takes node, returns array of neighbors
  @option [Function] heuristic Takes node, returns A* heuristic
  @option [Function] isGoal Takes node, returns true if node is goal
  @option [Function] distance Takes two nodes returns distance between them

  @returns {Object} Returns the goal node with a tracable path to the start
###

It's not clear which options you expect you be left as their default values
most frequently. If most options will be left as defaults most of the time,
and the function will "just work" without configuration, use an options
object and set sensible defaults.

aStar = (start, opts = {}) ->
  opts.neighbors or= (node) -> []
  opts.heuristic or= (node) -> 0
  opts.isGoal    or= (node) -> opts.heuristic(node) is 0
  opts.distance  or= (a, b) -> 1

If you want to find paths from many start points, you might
setup your function once and allow several calls, each providing a start point.

AStar = (opts = {}) ->
  opts.distance  or= (a, b) -> 1
  # ... and other defaults

  (start) ->
    # logic for calculating path from "start"

# use it like this
astar = AStar
  isGoal: -> yes
  neighbors: -> [1, 2, 3]

# goal is the destination node (as it was in the original logic)
goal = astar {x: 1, y: 2}

Inside the logic function, remember that "Clarity is better than cleverness".
Slightly longer, but much more descriptive names go a long way to making the
operations easier to understand.

(start) ->
  closed = {} # nodes already evaluated
  nodes  = {} # key: node to be evaluated, value: f-score (F = G + H)
  gscore = [] # the exact cost to reach this node from start

Breaking the operations in to related sections makes it easier to follow.

  # constructing path
  addNode = (node, src) ->
    node.src = src
    gscore[node] = if src? then gscore[src] + opts.distance src, node else 0
    nodes[node] = gscore[node] + opts.heuristic(node)

Naming functions with verbs and naming functions that return booleans with is
and has usually increases clarity. Verbs do things, so do functions. You
want the behavior of your code to be unsurprising to the person reading it.

  # selecting best path
  isBetter = (a, b) ->
    a is null or b < nodes[a]

  selectBest = (best = null) ->
    best = node for node, fscore of nodes when isBetter(best, fscore)
    closed[best] = yes if best?
    delete nodes[best]
    best

Break complex boolean questions into parts so the reader (which is also you,
later) can follow (with a minimal cognitive load) what you intend to be
determining with your comparisons.

  # answers about current node
  isOpen = (node) ->
    not closed[node]

  isShorter = (a, b) ->
    nodes[a] is null or gscore[b] + opts.distance(a, b) <= gscore[a]

  isAvailable = (neighbor, node) ->
    isOpen(neighbor) and isShorter(neighbor, node)

The big loop that does all the work would be clearer if you could quickly see
what situation would trigger the loop ending. while true is less communicative
than doneSearching.

  findGoal = (start) ->
    # insert start point
    addNode start, null

    # store the node in use
    node = null

    doneSearching = ->
      node = selectBest()
      return yes if node is null or opts.isGoal node
      no

    # find the shortest path in the current open set
    # stop looking when out of options or at the goal
    until doneSearching()
      for neighbor in getNeighbors node when isAvailable neighbor, node
        addNode neighbor, node
    node

Everything up to here defines the operations that will be used. This is the
single point that triggers action in this function. Reducing the number of
moving parts makes tracing the logic path easier.

  findGoal(start)


The FULL JOIN looks a bit odd for this query.  An INNER JOIN would be more appropriate if all employees have an associated UserEntity row (trusted foreign key relationship) and your intent is to return only employee user entity types, which seems to be the purpose of EntityType = 0 in the WHERE clause.

It is best to avoid applying functions to columns in JOIN and WHERE clauses because that prevents indexes on those columns from being used efficiently.  Columns should stand alone on at least one side of the comparison operator when possible.  If all photos have the same file extension and you don't have subdirectories in your file table, you can use the refactored example below to build the file namespace path and use the GETPATHLOCATOR function to return the unique path_locator of the photo.  The path_locator column is the file table primary key so this will be efficient and ensure only one row is returned per employee.

CREATE VIEW [emp].[ViewEmployees]
    AS SELECT
        ue.Id,
        ue.Active,
        ue.Comments,
        ue.Created,
        ue.IsLockedOut,
        ue.LastLoggedOn,
        ue.NameIdentifier,
        e.FirstName,
        e.MiddleName,
        e.LastName,
        e.DisplayName,
        e.Duties,
        e.EmailAddress,
        e.FullPart,
        e.JobTitle,
        e.LegacyId,
        e.OtherPhones,
        e.Phone,
        e.Profile,
        e.StartDate,
        e.ShowOnDirectories,
        ep.name as PhotoName,
        ep.file_stream as PhotoBytes
FROM [security].[UserEntity] as ue
JOIN [emp].[Employees] as e on
    ue.Id = e.Id
LEFT JOIN emp.EmployeePhotos as ep on
    ep.path_locator =
        GETPATHLOCATOR (
            FILETABLEROOTPATH ( 'emp.EmployeePhotos')
            + '\'
            + SUBSTRING(e.EmailAddress, 0, CHARINDEX('@', e.EmailAddress, 0))
            + '.jpg')
WHERE
    ue.UserEntityType = 0;

Alternatively, you could create a unique index on the file table name column and change the file table LEFT JOIN clause to:

WHERE ep.name = SUBSTRING(e.EmailAddress, 0, CHARINDEX('@', e.EmailAddress, 0))
            + '.jpg'

Regarding you question about retrieving the photo via a separate query, it would be best to return the image in the same query, assuming the application actually uses it.  If you have cases where this view is used but the photo isn't needed, make sure the PhotoName and PhotoBytes columns are omitted from the SELECT query column list when querying this view.  That should allow SQL Server to remove the unneeded file table from the query plan.


Extension method to retrieve a sample from a collection

public static T Sample<T>(this IEnumerable<T> values)
        {
            return Sample(values, 1).First();
        }

Nice helper method.

            if(!values.Any())
            {
                throw new InvalidOperationException("Collection empty.");
            }

I would have used an ArgumentOutOfRangeException, but that's a matter of personal preference. Should it throw an exception if size == 0 or return an empty list? That's a tricky edge case which should be clearly documented.

        public static IEnumerable<T> Sample<T>(this IEnumerable<T> values, int size)

I would prefer the Random to be an argument too, even if it's as Random rnd = null with a fallback inside the method. Being able to seed your random selection is important for testing the code and for reproducing results if it's a scientific project.

            if (size < 1)
            {
                return new List<T>();
            }

I would definitely prefer to throw an ArgumentOutOfRangeException if size < 0.

            if (size >= values.Count())
            {
                return values;
            }

If size > values.Count() then I think that should be ArgumentOutOfRangeException or InvalidOperationException. Again, whichever way you finally decide, it should be clearly documented.

Note that we've now called two methods which iterate partially or fully through values. If it was a non-deterministic iterator we have problems. An example of a non-deterministic iterator would be

public IEnumerable<int> Demo()
{
    var rnd = new Random();
    for (int i = rnd.Next(10); i > 0; i--) yield return rnd.Next();
}

If you call this once and then loop through the resulting iterator multiple times then it will not consistently return the same values. You may think that in real usage you won't come across iterators like that, but sometimes the non-determinism is a lot more subtle.

            var samples = new List<T>();
            var source = new List<T>(values);

Since we have to convert source to a list here, there's an argument for doing it earlier and ensuring that we only iterate through values once, solving the problem of non-deterministic iterators.

                source.Remove(value);

This is expensive. It's asymptotically more efficient to replace this with

                source[index] = source[source.Count - 1];
                source.RemoveAt(source.Count - 1);

Finally, on the names. In your context it might be obvious that Sample means "sample without replacement", but in some contexts it might be important to distinguish between sampling with and without replacement. Consider whether you might need to distinguish the cases in future usage of the library.

Postscript: t3chb0t's suggestion of a Randomise method which can then be combined with Take is compatible with a rewrite of your GetSamples method, and in fact this is what I have kicking around in my library of utility methods (although I call it Shuffle). As a modification of your code:

    public static IEnumerable<T> Randomise<T>(IEnumerable<T> values, Random rnd = null)
    {
        if (rnd == null) rnd = _rnd;

        var source = new List<T>(values);
        while (source.Count > 0)
        {
            var index = rnd.Next(source.Count);
            yield return source[index];
            source[index] = source[source.Count - 1];
            source.RemoveAt(source.Count - 1);
        }
    }


Printing the days of the week for every day this year

The only thing I have to say is that the use of strftime and %A means that the output will depend on the current locale setting.

This may be a bug or a feature depending on what your original intention was.

Also, the use of char buf[80] seems rather small for today's processors. The only way that strftime is going to fail is if it can't fit all of the output in the buffer. Since memory is cheap, you might as well make it char buf[256] or buf[1024]. This kinda of ties in with with the question of whether you expect to use this with custom locales.

Alternatives:

use strftime_l to use a specific locale
create your own array of weekday names instead of %A and use the tm_wday field to index into that array


Yes. I would add try..finally so that the file will be properly closed even in the case of exception (hopefully my remembrance of the syntax isn't too rusty):

var
  openfile: TextFile;
begin
      AssignFile(openfile, 'test.exe');
      Append(openfile);
      try
          WriteLn(openfile,'[test]hi world[test]');
      finally
          CloseFile(openfile);
      end;
end;

also, you say you want to write binary files as well as text files.. so don't use TextFile. The "modern" way would be to use TFileStream:

with TFileStream.Create('test.exe', fmOpenWrite) do
try
  Seek(0,soFromEnd);
  Write(...);
finally
  Free;
end;


Is it bad practice to have executable code in my channel state object?

I agree that you should pull this functionality out of CommunicationStateMachine. Your state machine should only expose the methods necessarily to make changes in state and to query the current state. Your CommunicationStateMachine class should also be responsible for enforcing the rules of your state machine, i.e. ensuring that only valid state transitions happen. This logic is typically hidden inside the class and invoked when an attempt is made to change state.

In general, the approach you've suggested (the State design pattern) seems like a sensible choice based on your description of your requirements.

Minor note: you've got a small typo on checkJsonMessageIntegraty, which should be Integrity at the end. It may also be more intuitive if your class is called JsonProcessor to reflect its purpose.


Find missing element in an array of unique elements from 0 to n

I don't think there is a better than \$O(n)\$ and \$O(1)\$ to this problem.

However you can simplify the code a little (trivial) by subtracting from the expected total.

const findVal = nums => vals.reduce((t, v) => t - v, nums.length * (nums.length + 1) / 2);

Or

function findVal(nums) {
    var total = nums.length * (nums.length + 1) / 2;
    for (const v of nums) { total -= v }
    return total;
}

BTW

The extra brackets are not needed when calculate the total

(x * (x + 1)) / 2 === x * (x + 1) / 2


Calculate working days and excluding specific dates (Holidays)

Bug
There is a bug in this method. It counts non-working days because the workDay condition needs to be negated.
return
    Enumerable
        .Range(0, (finishDate - current).Days)
        .Count(day => !isExcludedDate(current.AddDays(day)));

Naming
Then comes the naming. What's with the prefixes fw, dtm, lst? In C# we don't use the hungarian notation. You should use either the camelCase or PascalCase naming where appropriate.

Closures
You could take advantage of closures and simplify the Count
public static int GetWorkingDays(this DateTime current, DateTime finishDateExclusive, List<DateTime> excludedDates)
{
    Func<int, bool> isWorkingDay = days =>
    {
        var currentDate = current.AddDays(days);
        var isNonWorkingDay =
            currentDate.DayOfWeek == DayOfWeek.Saturday ||
            currentDate.DayOfWeek == DayOfWeek.Sunday ||
            excludedDates.Exists(excludedDate => excludedDate.Date.Equals(currentDate.Date));
        return !isNonWorkingDay;
    };

    return Enumerable.Range(0, (finishDateExclusive - current).Days).Count(isWorkingDay);
}

Depending on how long the List<DateTime> excludedDates is, you may consider using a HashSet<DataTime>.
Upper range

1 + (dtmFinishDate - dtmCurrent).Days

Most .NET APIs consider the upper range exclusive thus it might be a good idea to follow this style by removig the +1 and renaming the finishDate to finishDateExclusive.


Longest non-decreasing subsequence, in Haskell

A few general remarks

I find that stepped whiles are as evil as nested if statements for readability of the code. Here, you have three levels of nesting.
Relying on the surrounding environment for variables can some times obscure possibility to generalize (You make use of x and m for inner definitions)

So here is what I would do

import Data.Sequence as DS
import Numeric.Search.Range as R

seqLast::Seq a -> a
seqLast xs = index xs ((DS.length xs) - 1)

insert_idx :: Ord a => a -> Seq [a] -> Maybe Int
insert_idx y m = searchFromTo (fn y) 0 $ (DS.length m) - 1
  where fn y idx = y < (head (index m idx))

-- Return the longest non-decreasing subsequence of an input sequence of integers
nonDecreasing::[Int] -> [Int]
nonDecreasing = Prelude.reverse . seqLast . makeM
  where makeM = foldl updateM empty
        updateM m x | DS.null m = singleton [x]
                    | otherwise = case insert_idx x m of
                        Nothing -> m |> (x: seqLast m)
                        Just l -> update l (x:geti l m) m
        geti 0 _ = []
        geti l m = index m (l -1)


This is very old, but I'd like to give a "modern way" of implementing this.

Everything should be a project, e.g. usethis::create_package("roll_util")

Every function should be in its own R-file, e.g. usethis::use_r("roll_zscore")

First version:
roll_zscore <- function(x, ...) {
avg <- RcppRoll::roll_mean(x, ...)
std <- RcppRoll::roll_sd(x, ...)

(x - avg) / std
}

Here, instead of y, we are inheriting all the rolling-operation behaviour
that is provided by {RcppRoll} (remember to add it as a dependency,
usethis::use_package("RcppRoll"))

Documentation, second version
#' Rolling Z-scores
#'
#'
#' @param x a time-series `xts` object
#' @inheritDotParams RcppRoll::roll_mean
#'
roll_zscore <- function(x, ...) {
#omitted

Next, example/test/etc.

Testing framework: usethis::use_testthat()
Unit-test for this function: usethis::use_test("roll_zscore")
We want it to work for {xts} objects, so we add it as a suggestion, because really this function could work with other stuff. usethis::use_package("xts", "Suggests")

The test looks like this:
test_that("standard example of roll_zscore", {
    requireNamespace("xts", quietly = TRUE)

    data(sample_matrix, package = "xts")
    sample.xts <- xts::as.xts(sample_matrix, descr='my new xts object')

    roll_zscore(sample.xts$Open, n = 2, fill = NA)
    roll_zscore(sample.xts$Open, n = 25, NA)
})

From this test, we discover some crucial problems with this implementation.

It doesn't work for n = 1. This is probably due to sd.
attached to it.
In order, to do the last calculation, the fill argument must be set to
something, otherwise the vectors won't be of equal length.

Either decide to handle these in the function, in the documentation, or elsewhere.

To properly handle ellipsis arguments, I've made use of do.call. Honestly, if I
wasn't trying to make this as simple as possible, I'd have used rlang and purrr::exec.
Final version of the code:
#' Rolling Z-scores
#'
#'
#' @param x a time-series `xts` object
#' @inheritDotParams RcppRoll::roll_mean
#'
roll_zscore <- function(x, ...) {
  args <- list(...)

  # either use provided `fill` or `NA`
  args$fill <- if (is.null(args$fill)) NA else args$fill
  args <- append(args, list(x = x))

  avg <- do.call(RcppRoll::roll_mean, args)
  std <- do.call(RcppRoll::roll_sd, args)

  (x - avg) / std
}

And final test file:
test_that("standard example of roll_zscore", {
  requireNamespace("xts", quietly = TRUE)

  data(sample_matrix, package = "xts")
  sample.xts <- xts::as.xts(sample_matrix, descr='my new xts object')

  roll_zscore(sample.xts, n = 3)
  roll_zscore(sample.xts$Open, n = 25)
  roll_zscore(sample.xts, n = 3, fill = 0)
  roll_zscore(sample.xts, n = 3, fill = NA)
  roll_zscore(sample.xts$Open, n = 2, fill = NA)
  roll_zscore(sample.xts$Open, n = 25, fill = NA)
})


SQLAlchemy - InsertFromSelect with columns support

columns.append(compiler.process(column, asfrom=True))

should be simply

columns.append(column.name)

and

table = compiler.process(element.insert_spec[0].table)

should be

table = compiler.process(element.insert_spec[0].table, asfrom=True)


It's hard to help without knowing the sizes, but:

The first thing to do would be to measure the relative cost of each of the 5 statements to see where the bottleneck is.
-(a5/2 + d1/2 + log(a1)) could be precomputed into a temporary outside the loop.
Replace pow(A1.row(j).transpose(), 2) by A1.row(j).transpose().square().
Compilation flags might also help: make sure you enabled AVX and if supported FMA using e.g., -march=native.
Depending on the sizes, you might want to rewrite the expressions to benefits from faster matrix-matrix products:

'

T = (M2-M4).transpose() * M1;
for(j...)
  ...
  A1.row(j) = a1*a2 * (T.col(j) - M1.col(j).squaredNorm() * M3.row(j).transpose());
  ...


Encrypt and decrypt a serializable object

Some obvious problems that jump into the eye:

Don't use duplicate string literals, like "MyDifficultPassw" and "AES/ECB/PKCS5Padding". Put them into constants and define them near the top.
Don't e.printStackTrace(). It's considered bad practice.
The encrypt and decrypt methods violate the single responsibility principle, because they encrypt / decrypt and at the same time do file I/O. Instead of writing to / reading from a filesystem path, it would be better to work with streams. That would open make them testable too (see below).
The decrypt method takes a Serializable object that's not used at all. Also, the initialization SealedObject sealedObject = null; is pointless, as the variable is always assigned before use anyway.

It would be slightly better this way:

private static final byte[] key = "MyDifficultPassw".getBytes();
private static final String transformation = "AES/ECB/PKCS5Padding";

public static void encrypt(Serializable object, OutputStream ostream) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    try {
        // Length is 16 byte
        SecretKeySpec sks = new SecretKeySpec(key, transformation);

        // Create cipher
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.ENCRYPT_MODE, sks);
        SealedObject sealedObject = new SealedObject(object, cipher);

        // Wrap the output stream
        CipherOutputStream cos = new CipherOutputStream(ostream, cipher);
        ObjectOutputStream outputStream = new ObjectOutputStream(cos);
        outputStream.writeObject(sealedObject);
        outputStream.close();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }
}

public static Object decrypt(InputStream istream) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    SecretKeySpec sks = new SecretKeySpec(key, transformation);
    Cipher cipher = Cipher.getInstance(transformation);
    cipher.init(Cipher.DECRYPT_MODE, sks);

    CipherInputStream cipherInputStream = new CipherInputStream(istream, cipher);
    ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
    SealedObject sealedObject;
    try {
        sealedObject = (SealedObject) inputStream.readObject();
        return sealedObject.getObject(cipher);
    } catch (ClassNotFoundException | IllegalBlockSizeException | BadPaddingException e) {
        e.printStackTrace();
        return null;
    }
}

This is only slightly better, it still looks quite messy. But it has the big advantage that now this is testable, for example:

@Test
public void testEncryptDecryptString() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
    String orig = "hello";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    encrypt(orig, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    assertEquals(orig, decrypt(bais));
}

@Test
public void testEncryptDecryptPerson() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
    Person orig = new Person("Jack", 21);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    encrypt(orig, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    assertEquals(orig, decrypt(bais));
}

static class Person implements Serializable {
    private static final long serialVersionUID = 0;
    private final String name;
    private final int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Person person = (Person) o;

        if (age != person.age) {
            return false;
        }
        if (!name.equals(person.name)) {
            return false;
        }

        return true;
    }
    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + age;
        return result;
    }
}


Inheritance selfmade or reinventing wheel

From some staring at your code:

Do not declare var in an if block, it gives the wrong impression. I would just declare it on top, something like this:

//Define namespace
var SimpleJSLib;
SimpleJSLib = SimpleJSLib || {};

As far as naming, since SimpleJSLib is not a constructor, it should not start with capital S. The name JSLib is not very informative beyond what language it is writen in..
I know that for some _ in _protected means "private", but I agree with Crockford that this convention should be avoided
Now a big one: you broke support for instanceof operator, that's just wrong
Furthermore, you kind of broke support for prototype, you are also not using hasOwnProperty anywhere when you construct objects
And, JS has a perfectly valid constructor, but you decided to have your own construct
Finally, this will be messy once you want to start serializing with JSON

Honestly, read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript and abandon your code. I would not want to maintain code that relies on this.


Find all palindromes in the danish language

You are doing a double loop checking against all other words to determine if something is a palindrome. This is unnecessary. You can look at a single word and determine if it is a palindrome, by reversing it. This should reduce the number of checks by a factor of n.

You should also prefer using a range for to a raw for-loop.

find_palindromes can then become something like this:

std::vector<std::string> find_palindromes(const std::vector<std::string>& words)
{
    for (const std::string& word : words )
    {
        std::string reverseWord(word);
        std::reverse(reverseWord.begin(), reverseWord.end());

        if (word == reverseWord)
        {
            if (std::find(palindromes.begin(), palindromes.end(), first_word) == palindromes.end())
            {
                palindromes.push_back(first_word);
            }
        }
     }

    return palindromes;
}


Naming
There are .NET Naming Guidelines which state that methods should be named using PascalCase casing. You haven't done this for buildString().
The code

The InnerXml property returns a string hence there is no need to call ToString() on the property.
Because all methods are public you should do proper parameter validation. At least you should check if the passed parameter is null and if yes throw an ArgumentNullException.
The PrintOutput () method does way too much. It builds the output, writes it to the console and reads a line from the console.
Because _root won't change you should make it readonly.
Calling PrintOutput twice results in doubling the printed value because you never reset/clear the StringBuilder.
The method name of ReturnNameAsString is too much. Because the method isn't void it is clear that it returns something. From looking at the returned type (string) it is clear what the method returns. Just call it GetNodeName instead.
The class name XMLRecursionReader exposes too much information about the implementation. A user of your code won't need to know that you solve the task by using recursion.
Both methods buildString and ReturnNameAsString should be private.
The if (node.HasChildNodes) in the buildString method is superflous because you are using a foreach to iterate over the ChildNodes. If there aren't any ChildNodes the foreach won't iterate.
The constructor assumes that the passed XmlDocument containes ChildNodes which may not be the case.


Yes this is fine.

By the single responsibility principle, and to achieve functional cohesion, a function should do one thing. As the responsibility of this function takes two logical steps, it makes sense to move those steps to their own functions. And since these functions are only used once, and so they would not be useful not desirable in the global namespace, it makes sense to hide them as inner functions.


SqlConnection, SqlCommand, etc. all implement IDisposable and thus they should be encapsulated in using blocks. Instead you tie SqlConnection to a singleton class, which is the opposite of that.

Here's how they should be used:

using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();

    using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine("{0} {1} {2}",
            reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
        }
    }
}


Bash delete folder if not present in other folder

find is good for finding files and directories recursively in a filesystem tree.
Based on your description and example, you probably don't need that.
If you want to check that some directory foo exists directly under /some/path,
it's much simpler and more efficient to use the test or [ builtin.

There are some other minor issues in the posted code:

It's a good practice (and often necessary) to double-quote variables in command parameters. For example instead of rm -rf ${dir%*/} write rm -rf "${dir%*/}"
Instead of writing ${dir%*/} 3 times, it would be better to store in a variable. In fact you did store the result of the first "call" in a variable, and since subsequent calls on the modified value will be the same, you could have used $dir.
I think dir=${dir%/} is equivalent to dir=${dir%*/} but simpler.

Putting the above together, a cleaner, more efficient alternative:

#!/usr/bin/env bash

for dir in ./Peter/*/*/
do
    dir=${dir%/}
    name=${dir##*/}
    if ! [ -d "./Eva/animals/$name" ]
    then
        echo "$dir not found and deleted"
        rm -rf "$dir"
    fi
done


Developing an alert notification in AngularJS

One simple thing you can do is remove the need for the $observe and place the template inside the directive and use ngShow to handle the show/hide action.  (also added in scope that has two way binding to the alertData object.)

Updated Directive

    var myApp = angular.module('myApp', []);

    myApp.directive('notification', ['$timeout', function ($timeout) {
        return {
            restrict: 'E',
            template:"
{{alertData.message}}
",
            scope:{
              alertData:"="
            }
        };
    }]);

And html

    <notification alert-data="notification"></notification>
<button id="submit" name="submit" class="btn btn-default" type="submit" ng-click="notification.status = 'show'; notification.message = 'Oh yeah!'; notification.type = 'info';">Show</button>

Updated plunkr


Android RecyclerView Adapter: Passing normal clicks and menu clicks over the same activity

It's quite hard to read that code. I think some part is missing as I can't figure out what's going on.

However when you look at SOLID principles, you'll find that the public interface OnItemClickListener you created probably violates the I — The Interface Segregation Principle (ISP), exactly as TextWatcher does.

For more on this, see also Donn Felker's article I is for the Interface Segregation Principle.


Nested routes and proper place for a function?

I would not create custom controller actions. up and down are attributes of a Vote, so I would do the following:

resources :widgets do
  resources :votes, only: [:new, :create]
end

And then send a POST to VotesController#create with params[direction: 'up'] and have an attribute on Vote called direction.

Then validate Vote#direction can only be up or down:

class Vote < ActionController:Base
  validates_inclusion_of :direction, in: %w(up down)
end

Your check for this kind of routing decision is to run rake routes and make sure the route aliases make sense, in this case we are really creating widget_votes, which looks like:

         Prefix Verb   URI Pattern                             Controller#Action
   widget_votes POST   /widgets/:widget_id/votes(.:format)     votes#create
new_widget_vote GET    /widgets/:widget_id/votes/new(.:format) votes#new


Java's Integer class has a built-in method to parse a hex number (string) into an int:

Integer.valueOf("AB", 16)

W.R.T. your code, here are some observations:

hexRep should be final
Ideally your method should also accept lower-case text (just call toUpperCase() on the string)
Include some unit tests perhaps?
I wouldn't put that single method in a class of its own. More appropriate would be to put it in a more general utility class


Asynchronous method and collection binding

First, I want to point out the behavior of method that is declared as async void. When the code reaches this line:

var result = await data;

The code following after _service.GetAnimateur is executed. async void is there only for event handlers. So using this signature creates more problems than it solves.

Second, I may not see the whole picture, but your GetAnimateur looks weird. I think it is because the problem I've mentioned earlier. The most readable and understandable may be code like:

public Task<IEnumerable<fiche>> GetAnimateur()
{
        return Task.Factory.StartNew(() =>
            {
                DataEntities _db = new DataEntities();
                return (IEnumerable<fiche>) _db.fiche;
            });
}

and consume like:

try
{
    var list = await GetAmateur();
    // success
}
catch (Exception ex)
{
    // fail
}

or even:

GetAmateur().ContinueWith(t =>
    {
        if (t.IsCompleted)
        {
            var list = t.Result;
            // success
        }
        else
        {
            var ex = t.Exception;
            // fail
        }
    }, TaskScheduler.FromCurrentSynchronizationContext());

Third, when you add or remove an item from ObservableCollection, the UI gets updated, slowing down performance. One common way to create an observable collection that supports painless multi-adding is

public class RangeObservableCollection<T> : ObservableCollection<T>
{
    private bool _suppressNotification = false;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (!_suppressNotification)
            base.OnCollectionChanged(e);
    }

    public void AddRange(IEnumerable<T> list)
    {
        if (list == null)
            throw new ArgumentNullException("list");

        _suppressNotification = true;

        foreach (T item in list)
        {
            Add(item);
        }
        _suppressNotification = false;
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

So you simply use RangeObservableCollection instead of ObservableCollection.

Fourth, just don't forget about tuning your EF properly for better performance.


Filtering out, a list of games, based on their followers

f-strings
I recommend to use f-strings (Python version >= 3.6) for string formatting. See this link for more details:
https://www.python.org/dev/peps/pep-0498/
When you use them you can replace
if month1 < 10:
    month1 = "0" + str(month1)

with an expression like this:
month1 = f'{month1:02}'

This adds a leading zero if month1 only has one digit.
In addition, an expression like:
 Url = (
        "https://api.rawg.io/api/games?dates="
        + str(year1)
        + "-"
        + str(month1)
        + "-"
        + str(day1)
        + ","
        + str(year2)
        + "-"
        + str(month2)
        + "-"
        + str(day2)
        + "&page="
        + str(PageNumber)
        + "&platforms=4,187,1,18,186&page_size=40&ordering=released"
    )

can be written as
url_part1 = "https://api.rawg.io/api/games?dates="
url_part2 = "&platforms=4,187,1,18,186&page_size=40&ordering=released"

 Url = f"{url_part1}{year1}-{month1}-{day1},{year2}-{month2}-{day2}&page={PageNumber}{url_part2}"

using f-strings. This is shorter and less error prone (less quotes you can forget), opinions might vary regarding the readability, though. Type conversions (str(.)) are not needed anymore.
Avoid hardcoding
It is good that you added a comment to explain where the number 40 comes from:
AmountOfPages = AmountOfGames // 40 #1 page contains 40 so it does amount//40 to get pages

However, it would be even better if you assigned this number to a variable with a telling name. For example
games_per_page = 40 # Preferably, put this on the top of your script or in a config file
# [...]
AmountOfPages = AmountOfGames // games_per_page

This is more flexible. Imagine the number of games per page changes.
Leftover page: ceiling division
In this part you first do a floor division (//), then you add 1 for leftover pages
AmountOfPages = AmountOfGames // games_per_page#1 page contains 40 so it does amount//40 to get pages
if(AmountOfGames%games_per_page != 0):
    AmountOfPages = AmountOfPages + 1 #does +1 if there's a leftover page

This can be simplified with a ceiling division
import math

AmountOfPages = math.ceil(AmountOfGames / games_per_page)


Python Hash Table implemented using lists

Restructuring and micro-optimization

Hard-coded table size 54 is better defined as class constant:

T_SIZE = 54

Encapsulate the crucial list/table at least as protected property self._Table.

Calling self._get_value(key) and the condition if self._Table[val] == None are repeated in most crucial methods. To reduce that noisy repetition an additional method can be defined which will return a tuple of calculated value val and is_empty ("empty slot" flag):

def _check_value(self, key):
    val = self._get_value(key)
    is_empty = self._Table[val] is None
    return val, is_empty

It doesn't make sense to construct if ... else conditional if the 1st if branch return 's immediately.

Both delete and lookup methods, on existing item, will perform 2 access/lookup operations on self._Table[val]:

key in self._Table[val]
self._Table[val].index(key)

To reduce access operations there we can apply try/except trick and returning the needed result in each separate block. See the final implementation below:

class HashTable:
    T_SIZE = 54

    # Initialize the table with a fixed size
    def __init__(self):
        self._Table = [None] * HashTable.T_SIZE

    def _get_value(self, key):
        total = hash(key)
        return total % HashTable.T_SIZE

    def _check_value(self, key):
        val = self._get_value(key)
        is_empty = self._Table[val] is None
        return val, is_empty

    def insert(self, key):
        val, is_empty = self._check_value(key)
        col = False  # Collision flag
        index = 0

        if is_empty:  # Empty slot - turn into list of keys to avoid extra cases
            self._Table[val] = [key]
        else:
            self._Table[val].append(key)  # Collision - append
            col = True
            index = len(self._Table[val]) - 1

        return val, col, index

    def delete(self, key):
        val, is_empty = self._check_value(key)
        if is_empty:  # Deleting unexisting element
            return -1, 0

        try:
            index = self._Table[val].index(key)
            self._Table[val].remove(key)
            return val, index
        except ValueError:  # No match was found in list, element does not exist
            return -1, 0

    def lookup(self, key):
        val, is_empty = self._check_value(key)
        if is_empty:
            return -1, 0
        try:
            index = self._Table[val].index(key)
            return val, index
        except ValueError:  # No match was found in list, element does not exist
            return -1, 0

    def clear(self):
        self.__init__()

In case if _get_value method won't be used in standalone context - you may easily inline it into _check_value method.

Sample usage:

h = HashTable()
h.insert('abc')
h.insert('abc')
print(h.lookup('abc'))
print(h.lookup('1abc'))
print(h.delete('abc'))
print(h.delete('abc'))
print(h.delete('abc'))

The output (consecutively):

(8, 0)
(-1, 0)
(8, 0)
(8, 0)
(-1, 0)


You make the code really hard to read:
#define INJECTION_SET(FuncName, Substitute)\
private:\
template<class T>\
class FuncName##Class {\
public:\
FuncName##Class():m_func((T)Substitute){}\
T m_func;\
};\
FuncName##Class<decltype(Substitute)> m_##FuncName##Class;\
mutable int m_##FuncName##CallCounter = 0;\
public:\
void Inject##FuncName(decltype(Substitute) sub){\
m_##FuncName##Class.m_func = sub;}\
int Get##FuncName##CallCounter(){return m_##FuncName##CallCounter;}

just because it is a  macro does not mean it needs to be unreadable. You can still format it nicely for the maintainer.
#define INJECTION_SET(FuncName, Substitute)                         \
                                                                    \
    private:                                                        \
    template<class T>                                               \
    class FuncName##Class                                           \
    {                                                               \
        public:                                                     \
            FuncName##Class():m_func((T)Substitute){}               \
            T m_func;                                               \
    };                                                              \
                                                                    \
    FuncName##Class<decltype(Substitute)> m_##FuncName##Class;      \
                                                                    \
    mutable int m_##FuncName##CallCounter = 0;                      \
    public:                                                         \
    void Inject##FuncName(decltype(Substitute) sub)                 \
    {                                                               \
        m_##FuncName##Class.m_func = sub;                           \
    }                                                               \
    int Get##FuncName##CallCounter()                                \
    {                                                               \
        return m_##FuncName##CallCounter;                           \
    }


I believe you are missing the point of the exercise - instead of 'decoding' the input numbers, and then 're-encoding' the output number - you are supposed to iteratively get to the answer by going over the nodes of both lists:

public static LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2) {
  return addLists(0, l1, l2);
}

private static LinkedListNode addLists(int carryOver, LinkedListNode l1, LinkedListNode l2) {
  // stop conditions
  if (l1 == null && l2 == null && carryOver == 0) {
    return null;
  }
  if (l1 == null) {
    l1 = new LinkedListNode(0);
  }
  if (l2 == null) {
    l2 = new LinkedListNode(0);
  }

  // iteration
  int addedValue = l1.value + l2.value + carryOver;
  carryOver = 0;

  if (addedValue >= 10) {
    addedValue -= 10;
    carryOver = 1;
  }

  l3 = new LinkedListNode(addedValue);

  // recursion
  l3.next = addLists(carryOver, l1.next, l2.next);

  return l3;
}


The forced casts as! V in the get() method might seem safe at first
sight, since you do some type-checking before. But they are not:
If a default value for some key exists, but is of the wrong type then
your program can crash. This can for example happen if you change the
type of some default value between program releases. You can easily
reproduce the problem by setting the default value to an incompatible
type before retrieving it with your class:

UserDefaults.standard.set([1, 2, 3], forKey: "username")

class MyDefaults {
    let USERNAME = DefaultValue<String> (name: "username", defValue: "Joe")
}

print(MyDefaults.USERNAME.get())

which crashes at

return userDefaults.string(forKey: name) as! V
// Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

This can be avoided with optional casting as? V, and then the
entire get() method simplifies to

func get() -> V {
    return userDefaults.object(forKey: name) as? V ?? defValue
}

As a bonus, the code now works not only with integers, booleans and
strings, but with all types (provided that they are “UserDefaults compatible”).

I do not see a reason to create separate UserDefaults instances,
you can share the standard instance:

let userDefaults = UserDefaults.standard

The reset() method could simply remove the value instead of setting
the default value:

func reset() {
    userDefaults.removeObject(forKey: name)
}

A possible advantage is that you can retrieve it with a different
default value later.

I would use “default” as argument label in the init method:

init(name: String, default defValue: V) {
    self.name = name
    self.defValue = defValue
}

That looks nicer when called

let USERNAME = DefaultValue<String> (name: "username", default: "")

and also mimics the subscript(_:default:) of Swift dictionaries.

The set() method should have an empty argument label

func set(_ value: V) {
    userDefaults.set(value, forKey: name)
}

like, for example, set(_:forKey:).

If your intention of class MyDefaults is to avoid global variables
and to provide a “namespace”: This can also be achieved with a
case-less enum:

enum MyDefaults {
    static let USERNAME = DefaultValue<String>(name: "username", default: "")
}

MyDefaults.USERNAME.set("elcuco")
print(MyDefaults.USERNAME.get())

so that no instances have to be created.

Naming: According to the Swift API Design Guidelines:

  Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase

so it should be

enum MyDefaults {
    static let loggedIn = DefaultValue<Bool> (name: "logged_in", default: false)
    static let userName = DefaultValue<String>(name: "username", default: "")
}

instead of LOGGED_IN and USERNAME.


If you want to optimize for speed and possibly memory, just use regular loops to build up your dictionary, though it may hurt readability.

The idea is simple, scan the string for keys and values simultaneously.  Don't extract substrings until you know what you need.  Scan each token until you hit a delimiter and add the corresponding keys and values to your dictionary.

Assuming none of your keys or values do not contain any of your delimiters and everything is well formed and you have the same amount of values as you do keys for every string.

var myStrings = new[]
{
    "1-2-3-4-5|a-b-c-d-e",
    "10-20-30-40-50|aaa-bbb-ccc-ddd-eee",
};
var delims = new[] { '-', '|' };
var dict = new Dictionary<string, string>();
foreach (var str in myStrings)
{
    var sepIndex = str.IndexOf('|');

    var keyStart = 0;
    var valueStart = sepIndex + 1;
    while (keyStart < sepIndex)
    {
        // scan for the end of the token
        var keyEnd = str.IndexOfAny(delims, keyStart);
        var valueEnd = keyEnd < sepIndex
            ? str.IndexOfAny(delims, valueStart)
            : str.Length;

        // extract and add the tokens
        var key = str.Substring(keyStart, keyEnd - keyStart);
        var value = str.Substring(valueStart, valueEnd - valueStart);
        dict.Add(key, value);

        keyStart = keyEnd + 1;
        valueStart = valueEnd + 1;
    }
}

For readability, a declarative style works well and LINQ is king, just use it better.

var dict =
    (from str in myStrings
    let split = str.Split('|')
    let keys = split[0].Split('-')
    let values = split[1].Split('-')
    from pair in keys.Zip(values, (key, value) => new { key, value })
    select pair).ToDictionary(x => x.key, x => x.value);

As a side note, don't throw things into a list just for the sake of using the ForEach() method, you don't need the overhead of the list just to be able to interate over a collection through that method.


Cell division Solving algorithm problems

namespace ConsoleApplication1
{
  class Program

These names tell no-one anything useful about what the program does, and there's no comment either. If you find this file on your hard drive in a year's time, will you remember what it's for?

        StringBuilder m_strbuilder = new StringBuilder();

        ...

        m_strbuilder.Append(Result);
        Console.WriteLine(m_strbuilder);

m_strbuilder is a misleading name (m_ is one convention for naming fields, but I've never seen it used for local variables); and the StringBuilder is completely unnecessary. Console.WriteLine(object) can be used as well on one object as another, so this could be simplified to

        ...

        Console.WriteLine(Result);

The indentation is crazy. I suspect that it's due to mixed tabs and spaces being converted to all spaces by the StackExchange software. But consistent code formatting is a good thing in general: reformat your code before you commit / submit for review.

         while (etc)
        {
           try
           {
             Cells.Clear();

             Inputdata = Console.ReadLine();

             Textdata = Inputdata.Split(' ');

             if (Textdata[0] != null && Textdata[1] != null && Textdata[2] != null)
             {
                int.TryParse(Textdata[0], out FirstCell);
                int.TryParse(Textdata[1], out SecondCell);
                int.TryParse(Textdata[2], out Sum);
              }

            else
                continue;

            if ( 0 < FirstCell && FirstCell <= 10000000)
            {
                if (0 < SecondCell && SecondCell <= 10000000)
                {
                    if (2 <= Sum && Sum <= 100000000)
                        etc = false;
                    else
                        continue;
                }
                else
                    continue;
             }
            else
                continue;
           }

        catch (ArgumentException e)
        {
            Console.WriteLine("Unable to add {0}", e.ToString());
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine("Unable to add {0}", e.ToString());
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("Unable to add {0}", e.ToString());
        }
       }

Firstly, this is a complicated bunch of code with a narrowly defined purpose.  On that basis it should be pulled out into a method. This would also allow a more elegant escape from the infinite loop, using return.

Secondly, even if it isn't in a method, some of those variables have narrow scopes and should be defined in their real scope rather than outside it. E.g. Textdata is not used outside the loop, so should be defined inside it.

Thirdly, the convention in C# is that local variables start with a lowercase letter, not an uppercase one.

Fourthly, the error handling is wrong. I tested this without supplying input (because a previous version of the question hardcoded the input and didn't require it to be supplied), and got an infinite loop outputting Unable to add System.NullReferenceException.

Fifthly, the input specification is essentially missing from the spec posted in the question, but I find the assumption that there will be exactly two starting cells to be unnecessarily restrictive. IMO the code could be simpler without that assumption.

         for (int i = 2; i < Sum; i++)
        {
            Result += (ulong)Cells[MinIndex];

            Cells[MinIndex] += 1;

            Cells.Insert(MinIndex + 1, Cells[MinIndex]);

            if (MinIndex + 1 != Cells.Count - 1)
            {
                if (Cells[MinIndex + 2] < Cells[MinIndex])
                    MinIndex = MinIndex + 2;
                else
                    MinIndex = 0;
            }
            else
                MinIndex = 0;
        }

Inserting into the middle of a List usually means that you're using the wrong data structure for the task. The right data structure for this approach would surely be a priority queue of some kind.

However, the approach can be optimised a lot. Consider input 1 1 67108864. Initially you have two 1s. After two generations you will have four 2s. After six generations you will have eight 3s. In general, if you have n of the smallest value G, and you still need n or more generations, you can replace all of them with 2n copies of G+1 at cost 2nG. So if you track generation and multiplicity you can go from executing the outer loop Sum - 2 times to roughly log(Sum) times, again using a priority queue. Work through the maths a bit more and you can make it a constant time calculation with no loops (assuming that you only have two cells in the starting state - if you adapt for an arbitrary number of cells as I suggested above, you need one loop).


Write input bytes to a file directly in Python3

Consider using any() for implementing validate_input_list and valid_chars


There is no universal rule and this particular decision is use-case specific. Note that there are other options as well, like returning -1 for an empty list.

If we consider that max() naturally does not work with empty sequences:

In [1]: max([])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-8d2766aecf92> in <module>()
----> 1 max([])

ValueError: max() arg is an empty sequence

Then, throwing an error makes more sense in this particular situation. If you do so, you can empower your docstring with a doctest:

def poker(hands):
    """
    Returns the best hand from a list of hands.

        Parameters:
            hands: list

        Example:
            poker(hands) => hands

    Raises a ValueError in case of empty list of hands:

    >>> poker([])
    Traceback (most recent call last):
      ...
    ValueError: Empty list of hands.
    """
    if not hands:
        raise ValueError("Empty list of hands.")

    return max(hands, key=hand_rank)


Auto-complete using Tries in Python with OOP

Bug
Put 'a' in word_list: it is not found by autocomplete('a'). This is because all_suffixes doesn't use the result variable when building the result in case the node has children.
Naming

The name self.flag tells nothing about the purpose of the variable. self.word_end would be better.
all_suffixes returns whole words, not suffixes. words_with_prefix would be a better name. Alternatively, the function could return suffixes only and adding the prefix would be the responsibility of autocomplete.

Other
Instead of using a set and reduce in all_suffixes, it would be simpler to use just a list and extend it in a loop. (There should be no duplicate words in the list anyway, because the trie does not store duplicates)
def words_with_prefix(self, prefix):
    results = []
    if self.word_end:
        results.append(prefix)
    for (char, node) in self.children.items():
        results.extend(node.all_suffixes(prefix + char))
    return results


Checking if an integer permutation is cyclic in Java

Here

int nextNumber = array[array[0]];
int visitedNumbers = 1;

while (nextNumber != array[0]) {
    nextNumber = array[nextNumber];
    visitedNumbers++;
}

you determine the length of the orbit starting array[0]. If you start at 0 instead then some array lookups are saved, and I find it easier to understand:

int nextNumber = array[0];
int visitedNumbers = 1;

while (nextNumber != 0) {
    nextNumber = array[nextNumber];
    visitedNumbers++;
}

And with a do-while loop the initial array lookup can be made part of the loop:

int currentNumber = 0;
int visitedNumbers = 0;

do {
    currentNumber = array[currentNumber];
    visitedNumbers++;
} while (currentNumber != 0);

Further suggestions:

Checking for duplicate array elements is not necessary if you limit the number of iterations:

int currentNumber = 0;
int visitedNumbers = 0;

do {
    currentNumber = array[currentNumber];
    visitedNumbers++;
} while (visitedNumbers <= array.length && currentNumber != 0);

This saves one array traversal and the additional storage in checkArrayElements(). The only downside is that calling the function with an invalid permutation now possibly returns false instead of throwing an error.

Similarly, the “bounds check” can be made directly in that loop. That might be viewed as a violation of the “separation of concerns” principle, but saves one array traversal.


Optimizing code for Project-Euler Problem #23

Your idea is perfectly fine (subtracting all sum of pairs from the candidates range), but I would write it differently:

xs = (1..28123)
abundants = xs.select(&:abundant?)
solution = (xs.to_set - abundants.repeated_combination(2).to_set { |x, y| x + y }).sum

With a similar idea, this is probably faster (but also a bit less declarative):

xs = (1..28123)
abundants = xs.select(&:abundant?).to_set
solution = xs.select { |x| abundants.none? { |a| abundants.include?(x - a) } }.sum


Your code is pretty good!  I have only one substantive and a few stylistic suggestion.

Style

Since sentence is a hard-coded variable, Python convention is that it should be in all-uppercase, i.e. SENTENCE is a better variable name.
What are u and n in your code?  It's hard to figure out what those variables mean.  Could you be more descriptive with your naming?
Your call to .lower() on sentence is hidden after the very long sentence.  For readability I wouldn't hide any function calls at the end of very long strings.
Python has multi-line string support using the """ delimiters.  Using it makes the sentence and the code more readable, although at the expense of introducing newline \n characters that would show up on the histogram if they are not removed.  In my code below I use the """ delimiter and remove the \n characters I introduced to break the string into screen-width-sized chunks.  PEP8 convention is that code lines shouldn't be more than about 80 characters long.
You should consider breaking this code up into two functions, one to make generate the data, and one to make the graph, but we can leave that for another time.

Substance

Since your sentence is a Python string (not a NumPy character array), you can generate the data for your histogram quite easily by using the Counter data type that is available in the collections module.  It's designed for exactly applications like this.  Doing so will let you avoid the complications of bin edges vs. bin centers that stem from using np.histogram entirely.

Putting all these ideas together:

import matplotlib.pyplot as plt
import numpy as np
from collections import Counter

SENTENCE = """Only the fool would take trouble to verify that his sentence was composed of ten a's, three b's, four c's,
four d's, forty-six e's, sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine l's, four m's, twenty-five n's,
twenty-four o's, five p's, sixteen r's, forty-one s's, thirty-seven t's, ten u's, eight v's, eight w's, four x's,
eleven y's, twenty-seven commas, twenty-three apostrophes, seven hyphens and, last but not least, a single !"""

# generate histogram
letters_hist = Counter(SENTENCE.lower().replace('\n', ''))
counts = letters_hist.values()
letters = letters_hist.keys()

# graph data
bar_x_locations = np.arange(len(counts))
plt.bar(bar_x_locations, counts, align = 'center')
plt.xticks(bar_x_locations, letters)
plt.grid()
plt.show()

Other

It wasn't anything you did with plt.xticks that led to the gaps.  That's the matplotlib default.  If you want a "tight" border to the graph, try adding a plt.xlim(-0.5, len(counts) - 0.5) before the plt.show().