1. Don't use \" in string

Go provide a very nice way to handle quote (") in strings:

instead of

fmt.Sprintf("MediaWiki module \"%s\" reported an error: %s (%s)", ...)

you can use

fmt.Sprintf(`MediaWiki module "%s" reported an error: %s (%s)`, ...)

It's easier and nicer to read

2. Use range loop instead of switch

Instead of specifiying behavior for 3 cases ( 0, 1, default), we can use a simple range loop

So this

func (e MediaWikiErrors) Error() string {
    switch len(e) {
    case 0:
        return ""
    case 1:
        return e[0].Error()
    default:
        codes := make([]string, len(e))
        for i, err := range e {
            codes[i] = err.Code
        }
        return fmt.Sprintf("MediaWiki API reported multiple errors: %s", strings.Join(codes, ", "))
    }
}

become simply this:

func (e MediaWikiErrors) Error() (errMsg string) {
    for _, err := range e {
        errMsg += err.Error() + "\n"
    }
    return errMsg
}

I prefer joining errors with a line return (\n) instead of a comma, but it's just my personal taste. Multiple errors would be printed like this:

MediaWiki module "module_1" reported an error: parsing error (3)
MediaWiki module "module_2" reported an error: access denied (22)


For starter, you shouldn't use abreviations for your variables/functions names: perms for permutations, st for string, let for letter, equiv for equivalence_table… You gain nothing doing so, except obfuscating what is going on which impairs readability.

Then I find that your function has a wrong name, as permutations refers more naturally to swapping the order of the letters. I would rather use something along the line of case_swap or character_equivalence. I find these names more descriptive in constructs of the form for word in <function_name>('I got it.').

Now, what about the behaviour of your function when given a string with characters that are not in string.ascii_lowercase or string.ascii_uppercase, as the spaces or the dot in my previous example? You should handle such cases where let is not a key in equivs. And the simplest to do so is to fallback to using only let in such cases: equivs[let] can become equivs.get(let, let).

An other thing, that I particularly like with Python, is how it is simple to write lazy functions. Instead of building whole lists of results and storing them in memory, you can just yield intermediate results as you compute them. And I have the feeling that such function would benefit from being writen as a generator since I believe it will most likely be called to iterate over its result. And to do that without computing a whole bunch of intermediary string before the first usefull result, we can:

use a recursive function to prepend the equivalents of the first letter to the computed equivalents of the rest of the string; or
ask python to generate the cartesian product by providing ourselves a list of equivalent values for each letter.

The recursive function would look like:

def swap_case(sentence, equivalence_table):
    letter, *rest = sentence
    equivalents = equivalence_table.get(letter, letter)
    if not rest:
        yield from equivalents
    else:
        for end in swap_case(rest, equivalence_table):
            for symbol in equivalents:
                yield symbol + end

but recursion has its limits, especially in the number of function calls you can perform. So I would prefer to use the product generator from itertools to leverage fast iteration optimized in C:

import itertools

def swap_case(sentence, equivalence_table):
    equivalent_letters = (equivalence_table.get(l, l) for l in sentence)
    for characters in itertools.product(*equivalent_letters):
        yield ''.join(characters)

Here the join is needed since itertools.product generates lists of values taken from the provided iterables.

You can also sacrifice a bit of readability to continue iterating in C rather than using a for loop in Python by using map to apply ''.join to each list yielded by itertools.product:

def swap_case(sentence, equivalence_table):
    equivalent_letters = (equivalence_table.get(l, l) for l in sentence)
    return map(''.join, itertools.product(*equivalent_letters))

All in all, both version doesn't change the time complexity of the algorithm since you still have to generate the same amount of values. But the memory usage should be drastically lower.

You may also have noted that I changed the signature to include the equivalence table as a parameter. This is twofold:

easier testing as the function does not relly on a global variable;
parametrizable output as we may want some equivalences in some cases but not in others.

And if we want to easily provide various equivalence tables, we should as well write a function that makes it for us. Looking back at how swap_case will handle it, we should provide the equivalent letters as a value for each of the symbols as a key. Let's also provide an option to include/exclude uppercase letter as well:

def build_equivalence_table(use_uppercase=True, **kwargs):
    values = string.ascii_lowercase
    if use_uppercase:
        values = map(''.join, zip(values, string.ascii_uppercase))
    table = dict(zip(string.ascii_lowercase, values))
    for letter, equivalents in kwargs.items():
        table[letter.lower()] += equivalents
    # At this points, keys of `table` are only lowercase letters
    # let's include all the variants as well
    return {variant: group for group in table.values() for variant in group}

Usage being:

>>> build_equivalence_table(a='@4', t='7', l='!1', e='3')
{'p': 'pP', 'k': 'kK', 'r': 'rR', 'V': 'vV', 'U': 'uU', 'I': 'iI', 'i': 'iI', 'J': 'jJ', 'A': 'aA@4', 'n': 'nN', 's': 'sS', 'K': 'kK', 'D': 'dD', '1': 'lL!1', 'j': 'jJ', 'z': 'zZ', 'B': 'bB', 'w': 'wW', 'C': 'cC', 'P': 'pP', 'N': 'nN', 'Y': 'yY', 'G': 'gG', 'g': 'gG', 'q': 'qQ', 'T': 'tT7', 'h': 'hH', 'M': 'mM', '7': 'tT7', '!': 'lL!1', 'F': 'fF', 'd': 'dD', 'X': 'xX', 'l': 'lL!1', 'f': 'fF', 't': 'tT7', 'y': 'yY', 'e': 'eE3', 'x': 'xX', 'v': 'vV', 'b': 'bB', 'H': 'hH', 'Z': 'zZ', 'L': 'lL!1', 'S': 'sS', 'c': 'cC', 'a': 'aA@4', 'Q': 'qQ', '4': 'aA@4', 'W': 'wW', 'E': 'eE3', 'R': 'rR', 'o': 'oO', '@': 'aA@4', 'm': 'mM', '3': 'eE3', 'u': 'uU', 'O': 'oO'}


Grouping filenames by basename and extension

Don't worry about dummy variable names, naming is hard, and it can be fixed up later.

For my solution, there are a number of changes:

code is simplified by having a short inner function
the "yield" operator produces results one at a time, vs a list of results being processed in batch
the original code would process job files multiple times. IE if beer.sh and beer.hin were in a directory, the job would be scanned twice.
a simple test is added; modules added in PEP8 style; documentation; name clarification

source: mglob.py with test

'''
mglob.py -- print job files in directory

TEST USAGE:
    python -m unittest mglob
'''

import glob
import os
import unittest

def find_jobs(path):
    def find_job_paths(root, files, base):
        """
        given a job base filename, list related job files that exist
        """
        JOB_SUFFIXES = ['.sh', '.hin', '.in', '.hout', '.out']
        for suffix in JOB_SUFFIXES:
            newfile = base + suffix
            if newfile in files:
                yield os.path.join(root, newfile)
            else:
                yield None

    for root, dirs, files in os.walk(path):
        # process each file base name once
        bases = set(os.path.splitext(file_)[0]
                    for file_ in files)
        for base in bases:
            job_paths = list(find_job_paths(root, files, base))
            if any(job_paths):
                yield job_paths

class TestFind(unittest.TestCase):
    def test_simple(self):
        result = list(find_jobs('temp'))
        self.assertEquals(
            result, [
                [None, None, 'temp/run2.in', None, 'temp/run2.out'],
                ['temp/run.sh', 'temp/run.hin', None, 'temp/run.hout', None],
            ],
            result)


Writing to a csv file in a customized way using scrapy

I'd like to mention, that there is a special way of making output files in scrapy - item pipelines. So, in order to make it right, you should write your own pipeline (or modify standard one via subclassing).

Also, you does not close the file, once you're done and you keep it open most of the time. The both problems are handled nicely with pipelines.

UPD: Well, you've asked for a better way, there it is. Although, if it's not acceptable for some hard-to-explain reasons (it's understandable), here's the other approach, how to make it better.

Don't leave the file open. There is a method (__del__()) which destroys the spider object. Add the code to close the file before it.
Another one is to store only the filename in the variable and open / close the file each time you write into it.
Another option is to use NoSQL database, which does not need to be opened / closed. And after scraping is done - get the output file from it.
If you have a few values to scrape you can store it in object variable, and then export it before __del__() method.

All the ways above are NOT welcomed by the actual developer community and may lead to serious problem in future. Use them carefully. Sometimes it's easier (in the long run) to read and understand how it really should be done.

Maybe it's the exact case?


Language Features

You are trying to use new C++ language features, but you appear to be using them inefficiently.

This:

std::for_each(URLS.begin(),URLS.end(), [this](const char* url){return this -> DownloadImage(url);});

can be replaced by a simple:

for (auto& url : URLS) DownloadImage(url)

Using auto for method declarations only to specify the return type at the end of the line is confusing.

Memory Management

Rule of 5: a class which needs a custom destructor for dealing with resource (de)allocations, most likely also needs a custom copy constructor, assignment operator and move constructor/assignment operator.

You are creating raw copies of strings only to store raw pointers to the characters. Simply use string.c_str() when you need to pass a raw pointer to the library and let the string class manage the memory.

CURL

Writing to the file via the callback and also asking curl to write the data to a file looks like duplicate work. Any reason for this?

OOP

The class isn't a good example of object-oriented design. The only available public method, Interface, doesn't indicate what it might do. The entire code might have been better off as a single function.


Q1: Sure
Q2: Technically you are not setting a name, and that variable is hence misleading
Q3: You could do that, but I would propose you just send the whole object to the constructor, and let that constructor do the .. constructing ;)

Further notes:

g is a terrible name, Group is a much better one (capital G because this function is a constructor)
Using the jQuery each feels wrong, just go bare metal and use the Array built-ins
Speaking of which getGroupsWithStatus becomes a one-liner with the Array.filter() built-in
The reliance of main() on myGroups is unhealthy, you are treating myGroups as a global, it should be local to main, especially if you are putting querying functions within main
If you are not using a fat arrow syntax function, then you should provide a function name (getGroupsWithStatus = function (status) => getGroupsWithStatus = function queryGroupsWithStatus(status)

This is my counter proposal:

var jsonTmp = '{ "groups": [ { "name": "G1", "status": "inactive" }, { "name": "G2", "status": "active"}, { "name": "G3", "status": "inactive" }] }'

function Group(key, properties) {
    this.key = key;

    properties = properties || {};
    this.name = properties.name;
    this.status = properties.status;
}

function main() {
    this.groups = [];

    this.createGroups = function (json) {
      var data = JSON.parse(json)
      this.groups = data.groups.map( (o,key) => new Group(key,o) );
    }

    this.getGroupsWithStatus = function querygetGroupsWithStatus(status) {
      return this.groups.filter( group => group.status == status  )
    }
}

var myGame = new main();
myGame.createGroups(jsonTmp);
console.log( myGame.getGroupsWithStatus("inactive") );


let private currentValue state = Map.find state.Pointer state.Memory

This won't work correctly if you try to access memory that hasn't been set yet. Doing that should return 0, but will instead throw an exception. You can fix that by using Map.tryFind together with defaultArg:

let private currentValue state = defaultArg (Map.tryFind state.Pointer state.Memory) 0

let m = Map.remove state.Pointer state.Memory
Map.add state.Pointer (op x) m

You don't need to remove before adding the key back in, because add will overwrite the old value. (The documentation isn't clear on that.)

This also means you can make your code more DRY by using currentValue:

let updateMemory =
    Map.add state.Pointer (op (currentValue state)) state.Memory

let rec parsing =

I think that parsing is a weird name for a function, function names should be verbs. Since you're already using parse, if you can't figure out any better name, you could use something like parseInternal or parse'.

| x :: xs when x = '[' ->
    let innerLoop, innerRemaining = parsing xs
    let commands, remaining = parsing innerRemaining
    let remainingCommands, after = parsing remaining
    Loop(innerLoop) :: commands @ remainingCommands, after

This code doesn't make any sense to me. And testing it on Wikipedia's Hello World program gives me incorrect results. Instead, I think it should look like this:

| x :: xs when x = '[' ->
    let innerLoop, innerRemaining = parsing xs
    let commands, remaining = parsing innerRemaining
    Loop(innerLoop) :: commands, remaining

code
|> Seq.toList
|> parsing
|> fst

This means that if you encounter unmatched ], you're going to treat it as the end of the file. Is that the correct behavior?

