I must admit this is pretty good code for someone that has just started, I like that you use the more "functional" style Javascript allow you to use . So good job :) But there are some design issues I see with the code.

1. Factory vs constructor

Your Validator has a make method which takes the rules in, It is basically used as a factory method (A factory is a design pattern if you are not familuar with it). But it has none of the benefits a factory gives you, since it is a instance method.

Having to instantiate a Validator object and then being forced to call make is cumbersome. Instead I suggest you make the make function static and add a constructor

class Validator
{
   static make(rules)
   {
        return new Validator(rules);
   }

   constructor(rules)
   {
       this.rules = rules;
   }
}

2. Checking class properties

You don't need to do this check in your valid function.

if (!this.hasOwnProperty('rules')) {
    return true;
}

Since it's practically not possible to not have rules with the proposed factory. I understand why this is here though. You wanted to make sure you can't forget the make call after instantiating a Validator object. But that's a wrong schematic. If the caller uses your code wrong it should fail, and not say "I don't care, but this is valid"

3. Naming

Methods should indicate that they are actions, and properties that they are values.

Your valid method sounds a lot like a property, like a value. I would call it validate since that is a verb and makes it clear that it does something and not "is" something. And I would rename the property valid that your return in your valid method to isValid

4. ES6

EDIT: I noticed to late that you already used an arrow function in your code. Ignore the explanation if you want and just replace the Object.keys().forEach(callback) callback with an arrow function. BTW you do not need the parentheses if you only have one parameter.

You can use a arrow function in your forEach(function) function. This is a es6 feature and a bit more advanced tho. Using functions is fine but it can solve the issue you have with scoping.

The function keyword does create a new scope and therefore changes the meaning of this. The arrow function on the other hand behaves exactly like a function but does not change the meaning of this

validate() {
    let errors = [];

    Object.keys(rules).forEach(key => {
        let formElement = document.getElementsByName(key)[0];

        if (formElement == undefined) {
            return;
        }

        let ruleSet = rules[key].split('|');

        ruleSet.forEach((rule) => {
            let result = this.checkRuleForElement(rule, formElement)

            if (!result.valid && result.message != undefined) {
                errors.push(result.message);
            }
        });
    });

    return {
        isValid: errors.length == 0,
        errors
    }
}

Another thing you can leave out is the
errors: errors part. You can shorten it to just errors since the name of the variable is the same as key of the object

5. Decouple things

Currently your "rule running" and "rule definitions" are all in the same class/method (in the switch in checkRuleForElement) So if you want to add a new rule you have to modify your Validator class which should only do one thing: Invoke the rules for a element. The rule definitions are a whole separate concern.

You can try to decouple it by using arrays.

A sample implementation may look like this:

// This is not good code, take it as an "idea" or psuedocode

class Validator
{
   static registeredRules = [];

   static registerRule(name, run)
   {
      Validator.registeredRules.push({ name, run });
   }

   checkRuleForElement(ruleName, formElement)
   {
      var rule = Validator.registeredRule.find(element => element.name === ruleName);
      return rule.run(formElement);
   }
}

6. Abstract things

A thing you may want to consider is that there may be multiple forms or multiple elements, with your current implementation you are relying on the fact that there are is a unique element foreach "rule". Also you are interacting with the Dom directly which makes things hard to change when that assumption changes.

You could solve this by, for example using Dom elements as an input:

Validator.make({
     document.querySelector("#user_input"): "required"
})

Bonus exercises

You can try to add a more advanced "rule parser" and add parameters for rules.

This could look like this:

Validator.make({
  "username": "required|min:5"
})

Another thing you could try is, skipping this whole "naming" thing and using just functions

For example

const required = element => element != undefined;

// If you do not understand this Syntax, it's basically a function that returns a function.
const min = count => element => element.length > count

Validator.make({
  "username": [required, min(5)]
});

This would give you several advantages. For example that your rules can be checked by a static analyzer, If you use strings there is always a chance you mistype something, like use "regired" instead of "required" and not even notice it, with functions on the other hand you will get an error if you use something that is undefined. Also you could reuse rules better.

Have fun :)

I wrote this from my mobile so if there are any mistakes let my know. I will most likely add more when I get my hands on a pc!


Variable scope

In order to make things easier to read/write, it is prefered to declare local variables as late as possible and in the smallest possible scope.

In your case, this holds for :

int numberOfTests = s.nextInt();

int l = s.nextInt();

int n = s.nextInt();

int pomoc = l / ((int) primeTable.get(i));

Also, BitSet primeBitSet can be declared just before the loop using it.

Continue

The way you use continue make things complicated for no obvious reasons.

            if (primeBitSet.get(j - 1) == true) {
                continue;
            } else {
                primeTable.add(j);
                for (int k = 2 * j; k <= n; k += j) {
                    primeBitSet.set(k - 1);
                }
            }

can be written :

            if (!primeBitSet.get(j - 1)) {
                primeTable.add(j);
                for (int k = 2 * j; k <= n; k += j) {
                    primeBitSet.set(k - 1);
                }
            }

New lines

The way you use new lines does not seem to make much sense. You should try to separate things into different "paragraphs".

After taking into accounts these comments about style, here's what the code would be like :

public class Main {

    public static void main(String[] args)throws IOException {
        Scanner s = new Scanner(System.in);
        int numberOfTests = s.nextInt();

        for (int q = 0; q < numberOfTests; q++) {
            int l = s.nextInt();
            int n = s.nextInt();
            if (l==1)l++;
            ArrayList <Integer> primeTable = new ArrayList <Integer>((int) Math.sqrt(n));
            if (l < 1 || n < 1 || l > n || n > 1000000000) {
                System.exit(0);
            }

            //classic sieve from 1 to sqrt(n)
            BitSet primeBitSet = new BitSet((int) (Math.sqrt(n) + 1));
            for (int j = 2; j * j <= n; j++) {
                if (!primeBitSet.get(j - 1)) {
                    primeTable.add(j);
                    for (int k = 2 * j; k <= n; k += j) {
                        primeBitSet.set(k - 1);
                    }
                }
            }

            //sieve in the expected range using primes generated by the classic sieve
            BitSet primesInRangeBitSet = new BitSet(n - l + 1);
            for (int i = 0; i < primeTable.size(); ++i) {
                int pomoc = (l / ((int) primeTable.get(i))) * ((int) primeTable.get(i));
                for (int j = pomoc; j <= n; j = j + (int) primeTable.get(i)) {
                    if (j >= l && !primesInRangeBitSet.get(j - l)) {
                        primesInRangeBitSet.set(j - l);
                    }
                }
            }

            //outputting the primes
            for (int k = 0; k < primeTable.size(); k++){
                if((int)primeTable.get(k)>= l &&(int) primeTable.get(k) <= n)
                    System.out.println(primeTable.get(k));
            }
            for (int k = 0; k < primesInRangeBitSet.size(); k++) {
                if (primesInRangeBitSet.get(k) == false && k <= n - l ) {
                    System.out.println((k + l));
                }
            }
            System.out.println("");
        }
    }
}

Algorithm

Now, this being said, there is a much bigger issue here. If tou want to implement Sieve of Eratosthene properly, everything you need is just a BitSet of size 1.
If you really want to (but I don't really see the point), you can add primes numbers in a list as you detect them. If you just need to print them, you can print them as you detect them. In any case, I guess that from a performance point of view, it is not such a big deal to reiterate over the whole BitSet looking from prime numbers.


Iterating through list and calling method with different parameters for each item

The second parameter has the same value twice (query1) the first parameter also has the same value twice ("connectionstring1"), this means you can remove 1 if statement if you create 2 variables with initial values like this:

foreach (var environment in Environments)
{
    string connectionString = "connectionstring1";
    var query = query1;
    if (environment == "environment2")
    {
        query = query2;
    }
    else if (environment == "environment3")
    {
        connectionString = "connectionstring2";
    }
    FillList(connectionString, query);
}

Another option would be to add Dictionary<string, Action> which will allow you to easily map string -> method call like this:

Dictionary<string, Action> dictionary = new Dictionary<string, Action>
{
    ["environment1"] = () => FillList("connectionstring1", query1),
    ["environment2"] = () => FillList("connectionstring1", query2),
    ["environment3"] = () => FillList("connectionstring2", query1)
};
foreach (var environment in Environments)
{
    dictionary[environment].Invoke();
}


Solution for kth row of Pascal's triangle for a job interview

For one thing, the inconsistency with whitespace use and curly brace placing may demonstrate a lack of attention to detail.  Before you attack the actual problem, make sure your code is written cleanly.

This:

for(int i=0;i<=rowIndex;i++)

should use some whitespace:

for (int i = 0; i <= rowIndex; i++)

You already do this in other places, and it should be done everywhere.

Also, this:

for(int i=0;i<=rowIndex;i++)
{sol=C(rowIndex,i);
v.push_back(sol);}

looks a bit sloppy and is harder to read.  Again, use more whitespace, but also separate the loop body from the curly braces.

for (int i = 0; i <= rowIndex; i++) {
    sol = C(rowIndex, i);
    v.push_back(sol);
}


Project Euler # 56 Powerful digit sum in Python

Very nice code! Here are a few small comments, most of which are not something you have to change but rather food for thoughts as you learn more.

Although this is a matter of personal style, I would turn around your docstrings so what is returned comes first, if possible.

I.e. I would write

"""Generates all numbers of the form `a ** b` for `a, b < n`."""
"""Return the sum of digits of the number `n`."""
"""Return the max sum of the digits of all numbers of the form `a ** b` for `a, b < n`."""

If a generator expression is the only argument to a function, one pair of () can be omitted:

return max(get_digit_sum(num) for num in get_powers(n))

Although sometimes discouraged, if you need those last 10% of speed, this is slightly faster since int is a built-in function implemented in C:

def get_digit_sum(n):
    return sum(map(int, str(n)))

Nested for loops can be replaced with itertools.product, although here it is arguably harder to read instead of easier. For high levels of nestedness it can help increase readability, though.

from itertools import product

def get_powers(n):
    for num, power in product(range(n), range(n)):
        yield num ** power


Want to know vulnerabilities in below program finding minimum positive number greater than 0 that doesn't occur in array

At first glance, your code looks quite verbose. Seeing as it was an assignment for some type of class, I'm also assuming that points would've been deducted for you doing something that is considered bad practice. With this in mind, let's go through the code:

    int i=0, j=0, k=0;
    int result = 1, tmp = 0;

    for(i=0; i < N; i++) {
        for(j=i+1; j < N; j++) {
            if(A[j] < A[i]) {
                tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
            }
        }
    }

    for (i = 0; i < N; i++) {
        printf("%d\n", A[i]);
    }

In C99, declaring all variables at the start of the function isn't required. Variables like i, j, and k should be block scoped.

You're also sorting your array in a function that is called solution. The name isn't very descriptive, and given how that function returns an integer, I wouldn't expect it to actually change the array I'm passing.

Your solution function has a single point of return. That's fine, if that's what you were asked to do. However, generally speaking, most people prefer to return early. It simplifies the code, and reduces the total number of else's quite a lot.

You're missing some checks. An array, once passed to a function, decays into a pointer. I'd write the function as int solution(int *in, int size), and if I wanted to be paranoid about safety, I'd check for in == NULL and make sure size is non-negative. Then again, the size of the array is obtained through the sizeof operator, which actually yields a value of type size_t. Perhaps it makes sense to change your function argument to accept a size_t instead of an int? size_t is unsigned, so no need to check for negative values there...

You're sorting the array in ascending order. Understandable, of course, but why aren't you using qsort? It's better practice to write functions that only do 1 thing. Your solution function handles sorting, prints some debug output, and then sets about searching the lowest missing positive integer. Let's assume, for now, that changing the array that's being passed is not an issue, I'd break things up into 2 functions and write this:

static
int sort_ascending(const void *a, const void *b) {
    int av = *(int *)a, bv = *(int *)b;

    if (av == bv)
        return 0;
    if (av > bv)
        return 1;
    return -1;
}

static
int get_missing(int *in, size_t size) {
    // let's make sure the pointer can be dereferenced:
    if (in == NULL)
        return -1; // -1 is a common error value to return
    // first, sort the array
    qsort(in, size, sizeof *in, sort_ascending);

    // now let's just iterate over the array and find the answer
    // note, we're iterating until the NEXT TO LAST element, because we access in[i+1] in the body
    for (int i = 0; i < size-1; i++) {
        int v = in[i]+1; // the lowest possible value based on in[i]
        // if v is positive, and smaller than the next value in the array
        // we're done, and we can return
        if (v > 0 && v < in[i+1])
            return v;
    }
    // we didn't return from the loop. The lowest value is in[size-1]+1, if it's positive:
    int last = in[size-1]+1;
    if (last > 0)
        return last;
    // the highest value in the array was still negative, so the lowest positive missing value is 1
    return 1;
}

The last bit (getting the last value from the input, adding 1 and returning) is something that I'd probably leave at the end, but some might choose to perform this check before iterating the array. If the last (highest) value in the array is still negative, the loop is just a waste of time. The function then would look like this:

static
int get_missing(int *int, size_t size) {
    if (in == NULL || size == 0)
        return -1;
    qsort(in, size, sizeof *in, sort_ascending);

    if (in[size-1] <= 0) // highest value is 0 or less
        return 1;

    for (int i = 0; i < size -1; i++) {
        int v = in[i]+1;
        if (v > 0 && v < in[i+1])
            return v;
    }
}

As you can see, the function is a lot smaller, and fairly easy to read. The thing I don't like about checking the last element in the array before iterating is that it means the last return in the function is kind of "hidden" in a loop body. That may be personal preference, and if the input array is potentially huge, it's likely to be more efficient to preform that check. Then again, using qsort_r and passing in a pointer to an int allows you to count the number of negative values in the array, and that way you can start the iteration at the correct offset right away, but that's premature optimization. Let's get back to the matter at hand.

What was changed:

So far, we've changed:

Sorting separated out in a separate function, and using qsort rather than a nested loop
Checking for zero and NULL array
Returning early
Have error values returned in case the input is invalid (a -1)

What we still haven't addressed is the side-effect your function has. The input array is altered. This is considered bad practice (unless it's well documented, and is done for a clear reason). The way I'd solve it is by creating a copy:

