Selecting and copying event log entries for some machine

I find this query difficult to read to begin with. Here are my comments:

When you DECLARE a bunch of variables it is useful to name them such that they will be easy for another programmer to identify throughout the script. For example adding v_ in front of them is a good way. Also calling a variable just l is pretty cryptic.
select * is sometimes not a good idea; that is, unless you actually need all of the columns. I see you use that a lot and it could be part of your performance issues. Part of why it may be problematic is also that your result set is unpredictable, if a column is added or dropped for instance, or renamed, your query would not be repeatable. It's better to get a "column does not exist" error than get unpredictable result set. Be explicit when you can.
The lack of proper indenting in your script, as well as the lack of a proper explanation in your question (or as comments within your script), in addition to some of it being in Polish it seems, makes it very difficult to decrypt what you are doing here unless you provide more information.
You have lots of variables, most of them holding lots of data (select * into etc.).  This likely is affecting performance. Multiple levels of nested subqueries can also slow it down.


Injecting a set of files in a Thymeleaf template while keeping the amount of tags at a minimum

Thymeleaf has a mechanism for removing template fragments. You can use the th:remove="tag" attribute to remove the containing tag but not its children:

<div th:each="f : ${files}" th:remove="tag">
    <h1 th:text="${f.value.pageTitle}"></h1>
    [(${content[ f.key ]})]
</div>

The resulting output will not contain the div but the h1 element and the text node.


Clearly employ contract requirements

"Write a function that ...  contains unknown number of words of max length 10 each." should echo in code someplace a 10 named something like "words of max length".  Use "size" for the size of the array.  With strings, best to use "length" in the context of the number of characters before the '\0'.