And thinking about unmatched brackets some more, unmatched [ are automatically closed at the end of the input. Is that correct?

(fun x -> x + 1)

You can shorten this to: ((+) 1).

let private compute bytecode =

I think that bytecode is a misleading name here, since it's not a code composed of bytes, it's an AST.

| Loop(xs) ->
    let nextState = computeProgram state xs
    if currentValue (nextState) = 0 then nextState
    else cmp nextState cmd

This is not correct. Brainfuck loops are equivalent to while loops, not do while loops. The correct code would be something like:

| Loop(xs) ->
    if currentValue state = 0
    then state
    else
        let nextState = computeProgram state xs
        cmp nextState cmd


A simple clusterness measure of data in one dimension using Java

In my opinion your code is perfectly fine! I just found some fussy thinks.

HTML Comments
In Robert C. Martin's book Clean Code under HTML Comments you can read

HTML in source code comments is an abomination [...]. It makes the comments hard to read in the one place where they should be easy to read — the editor/IDE. If comments are going to be extracted by some tool (like Javadoc) to appear in a Web page, then it should be the responsibility of that tool, and not the programmer, to adorn the comments with appropriate HTML.

In to places you uses the -tag. Which can be replaced by javadocs {@code}
For example from

x1, x2, ..., xn

to
{@code x1, x2, ..., xn}

Duplicated Statement
The statement points.size() - 1 occurs three times inside the method computeClusternessMeasure. Even it is only a \$O(1)\$-statement it makes it easier to read the variable indexOfLastEntry instead of points.size() - 1

An Other Argument
Currently computeClusternessMeasure takes a Collection but instead you need a List. This "transformation" has nothing to do with the algorithm and a a collection makes additional to that no sense..
Furthermore you need to sort it..
Take a First-Class-Collection as Argument
If you want to keep the flexibility you could create a First-Class-Collection.

Any class that contains a collection should contain no other member variables. Each collection gets wrapped in its own class, so now behaviors related to the collection have a home.

The method signature I want to create is double computeClusternessMeasure(SortedMessurementPoints points)
public class SortedMessurementPoints {

      private List<Double> points;

      public SortedMessurementPoints(Collection<Double> points) {
          List<Double> asList = new ArrayList(points);
          Collection.sort(asList )
          this.points = asList;
      }

      public double get(int index) {
          return points.get(index);
      }

      public int indexOfLastEntry() {
            return points.size() - 1;
      }
}

public double computeClusternessMeasure(SortedMessurementPoints points) {
    double minimumPoint = points.get(0);
    double maximumPoint = points.get(points.indexOfLastEntry());
    double range = maximumPoint - minimumPoint;

    if (range == 0.0) {
        // Once here, all data points are equal and so CM must be 1.0.
        return 1.0;
    }

    double expectedDifference = range / points.indexOfLastEntry();
    double sum = 0.0;

    for (int i = 0; i < points.indexOfLastEntry(); i++) {
        double currentDifference = points.get(i + 1) - points.get(i);
        sum += Math.min(Math.abs(expectedDifference - currentDifference),
                                     expectedDifference);
    }

    return sum / range;
}


Check array contains element at compile time

You have to compare values char by char, or even simpler change const char* to std::string_view make your code work.

Thanks to the deduction guides, you can just write std::array = ... and template parameters will be automatically deduced.

Also, you can simplify your loop using a "range-based for".
 If we generalize for other types of compile-time array, we get:

#include <array>
#include <string_view>

using namespace std::string_view_literals;
constexpr std::array COEFFICIENTS = { "VERSION"sv, "CHANNELS"sv, "ADAPTIVE"sv };

template <typename T, size_t N>
constexpr bool array_has(const std::array<T, N>& array, const T& value) {
  for (const auto& v : array) {
    if (value == v) return true;
  }
  return false;
}

constexpr bool coefficientExists(const std::string_view name)
{
    return array_has(COEFFICIENTS, name);
}

int main()
{
    static_assert(coefficientExists("VERSION"), "should exist");
    static_assert(!coefficientExists("TEST"), "should not exist");
}

With C++20 you can even do simpler:

#include <algorithm>
//...
template <typename T, size_t N>
constexpr bool array_has(const std::array<T, N> array, const T value) {
return std::any_of(array.begin(), array.end(), [value](auto current){ return current == value; });
}


Slicing a list, as in leftArray = input[:middleIndex], creates a copy and takes \$O(n)\$ time. You can avoid that by passing the whole list together with left and right indices as function arguments.
Another problem with the slicing approach is that you need to look at three values to recognize the peak, but the slices can become shorter than three elements.
Python's chained comparison would be handy here:

middleIsMax = input[middleIndex - 1] < input[middleIndex] > input[middleIndex + 1]


Minimal, very simple, implementation of an HTTP server for static content, using only core node.js modules

Are the fs and path packages needed? Do they simplify things enough to justify the inclusion?

fs is needed. How else would you get your data down the line without reading it in? path could be replaced with your own path utility library, but I wouldn't waste time reinventing that when a built-in one already exists.

Can this be written more concisely?

This is probably as concise as you can get it. Any further would probably make it unreadable.

Is the ternary operator justified? Would you keep it here, or is an if construct preferred?

Yep, ternary is fine. It's the check that might need improvement. That's because you're only tacking on index.html if the path is /. In other web servers, any path that ends in / assumes that index.html will be tacked on.
const filePath = path.resolve(`${rootPath}${fileUrl}`)

So one of the dangers when writing a web server is directory traversal. It's when your path resolver (in your case, this line) resolves to a path outside the web directory, and your server just willingly serves it. You'll need to check if the path resolved is still in your web directory.
res.setHeader('Content-Type', 'text/html')

function reqIsOk (req, filePath) {
  const fileExt = path.extname(filePath)
  return req.method === 'GET' && fileExt === '.html' && fs.existsSync(filePath)
}

A static server can be more than just HTML. Replace the hardcoded text/html with a value coming from a map of file extension to mimetype.


Varags

Since Java 1.5, you can use varargs in your method so that you can pass in a sequence of elements, instead of an explicit array:

public static boolean isMaxMinEqual(int... values) {
    // use values like a normal int[] array
}

Variables assignment

You have declared status right at the start, but it's actually redundant as you can simply return from the method directly in the places where you use them:

if (a.length < 2) {
    // status = false;
    // return status;
    return false; // shorter and clearer
}
// ...
/*
if (maxCount == minCount && count >= 1) {
    status = true;
}
return status;
*/
return maxCount == minCount && count >= 1; // no need to set status = true

'Debug' statements

System.out.println(count);
System.out.println("max is: " + max);
System.out.println("min is: " + min);
System.out.println("Max Count is: " + maxCount);
System.out.println("Min Count is: " + minCount);

These look like 'debug' statements where the developer (or user) is manually checking that the counting is done correctly. Usually, this should be done through a logging framework (so that the verbosity can be adjusted), or be eliminated entirely. It does not serve a direct purpose as to the method's usage.

Iterations

Your approach has to iterate through the array three times:

Find the min/max.
Count the max.
Count the min.

In fact, these can be done in one pass:

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int minCounter = 0;
int maxCounter = 0;
for (int i : values) {
    if (i < min) {
        min = i;
        minCounter = 1;
    } else if (i == min) {
        minCounter++;
    }
    if (i > max) {
        max = i;
        maxCounter = 1;
    } else if (i == max) {
        maxCounter++;
    }
}
return minCounter == maxCounter && min != max;

The idea here is that when you need to reset your min/max values, you can just reset your counters to 1 and proceed, instead of having to iterate again.

If you do not mind extra ternary operators, you can sort of combine both if branches per min/max too:

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int minCounter = 0;
int maxCounter = 0;
for (int i : values) {
    if (i <= min) {
        minCounter = 1 + (i == min ? minCounter : 0);
        min = i;
    }
    if (i >= max) {
        maxCounter = 1 + (i == max ? maxCounter : 0);
        max = i;
    }
}
return minCounter == maxCounter && min != max;


If you swap the last two lines, so you actually free the memory before returning, then the code looks to be leak-free in the face of errors - well done!  You do read uninitialized values from the allocated memory; don't do that even in a test program (Valgrind complains a lot).

Some notes:

This reads easier if you re-order the multiplication:

p = malloc(sizeof(*p)*n); // yours

p = malloc(n * sizeof *p); // mine

(BTW, it's good that you are using sizeof *p rather than sizeof (double), as this means no risk of the type becoming out of step with the size allocated.  Definitely a good practice to be encouraged!).

Testing pointers against NULL is more idiomatic if you use the default conversion to boolean:

if(p==NULL){ // yours

if (!p) { // mine

Error messages should go to standard error, not standard output, and should end with a newline:

    printf("Error! Memory not allocated."); // yours

    fprintf(stderr, "Error! Memory not allocated.\n"); // mine

The reallocation can be simplified in a similar manner to the initial allocation; I'd declare and allocate in a single line like this:

double *temp; // yours
temp = realloc(p,(n+add)*sizeof(*temp)); // yours

double *temp = realloc(p, (n+add) * sizeof *temp); // mine

Complete program

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

int main() {
    int n = 10;

    double *p = malloc(n * sizeof *p);
    if (!p) {
        fprintf(stderr, "Error! Memory not allocated.\n");
        return 1;
    }

    /* initialize these values */
    for (int i = 0;  i < n;  ++i)
        p[i] = i;

    for (int i = 0;  i < n;  ++i)
        printf("%lf\n", p[i]);
    printf("\n");

    int add = 3;
    double *temp = realloc(p, (n+add) * sizeof *temp);
    if (temp) {
        p = temp;
    } else {
        free(p);
        fprintf(stderr, "Error! Memory not reallocated.\n");
        return 1;
    }

    /* initialize the new values */
    for (int i = n;  i < n+add;  ++i)
        p[i] = 100 + i;

    for (int i = 0;  i < n+add;  ++i)
        printf("%lf\n", p[i]);

    free(p);
    return 0;
}

If we build this with my usual Makefile and run it in Valgrind, we see no leaks:

gcc -std=c11 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds 166874.c -o 166874
valgrind --leak-check=full ./166874

==30432== Memcheck, a memory error detector
==30432== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==30432== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==30432== Command: ./166874
==30432==
0.000000
1.000000
2.000000
3.000000
4.000000
5.000000
6.000000
7.000000
8.000000
9.000000

0.000000
1.000000
2.000000
3.000000
4.000000
5.000000
6.000000
7.000000
8.000000
9.000000
110.000000
111.000000
112.000000
==30432==
==30432== HEAP SUMMARY:
==30432==     in use at exit: 0 bytes in 0 blocks
==30432==   total heap usage: 3 allocs, 3 frees, 1,208 bytes allocated
==30432==
==30432== All heap blocks were freed -- no leaks are possible
==30432==
==30432== For counts of detected and suppressed errors, rerun with: -v
==30432== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)


Return an object but with one property different

As said in a comment above, using a conditional assignment would be your best bet:

class Project {

  static createProject(data) {
    return {
      owner: {
        name: data.owner,
        avatar: data.ownerAvatar
      },
      users: [
        {
          name: data.owner,
          avatar: data.ownerAvatar,
          active: true,
        }],
      name: data.name,
      retrospectives: [],
      color: data.name === 'default' ? '#1F2532' : pickColor([])
    }
  }
}


You may combine var statements and put them top of your function. Strip unused variables like parity and use element variable instead of using #defaultCountdown directly. And lastly, a little formatting will make your code much readable. Here is the result.

If you're trying to accomplish relative countdown, plugin itself supports it. I also put an example to show how to do it.

function stringToCountdown(selector, str){
    var hh = parseInt(str.substr(0,2), 10),
        mm = parseInt(str.substr(2,2), 10),
        ss = parseInt(str.substr(4,2), 10),
        austDay = new Date();

    austDay = new Date(
        austDay.getFullYear(),
        austDay.getMonth(),
        austDay.getDate(),
        austDay.getHours() + hh,
        austDay.getMinutes() + mm,
        austDay.getSeconds() + ss
    );

    $(selector).countdown({
        until: austDay,
        compact: true,
        format: 'dHMs',
        expiryText: 'No More Counter for you'
    });
}

$(function () {
    stringToCountdown('#defaultCountdown','000010');
});

And this is less readable version. There is no extra variable. So it may run a little bit faster.

function stringToCountdown(selector, str){
    var austDay = new Date();
    $(selector).countdown({
        until: new Date(
            austDay.getFullYear(),
            austDay.getMonth(),
            austDay.getDate(),
            austDay.getHours() + parseInt(str.substr(0,2), 10),
            austDay.getMinutes() + parseInt(str.substr(2,2), 10),
            austDay.getSeconds() + parseInt(str.substr(4,2), 10)
        ),
        compact: true,
        format: 'dHMs',
        expiryText: 'No More Counter for you'
    });
}

$(function () {
    stringToCountdown('#defaultCountdown','000010');
});


Converting timedate timezones with Joda-Time

First of all, currently it does not compile. You should fix that, non-working codes are off-topic here.
According to the Code Conventions for the Java Programming Language, method names should start with lowercase letters and class names should start with uppercase letters. ConvertTimeZones should be convertTimeZones.

Code Conventions for the Java Programming Language, 9 - Naming Conventions
Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions

The o prefix is unnecessary for every variable.
You could omit lots of intermediate objects. Here is a simplified version:

public static String convertTimeZones(final String fromTimeZoneString,
        final String toTimeZoneString, final String fromDateTime) {
    final DateTimeZone fromTimeZone = DateTimeZone.forID(fromTimeZoneString);
    final DateTimeZone toTimeZone = DateTimeZone.forID(toTimeZoneString);
    final DateTime dateTime = new DateTime(fromDateTime, fromTimeZone);

    final DateTimeFormatter outputFormatter
        = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss").withZone(toTimeZone);
    return outputFormatter.print(dateTime);
}

Here are a few unit tests:

import static ...TimeZoneConverter.convertTimeZones;
import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(value = Parameterized.class)
public class TimeZoneConverterTest {

    private final String expectedDatetime;
    private final String fromTimezone;
    private final String toTimezone;
    private final String inputDatetime;

    public TimeZoneConverterTest(final String expectedDatetime,
            final String fromTimezone, final String toTimezone,
            final String inputDatetime) {
        this.expectedDatetime = expectedDatetime;
        this.fromTimezone = fromTimezone;
        this.toTimezone = toTimezone;
        this.inputDatetime = inputDatetime;
    }

    @Parameters
    public static Collection<Object[]> data() {
        final Object[][] data = new Object[][] {
            { "2012-05-08 19:00:00",
                "UTC", "Europe/London", "2012-05-08T18:00:00" },
            { "2012-05-08 17:00:00",
                "Europe/London", "UTC", "2012-05-08T18:00:00" },
            { "2012-05-08 20:00:00",
                "UTC", "CET", "2012-05-08T18:00:00" },
            { "2012-05-08 19:00:00",
                "America/Tijuana", "CET", "2012-05-08T10:00:00" },
            { "2012-11-08 21:00:00",
                "Europe/London", "Asia/Dubai", "2012-11-08T17:00:00" },
            { "2012-11-19 2:00:00",
                "Europe/London", "Asia/Tokyo", "2012-11-18T17:00:00" } };
        return Arrays.asList(data);
    }

    @Test
    public void test() {
        assertEquals(expectedDatetime,
            convertTimeZones(fromTimezone, toTimezone, inputDatetime));
    }
}


Group chars in an array if they have the same start and end elements

I agree that the question takes a little time to understand. Once I understood it, I felt compelled to code a solution, which is below.

The solution you built gets the length between each letter, but the question is more nuanced.  The formal logic is in the code, but in plain English: A scene only ends when all of the shots it contains are done.

On a related note, I would consider your solution to be a "procedural" approach to solving the problem.

As an object-oriented language, C# lends itself to the "object-oriented" approach, which to me means modeling the domain with classes. In this case, a Movie class and a Scene class. I initially thought there would be a Shot class, but in this example shots are reduced to character labels, so it was unnecessary.

Of course a real solution would definitely contain a Shot class, perhaps with additional properties like Camera, Lighting, and Description.

Here is the output:

Here is the sample code:

using System;
using System.Collections.Generic;
using System.Linq;

public class App_MovieScenes
{
    public void Run()
    {
        var shotList = new char[] { 'a', 'b', 'a', 'b', 'c', 'b', 'a', 'c', 'a', 'd', 'e', 'f', 'e', 'g', 'd', 'e', 'h', 'i', 'j', 'h', 'k', 'l', 'i', 'j' };
        var movie = new Movie(shotList);
        movie.ToScenes();
        movie.Output();
    }
}

public class Movie
{
    private char[] shotList;

    public List<Scene> Scenes { get; private set; }

    public Movie(char[] shotList) => this.shotList = shotList ?? new char[1];

    public void ToScenes()
    {
        var all = new string(shotList);
        var groups = new List<List<char>>();
        var group = new List<char>();
        var index = 0;

        all.ToList().ForEach(c =>
        {
            var remaining = all.Substring(index++);
            var groupIsEmpty = !group.Any();
            var anyInGroupHasMore = group.Any(g => remaining.Contains(g));

            if (groupIsEmpty || !anyInGroupHasMore)
            {
                ///start a new group
                group = new List<char>();
                group.Add(c);
                groups.Add(group);
            }
            else
            {
                ///add to current group
                group.Add(c);
            }
        });

        Scenes = groups.Select(g => new Scene(g)).ToList();
    }

    public void Output() => Console.WriteLine(ToString());

    public override string ToString() => string.Join("\n", Scenes.Select(s => s.ToShotList()));
}

public class Scene
{
    public List<char> Shots { get; private set; }
    public int Length => Shots.Count;

    public Scene(List<char> shots) => Shots = shots;

    public string ToShotList() => $"{Length}\t{string.Join(", ", Shots)}";
}


Remove every line that include and follows the second occurrence of a given pattern

This should be pretty speedy:

awk '/bar/ {n++} n==2 {exit} {print}' file

To pass the pattern from the shell:

awk -v p="$pattern" '$0 ~ p {n++} n==2 {exit} {print}' file


CMakeList to compile and link an executable using Boost

As commented by @drescherjm and @NicolasHolthaus your example code already looks pretty good. If you are getting less verbose, you will always loose some information.

Minimal Version

To demonstrate this, let's take a look at a minimal version of your code:

cmake_minimum_required(VERSION 3.4)
project(AwesomeScheduler)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin")

find_package(Boost REQUIRED COMPONENTS system filesystem)

include_directories(header)

add_executable(Dispatcher src/socket.cpp src/dispatcher.cpp)
add_executable(EndUser src/socket.cpp src/end-user.cpp src/task_properties.cpp)
target_link_libraries(EndUser Boost::system Boost::filesystem)

I have

moved the source files into the add_executable() calls
eliminated the header files
used the IMPORTED targets from Boost, which implicitly declares the header paths also
done some cosmetic changes to the global settings

used the more cross-platform CMAKE_CXX_STANDARD setting
using .. from the binary dir looks odd, I assumed something relative to the source dir

Something in Between

Because grouping the source files and adding the header files has its advantages in respect of readability, maintainability and CMake's own abilities during build environment generation, here is what I would have done in the setup you have described here:

cmake_minimum_required(VERSION 3.4)
project(AwesomeScheduler)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin")

find_package(Boost REQUIRED COMPONENTS system filesystem)

set(
    SOCKET_SOUCE_FILES
        src/socket.cpp
        header/socket.h
)
set(
    ENDUSER_SOURCE_FILES
        src/end-user.cpp
        header/end-user.h
        src/task_properties.cpp
        header/task_properties.h
        header/util.h
)
set(
    DISPTACHER_SOURCE_FILES
        src/dispatcher.cpp
        header/dispatcher.h
        header/util.h
)

add_library(Socket OBJECT ${SOCKET_SOUCE_FILES})
target_include_directories(Socket PUBLIC header)

add_executable(Dispatcher ${DISPTACHER_SOURCE_FILES} $<TARGET_OBJECTS:Socket>)
target_include_directories(Dispatcher PRIVATE header)

add_executable(EndUser ${ENDUSER_SOURCE_FILES} $<TARGET_OBJECTS:Socket>)
target_include_directories(Dispatcher PRIVATE header)
target_link_libraries(EndUser Boost::system Boost::filesystem)

Now you have

the possibility to

add/remove files conditionally to your source file lists
reuse the lists in calls to e.g. set_source_files_properties() or source_group()

the headers getting checked for availability and added to IDE projects during generation
the grouping of Socket sources into a object library with e.g. it's own set of target properties to be modified
no global include directory anymore, but target specific include directories

on this small project with only one header folder it might be oversized, but if your code gets larger you should definitely think about the directory structure of your code
So it could look something like

AwesomeScheduler/
  CMakeLists.txt
  Dispatcher/
    CMakeLists.txt
    src/
      dispatcher.cpp
      dispatcher.h
  EndUser/
    CMakeLists.txt
    src/
      end-user.cpp
      end-user.h
  lib/
    Socket/
      CMakeLists.txt
      src/
        socket.cpp
      include/
        socket.h
  include/
    util.h

References

FindBoost CMake Module
https://stackoverflow.com/questions/6594796/how-do-i-make-cmake-output-into-a-bin-dir
https://stackoverflow.com/questions/10851247/how-to-activate-c-11-in-cmake
https://stackoverflow.com/questions/2924037/separate-include-and-src-folders-for-application-level-code
https://stackoverflow.com/questions/2360734/whats-a-good-directory-structure-for-larger-c-projects-using-makefile
https://stackoverflow.com/questions/36872117/various-libs-in-subfolders-how-do-i-export-them-to-the-parent


Namespace scope and pollution is often a problem in programming, and when reading code, if there are two usages of a particular identifier, a reader may not understand exactly which one you mean, and the complier may have different scope rules than you expect, so it is worthwhile to not re-use names.

In this particular case, consider using query instead of get in the public API

Public Function query_assignments(e_id As Long, yr As Integer, wk As Integer) As DAO.Recordset


Selecting a specific row with a desired value

Will this work?

var dr= (from avTable in DAL.DataStore.DSet.Tables["Values1"].AsEnumerable()
         join pavTable in DAL.DataStore.DSet.Tables["Values2"].AsEnumerable()
             on avTable.Field<int>("PK") equals pavTable.Field<int>("FK_Value");
         where
             (pavTable.Field<int>("FKI_ProductAttribute") == Value2 &&
              avTable.Field<string>("Name") == "Specific Value") ||
              pavTable.Field<int>("FKI_ProductAttribute") == Value2
         select avTable)
        .FirstOrDefault();

I don't really have a way to test this, but I believe if the first part of the where clause criteria is met, the part after the || is skipped. If the first part returns no record then the second part is evaluated and will return a result ...or null.


REST API stored in a MongoDB Atlas Database

In general, I think the code looks pretty good.  I would suggest two changes:

Dry

In an effort to keep the code DRY, I suggest constructing the player dict in a function for that purpose like:

def player_to_dict(player):
    return {
        'name': player['name'],
        'position': player['position'],
        'nationality': player['nation'],
        'position': player['position'],
        'foot': player['foot'],
        'age': utils.date_to_age(player['birth_date']),
        'profile_img': player['profile_img'],
        'abilities': player['abilities']
    }

This takes out quite a bit of code from:

def get_player(name):
    try:
        player = db.players.find_one({'name': name})
        return jsonify({'result': player_to_dict(player)})
    ....

I like comprehensions:

Using a list comprehension and the new player_to_dict(), you can remove the explicit for loop and instead make get_all_players much smaller and looking like quite similar to get_player.

def get_all_players():
    try:
        players = db.players.find()
        return jsonify({'result': [player_to_dict(player) for player in players]})
    ....


Seems to me you just need to add the phase to the angle in update().
def update(val):
    amp = aslider.val
    freq = fslider.val
    phase = phslider.val
    t = np.linspace(0, 5, 200)

    y.set_ydata(amp*np.sin(2*np.pi*freq*t + phase))  # << add phase here

fslider.on_changed(update)
aslider.on_changed(update)
tslider.on_changed(update)
pslider.on_changed(update)
phslider.on_changed(update)  # update on slider change


Your code looks good to me. I like how it takes pipelined input. That is pretty elegant.

You don't need the Position=0 here:

[Parameter(Position=0,ValueFromPipeline=$true)]

This is what the help says about that:

  By default, all function parameters are positional. Windows PowerShell        assigns position numbers to parameters in the order in which the        parameters are declared in the function.

The following comments are just my personal preferences. If this were a real code review for production code, I wouldn't insist on any of it. Feel free to ignore!

I think the switch statement there is elegant but a little confusing. In most languages, switch will only ever select a single branch. When I see "switch", I expect it to select one branch only. That's just a habit of thought. Your code took me by surprise. I had to stop and think about how it managed to get both "Fizz" and "Buzz" for the number 15.

I'm almost tempted to say that multiple selection in switch statements is a misfeature of PowerShell because it violates the principle of least surprise. I'm torn on that question however because it is a cool feature.

Personally I would have used two if statements. Even though that would have been clunklier, it would have been clearer and more explicit in my opinion, and therefore better.

Regarding this line:

-join $result

That is correct according to the help. -join can indeed be a unary operator. It looks weird though. I'd never seen it like that before, and it took me by surprise. Personally I would have used it as a binary operator in the usual fashion:

$result -join ""


What is a reason for using alarm() with sleep()? Why not just

void sigIntHandler(int signum) {
  fprintf(stdout, "received interrupt. going to exit.\n");
  exit(0);
}

int main(int argc, char* argv[]) {
  if(initializeEnvironment(argc, argv) == -1) {
    return -1;
  }
  signal(SIGINT, signalAlarmHandler); /* for testing purposes */

  while(1) {
    sleep(10);
    /* checking for condition here */
  }
}

Also:

fprintf() is not signal-safe, better not to use it from signal handler
signal() is obsolete and implementation-dependent, use sigaction() for consistent results.


Scraping GitHub for security vulnerabilities

PEP8 - click, read, apply

PEP8 gives coding conventions for the Python code comprising the
standard library in the main Python distribution

you should use 4 spaces per indentation level
function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility
variable names should also stick to the above rule
there should be two newlines between each method
use augmented assigments where possible (url = url + ('/git/trees/%s?recursive=1' % sha) -> url += '/git/trees/%s?recursive=1' % sha)
you're sometimes using double-quotes around strings, and sometimes single-quotes. Choose one and stick to that.
use format() instead of the old %
I'd rather suggest you use the print() function even if you're using python 2.7. It will make you code easily portable.
you're lacking docstrings. Write docstrings for all public modules, functions, classes, and methods. They are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.)

Code:
import base64
import os
import re
import requests

def get_repos(since=0):
    """
    Left as an exercise for OP
    """
    url = 'http://api.github.com/repositories'
    data = '{{since: {}}}'.format(since)
    response = requests.get(url, data=data)

    if response.status_code == 403:
        print('Problem making request! {}'.format(response.status_code))
        print(response.headers)

    matches = re.match(r'<.+?>', response.headers['Link'])
    next = matches.group(0)[1:-1]

    return response.json(), next

def get_repo(url):
    """
    Left as an exercise for OP
    """
    return requests.get(url).json()

def get_readme(url):
    """
    Left as an exercise for OP
    """
    url += '/readme'
    return requests.get(url).json()

# todo: return array of all commits so we can examine each one
def get_repo_sha(url):
    """
    Left as an exercise for OP
    """
    commits = requests.get(url + '/commits').json()
    return commits[0]['sha']

def get_file_content(item):
    """
    Left as an exercise for OP
    """
    ignore_extensions = ['jpg']
    filename, extension = os.path.splitext(item['path'])

    if extension in ignore_extensions:
        return []

    content = requests.get(item['url']).json()
    lines = content['content'].split('\n')
    lines = map(base64.b64decode, lines)

    print('Path: '.format(item['path']))
    print('Lines: '.format(''.join(lines[:5])))

    return ''.join(lines)

def get_repo_contents(url, sha):
    """
    Left as an exercise for OP
    """
    url += '/git/trees/{}?recursive=1'.format(sha)

    return requests.get(url).json()

For the second .py file:

the above rules apply
don't import modules you're not using (import json)

Code
import github

def process_repo_contents(repo_contents):
    """
    Left as an exercise for OP
    """
    for tree in repo_contents['tree']:
        content_type = tree['type']
        print('content_type --- {}'.format(content_type))

        if content_type == 'blob':
            github.get_file_content(tree)
            print('***blob***')
        elif content_type == 'tree':
            print('***tree***')

if __name__ == '__main__':
    repos, next = github.get_repos()
    for repo in repos[0:10]:
        sha = github.get_repo_sha(repo['url'])
        repo_json = github.get_repo_contents(repo['url'], sha)
        process_repo_contents(repo_json)

Pay more attention to variable names and data types

next is a builtin keyword so I'd recommend you to change it to something else
ignore_extensions is a list in your case. And it only keeps one string. Don't you think it would be more appropriate to make it a string from the beginning ?


Refactor method by removing else condition

"Else is evil"? That's a very peculiar point of view!
But if you really want to avoid it, you can look at early return, provided that isn't also regarded as evil - some people are very firm on the "single entry, single exit" principle.
Gilbert Le Blanc's code takes a similar approach to me, but in avoiding early return, he risks duplicated code execution, which may not be a problem here, but worries me a little.
The code below is not checked in any detail, but shows the idea, though it does duplicate code.
public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {

  if (requestContainsCustomDate(startDateFromParam, endDateFromParam)) {
    boolean isDateRangeValid = isDateRangeValid(startDateFromParam, endDateFromParam);
    if (!isDateRangeValid) {
      startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();
      endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();
    }
    setSessionAttributes(startDateFromParam, endDateFromParam, session);
    return isDateRangeValid;
  }

  if (sessionContainsCustomDate(session)) {
    startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();
    endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();
    setSessionAttributes(startDateFromParam, endDateFromParam, session);
  }

  return true;
}


I don't like how you're specifying the column aliases. I expect a whitespace between the column and the alias.

I like that you're not specifying the optional AS keyword though - I find it only adds clutter when it's there.

Also I would have used [square brackets] instead of single quotes, and layout the field names on separate lines, like this:

SELECT
     u.DisplayName [Display Name]
    ,u.Reputation [Rep]
    ,u.Location [Location]

That way you can easily add, reorder, or comment-out a column if you need to.


AngularJS apply filters on data previously filtered

In general, your data is structured very poorly for your filtering use cases. Having to iterate an entire array of users every time you want to apply a filter (and then having some of those filter methods further iterate nested data structures) will become a very slow process once you have a large number of data objects that you want to filter (not to mention also apply multiple filters towards).

It is also unclear how your filtering logic support AND vs. OR across the filtering criteria, so not sure how flexible/extensible what you have really is.

Finally, the approach you take on chaining the filters might need to be something you think about optimizing at some point. If you have fields that are unique, like login presumably is, these would almost seem to need different filter treatment than trying to iterate through all users making this comparison. These sorts of filters should be binary in the sense that the match will either return exactly one item or no items if the match isn't fulfilled. So, this is not so much a filter as it is an indexed lookup. This ties back to my concern about your data structure.  If you have unique fields, you should be able to perform an O(1) lookup to determine if that object with that unique value exists, not have to perform an O(n) iteration across all objects to look for this unique value.


From a once over

Not everybody in CR agrees, but I find tabular data best presented in an aligned format:

var API = {
  list:   [list  , 'private'],
  login:  [login , 'public' ],
  logout: [logout, 'private'],
  add:    [add   , 'admin'  ],
  remove: [remove, 'admin'  ],
  edit:   [edit  , 'admin'  ]
};

For your error handing, I would mention that using express is very nice for error handling. If you insist on doing it yourself you could do something like

function handle( f ){
  return function( err ){
    if(err){
      console.error('ERROR: ', err.message);
      return;
    }
    f.apply( this , arguments );
  }
}

Then you can

function remove(req, res) {
  find(req.body.username, handle( function (err, user) {
    user.remove( handle( function (err) {
      res.send('OK');
    }));
  }));
}

For your error message constants, I would declare them all together on top
I am ambivalent about using an array for your API config instead of an object, if you keep using that, I would suggest you use named constants declared on top:

    var callback   = API[label][CALLBACK];   //Where CALLBACK is earlier declared as 0
    var permission = API[label][PERMISSION]; //Where PERMISSION is earlier declared as 1


You can write

if raw_input("Enter the country from which you order from") == "Brazil":
    c = 1
else:
    c = 2

instead of

print "Enter the country from which you order from"
x=raw_input()
if x=="Brazil":
    c=1
else:
    c=2

as you are not using x anywhere. I less variable and raw_input has optional string so why not use that?

In function profit instead of using

if y%10==0:
    P=orderfromArgentinafb(y);
else:
    P=orderfromBrazil(y);

you can use

if y % 10:
    return orderfromBrazil(y)
else:
    return orderfromArgentinafb(y)

You don't need the variable P when you are just returning it.
Why are there semicolons at the end? This isn't C
Notice the changing the order of return. It gives the same result but with one less comparison.

Same thing can be done in function calculate.

Use if...elif... in case you are just doing one of the things. Using as it is leads to more comparisons than are needed.

In both the functions orderfromArgentina and orderfromArgentinafb a simple reordering of statements can lead to removal of additional variable Cost.

You need to read a style guide. Check for official tutorials of Python. They contain brief style guide. That is also an optimization. It doesn't effect memory or time complexity but it leads to better maintenance


From your code it looks like you're changing one of "enabled" options only in one of the five cases. You can do that with a loop, using a class selector.

Also, it may be just me, but I don't think you should use value in an input box / radio button to store something different than the default value that you want that item to have. I suggest changing it to something like value_type.

So, what you can do is add another class to your input elements, select by that and do what you need, something like:

$(function() {
    $('input.entity-option').change(function() {
    if (this.value_type === "I") {
        $("#user_ssn").prop("disabled", false);
        $("#user_ein").prop("disabled", true);
      } else {
        $("#user_ssn").prop("disabled", true);
        $("#user_ein").prop("disabled", false);
      }
    });
  });

And in your HTML you need something like:

    <input class="radio_buttons required entity-option" required="required" aria-required="true" type="radio" value_type="I" name="user[entity_type]" id="user_entity_type_i" />
    Individual / Sole Proprietor

    <input class="radio_buttons required entity-option" required="required" aria-required="true" type="radio" value_type="C" name="user[entity_type]" id="user_entity_type_c" />
    Corporation

    <input class="radio_buttons required entity-option" required="required" aria-required="true" type="radio" value_type="P" name="user[entity_type]" id="user_entity_type_p" />
      Partnership

    <input class="radio_buttons required entity-option" required="required" aria-required="true" type="radio" value_type="L" name="user[entity_type]" id="user_entity_type_l" />
    Limited Liability Company

     <input class="radio_buttons required entity-option" required="required" aria-required="true" type="radio" value_type="O" name="user[entity_type]" id="user_entity_type_o" />
       Other


Advent Of Code 2020, day 1, find desired sum and multiply the addends

Looks mostly fine, though there are a few issues:
Argument bug/typo You're referring to top-level variable entries inside the function instead of to the listAsString argument.
Match numbers? Even if it's said that the input will contain line-separated numbers, I'd feel safer matching numeric characters instead of splitting by newlines. It'll be more robust if the input happens to not be formatted perfectly correctly, or at least makes the intent (to extract an array of only digit characters from the input) a bit clearer, without relying on the description.
Maybe use Number? Once you have an array of digit characters, you turn them all into numbers with .map(s => s*1). I think the intent - to cast to numbers - would be a bit clearer by using .map(Number) instead.
i is conventionally used to indicate the index being iterated over. Here, i isn't being used as the index, but as the element being iterated over. Maybe use num instead?
target - i can be saved into a variable instead of repeating it twice, if you want.
Counting bug If the target sum happens to be a sum of two of the same number, eg: 1010 + 1010, those will be matched even if the input only contains one of those numbers, since you're using a Set which doesn't differentiate one occurrence from multiple.
To fix this, you could add an index check to the original array if the two numbers happen to be the same (as I've done below), or count up occurrences into an object, or something like that.

With findTargetSum3, in addition to the above:
Computational complexity is unnecessarily large The first approach is O(n), which is good. This second approach is O(n ^ 2), since you're checking every element against every other element. I'd ditch findTargetSum3 completely.
Prefer strict equality over loose equality - yes, the types are surely the same, so it doesn't make a difference in the logic, but strict equality with !== and === is easier to understand at a glance due to the lack of strange coercion rules. Whenever I see sloppy comparison (especially in professional code), I think: "Why isn't strict comparison being used, is there some possible type coercion weirdness going on that wasn't explicit?" Better to be consistent and use strict equality comparison everywhere.

function findTargetSum(listAsString, target){
  const numbers = listAsString.match(/\d+/g).map(Number);
  const set = new Set(numbers);
  for (const num of set) {
    const otherNum = target - num;
    if (
      set.has(otherNum) &&
      (num !== otherNum || numbers.indexOf(num) !== numbers.lastIndexOf(otherNum))
    ) {
       return num * otherNum;
    }
  }
}

const entries = `1780
1693
1830
1756
1858
1868
1968
1809
1996
1962
1800
1974
1805
1795
170
1684
1659
1713
1848
1749
1717
1734
956
1782
1834
1785
1786
1994
1652
1669
1812
1954
1984
1665
1987
1562
2004
2010
1551
961
1854
2005
1883
1965
475
1776
1791
262
1912
1227
1486
1989
1857
825
1683
1991
1875
1982
1654
1767
1673
1973
1886
1731
1745
1770
1995
1721
1662
1679
1783
1999
1889
1746
1902
2003
1698
1794
1798
1951
1953
2007
1899
1658
1705
62
1819
1708
1666
2006
1763
1732
1613
1841
1747
1489
1845
2008
1885
2002
1735
1656
1771
1950
1704
1737
1748
1759
1802
2000
1955
1738
1761
1765
1853
1900
1709
1979
1911
1775
1813
1949
1966
1774
1977
1757
1992
2009
1956
1840
1988
1985
1993
1718
1976
1078
1997
1897
1792
1790
1801
1871
1727
1700
1485
942
1686
1859
1676
802
1952
1998
1961
1844
1808
1703
1980
1766
1963
1849
1670
1716
1957
1660
1816
1762
1829
526
359
2001
1874
1778
1873
1511
1810
1699
1970
1690
1978
1892
1691
1781
1777
1975
1967
1694
1969
1959
1910
1826
1672
1655
1839
1986
1872
1983
1981
1972
1772
1760`;
console.log(findTargetSum(entries, 2020));
console.log(findTargetSum(`1
3
3
5`, 6));


In general, the code is nice and readable.  Here's some small suggestions:

This:

for (unsigned long i = 0; i < 7; i++) {
    int job;
    std::cin >> job;
    job_list.push_back(job);
}

can be simplified (?) to

std::copy_n(std::istream_iterator<int>{std::cin}, 7, std::back_inserter(job));

Introduce variables when you use them.  For example, the declaration of permutations may be moved after reading and sorting the numbers.
Marking original_permutation as const indicates that it is used for comparison only.
Use emplace:

permutations.emplace(job_list.begin(), job_list.begin() + 3);

instead of

permutations.insert(std::vector<int>(job_list.begin(), job_list.begin() + 3));

const auto& in the for loops.  Also, std::cout << '\n' instead of std::endl(std::cout).
Consider extracting the functionality into a function and changing magic numbers to arguments.

Of course, there are more efficient ways to do this.  Your code generates
$$ 7! = 7 \times 6 \times 5 \times 4 \times 3 \times 2 \times 1 = 5040 $$
permutations, but only end up with
$$ 7^{\underline{3}} = 7 \times 6 \times 5 = 210 $$
results, and let std::set discard the remaining \$5040 - 210 = 4830\$ permutations.  You can modify your code so that it only stores one in \$4! = 24\$ permutations, but the other answers to the linked question provide better algorithms.


Simple addition, multiplication, divison, and subtraction program

Be careful with exceptions. int(answer) may raise a ValueError if an answer cannot be converted. Same goes for unchecked division.
In case of an illegal choice, choose doesn't return a value. Not a problem here, but rather a bad habit.
if/elif/elif/... cascade is usually better expressed via a dictionary, in this case of 2-tuples (a format string and a lambda:

problems = { "ADD": ("{} + {}", lambda x,y: x + y),
             "MULT": (...),
              etc }

Then the body of choose could be reduced to

try:
    format, action = problems[types.upper()]
    print format.format(num1, num2)
    return action(num1, num2)
except KeyError:
    print "Choose only from %s" % ",".join([key for key in problem.keys()])

and you may freely add more operations to problems not ever touching the code.


Iterating over a range of dates in a shell script

Start with the query and work backwards.  A poorly-written, poorly-performing query is not a good foundation to build on.

Here is your query (re-formatted to more readable)

SELECT il.BatchID
FROM tbl_batch_table AS il
WHERE
  il.batch_name LIKE '%$batchdate%'
  AND il.batch_name LIKE '%$batchwupos%'
  AND il.status='SUCCESS'

This query will not be able to leverage an index on batch_name because you are using a LIKE condition that starts with a wild card character.

Can you split apart the batch date information in your DB table into it's own column?  That would give you the ability to do things like:

Query on a date range AND use index to do so.
Perform date-based math (adding/subtracting days)

Imagine this sort of query:

SELECT
    il.batch_date,
    /* Create calculated field representing processing date four days
       after batch date */
    DATE_ADD(il.batch_date, INTERVAL 4 DAY) AS processing_date,
    il.BatchID
FROM tbl_batch_table AS il
WHERE
  /* Filter for records batched in last 4 days */
  il.batch_date >= DATE_SUB(CURDATE(), INTERVAL 4 DAY)
  AND il.status='SUCCESS'
/* Order your results */
ORDER BY il.batch_date ASC, il.BatchID ASC

Here you can leverage an index on batch_date for WHERE clause and ordering.  You can also totally eliminate having multiple queries as you are getting records for the entire range of dates at once.

If you wanted to go with the suggestion from other answer and aggregate information for each date with concatenated results, you could add GROUP BY and GROUP CONCAT to this query like follows:

SELECT
    /* Create calculated field representing processing date four days
       after batch date */
    DATE_ADD(il.batch_date, INTERVAL 4 DAY) AS processing_date,
    GROUP_CONCAT(il.BatchID) AS batch_ids
FROM tbl_batch_table AS il
WHERE
  /* Filter for records batched in last 4 days */
  il.batch_date >= DATE_SUB(CURDATE(), INTERVAL 4 DAY)
  AND il.status='SUCCESS'
GROUP BY processing_date
/* Order your results */
ORDER BY il.batch_date ASC, il.BatchID ASC


You will not get dramatic speedups untill you can vectorize the operations, but here are some tips already

indexing before iterating

instead of

for i, row in df.iterrows():
    if row['event'] == 1:

If you do

for i, row in df[df['event'] == 1].rows():

you will iterate over less rows.

itertuples

generally, itertuples is faster than iterrows

comparable_rows

for comparable_rows you are only interested in the proba and the length, so you might as well make this into a Series, or even better, a numpy array.

The test (df['event'] == 0) doesn't change during the iteration, so you can define a df2 = df[df['event'] == 0] outside of the loop

n_correct_rows

instead of len(comparable_rows[comparable_rows['proba'] < row['proba']]), you can use the fact that True == 1 do (comparable_rows['proba'] < row.proba).sum()

result

def c_index3(y_pred, events, times):
    df = pd.DataFrame(data={'proba':y_pred, 'event':events, 'time':times})
    n_total_correct = 0
    n_total_comparable = 0
    df = df.sort_values(by=['time'])
    df2 = df.loc[df['event'] == 0]
    for row in df[df['event'] == 1].itertuples():
        comparable_rows = df2.loc[(df2['time'] > row.time), 'proba'].values
        n_correct_rows = (comparable_rows < row.proba).sum()
        n_total_correct += n_correct_rows
        n_total_comparable += len(comparable_rows)

    return n_total_correct / n_total_comparable if n_total_comparable else N

timings

data = ([0.1, 0.3, 0.67, 0.45, 0.56], [1.0,0.0,1.0,0.0,1.0], [3.1,4.5,6.7,5.2,3.4])
%timeit c_index1(*data)

5.17 ms ± 33.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit c_index3(*data)

3.77 ms ± 160 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


For this kind of a simple "storage" class, it might be more appropriate to use either a simple dictionary or a collections.namedtuple():

from collections import namedtuple

MovieDocument = namedtuple('MovieDocument', ['name', 'genre', 'quality', 'size', 'rating'])

Note, style-wise, the class name should be defined in PascalCase starting with a capital letter.

Also, consider making get_links() a generator and renaming it to, say, crawl() as it is not actually getting the links but crawling and returning movie objects.

I would also use an EAFP approach for the next page link retrieval.

The code with all the changes applied:

from collections import namedtuple
from urllib.request import urljoin

import requests
from lxml.html import fromstring

Movie = namedtuple('MovieDocument', ['name', 'genre', 'quality', 'size', 'rating'])

def crawl(link):
    root = fromstring(requests.get(link).text)
    for item in root.cssselect(".mv"):
        name = item.cssselect("h3 a")[0].text
        genre = item.cssselect("li b:contains('Genre:')")[0].tail
        quality = item.cssselect("li b:contains('Quality:')")[0].tail
        size = item.cssselect("li b:contains('Size:')")[0].tail
        rating = item.cssselect("li b:contains('Rating:')")[0].tail

        yield Movie(name, genre, quality, size, rating)

    try:
        next_page = root.cssselect(".pager a:contains('Next')")[0].attrib['href']
        full_link = urljoin(link,next_page)
        yield from crawl(full_link)
    except IndexError:
        pass

if __name__ == '__main__':
    for movie in crawl("https://www.yify-torrent.org/search/western/"):
        print(movie.name, movie.genre, movie.quality, movie.size, movie.rating)

There is, though, still this repetition in the CSS selectors - consider extracting it into a reusable function parameterized with a text you then use in contains().


If the goal is to run a task at the same time each day, it is better
to capture the value of the real-time clock, because using successive 24
hour intervals can give you a "time creep".  Something along these lines
would work fine (you'd probably put this in a separate thread):

import time

def time_of_day:
     return time.strftime("%H:%M:%S")

target_time = "18:00:00"

while True:
    while time_of_day() != target_time:
         time.sleep(.1)
    call_function()
    while time_of_day() == target_time:
         time.sleep(.1)


Trig based functions in sfml, angling of sprites

Single Responsibility
Overall, I see one really big thing that I think needs to be addressed before anything else can be addressed. Namely, your class is doing way too many things. A class should have one single purpose. It should avoid relying on other classes as much as reasonably possible. This is known as loose coupling. A class that figures out positions and angles of a ship should not have to know anything about windows or mouse buttons. As such, I'd change the prototype for void angleShipToMouse to something like this:
void angleShipToMouse(const sf::Vector2f& mousePosition)

I'd then remove the logic that gets the mouse button state and checks whether a button is pressed and whether the position is within the window bounds and put those somewhere else in your program.
Do as few transformations of data as necessary
Several places in your code you're converting between degrees and radians. There are several problems with doing this:

It becomes difficult to figure out or remember which units a variable is in, particularly if it's named something generic like angle or rotation.
It's inefficient in both the space the program takes up and the time it takes to execute. It might not matter here, but maybe it will later.
It can introduce inaccuracies. Again, they may not be noticeable in this code, but they could be multiplied later.

In general, all code other than code which displays values to users is probably going to want to operate in radians. All math functions in the standard library use radians. You should probably be using radians internally and only converting to degrees for display.
Also, when you do want to convert between degrees and radians, you should write a named function to do it and call that function rather than always writing the values inline. It's easy to mistype one of the values and someone not familiar with the transformation might not immediately understand it looking at the code. If you had functions named degreesToRadians() and radiansToDegrees(), it becomes immediately obvious to anyone reading the code what you're doing.
Avoid magic numbers
In moveCircle() you have the value 400 twice in the first line. What does it represent? I'm guessing that the window or view this is in is 800x800 pixels, so (400, 400) is the center? If so, you should at least have a constant defined for that. I recommend something like:
const sf::Vector2f kWindowCenter(400, 400);

Or better yet, pass in the point you want to rotate around! What happens if you want to let the user resize the window (or view)? What if you want to rotate around a different point?


Smart way to shorten the current working directory in pure Bash

Returning values by variable is 3-10 times faster than capturing an echo with $( ).  Your temp variable is already global.  Just name it something similar to what the surrounding function is named.

Whitespace and comments affect bash performance negatively.  It's not a big penalty, just something to be aware of.

A regular expression can do the "last two path components" extraction very compactly.

cwd() {
  cwd=$PWD
  [[ $cwd/ == $HOME/* ]] && cwd=~${cwd#$HOME}
  [[ $cwd =~ ./([^/]+/[^/]+)$ ]] && cwd=${BASH_REMATCH[1]}
}

PROMPT_COMMAND=cwd

PS1="\$cwd \$"

I'd say not to count the tilde as a path component: it's only one extra character that carries a lot of information, well worth the single column.   The regex is then:

  [[ $cwd =~ (..|[^~])/([^/]+/[^/]+)$ ]] && cwd=${BASH_REMATCH[2]}


Stack seems more or less deprecated. Javadoc says the following:

  A more complete and consistent set of LIFO stack
  operations is provided by the Deque interface and its
  implementations, which should be used in preference to this class.

I guess an ArrayDeque is a good choice here.
It's seems that StringTokenizer is also deprecated. Javadoc says the following:

  StringTokenizer is a legacy class that is retained for
  compatibility reasons although its use is discouraged in new code.
  It is recommended that anyone seeking this functionality use the
  split method of String or the java.util.regex package instead.

I'd rename

buff to result
stack to words
str to word

to describe their purpose. It would be easier to read and help understanding code.
You could move the declaration of buff right before the second while loop.

StringBuilder buff = new StringBuilder();
while (!stack.isEmpty()) {
    buff.append(stack.pop());
    if (!stack.isEmpty())
        buff.append(" ");
}

Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (Effective Java, Second Edition, Item 45: Minimize the scope of local variables)

if(!str.equals(""))

You could use String.isEmpty() here. It's easier to read since it says in a similar language to English what does this condition do.

if(!str.equals("")) stack.push(str);

According to the Code Conventions for the Java Programming Language,

  if statements always use braces {}.

Omitting them is error-prone. I've found the one-liner above hard to read because if you scan the code line by line it's easy to miss that at the end of the line there is a statement (push).
It's good to know that there is a similar function in Apache Commons Lang: StringUtils.reverseDelimited. You can check the implementation online for other ideas.

(See also: Effective Java, 2nd edition, Item 47: Know and use the libraries The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)

Here is the modified code with the Deque and other suggestions:

public static String reverseWords(String input) {
    Deque<String> words = new ArrayDeque<>();
    for (String word: input.split(" ")) {
        if (!word.isEmpty()) {
            words.addFirst(word);
        }
    }
    StringBuilder result = new StringBuilder();
    while (!words.isEmpty()) {
        result.append(words.removeFirst());
        if (!words.isEmpty()) {
            result.append(" ");
        }
    }
    return result.toString();
}


Pre-commit hook to prevent large file commits

Although described as a Bash script, this appears to be a portable shell script that can be run by any POSIX-conformant shell.  That's a good thing, as it means we can use a much smaller, leaner shell such as Dash.

If you haven't yet installed shellcheck, I recommend you do so (there's also a web version you can try).  It highlights the following:

Useless cat here:

bytez=$(cat "$(git rev-parse --show-toplevel)/$1" | wc -c)

That can be simplified to

bytez=$(<"$(git rev-parse --show-toplevel)/$1" wc -c)

Unquoted expansion of $1 - we really wanted to write "$1" there.
Unsafe read x ought to be read -r x
$x is unquoted

Piping the file into wc isn't an efficient way to measure size of a file; we could simply use stat:

bytez=$(stat -c %s "$(git rev-parse --show-toplevel)/$1")

And instead of running git rev-parse for every file in the changeset, run it once and remember the value in a variable.

The error message should go to the standard error stream (I see the whole script is redirected to &2)

It's not obvious why set -e is right down inside the if - I'd normally put that immediately after the shebang.

Consider also set -u to help detect a likely cause of errors.

Spelling: unless you really mean "1 millibit", that should be "1MB".

A suggestion that might fall into the "too cute" category: since git config --bool always produces true or false as output, we can simply execute that as a command:

if ! $(git config --bool hooks.allowbigfiles)
then

Line-based reading (i.e. git diff --name-only | while read) isn't totally robust; there's a -z option provided to produce NUL-separated output.  This will require Bash, though, in order to read -d.

Improved code

#!/bin/bash

set -e

too_big() {
    if [ "$(stat -c %s "$toplevel/$1")" -gt 1000000 ] ; then
        cat <<EOF
Error: Attempting to commit a file larger than approximately 1MB.
Commiting large files slows jenkins builds, clones, and other
operations we would rather not slow down.
Consider generating, downloading, zipping, etc these files.
Offending file - $1
EOF
        exit 1
    fi
}

# If you want to allow large files to be committed set this variable to true.
allowbigfiles=$(git config --bool hooks.allowbigfiles)

# Redirect output to stderr.
exec >&2

if ! "$allowbigfiles"
then
    toplevel=$(git rev-parse --show-toplevel)
    git diff --name-only -z --cached "$1" |
        while IFS= read -d '' -r x; do too_big "$x"; done
fi


A function to remove characters from a string

Don't abuse reduce. Reduce should be used when you want to reduce the list. Take using reduce to find the sum of a list: [1, 2, 3].reduce((a, b) => a + b, 0).
Use filter if you want to filter a list. arr.filter(i => !set.has(i)).
You may want to instead use regex.replace. However, it'd require checking your chars for any regex escape stuff.

However if you ignore that, it could be as easy as:

function remove(str, chars) {
  return str.replace(new RegExp(`[${chars}]`, 'g'), '');
}

Otherwise using the above, for \$O(n)\$ time and space complexity, could get you:

function remove(str, chars) {
    var set = new Set(chars);
    return [...str].filter(i => !set.has(i)).join('');
}


Don't use public fields. Instead, make them public properties.
Use proper naming.
What is sp? storedProcedureName will be better.
Dictionary is a collection of parameters. Therefore, use the plural name: parameters.
Using the AddWithValue method may result in poor query performance. Use the Add method with the exact SqlDbType type specified.
The ExecuteNonQuery method returns the number of rows affected. Therefore, your ExecuteResultWithParameter method should return this value.
You can get rid of the bool result variable. The failure of the method should be signaled by an exception that is re-thrown in the catch block: throw ex; (please note: the name starts with a small letter).
The ReturnResultWithParameter method has an unused sp parameter. Remove it.
You swallow exceptions with empty catch blocks. Therefore, there is no way to find out about query errors.
In all methods, you dispose of the connection and the command in the finally blocks. After that, the methods cannot be called again without re-instantiating the class.
There are extra empty lines in your code - this is also an error.
Many of the errors I described will catch Visual Studio extensions like FxCop, StyleCop, and others. They will not only find them, but also suggest ways to fix them. Start using these extensions.


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

Throw errors rather than printing error messages

The user of your code may be creating a GUI with no command line available and will not appreciate having your code printing instead of indicating an error to the calling code.  The two ways that C++ programs generally signal an error are either by throwing an exception (if the circumstance really is exceptional) or by returning a value that indicates an error.

Use consistent formatting

The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.

Consider adding functionality

Since this is a fixed-size rather than a dynamically sized stack, it would make sense to either allow the user to specify that size (as perhaps with a default parameter for the constructor) and to query it.  Also, consider adding functions such as isFull() and isEmpty().


To avoid the messy switch block, you should probably create an interface or abstract class called FileConversionHandler:

public abstract class FileConversionHandler {
    public abstract void process(File f);
}

Then, for each type of file, make a subclass that implements process() differently.


Extract common code in each conditional branch

In the block:

    switch (c) {
        case R_BRACE:
            currString.insert(0, L_BRACE);
            i++;
            count++;
            break;
        case R_BRACKET:
            currString.insert(0, L_BRACKET);
            i++;
            count++;
            break;
        case R_PAREN:
            currString.insert(0, L_PAREN);
            i++;
            count++;
            break;
    }

You always execute:

        i++;
        count++;

So you can simplify and write just:

    switch (c) {
        case R_BRACE:
            currString.insert(0, L_BRACE);
            break;
        case R_BRACKET:
            currString.insert(0, L_BRACKET);
            break;
        case R_PAREN:
            currString.insert(0, L_PAREN);
            break;
    }
    i++;
    count++;


Very small start to MVC refactor in iOS app

if (_phoneNumbers) {
    [_phoneNumbers removeAllObjects];
}

if (!_phoneNumbers) {
    //Create _phoneNumbers array
    _phoneNumbers = [[NSMutableArray alloc]init];
}

Instead of this, we can replace all these lines with simply:

_phoneNumbers = [NSMutableArray array];

The best advantage of this, is we don't run into any problems of emptying an array that someone else might have a reference to.  This could cause problems if, for example, you were using the phone numbers array as the data for a table view.  If you all of the sudden removed all the objects, but didn't call reloadData on the table view, the next time it tried grabbing a cell, it could be an index out of bounds.

ABMultiValueRef *phoneNumberRef = ABRecordCopyValue(_contactRef, kABPersonPhoneProperty);

NSString *phoneNumber = [[NSString alloc] init];

// Make sure multi value ref exists
if (phoneNumberRef) {
    CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumberRef);

    for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
        phoneNumber = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phoneNumberRef, i);
        CFStringRef label = ABMultiValueCopyLabelAtIndex(phoneNumberRef, i);
        if (label) {

        [_phoneNumbers addObject:phoneNumber];
            NSLog(@"phoneNumbers count in method: %d", _phoneNumbers.count);
        }
        CFRelease(label);
    }
    CFRelease(phoneNumberRef);
}

I think this section is problematic.  I don't know enough about AddressBook to really tell you for sure, so for now I'm just mentioning it and reserving a section for in the future if I come back and figure out what's wrong with it.  The CFRelease on phoneNumberRef seems particularly suspicious.

BOOL result = [self.addressBook requestAccess];

if (!result) {
    [self performSegueWithIdentifier:@"addFriendsToMediaCaptureSegue" sender:self];
}

if (result) {

This could and probably should be refactored into:

if (![self.addressBook requestAccess]) {
    [self performSegueWithIdentifier:@"addFriendsToMediaCaptureSegue" sender:self];
} else {

But... with that said, I did take a look at the requestAccess method in the link.  Strictly speaking, it's not in the question and so it's not strictly up for review, but, I'm quite certain it will always return NO, as the return is synchronous but the variable being returned is only set in an asynchronous block, and as such, will always be set too late.

int index2;
for (index2 = 0; index2 < self.currentContact.phoneNumbers.count; index2++) {
    if (self.currentContact.firstName) {
        // Add current contact's phone number to array
        [self.potentiaFriendsPhoneNumberArray addObject:self.currentContact.phoneNumbers[index2]];

        // Add current contact's first name to array
        [self.potentiaFriendsNotInParseFirstNamesArray addObject:self.currentContact.firstName];
    }
}

First, we can declare our iterator variable in the for loop initialization statement.  Remember, you did this a few lines up.  But perhaps more importantly, why don't we use a forin?

for (id phoneNumber in self.currentContact.phoneNumbers) {
    [self.potentialFriendsPhoneNumberArray addObject:phoneNumber];
    [self.potentialFriendsNotInParseFirstNamesArray addObject:self.currentContact.firstName];
}

We should also move the if check outside the loop so that the entire loop can be circumvented in the case that we're never going to add anything anyway.  Embed the loop within the if.

Also, it doesn't make a ton of sense to me for there to be two separate arrays. I understand that you'll want a name associated with all the phone numbers, however it's better to do this with a single array, either by filling it with dictionaries with a key for the phone number and a key for the name, or by creating a custom object that will hold both of these parts.


Another problem with making the enum values pointers, is that it changes the in-memory representation of an enum. There are many situations where it's necessary for the enum to be an int (such as reading/writing structs to/from files).

If you need type-checked enums, it is better to use C++.


Finding multiples of 3 or 5 with MIPS assembly (Project Euler #1)

Your code is very clean and simplistic, which is a good thing. There is just one glaring problem that I see.

div
As you may already know, the div instruction is very slow instruction. I don't know precisely how slow, but on the x86 systems, the instruction has a latency of about 70.
A better solution would be to treat two registers as counters for the numbers 3 and 5. Here is what I mean by that:

Load register A with 3
Load register B with 5
Subtract 1 from A
Subtract 1 from B
If A == 0, increment the total by the iterator. Load A with 3 and go to step 3.
If B == 0, increment the total by the iterator. Load B with 5 and go to step 5.

By replacing these steps with the div instruction, your code will run significantly faster.

If you would like me to show you how your code would look with the above change, let me know in a comment.


Finding the possible number of equal pairs in an array

Based on the calculation of the number of pairs -your assertion is correct.
The whole calculation method could be simplified by:
    public static List<KeyValuePair<int,int>> solution(int[] A)
    {

        //n(n-1)/2 number of pairs by a given set
        return  A.GroupBy(x => x).ToList().
            Select(y => new KeyValuePair<int, int>((y.Count() * (y.Count() - 1)) / 2, y.Key)).ToList();
    }


Using closure, alias and namespace extension patterns: How to allow for independent instantiations of plugin?

There is only one copy of window.FOO and window.FOO.init, despite its name does not create new objects. window.FOO.init just overwrites _msg that (function(exports) {... closed over each time it is called. _listenForChange() holds a reference to the closed over _msg. If you want it to keep a copy of the value at the time init is called then you can do like so:

_addEvent(window, 'resize', listenForChange2(), exports);

var listenForChange2 = function() {
    var msg = _msg; // keep own copy of the _msg
    return function() {
        var li = document.createElement('li');
        li.innerHTML = String("second version " + msg);
        _ol.appendChild(li);
        if (typeof console !== 'undefined') console.log(msg);
    }
}

Review of the code posted in the EDIT #1

First of all you are still confused about closures. It is important that you understand them because they are how you associate some state with a function. But explaining closures is not within the scope of Code Review. And you probably won't get any better answers than these, the accepted answer in this SO question and this article linked from there. You can fix your bug if you understand these.

Also the answer above fixes the bug if you KEEP the parens here:

_addEvent(window, 'resize', listenForChange2(), exports);

I the JSBIN you posted just add the parens and It works. So I will not repeat how can you fix the answer in the new code.

Onto the review. I will go over the code top down:

    exports.init = function(arg) {

By convention init method of an object is used for object initialization. It is not what it does here. Better name

       this._msg = arg;

You need not keep a copy of _msg since it will not be used elsewhere. You prepend the name with an underscore as if to indicate it is a private member (which practice I do not recommend BTW), but then expose it as public by assigning to this.. You can see, in the Firebug console for example, that Foo._msg is defined.

    exports.listenForChange = function() {

You need not expose this either.

    var listenForChange = function() {

would be just as good.

        var msg = this._msg;

If you do not create a new function, copying the value does not do anything.

    exports.addEvent = function(elem, type, handle, context) {

You need not expose this either, as it will not be called like Foo.addEvent.

Also adding another layer of indirection solving any problem, does not apply here.
Whenever there is something you do not understand, namely a bug,
adding another layer exacerbates the problem.
What does this refer to when the listenForChange function is run?

Even if you fix your bug this may introduce another one:

                elem['on' + type] = function() { handle.call(context); };

You are overwriting the onclick. Only the last handler assigned to the onResize will fire.

This is unnecessary:

    return exports; // Expose the API.

No one is using the returned value.
Moreover the comment is misleading as everything you assingn to exports. will be exposed,
whether you return it or not.


Setting Property Values Programmatically in a JSON Object

Stupid nitpick..

There's no such thing as a JSON object in Javascript, they're just objects in Javascript. JSON stands for JavaScript Object Notation - Talking about JSON objects in the context of Javascript is like saying "strawberry flavored strawberry ice-cream which is strawberry flavored." Sorry. </rant>

Best option

If this is a realistic representation of your objective then the third one is the best, fastest and most concise. Creating a function to add two numbers is a waste of space and memory. Creating a variable is also a waste of memory as it will just have to get garbage collected.

Approaches you aven't considered

class add2Numbers{
    constructor(){
        this.addend = 0;
        this.augend = 0;
        this.result = 0;
    }

    parseNum(n){
        return parseFloat(n);
    }

    addAddend(n){
        this.addend = this.parseNum(n);
    }

    addAugend(n){
        this.augend = this.parseNum(n);
    }

    doMath(){
        this.result = this.addend + this.augend;
    }

    getResult(){
        return this.result;
    }
}

function insertProperty(obj, key, value){
    obj[key] = value;
}

var o = {};
var adder = new add2Numbers();
adder.addAddend(2);
adder.addAugend(5);
adder.doMath();
var result = adder.getResult();
insertProperty(o, 'sum', result);

// o now contains a property called 'sum' which contains the
// sum of the numbers 2 and 5
console.log(o);

</sarcasm>

The point that I'm trying to make is that new programmers and even old ones for some reason spend way too much time worrying about stupid buzzwords that they completely forget about common sense. The only buzzword you need right now is K.I.S.S.

Good luck and godspeed.


How to exactly work with the JSON Object and jQuery, adding info to posts

I don't think that I can give reasons why this is better (i.e. faster).  Only I feel that it is more readable and scalable.

I like to use the data attributes for information like ids.  For a long time, classes were the way to go but we had to deal with cluttered classes :(.  Data attributes keep things cleaner in my opinion–plus it makes it easier to have multiple counters on the page.

x

y

z

x

y

z

Using the same data:

var data = {
    "posts": {
        "60": { "x" : "100", "y" : "200" , "z" : "300" },
        "64": { "x" : "400", "y" : "500" , "z" : "560" }
    }
};

And then using javascripts for-in:

var posts = data.posts;

for(var item in posts) {
    for(var counter in posts[item]) {
        var selector = "[data-counter=" + item + "-" + counter + "]",
            count = posts[item][counter];

        $(selector).text(count);
    }
}


Implementing String to int (atoi) in Java

All in all, that's a pretty good implementation in a number of key details.

Using the Character.isDigit() and Character.getNumericValue() methods are good to see.

The Math.* methods that handle the overflow conditions are good too.

I am not sure if you intended it, but you also correctly handle an obscure edge-case in 32-bit signed integer systems (not just Java), where Integer.MIN_VALUE is not the same as - Integer.MAX_VALUE ... and your code actually gets it right for an exact input of the text "-2147483648"

So, you have good details in your code.... and I can't see any broken edge-cases.

My only recommendation would be that a state-machine may make things simpler... with just one loop..... but the state-machine may be a bit messy too, although I think it works out better in the long run...

public static int rlAtoi(String str) {
    boolean started = false;
    boolean negative = false;
    int result = 0;
    try {
        for (char c : str.toCharArray()) {
            if (!started && Character.isWhitespace(c)) {
                // great, ignore it.
            } else if (!started && (c == '+' || c == '-')) {
                // great, a sign
                negative = c == '-';
                started = true;
            } else if (Character.isDigit(c)) {
                result = Math.multiplyExact(result, 10);
                result = Math.addExact(result, Character.getNumericValue(c));
                started = true;
            } else {
                // done....
                break;
            }
        }
    } catch (ArithmeticException e) {
        return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
    }
    return negative ? -result : result;
}

Note that in a raw performance benchmark, I suspect your solution will be (slightly) faster, but I prefer readability over small incremental performance gains, unless performance is extremely critical.


Set state in life cycle events from props

In order to keep to the React pattern and stick to immutability of props simply separate your code to have a parent component which carries out the logic and passes the the date to the child component which can then be displayed in the child's render component.

It would then look something like this:

var React = require('React');

var MomentDisplay = React.createClass({
    propTypes: {
        date: React.PropTypes.string.isRequired
    },
    render: function() {
        return (
            <span>
                {this.props.displayDate}
            </span>
        )
    }
});

var MomentAgo = React.createClass({
    getInitialState: function () {
        return {
            date: null,
            displayDate: null
        };
    },
    componentWillMount: function () {
        this.setState({date: this.props.date});
    },
    componentDidMount: function () {
        setTimeout(function(){
            this.setState({displayDate: date.format('DD MMMM YYYY')});
        }, 3000);
    },
    render: function () {
        return (
            <MomentDisplay displayDate={this.state.displayDate} />
            )
        }
});


Thread which executes code after Thread.sleep() and can be cancelled only if it's sleeping

I haven't analysed your code in detail, but it looks threadsafe on a quick scan.
I'd just suggest that you avoid reinventing the wheel. The java.util.Timer class will, I think, fit your use-case and is clearer that you are cancelling rather than interrupting your scheduled task. I think we can be fairly confident that it has been well-enough designed, implemented and reviewed to be threadsafe ...


extending Exception to allow for auto appending class name on exception message

Changing an inherited method signature isn't a good idea. It means how you call a method changes depending on what exact class you're calling.

Exception::__construct has only 3 arguments, but the first of which can be anything. As such you could do:

class DataException extends Exception
{
   protected $solved;
   protected $howSolved;

   public function __construct($message = null, $code = 0, Exception $previous = null)
    {
    $solved = $howSolved = false;
    if (is_array($message))  {
        $solved = $message['solved']; // message is an array
        ...
        $message = $message['message']; // and now it's a string to be used/compatible with the parent
    }

Which would work whether $message was a string or an array - and without changing the method signature.

Why do you have setters for properties on a exception? Sounds like you're using exceptions for something they aren't designed.


You should pass O to your bsf and terminate it, once you reach zero oxigen. Big map with low O can cause TLE.
You don't need the map, you can reuse the array and just mark visited spots (e.g. with '*'). This would be wave algorithm (handle all nodes in the queue at the start of the step, reduce counter O and proceed to next step, unless T or zero O reached). This is simplification of Dijkstra algorithm for graph with all weights=1.
Your code is hard to read. You are on Code Review! You are using C++ but program like in old C. Use typedef instead of #define when possible, avoid super-shortcuts like s and s2, please.


How can I make this jQuery code better so variables aren't repeated and the code is more efficient?

Have a look at the .hover() event and .toggleClass().

With those, you could do:

item.hover(function (event) {
  var hovering = event.type === 'mouseenter',
      cover = $(this).find('.item-cover'),
      title = cover.find('.title');
      description = cover.find('.short-description'),
      separator = cover.find('.seperator');

  // skip this by simply adding "animated" in the HTML to begin with
  $().add(cover, title, description, separator).addClass('animated');

  // toggle with a boolean argument to force one state or another
  cover.toggleClass('fadeOut', !hovering).toggleClass('fadeIn', hovering);
  title.toggleClass('fadeOutDown', !hovering).toggleClass('fadeInUp', hovering);
  description.toggleClass('fadeOutUp', !hovering).toggleClass('fadeInDown', hovering);
  separator.toggleClass('fadeOut', !hovering).toggleClass('fadeInUp', hovering);
});

But it might be nice to be more "declarative" by adding a little helper function:

item.hover(function (event) {
  var hovering = event.type === 'mouseenter',
      cover = $(this).find('.item-cover'),
      title = cover.find('.title');
      description = cover.find('.short-description'),
      separator = cover.find('.seperator');

  // toggle the enterClass if mouse is hovering, otherwise toggle leaveClass
  function setClass(selection, enterClass, leaveClass) {
    selection.toggleClass(enterClass, hovering).toggleClass(leaveClass, !hovering);
  }

  // skip this by simply adding "animated" in the HTML to begin with
  $().add(cover, title, description, separator).addClass('animated');

  setClass(cover, 'fadeIn', 'fadeOut');
  setClass(title, 'fadeInUp', 'fadeOutDown');
  setClass(description, 'fadeInDown', 'fadeOutUp');
  setClass(separator, 'fadeInUp', 'fadeOut');
});

By the way, it's "separator" with two a's, not two e's.