static
int get_missing(const int *in, size_t size) {
    if (in == NULL || size == 0)
       return -1;
    // allocate memory for copy of input array
    int *temp = malloc(size * sizeof *in);
    if (temp == NULL)
        return -1;
    // copy the array
    memcpy(temp, in, size * sizeof *temp);

    // from here on, we use the copy
    qsort(temp, size, sizeof *temp, sort_ascending);
    if (temp[size-1] <= 0) {
        free(temp); // free memory
        return 1;
    }

    for (int i = 0; i < size -1; i++) {
        int v = temp[i]+1;
        if (v > 0 && v < temp[i+1]) {
            free(temp);
            return v;
        }
    }
}

Now if we do something like:

int main( void ) {
    int arr[] = int a[] = {1,3,6,4,1,2};
    int ret = get_missing(arr, ARRAY_SIZE(arr));
    for (int i=0; i < ARRAY_SIZE(arr); i++)
        printf("arr[%d] = %d\n", i, arr[i]);
    printf("Lowest positive int not in arr is %d\n", ret);
    return 0;
}

You'll see that the original array was not altered. The get_missing function now also communicates that clearly to:

int get_missing(const int *in, size_t size);

Looking at this, I know right away this function will return an int, accepts a pointer (decayed array), and will not change the argument (as it's const). I am expected to pass in a size value, which cannot be negative.

Putting it all together:

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

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))

static
int sort_callback(const void* a, const void* b) {
    int av = *((int *)a), bv = *(int *)b;

    if (av == bv)
        return 0;
    if (av < bv)
        return -1;
    return 1;
}

static
int get_missing_sideeffect(int *arr, int size) {
    qsort(arr, size, sizeof *arr, sort_callback);

    for (int i = 0; i < size-1; i++) {
        int next = arr[i] +1;
        if (next > 0 && arr[i+1] > next)
            return next;
    }

    int last = arr[size-1];
    if (last <= 0)
        last = 0;

    return last+1;
}

static
int get_missing(const int *in, size_t size) {
    if (in == NULL || size == 0)
       return -1;

    int *temp = malloc(size * sizeof *in);
    if (temp == NULL)
        return -1;

    memcpy(temp, in, size * sizeof *in);

    qsort(temp, size, sizeof *temp, sort_callback);
    if (temp[size-1] <= 0) {
        free(temp);
        return 1;
    }

    for (int i = 0; i < size -1; i++) {
        int v = temp[i]+1;
        if (v > 0 && v < temp[i+1]) {
            free(temp);
            return v;
        }
    }
}

int main(void) {
    int a[] = {1,3,6,4,1,2};
    int ret1 = get_missing(a, ARRAY_SIZE(a));
    // prints out a unchanged
    for (int i = 0; i < ARRAY_SIZE(a); i++)
        printf("a[%d] = %d\n", i, a[i]);
    int ret2 = get_missing_sideeffect(a, ARRAY_SIZE(a));

    printf("Smallest positive integer: %d -> %d\n", ret1, ret2);

    // shows a was changed due to side-effect
    for (int i = 0; i < ARRAY_SIZE(a); i++)
        printf("a[%d] = %d\n", i, a[i]);

    return 0;
}

As chux correctly pointed out: the version I posted here could've resulted in integer overflow. To fix this problem, it's a simple matter of returning 0 to indicate an error, and an unsigned int in all other cases (if the input has all ints up to (and including) INT_MAX).

Another issue I've realised is that the code wouldn't return a value like 1, if the input looked something like {2, 3, 4, 5}, whereas clearly, the smallest positive int missing from the array is 1. For these reasons, I'll write a final version of get_missing here:

static
unsigned int get_missing(const int *in, size_t size) {
    if (in == NULL || size == 0)
       return 0;

    int *temp = malloc(size * sizeof *in);
    if (temp == NULL)
        return 0;

    memcpy(temp, in, size * sizeof *in);

    qsort(temp, size, sizeof *temp, sort_callback);

    // lowest value in temp > 1, or highest value is zero or less
    if (temp[0] > 1 || temp[size-1] <= 0) {
        free(temp);
        return 1;
    }

    unsigned int v = 0;
    for (int i = 0; i < size -1; i++) {
        v = temp[i]+1u;
        if (v > 0 && v < temp[i+1]) {
            free(temp);
            return v;
        }
    }
    return v;
}

So I've added the check to make sure we return 1 if the input starts with 2 or more. I've changed the function to return an unsigned int (which means you have to print the output using printf("Return value %ud\n", ret);). Lastly, I'm also declaring v outside of the for loop. The last return statement won't ever be reached, but when I compiled the code in its original form (gcc -std=c99 main.c -o missing -Wall), the compiler spits out a warning.


Random Number Guessing Game Code Efficiency - Python

I'm not exactly sure what you're asking but with my best guess, I'll give it a try.
What you should be turning into functions (in my opinon)

"bad" inputs (such as 'a', 'b' etc. or '%', '*' etc.); error trapping algorithm chunk
of code into a function.

"You're hot on the trail" etc.) block of code can also be converted
to a function.

My biggest concern with your program is the following:
if text != "yes":  then  play = False - Why just "yes"?? Why not "yes" and "Yes"?
What if the user inputs "Yes" - with a capital "Y" instead of "yes" - with a lower-case "y"? (I tried this by the way, and this was the output: "Ok, thank you for playing!"). For them (the user) they're indicating that they want to have another try at the game, but due to your code's incompetence for a variety of options (like "Yes" or "yes" - for replaying, "No" or "no" - for NOT replaying). Please solve this problem.
Now to your more imperative problem (the functions), I can give it a shot.
Note: You should aim for maximum clarity if you want your code to be re-used by others, or to make it easier to read and understand (not just for others but for you as well!).
if guess > 10 * difficulty or guess < 1:
                print("That's an invalid input, please re-enter your number.")
                # ⬆ this particular line!! ⬆
                continue
            break

You didn't specify WHY the input is invalid, you stated the obvious by saying "It's an invalid input"...be concise and again, aim for MAXIMUM clarity.
Note: I did abbreviate some of the variable/function names just for saving time.
Anyway, here's how I would've done this:
import random

#variables:
sc = 0
pl = True

# "bad" input loop function.
def get_num(diff):

    while True:
        try:
            gs = int(input("Guess what number I am thinking of  "))
        except:
            print("Please enter a NUMBER. Letters (a, b...) and symbols (#, %...) are not appropriate vales.")
            continue

        if gs > 10 * diff or gs < 1:
            print("Your number is not in the right range, please re-enter your number!")
            continue
        return gs

# "hot and cold" function
def temp_func(gs, num):

    if gs == num:
        print("CORRECT!")
        return True
    elif abs(gs - num) == 1:
        print("HOT!")
        return False
    elif abs(gs - num) <= 3:
        print("WARM")
        return False
    else:
        print("COLD!")
        return False