//#define MAX_CHARS 11
#define WORD_MAX_LENGTH 10
#define WORD_SIZE (WORD_MAX_LENGTH + 1)
...
// calloc(MAX_CHARS, ...
calloc(WORD_SIZE, ...

Use int with fgetc()

fgetc() returns values in the unsigned char range and the negative EOF.  These typical 257 different values will not distinctively fit in an 8-bit char.  With original code, should char be an unsigned char, your loop is infinite.

// char ch;
int ch;
...
while((ch = fgetc(file)) != EOF) {

Check return value of fopen() and calloc()

Should the open fail, detect it.

FILE *file = fopen(filename, "r");
if (file == NULL) {
  fprintf(stderr, "Unable to open file <%s>\n", filename);
  return 0;
}

Should the allocation of more than 0 bytes returnNULL,detect it.

arr = (char**) calloc(counter, sizeof(char*));
if (arr == NULL && counter != 0) {
  fprintf(stderr, "Out of memory\n");
  return 0;
}

Improve *alloc() style

Cast not needed.
Allocate to the size of the object, not the type.  Easier to code right, review and  maintain.

// arr = (char**) calloc(counter, sizeof(char*));
arr = calloc(counter, sizeof *arr);

Good use of sentinels in printing strings

 //                                v   v
 printf("The most frequent word is \"%s\" ...

Lack of bounds checking

Code should ensure i, j are not to big.

if (i >= counter) Handle_Error_Somehow();
i++;

if (j >= MAX_CHARS) Handle_Error_Somehow();
else {
  arr[i][j] = ch;
}

Missing fclose()

fclose(file);

Little bits.

I'd expect size_t counter, i, j, k for array indexing as size_t is neither too narrow nor too wide.  Be mindful it is an unsigned type.

Style: if (index_max != NULL){ is replaceable with if (index_max) {.  I find the the 2nd clearer.


python script to download multiple reports from odoo

Wasted looping

Let's do a pop quiz on this code:

partner = ([p for p in self.partners if p["id"] == invoice_id])[0]

If self.partner contains a million values,
and the first value has id equal to invoice_id,
how many values will be visited?

       All of them :(

That's unfortunate.
It would be better to spell out a loop:

for p in self.partners:
    if p["id"] == invoice_id:
        partner = p
        break
else:
    partner = None

Sure, this is longer, but it avoids a performance issue waiting to happen,
and it also handles the case gracefully when there is no matching value.

A compact alternative is possible using generator expressions, which are very cool:

partner = next(p for p in self.partners if p["id"] == invoice_id)

However, in this case, you would still need to handle the case when there is no matching value.
You would do that by expecting StopIteration to be raised.

Avoid wildcard imports

It's good to avoid wildcard imports.
It makes it easier to understand where symbols come from.
When you import *,
it can easily become confusing to tell where some names come from.

In this code the wildcard import seems pointless:

from dateutil.relativedelta import *
today = date.today()
nextmonth = today+relativedelta(months=+1)
nextmonth = nextmonth+relativedelta(day=1)

return nextmonth

It seems the only thing it imports is the relativedelta,
so you could write just that instead of using a *.

Also, I think that the last 3 statements are actually easier to read inlined:

return today + relativedelta(months=1) + relativedelta(day=1)

Import at the top of the file

It's recommended to import packages at the top of the file, not inside functions.

The above link is part of PEP8, a collection of recommended guidelines that should help you achieve the goals such as maintainability outlined in your question.

Drop pointless statement

In the constructor of UniReportPrinter there is this line:

odooconnection1 = ''

I'm wondering if you might be confusing odooconnection1 with self.odooconnection1.
They are different variables.
The first is a local variable,
the second is a field of the object being created.

If you want to unset self.odooconnection1, assign None to it instead of an empty string.

Getters should return something

I would expect functions with "get" in the name to return something.
The __get_partner_details function doesn't return anything.
I suggest to rename the method. Perhaps replace "get" with "fetch".

Be consistent

In some places I see print("string"), in others print "string".

In some places I see '{}/foo'.format(bar), in others '%s/foo' % bar, or bar + '/foo'.

It's good to be consistent.
And to consistently use the right techniques.
In each of these examples the right technique is the first.

Use '...'.format(...)

Especially when formatting complex strings like here,
definitely use '...'.format(...) instead:

return str(partner['partner_id'][0])+'-'+partner['reference'] + '.pdf'


Process list of e-mail addresses in PHP 5.3

Alright, I have a number of suggestions. Some of which will invalidate others. The reason I'm keeping these "invalid" bits in is because they are just good practice and I'm trying to pass that along. In order to get the most from this you will have to read all the way through.

First off, why are you using lambda functions (also known as anonymous functions or closures)? This seems completely unnecessary. The thing to keep in mind about lambda functions is that they are not compiled at run time. This means that they should be used sparingly because each time they are called they must be compiled separately. Lambda functions should really only be used for callbacks. Though I'll be honest, I don't even use them then. They tend to make the functions they are used in bulky and therefore difficult to read. In the five, almost six, years I've been doing this I've never once used, or needed, lambda functionality. Best to just use a real function and set a return value. Though that may just be an opinion.

REGEX should only be used as a last resort. Yes it is much more powerful than any of the simpler string functions, but because of that power it requires more processing power as well, and is therefore usually slower. So, if you can do the same thing with a simpler function, it is more than likely better. For instance, you could use explode() here to separate the initial string by spaces to get the first name, last name, and email addresses. If multiple addresses are used you can use explode()'s limiter to only return 3 elements, then use explode() again on the email section. This appears to be what you are doing anyways and is more than likely quicker. Though you may not notice a difference unless you are doing it thousands of times. Besides, REGEX is almost impossible to read and if not documented properly just looks like a foreign language to those of us who come after you and try to figure out what it does. REGEX is another one of those things I've hardly ever needed to have, there is almost always another way.

$matches = explode( ' ', $address, 3 );
list( $firstName, $lastName, $addresses ) = $matches;//for illustration purposes only
$addresses = trim( $addresses, '<>' );//remove those brackets before exploding
$addresses = explode( ', ', $addresses );//could use str_getcsv() here if you wanted

Because explode() always creates an array unless the string passed to it was empty, you can now just check that the result isn't FALSE and then check the array's size to determine if the only thing it contains is an address. This looks much better than that long list of confusing if arguments.

if( $matches === FALSE ) {
    return FALSE;
}
if( count( $matches ) == 1 ) {
    return $address;
}

By the way, you should still validate and sanitize the address with filter_var() in the above scenario. Validate with FILTER_VALIDATE_EMAIL and sanitize with FILTER_SANITIZE_EMAIL. I believe you can even do both at once. Well, I know you can, but I'm not sure if it will return FALSE if its not valid, so you may have to play around with it.

$email = filter_var( $address, FILTER_VALIDATE_EMAIL | FILTER_SANITIZE_EMAIL );

For and while loops declare the functions passed to them as parameters on each iteration, so using count() as a parameter here is inefficient. This value isn't going to change so it should be declared before the loop. Foreach is the only loop that doesn't have this issue, though it is still better, in my opinion, to separate functions from foreach loops as well.

$length = count( $matches[ 0 ] );
for( $i = 0; $i < $length; $i++ ) {

Although, I believe you could get away with just using array_combine() here instead of a loop.

$parsedAddress = array_combine( $matches[ 2 ], $matches [ 1 ] );

str_getcsv() may do what you want, but only because it is a hack. CSV stands for "Comma Separated Values" and is used to store and read data separated by commas. I think, though I can't find it documented anywhere, that I remember reading somewhere that it also uses angle brackets "<>" to separate groups and that is why this works, though I'm not sure. I'm honestly not sure why this works, but you should not rely on hacks to get a job done. What if that function changes? Then if you ever upgrade your server you will be stuck trying to figure out how to fix it, or someone else with less knowledge of how this works will. Besides, you've already gotten those email addresses into an array, why do it again? Just use array_keys() on $parsedAddress to get an array of email addresses. Better yet, while you are looping over $matches the first time and setting them, why not just use filter_var() there? Or if you end up using the array_combine() example, you could use array_map() to apply a callback function, in this case filter_var(), to the array_keys(). You've not just doubled the work here, but quadrupled it. You loop over $matches, then you loop over $addressCSV, then when you merge them, PHP loops over both arrays again to find the differences.

Last thing. Why are you referencing $address? I can find no instance where you are changing its value. This is also unnecessary, and, in my opinion, is a big no-no. Variable referencing is a powerful tool, but, like most powerful tools, it does have some drawbacks. The biggest one is that they are difficult to spot and therefore make troubleshooting difficult. Another is that they aren't well known. So while I can spot this, someone else may have never seen it before. After all, it is just an ampersand and not an actual function that they can easily look up.

I hope this all helps. If you need any clarification, just ask.


Reviewing my implementation of a stack using linked list

Some minor comments to add to what others have said.

Adding an underscore to the end of struct stack is just noise. It achieves
nothing, so leave it out.
Omit the spaces around -> and add them after keywords (if, while etc)
you are allocating only enough memory to hold a pointer to a stack node
(stack*). Instead you should be allocating a node:

head = malloc(sizeof(stack));

or:

head = malloc(sizeof *head);

Note also that there is no cast (we are writing C, not C++)

The version suggested by @ChrisWue is elegant, but it does need
two structures.  You could achieve the same thing but with only a
single struct (your existing stack) like this:

stack* push(stack *head, int data, int *result)
{
    stack *s = malloc(sizeof *s);
    if (s) {
        s->data = data;
        s->next = head;
        *result = 1;
    }
    else *result = 0;
    return s;
}

stack* pop(stack *head, int *data, int *result)
{
    if (!head) {
        *result = 0;
        return head;
    }
    *result = 1;
    stack *next = head->next;
    *data = head->data;
    free(head);
    return next;
}

But note that you must then be careful always to assign the return value to
head in the caller:

    int data;
    int ok;
    stack *head = NULL;
    ...
    head = push(head, data, &ok);
    if (ok) {
        ...
    }
    head = pop(head, &data, &ok);
    if (ok) {
        ...
    }


Hide/un-hide directory and open directory based on argument

Avoid echo -n

Avoid using any flags of echo, like this, as it's not portable:

    echo -n ": "

This is more portable, and produces the same output:

    printf ": "

Get rid of empty statements

These empty else statements are pointless,
I suggest to remove them:

else
    :

Simplify

This can be simplified:

    if [ "$result" = "$input" ]
    then
        clear
        mv $DIR2 $DIR
    else
        clear
    fi

Since in both branches of the if-else you clear, this is the same:

    clear
    if [ "$result" = "$input" ]
    then
        mv $DIR2 $DIR
    fi

Quote variables in paths

Typically you should double-quote variables,
especially when used as paths. So instead of this:

        mv $DIR2 $DIR

This is recommended and safer:

        mv "$DIR2" "$DIR"

Avoid duplicated code

The code in opendir and basic is almost the same.
The only difference I see is the content of the "$result" = "$input" conditions.
Consider using a single function with a flag to determine the behavior inside the main conditional.


A push style parser combinator in Haskell

It'll lazily take no more memory than it takes time to find the first result if you do not try to enumerate all possible results.

For many/some to only try one option, you want Maybe's Alternative/MonadPlus behavior, not []'s. You could parametrize your Parser type in the Alternative used so the user can change it on the fly.

yoctoparsec uses this "push" style.

parseString (hoistFreeT maybeToList $ many $ some $ mfilter (=='.') token) "...."


Longest Alternating Substring Code Challenge

Include the headers we need

#include <string>
#include <vector>

Don't make unnecessary copies

std::string longestSubstring(const std::string& digits) {

Also, consider storing std::string_view objects internally, as these are much lighter than owning strings.

Fix the bug

I get a SIGABRT when I call with empty string as argument:

==1629582==    by 0x4914B54: __cxa_throw (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==1629582==    by 0x490C090: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==1629582==    by 0x10AC0B: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::at(unsigned long) const (basic_string.h:1087)
==1629582==    by 0x10A30F: longestSubstring(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (238652.cpp:12)
==1629582==    by 0x10A725: main (238652.cpp:46)

Use the algorithm library

The standard <algorithm> library has the tools you need, that will save you writing much tedious and error-prone code for yourself.

The most useful function here is std::adjacent_find(), which you can use with a simple predicate such as

auto const both_even_or_both_odd
    = [](auto a, auto b){ return a % 2 == b % 2; };

No need to store all the substrings

We only need to remember the longest substring seen so far, so there's no need for the two vectors.  Just have a single std::string_view variable that you update when you find a longer run than the existing one.

Modified version

Here's a version using std::adjacent_find() as suggested:

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

std::string longestSubstring(const std::string& digits)
{
    std::string longest = "";

    auto const same_mod2 = [](auto a, auto b){ return a % 2 == b % 2; };

    auto start = digits.begin();
    while (start < digits.end()) {
        auto finish = std::adjacent_find(start, digits.end(), same_mod2);
        if (finish != digits.end()) {
            ++finish;
        }
        auto const candidate = std::string{start, finish};
        if (candidate.size() > longest.size()) {
            longest = std::move(candidate);
        }
        start = finish;
    }

    return std::string{longest};
}

And a simple test:

#include <iostream>

int main()
{
    for (auto const& s: { "", "0", "11", "01", "112",
                          "0112", "01224", "01223", "01123" }) {
        std::cout << s << "-->" << longestSubstring(s) << '\n';
    }
}


Python algorithm to return all two-tuple permutations of numbers up to n

I'd say your code is well-structured and easy to read. The approach however can be simplified using the itertools module from the standard library. itertools provides useful implementations for things like combinations, permutations, cartesian product and a lot more.
Here's the simplest and fastest approach I could come up with, that is equivalent to your implementation:
from itertools import product

def valid_tuple(number_pair: tuple) -> bool:
    a, b = number_pair
    return abs(b) <= abs(a)

def get_values_product(n: int) -> list:
    out = product(range(-n, n + 1), repeat=2)
    out = filter(valid_tuple, out)
    return sorted(out, key=lambda t: abs(t[0]))

It's usually faster to use functions that are built-in or included in standard library modules. itertools.product returns the cartesian product of input iterables, which is exactly what we want here. On my machine, this takes about half the time of your original implementation.

As you need sorted output I don't think there's a way to significantly reduce the space complexity. If you didn't need the output to be sorted, you could turn it into a generator, which is really memory-efficient.
Edit:
Here's how you can get the same desired sorted output while optimising space complexity:
from itertools import product, chain
from typing import Generator

def get_values_generator(n: int) -> Generator:
    if n < 0:
        return

    numbers = chain(*zip(range(n + 1), range(-1, -n - 1, -1)), [n])

    pairs = product(numbers, repeat=2)

    yield from filter(valid_tuple, pairs)

This works because we already pre-sort the list of numbers before calculating the cartesian product. This implementation returns a generator object, i.e. an iterator instead of a list. This means you might have to make some slight adjustments to the code that uses the return value of get_values.
Here's a comparison of the memory used by the return values of both approaches:
num = 50

sorted_list = get_values(num)
generator_obj = get_values_generator(num)

print(sys.getsizeof(sorted_list))
print(sys.getsizeof(generator_obj))

prints
> 85176
> 112

When changing num = 500, we get:
> 8448728
> 112

As you can see, the memory used by the generator object is constant at 112 bytes.
Here's some validation regarding the correctness of our result:
print("Same elements:\t", set(sorted_list) == set(generated_list))
print("Same length:\t", len(sorted_list) == len(generated_list))
print("No duplicates:\t", len(generated_list) == len(set(generated_list)))

print("Sorted:\t\t\t", all(abs(x[0]) <= abs(y[0]) for x, y in zip(generated_list, generated_list[1:])))

We get the same output for negative and positive numbers, as well as zero:
> Same elements:     True
> Same length:       True
> No duplicates:     True
> Sorted:            True


Beginner radian/degree converter program

Nowadays is common to omit the generic type on the right hand side of an assignment so instead of

 ArrayList<Integer> divisors = new ArrayList<Integer>();

you can write

 ArrayList<Integer> divisors = new ArrayList<>();

Since you are not using any ArrayList specific functionality it is cleaner to declare divisors as List (same goes for gcd)

 List<Integer> divisors = new ArrayList<>();

The call gcd.get(gcd.size() deserves a separate method with a reasonable name.

Regarding BufferedReader userInput ... while in this example it is harmless to not close IO resources, it is good practice to do so in general. Check out "try with resources statement": https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html.

It is also common to reuse the Reader and not create a new one every time you need to perform a read operation. With this in mind you will have something like this:

public static void main(String[] args) throws IOException {
    System.out.println("Do you want to convert from radicals to degrees, or degrees to radicals?");
    System.out.print("Use \"R\" for radials to degrees, and \"D\" for degrees to radicals: ");
    try (BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in))) {
        String userChoice = userInput.readLine();

        if (userChoice.contains("D") || userChoice.contains("d")) {

            System.out.print("Degrees: ");
            dtr(userInput);

        } else if (userChoice.contains("R") || userChoice.contains("r")) {

            System.out.println("Radical numerator (omit pi): ");
            System.out.println("Radical denominator: ");
            rtd(userInput);

        } else {

            System.out.println("Invalid response. Please restart the program.");
        }
    }
}

Note that now rtd requires only one parameter. Because you print before reading user input, the user gets to see

 Radical numerator (omit pi):
 Radical denominator:

before she has an opportunity to provide any input. Those statements should move into rtd interleaved with reading user input.

 if (userChoice.contains("D") || userChoice.contains("d"))

can be simplified like so:

if (userChoice.toLowerCase().contains("d")) {


I would use more legible names for variables and classes, they make it easier to read code as plain text (which is useful for other people to understand your code).

For example: naming your class AgeCalculator instead of AgeCalc, or ageCalculator instead of ac when instantiating it.

It is not that important on this example because it's not an extensive code, but if it where, it would be very difficult even for yourself (as the code owner) to remember what all variables mean, for further explanation I would suggest reading the disadvantages paragraph of https://en.wikipedia.org/wiki/Hungarian_notation

Another thing I could suggest you is to have your main method outside AgeCalculator, you should only keep inside methods that represent its behaviour.

I would start practising those, good luck!

EDIT

I found an example at http://www.tutorialspoint.com/java/java_object_classes.htm
I modified it a bit to also apply what I understand are more legible names:

import java.io.*;

public class Employee{

   String name;
   int age;
   String designation;
   double salary;

   // This is the constructor of the class Employee
   public Employee(String name){
      this.name = name;
   }
   // Assign the age of the Employee  to the variable age.
   public void setAge(int newAge){
      age =  newAge;
   }
   /* Assign the designation to the variable designation.*/
   public void setDesignation(String newDesignation){
      designation = newDesignation;
   }
   /* Assign the salary to the variable salary.*/
   public void setSalary(double newSalary){
      salary = newSalary;
   }
   /* Print the Employee details */
   public void printEmployee(){
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}

As you can see, variable names get a bit longer, but they also state what they are for, just by reading their names, so you don't have to remember "What did 'asdf' mean??" xD get me?

Also take into account that in complex code, you probably would have to be remembering many variables, and sometimes it won't be your code at all! So you won't be familiar with it.

Now, the main method, should be in another class (probably another file):

import java.io.*;

public class TheClassThatHasMainMethod{

   public static void main(String args[]){
      /* Create two objects using constructor */
      Employee firstEmployee = new Employee("James Smith");
      Employee secondEmployee = new Employee("Mary Anne");

      // Invoking methods for each object created
      firstEmployee.setAge(26);
      firstEmployee.setDesignation("Senior Software Engineer");
      firstEmployee.setSalary(1000);
      firstEmployee.printEmployee();

      secondEmployee.setAge(21);
      secondEmployee.setDesignation("Software Engineer");
      secondEmployee.setSalary(500);
      secondEmployee.printEmployee();
   }
}

Because as I said, you should only keep inside a class, methods that represent it's behaviour. At least in Object Oriented Programming, like this case, because each time you initialise a new Object (new Employee), you want it to behave like an Employee and expect it to have Employee methods, like calculating it's salary for example, or getting it's name. But a method called "main" doesn't make sense at all, an employee could give you his salary or name, not his... main?

Also remember that main is a special method that represents the beginning of the execution of your code, it should be separated from the rest of your objects and it must be unique.

Well hope I've helped some, I've also much to learn myself, good luck!


Concatenating an splitting seems like you're making extra work for yourself.  I suggest summing the results of a string-to-integer translation.

from collections import defaultdict

_RISK_SCORE = defaultdict(int, [('Extreme Risk', 3), ('High Risk', 2), ('At Risk', 1)])

@property
def risk_status(self):
    """ This function assigns numeric weight to risks. It returns an overall integer score. """
    return sum(self._RISK_SCORE[r] for r in (
        self.si_risk,
        self.aggbs_risk,
        self.cfimb_risk,
        self.cfiab_risk,
        self.cei_risk,
    ))


Function to check whether a path is valid or not needs your critique

Personally if  the preconditions to the function are not met then I like to return quickly and this not add to the nesting:

Bool_T PathValid( IN const char * path )
{
    if( path != NULL )
    {
        // wrong argument
        return false;
    }

    if( GetCharsNumInPath( IN path ) <= MAX_PATH_LEN )
    {
        LOG_ERROR( "PathValid FAILURE --> path is too long" );
        return false;
    }

    // Main Function body here.
}

Of course in C you don't want to have too many return points from a function (as at each return point you need to close all open resources and tidy up. So in C (unlike C++) I find my code looking like this:

<type>   function(<Parameters>)
{
      if (!<pre-condition1>)
      {    return <errorStat1>;
      }

      if (!<pre-condition2>)
      {    return <errorStat2>;
      }

      ....

      if (!<pre-condition-N>)
      {    return <errorStat-N>;
      }

      <type>   result = <initial Result>;
      <Set all Resource to NULL>

      // Code Which can generate errors>
      // If it does then set error state. and stop processing.
      // BUT DO NOT RETURN from this code.

      < Close all resource >
      return result;
}

Your check for invalid characters is Windows specific. The OS will usually have a platform or OS specific set of functions for checking valid characters.

Your set of invalid characters is not true for all platforms.
The use of ':' as the second character is Windows only.

If it is there the first character should be 'A' - 'Z'

Limiting the use of space is Windows only
Are you sure about "." not being allowed as last character?
On windows two '\\' can be used as the first two characters to indicate network resource.
Windows has more than one path separator.

The old style '\' (traditional backslash)
The new style '/'  (normal slash).

In your function counting characters in the path. You basically traverse the string twice. Why not combine the two traversals into a single pass:

// int n = strlen( path );
// Not requires (all this does is look for '\0')

for( i = 0; path[i]; i++ )
{       //  ^^^^^^^  Test for '\0'  character

    if( ( path[i] < 0x80 ) || ( path[i] > 0xbf ) )
    {    cnt++;
    }
}


I would try to decouple the idea of traversing the matrix to collect information about its content and the actual definition of find_zeros. This way you can reuse the same traversal to implement other functions too.

This leads to something like this (I don't assume that the matrix is a square one): indexedTraversal takes a function add and an initial value ini for the accumulator we will use when traversing the matrix mat. add updates the accumulator given the position of the current cell and its content.

type 'a matrix = 'a array array

let indexedTraversal
    (add : int -> int -> 'a -> 'b -> 'b)
    (ini : 'b)
    (mat : 'a matrix)
    : 'b =
  let m = Array.length mat     in
  let n = Array.length mat.(0) in
  let rec aux (i : int) (j : int) (acc : 'b) =
    let acc' = add i j mat.(i).(j) acc in
         if j < n - 1 then aux i (j + 1) acc'
    else if i < m - 1 then aux (i + 1) 0 acc'
    else acc'
  in aux 0 0 ini

(nota: I don't check that m > 0 here so Array.length mat.(0) might raise an error. You can (and should!) add the test to handle that edge case)

You can then implement find_zeros by defining an appropriate testElt and calling indexedTraversal with the empty list as the inital accumulator. Here I call List.rev because otherwise the result is actually the reverse of what you had implemented. If you don't care about the order in which the elements are listed, you can just do away with it.

let find_zeros (m : int matrix) : (int * int) list =
  let testElt i j x ijs = if x == 0 then (i,j)::ijs else ijs
  in List.rev (indexedTraversal testElt [] m)

We can try it on a simple example and it works:

utop # find_zeros [| [|0;1|]; [|1;0|]|];;
- : (int * int) list = [(0, 0); (1, 1)]


keep the value in one place which make it more simple to change it

You will never change it (why would you?) so this is not a valid reason. And if you did change it then search/replace works fine.

  keep available property dictionary in one place (in the model)

This looks like MySQL to me. So I suggest using an enum for this instead of a varchar. It will be much faster, take less storage space, prevent invalid values, and have the benefit of storing the dictionary right in the database.

  make the code completion available in IDE instead of searching for correct property name to copy/paste it

This  is nice - however is there no other way to do this? Can you not add some kind of configuration file that will define these?

In the "not good" column I would put adds complexity for little gain. You've taken a string, and turned it back into a different string, only uppercase.

Now, if you were going to store these as integers (i.e. do the equivalent of enum yourself) then making constants has value. You are turning a string into a number, so it actually does something.

So, my suggestion:

Either use enums in your database, and just write them as strings, or store integers, and use the constants.

But don't store these properties as strings.

(BTW, suppose you want to convert from one to the other: Search/replace! I've seen too many cases of overengineering things just from fear of search/replace.)


Display Thousands/Millions of different background images

Sluggishness

Memory limits

Take a look at a random folder of images on your computer, and observe it's size. Thousands of images will amount to gigabytes of space, which means all that needs to be loaded into memory. You can simply not do that reliably.

There is also not really a point in rendering things that the user cannot see.

Thousands or millions of images?

Consider why you think you need to display thousands or millions of images. Consider a pretty sizeable screen of 1920 by 1080 pixels. If you have 30 pixels in width and 30 pixels of height, you can fit 60 * 36, or 2304 images on screen. At some point you will not be able to make out anything.

Multiple canvas elements

There does not seem to be a reason to use multiple canvas elements. If you want a background with hundreds of images, you can redraw the same canvas as you scroll. In fact, this is probably the best way of dealing with your current situation.

Coding style

Wrap your code in an IIFE

Wrap your code in an Immediately Invoked Function Expression. This causes the variables to not spill into other code you or others write. An IIFE looks something like this:

(function () {
  // ...
})();

Look at your variable names

Some of your variable names do not really make sense. cInt seems an iteration of your canvas element. I am not sure why you use loopCInt at all. Replace it with canvasIdentifier or canvasIteration. canvasName is actually a CanvasElement, not a name. goDown looks like a function name at first glance, but is actually the number of pixels from the top, so just name it top. right is actually what you would refer to as left if you worked with absolutely positioned elements, namely the number of pixels from the left edge.

Bookkeeping

You are using a while loop, and because of that have a lot of lines related to bookkeeping. Since you are managing both a row and a column in a single loop, it is not very readable either. I would recommend replacing it with two for loops.

Factor out functions

You want to start factoring out functions with some kind of behaviour earlier than later in your code. You currently have one giant blob of code that, while it does what you want to do, is a nightmare to read through when you expand it. A pretty obvious thing to abstract out is to move things to draw the scene into their own function. You can then call that function to draw or redraw things.

Factor out magic numbers/strings

You currently set "1000" for the width and height, and draw squares of 30 by 30. Move these numbers/strings to their own variable that you can easily change. This allows you to re-use them and quickly change them when you decide, for example, to have a border of 10 pixels around your canvas.

Example

Below I applied some of these to your code. I also put in an example where the canvas is redrawn when you scroll the screen. I added a random number generator that can be seeded, so that I can show off that you can create a consistent screen. You can probably improve on that, considering that it now generates too many colors.

// https://stackoverflow.com/a/19301306/2209007
function RandomGenerator() {
  var m_w = 123456789;
  var m_z = 987654321;
  var mask = 0xffffffff;

  // Takes any integer
  this.seed = function(i) {
      m_w = i;
      m_z = 987654321;
  }

  // Returns number between 0 (inclusive) and 1.0 (exclusive),
  // just like Math.random().
  this.random = function()
  {
      m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
      m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
      var result = ((m_z << 16) + m_w) & mask;
      result /= 4294967296;
      return result + 0.5;
  }

  this.randomHexColor = function()
  {
    var hexFFFFFF = 16777215;

    return '#' + Math.floor(this.random() * hexFFFFFF).toString(16);
  }
}

(function() {
  var canvas = document.getElementById('background-canvas');
  var ctx = canvas.getContext("2d");
  var windowWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  var windowHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  canvas.setAttribute('width', windowWidth);
  canvas.setAttribute('height', windowHeight);

  var imageWidth = 30;
  var imageHeight = 30;

  var randomGenerator = new RandomGenerator();

  function draw(offset)
  {
    window.requestAnimationFrame(function () {
      randomGenerator.seed(1);

      for (var top = -offset; top < windowHeight; top += imageHeight) {
        for (var left = 0; left < windowWidth; left += imageWidth) {
          if (offset < -imageHeight) {
            randomGenerator.randomHexColor();
            continue;
          }
          ctx.beginPath();
          ctx.rect(left, top, imageWidth, imageHeight);
          ctx.fillStyle = randomGenerator.randomHexColor();
          ctx.fill();
        }
      }
    });
  }

  draw(0);

  document.addEventListener('scroll', function() {
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

    draw(scrollTop);
  });
})();
#background-canvas {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 10px;
  left: 10px;
  z-index: -1;
}

body {
  height: 200vh;
}
<canvas id="background-canvas"></canvas>


SQL procedure with cursor to check if values in table 1 are also in table 2

Doing that (checking if values in Table1 are or aren't in Table2) is typically done with a LEFT JOIN. Or a RIGHT JOIN if you want to get creative. Using a CURSOR in T-SQL should be you last resort!
Something like this:
SELECT t1.[columns]
FROM [table1] t1
LEFT JOIN [table2] t2 ON t1.[key] = t2.[key]
WHERE t2.[key] IS NULL

Style
There are a number of accepted standards for writing T-SQL. Some people write the keywords in ALLCAPS, others write them in lowercase - which convention you chose is entirely up to you and, in the end, doesn't matter.
What does matter though, is consistency.

and DateAdd(day, ZaN_DataRealizacji,CONVERT(DATETIME,'1800-12-28',120)) >= @dzisiaj
AND DateAdd(day, ZaN_DataRealizacji,CONVERT(DATETIME,'1800-12-28',120)) <  @jutro

and

select * from #Temp_Table
order by seria

shouldn't be in the same script. Pick a convention, stick to it, and thank yourself later :)
One helpful convention I've adopted, is comma-first. This:

SELECT ZaN_MagNumer,Zan_ZamSeria,Zan_DataRealizacji

Would look like that:
SELECT
     ZaN_MagNumer
    ,Zan_ZamSeria
    ,Zan_DataRealizacji

This allows you to easily comment-out, remove, add or reorder columns while reducing the room for error.


Check whether a given sequence can be rearranged using a stack

FYI, this question is probably off-topic here because you asked "if [the code] is correct" instead of merely asserting that it was correct and waiting for someone else to find the bugs. ;)  However, I think your code is correct, although it can be improved.

The biggest improvement you should make is to use functions. See your first few lines?

stackInput = [1,2,3,4,5]
expOutput = [4,5,3,2,1] # return True
#expOutput = [4,3,5,1,2] # return False

Commented-out code is a code smell. In this case, the root problem is that you need a way to run your algorithm with two (or more) different inputs... and the structured-programming solution to that is to use a function. Example:

def canBeReachedByStackManipulations(stackInput, expOutput):
    # ...
    return outputIndex == len(expOutput)

assert canBeReachedByStackManipulations([1,2,3,4,5], [4,5,3,2,1]) == True
assert canBeReachedByStackManipulations([1,2,3,4,5], [4,3,5,1,2]) == False

Ta-da, your whole program works without needing manual commenting-and-uncommenting! And as a bonus, you've gotten started on writing unit tests for your function.

By the way, I called the parameters stackInput and expOutput because that's what you did; but in practice I would call them input and output.

i = 0
while i < (len(stackInput)):
    stack.append(stackInput[i])
    i += 1

First, (len(stackInput)) is a silly way to write len(stackInput).

Second, you should learn about for-loops. What you wrote is equivalent to

for value in stackInput:
    stack.append(value)

and if you actually needed the i for some reason, you could have written

for i, value in enumerate(stackInput):

It's strange that you call your output index outputIndex but you call your input index i. Your readers will appreciate it if you keep symmetry as much as possible: write inputIndex and outputIndex, or else write i and j, but don't mix and match like that.

result appears to be unused. This is especially obvious once you start using functions, because then it becomes an unused local variable, and there are plenty of tools out there (e.g. pyflakes or pep8) which will "lint" your code for unused variables and other trivial mistakes. You should get in the habit of using one of these linters and fixing all the issues it finds, even before you run your code for the first time.

Finally, here's your bug! (Remember how I said I thought your code was correct? Well, I did...)

assert canBeReachedByStackManipulations([1,2,3], [1,2,3]) == True

Traceback (most recent call last):
  File "x.py", line 17, in <module>
    assert canBeReachedByStackManipulations([1,2,3], [1,2,3]) == True
  File "x.py", line 10, in canBeReachedByStackManipulations
    while outputIndex < len(expOutput) and stack[-1] == expOutput[outputIndex]:
IndexError: list index out of range


Functions
Always write code as functions. Even when its just an example, writing code as a function gives it a name, and make you think in terms of that name.
Functions should be as simple as possible doing one thing only. (see rewrite)
Review

USE SEMICOLONS!!!
Don't add code that is redundant or superfluous. Eg  var secondPlace = null can be var secondPlace.
Keep it DRY. (Don't Repeat Yourself). You have a lot of repeated code that does similar or the same. Using function will reduce a lot of repeated code.
Use constants to define magic values. (see rewrite)
Use an Array to hold lists of strings then use Array.join to join them using the delimiter (see rewrite)
Use appropriate names. Names define the abstractions you use, poor naming make code harder to understand especially when a single abstract concept gets many names, or the same name represent multiple abstractions.

points As records should be results
key could be id.
amount could be score

Rewrite
Rewrite is just an example as there are many ways to do this.
Functions
The rewrite breaks the task into 3 parts.

groupByScore groups by score. Using a Map indexed by score to hold arrays of ids with each score. Returns the groups as the Map
sortByScore Takes the grouped results and sorts by score returning an array
resultsByPlace Takes an array of grouped results and returning an array of strings each containing the place, id, and score.

Constants
There are two constants that remove magic values from the code and moves them to one place at the top of the code.
One of the constants is defined as a function score2Str and created the string eg " has 1 point"
Util functions
Common tasks can be written as utility functions. These function can be part of a library of functions you can use within other projects. There is one Util function pluralize that adds a "s" when a value is not != 1. It is defined as a tagged template and can be used as a tagged template
pluralize` point${score}`

Or called as a function
pluralize([` point`], score)

As modules
Thus we get the code as
File strings/utils.jsm
const pluralize = (strs, value) => strs[0] + (value != 1 ? "s" : "") + (strs[1] ? strs[1]: "");
export {pluralize};

File studentResults.jsm
import {pluralize} from "./strings/utils.jsm";

const PLACINGS = ":First Place: ,:Second Place: ,:Thrid Place: ".split(",");
const score2Str = score => " has " + score +  pluralize` point${score}`;

function groupByScore(students) {
    const scoreGroups = new Map();
    Object.entries(students).forEach(([id, score]) => {
        const group = scoreGroups.get(score);
        if (group) { group.push(id) }
        else { scoreGroups.set(score, [id]) }
    });
    return scoreGroups;
}
function sortByScore(scoreGroups) {
    return [...scoreGroups.entries()].sort((gA, gB) => gB[0] - gA[0]);
}
function resultsByPlace(sorted, cats = PLACINGS, scoreStr = score2Str) {
    var idx = 0;
    const results = [];
    for (const [score, group] of sorted) {
        const cat = idx < cats.length ? cats[idx ++] : (idx ++, "");
        results.push(...group.map(id => cat + id + scoreStr(score)));
    }
    return results;
}
export {groupByScore, sortByScore, resultsByPlace};

As running example.
As CodeReview snippets do not support modules below is a working example compatible with CodeReview snippets.
Code

const pluralize = (strs, value) => strs[0] + (value != 1 ? "s" : "") + (strs[1] ? strs[1]: "");
const tag = (tag, props = {}) => Object.assign(document.createElement(tag), props);
const append = (par, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), par);

// Rewrite
const studentScores = {'Adam': 3, 'Bill': 5,'Cindy': 4, 'Dafney': 5, 'Eric': 4, 'Fred': 5, 'Graham': 4, 'Hillary': 4, 'Ian': 3, 'Jill': 1, 'Kev': 0};
const PLACINGS = ":First Place: ,:Second Place: ,:Thrid Place: ".split(",");
const score2Str = score => " has " + score +  pluralize` point${score}`;

const results = resultsByPlace(sortByScore(groupByScore(studentScores)));
append(document.body, ...results.map(result => tag("div",{textContent: result})));
function groupByScore(students) {
    const scoreGroups = new Map();
    Object.entries(students).forEach(([id, score]) => {
        const group = scoreGroups.get(score);
        if (group) { group.push(id) }
        else { scoreGroups.set(score, [id]) }
    });
    return scoreGroups;
}
function sortByScore(scoreGroups) {
    return [...scoreGroups.entries()].sort((gA, gB) => gB[0] - gA[0]);
}
function resultsByPlace(sorted, cats = PLACINGS) {
    var idx = 0;
    const results = [];
    for (const [score, group] of sorted) {
        const cat = idx < cats.length ? cats[idx ++] : (idx ++, "");
        results.push(...group.map(id => cat + id + score2Str(score)));
    }
    return results;
}


To answer your question, to me this is an illegitimate use of ref on a value type parameter.

Here's why:

1) Legit usages of ref are when you need to keep track the value of ref parameter or when passing the value is expensive. e.g. when using recursion to traverse a tree and you need to keep track of its depth.

Node<T> FindNode(T root, int nodeValue, ref int depth);

2) The code by the Solution Architect looks confusing and weird because it should be using out parameters instead (not to mention that it smells and looks like it deserves some refactoring).

Unlike ref params, out params need not be initialized prior being passed; which is why returnedOptionSetStringValue and returnedInt are being initialized.

For further reading:
http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx
https://stackoverflow.com/questions/1516876/when-to-use-ref-vs-out


Multithreaded telnet chat server in Java

I scanned the code of Server 3 times, looking for where something is added to handlers. Because that's where I expected it.
I thought the code might be broken or that sendAll is an unused method, because handlers seems always empty.
Finally I found that it's the MessageHandler instances that use Server.getHandlers(), and append themselves.

Why is MessageHandler aware of the handlers of the server?
MessageHandler doesn't really need to be aware of the collection of handlers in the server, does it?
It doesn't, and therefore shouldn't.
In fact, it would be better if the message handlers were cleanly isolated from each other.

By the same line of reasoning,
why is MessageHandler aware of the Server at all?
It would be better if it wasn't.
If you want to let message handlers interact with the server in some way,
it would be better to create a dedicated interface for that,
and pass an instance of that interface to message handlers.

It's not recommended to start threads from constructors.
It would be better to let Server call .run() on the message handlers right after construction.

Do not nest try blocks within try blocks.
Break up the large try-catch to smaller blocks with minimal code within any try. The nesting will naturally disappear,
and the code will become easier to understand and to debug.

In Java it's recommended to declare class fields at the top, followed by constructors, followed by methods.


Caching 1600 integers and searching from treeSet takes a lot of time

You claim the lookup in the TreeSet takes a long time, why don't you use a HashSet which guarantees constant time instead of the log(n) time of TreeSet.

Also did you profile your code to verify that it is the lookup that is taking so much time? And that it isn't something else?


If you know exactly which radio button you are interested in, then you should prefer to select it by ID, for performance.  Presumably, your radio buttons will be part of a group with the same name, so it would be more conventional to select the elements by the name instead of by a class.

If you have to conditionally call .show() and .hide(), you can use .toggle().

Avoid hard-coding hide() as the initial state.  It would be better to have the "Hide" radio button marked as checked in the HTML, then let the JavaScript follow suit.  To bind an event handler and execute it right away, you could use .trigger(), but note that triggering the 'click' event also toggles the radio state, so you'll want to make a separate 'init-post-format' event type.

$(function() {
    $('input[name=post-format]').on('click init-post-format', function() {
        $('#gallery-box').toggle($('#post-format-gallery').prop('checked'));
    }).trigger('init-post-format');
});

<input type="radio" name="post-format" id="post-format-gallery">Show gallery
<input type="radio" name="post-format" checked>Hide gallery

The Gallery


I think the key thing you are missing isn't a better pow function.  The problem is that you are iterating d times without checking whether you have surpassed l.  Notice that for the lowest c of 1, you are multiplying by 2 every loop.  The maximum l is 1000000000 which is less than 2^30.  Therefore the max number of loops you will ever need is 30.

If you simply checked every loop:

if (x >= l)
    break;

then you limit your loop to 30 iterations instead of 1000000000 iterations.


Getting the value of a custom attribute from an enum

Make it general purpose using generics.

Though I'd strongly suggest you rename your attribute to follow .NET guidelines.  It should always be in the form AttributeNameAttribute.  Enum values should be in CamelCase.  And it is common to name classes containing extension methods to be named the same as the class it is extending followed by Extensions.

Otherwise, that's pretty much how you'd get custom attributes of a field.

public static class EnumExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        return type.GetField(name) // I prefer to get attributes this way
            .GetCustomAttributes(false)
            .OfType<TAttribute>()
            .SingleOrDefault();
    }
}

public class PlanetInfoAttribute : Attribute
{
    internal PlanetInfoAttribute(double mass, double radius)
    {
        this.Mass = mass;
        this.Radius = radius;
    }
    public double Mass { get; private set; }
    public double Radius { get; private set; }
}

public enum Planet
{
    [PlanetInfo(3.303e+23, 2.43970e6)]  Mecury,
    [PlanetInfo(4.869e+24, 6.05180e6)]  Venus,
    [PlanetInfo(5.976e+24, 6.37814e6)]  Earth,
    [PlanetInfo(6.421e+23, 3.39720e6)]  Mars,
    [PlanetInfo(1.900e+27, 7.14920e7)]  Jupiter,
    [PlanetInfo(5.688e+26, 6.02680e7)]  Saturn,
    [PlanetInfo(8.686e+25, 2.55590e7)]  Uranus,
    [PlanetInfo(1.024e+26, 2.47460e7)]  Neptune,
    [PlanetInfo(1.270e+22, 1.13700e6)]  Pluto,
}

public static class PlanetExtensions
{
    public static double GetSurfaceGravity(this Planet p)
    {
        var attr = p.GetAttribute<PlanetInfoAttribute>();
        return G * attr.Mass / (attr.Radius * attr.Radius);
    }

    public static double GetSurfaceWeight(this Planet p, double otherMass)
    {
        return otherMass * p.GetSurfaceGravity();
    }

    public const double G = 6.67300E-11;
}

It should be pointed out that there are methods to retrieve custom attributes in the framework now as of .Net 4.5. See the CustomAttributeExtensions class. This should simplify the extension method a bit. It might be worth changing the name of the extension to GetCustomAttribute() as well since it will always be a custom attribute.

public static class EnumExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        return type.GetField(name) // I prefer to get attributes this way
            .GetCustomAttribute<TAttribute>();
    }
}


Removing duplicate hashes in an array while keeping count of the times the hash was present

Does it have to be an Array? I.e. is the order important?

If not, then there is actually a data structure that does exactly what you want: the multiset. A multiset is just like a set, except that its elements have a multiplicity. In other words, a set can tell you whether or not an element is a member, a multiset in addition can tell you how often it is a member.

Basically, if you use a multiset, you will not have to do anything, since the multiset keeps track of the multiplicity (i.e. your quantity) for you.

There is no multiset in the Ruby core library or standard library, but there are a couple of third-party libraries and gems. I'll just grab one randomly, it doesn't really matter which one; their APIs are fairly similar.

require 'multiset'

price_params_items = %w[item2 item1 item3 item2 item3 item3]

result = Multiset[*price_params_items]
#=> #<Multiset:#2 "item2", #1 "item1", #3 "item3">

And that's it! You might ask yourself, where is the algorithm gone? That is a general property of programming: if you find the right data structure(s), the algorithm(s) become(s) much simpler, or in this case, even vanishes completely.

Unfortunately, for this specific implementation of multiset, there is no direct way to retrieve the multiplicity of an element, but you can convert it to a hash, and then you get what you need:

result.to_hash
#=> { "item2" => 2, "item1" => 1, "item3" => 3 }


Automatically implement operator+ using CRTP

Missing header
I had to #include <utility> to get a definition for std::move().
Don't delete your destructors
You didn't show us your tests, but I struggled to get my obvious code to compile.  Part of the reason was the deleted constructors; I changed the default constructor to protected and made the copy/move constructors to protected and = default, and then I was able to inherit without having to explicitly write copy/move construct/assign in my subclass:
struct Test : public Sumable<Test>
{
    int i;
    Test(int i) : i(i) {}
    Test& operator+=(const Test& t) { i += t.i; return *this; }
};

There's no need to move() when returning
I know the question is tagged C++11, but even there, any benefit is questionable (and particularly unlikely to exist when the function is inlined).  When you move the code to a more recent standard, it's actively harmful.
Pass by value instead of copying from a reference
If you can insist on the usual x + y == y + x (which seems to be assumed already, given the third and fourth methods, which compute rhs += *this), then you can pass rhs by value (since we need to copy one of the arguments), which will be move-constructed as and when appropriate:
template<class T>
inline T Sumable<T>::operator+(T rhs) const
{
    return rhs += *static_cast<const T*>(this);
}

That's now one method instead of four.
N.B. I had to introduce the static_cast there, as your code wouldn't compile with GCC 8.0 without it.
Consider free functions
Inheritance isn't necessarily the best solution to everything in C++.  You may be better writing free functions instead (in the same namespace as your classes, or in a specific includable namespace, along the lines of std::rel_ops).
Here's a start, including a basic test:
#include <type_traits>

namespace arithmetic_ops
{
    template<typename T, typename U>
    auto operator+(T t, U&& u)
        -> typename std::remove_reference<decltype(t+=u)>::type
    {
        return t += u;
    }

    template<typename T, typename U>
    auto operator+(T&& t, U u)
        -> typename std::enable_if<!std::is_assignable<T,U>::value,
                                   decltype(operator+(u,t))>::type
    {
        return u + t;
    }
}

namespace test {
    struct Test
    {
        int i;
        Test(int i) : i(i) {}
        Test& operator+=(const Test& t) { i += t.i; return *this; }
    };
}

int main()
{
    using namespace arithmetic_ops;

    test::Test a(4);
    test::Test b(-4);
    return (0 + a + b + 0).i;
}

I've used forwarding references above for the non-copied argument - that allows us to have only one method for the class-first case (the second version being an override for cases such as 0 + a where the first argument must be converted).
The enable_if avoids ambiguity when t + u and u + t are both possible.
The ::type and ::value members get shortened from C++14, with _t and _v suffixes to the names (e.g. std::remove_reference_t<decltype(t+=u)> and std::enable_if_t<!std::is_assignable_v<T,U>, decltype(operator+(u,t))>.
a and/or b can be made const in this test without breaking it.


You could still use options_for_select without much hassle:

<%= options_for_select (0..2).map { |i| [show_budget_mode(i), i] }, params[:current_budget_mode].to_i %>

Of course, I'd recommend creating the array in the controller or a helper, rather than the view. The view should ideally do as little logic as possible.

Alternatively, you could use content_tag just the keep the code cleaner:

<% (0..2).each do |i| %>
  <%= content_tag :option, show_budget_mode(i), selected: params[:current_budget_mode].to_i == i %>
<% end %>

Again, I'd recommend moving stuff to the controller. Even a current_budget_mode helper method would help clean things up:

class SomeController < ActionController
  helper_method :current_budget_mode, :budget_modes

  def current_budget_mode
    params[:current_budget_mode].to_i
  end

  def budget_modes
    (0..2).to_a
  end
end

which would clean up the view:

<% budget_modes.each do |i| %>
  <%= content_tag :option, show_budget_mode(i), selected: current_budget_mode == i %>
<% end %>

or

<%= options_for_select budget_modes.map { |i| [show_budget_mode(i), i] }, current_budget_mode %>


Looks good to me. Only thing I would say is:

The accessor methods (get / set) in Point3D are unnecessary as they don't do any processing or restrict any access. The class would be better suited to have simple, public x, y, z properties.
I don't see the purpose of the Geometry3D class. Maybe it's because I don't know much about your intentions or programming for 3d, but looks like things would be more straight-forward if indices and vertices properties were directly on Primitive3D. If it make sense to separate them off because they're processed as a pair by other parts of your program, you might also consider creating a IGeometry3D interface, which the Primitive3D class can implement. This would prevent there from being any ambiguity around ownership. (Not sure if I'm describing my thoughts, clearly.)

I don't think getters and setters are bad for OOP programming. I think they're fantastic. They allow for validation of property values, pre- and post-processing when changing properties, lazy execution of calculations that aren't always necessary, and a lot of other things. Admittedly, you could do all of that with functions. But, to my thinking, an important part of programming is managing complexity and thoughtful use of accessor methods can simplify APIs, which in turn makes life easier (fewer bugs and easier to maintain).


Reducing code for animation of expanding menus

@Bludream came quite close, he noticed the code that was copy pasted, turned the common parts into a function, and then he used a loop to execute everything. The error is in doing both animations on the hover event. This should work:

var mouseLeaveAnimation = { right: -280 };
var mouseEnterAnimation = { right: 0 };

for(var i = 1; i < 6; i++) {

  $('#menu-' + i + ', #menu-event-' + i).hover(function() {
    $('#menu-deco-' + i).stop().animate(mouseEnterAnimation, 'fast');
  }, function() {
    $('#menu-deco-' + i).stop().animate(mouseLeaveAnimation, 'fast');
  });
}


splice mutates the existing array. You wouldn't want to do that as you might not be sure where else the array is being used. You might be expecting values in the array after calling this function, yet this function wiped them off.

Now if you're really sure you want to use splice to remove items in an array, loop backwards. The ending i-- isn't very visible and missing it would mean skipped items.

Lodash isn't necessary as you have the native array.filter. This is unless you still plan to support browsers that don't do ES5 (like IE8 and older).

Your function isn't consistent. The ideal return is an array. But if I put in a falsy value, it returns that value, not an array.

The length check is meaningless. An empty array has the length of 0 which means the loop will never run at all.

Your function is essentially just including all values that aren't null, undefined or have a state of rejected. However, the name is misleading. You never explicitly mention that you're only getting the val properties as a result. You should name your function explicitly, or split off the operations separately.

As noted in the comments (and it wasn't apparent in the code), you're collecting the val property of the filtered items. This can easily be done with an array.map. So after filtering down to the items we do need, we transform the values to the ones we need.

filterNullUndefinedOrRejected: function(oData){
  return !oData ? [] : oData.filter(function(oDatum){
    if(oDatum.state === 'rejected') console.log(oDatum.error);
    return oDatum.val !== null && oDatum.val !== undefined && oDatum.state !== "rejected";
  }).map(function(oData){
    return oData.val;
  });
}


Optimizing Dijkstra on grid Python (Microsoft Interview)

Actual time complexity
As you correctly state, the expected time complexity of Dijkstra's on a square matrix is O(n^2 log n). However, your algorithm has a complexity of at least O(n^4) due to the way you locate the minimum vertex.
for _ in range(n):
    for currj in range(n):
        # <--- executed n^2 times here
        mini,minj = self.minimumVertex(distMat,visited)
        ...

def minimumVertex(self,distMat,visited):
    minVertexi = 0
    minVertexj = 0
    max1 = INT_MAX
    for i in range(n):
        for j in range(n):
            # <--- takes n^2 time
            ...

In fact, the algorithm you implemented isn't purely Dijkstra's, but a blend of Dijkstra's algorithm and Floyd's algorithm.
You should read through the links above, particularly the Pseudocode sections to understand how each of the algorithms works, and the parts that you're mixing up.
Dijkstra's algorithm
The key data structure which allows Dijkstra's algorithm to work in O(n^2 log n) time is a priority queue which allows you to insert elements and remove the top element in O(log n) time.
This data structure is commonly implemented using a binary heap, and has a standard implementation in Python as the heapq library.
You should adapt your code to use this data structure instead of the distance table as shown below.
It is important that the first field of the tuple is the distance, since this determines the sorting.
def minimumCostPath(self, grid):
    # definitions of n, visited, drow, dcol

    queue = [(grid[0][0], 0, 0)]
    while queue:
        dist, i, j = heapq.heappop(queue)

        if visited[i][j]:
            continue
        visited[i][j] = True

        if i == j == n - 1:
            return dist

        for k in range(len(drow)):
            ni = i + drow[k]
            nj = j + dcol[k]
            if 0 <= ni < n and 0 <= nj < n:
                heapq.heappush(queue, (dist + grid[ni][nj], ni, nj))

    assert False, "queue is exhausted but we haven't reached the destination yet"

Benchmarking surprise
After writing all of this, I decided to quantify the improvement by benchmarking.
This is the code I used to see how my implementation compares against the original.
if __name__ == "__main__":
    import time
    N = 100
    grid = [[j for _ in range(N)] for j in range(N)]
    solver = Solution()

    start = time.time()
    print(solver.minimumCostPath(grid))
    end = time.time()
    print(f"Solved grid with size {N} in {1000*(end - start):.3f}ms")

To my surprise, your version was actually faster, but more importantly it gave incorrect results.

My logic is alright

No, it's not.
The issue is the usage of n in the minimumVertex function. Because you define n = 4 as a global, this value is used instead of the actual size of the grid. This makes your algorithm appear fast, but actually be incorrect for n > 4.
Conclusion
As it turns out, while the algorithm you (I imagine) intended to implement is O(n^4), your code was actually O(n^2) all along. If this really resulted in TLE, Python is not going to be able to handle this question.
What I find much more likely is that your code failed due to an incorrect response - using the correct implementation of Dijkstra's above is likely to fix this.


Thread safe static collection, is this code safe

No, it's not safe because you're locking only when writing. You prevent multiple writings to occur simultaneously but:

Caller might call KeyExists() in the middle of Insert(), in this case:

data[partition][key] might be not null but still empty.
data or data[partition] might be in an intermediate invalid internal state.

If you add a Delete() function then reading may go through the same indeterminate states.
When calling Get() you can go through the same indeterminate states as above, plus if you add Delete() then you might be in the middle of that (also Delete() might be called after KeyExists() and before Get()).

That said let's see few other improvments you can make:

Calling ContainsKey() and then searching the value in the dictionary is pretty inefficient because search is done twice. There is a TryGetValue() method for this:

When you  have an else section you may want to keep the if condition positive, negation is a small ! symbol which may be unnoticed.

with dictionary[key] = value you do not need to call ContainsKey(), that check is already done efficiently inside the setter.

In code (C#7, if earlier version you can't use out var and sub has to be declared before):

public static void Insert(string partition, string key, object value)
{
    lock (locker)
    {
        if (data.TryGetValue(partition, out var sub))
        {
            sub[key] = value;
        }
        else
        {
            sub = new Dictionary<string, object>();
            sub.Add(key, value);
            data.Add(partition, sub);
        }
    }
}

Now add locking also in the functions to read from the dictionary and you're almost done.

You do not validate parameters. I don't know if for your usage scenarios a null value (or an empty string) for partition, key and values are allowed or not. If not then you must validate your inputs. Something as simple as:

if (partition == null)
    throw new ArgumentNullException(nameof(partition));

if (partition.Length == 0)
    throw new ArgumentException("Partition cannot be an empty string", nameof(partition));

What about a string made of spaces? In that case you might change second check to:

if (String.IsNullOrWhiteSpace(partition))
    throw new ArgumentException("Partition cannot be...", nameof(partition));

Now you can consider if Monitor (what's used by lock) is the most appropriate synchronization mechanism for your cache. If you expect multiple concurrent reads and (after an initial period) very few writes then a ReadWriterLockSlim may give you much much better performance. Profile.

I left these points to the end but they're actually the first things you should consider.

What about testing? Static methods are a nightmare for testing (if you want to replace them with something else at calling point). You may use a default singleton instance (not the perfect thing to do but better than nothing).

Your class has nothing of a cache. It's a sort of MultiMap but it has nothing to do with a cache. What I'd do? Design a not thread-safe MultiMultiMap<TKeyOuter, TKeyInner, TValue> (eventually considering to implement ILookup) which I might reuse somewhere else (even if the standard MultiMap<TKey, TValue> is probably much more common).

Now I can design a thread-safe access class around it (call it cache if you want).

Now you should start putting some caching logic inside this class, in this moment you have everything at calling point (because CacheService has too few responsibilities). What about:

A method which accepts a Func<object> instead of object itself?
A method to clear the cache.
A method to set an expiration for each item.
A method to limit the memory size used for caching.

Then you might want to abstract cache storage (memory in this case) from cache interface. What if objects you're constructing are pretty huge and expensive to build? Maybe switching to disk storage is still better than re-build them (for example if they come from network data...). Move interface to a base class (or...an interface) and derive this memory cache from that.

Did you consider to use System.Runtime.Caching.MemoryCache instead?


You have an actual error in your code:

$ python test.py
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    ('Order Pizza', order_pizza),
NameError: name 'order_pizza' is not defined

You need to define menu_entries after creating the things it refers to.

Some notes:

All Python code could benefit from being run through at least one linter such as flake8 or pycodestyle. Nothing springs out at me except possibly the indentation of menu_entries, but it's worth a check.
Generally, names don't need to repeat anything which is understood from context. So def menu(menu_title, menu_entries): could be easier written as def menu(title, entries):
You always add one to mpoint - a cleaner solution would be to mpoint = 1 and continue from there. If mpoint was used for indexing into an array that would be different, but it's really only for presentation.
When reading the code top to bottom I should be able to understand what a name means the first time I encounter it. mpoint should be renamed to what it is (maybe menu_index?).
For consistency (and to write more idiomatic code) the strings in all your print statements should be formatted.
This is a prime example for code which could be made object oriented - obvious classes include Menu, MenuEntry and Order.
Setting task = None and then checking if it's None to check whether you should continue is redundant - you can just continue immediately.
size is unused in order_pizza, so it should be removed.


Median of two sorted arrays (optimal runtime)

I believe the test cases are not generated randomly. Your code will fail on almost all cases if the cases are generated in a random way.
For instance,
if array A is [0, 10000], and array B contains an arbitrary number of elements with arbitrary values from (0, 10000) except 5000, your code will fail. It is not relevant if the test cases contain negative numbers or not.


I feel that both the mapping code and the fetch code could be more efficient by better utilizing LINQ projection.

more efficient yes but this time without linq.

if (serverDictionary.ContainsKey(applicationName))
    serverDictionary[applicationName].Add(server);
else
    serverDictionary.Add(applicationName, new List<Server> { server });

This is a very inconvenient way of adding new items to your dictionary because you are accessing it twice for each new item. With TryGetValue you can do the same with only one access to it. This means that if you could retrieve the value then you already have and it's ready to use, there's no need to use the indexer anymore. If however it's not there, then you just add it.

if (serverDictionary.TryGetValue(applicationName, out List<Server> servers))
{
    servers.Add(server);
}
else
{
    serverDictionary[applicationName] = new List<Server> { server };
}

_appServers.Where(pair => pair.Key.EqualsIgnoreCase(applicationName))
    .ForEach(pair => servers.AddRange(pair.Value));

This might be super inefficient. If you use a dictionary then don't use linq if you don't have to. For fetching you can use the TryGetValue method agian:

return
    serverDictionary.TryGetValue(applicationName, out List<Server> servers)
        ? servers
        : Enumerable.Empty<Server>();

Retrieving an item with TryGetValue means it's an O(1) operation whereas the same done with the original query means that the entire dictionary needs to be searched which means O(n). If you need to return a copy of the server list the you might use linq for it and call .ToList() on the servers.

There is one more thing about the linq query. You search for the key by ignoring the case. If you have multiple names but with different case then the resulting list will contain items of all those keys. Is this really what you want? The Where won't stop at the first match.

I don't know how you create the dictionary but if you want to ignore the case of the key you should initialize the dictionary appropriately by specifying the key comparer:

serverDictionary = new Dictionary<string, List<Server>>(StringComparer.OrdinalIgnoreCase);

Now the keys is case-insensitive also during adding.


Calculating if vehicle's mileage is in service window

This seems overly complex or not complex enough.  If the fuel filter is replaced at 12,500, then the next service window should be from 25,000 to 30,000, not 27,500 to 32,500.

If the fuel filter is not replaced by 17,500, it doesn't go back into service either.  It still needs replaced at 18,000, etc.

$current_mileage = 27500;
$last_service = 12500;
$service_interval = 15000;
$half_window = 2500;

$is_due = $current_mileage + $half_window <= $last_service + $service_interval;

$is_overdue = $current_mileage > $last_service + $service_interval + $half_window;

This seems to better reflect how service windows work in practice.


C# basic dictionary (hash) implementation

There are several (major) problems with this class:

Keys that contain a : character cannot be used to look up their value, and values that contain a : character are only partially returned. Also, this class cannot handle null values (it returns an empty string instead). Don't mash keys and values together into a single value, using a key-value object instead (such as KeyValuePair<TKey, TValue>).
Keys that start with anything but [a-zA-Z] cause an IndexOutOfRangeException. This is not documented anywhere, and there's no obvious reason why such keys shouldn't be allowed (phone books aren't limited to countries with a Latin alphabet, after all). Why not use the modulus of the hash value and the number of buckets?
Non-existing keys produce a 'magic' value, which isn't documented anywhere. Moreover, a caller won't be able to distinguish between a non-existing key and an actual (valid) "Not found!" value. You may want to throw an exception instead. Alternately, you could provide a TryGetValue method instead.
Overwriting the value for an existing key is not possible. Your class will store both values (why?), but lookups will continue to return the first value. I would expect the new entry to replace the earlier one. If that's not the intended behavior, then I'd expect that to be documented, and an appropriate exception to be thrown.
Your hash function is poorly chosen. Ideally, you'll want to spread entries across buckets as evenly as possible, so each lookup will take roughly the same amount of time on average. If items are concentrated in only a few buckets (some characters are more frequently used than others) then lookups for such keys will be slower. Why not use key.GetHashCode() instead, or let the caller provide a hashing method in the constructor?
Using a fixed number of buckets means that lookup times are essentially \$O(n)\$, not \$O(1)\$. Locating a bucket takes constant time, while searching through multiple entries in a bucket takes linear time, so you'll want to limit the number of entries per bucket (ideally to 1). That requires some kind of resizing strategy.

Other minor issues:

By calling Split(':') and HashFunction multiple times you're doing the same work repeatedly. Just call them once and store the result in a variable.
Some names could be clarified a bit: MyHashTable or MyHashMap instead of MyHash, and buckets instead of storage.
Going for a generic implementation would not only be of more practical use, it would also have helped you to avoid some of the above problems: you wouldn't have been able to mash keys and values together or to use a sub-optimal leading-character 'hash'.


Duplicate IDs are invalid HTML You have multiple elements of id='input', which is not permitted in HTML. If multiple elements need a particular attribute, use classes instead. IDs should be reserved for elements that are going to be absolutely unique on a page (or, you could also consider not using IDs at all, since they implicitly create global variables, which can lead to hard-to-understand bugs).
Input iteration You put the input collection into a variable named items, which is good: const items = document.querySelectorAll('#input'); but then you pass the collection to a function whose parameter is named item, and you do:
for (let i = 0; i < item.length; i++) {
  if (item[i].value) { // Check if contains value
    // a long block
  }

A reader of the code wouldn't expect an individual item to have a length and a numeric index. How about calling the parameter items instead - or, even better, inputs?

Rather than iterate over the indicies of each element, since you don't actually care about the indicies, but only about the underlying elements, it might be preferable to use for..of instead, so you never have to reference the indicies.

Nested indentation can be difficult to read. Instead of a long block inside an if statement, consider continuing the loop early instead:

for (const input of inputs) {
  if (!input.value) {
    continue;
  }
  // put validation code here

Or put it into a function:
for (const input of inputs) {
  if (input.value) {
    validateInput(input);
  }

Check validity on blur, not on click. Your current implementation will show errors only after the user has inputted something invalid, focused away, then clicked on the input box again. Better to inform them immediately, as soon as a box is de-focused.
Check validity even if input is empty, since errors may be displayed - if the input is empty, you'll want to clear the error. You could also consider clearing errors when an input is focused (so that errors are only displayed when an input currently isn't active).
Error text is always the same, so don't set it via the JS - put it into the HTML, and hide the error on pageload.
Use the case-insensitive flag in regular expressions instead of repeating both the capital and lowercase versions, eg: /^[a-z]$/i
Wording Contact with us would be better as Contact us
DRY input navigation There are a few sources of repetitiveness in the code:

Separate class names for each input, requiring iteration through each class name in the switch
Separate error class names for each input
Separate logic for each class name

You can make this better by:

Use an object indexed by the name attribute of each input, whose values are regular expressions to test the values against
Navigate to the input's adjacent error element with nextElementSibling instead of having separate error classes

For the email, you can use a regular expression so that the validation is of the same shape as for the other inputs.
const validators = {
  name: /^[a-z]$/i,
  surname: /^[a-z]$/i,
  email: /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/,
  phone: /^\d{5,}$/,
};
for (const input of document.querySelectorAll('#input')) {
  input.addEventListener('blur', () => {
    checkValidity(input);
  });
}
const checkValidity = (input) => {
  const isBad = validators[input.name].test(input.value);
  input.nextElementSibling.classList.toggle('p-hidden', isBad);
};

That's all you need.

'use strict';

const validators = {
  name: /^[a-z]+$/i,
  surname: /^[a-z]+$/i,
  email: /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/,
  phone: /^\d{5,}$/,
};
for (const input of document.querySelectorAll('.wrapper input')) {
  input.addEventListener('blur', () => {
    checkValidity(input);
  });
}
const checkValidity = (input) => {
  const isBad = validators[input.name].test(input.value);
  input.nextElementSibling.classList.toggle('p-hidden', isBad);
};
.p-hidden {
  display: none;
}
<form action="#" class="form">

Contact us

      <input name="name" placeholder="First name *" required>

Invalid data

      <input name="surname" placeholder="Surname">

Invalid data

      <input name="email" placeholder="E-mail *" required>

Invalid data

      <input name="phone" placeholder="Phone number">

Invalid data

    <textarea name="message" rows="8" cols="80" placeholder="Message *" required></textarea>
    <button href="#" class="btn">Submit</button>

</form>

The email regex is probably more complicated than it needs to be, you could write a much more easy-to-read one with only a handful of characters that works just as well in 99% of situations, if you wanted.
Another option would be to remove all the JavaScript, and use the pattern attribute and type="email" in the HTML instead, letting the browser inform the user of invalid inputs:

<form action="#" class="form">

Contact us

      <input name="name" placeholder="First name *" required pattern="[a-zA-z]+">

      <input name="surname" placeholder="Surname" pattern="[a-zA-z]+">

      <input name="email" placeholder="E-mail *" required type="email">

      <input name="phone" placeholder="Phone number" pattern="\d+{5,}">

    <textarea name="message" rows="8" cols="80" placeholder="Message *" required></textarea>
    <button href="#" class="btn">Submit</button>

</form>

Result:


I guess your logic is fine. I just don't like what you do with the variable difference. You could return directly instead and save the variable and two lines.

In case the overflow s probable, you're wasting a lot of time because of the exception. You could do something like

long result = minuend - subtrahend;
return minuend >= 0 | (minuend ^ result) >= 0 ? result : Long.MIN_VALUE;

instead (condition adapted from LongMath.checkedSubtract). You could test it both against your original implementation (e.g. with a few random values) and against some known cases.

As suggested by user1071840, a simpler condition may be used:

return Long.MIN_VALUE + subtrahend > minuend ? minuend - subtrahend : Long.MIN_VALUE;

Actually, rolfl's condition is even simpler.


Nice use of the Prime Number Theorem there. However, there are some issues with your code as is:

The name nth does not convey the meaning of the function.
A return statement is used instead of an expression at the end of the function.
The composite marking can start at prime * prime, as all smaller composites are already marked by previous primes.
The \$\left(2^{32}-1\right)\text{th}\$ prime is larger than \$2^{32}-1\$, but less than \$2^{64}-1\$, so u64 is a better return type.
The function will use a lot of memory if we use <u32>::max_value() as input.
The first (\$1\text{st}\$) prime number \$p_1\$ is \$2\$, but your code returns \$3\$ on nth(1).
The behaviour is not documented at the moment, as the function is missing all documentation.
The function doesn't necessarily return a prime number.

The last issue is the greatest one, to be honest. If I use a nth_prime function, I expect the function to return a prime number and only a prime number, whereas <u32>::max_value() is a composite. If it's possible that your function does not return a valid result, use Option or Result instead:

// https://play.rust-lang.org/?gist=4d6abc78a8c0d205da57a17c02201d7c&version=stable&mode=release&edition=2015

/// Returns the nth prime.
///
/// It uses a sieve internally, with a size of roughly
/// `n * (n.ln() + n.ln().ln()` bytes. As a result, its
/// runtime is also bound loglinear by the upper term.
///
/// # Examples
///
/// ```
/// use <yourcrate>::nth_prime;
///
/// assert_eq!(nth_prime(0), None);
/// assert_eq!(nth_prime(1), Some(2));
/// assert_eq!(nth_prime(2), Some(3));
/// assert_eq!(nth_prime(3), Some(5));
/// ```
///
///
pub fn nth_prime(n: u32) -> Option<u64> {
    if n < 1 {
        return None;
    }

    // The prime counting function is pi(x) which is approximately x/ln(x)
    // A good upper bound for the nth prime is ceil(x * ln(x * ln(x)))
    let x = if n <= 10 { 10.0 } else { n as f64 };
    let limit: usize = (x * (x * (x).ln()).ln()).ceil() as usize;
    let mut sieve = vec![true; limit];
    let mut count = 0;

    // Exceptional case for 0 and 1
    sieve[0] = false;
    sieve[1] = false;

    for prime in 2..limit {
        if !sieve[prime] {
            continue;
        }
        count += 1;
        if count == n {
            return Some(prime as u64);
        }

        for multiple in ((prime * prime)..limit).step_by(prime) {
            sieve[multiple] = false;
        }
    }
    None
}

Note that the documentation's examples show that 0 isn't a viable index for primes, and that nth_prime(1) == Some(2).

Other than that, we can optimize the code a little bit further if we consider 2 as a special case and then step (3..limit).step_by(2), but that makes the code slightly harder to read. There are also several approaches to keep the memory usage limited, but they are harder to achieve.

Other than that, well done, although I'd link to the Prime Number Theorem for the approximation.


Review

Don't use underscores in enum values NotSupported
The enum value with integer value 0 represents its default value; I would make this NotSupported in order to avoid some bias
GetPlatform is a method name; prefer Platform as property name
Since the platform won't change while your program is running, consider using a Lazy to retrieve the platform once.

Don't like if-statements?

Let's first refactor the enum to match aforementioned conventions:

public enum OSPlatform
{
    NotSupported,
    Windows,
    OSX,
    Linux,
}

We could then use a Lazy:

 static readonly Lazy<OSPlatform> platform = new Lazy<OSPlatform>(GetPlatform, true);
 public static OSPlatform Platform => platform.Value;

And refactor the intitial method using a helper generator using a simple ValueTuple to avoid the boiler-plate if-statements.

private static IEnumerable
    <(OSPlatform Platform, RuntimeOSPlatform RuntimePlatform)?> EnumeratePlatforms()
{
    yield return (OSPlatform.Windows, RuntimeOSPlatform.Windows);
    yield return (OSPlatform.OSX, RuntimeOSPlatform.OSX);
    yield return (OSPlatform.Linux, RuntimeOSPlatform.Linux);
}

private static OSPlatform GetPlatform()
{
    return EnumeratePlatforms().FirstOrDefault(p
       => RuntimeInformation.IsOSPlatform(p.Value.RuntimePlatform))?.Platform ?? default;
}

I've created an alias to avoid redundant namespace code:

using RuntimeOSPlatform = System.Runtime.InteropServices.OSPlatform;

If you want to have some fun, you could refactor this solution to use Expression and some reflection to avoid creating hard-coded tuples.


Here are some things that may help you improve your code.

Strive for portable code

Several of the features of this code are either platform-specific or compiler-specific or both.  Specifically, #include <conio.h>, and #include "stdafx.h" both non-standard.  Further, neither are actually used so I would strongly recommend omitting them.

Prefer to avoid using new and delete directly

In modern C++, it's usually better to avoid explicit calls to new and delete.  In particular, it seems that the goal of this program is to create the perlinnoise matrix.  It is not clear whether you're intending to also use the noise array or if it's just a byproduct of the production of the perlinnoise array.   In any case, use of raw new and delete tends to lead to the problem mentioned in the next suggestion.

Consider using a better random number generator

You are currently using

noise[i][j] = (float)rand() / RAND_MAX;

However, that's the old C way to do things.  better solution, if your compiler and library supports it, would be to use the C++11 `std::uniform_real_distribution.  It looks complex, but it's actually pretty easy to use, as I'll demonstrate below.

Don't leak memory

If you use new and delete directly, you must take care to make sure they match in every instance.  This is quite easy to get wrong, and in fact, this code gets it wrong.  In particular, the perlin_noise routine leaks memory.  Track how long it takes you to find and fix the problem, and then compare it to the following suggestion.

Use objects

C++ is an object-oriented language and accomodating and encouraging that style of design is one of the key benefits of using C++.  For that reason, and because it makes your program cleaner, easier to maintain, easier to re-use and less prone to error, I'd highly recommend using objects for this program.

Use the Standard Template Library

There is a lot of functionality already available to you if you use the Standard Template Library (STL).  To illustrate this and a number of the previous points, here is a rewrite of your white_noise routine as an object.  First, we need a way to initialize it with random values, and then a way to address individual noise values by index.  This is easily done by deriving a WhiteNoise object from a std::valarray.

struct WhiteNoise : public std::valarray<double>
{
    WhiteNoise(int w, int h) :
        std::valarray<double>(w*h),
        width{w},
        height{h}
    {
        std::mt19937 gen;
        std::uniform_real_distribution<double> dis;
        for (auto &value : *this) {
            value = dis(gen);
        }
    }
    int width;
    int height;
};

Note that there is no explicit call to new or delete and that the width and height are embedded into the object rather than separate quantities.  If you create a similar PerlinNoise object, the main function could look like this:

int main()
{
    const int w = 400;
    const int h = 400;

    WhiteNoise wn(w,h);
    PerlinNoise pn(wn, 8, 0.7);

    // Create a bitmap just so that we have something to look at.
    makePGM(pn, "perlin.pgm");
}

The result: no memory leak and a much shorter, cleaner program (also faster in my testing, but you should test it on your machine).  The makePGM is just a function I wrote to create a bitmap image to visualize the result.


1. Make sure your variable names are both short and to the point, using a parameter called junk is pointless. Also, this could cause conflicts if you ever write other code and import this.

def parse(junk):
    ugly = str(junk)[2:-1]
    lines = ugly.split('\\n')
    return lines

2. urllib is outdated. Unless there is a specific reason you need to use urllib, you should use urllib2. Urllib2 is faster and more simple.

import urllib.request

3. This part looks a bit messy:
webbrowser.open_new_tab(os.path.dirname(os.path.abspath(__file__))+'/cache.html')
Perhaps separate into multiple lines for readability.


batch progress visualization In React.js

The function render() in only supposed to render. It is not supposed to compute some style, set variables, have any logic other than render: (Functions Names Should Say What They Do). This should respect the SRP (Single Responsiblity Principle), as well as another clean code rule: 'A Function Should Do One Thing'.

What could be code smell in your first file:

A unused constructor should not be there at all,
The percentage calculation should be put in a function of its own
The color choice should be placed in a function of its own

What could be code smell in your second file:

A unused constructor should be removed

For both files, you could also add some prop types verifications using the library 'prop_types'.

As for your questions, with short answers:

Not it's not Ok
Depends on what you intend to do!
This article should help you choose: React Functional or Class components ? - even though you can use hooks now as well :)


How could this "complex method" for codeclimate be refactored?

A few things caught my eye:

You don't check whether e.save actually worked. If it fails, you'll have problems down the line.
meeting.meeting_date_end ||= meeting.meeting_date_start
Don't set an attribute on a record you don't "own"! In this case, a meeting object is being passed to the method to be copied - not altered. Use a local variable instead. It could be a nasty surprise to other parts of the code, to find that the meeting's been altered. Treat the meeting as strictly read-only.
Why are some of your meeting's date/time-attributes prefixed with the class name? It's redundant; they're attributes on a Meeting instance, so there's no reason to name them meeting_*. You also prefix event.datetime_start with the type, which isn't Ruby-like or Rails-like either. In both cases, something like starts_at and ends_at would be more than enough. It'd follow the convention set by updated_at and created_at and be immediately recognizable.
Speaking of, why are your meeting's date/time attributes defined in the local timezone? I'd advice you to store everything as UTC, so you don't have to worry about conversion (as you do in your current code). Because timezone conversion always ends up being painful.
e.description = (!meeting.description.blank?) ? meeting.description : ''
The parentheses aren't necessary, but moreover there's the present? method, which does what you want here: The opposite of blank?.
However, you could also just do e.description = meeting.description || '' since blank? triggers on nils and empty strings, but the latter is the default anyway, so you really only want to default in case of nil.
Similarly, this if !meeting.committee.nil? can be written a few other ways:

unless meeting.commitee.nil?
if meeting.commitee.present?
if meeting.commitee

The last one is the simplest and clearest, but all of them are, to my eyes, better than saying "if the committee is not not there"
My biggest concern is that this is a lot of data duplication - seemingly for no reason. Since Event already belongs to a Meeting, why duplicate anything? Everything should be available since you have event.meeting. Duplicating everything doesn't really make sense as long as you have the Meeting record. All you gain is the task of keeping two separate sets of data in sync whenever one changes. To me, this approach doesn't really make sense.

So I'd stick with:

event = meeting.events.create(eventcolor_id: params[:eventcolors_select])

and maybe add some accessor methods (decorators) to Event to give you the correct datetime_start and datetime_end. No need for the method at all.

Semantically, I'd prefer to have it flipped the other way, though: Make a meeting belong_to an event. A calendar event is a pretty generic entity: It can be anything with a time and (optionally) a place. A meeting, meanwhile, is a more specific thing. So to my mind, it'd make more sense to have a meeting attached to a calendar event, rather than the other way around.

Or you can do Single Table Inheritance with Event as the parent class. Or have an even more generic model - or models - the wrap the time and/or place, and have both Event and Meeting refer to that.

Basically, there are many ways to handle this without duplicating data.

Meanwhile, just looking at the code as-is, you can get rid of some lines:

# Note: May raise ActiveRecord::RecordInvalid
def self.create_from_meeting(meeting, eventcolor)
  Event.find_or_initialize_by(meeting_id: meeting.id) do |e|
    # copy all the identically-named attributes
    %w(title location address1 address2 city state zip description).each do |attribute|
      e.send("#{attribute}=", meeting.send(attribute))
    end
    e.datetime_start = Time.zone.local_to_utc(meeting.meeting_date_start)
    e.datetime_end = Time.zone.local_to_utc(meeting.meeting_date_end || meeting.meeting_date_start)
    e.eventcolor_id = eventcolor
    e.save! # raises an exception if it fails
    e.committees << meeting.committee if meeting.committee
  end
end

But it's still not very pretty, just shorter. Again, the main issue is the duplication.


Multiplying and adding big numbers represented with strings

Use the correct functions to convert to types

I think you are using the bitwise | to convert a string to a number:

if ((a | 0) == 0 || (b | 0) == 0) {
    return '0';
}

I think parseInt can show this intent more clearly:

if (parseInt(a) == 0 || parseInt(b) == 0) {
    return '0';
}