while pl:
    while True:
        try:
            diff = int(input("Give me a number between 1 and 3 "
                                   "(these are the difficulty levels) \n\n 1 = easy \n 2 = medium \n 3 = hard \n\n"))
        except:
            print("This is not a number!")
            continue

        if diff > 3 or diff < 1:
            print("That's an invalid input, please re-enter your number")
            continue
        break

    num = random.randint(1, 10 * diff)

    attmp = 0
    gs = 0

    while gs != num and attmp < 3:
        attmp += 1
        print("attempt number " + str(attmp))

        gs = get_num(diff)

        did_win = temp_func(gs, num)
        if did_win:
            sc += 1
            break

    if attmp == 3 and gs != num:
        print("Oops! You've run out of guesses!")
        print("The number I was thinking of was " + str(num) + ".")

    print("Your final score is " + str(sc))

    txt = input("If you want to play again, type 'yes' ")
    if txt != "yes":
        pl = False
        print("TYPE GOODBYE MESSAGE HERE")


Cleaning up complex if statements for Chess game

You can enhance the readability by extracting the conditons of your ifs to functions without chanceing the performance. Plus you can remove your duplicate code like positon.x +1 < 8


Usually when we do something similar we use a repository (pattern). It allows us to encapsulate the entire interaction with the database so that we don't have to think about the queries again and again.

For example:

class MyDatabase
{
    public MyDatabase(string connectionString = null)
    {
        // use the specified or the default connection string
        ConnectionString = connectionString ?? @"Server=PC\SQLEXPRESS;Database=example;User=sa;Pwd=example;";
    }

    public string ConnectionString { get; private set; }

    public int GetStringID(string stringValue)
    {
        // here comes the select and connection manintenance
    }
}

When working with database objects you should always use the using statement to free the resources. Always check the documentaiton if something implements the IDisposable interface.

Your actual code should look like this:

using(var sqlConnection = new SqlConnection(ConnectionString))
{
    // work with the connection where
}

There are few more types that are disposable too (i.e. the SqlCommand or the SqlDataReader).

With the repository your button1_Click could look like this:

private void button1_Click(object sender, EventArgs e)
{
    var db = new MyDatabase();
    StringID = db.GetStringID(textBox1.Text);
}

Naming

Even when working with the simplest projects you should always use meaningful names and button1 or textBox1 are really bad. I don't know what the button1 does but the text-box could be named stringValueTextBox or the textBox2 should be called linkTextBox etc.


Function that takes an array of integers and returns that array rotated to the right N components

The obvious solution

Not sure if you know the obvious solution and just want to re-invent the wheel or if you are just not aware of this but you could just do :

>>> l = [1, 2, 3, 4, 5, 6]
>>> n = 2
>>> l[-n:] + l[:-n]
[5, 6, 1, 2, 3, 4]

The actual review : details

You have split your code into multiple functions, documented them, and written the usual if __name-- == 'main': test : this is already a pretty good beginning.

Also, pep8 only complies about some whitespace not following the Python Style Guide (this is worth fixing it anyway).

However, here a few things that do not look good in your code and could easily be fixed :

your code can be python 3 compliant by adding parentheses in your calls to print.
you have the same typo rorate in multiple places
list is a bad name for a list as you can easily mix-up with the type
your function and variable names do not follow the convention.

After fixing all this, you get something like :

def copy_digit(lst, index, item):
    """
            Copy the item to the indexed location in the given list
    """
    lst[index] = item
    return lst

def rotate_list(lst, nb_rotate):
    """
            Rotate List to right
    """
    print("Function received {0},{1}".format(lst, nb_rotate))
    for rotate in range(N):
        last_item = lst[-1]
        for i in range(len(lst) - 2, -1, -1):
            item_to_shift = lst[i]
            lst = copy_digit(lst, i + 1, item_to_shift)
        lst[0] = last_item
    print("Rotate once: {0}".format(lst))
    return lst

if __name__ == '__main__':
    """
       This program will rotate right the given list N no of times
    """

    array = [1, 2, 3, 4, 5, 6]
    N = 2
    print("Rotate an array: ", array, "No of times: ", N)
    final_list = rotate_list(array, N)
    print("Rotated List: ", final_list)

A subtle bug

What if I was to call :

final_list = rotate_list(array, 2)

? Surprisingly enough, I'd get an error. I'll let you have a look at this because it is not very complicated.

Clearer interface for your functions

Your function copy_digit updates the list and returns it. There is no real need for this as the caller would already have the initial list. Then you can just have :

def copy_digit(lst, index, item):
    """
            Copy the item to the indexed location in the given list
    """
    lst[index] = item

and

...
copy_digit(lst, i + 1, item_to_shift)
...

Of course, the need for a function seems a bit doubtful here. Let's inline this :

...
lst[i + 1] = item_to_shift
...

Then, it seems like the item_to_shift variable is not really required anymore :

for i in range(len(lst) - 2, -1, -1):
    lst[i + 1] = lst[i]

And more generally

In Programming Pearls (sorry I couldn't find the relevant full text), Jon Bentley describes different solutions to the problem. Some are quite original and actually very easy to implement on top of being efficient. I'll let you google "programming pearls rotate" if you want to read more about this. It is definitely worth a read (and the whole book is too).


Efficient way to remove duplicate strings after adding their key values

Avoid using namespace std;

Importing all names of a namespace is a bad habit to get into, and can cause surprise when names like begin and size are in the global namespace.  Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope.

The exceptions to this rule are namespaces explicitly intended to be imported wholesale, such as the std::literals namespaces.

Avoid preprocessor macros

If you want a shorter name for a type, it's much safer to write

using ull = unsigned long long;

Personally, I'd give it a name that reflects what I want to use it for, rather than what it (currently) is.

Improve naming

What's the significance of vec as a name?  It's confusingly similar to vector, but it's used as an element of a vector.  Similarly, its members s and e convey nothing - consider name and count, if that's what they represent.

Simplify the logic

It's a lot easier to accumulate counts if you introduce a std::map to hold the sums:

std::map<std::string,ull> accumulator;
for (auto const& element: v)
    accumulator[element.s] += element.e;

// write them back into the vector
v.clear();
for (auto const& element: accumulator)
    v.push_back(vec{element.first, element.second});


ThreadManager.h

What is Task.h? Why are you including it? I see no names that aren't covered by the standard headers you include.

There's no apparent order to your private members. You mix methods and data members; it looks like the members are added in the order they were written, as opposed to some logical order. I recommend putting your methods before your data members (my recommendation matches the Google C++ Style Guide), and determining a logical order within each set.

In general, the header is the place to document your interface. What are the semantics of ScheduleTask? Can it be called from multiple threads without mutual exclusion? Will Run return? Does ThreadPoolExecutor reuse threads after there work is complete? If so, will ThreadPoolExecutor ever destroy threads after creating them? Does the destructor block?

Worker is an odd name for a method. It is the usual practice that function names should be some sort of verb phrase; Worker is a noun, and it doesn't give a lot of insight into what it does.

maxWorkers should probably be declared const; it shouldn't change after construction.

Comments on the private data members should clearly indicate which members are guarded by the mutex.

ThreadManager.cpp

Constructors should use initializers wherever possible:

ThreadPoolExecutor::ThreadPoolExecutor(int maxWorkers) : maxWorkers(maxWorkers) {}

This will allow the member to be declared const.

Your destructor throws if Run has never been called: A default constructed thread is not joinable. That's not the biggest problem: Your destructor never returns if maxWorkers > 0 because none of your calls to join ever complete.

It is distracting (and unidiomatic!) to see unnecessary this-> warts prepended to each member access. If you must have a visual indicator that you are accessing members rather than local variables, adopt a naming convention for your data members (common ones I've seen: maxWorkers_, m_maxWorkers).

In ScheduleTask, it is unnecessary to call lock.unlock();. std::unique_lock unlocks its owned mutex in its destructor; when I see explicit unlocking, I expect that it's because of complicated locking semantics (e.g. conditional unlocking, or unlocking before lock goes out of scope, as in Worker) and look around for the complication; there's no such complication here.

maxWorkers appears to be a misnomer as you never have fewer workers. Maybe numWorkers?


Searching for categories and storing them

There are two pairs of loops that are the same and can be combined like this:

int charCount = 0;
List<string> categories = new List<string>();
for (int j = 0; j < dgv.RowCount; j++)
{
    charCount += (int)dgv.Rows[j].Cells[4].Value;

    // look at every category in the dgv and see if we have a unique value in a container
    List<string> result = categories.FindAll(
        delegate(string b)
        {
            return b == dgv.Rows[j].Cells[1].Value.ToString();
        }
    );
    // if we don't have a unique ID then add it
    if (result.Count == 0)
    {
        categories.Add(dgv.Rows[j].Cells[1].Value.ToString());
    }
}

treeView1.Nodes.Add(languageTabs.TabPages[i].Text.ToUpper() + " Statistics");
treeView1.Nodes[i].Nodes.Add("Total Number Of Strings: " + dgv.RowCount); // might need to remove '--' from count
treeView1.Nodes[i].Nodes.Add("Total Number Of Chars: " + charCount);
treeView1.Nodes[i].Nodes.Add("Total Number Of Strings and Chars per Category: ");

int[] categoryCount = new int[categories.Count];
int count = 0;
foreach (string cat in categories)
{
    for (int j = 0; j < dgv.RowCount; j++)
    {
        if (dgv.Rows[j].Cells[1].Value.ToString() == cat)
        {
            categoryCount[count]++;
        }
    }

    treeView1.Nodes[i].Nodes[2].Nodes.Add(cat + ":   " + categoryCount[count].ToString());
    count++;
}

Note that the categoryCount array is no longer ncessary, and add Saeed's answer and you get:

int charCount = 0;
List<string> categories = new List<string>();
for (int j = 0; j < dgv.RowCount; j++)
{
    charCount += (int)dgv.Rows[j].Cells[4].Value;

    if (!categories.Any(x=>x == dgv.Rows[j].Cells[1].Value.ToString()))
        categories.Add(dgv.Rows[j].Cells[1].Value.ToString());
}

treeView1.Nodes.Add(languageTabs.TabPages[i].Text.ToUpper() + " Statistics");
treeView1.Nodes[i].Nodes.Add("Total Number Of Strings: " + dgv.RowCount); // might need to remove '--' from count
treeView1.Nodes[i].Nodes.Add("Total Number Of Chars: " + charCount);
treeView1.Nodes[i].Nodes.Add("Total Number Of Strings and Chars per Category: ");

foreach (string cat in categories)
{
    int count = 0;
    for (int j = 0; j < dgv.RowCount; j++)
    {
        if (dgv.Rows[j].Cells[1].Value.ToString() == cat)
        {
            count++;
        }
    }

    treeView1.Nodes[i].Nodes[2].Nodes.Add(cat + ":   " + count.ToString());
}

Then, assuming that dgv.Rows implements IEnumerable you can do this to the second loop:

foreach (string cat in categories)
{
    int count = dgv.Rows.Where(r => r.Cells[1].Value.ToString() == cat).Count();
    treeView1.Nodes[i].Nodes[2].Nodes.Add(cat + ":   " + count.ToString());
}


Find if cookie name exists in the cookie string

Option 1: Same functionality, smaller size

  Can I reduce the code in a better way more optimised?

If you want to optimize for size, then here's a suggestion for a more compact version:

function checkCookie(cookies, name) {
    return (cookies || '')
        .split(/;\s*/)
        .some(cookie => cookie.split('=', 1)[0] === name)
}

(cookies || '') produces the same function result as the original if(…) return false
split uses a regular expression that matches the space after the semicolon, saving the trim in the lines below
the assignments for eachCookie and res can be removed, leading to a single line some call

Benefits: short & concise

Limitations: only checks for existence of a cookie, not its value

Option 2: More versatility, similar size

There is an opportunity for a different design that allows for more generic use cases: you can first parse the cookie string into a plain object and then check for the existence of the cookie in question.

function parseCookie(cookie) {
    return (cookie || '')
        .split(/;\s*/)
        .reduce((result, entry) => {
            const [key, value] = entry.split('=', 2)
            result[key] = value
            return result
        }, {})
}

function checkCookie(cookies, name) {
    return Boolean(parseCookie(cookie)[name])
}

Granted, this a solution may be a bit "slower" than the original implementation. This shouldn't be an actual issue unless you intend to parse millions of cookie strings and time is a constraint.

What you gain in return though is a lean, readable, reusable function that lets you check for the existence of a cookie and in addition can also return the cookie’s value.

Benefits: check for cookie existence and get values; faster than original solution when checking multiple cookies

Limitations: no savings in size

Option 3: Universal key-value parser, a bit larger

The above solution is based on code that I use to parse URL query strings. Both cookie- and query strings are key-value pairs, except cookies use a semicolon ; as a separator, while query strings use an ampersand &. If we adapt our function to accept the separator and equals sign as (optional) parameters, we can parse query strings and cookies with the same function:

function parseValues(cookie, sep, eq) {
    sep = sep || /;\s*/
    eq = eq || '='

    return (cookie || '')
        .split(sep)
        .reduce((result, entry) => {
            const [key, value] = entry.split(eq, 2)
            result[key] = decodeURIComponent(value)
            return result
        }, {})
}

function parseCookies(cookies) {
    return parseValues(cookies)
}

function parseQuery(query) {
    return parseValues(query, '&')
}

function checkCookie(cookies, name) {
    return Boolean(parseCookie(cookie)[name])
}

Option 4: Consider using libraries

I understand that you wanted to write your own function as opposed to introducing cookie-parser, which does a lot more than what you actually need - especially signing & signature verification - and is thus larger in size than what you aim for.

Other options would be cookie or lightcookie, which are smaller in size and might be a good choice over writing your own function.

const lightcookie = require('lightcookie')

function checkCookie(cookies, name) {
    return Boolean(lightcookie.parse(cookies)[name])
}

Benefits: save time; avoid mistakes; benfit from tested & verified code

Limitations: can be larger than what you are willing or able to include


Using the unicodeScalars view of the Swift String is a good start,
but the code can be simplified:

There is no need to create an array first, you can call map
directly on the unicodeScalars collection.
The conversion to Character is not needed, the array of shifted
unicode scalars can be converted directly back to a string
(attribution to this answer on Stack Overflow).

Also the variable name unicodePoints is misleading, because that
is an array of Character in your code.

Your method then becomes

func encrypt(message: String, shift: Int) -> String {
    let unicodeScalars = message.unicodeScalars.map { UnicodeScalar(Int($0.value) + shift)! }
    return String(String.UnicodeScalarView(unicodeScalars))
}

However, this is probably not yet what you want. Example:

let message = "Attack at dawn"
print(encrypt(message: message, shift: 2))    // Cvvcem"cv"fcyp
print(encrypt(message: message, shift: 10))   // K~~kmu*k~*nkx

All characters are shifted by the given amount so that a space
becomes a quotation mark, and some letters are transformed to non-letters. Also

print(encrypt(message: message, shift: -100))

crashes at runtime, because the unicode scalar value is shifted to
an invalid value.

The traditional Caesar Cipher transforms only letters in the range
A...Z, and rotates them, so that shifting "Z" by 2 becomes "B".
Lowercase letters can be transformed to uppercase, but other characters
are usually ignored (either removed or left unchanged).

Here is a possible implementation with an inner function
shiftLetter() which transforms a single letter.
This inner function is used as argument in

msg.unicodeScalars.map(shiftLetter)

to transform the entire String:

func encrypt(message: String, shift: Int) -> String {

    func shiftLetter(ucs: UnicodeScalar) -> UnicodeScalar {
        let firstLetter = Int(UnicodeScalar("A").value)
        let lastLetter = Int(UnicodeScalar("Z").value)
        let letterCount = lastLetter - firstLetter + 1

        let value = Int(ucs.value)
        switch value {
        case firstLetter...lastLetter:
            // Offset relative to first letter:
            var offset = value - firstLetter
            // Apply shift amount (can be positive or negative):
            offset += shift
            // Transform back to the range firstLetter...lastLetter:
            offset = (offset % letterCount + letterCount) % letterCount
            // Return corresponding character:
            return UnicodeScalar(firstLetter + offset)!
        default:
            // Not in the range A...Z, leave unchanged:
            return ucs
        }
    }

    let msg = message.uppercased()
    return String(String.UnicodeScalarView(msg.unicodeScalars.map(shiftLetter)))
}

Examples:

let message = "Attack at dawn"
print(encrypt(message: message, shift: 2))    // CVVCEM CV FCYP
print(encrypt(message: message, shift: 10))   // KDDKMU KD NKGX
print(encrypt(message: message, shift: -100)) // EXXEGO EX HEAR


I can't see how tail recursion comes into the picture exactly, but I would start with putting a stop watch around the do that populates the cache and checking how much work it actually needs to do, just to see whether you couldn't get away with what you have now. There's certainly some value in computing only the part of the curve you need, but I'd check how much that would gain you before making that code more complicated.

For starters, you certainly don't need let bindings for end_date and points. You already have them accessible anywhere within your type as they're constructor arguments. You can also drop the {} and seq {} in you for ... in ... do expressions.

A quick and simple way to delay populating of the cache until it's needed is to make it lazy.

let cache =
     Lazy.Create <| fun () ->
        let cache = Array.zeroCreate ((end_date - start_date).Days + 1)
        (* the entirety of your 'do' goes here *)
        cache

interface IDiscountCurve with
    member this.Df(date) =
        cache.Value.[(date - start_date).Days]

This way it will only be populated once Df is called, and no work would be done on object's construction.


Compare two columns in an Excel spreadsheet

I'm sure you can further optimize the code, but this will definitely run faster.

It will run faster for a number of reasons, firstly I've combined one of your loops so you only have two For Loops, the second reason is that the code won't be looking at every cell in the worksheet, but it will find the last row with data and loop until then:

Sub compare()
    Dim ListA As Range
    Dim ListB As Range
    Dim c As Range
    Call Unprotect

    ListARange = Cells(Rows.Count, "A").End(xlUp).Row 'find the last row with data on column A
    ListBRange = Cells(Rows.Count, "B").End(xlUp).Row 'find the last row with data on column B

    Set ListA = Range("A2:A" & ListARange) 'set your range only until the last row with data
    Set ListB = Range("B2:B" & ListBRange)
    Application.ScreenUpdating = False

    Range("C1").Value = "Files in A that are NOT in B"
    Range("D1").Value = "Files in B that are Not in A"
    Range("E1").Value = "Matching Files"

    For Each c In ListA
        If Application.CountIf(ListB, c) = 0 Then
            Cells(Cells(Rows.Count, "C").End(xlUp).Row + 1, "C").Value = c
        ElseIf Application.CountIf(ListB, c) >= 1 Then
            Cells(Cells(Rows.Count, "E").End(xlUp).Row + 1, "E").Value = c
        End If
    Next c

    For Each c In ListB
        If Application.CountIf(ListA, c) = 0 Then Cells(Cells(Rows.Count, "D").End(xlUp).Row + 1, "D").Value = c
    Next c

    Application.ScreenUpdating = True

    Call Protect
End Sub


Checking if 3 numbers are an arithmetic progression

The requirements are that (1) b - a == c - b and that (2) a < b < c, except when equalOk is true, in which case (3) a <= b <= c. If (1) is true, then it is sufficient to just check a < b for (2) and a <= b for (3).

private bool InOrderEqual(int a, int b, int c, bool equalOk) {
    if (b - a != c - b) return false; // (1)
    if (equalOk) return a <= b; // (3)
    return a < b; // (2)
}

Originally, equidistance was not an explicit requirement.

Original answer:

The requirements are that a < b < c, except when equalOk is true, in which case a <= b <= c. There's no need for anything more complex than this:

private bool InOrderEqual(int a, int b, int c, bool equalOk) {
    if (equalOk) return a <= b && b <= c;
    return a < b && b < c;
}


Count all possible attendance records with length n, which will be regarded as rewardable

First of all, java doesn't like deep recursive calls. I tried running the following mini program on my machine and it only went up to 11398 before ending with a stackoverflow:

public static void main(String[] args) throws Exception {
    recurseTest(0);
}

public static void recurseTest(int n){
    System.out.println(n);
    recurseTest(n+1);
}

Notice that this only stores an int each call.

So you're better of calculating everything in a for loop instead.

It would be nice if we could do a single pass over the entire record choosing which letter to add at that step and update our total (+ helper totals). That way we don't even need to consider memoisation.

Let's look at which totals we want to keep track of to calculate the correct result.

First we have the requirement that the entire string can only have at most 1 letter A. So I would keep track of 2 groups of totals. Those that don't have an A yet. And those that do.

Next we must ensure that we can have at most 2 consecutive Ls. So let's keep track of how many L's are in the end at the previous step.

This leads to the following 6 variables.

long noA0;
long noA1;
long noA2;
long a0;
long a1;
long a2;

where noAx means it doesn't contain an A yet and ends with x letters L.

Here's what we would like to write in each step to update to the new values:

noA0 = noA0 + noA1 + noA2; //added P to any of the previous noA's
noA1 = noA0;
noA2 = noA1;
a0 = noA0 + noA1 + noA2 + a0 + a1 + a2; //added A to noA_ or added P to a_
a1 = a0;
a2 = a1;

But that has the problem that we are using updated values already. So we need to store some temp values instead.

tempnoA0 = noA0 + noA1 + noA2; //added P to any of the previous noA's
tempa0 = noA0 + noA1 + noA2 + a0 + a1 + a2; //added A to noA_ or added P to a_
noA2 = noA1;
noA1 = noA0;
a2 = a1;
a1 = a0;
noA0 = tempnoA0;
a0 = tempa0;

Now all you have to do is run this in a loop and figure out what the actual end result is. But that shouldn't be too hard right?

A last thing to consider is when to do the modulo. It may well be worth doing this at the right times during the loop as well to reduce the risk of overflowing the long (although I didn't actually look if this would be a real problem or not).


Simple SingleLinkedList Implementation in C++

You asked about pointer usage, so a topic which may interest you is:

Indirect Pointers

Indirect pointers fall into the "easy to use, difficult to think up" category, but are useful in many cases, so are worth understanding, and apply to a linked list.

In your implementation of deleting a node there are two cases, one where the head should be deleted, and one where somewhere else should be, and in both cases you do roughly the same thing. We can get rid of that duplicated code.

Instead of

node* temp = head;

we can take the pointer to head, like

node** indirect = &head;

and as we go along, we can move indirect to the pointer to this node's next pointer

indirect = &((*indirect)->next);

Put together, this results in a method which looks something like this:

void SingleLinkedList::deleteNode(node* toBeDeleted){
    node* prev = nullptr;
    node** indirect = &head;

    while(*indirect != toBeDeleted){
        prev = *indirect;
        indirect = &((*indirect)->next);
    }

    *indirect = toBeDeleted->next;
    delete toBeDeleted;

    if(!(*indirect)) tail = prev;
}

Notice that the special case can be totally removed because, in the first assignment to indirect, indirect contains a pointer to somewhere in the stack (where head is), and in future assignments it has a value in the heap (where the current node is)


There's a test suite of 2000 test cases available at https://www.w3.org/XML/Test/ - try it out.
From a quick glance, it's not clear to me how you're handling content within comments or CDATA sections - which might be well-formed XML, or it might be something approximating to well-formed XML.
Another comment is that messing with whitespace is dangerous in mixed content. With inline markup (bold, italic etc) preserving whitespace as written may be important.


Merge two list and discarding duplicates

Pick a good return type

A deque is a Double Ended QUEue. Deques are great for when you have to insert and erase from the front as well as the back. You never need this for your problem - all you ever need is to insert at the end. You just need a normal list.

Generate when you can

Rather than necessarily giving the entire result all at once, it's better to just yield the next element as you go. This is a simple change in your algorithm (just yield x instead of result.append(x)), but could have serious performance implications down the line if you have lots of large iterables. If the caller wants a full list, then can always explicitly write list(merge_no_duplicates(a, b, c)).

Use the standard when you can

There is a function that already merges sorted inputs into a single sorted output: heapq.merge. It will give you duplicates, but that seems like a much better starting point than writing everything from scratch:

def merge_no_duplicates(*iterables):
    last = object()

    for val in heapq.merge(*iterables):
        if val != last:
            last = val
            yield val

If you don't want to use heapq.merge, then you can at least use this framework to separate the "merge sorted iterables" concern from the "remove duplicates" concern.


I find those classes should but just simple POCO classes with get/set properties. They could sit either inside a DTO or Model namespace or could have a Dto suffix and simple names like Person or PrivatePerson or BusinessPerson. They are not service providers as you call them.

However, you do want to differentiate between a PrivateCountry and a BusinessCountry. You could do this by adding the type of operation you need them for, like PrivateCountryForAddingDto or BusinessCountryForUpdatingDto. With this pattern you will have a few more models but the good thing is that each command will have its own independent model that can have its own validation logic. A model for adding does not necessarily have to have the same requirements as a model for updating. Some fields might be optional in one case and mandatory in another case.


I don't have a solution better than yours (you can google for java 3Sum O(n^2) to find some examples), but I have some small comments on your code:

While loops

I would remove all the while loops. They make your code harder to read and don't really speed it up (in my tests, they actually slowed it down).

Minor performance improvements

array access costs time, if you save num[i], etc in local variables, it will slightly speed your code up.
move quicker checks to the beginning: nj > 0 && ni + nj > 0 instead of ni + nj > 0 && nj > 0 should be quicker, but only marginally so.

Style

use correct indentation
in Java, the opening curly bracket commonly goes on the same line
use curly brackets, even for one-line statements
use more spaces (for example while(k+1<num.length && num[k]==num[k+1]) would be while (k + 1 < num.length && num[k] == num[k + 1])


Validation class to avoid ugly if-else blocks

First of all, you're not using your generics properly here:

private IValidator validator;

I would change this to

private final IValidator<String> validator;

Because:

final because the value does not change, and should not change. The field should be immutable
<String> to use generics properly. Otherwise you should get a compiler warning saying IValidator is a raw type. References to generic type IValidator<E> should be parameterized

However, I think your Context is not very useful. I don't see any reason for why you need it. You can accomplish the exact same things by using:

public class TestValidation {
  public static void main(String[] args) {
    IValidator<String> context;
    context = new SomeFieldOne();
    System.out.println(context.validate("some field one"));
    context = new SomeFieldTwo();
    System.out.println(context.validate("some field two"));
    // test other fields ....
    // .........
  }
}

This is less code and has the same effect. And it also looks better and improves readability as changing strategy now calls only one constructor instead of two.

I assume you're compiling with Java 1.6 or above, and therefore your classes that implements the IValidator interface should mark the validate method with @Override to comply with the Java coding conventions. (Marking methods with @Override that overrides interface methods was not supported at all in previous Java versions)

@Override
public boolean validate(T field) {


Give your method a proper name. These auto-generated names are pure terror!
You can import ActionEvent directly, no need to reference it with the entire package name.
Your formatting is unusual at best, I'd call it bad. I know this is, for some reason, the preferred way to set braces in the Linux kernel code, but this is Java, not C.
You are using hard-coded file paths. Absolute no-go. What if the user named his main partition D or installed xampp somewhere else – or is using Mac or Linux?
Why are you storing the result in Process p if you never use that variable?
" // Prints error in red" is a comment that is both completely useless (why do I need to know this right then and there?) and will rot faster than you can imagine.


Delete the characters of one string from another string

I'd use an object to hold the compiled version  of the process for maximum efficiency. This would allow user to create a stripping tool and re-use it for maximum throughput.

Also you have the opportunity to create Strippers. :)

public class Test {

    /**
     * Use a Stripper to encode the stripping process.
     */
    private static class Stripper {

        /**
         * Boolean lookup for maximimum performance.
         *
         * Could use BitSet to save a little space.
         *
         * Length 256 - assumes ASCII.
         */
        private final boolean[] strip = new boolean[256];

        // Compiles the strip string.
        public Stripper(CharSequence strip) {
            for (int i = 0; i < strip.length(); i++) {
                char ch = strip.charAt(i);
                // Both lowercase and uppercase.
                this.strip[Character.toLowerCase(ch)] = true;
                this.strip[Character.toUpperCase(ch)] = true;
            }
        }

        /**
         * Strips all characters from s that were in the `strip` parameter of
         * the constructor.
         *
         * Note the use of `CharSequence` to avoid premature `toString`.
         *
         * @param s - The source of the data to strip.
         * @return The stripped version of s
         */
        public CharSequence strip(CharSequence s) {
            StringBuilder stripped = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if (!strip[ch]) {
                    stripped.append(ch);
                }
            }
            return stripped;
        }
    }

    public static final String strip(String from, String strip) {
        return new Stripper(strip).strip(from).toString();
    }

    public void test() {
        System.out.println("Stripped: " + strip("John Lennon", "Paul ON"));

    }

    public static void main(String args[]) {
        try {
            new Test().test();
        } catch (Throwable ex) {
            ex.printStackTrace(System.err);
        }
    }
}

Correctly prints:

  Jhe

This algorithm should have an \$O(n)\$ construction complexity and an \$O(n)\$ processing complexity.

Please forgive the I'd do it a completely different way - this answer was posted before it was moved to Code Review.

Added

It seems a bit of narrative would be useful.

Obviously the desired process comes in two parts, first the setup and second the stripping of characters from the original string. This code performs the setup during the construction of the object by building an array of 256 booleans, one for each possible 8-bit character code. Each boolean holds a true value if the character at this position should be stripped from the string.

This ensures that the absolute minimum needs to be done at process time. All that is required is to take one pass through the string, looking up each character in the boolean array. If we find true then the character is discarded, a false means keep it.


Singleton Design Pattern implementation in a not traditional way

Your implementation does the trick. For what it's worth, I would consider your implementation the current "traditional way". It is thread-safe. The static constructor is guaranteed to run only once, so you won't accidentally end up with two instances if two threads try to grab the instance for the first time simultaneously.

Laziness

There is one more thing you might want to consider though. Because of the way the static constructor works, it is executed the first time the class is referenced in the code. This means that the instance in your singleton is created, even when you don't try to grab the instance, but another static variable perhaps.

To fix this, you might want to make the creation of the instance lazy, so that it really only fires when you need it. To do this, you can use the Lazy<T> class.

Sealed

This is mostly a formality, but it's nice when trying to do it formally. The sealed keyword means that that class cannot be inherited from. The private constructor already ensured that, but this makes it more explicit.

Readonly

As Jesse mentioned in the comments, it's a good idea to make the instance field (lazy or not) readonly. This prevents you from accidentally mucking up your singleton instance from within the class.

public sealed class Person
{
    private Person() { }
    private static readonly Lazy<Person> lazyPersonInstance = new Lazy<Person>(() => new Person());
    public static Person GetPersonInstance()
    {
        return lazyPersonInstance.Value;
    }
}

Your method GetPersonInstance can also be a getter-property:

    public static Person Instance => lazyPersonInstance.Value;

Exceptions

IEatBagels already posted an answer about throwing exceptions. I'll elaborate a bit on how it would work in this example. We're looking at the scenario where instantiating the singleton instance throws an exception.

In your code, this exception would be thrown when the static constructor is ran. As IEatBagels points out, when this happens, the type is broken for the rest of the "program". This means that you have one shot at creating your instance.

In my example, the initiation of the instance does not happen during the execution of the static constructor. All we do during static initialization - static constructor and static fields act similarly IIRC - is creating the Lazy<T> object with the factory method. This method is only executed when lazyPersonInstance.Value is called.

However, Lazy<T> caches exceptions. This means that if the factory method throws an exception, that exception will be rethrown on every subsequent call to lazyPersonInstance.Value. Without re-executing the factory method. So in the end, this is the same problem as the static constructor problem. The Lazy<T> docs have the following to say:

  The Lazy stands in for an actual T that otherwise would have been initialized at some earlier point, usually during startup. A failure at that earlier point is usually fatal. If there is a potential for a recoverable failure, we recommend that you build the retry logic into the initialization routine (in this case, the factory method), just as you would if you weren't using lazy initialization.
  MSDN docs

So if you really must throw exceptions in your constructor, be sure to handle them in the factory method.

Exceptions and thread-safety

There's one more workaround for the problem of exceptions in constructors. Lazy has three thread-safety modes, defined in the enum System.Threading.LazyThreadSafetyMode which can be passed to the constructor of Lazy<T>.

None. No thread safety.
ExecutionAndPublication. This is the default. This ensures that the factory method is executed only once, and that the object on lazy.Value is always the same across threads.
PublicationOnly. This only ensures thread-safety on lazy.Value. It can happen that the factory method is executed simultaneously by multiple threads, but the resulting instance is still the same. The others are discarded. According to the Lazy<T> docs, Exceptions are not cached here.

This leaves you, the implementer of the singleton with a decision: if there are exceptions that might be thrown, that can't be handled within the factory method, and that might not throw in subsequent attempts (weird, but might happen), you could consider loosening up some of the locking on Lazy to allow for this behaviour.

For further reading, see this blog post by Jon Skeet.


Iterative Implementation of Negamax Alpha-Beta

Some quick suggestions:

Split the code into smaller methods, with understandable names - it will become simpler!
Use clear variable names (even if they are longer) and try to avoid "shortenings";
Never use less than 3 characters for variable names... le? r? mv?!? (int i in for cycles is an exception because it is idiomatic);
Use PascalCase (not camelCase) for methods and properties;
Use camelCase (not lowercase) for local variables;
Don't repeat code (var le = legals(bd); while (le.Any()) { ... }), extract it to a method.


This is a very solid attempt!

Really, the only negative comment I have is that you collect words into a Vec and then immediately iterate over it. Instead, you can just use the iterator directly.

Regarding avoiding let mut, there's nothing specific to your code I can think of, but there are a few general methods to avoid it.

The first is to make a block and return it from that:

let v = {
    let mut v = vec![2, 3, 1];
    v.sort();
    v
}

The second is to rebind as immutable.

let mut v = vec![2, 3, 1];
v.sort();
let v = v;

The third is to use a crate like tap, which provides a trait implemented by everything which provides a tap method.

let v = vec![2, 3, 1].tap(|mut v| v.sort());

Next, I have some suggestions for alternatives and personal preferences.

Rather than splitting on whitespace then sanitizing words, you could use regex's match function and select all continuous sequences of letters. This has slightly different semantics, since it would separate e.g. "can't" into two words. However, you could instead also allow ' and - in a word. By instead scanning by regex with find_all, you can specify exactly what constitutes a word.

Instead of or_insert(0), you can use or_default(). Since the default for numbers is 0, This does the same exact thing, but is a bit cleaner.

When collecting, I prefer to annotate the type of the variable (let x: T) rather than using turbofish notation (::<T>), I believe it looks cleaner.

The way you're sorting is perfectly fine, but I prefer using sort_by_key when possible (and reasonable). In this case, you can just wrap the key in std::cmp::Reverse, a helpful struct that reverses the ord instance on it's contents.

In general, I don't see any unneeded clones/allocations. Since the hashmap is so temporary, I would typically suggest making it's key a &str, but you can't do this since you have to make your keys lowercase. However, there's a clever way to get around this. You can wrap your &strs in a helper struct that does case insensitive hash and eq. Luckily, there's a crate for this called unicase, with structs for unicode-case-insensitive and ascii-case-insensitive String/&str. By doing this, you eliminate the allocation of a String for each word. Note that this will make your words have the case of the first time they occur, so you may want to lowercase them before printing them.

All together, here's how I might write this program.

use std::cmp::Reverse;
use std::collections::HashMap;

use unicase::Ascii;
use lazy_static::lazy_static;
use regex::Regex;

lazy_static! {
    static ref WORD: Regex = Regex::new("[-'a-zA-Z]+").unwrap();
}

fn main() {
    let data = std::fs::read_to_string("data.txt").unwrap();
    let words = WORD.find_iter(&data);

    let mut freqs: HashMap<Ascii<&str>, usize> = HashMap::new();
    for word in words {
        *freqs.entry(Ascii::new(word.as_str())).or_default() += 1;
    }

    let mut freqs: Vec<_> = freqs.into_iter().collect();
    freqs.sort_by_key(|&(_, freq)| Reverse(freq));

    for (word, freq) in freqs {
        println!("{}: {}", word, freq);
    }
}


Wipe sensitive information from memory in Python

One advantage of the logger module is that you can pass it strings and objects to log at some level, and the string formatting is only performed if it is actually needed (i.e. the logging level is low enough). Also, having the gc.collect() actually hides it a lot, I was looking for it for some time. So I would do this instead:

def wipe_sensitive_info(d, keys):
    """
    In Python we are not able to overwrite memory areas. What we do is:
    - remove references to the specified objects, in this case keys in a dictionary
    - immediately call garbage collection
    """
    # TODO: the following points are pending
    #   - this relies on the gc to remove the objects from memory (de-allocate memory).
    #   - the memory itself is not guaranteed to be overwritten.
    #   - this will only deallocate objects which are not being referred somewhere else (ref count 0 after del)
    for key in keys:
        del d[key]
    n_garbage_collected = gc.collect()
    logger.info("Garbage collected %s objects", n_garbage_collected)

You could add a check for objects which have reference counts left:

import sys

...

for key in keys:
    if sys.getrefcount(d[key]) > 2:
        # The count returned is generally one higher than you might expect,
        # because it includes the (temporary) reference as an argument to
        # getrefcount().
        logger.debug("Object potentially has references left: %s", key)
    del d[key]

Note that this might give you some false positives for interned objects, like small integers or strings. Case in point, in an interactive session, sys.getrefcount("s") just gave me 1071.


Apply labels from a stream to a Bitraversable

The fmap in labelLeft should be (.). Control.Lens.Zoom provides something like withStateLens. Inline definitions that are only used once.

bilabelWith
    :: Bitraversable t
    => (l ->  indexl -> l') -> (r ->  indexr -> r')
    -> Stream indexl        -> Stream indexr
    -> t l r -> t l' r'
bilabelWith f g xs ys = flip evalState (xs, ys) .
  bitraverse (zoom _1 . pops . f) (zoom _2 . pops . g)

pops :: (s -> a) -> State (Stream s) a
pops = flip fmap $ state $ \(Stream.Cons x xs) -> (x, xs)


Your is_prime() function checks if num is a multiple of any number below it. This means that it checks if it is a multiple of 2, 4, 6, 8, 10, etc. We know that if it isn't a multiple of 2, it won't be a multiple of 4, etc. This goes for all other numbers, if it isn't a multiple of 3, it won't be a multiple of 27 (3x3x3).

What you need to do is check if num is a multiple of any prime number before it.

def nth_prime_number(n):
    # initial prime number list
    prime_list = [2]
    # first number to test if prime
    num = 3
    # keep generating primes until we get to the nth one
    while len(prime_list) < n:

        # check if num is divisible by any prime before it
        for p in prime_list:
            # if there is no remainder dividing the number
            # then the number is not a prime
            if num % p == 0:
                # break to stop testing more numbers, we know it's not a prime
                break

        # if it is a prime, then add it to the list
        # after a for loop, else runs if the "break" command has not been given
        else:
            # append to prime list
            prime_list.append(num)

        # same optimization you had, don't check even numbers
        num += 2

    # return the last prime number generated
    return prime_list[-1]

I'm sure someone else here will come up with an even more efficient solution, but this'll get you started.


It seems good but I have some comments on this,

Why do you create a new ListItem in every property change and not just replace to old property with the new one?

_list[index].Property1 = property1;

You raise the event without null check. Do this:

var listChanged = ListChanged;
if (listChanged != null)
    listChanged(this,new ListChangedEventArgs(ListChangedType.ItemChanged, index));

As a side note, if Property1 or Property2 are complex objects, It's recommended to create for them you own equal methods (Equal, GetHashCode, == and !=). If the are generic, implement IEquatable<T>


I think you should not really need to worry about that. This is for sure a non-performance critical part of your application and all the objects you create are almost immediately freed. My advice is to avoid premature optimisation and to focus on code readability instead.

I'd use some meaningful names. I'd replace iss, beg, vm with inputStream, beginning, variables_map. It improves readability a lot.

You should also consider splitting your code in different methods and make sure that everything has a single concern. Your main is doing everything and that's not very good in my opinion.
What about moving your prompt declaration to a constant defined at class level instead that inside the main?
I'd also introduce a create_options_descriptions() and a bool execute_next_command(...) methods.

Your main should look like:

int main(int argc, char* argv[])
{
    po::options_description options_description = create_options_description();
    po::variables_map vm;

    /*
     * It's better to pass std::cin and std::cout as dependencies so it
     * will be trivial to change it with references to other streams
     * if you ever need to.
     */
    while(execute_next_command(std::cin, std::cout, vm));
}

Execute next should follow the same idea and be split in a few methods like: read_input(...) that produces a list of arguments and bool process_args(...) that will take care of processing them and do the appropriate thing.


Okay, so the first thing here: prevent yourself from SQL injections. Of course you can escape your parameters but parametrized queries with PDO or so would be much better. You can also use mysqli - here's an example:

Also this won't execute since you have syntax errors in there (ie a missing ; here:  $cookieexpire = 600 //Time in MS).

Also, don't rely on cookies for this. If someone really wants to spam, it is really easy just to delete your cookies or just return them in a valid state... store the ipaddress (or ipaddr and the browser-string) and then save that in a database (or something like redis).

There is much more to talk about here, but this would be a good start.


Limiting the amount of Calls to a Server

I see several problems with your code:

You're mixing server code with UI
You're leaking activity reference in the Runnable
Your call takes longer time than 100ms
With code inside of you runnable you will miss changes to values that happened after the thread started (if it's not finished yet)

It is quite extensive to solve the first point. But all other points are quite easy to do:

Make inner class static and use a static variable to be delivered to server. This is not a nice solution, since everything should be stateless but at least you will fix the memory leak. If you make a presenter or uploader class that I would always notify it about UI updates and this new class will be resposnsible about removing back pressure from network uploading
I don't know if it is problem or not but I will do it a bit differently. I would create a Handler and submit Runnable to upload with delay 1 second (or your preferrable delay). And if there are changes are happening I would just reschedule the submission with same delay to later. So it will guarantee that you submit only "final" values in the delay context
Will be solved by #3


Showing statistics of popular JavaScript frameworks from GitHub API

Your questions

  How was my first javascript app?

Overall the code seems somewhat fine for a first attempt (barring the flaw mentioned in the first section below). It isn't difficult to read though it does have a few extra levels of nesting which could be cleaned up with abstraction code functions out to named functions.

  Is there a better way to do this?

As was suggested by others, there isn't really a point to returning the data nested under a key "data". Refer also to the other suggestions below for simplifying the code.

Other Feedback/Suggestions

Likely implementation flaw

frameworks.forEach(framework => {
  const promises = [];
  promises.push(frameworkData(framework.url));
  Promise.all(promises)

This code will call Promises.all() passing an array with a single promise, which seems pointless. While there is no rule that says there has to be two or more promises it basically defeats the purpose.

Presumably you meant to push the promises into an array and pass the array with all promises to the call to Promise.all().

Creating array of promises

One could use Array.prototype.map() to construct the array.

const promises = frameworks.map(framework => frameworkData(framework.url));

utilizing data

If you take the advice above, the first argument in a callback to .then() chained to Promise.all() should be an array of the data objects returned by the last promise callback within each call to frameworkData(), and there won’t be any reference to ‘frameworkso you might either need to pass that object along through the call toframeworkData` or look it up by index.

Template inline

The template literal used to define card could be moved out to a template tag with slots  or a

Then that could be referenced via the JavaScript:

const cardTemplate = document.getElementById('card-template').innerHTML;

You would then need interpolate the string, and unfortunately that isn't in a template literal anymore. However, an approach like outlined in this post should suffice.

The following function added in the JavaScript like this:

String.prototype.interpolate = function(params) {
  const names = Object.keys(params);
  const vals = Object.values(params);
  return new Function(...names, `return \`${this}\`;`)(...vals);
}

Would allow for a line like this:

row.innerHTML += cardTemplate.interpolate(data);

Simplifying single line returns in arrow statements

Arrow functions that simply have one line in the block, like:

resp => {
  return resp.json();
}

Can be simplified to a single line without the block and return:

resp => resp.json()

Unused variable

The following variable doesn't appear to be utilized:

let now = new Date();

It can be removed unless you plan to utilize it in the future. If the value never changes, it would be wise to declare it with const.

Putting it all together

See simplified code below.

String.prototype.interpolate = function(params) {
  const names = Object.keys(params);
  const vals = Object.values(params);
  return new Function(...names, `return \`${this}\`;`)(...vals);
}
const frameworks = [{
    name: "angular",
    logo: "img/angular.png",
    url: "https://api.github.com/repos/angular/angular.js"
  },
  {
    name: "ember",
    logo: "img/ember.png",
    url: "https://api.github.com/repos/emberjs/ember.js"
  },
  {
    name: "react",
    logo: "img/react.png",
    url: "https://api.github.com/repos/facebook/react"
  },
  {
    name: "vue",
    logo: "img/vue.png",
    url: "https://api.github.com/repos/vuejs/vue"
  }
];

const frameworkData = framework => {
  return fetch(framework.url)
    .then(resp => resp.json())
    .then(data => {
      return {
          logo: framework.logo,
          name: data.name,
          forks: data.forks_count,
          stars: data.stargazers_count,
          issues: data.open_issues_count
      };
    });
};

const setup = () => {
  const row = document.getElementById("row");
  const cardTemplate = document.getElementById('card-template').innerHTML;
  const promises = frameworks.map(framework => frameworkData(framework));
  Promise.all(promises).then(data => {
    row.innerHTML = data.map(obj => cardTemplate.interpolate(obj));
  });
};

document.addEventListener('DOMContentLoaded', setup);


Looks nice and clean.

One thing to note:

With Iterators Const Iterator is not the same as Iterator_Const. The first means you will not change the iterator while the second means you will not change what the iterator points at. You actually want to mean the second the first one is rarely useful.

<ReturnType> SortAndCountInversionsSubroutine(
                 const It begin, const It middle, const It end,
            //   ^^^^^           ^^^^^             ^^^^
                 unsigned int& count)

That's not a very useful const.
Just use:

template<typename It>
// When C++ concepts get added just uncomment the line below.
// requires std::is_const<typename std::iterator_traits<It>::reference_type>::value
<ReturnType> SortAndCountInversionsSubroutine(
                 It begin, It middle, It end,
                 unsigned int& count)

I "might" change this:

auto v = SortAndCountInversionsSubroutine(begin, mid, end, count);
std::move(v.cbegin(), v.cend(), begin);

I might move the std::move() into the SortAndCountInversionsSubroutine() the trouble with that is you need to change the iterators from being iterator_const (once you have fixed the first point) to non const. The advantage of course is that you don't have to return a vectorfrom a function.


My only real comment to make is that the subquery is irrelevant. You can achieve the same result without it.

When specifying your column aliases in the outer query. There is no need for you to use AS picid as the column is already called picid.

You could also use table aliases as well to shorten some of the statements. I personally prefer to see aliases than fully qualified table names. Assuming everyone sticks to a naming convention of course. My normal rule of thumb is that each capital letter of the table becomes the alias.

Also, as we can remove the subquery, we can change the WHERE clause so it is no longer filtering out the attachment name but instead the PK (WHERE a.Id IS NOT NULL).

For the columns being returned, can we make them more explicit? i.e. CandidateName instead of CName, etc.

Here is the modified version of your query using the changes above:

SELECT
     c.Name     AS CandidateName
    ,c.picid    AS PicId
    ,a.Name     AS AttachmentName
FROM Candidates c
LEFT JOIN AttachmentCandidate ac ON c.Id = ac.CandidateId
LEFT JOIN Attachments a ON ac.AttachmentId = a.Id
WHERE c.picid IS NOT NULL
OR a.Id IS NOT NULL

I'm not sure whether the formatting is just bad when you created your question or whether your SQL query is like that? If so, it's badly formatted and difficult to read. I try and break up each part of the query into separate segments so it's easy to read and maintain by others:

SELECT
     r.cname
    ,r.PicId
    ,r.attName
FROM
(
    SELECT
        Candidates.Name     AS cname
        ,Candidates.PicId   AS picid
        ,Attachments.Name   AS attname
    FROM Candidates
    LEFT JOIN AttachmentCandidate ON Candidates.Id = AttachmentCandidate.CandidateId
    LEFT JOIN Attachments ON AttachmentCandidate.AttachmentId = Attachments.Id
) AS r
WHERE (r.PicId IS NOT NULL OR r.attName IS NOT NULL)

As you requested an alternative, i'll give you one. Essentially it's pretty much the reverse of what you're doing. I'm gathering all of the candidates with attachments first and then I RIGHT JOIN back onto the candidates table and filter out the ones without a PicId.

SELECT
    c.Name      AS CandidateName
    ,c.PicId    AS PicId
    ,a.Name     AS AttachmentName
FROM AttachmentCandidate ac
INNER JOIN Attachments a ON a.Id = ac.AttachmentId
RIGHT JOIN Candidates c ON c.Id = ac.CandidateId
WHERE c.picid IS NOT NULL
OR a.Id IS NOT NULL


De-linearize a 2d linearized grid and calculate distance between 2 points

What you are doing is packing the two integer coordinates into a single integer, then unpacking them.

Let us assume that \$\text{height} \leq \text{width}\$, let w = width. Translate the lattice so that \$ 0 \leq x,y\leq w-1\$.

Using these assumptions, the packing can be done by writing the coordinates in base w. For example, if w = 10, x=4, and y=7, then the representation is w*y + x = 7*10 + 4 = 74.

Using our assumptions this is an injective function, i.e. to one pair \$(x,y)\$ there exists at most one \$k\$ such that \$k=wy+x\$, and each such \$k\$ uniquely determine the \$(x,y)\$. This means that the packing-unpacking is well-defined, which is great: same points will have the same representations, and a representation corresponds to exactly one point.

Your code,

y = k / w;
x = k - w * y;

could be written a few different ways, e.g. using %,

y = k / w
x = k % w

or by using std::div.

Modern compilers will compile all of these to the same instruction: idivl, so you don't have to worry about this part, just don't forget to tell your compiler to optimize slightly. For example, g++ needs the -O1 flag.

So that's about as good as it gets, unless we can use some faster form of integer division(from now on, simply division).

If a number is in base \$b\$, then it's really easy to divide it by powers of \$b\$: just shift the numbers around; e.g. 1234/10^3 = 1, 1234 % 10^3 = 4.

That's all fine and well, but string operations aren't going to be faster than idivl. Luckily we don't need those, because by choosing \$w=2^n\$, we can leverage bit-shifts, and bitwise-and to do exactly the same for us, really fast.

Let's find the smallest \$n \in \mathbb N\$, such that \$w \leq 2^n\$. Let \$ w = 2^n\$. Perhaps you won't use a few coordinates, but that's not really a problem.
Now our division code will look like this.

y = k >> n
x = k & ((1 << n) - 1)

Here x will be the first nth bits of k, and y will be the rest. For example, if k = 1101, n=2, then x = 1101 & ((1 << 2) - 1) = 1101 & (0100 - 0001) = 1101 & 0011 = 0001 = 01, y = 1101 >> 2 = 0011 = 11.

Now let's see if the compilers are clever enough to do this for us automatically.

int func1(int a) {
    int x = a / 1024;
    int y = a % 1024;
    return x+y;
}

int func2(int a) {
    int x = a >> 10;
    int y = a & ((1 << 10) - 1);
    return x+y;
}

Let's see the assembly code generated from the code above, if we allow the compiler to optimize a bit.

_Z5func1i:
    leal    1023(%rdi), %eax
    testl   %edi, %edi
    movl    %edi, %edx
    cmovns  %edi, %eax
    sarl    $31, %edx
    shrl    $22, %edx
    sarl    $10, %eax
    addl    %edx, %edi
    andl    $1023, %edi
    subl    %edx, %edi
    addl    %edi, %eax
    ret

_Z5func2j:
    movl    %edi, %eax
    andl    $1023, %edi
    shrl    $10, %eax
    addl    %edi, %eax
    ret

As you can see, besides some sign-checking, the two codes are identical. In fact, after specifying that we are working with unsigned integers, we get the same output:

    movl    %edi, %eax
    andl    $1023, %edi
    shrl    $10, %eax
    addl    %edi, %eax
    ret

This means that we can keep our more readable operators: %, and /. Hurray!

Now let's look at the last part of your code, and let's change it to a more general formula.

double distance = metric(xDiff,yDiff);

Where metric is a function calculating a distance. In your case, metric corresponds to the Euclidean metric,

double metric(int dx, int dy) {
   return std::sqrt(dx*dx+dy*dy);
}

Depending on your needs, you could use other metrics; as you are working on an integer lattice, I'd suggest you take a look at the taxicab metric. Its calculation is faster, and there is less room for numerical errors.

double metric(int dx, int dy) {
   return std::abs(dx) + std::abs(dy);
}

Implementing these changes result in code, which is a constant time faster, than your
original one.

While it was fun figuring out, I doubt this is the kind of speed up you were hoping for. I think optimizing other parts of your code could have greater benefits. Perhaps consider posting them as a separate question.


How do I better structure Java code to avoid dereferencing null?

You need to ensure that every statement in the switch is one that ensures that sb != null holds, this is not the case currently.

You can fix this by throwing an exception instead of logging a message, like this:

default:
    throw new IllegalArgumentException("input was invalid: " + userInput);

I also included that it tells you what the actual input was.

Other remarks are that your code has syntax errors, making it borderline ontopic, and your coding style definately needs improvement, I propose the following hence:

StringBuilder sb = null;
switch (userInput) {
    case 1:
        sb = method1();
        break;
    case 2:
        sb = method2();
        break;
    case 3:
        sb = method3();
        break;
    case 4:
        sb = method4();
        break;
    default:
        throw new IllegalArgumentException("input was invalid: " + userInput);
}

System.out.println(sb.toString());

Furthermore it seems very odd to me that your methods return a StringBuilder. I would just work with Strings here, as you are not doing an extensive amount of string concatenation.

Short guide:

String, to be used for regular text.
StringBuilder, to be used when you need to concentate/append a lot of strings.
StringBuffer, similar to StringBuilder, but now add to that that you are working in a multithreaded environment, hence you will almost never need this.


What happens if the user types "s"?  Your program says:

Enter Buyer Name:

Oops!  It was supposed to be uppercase, wasn't it?  I'm not sure why you want it to be case-sensitive, but you should tell the user of his mistake instead of just going on as if you know what he meant.  That means, I would change else: to elif not file: and add an else: that prints something like Sorry, I don't know what that means.

Your search_file = ... line is useless because you redefine search_file on the next line (with open(...) as search_file:).  By the way, I am happy to see that you are using with blocks.  That is rare, but good practice.

Your naming is not consistent with PEP 8, the Python style guide, on Method Names and Instance Variables:

  Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability...

You use int(input(...)) without a try block.  That is dangerous.  If the user types something that is not a valid integer, there will be a very nasty error.  You should use a while loop that keeps going until the user types a valid integer.  The validity test would, of course, be with a try-except block.

out_file.close() is unnecessary in your with block.  The with block will take care of closing the file.

You might want to take a look at the csv module.  With its help, you are more flexible with the format in which the entries are printed.  Your printing code might end up looking something like this:

template = "Name: {name} || Invoice Number: {invoice} || Quantity: {quantity} || Price: ${price}\n\n"

...

with open(look_in, "rt") as search_file:
    for line in csv.DictReader(search_file):
        if line['invoice'] == keyword:
            print(template.format(**line))

Your writing code:

with open("usb.txt", "at") as out_file:
    writer = csv.DictWriter(out_file, (
      'name', 'invoice', 'quantity', 'price')):

    writer.writeheader()
    writer.writerow({
        'name': Name, 'invoice': InNum, 'quantity': Quant,
        'price': Price})

As it is, an entry might be displayed just because its name includes the invoice number.  With a csv file, that is no longer possible.


performance of modulus operator vs if statement

EDIT
I missed the fact that this question was about C instead of C#. This likely invalidates my performance argument, so I removed that part of the answer. However, I do think that the readability argument (which is 90% of my answer) remains to be a relevant consideration.

You didn't really explain what the code does, and you really should have. We need the surrounding context to make sense of why each snippet is relevant.

However, if I can rely on the fact that whoever corrected your code is sure that the alternative works the same way, then I think I understand the scenario:

You are incrementing i, e.g. i++;
You're trying to have i increment from 0 up to N, multiple times. E.g. if N = 5, you want 0,1,2,3,4,0,1,2,3,4,... For the rest of the answer, I will refer to this behavior as "cyclical values".

The rest of the answer works under this assumption.

I agree with the corrected version.
The modulo operator is a fairly niche operator, compared to other C# operations. By that, I mean that when you encounter the modulo operator, you can almost immediately assume that you're dealing with cyclical values.
This cyclical behavior is exactly the case for you, so I do advocate the use of the modulo operator. It makes the cyclical nature of the algorithm easily discernible.

Distinguishing between the logical and the mathematical.
There are other cases where you can choose between a logical approach and a mathematical one. A simple example is for (mathematical) and foreach (logical):
for(int i = 0 ; i < myArray.Length; i++)
{
    var item = myArray[i];

    // ...
}

foreach(var item in myArray)
{
    //...
}

These two are functionally equivalent. However, more importantly, observe the intention of a for/foreach: it is used to direct the logical flow, it's not used (by itself) for calculating and storing values.
In the majority of cases, I would advocate the use of a foreach instead of a for, because it is easier to read a logical approach when the intention of the code is to direct the logical flow.
Note that for loops have their uses, e.g. when your iterations need a counter value to keep track of which iteration you're in. This is where the mathematical side of things becomes more important. But for the majority of use cases, you'll simply be iterating over an entire list and will not need a counter.
If you boil this down, you get to the following rule of thumb:

In cases where the mathematical and logical approaches are sufficiently equivalent (!) you should use the logical approach when you're directing the algorithm's logic, and you should use the mathematical approach when making calculations.
This closes the gap between the code and the intention of the code. The smaller the gap, the more readable the code will be.

The general idea here is that when you use a mathematical approach for a logical flow, then the developer needs to understand the mathematics to understand how the code will flow.
A sufficiently experienced developer will of course not get hindered by something he's familiar with, e.g. the simple for that I used. But as the logic gets more and more complex, the mathematical approach will compromise more and more of the code readability, faster than the logical approach will.

Let's go back to comparing your two options:
if (i >= N)
    i = 0;

i %= N;

Observe the intention of the code: You are trying to find the next value of i. That is inherently a mathematical operation, and therefore warrants the use of a mathematical approach over a logical one.


Checking if a random number exist within an interval efficiently

What you are basically asking is for a way to generate values with different weights.

In this case, you want 0 to be generated 30% of the time, 1 to be generated 40% of the time and 2 to be generated 30% of the time. Rather than checking intervals, it is much easier to generate a sequence that has elements that correspond to the probabilities.

For example, we could replicate the probabilities needed by having a 10-element list like so: [0, 0, 0, 1, 1, 1, 1, 2, 2, 2] and then pick 1 random element from it. How did I get 10? 10 is the minimal number of elements that evenly divides 30, 40 and 30 (the probabilities) multiplied by the sum of the weights (30 + 40 + 30)/10 = 10.

Another example is if we wanted 0 to occur 1% of the time and 1 to occur 99% of the time, then we could pick one element from [0, 1, ..., 1] where there are 99 1's. The 100 elements comes from (1 + 99 (sum of weights))/ 1 (divisor, or gcd to be precise) = 100.

Now assuming that all your probabilities are integral percentages (1%, 2%, ... 100%). Then you can always use 100 elements. Then for 5% you repeat the element 5x, 12x for 12% and so on.

Now let's do some code:

Lets say you build something like this: weighted_choices = [(0, 30), (1, 40), (2, 30)], where the 0, 1, 2 are the values and 30, 40, 30 are the percentage weights.

Then the code to select a item based on the weight is like so:

sample = [val for val, cnt in choices for i in range(cnt)]
random.choice(sample)

Note: This is code is taken straight from the random module documentation

If you want a simple, but slower version:

sample = []
for value, weight in choices:
    for i in range(0, weight):
        sample.append(value)
random.choice(sample)

If you want to read up on an even more general variation, go look at random's documentation


Project Euler Problem 10. Sum of all primes < 2mil

One of the fastest way to find primes is with a Sieve, which works like this:

(image courtesy of linked Wikipedia article)

All you have to do is create an array with 2 million elements:

#define MAX 2000000

// ...

bool* getSieve()
{
    bool isPrimeArray[] = new bool[MAX + 1];

Then you perform the sieve to it:

    for (int i = 2; i <= n; i++) {
        isPrimeArray[i] = true;
    }
    for (int i = 2; i * i <= n; i++) {
        if (isPrimeArray[i]) {
            for (int j = i; i * j <= n; j++) {
                isPrimeArray[i * j] = false;
            }
        }
    }

And sum it:

    int index = 0;
    long result = 0;
    for (boolean isPrime : isPrimeArray) {
        if (isPrime) {
            result += index;
        }
        index++;
    }
    return result;

Result:

#include <iostream>

#define MAX 2000000

bool* getSieve()
{
    bool isPrimeArray[] = new bool[MAX + 1];
    for (int i = 2; i <= n; i++) {
        isPrimeArray[i] = true;
    }
    for (int i = 2; i * i <= n; i++) {
        if (isPrimeArray[i]) {
            for (int j = i; i * j <= n; j++) {
                isPrimeArray[i * j] = false;
            }
        }
    }
}

int sumAllPrimes()
{
    bool* isPrimeArray = getSieve();
    int index = 0;
    long result = 0;
    for (boolean isPrime : isPrimeArray) {
        if (isPrime) {
            result += index;
        }
        index++;
    }
    return result;
}

int main()
{
    cout << sumAllPrimes();
}


I would assume that this
For Each d As KeyValuePair(Of String, String) In dict
    Using outputFile As New StreamWriter("E:\" & Convert.ToString("file.txt"), True)
        outputFile.WriteLine(d.Key & "," & d.Value)
    End Using
Next

is the bottleneck of your code. You are opening, writing to and closeing the file for each KeyValuePair of the dictionary.
Change it like
Using outputFile As New StreamWriter("E:\" & Convert.ToString("file.txt"), True)
    For Each d As KeyValuePair(Of String, String) In dict
            outputFile.WriteLine(d.Key & "," & d.Value)
    Next
End Using

and it should be running much faster.
Btw, why do you use Convert.ToString("file.txt") ?

InitIndexing()
by changing the condition of the f.Folders.Count to check if Count = 0 you could return early from the Sub and therefor save one level of indentation like so
If f.Folders.Count = 0 Then Exit Sub

For c = 1 To f.Folders.Count
    Dim Folder As Outlook.Folder = f.Folders.Item(c)
    Dim r As String = Folder.FolderPath
    For Each ml In Folder.Items
        oPA = ml.PropertyAccessor
        skey = oPA.BinaryToString(oPA.GetProperty(PropName))
        If Not dict.ContainsKey(skey) Then
            dict.Add(skey, r)
        End If
    Next
    Call InitIndexing(Folder)
Next

but you have bigger problems here: Naming ! You shouldn't use abbreviations to name things. If you come back to this code in 3 months you won't know the meaning of oPA, r or objName. You should always use meaningful names to name things.