Consistency

Sometimes you use snake_case and sometimes you use camelCase: in JavaScript we usually use camel case, it's not mandatory but stick to one. Then, for example, count_el should be countEl (or a better, more descriptive name, IMHO no need to abbreviate element here.)

In ctor you saved a copy of some properties to abbreviate (I suppose) code elsewhere however, you use it just once. You can drop it altogether.

Reuse

You parse a boolean value twice, it's enough to introduce a more robust function:

const parseBoolean(value) => (/true/i).test(value);

There are a few different techniques to parse a boolean (direct string comparison as you're doing, regex, JSON.parse(), and few more). Just pick one, in this case it's not probably that important. Note: use === instead of ==.

Now that you have a function (which accepts, via conversion, both a boolean and a string) you can write:

toggle() {
    this.el.dataset.toggled = !parseBoolean(this.el.dataset.toggled);
}

In this example I'm storing boolean, add .toString() if appropriate. toggleCount() will then use if (parseBoolean(this.el.dataset.toggled)). You may want to introduce a function const isElementToggled = () => parseBoolean(this.el.dataset.toggled);.

Style & misc

IMHO setClickHandlers() does both too little and too much. Its responsibility is to add a click handler (and it's too little to be a separate function) but it also IS the click handler (and it's too much). Declare a separate function:

handleClick(e) {
    this.postVote();
    this.toggle();
    this.toggleCount();
}

And attach it directly in your ctor:

el.addEventListener("click", this.handleClick.bind(this));

If you're targeting ES6 then do not use (unless there is a strong compelling reason) var, use const and let instead.

The snippet where you create Vote may be simplified, no need to check Array.length if using Array.forEach():

document.addEventListener("turbolinks:load", ()=> {
  document.querySelectorAll('[data-vote]').forEach(x => new Vote(x));
});

If the AJAX call to post a vote fails then you local counter is already incremented and it won't go back. The problem is that you consider these actions as part of the click event handler when they should really be an effect of the sucessfull AJAX call:

axios({ ... }).then((data) => {
    this.toggle();
    this.toggleCount();
});

In this way if the call fails you won't have unsynchronized UI. Alternatively, if call is really slow, you may want to update UI immediately and revert it back if failed:

this.toggle();
this.toggleCount();

axios({ /* ... */ }).then((data) => {
    // ...
}).catch((data) => {
    this.toggle();
    this.toggleCount();
});

In any case the code to attach the event handler in ctor will then simply be:

el.addEventListener("click", this.postVote.bind(this));

I, personally, find that to create a discardable object only because of its side effects is slightly misleading for the reader. In JavaScript you can have nested functions and if you do not need to carry a state then you do not need classes. There is no reason to avoid something like this:

document.addEventListener("turbolinks:load", ()=> {
  document.querySelectorAll('[data-vote]').forEach(attachClickHandler);
});

Where attachClickHandler() is simply:

function attachClickHandler(element) {
    function postVote() { /* ... */ }
    function toggle() { /* ... */ }
    function toggleCount() { /* ... */ }

    el.addEventListener("click", postVote);
}

Code might be even more simple if you had a module for this "Vote Component" but it really really depends on the UI framework/library you're using (if any.)


Grouping a Pandas Dataframe by two parameters

In all your code was not too bad. You can groupby on 2 items:

votes_per_state = df.groupby(["state", "party"])["votes"].sum().unstack(fill_value=0)

state Aam Aadmi Party All India Trinamool Congress    Bharatiya Janata Party  Communist Party of India (Marxist)  Indian National Congress    other
Andaman & Nicobar Islands 3737    2283    90969   1777    83157   0
Andhra Pradesh    0   0   85  0   0   100

Then you can define which party you're interested in, and manually assemble a DataFrame

party_of_interest = "Bharatiya Janata Party"
result = pd.DataFrame(
    {
        party_of_interest: votes_per_state[party_of_interest],
        "total": votes_per_state.sum(axis=1),
    }
)

state Bharatiya Janata Party  total
Andaman & Nicobar Islands 90969   181923
Andhra Pradesh    85  185

If you want you can even add a percentage:

result = pd.DataFrame(
    {
        party_of_interest: votes_per_state[party_of_interest],
        "total": votes_per_state.sum(axis=1),
        "pct": (
            votes_per_state[party_of_interest]
            / votes_per_state.sum(axis=1)
            * 100
        ).round(1),
    }
)

state Bharatiya Janata Party  total   pct
Andaman & Nicobar Islands 90969   181923  50.0
Andhra Pradesh    85  185 45.9


Regular expression to identify java function

I have no idea what you are trying to match with \\s+\\w+\\s+\\w+\\s*.  If you are looking for a return type, then that won't do at all.

It appears that you are trying to match the function body using \\{.*\\}.  That won't work, because braces may be nested, and regular expressions cannot handle nesting.

Modifier keywords can appear in any order, and you are missing a few, such as:

synchronized
transient
volatile
strictfp

If you want to implement this correctly, don't just make assumptions based on code that you have been seeing.  Read the Java Language Specification.


I don't think that time complexity could be improved. An in-place approach is to flatten the tree into a list (the key is to reuse child pointers), and recreate the tree as BST. To flatten,

    def flatten(root):
        rightmost = get_rightmost(root)
        while root:
            rightmost.right = root.left
            rightmost = get_rightmost(root.left)
            root.left = None
            root = root.right

The time complexity of flattening is linear.

To recreate,

    def list_to_bst(root):
        cursor = root
        while cursor:
            next = cursor.right
            cursor.right = None
            root = insert(root, cursor)
            cursor = next

insert is a standard (or balanced, if you want to go fancy) BST insertion. get_rightmost is trivial.

There is no recursion, so the space complexity is constant. The time complexity is bounded by insertion, that is in a \$O(n\log n)\$ ballpark.


Exposing the IV only leaves room for errors. Simply generate it at the start of encryption.
There is no point in having a completely unrelated hash method on this class.
There is not integrity protection, so an attacker who can modify the ciphertext you decrypt will likely be able to pull off a padding-oracle attack. Unfortunately it's not trivial to combine streaming decryption with integrity protection, since you must ensure that you don't release any plaintext you haven't authenticated.
Once you eliminate the IV storage, as recommended above, you have no state to preserve across calls, which means you don't need any instance fields anymore. They only make your class thread-unsafe without any benefit.
Closing out seems pretty weird, I wouldn't expect that behaviour. On the other hand you don't close in.
If you decide to dispose resources, use try...finally (or try-with-resources) to do so reliably.
I'd make the class immutable and threadsafe, storing only the key (and algorithm if it's not hardcoded) in it.


Cleaning up conditional statements regarding new values

You can use the null-coalescing operator ?? like this:

NewPosition = (newValues["Position"] ?? "").ToString();

The core of this approach is this expression:

newValues["Position"] ?? ""

The ?? operator evaluates the left expression first (i.e. newValues["Position"]), and uses it as the result if it's not null. If the first expression is null, the second expression is evaluated, and its result is returned as the overall result of the expression.

For the last one, use ?:

NewAppt = (newValues["Appts"] != null) ? 1 : 0;


Calculate next position and velocity after "bounce"

Review

You have redundant code. Store position + velocity in a variable.
Use well-known variable names when the code is of a mathematical nature. Distance x Velocity v A clamped area [a,b].
It is not clear from your description what should happen if the distance is so far away from the boundaries, that when reflecting the movement you are still out of bounds, but on the other side.
.x(max - ((position + velocity) % max)) This does not correspond to your description of

  the next position should be equal to the amount the object would be beyond the boundary subtracted from the boundary

Proposed Solution

Use mathematical variable names.
Allow damped bouncing when the distance is too far out of bounds (Damped bouncing reflects the value x, alternating around the boundaries until it is clamped with the area [a,b]).
Make both 0 and max a variable, respectively a and b.

public TwoVector<Double> getNextPositionAndVelocity(double x, double v, double a, double b)
{
    assert a < b;
    double xn = x + v;

    // the loop allows for damped bouncing
    while (true) {
        if (xn < a) {
            xn = a - xn;
            v = Math.abs(v);
        }
        else if (xn > b) {
            xn = b - (xn - b);
            v = -Math.abs(v);
        }
        else {
            break;
        }
    }

    return TwoVector.<Double>builder().x(xn).y(v).build();
}


Different Constructors, Same Implementation

Two things your could do:

Refactor the common code into a method (like Initialize) and call that:

private void Initialize()
{
    base.GetProperty("FirstName");
    base.GetProperty("LastName");
}

public Person(Dictionary dictionary, string someString)
    : base(dictionary, someString)
{
    Initialize();
}

public Person(Dictionary dictionary, string[] someStringArray)
    : base(dictionary, someStringArray)
{
    Initialize();
}

Not sure whether that's an option as I don't know how the behaviour changes but you could reduce one case to the other:

public Person(Dictionary dictionary, string someString)
    : this(dictionary, new [] { someString })
{
}

public Person(Dictionary dictionary, string[] someStringArray)
    : base(dictionary, someStringArray)
{
    base.GetProperty("FirstName");
    base.GetProperty("LastName");
}

Apart from that:

I'd avoid the casting. Apparently only strings or arrays of strings make sense to be passed in. If you change the parameter to object then it is no longer clear to the caller what he can and cannot pass in and would have to write a test to make sure that what he is passing in will be accepted. It reduces the clarity of the interface.
GetProperty seems to be a strange thing to call in a constructor. I'd expect it to return a property value yet you do nothing with the return value.
Consider making "FirstName" and "LastName" (and any other property string you use) string constants rather than literals - especially if you use them in more than one place. Lambda expressions might be an option if they are actual properties on the object.


An alternative route is to use string.replace() and Regular Expressions to strip everything but the vowels from the string. Then count the length of the resulting string. This avoids iteration altogether.

const vowelCount = s => s.replace(/[^aeiou]/gi, '').length

console.log(vowelCount('The quick brown fox jumps over the lazy dog'))

The regex is /[^aeiou]/gi which means match everything that's NOT (^) in the set (aeiou), matching globally (g flag) and without regard to case (i flag). string.replace() then uses this pattern to replace all matching characters with a blank string. What remains are your vowels.


Name your variables and fields meaningfully. I have no idea what a,b,e, etc are.
Don't split your variable declaration and initalization. Instead of

final EditText ed;

Button dlt;

dlt = (Button) findViewById(R.id.button1);

ed = (EditText) findViewById(R.id.editText1);

do

final EditText ed = (EditText) findViewById(R.id.editText1);
final Button dlt = (Button) findViewById(R.id.button1);

And be consistent with your final usage. Either use it everywhere where appropriate or don't. Otherwise I start to wonder why ed is final and dlt is not.
There a TextUtils.isEmpty() method available on Android. Use it instead of

a11 != null && !a11.trim().equals("")

Use static field access. Instead of t1.LENGTH_SHORT use Toast.LENGTH_SHORT. All the fields t,t1 and t2 are unnecessary.
All your fields should be local variables.


Let's talk about this bit of code.

    int index=HashFunction(value.label);
    index = index % data.length;
    int increment = 1;
    boolean inserted = false;
    while (!inserted)
    {
        if (data[index] == null)
        {
            data[index] = new EdgeHashPair();
            data[index].addItem(value);
            noofitems++;
            inserted = true;
        }
        else
        {
            if (data[index].data.GetItem(0).label.compareTo(value.label) == 0)
            {
                data[index].addItem(value);
                inserted = true;
                noitems++;
            }
            else
            {
                index = index + (increment<<1);
                index = index % data.length;
            }
        }
    }

First, you have an else block in here...

        else
        {
            if (data[index].data.GetItem(0).label.compareTo(value.label) == 0)
            {
                data[index].addItem(value);
                inserted = true;
                noitems++;
            }
            else
            {
                index = index + (increment<<1);
                index = index % data.length;
            }
        }

... containing only an if-elseif chain. Merge these as such:

        else if (data[index].data.GetItem(0).label.compareTo(value.label) == 0)
        {
            data[index].addItem(value);
            inserted = true;
            noitems++;
        }
        else
        {
            index = index + (increment<<1);
            index = index % data.length;
        }

Second, you only use increment in a constant expression (increment<<1). Consider replacing this with the raw constant instead.

Third, you always loop at least once. So replace your while loop with a do-while loop.

Now for some design issues that could lead to reduced performance...

                int index = HashFunction(oldMap1.data.GetItem(0).label);

    int index=HashFunction(value.label);

When you resize the map, you rehash all the entries, even although their values didn't change. Store the calculated hash in the item.

    for (int i=0; i < key.length(); i++)
    {
        code = code*53+(key.charAt(i));
    }

When you hash the key, you do so via for-loop over String.length() and String.charAt. These are two function calls, and String.charAt continuously checks the length. Consider declaring a char array of length key.length(), then setting it with String.getChars. I'm assuming you have keys of a decent length here, and not very short. Do several performance tests for this, at different times and with different sets of data.

Performance-tuning your code is likely to be hard without semantics surrounding your code and timing information. See if there's ways to profile which functions take longest... on a more granular level than just this function.


Avoid code duplication
Your code is more verbose than necessary, because you are repeating a lot of things unnecessarily, or write things in a more complex way than necessary. For example:
(index + (index + length)) / 2

This looks really weird, and is actually equivalent to:
index + length / 2

Which makes much more sense. Even with that change, that expression is used a lot in the code, so it's best to give it a name:
uint32_t middle = index + length / 2;

You also duplicated a call to mergesort_helper() in order to handle odd and even cases of length. However, you don't have to if you write it like so:
uint32_t middle = index + length / 2;
uint32_t end = index + length;

mergesort_helper(array, index, middle - index, size_element, compare, storage);
mergesort_helper(array, middle, end - middle, size_element, compare, storage);

You might also want to consider renaming index to start.
Use const for pointer arguments in compare()
Since the function compare() should not modify the elements it is comparing, the arguments should be pointers to const:
int32_t compare(const void *ptr1, const void *ptr2) {
   const int32_t *temp_ptr1 = ptr1;
   const int32_t *temp_ptr2 = ptr2;
   ...
}

Optimizing the while-loop
There are a few minor changes that can be made to speed up the while-loop a little bit. First, calling compare() is probably going to be the most expensive operation, so you would want to avoid calling it if possible. Rearrange the order in which you check things to make use of short-circuiting:
if(i < middle && (j >= end || compare(...)))

In the above, compare() will only be called if i < middle is true and j >= end is false.
Another possible optimization is realizing that if i >= middle || j >= end, you know you only need to copy the remainder of one side of the midpoint. Instead of doing that element by element, you could do that in one large memcpy(). It also simplifies the if-statements in the while-loop, like so:
while (i < middle && j < end) {
    if (compare(array + i * size_element, array + j * size_element) <= 0) {
        memcpy(storage + k * size_element, array + i * size_element, size_element);
        i++;
    } else {
        memcpy(storage + k * size_element, array + j * size_element, size_element);
        j++;
    }

    k++;
}

/* Copy the remainder */
if (i < middle) {
    memcpy(storage + k * size_element, array + i * size_element, size_element * (middle - i));
} else {
    memcpy(storage + k * size_element, array + j * size_element, size_element * (end - j));
}

The above has also the advantage that compare() is only called once every iteration, whereas in your original code it could have been called twice.
Avoid void pointer arithmetic
Lau G mentioned void pointers, and indeed doing arithmetic on void pointers is illegal. The simple workaround is to cast it to a char * first:
static void mergesort_helper(void *array_ptr, ...)
{
    char *array = array_ptr;
    ...

To catch these sort of issues, enable strict compiler warnings. For GCC and Clang, use -Wall -pedantic. Fix all the warnings the compiler produces.


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

Use direct initialization

In the first line, we have this:

std::vector <int> v = { 2, // ...

However, this may be shortened slightly by simply omitting the =:

std::vector <int> v{ 2, // ...

This is list initialization which was standardized in C++11.

Use "range-for" to simplify the loop

Instead of using this somewhat complicated for loop:

for (int i = 1, countMode = 1, count = 1; i < v.size(); ++i) {

You could instead use a range-for:

for (const auto n : v) {

Avoid doing needless calculations

By definition, in a sorted list the first number will be min and the last max, so there's not much point in making those calculations.

Use better naming

Variables min and max are good because they give a good clue as to what they hold.  However, number might be better called prev since it's the previous number in the sorted list.

Here's one way to do all of that:

int max = v.back();
int min = v.front();
int prev = max;
int mode;
int maxcount = 0;
int currcount = 0;
for (const auto n : v) {
    if (n == prev) {
        ++currcount;
        if (currcount > maxcount) {
            maxcount = currcount;
            mode = n;
        }
    } else {
        currcount = 1;
    }
    prev = n;
}


Jasmine test involving a sequence of actions

The anonymous functions and hardcoded values can be abstracted. For example:

function click(value){
    utils.clickHotspotElementAtIndex(view, value, Function);
}

function tests(value){
    expect(utils.verifyHotSpotHasBeenHiglightedAtIndex(view, value)).toBe('true');
}

function test () {
    [0, 1, 2].map(tests);
}

Then the asynchronous code can be modernized via async/await:

async function sequencer() {
    const clicks = [1, 0, 2].map(click);
    await Promise.all(clicks);
}

function run() {
    beforeEach(sequencer);
    it('Then allow highlighting multiple responses', test);
}

And the call can simply be a one-liner:

describe('When a user selects a multiple-response Hotspot response', run);

References

Jasmine Tutorial: Asynchronous work
JavaScript loops - how to handle async/await


I see 1 bug, 1 problem and 1 minor thing:

as listed in the comment above: You are returning the number instead of the index. That's not very helpful for a binary search algorithm ;)
when the array does not contain the item you are returning 0. 0 is a valid array index, by convention you'd return -1 in that case.
not much of a problem but unnecessary: local variable number in first else block is obsolete.


Speech Synthesis to showcase how various voices sound with System.Speech.Synthesis

Take a look at arrays. It will allow you to quickly add and remove future options without needing to change the logic of the code. It will also allow you to possibly add more complex logic in a single place, instead of having to add code to every if/switch statements.

string[] options = { "Microsoft Hazel Desktop",
                     "Microsoft Heera Desktop",
                     "Microsoft David Desktop",
                     "Microsoft Zira Desktop",
                     "Microsoft Haruka Desktop",
                     "Microsoft Heami Desktop",
                     "Microsoft Huihui Desktop",
                     "Microsoft Tracy Desktop",
                     "Microsoft Hanhan Desktop"};

try
{
    synth.SelectVoice(options[comboBox.SelectedIndex]);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}


I'm not sure how I feel about you hardcoding that this should be a 4x4 matrix of floats, and that it should be column major. It seems straightforward enough to make a templated class like so

template <typename T, size_t numRows, size_t numCols>
class Matrix {
...
};

using mat4 = Matrix<float, 4, 4>;

It might also be worthwhile to have a boolean template parameter for whether or not it should be row or column major; in my experience many applications assume something is row major, and interfacing with your application might yield some unexpected issues.

If you do so, then I think adding a constructor to switch row/column major would be worthwhile as well.

I personally like using operator() instead of operator[] for getting a value at a given row and column; I feel like in general it shouldn't be up to the user to manually calculate the 1d index.  Something along the lines of this:

constexpr const T& operator()(size_t row, size_t col) const noexcept
{
    return matrix[col * numCols + row];
}

constexpr T& operator()(size_t row, size_t col) noexcept
{
    return matrix[col * numCols + row];
}

I also generally assume that at() (or similar) will be provided if indexing (or operator()-like access) is provided.

Don't use a member function like print(); instead implement operator<< so people can use it with their own streams as desired.  I see you're using printf - why? I've definitely used it before in my programs, but I usually think of it as a code-smell. If you want to add printf support that's fine, but I would argue that streams should be prioritized.

Your operator== is unnecessarily complicated - std::array implements it.

I don't like using this-> to refer to member functions; just use them.  Then your operator!= becomes return !operator==(other).

operator+= and operator*= can be done using std::transform.

You should implement iterators for your matrix as well. Whether you make them row-major or column-major shouldn't matter, but be consistent (assuming you make it possible to switch between orientations). No matter the orientation, the iteration order should be the same.

You should add some improved matrix multiplication algorithms (or, ideally, use a library that does it for you). With some SFINAE wizardry you can probably make a vectorized version, a tiled version, etc.  Probably only necessary if you actually make it possible to use larger matrices, although vectorization will probably still be a bit faster even for a small one.


Karger's min-cut algorithm implemented in python

contract_edge does not select edges with uniform distribution, because first a random vertex is selected and then a random edge of that vertex is chosen. This produces a skewed distribution on edges, with edges on low degree vertices having a higher chance of beeing selected than those of high degree vertices.


How can i simplify the following If code?

Use functions instead of repeating yourself The only difference between the tipo === 'asporto' branch and the tipo === 'takeaway' branch is the property name that gets passed into setHours: either .oreMinimeAsporto or .oreMinimeTakeaway. Create a function that takes that value as a parameter, then call it with either .oreMinimeAsporto or .oreMinimeTakeaway instead. That will about halve the size of your code.
const curDate = new Date();
const { tipo } = this.carrello;
if (tipo === 'asporto' || tipo === 'takeaway') {
    const casedProp = tipo[0].toUpperCase() + tipo.slice(1);
    changeDate(
        currDate,
        this.negozioSetup['oreMinime' + casedProp],
        this.negozioSetup['limiteOre' + casedProp],
    );
}

Split only once and destructure to grab the ore and minti values at once. You can also use Number instead of parseInt(str, 10), and use .map to apply the transformation to both elements at once:
const [ore, minuti] = this.negozioSetup.limiteOreAsporto.split(':').map(Number);

Call functions once rather than multiple times when possible - you don't need to call getHours every time, better to call it once and store the result in a variable.
const currHours = curDate.getHours();
const currHoursWithOffset = currHours + oreMinime;

Return early to avoid indentation hell - reading lots of {} blocks can make code more confusing to read than it needs to be. In the case of 00:00:00, consider running the one line that's needed and then returning, rather than having a large if/else.
The branches of currHours > ore and curDate.getHours() === ore && curDate.getMinutes() > minuti also contain the same logic inside the branches, so combine them into one if statement:
const changeDate = (date, oreMinime, limiteOre) => {
    const currHours = curDate.getHours();
    const currHoursWithOffset = currHours + oreMinime;
    if (limiteOre === '00:00:00') {
        curDate.setHours(currHoursWithOffset);
        return;
    }
    const [ore, minuti] = limiteOre.split(':').map(Number);
    if (currHours > ore || currHours === ore && curDate.getMinutes() > minuti) {
        curDate.setHours(
            currHours + oreMinime + 24
        );
    }
};
const curDate = new Date();
const { tipo } = this.carrello;
if (tipo === 'asporto' || tipo === 'takeaway') {
    const casedProp = tipo.slice(1).toUpperCase() + tipo.slice(1);
    changeDate(currDate, this.negozioSetup['oreMinime' + casedProp]);
}

You could put the values into variables first if you think the combined statement is difficult to read (I'll leave that to you, I don't understand the language) - eg
const cond1 = currHours > ore;
const cond2 = currHours === ore && curDate.getMinutes() > minuti;
if (cond1 || cond2) {
  // ...
}

Alternative to multiple separate properties On a broader scale, having to hard-code the correlation between this.carrello.tipo and the this.negozioSetup.oreMinime- property is a bit odd. If possible, consider rearranging your data so that the two oreMinime and limiteOre values are in an object instead of being two separate properties. Then you just need to use bracket notation to look up the value on the object:
ore: {
  asporto: { minime: <value>, takeaway: <value> },
  takeaway: { minime: <value>, takeaway: <value> },
}

Then you can:
changeDate(currDate, this.negozioSetup.ore[tipo]);

and change changeDate's parameters as needed.


The  _boStop and the _boIsSleeping fields are accessed by multiple threads, so you should synchronize them. You could use volatile fields or AtomicBooleans too.

Make sure that you do read operations in synchronized blocks too, not just writes:

  [...] synchronization has no effect unless both read and write operations are synchronized.

From Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data.
A possible bug: _boFreshRunListRequested is never set to false.
Using _ prefixes (and sometimes this.) to access fields it's not really necessary and it's just noise. Modern IDEs use highlighting to separate local variables from instance variables.
You could eliminate some comments, for example:

// Loop as long as no client has indicated the thread should stop.
while (!boStop) {

This could be

while (!threadStop) {

Another example:

   // Create the data.
   this.createFreshRunList();

Here you could rename the method to createData or createFreshData.

A good reading in this topic is Clean Code by Robert C. Martin and Code Complete, 2nd Edition by Steve McConnell.
It mainly depends on your requirements, but I'd consider renaming the class to DataRefresherImpl and implementing two interfaces: DataRefresherService and  DataRefresher. The first would be used only in the servlet/container initializer. The second is for the clients to get their data and to request new data creation. It would prevent clients to call the stopThread method accidentally.
OldCurmudgeon has already mentioned the getRunList method is dangerous. You could use Collections.unmodifiableList here. Furthermore, make sure that the BeanRunOutput objects are also immutable or handle the modifications. See also: Effective Java, 2nd Edition, Item 39: Make defensive copies when needed

Finally, here is an refactored version with the queue which was suggested by OldCurmudgeon.

public interface DataRefresherService {
    void shutdown();
}

public interface DataRefresher {
    List<BeanRunOutput> getRunList();
    void signalFreshRunListCreation();
}

public class DataRefresherImpl implements Runnable,
        DataRefresherService, DataRefresher {

    private final AtomicBoolean threadStop = new AtomicBoolean(false);

    private final ReentrantReadWriteLock listLock = new ReentrantReadWriteLock();

    private static final long REFRESH_INTERVAL_IN_MILLIS = 3000;

    private final ArrayBlockingQueue<String> refreshQueue =
        new ArrayBlockingQueue<String>(1);

    private List<BeanRunOutput> runList;

    public DataRefresherImpl() {
    }

    @Override
    public void run() {
        while (!threadStop.get()) {
            createFreshRunList();
            sleepAndWakeOnRequest();
        }
    }

    private void createFreshRunList() {
        listLock.writeLock().lock();
        try {
            runList = new ArrayList<BeanRunOutput>();
        } finally {
            listLock.writeLock().unlock();
        }
    }

    private void sleepAndWakeOnRequest() {
        try {
            refreshQueue.poll(REFRESH_INTERVAL_IN_MILLIS, TimeUnit.MILLISECONDS);
        } catch (InterruptedException ignored) {
        }
    }

    @Override
    public List<BeanRunOutput> getRunList() {
        listLock.readLock().lock();
        try {
            return runList;
        } finally {
            listLock.readLock().unlock();
        }
    }

    @Override
    public void signalFreshRunListCreation() {
        refreshQueue.offer("refresh");
    }

    @Override
    public void shutdown() {
        threadStop.set(true);
        refreshQueue.offer("shutdown");
    }
}

(I've not tested this too much.)


Convert Persian digits to English numbers

Instead of using a map,
you can get the corresponding digits directly by subtracting the character code of '۰'.
That is, since the character code of '۳' is 1779
and the character code of '۰' is 1776, you can calculate that:

'۳'.charCodeAt(0) - '۰'.charCodeAt(0) = 1779 - 1776 = 3

Using the above logic, the function can be written shorter:

String.prototype.toEnglishDigits = function () {
    var charCodeZero = '۰'.charCodeAt(0);
    return parseInt(this.replace(/[۰-۹]/g, function (w) {
        return w.charCodeAt(0) - charCodeZero;
    }));
}


What's better: return null or handle the Exception?

A possibly useful pattern here can be the Null Object-pattern.

Instead of returning null, return a "null SalePoint". Perhaps something like new SalePoint();, or new SalePoint("some special url");. Then make your saveSalePoint method do nothing if the SalePoint has a special url indicating that it's null.

Another option is to return null from your parseSalePoint method as you are currently doing and then simply return from the saveSalePoint method if the argument is null which will remove the null check from processBarCodeResponse.

Honestly, I can't tell you which option you should use or not. I can only present you with alternatives. Personally I like Null Object pattern a lot, but it doesn't always makes much sense to use that pattern.

By the way, why isn't SalePoint immutable? Instead of first creating a SalePoint object and then setting it's values one by one, read the values into variables and call a constructor which takes type, url, salePointId as arguments and get rid of the accessible properties (make them private, and also get rid of the setter-methods if you have any)


The code looks quite good to me in general. Here are a few remarks.

Avoid implicit conversion operators

The implicit conversion operator

template <class E, class T>
CheckValue<E, T>::operator E() const;

might do you more harm than good. In particular, if both E and T are of arithmetic type, forgetting to call get will happily use the error code instead of the value and you'll probably have a bad time tracing down this bug.

Maybe a plain old function would serve you better.

template <class E, class T>
E
CheckValue<E, T>::status() const;

Take sink arguments by-value

It seems to me that you expect E to be some cheaply copyable value type, like an enum or an integer so you can easily afford always making a copy. That's perfectly reasonable but then I'm surprised why you take it by const reference. Just take it by-value instead. If you're not so sure whether it will always be cheap to copy, apply std::move to it instead. It should never cost you anything and might sometimes benefit you.

template <class UT>
CheckValue(E, UT&& t) : e(std::move(e)), t(std::forward<UT>(t)) {}

Of course, you could also decide to take both parameters by forwarding reference, just in case.

template <class UE, class UT>
CheckValue(UE&& e, UT&& t) : e(std::forward<UE>(e)), t(std::forward<UT>(t)) {}

Consider special-casing the “success” case

Currently, your class does not know any semantics about E.  If its intention is to be used as “success or failure” indicator, you could make this explicit. This would also allow you to omit the error code when there actually is no error.

For example, you could add a third template parameter that indicates the “success” value (note that I have re-ordered the parameters).

template <class ValueT, class StatusT, StatusT Good = static_cast<StatusT>(0)>
class CheckValue;

Then you could offer a single-argument constructor

template <class ValueT, class StatusT, StatusT Good>
template <class V>
CheckValue<ValueT, StatusT, Good>::CheckValue(V&& v)
    : e(Good), t(std::forward<V>(v)) {}

and your happy path would be just return 42;.

Note that I have deliberately not marked the single-argument constructor as explicit in this case. Otherwise, you'd have to write return {42};. Which version you prefer is probably a matter of taste.

If your class knows about the distinct “success” case, you can add a check for it.

template <class ValueT, class StatusT, StatusT Good>
explicit
CheckValue::operator bool() const noexcept
{
  return (this->e == Good);
}

This would allow code like this.

if (const auto cv = prn(5, 2))
    std::cout << cv.get() << '\n';
else
    std::cerr << "error: " << to_string(cv.status()) << '\n';

Instead of a single Good value, you could have a more general predicate but this would deprive you of the ability to default it in the lucky case and smells like over-engineering to me.

Think whether you want a “no value” state

If your computation fails, you currently have to pass a dummy value to the constructor because it always initializes the t member. If an object of type T is expensive to construct, this would be wasteful. It also feels bad having to specify a value when you actually have none.  Of course, you also don't want to default-construct the t member in this case as this might be equally costly or not even possible.

The usual way to handle this is to use a properly aligned buffer instead of a typed variable T.

char buffer[sizeof(ValueT)] alignas(ValueT);

In your constructor, you use placement-new to create an object inside the buffer, if you have one.

template <class ValueT, class StatusT, StatusT Good>
template <class V>
CheckValue<ValueT, StatusT, Good>::CheckValue(V&& v) : e(Good)
{
  new (this->buffer) ValueT(std::forward<V>(v));
}

Your get function would then cast the buffer to a pointer of the appropriate type, after optionally checking that there is a value in it.

template <class ValueT, class StatusT, StatusT Good>
ValueT&
CheckValue<ValueT, StatusT, Good>::get()
{
  assert(this->e == Good);
  return *reinterpret_cast<ValueT *>(this->buffer);
}

Don't forget to invoke the destructor, too.

template <class ValueT, class StatusT, StatusT Good>
CheckValue<ValueT, StatusT, Good>::~CheckValue()
{
  if (this->e == Good)
    reinterpret_cast<ValueT *>(this->buffer)->~ValueT();
}

You would remove the two-argument constructor now. In order to construct an object in an error-state, you'll need a static factory function.

template <class ValueT, class StatusT, StatusT Good>
CheckValue<ValueT, StatusT, Good>
CheckValue<ValueT, StatusT, Good>::make_failure(StatusT e)
{
  assert(e != Good);
  CheckValue bad {};  // use private default-constructor
  bad.e = e;
  return bad;
}

The private default constructor does not initialize the object.

template <class ValueT, class StatusT, StatusT Good>
CheckValue<ValueT, StatusT, Good>::CheckValue() noexcept {}

It must never be called without setting e to anything but Good immediately afterwards.  (Or the destructor and the other functions would invoke undefined behavior.)  Therefore, it is essential that this dangerous constructor is private.

You will also need to write custom copy / move constructors and assignment operators. You might want to implement them in terms of a custom swap overload.

Consider restricting the type of the error code

Since the code makes a few assumptions about the type of the error code, you might as well make these explicit and restrict it to POD types. To do this, simply put

static_assert(std::is_pod<StatusT>::value, "Status code must be POD type");

at the top of your class definition.

Apply noexcept where appropriate

If a function has no pre-conditions and cannot fail, declare it as noexcept.

Consider using more descriptive names

Some of your variable names seem overly terse to me. As you could see in the example code I've written above, I'd strongly consider renaming t to value, e to status and so forth.

I also recommend that you establish a convention of naming (private) member variables specially. Personally, I like suffixing them with an underscore (eg value_); others prefer the m_ or M_ prefix (eg m_value). Pick what you like and use it consistently.

Use nouns for type names

An object represents a thing, not an action. A type represents a class of things. Therefore, it is generally accepted that type names should be nouns. In your case, CheckedValue would be preferred instead of CheckValue.


Optimally allocating a resource with time-varying demand and cost

Styling

I don't think PEP8 actually says anything about this, but I prefer to have spaces after commas in just about anything.  The comma is a way of separating two items, but sometimes it just isn't enough and other times it just looks squashed without the space.  You should not, however, put spaces around the = sign in all cases.  From PEP8:

  Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.

You break that rule in the definition of discretise().

Again from PEP8:

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

That is under the title Method Names and Instance Variables.  Classes should be PascalCase, but your variables should be as defined above.  Your variables, T, H, V, and X should have more descriptive names besides the fact that they should be lowercase.  I realize that you use v in val(), but if you gave more descriptive names to your variables, there wouldn't be a clash.

v = min(no_pump  , pump   )

What are you doing with all that whitespace?  It should look like this:

v = min(no_pump, pump)

You have many cases of things such as i+1, ii/10.0, etc.  PEP8 doesn't actually say anything against that, but my opinion is that you should use whitespace around the operators unless it makes something look confusing.  For example, a*b + c*d would look confusing if there were spaces around the asterisks, but in the case of val(ii/10.0), for example, I would prefer it to be val(ii / 10.0).

The logic

def record(D,key,item):
    if key in D.keys():
        D[key].append(item)
    else:
        D[key] = [item]

That function could be simplified to this:

def record(D, key, item):
    D.setdefault(key, []).append(item)

Take a look at the docs.  If you wanted to leave it how it was, though, you could still take out the .keys() part of the if statement.  Turning a dictionary into an iterator, which in does, turns it into an iterator of its keys.

def memoize(*args):
    cache = {}

    def memoizedFunction(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]

    memoizedFunction.cache = cache
    return memoizedFunction

Using memoizedFunction.cache = cache isn't helping you here.  You aren't even using it.  You might be better off defining a class:

class Memoize:
    def __init__(self, function):
        self.function = function
        self.cache = {}

    def __call__(self, *args):
        if args not in self.cache:
            self.cache[args] = self.function(*args)
        return self.cache[args]

I changed the name to Memoize to comply with PEP8, but that just means that you need to change @memoize to @Memoize.

        #           pump off         pump on

It isn't clear to me what that comment is saying.  The pump on part goes beyond the end of the next line.  If you meant it to be a comment on a different line, you should move it.

v = min(no_pump  , pump   )

# record optimal policy
if v == no_pump:
    pos = 0
else:
    pos = 1

Here would be a good use of the cmp() function:

v = cmp(no_pump, pump)
if v <= 0:
    pos = 0
else:
    pos = 1

ts = time.time()
...
te = time.time()

I can tell from the last line, print te - ts that those are meant to stand for time start and time end, but why not spell it out?  In this case it's fairly easy to tell what they are for, but it's a good habit to make your variable names very clear.  I would define them as start_time and end_time.


Extend your timer function so it can take all the parameters needed by func()
Don bother to pass func by const reference.

What I would have done
template<typename TimeT = std::chrono::milliseconds>
struct measure
{
    template<typename F, typename ...Args>
    static typename TimeT::rep execution(F func, Args&&... args)
    {
        auto start = std::chrono::system_clock::now();

        // Now call the function with all the parameters you need.
        func(std::forward<Args>(args)...);

        auto duration = std::chrono::duration_cast< TimeT>(std::chrono::system_clock::now() - start);

        return duration.count();
    }
};


Changing the state of another entity into the constructor method

In Python, a singleton should be a module, not a class. There's no good reason to define a class for that. That's what's going on in pyglet's case with pyglet.clock. If you want to define your own version you should do something like:

# myclock.py

from pyglet.clock import *

Then you can add functions/etc to that module to get additional behavior. This way you don't even need to call the set_default function.


Your algorithm seems to be working.

Here is the few things I would do to improve it:

// The routes should be a parameter of the function
function getParams(routes, url) {
  var params = null;

  // Depending on the targeted browser, you could use the native forEach method
  routes.forEach(function (route) {
    // I personally prefer to use methods in here
    if (params === null && routeMatch(route.url, url)) {
      params = computeParams(route.url, url);
    }
  });

  return { params: params };

  function routeMatch(route, url) {
    // You don't need to use `new RegExp`
    // I've added ^ and $ to be sure that it would be working with nested routes
    var matcher = '^' + route.replace(/(:\w+)/g, '([\\w-]+)') + '$';
    return url.match(matcher);
  }

  function computeParams(route, url) {
    var routeParts = route.split('/');
    var urlParts = url.split('/');
    var options = {};

    for (var i = 0, nbOfParts = routeParts.length; i < nbOfParts; i++) {
      // I check that the url part exists
      // and use the binary operator ~ that simplifies the `indexOf` method
      if (urlParts[i] && ~routeParts[i].indexOf(':')) {
        options[routeParts[i].slice(1)] = urlParts[i];
      }
    }

    return options;
  }
}

var routes = [ { url: '/home' }, { url: '/user/:id' }, { url: '/user/:id/post/:postId' }, { url: '/user/:id/post/:postId/comment/:cId' } ];

printResult(getParams(routes, "/home").params, {});
printResult(getParams(routes, "/user/42").params, { id: '42' });
printResult(getParams(routes, "/user/42/post/52").params, { id: '42', postId: '52' });
printResult(getParams(routes, "/user/42/post/52/").params, null);
printResult(getParams(routes, "/user/42/post/52/comment/").params, null);
printResult(getParams(routes, "/user/42/post/52/comment/yolo-22").params, { id: '42', postId: '52', cId: 'yolo-22' });
printResult(getParams(routes, "/contact").params, {});

function printResult(result, expected) {
  console.log('expected: ', expected, 'result: ', result);
}

That's all I can think of.


Node.js building a JSON restful web api structure

Sorry if I'm not answering your specific question, but are asking about overall style, or something else?  There's no "right/wrong way" for many things in node.

For example, I would have used http://expressjs.com/ for this:

var express = require('express')
var app = express.createServer()
app.use(express.bodyParser())

app.get('/users', function(req, resp, next) {
   ...
})

app.get('/users/:uid/posts/:pid', function(req, resp, next) {
   ...
})

app.post('/users', function(req, resp, next) {
   ...
})

app.listen(9090)


line_count can be obtained with len(lines) instead of an enumerate.
You use rstrip (rightstrip), I think that strip is better as you (probably) don't want to count the blanks of indentation as characters.
f is the standard name for files in Python not fin
Using list comprehension and a for loop as you do is much more readable than a functional alternative, anyway, down here I show you a functional version:

:

def code_metric(file_name):
    with open(file_name) as f:
        lines = f.read().splitlines()
    char_count = sum(map(len,(map(str.strip,filter(None,lines)))))
    return len(filter(None,lines)), char_count


Change functions based on jQuery plugin {options}

In my opinion it's a good idea to get rid of the switch case by using better naming for the inputs and by changing the structure of your functions to Object based functions, i.e. if you change your functions to this:

var showDate={
    all:function (){
        alert(d.toString());
    },
    date:function showDateOnly(){
        alert(d.toDateString());
    },
    time:function (){
        alert(d.toLocaleTimeString());
    }
};

and the setting options you get are ['all' , 'date' , 'time']

then you can call these functions like this:

(showDate[settings.date]) ? showDate[settings.date]() : showDate.all();

and get rid of the switch case. DEMO


Should I always use objects when coding in java even for a basic program like this one?

How would you not?  Note that you are using an object in this program now, a Scanner object.  You also use a Calculator class.  Because of course that's how Java works.  There are no methods outside of classes.

Now, should you make an intermediate class and objects?  Maybe.  Maybe not.  I would like to see more methods here.  For example, consider

    public static void displayForTimePeriod(String message, double amount, double multiplier) {
        System.out.println(message, amount * multiplier);
    }

That would allow you to simplify most of your code to something like

        double weekly = cost * packets;
        displayForTimePeriod("In one week you would save: €", weekly, 1.0);
        displayForTimePeriod("In one month you would save: €", weekly, 30/7.0);
        displayForTimePeriod("In three months you would save: €", weekly, 13.0);
        displayForTimePeriod("In six months you would save: €", weekly, 26.0);
        displayForTimePeriod("In one year you would save: €", weekly, 52.0);

You could go further and make a class, but the main thing that it would hold would be the amount.  Note that that stays the same in every call.

I might add

        System.out.println("On average, you'll save €" + (weekly/7) + " every day.");

If you wanted, you could make your years calculation more accurate by including leap years.  That would require you to get the current date from the system time.  Remember to handle leap centuries.  2000 was a leap year, but 1900 was not and 2100 won't be.

I made the monthly number more accurate.  Unless the month is February, there are more than twenty-eight days (four weeks) in a month.  The usual approximation is thirty.

I fixed the quarterly (three months) number as well.  There are thirteen weeks in most quarters (the exception is the first quarter when February does not have a leap day).  Twelve weeks will be too few for every quarter.


PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(currentDir + fileName)));
            ...
            BufferedReader reader = new BufferedReader(new FileReader(currentDir + fileName));

Never ever ever open a file for reading or writing characters without explicitly specifying the encoding. You'll think it's all working fine and then someone will run your program on Mac OS X and send you a file encoded in MacRoman because that's the default on their platform.

Yes, I learnt that one the hard way.

Unfortunately the Java standard library tries to make things "easy" by hiding access to the encoding and ends up making it hard for anyone who wants to write portable code (supposedly Java's strong point). You can't use FileWriter, because none of its constructors have an encoding parameter. You have to create a FileOutputStream and wrap it in an OutputStreamWriter. FileReader is similarly useless.


Finding the length of shortest transformation sequence from start to end

First of all, I really liked that your logic doesn't need to compare lengths: as soon as a match is found, it must be one of the shortest lengths, nice! And when the end is unreachable, the method returns 0, an impossible answer (since a valid length must be >= 1), so that's good too.

A couple of things can be improved.

Choose the right interfaces

Your method should work with Set<String> dict, and should not limit users to HashSet<String> dict.

Choose the right classes

A Deque is a collection that supports element insertion and removal at both ends. That's more than what you need. A Stack would have been enough for your purpose.

Simplify the inner for loops

The inner for loops are a bit wasteful and can be simplified. You are basically iterating over all possible 1-letter differences and check if in the dictionary. Instead, you could iterate elements of the dictionary and see if they have 1 letter difference. For example like this:

for (String item : dict.toArray(new String[dict.size()])) {
    if (isSingleCharDiff(analyzing, item)) {
        dict.remove(item);
        lengthCount.add(curCount + 1);
        wordSearch.add(item);
    }
}

Discrepancy with the specs

The problem description says:

  dict = ["hot","dot","dog","lot","log"]

With this exact input your method returns 0 because it will never reach end. The fix is simple enough, just add it to the dictionary somewhere near the start:

dict.add(end);

A wasted operation

Before the while loop, you do this:

wordSearch.add(start);
lengthCount.add(1);

but then inside the loop you immediately pop them. You could rework the code to eliminate that wasted operation:

String analyzing = start;
int curCount = 1;
while (true) {
    if (analyzing.equals(end)) {
        return curCount;
    }
    for (String item : dict.toArray(new String[dict.size()])) {
        if (isSingleCharDiff(analyzing, item)) {
            dict.remove(item);
            lengthCount.add(curCount + 1);
            wordSearch.add(item);
        }
    }
    if (wordSearch.isEmpty()) {
        break;
    }
    analyzing = wordSearch.pop();
    curCount = lengthCount.pop();
}


You forgot a std::
There's a string without std:: in front of it. I guess you secretly used using namespace std and/or #include <bits/stdc++.h> before submitting the result. The rest looks fine though.
Consider using const TreeNode * everywhere
I know the public API of the LeetCode problem explicitly takes non-const pointers to TreeNode, so you shouldn't change this. But consider that your functions, quite rightly so, don't modify the TreeNodes themselves. So you could write const TreeNode * everywhere you now have TreeNode *, and it would still compile correctly. So in real production code, that is what you should do.
Don't use this-> unnecessarily
In C++, there is rarely a need to write this->. So in findDuplicateSubtrees(), you can just write serialize(root, nodes_map).
Use range-for and structured bindings where appropriate
You can replace the for-loop in findDuplicateSubtrees() using range-for and structured bindings:
for (auto &[serialization, nodes]: nodes_map) {
    if (nodes.size() > 1) {
        duplicates.push_back(nodes[0]);
    }
}

Consider using a binary serialization format
There are many ways you could serialize trees. Making human-readable strings has some advantages: it is easy to reason about, and it is nice when having to put them in textual formats like XML or JSON files. But it can be inefficient to convert values to strings. In your case, you are only using the serialization internally, so a binary format might be more efficient.
In the case of trees of integers, an obvious representation is just a vector of ints. However, a node might have only one child, and you somehow have to encode that as well. You could use a std::optional<int>, and use std::nullopt to represent an unpopulated leaf node. The serialization format would then be:
std::vector<std::optional<int>> serialization;

The serialization function would then look like:
std::vector<std::optional<int>> serialize(TreeNode *node, std::unordered_map<std::string, std::vector<TreeNode *>> &nodes_map) {
    if (!node) {
        return {std::nullopt};
    }

    auto left = serialize(node->left, nodes_map);
    auto right = serialize(nodes->right, nodes_map);
    left.append(node->val);
    left.insert(left.end(), right.begin(), right.end()); // append right
    return left;
}

For the LeetCode problem, it's not worth doing this though; the algorithmic complexity is the same, and the string representation is smaller for trees with small values. Also, you can not use a std::unordered_map anymore for nodes_map, unless you write a custom hash function. You could use a std::map though, since optionals and vectors have well-defined ordering.


Easiest solution (to the time problem) is to change your logic (just a tiny bit).

if ($time >= $from && $time <= $to)

To:

if (($to > $from && ($time >= $from && $time <= $to)) ||
    ($to < $from && ($time >= $from || $time <= $to)))

You just change whether to restrict the time to be between the two, or to restrict it to be greater than one or less than the other in the case that the $to time is less than $from.

As far as cleaning up your code: this is about as idiomatic as php will get. Though you should definitely extract this to a function as appropriate.


Wikipedia indexer and shortest link finder

** this won't make your code more efficient, but is still something you should consider doing

With all your file opening, you should do it as:

with open('filename','r') as fin:
    urls/links = json.loads(fin.read())

while you have the try/catch block, your exception handler is not checking and closing open file handles, which is what the with context does


If I understand correctly, you wish to maintain a list of places, and record only the shortest route to each place. This means that each time you need to find any duplicate entry, and choose which to keep.

For this task, an unordered list is pretty much the worst choice you could use. Your algorithm is O(n2) (that is, O(n) for adding each of n elements), and while that isn't important for 10 destinations, it's pretty critical for 3 million!

Given that ordering is not critical here, a hash table is really the correct implementation to use. This will get you O(1) insert and lookup, and the added programming complexity and memory use is appropriate for that number of elements. If that's not possible somehow, then second best would be some kind of self-balancing tree.

Finally, it makes no sense to count the length of a large list by iterating the elements. Just increment a counter every time you add an element. A reduction from O(n) to O(1). (In theory, if you add and destroy a lot of elements very frequently, but only query the size once in a blue moon, then my statement is untrue, but I doubt that's the case here.)

As far as your existing implementation goes, it's a bad plan to create the new node and then not use it. Maybe in your implementation a garbage collector will sort it out, but otherwise it'll be a huge memory leak, not to mention wasted effort.


iterate over an array and delete elements conditionally

note : your break is useless, because if the block returns a falsey value, the url is kept.

Maybe it can just be a bit more expressive ?

def timeouts?( url )
  perform_request( url ) && false
rescue TimeoutError
  true
end

@urls.delete_if {|url| timeouts?( url ) }

You could even make timeouts? a method on your @urls objects, for extra readability :

@urls.delete_if( &:timeouts? )

if you want to keep @tokland's functionnal approach, just use :

@kept_urls = @urls.reject{|url| timeouts?( url ) }

however, it would not be fully "functionnal", because timeouts may not return the same results with the same arguments, depending on the execution environment.


This doesn't look good:

DatabaseManipulator dm = new DatabaseManipulator();
String[] usernameArray = dm.dbEntriesToArray("user_id");
String registeredPassword = dm.getRegisteredPassword(userId);

LoginModule lm = new LoginModule();
boolean hasExistingAccount = lm.hasExistingAccount(usernameArray, userId);
boolean isPasswordCorrect = lm.isPasswordCorrect(userPassword, registeredPassword);

The interaction between the current class, DatabaseManipulator and LoginModule is not natural and inefficient.
Why get an array of usernames from a DatabaseManipulator and pass that to LoginModule?
These classes are too tightly coupled: they know too much about each other.
The current class gets something from DatabaseManipulator and passes it on to LoginModule.
A system with too many connections between its elements like this is complex and rigid.

The responsibilities are also not well separated.
The current class shouldn't need to know the details of validating users,
but delegate to a dedicated UserManager class.
Consider these methods and responsibilities:

UserManager.isValidUser(String username): check if the user exists. The class will hide how this check is performed. Maybe it loads an array of all usernames, like the original code. Hopefully it doesn't, but to outsiders it won't matter. You can extend it later: you might add the concept of disabled users. This class and method will be the single place to make that change, the rest of your program doesn't have to know how it works.
UserManager.isPasswordCorrect(String username, String password): check if the password is correct

The original code would then become:

UserManager userManager = new UserManager();
boolean hasExistingAccount = userManager.isValidUsername(userId);
boolean isPasswordCorrect = userManager.isPasswordCorrect(userId, userPassword);

This is more intuitive, the details of user validation are now correctly hidden from the current class, and it's shorter too.

Security

I'm not sure it's such a good idea to tell the user when a username doesn't exist.
One can discover the valid usernames on the site by a brute-force attack.
It might be somewhat better to give the same error message whether the username exists or not, something:

  The username or password you entered is incorrect.

Minor things

These conditions can be joined:

if(!hasExistingAccount) {
    response.sendRedirect("login-result.jsp");

} else if(!isPasswordCorrect) {
    response.sendRedirect("login-result.jsp");

like this:

if (!hasExistingAccount || !isPasswordCorrect) {
    response.sendRedirect("login-result.jsp");
}

When you have code like this:

if (userId != null && userPassword != null) {

    // many, many, many lines of code...

} else {
    // redirect on illegal access of servlet
    response.sendRedirect("index.jsp");
}

... by the time you read until the else block, it can be difficult to remember what the if was about... In such situations it's better to make the shortest block come first by reverting the condition:

if (userId == null || userPassword == null) {
    // redirect on illegal access of servlet
    response.sendRedirect("index.jsp");
} else {
    // many, many, many lines of code...
}

or, it might be even more natural to return early and drop the else block,
reducing one level of indentation:

if (userId == null || userPassword == null) {
    // redirect on illegal access of servlet
    response.sendRedirect("index.jsp");
    return;
}

// many, many, many lines of code...

This is especially useful with more complex, arrow-shaped code, with many nested conditions.


There are some issues, such as not using obvious built-in solutions, an inefficient algorithm and what looks like a logic error possibly caused by having odd array-growing logic.

I'll start with the error. In int min = numbers[1]; you assume that there are at least two numbers. That may not be true, if the user immediately enters 0 - which raises the question of what the GCD of the empty set is (0 or 1, depending on who you believe), but whatever it should be, it's bad form to crash with an out-of-bounds exception.

The odd array-growing logic is probably part of that problem, it leaves a spurious 0 in the array which you thereafter actively ignore - it's simpler to not have it there to begin with. Anyway, you wanted an array that can change size - that's usually called ArrayList which, conveniently, already exists. You can also avoid saving up the input entirely, by computing the GCD while reading the input.

The GCD algorithm is strange and inefficient. It's not the familiar GCD algorithm, which is already a strike against it by itself since that makes it hard to tell what it's doing, and there is no redeeming quality. This is an algorithm with a very bad worst case, as much as O(min*N) (if the GCD turns out to be 1). I strongly recommend using the modulo-based version of the Euclidean algorithm, which is efficient and recognizable, or maybe Binary GCD if you want something different. In the unlikely case that you rejected it because it takes only two inputs, of course gcd(a, b, c) = gcd(gcd(a, b), c) and so on, so you can simply loop over your input and call GCD on the gcd-so-far and the number from the input.

Or, as mentioned, you could compute the GCD while reading the input, something like this:

int gcdSoFar = 0;

while (true) {
    int number = input.nextInt();
    if (number == 0)
        break;

    gcdSoFar = gcd(number, gcdSoFar);
}

System.out.println("The GCD of the input is: " + gcdSoFar);

This loses the print-back of the input, if you want to preserve that you could use an ArrayList. By the way, in Java 8 you can use String.join(", ", list) to make a comma-separated string from your list, you don't have to do that manually.


Hacker rank - Left rotation - PHP code feedback

Performance

Shifting the content of an array is a very expensive operation.
Lot's of assignments.

Realize that you don't really need to shift the content.
You can shift an offset index,
and use that shifted offset to print the desired output:

for ($i = 0; $i < $n; $i++) {
    $shifted = ($i + $k) % $n;
    printf("%d", $a[$shifted]);

    if ($i < $n-1) printf(" ");
}

Unnecessary statements

This is unnecessary, it serves no purpose at all, you can safely delete it:

$i; $j; $temp;

Input validation

Although input validation is a good practice,
in an online challenge you can trust that the input will be in the described format, and all values will be within the described ranges.
I haven't seen an exception to that yet.
So you don't need this kind of code:

if($n<0 || $n>1000000 || $k<0|| $k>1000000 || count($a) <=0)
    exit;

Formatting

The code is very poorly formatted:

Indentation is inconsistent
No spaces between operators make it look extremely compact and hard to read

Try to follow the writing style of the snippet in my first point.


I think you can avoid the Tracker.autorun completely by updating the value in a template helper -- this is possible because your data is coming from a Collection, so it's already reactive.  You can play around with it in this MeteorPad, but a brief summary follows:

<template name="slider">

  Slider's current value is...{{sliderVal}}
</template>

//JS -- ommitted the rendered bit, which looks identical to yours w/o the Tracker.autorun
Template.slider.helpers({
  sliderVal:  function() {
    var slider = Slider.findOne(); // this guy is reactive, so when another client updates the Collection, it'll get pushed to us
    if (slider) {           Template.instance().$('#slider').data('uiSlider').value(slider.slide); // Template.instance() b/c `this` doesn't return a template instance in a helper
      return slider.slide; // again, here you can return nothing if you'd rather have no text
    }
  }
});


JavaScript async functions queue approach

One thing I find problematic is that queue.next is visible and can openly be called. The problem arises if your async function is waiting, and something else suddenly shifts the queue. You would get an unexpected results. To remedy this, I would suggest hiding next so that only the callbacks are aware of it.

One way to do it is pass in next as an argument to the callback. next would be a function that simply calls the next callback. If I remember correctly, this is how express did middleware.

function callback(arg1, arg2, ..., next){
  // do stuff
  next(arg1, arg2, ...);
}

An alternative would be to return a Promise. An advantage with this approach is that you remove the complexity of having to wrap the next callback as the next argument and instead, just call the callback and expect a Promise.

function callback(resolvedValue){
  // do stuff
  return Promise.resolve(resolution);
}

For your error, you should not rely on try-catch. try-catch should only be used for unexpected errors or errors that are intentionally thrown (like from an API) and meant to be recovered. But in this case, you are aware that it will throw an error when the queue is empty. You should do the check if the queue is empty before proceeding instead of relying on try-catch.

You should consider hiding the queue array. The problem with it being in the open is that it can be modified freely. It might be altered unintentionally, causing odd results. Consider hiding it inside a closure.

Your queue should hold a flag indicating that it's running or paused. Your queue could be in the middle of an async operation when queue.start is called. You wouldn't want the queue to suddenly start running. Also, if your queue runs out of callbacks, what does it do? Does it pause? Does it pick up after receiving a callback? How does third-party code know if the queue is still processing? These are some things to consider, and it depends on how the queue is used.


Guess a number, any number, between 1 and 10

Global variables

Don't use global variables(like $bar). It is always bad practice because you can mutate the global variable from anywhere. The alternative is:
RANDOM_NUMBER = rand(1..10), notice that you can pass range as an argument of rand. rand(10) + 1 can return 11 so it isn't correct.

Style

Huge percentage of the Ruby community follow the style guide and this
is the most popular one Ruby style guide.

Style issues:

Use snake case for the names of methods and variables.
Use double quotes only if you use interpolation or special symbols like \n.

About the implementation

IMO will be more readable like this:

def guess_random_number
  puts 'Guess a number between 1 and 10'

  random_number = rand(1..10)

  while random_number != (guess_number = gets.to_i)
    if guess_number < random_number
      puts "too low \nplease, guess again"
    else
      puts "too high \nplease, guess again"
    end
  end

  puts "Right on, good guess \nbye"
end

guess_random_number

You see there is no need to expose the variable in the global scope.


Bash script to automate dev environment setup

I think you could benefit from using Ansible in this scenario then you can easily deploy your configuration to other machines and you will have learned a valuable IT skill.
And rather than use bash scripts, you use yaml configuration files.
As for your script: there is a fair amount of repetitive code. Rather than repeat the wget or curl, you could gather your sources into an array, then run wget/curl in a loop, because you are performing multiple operations that are similar. Upside: more concise code. Downside: less separation between the various steps. I can understand you did it this way. But if your file grows because you keep adding sources, you'd have to reconsider the approach and start using loops.
This is something you could have done here too:
mkdir $HOME/GoProjects
mkdir $HOME/GoProjects/src
mkdir $HOME/GoProjects/bin
mkdir $HOME/PyProjects
mkdir $HOME/JSProjects
mkdir $HOME/pemKeys

An array would make sense. As mentioned above, don't forget to quote !
Same for the apt install, but since you are adding some repo sources, that needs to be done beforehand, and it would require reorganization of your script.
The other issue is you are downloading specific software versions that will probably be outdated by the time you reinstall your computer. Thus, an outdated script becomes less valuable, if you have yet to update or patch your install to have a setup that is current.
As an example:
#install Go
wget https://dl.google.com/go/go1.14.3.linux-amd64.tar.gz
sudo tar xvfz go1.14.3.linux-amd64.tar.gz -C /usr/local/
rm -f go1.14.3.linux-amd64.tar.gz

I would use variables instead, so that the package name is defined only once:
#install Go
go_file="go1.14.3.linux-amd64.tar.gz"
wget "https://dl.google.com/go/$go_file"
sudo tar xvfz "$go_file" -C /usr/local/
rm -f "$go_file"

It is a minor change that will make maintenance of this file more manageable.
Also, you could move the code to dedicated functions. That makes it a bit easier to separate the various steps you are performing. Also, you can easily disable certain items by simply commenting out the function call (= changing only 1 line). In fact it would be nice if you could run your script à la carte, it is perfectly possible that you will want to run it again, but discard certain items that are already installed. For instance if your script crashed in the middle and you don't want to waste time reinstalling everything from the beginning, which is wasteful.
The other benefit of calling functions in sequence, is that you can easily reorder them. At some point you may find out that a certain piece of software should or must be installed before another, because of some dependencies.
I would install software packages from the regular OS repositories whenever possible. Do you really need to install Postgresql from source ?
I would also avoid PIP and install the Python packages from apt-get instead, unless they are not available for your OS.


Profile with static and input modes (View and Update)

Other than your handleOnChange handler is mutating state, this code seems understandable and readable enough to me, only minor comments about code style.
React-ness
React's synthetic events' persist function is a void return, so I don't think the logical OR between it and the state update necessary.
Mutating-state handler with odd event persisting.
handleOnChange = key => e => e.persist() || this.setState(prevState => {
  prevState.data[key] = e.target.value; // <-- this mutates existing state
  return prevState; // <-- saving previous state object back in state
})

Non-mutating-state handler. React class-based component state updates are merged in, but nested state needs to have their previous state merged manually. Also, instead of persisting the event for use in the "asynchronous" setState, it is more common to grab the event value and let react do what it needs with the event object (i.e. return back to pool).
handleOnChange = key => e => {
  const { value } = e.target;
  this.setState(prevState => ({
    data: {
      ...prevState.data,
      [key]: value,
    },
  }));
}

Readability
All other comments I'd have on the code are more about the readability, i.e. appropriate usage of whitespace, 2-space vs 4-space tabs, etc.. but these are largely dev team driven and tend to be subject to opinion.
Common practices though are

Single line space between code blocks (functions and any other logical "chunk" of code
Using curly brackets for functions that are more than simply an implicit return, i.e. they have more than a single expression
Using appropriate line breaks when lines of code get too long, usually around 80 chars

Maintainability/Reusability
The one remaining comment I'd have would be to try and abstract the this.getStaticOrInput logic and utilities into a separate react component, something like EditableInput that handles its toggling state internally.
<EditableInput name="first_name" value={...} etc.. />
<EditableInput name="last_name" value={...} etc.. />
...


Try this:

def generate_func(url_attr, type_class, source_type):
    def f(self, scan_id):
        for keyword in type_class.objects.all():
            self.process_rss_url(getattr(keyword, url_attr), source_type, keyword.id, keyword.last_scan_time, scan_id)
            keyword.last_scan_time = timezone.now()
            keyword.save()

    return f

handle_keywords = generate_func('rss', Keyword, SourceType.GOOGLE_ALERTS)
handle_rss = generate_func('feed_url', RSS, SourceType.RSS)


Reducing memory footprint in anagram-finding program for text

and just shortening it up Jesse's answer...

private static bool IsAnagramOf(this string word1, string word2)
{
    return word1
        .OrderBy(x => x)
        .SequenceEqual(word2.OrderBy(x => x));
}

static void Main(string[] args)
{
    using (var si = new StreamReader(Console.OpenStandardInput(8192)))
    {
        Console.SetIn(si);
        var split = (Console.ReadLine() ?? "").Split(new[] {',', '.', ' '}, StringSplitOptions.RemoveEmptyEntries);
        split.SelectMany(t => split.Where(s => (t != s) && t.IsAnagramOf(s))).ToList().ForEach(Console.WriteLine);
        Console.ReadLine();
    }
}


LeetCode: Network Delay Time Bellman Ford C#

You can optimize a bit by make it possible to step out of the first outer loop if the inner foreach-loop doesn't make any changes to dist in one iteration.

Wouldn't it be possible to test for maxWait whenever you update dist[v] in the foreach-loop:

{
    dist[v] = dist[u] + w;
    maxWait = Math.Max(maxWait, dist[v]);
}

This may og may not be an optimization - depending on the cost of comparing two integers potentially N * N times compared to the cost of an extra loop comparing them N-1 times?

You could make an early return in the find-max-loop:

       int maxWait = 0;
        for (int i = 1; i <= N; i++)
        {
          maxWait = Math.Max(maxWait, dist[i]);

          if (maxWait == int.MaxValue)
          {
            return -1;
          }
        }

or change it to:

int maxWait = dist.Skip(1).Max();
return maxWait < int.MaxValue ? maxWait : -1;


You can iterate over the hashes/arrays using a custom enumerator (modified from a StackOverflow answer here):

def dfs(obj, &blk)
  return enum_for(:dfs, obj) unless blk
  yield obj if obj.is_a? Hash
  if obj.is_a?(Hash) || obj.is_a?(Array)
    obj.each do |*a|
      dfs(a.last, &blk)
    end
  end
end

You can then use this enumerator builder method in any number of other helper methods for whatever you need. For example, to perform your example search, you could define:

def find_node_with_value(obj, key, value)
  dfs(obj).select do |node|
    node[key].respond_to?(:include?) && node[key].include?(value)
  end
end

And then use it like:

find_node_with_value(json_data, "field1", "something")
# [{"entry_id"=>544, "field1"=>"something" ...}, {"entry_id"=>546, "field1"=>"something!" ...}]


Read function that properly handles interrupts

My main problem is the recursion. I don't think its major but I personally would use a loop. Given the current layout I can't quite convince myself that it works in all situations (especially since there are two alternative recursive calls).

Declare variables close to the usage point (rather than everything at the top).

    ssize_t ret;
    ssize_t ret2;

C has been updated so that you can declare variables at any point in a function. This helps in readability as you don't need to scroll far to find the variable declaration. Also if you declare in the most restrictive scope possible it helps to prevent data leaking (out of a scope).

see: https://stackoverflow.com/a/8474123/14065

Try this:

static ssize_t read_all(int fdes, void* buffer, ssize_t size)
{
    ssize_t  totalRead = 0;

    while(totalRead != size)
    {
        ssize_t thisRead = read(fdes, buffer + totalRead, size - totalRead);

        if ((thisRead == -1) && (errno == EINTR)) {
            continue;
        }
        // Note: There are other errors that may not be erros.
        // EAGAIN or EWOULDBLOCK spring to mind but may need special handling
        // as immediately calling read may just cause a busy wait you may
        // want to suspend the thread by calling sleep..

        if (thisRead == -1) {
            return -1;
        }
        if (thisRead == 0) {
            break;
        }
        totalRead += thisRead;
    }
    return totalRead;
}


Your finally should strive to be as safe as it can, since you may have already had some error occur. To that end, you could run into trouble with a null pointer:

} finally {
    if (session.isOpen()) {
        session.close();
    }
}

If session is null then you've just caused another error, so test session before you call on it:

} finally {
    if (session != null && session.isOpen()) {
        session.close();
    }
}


It is necessary to have consistent and correct (as per style convention) white space. This includes vertical alignment (such as indentation) and spacing between and around particular syntax.

Convention on braces vary, but often braces are encouraged for single statement blocks. One reason is that a later revision may not realise to add braces when adding another statement to the block.

The following is how I might format the code. Note that I am not afraid to add extra blank lines to separate structures. I am not opposed to having three blank lines between methods, though I did not do that here.

import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;

public class Main {

  static Scanner input = new Scanner(System.in);

  public static void main(String[] args) {

    String[] words = {"java", "hello"};
    int random = (int)(0 + Math.random() * words.length);
    String wordToGuess = words[random];
    boolean isGuessed = false;
    int counter = 0;
    int maxGuess = 7;
    char[] chars = new char[wordToGuess.length()];

    for (int i = 0; i < chars.length; i++) {
      chars[i] = '-';
    }

    while (!isGuessed && counter < 7) {

      System.out.println("Enter your guess: ");

      char guess = input.next().charAt(0);

      counter++;
      maxGuess--;

      for (int i = 0; i < wordToGuess.length(); i++) {
        if (wordToGuess.charAt(i) == guess) {
          chars[i] = guess;
        }
      }

      if (doesContain(chars)) {

        for (int j = 0; j < wordToGuess.length(); j++) {
          System.out.print(chars[j] + " ");
        }

        System.out.println("Guess left: " + maxGuess);

      } else {

        System.out.println("Good job! The word is: ");

        for (int j = 0; j < wordToGuess.length(); j++) {
          System.out.print(chars[j] + " ");
        }

        System.out.print("Number of tries: ");
        System.out.print(counter);

        isGuessed = true;

      }

    }

  }

  public static boolean doesContain(char[] chars) {

    for (int i = 0; i < chars.length; i++) {
      if (chars[i] == '-') {
        return true;
      }
    }

    return false;

  }

}

This blob concerns me.

String[] words = {"java", "hello"};
int random = (int)(0 + Math.random() * words.length);
String wordToGuess = words[random];
boolean isGuessed = false;
int counter = 0;
int maxGuess = 7;
char[] chars = new char[wordToGuess.length()];

It is best to keep separate what can be kept separate. I took a look at "x depends on y" written as x ⇒ y and came up with this.

chars ⇒ wordToGuess
wordToGuess ⇒ words
wordToGuess ⇒ random
random ⇒ words

Therefore we can break and reorder these variable declarations like so:

String[] words = {"java", "hello"};
int random = (int)(0 + Math.random() * words.length);
String wordToGuess = words[random];
char[] chars = new char[wordToGuess.length()];

boolean isGuessed = false;
int counter = 0;
int maxGuess = 7;

Then looking down a bit further there is a for-loop which only depends on chars, so we can pull that up.

String[] words = {"java", "hello"};
int random = (int)(0 + Math.random() * words.length);
String wordToGuess = words[random];
char[] chars = new char[wordToGuess.length()];

for (int i = 0; i < chars.length; i++) {
  chars[i] = '-';
}

boolean isGuessed = false;
int counter = 0;
int maxGuess = 7;

There are seven variables in scope (are accessible) for the rest of main. For each variable one must wonder "does this matter later?". This increases the effort to understand a block of code. Doing a text search I found that words and random are unused later. Therefore, lets more closely contain them.

String wordToGuess;
{
  String[] words = {"java", "hello"};
  int random = (int)(0 + Math.random() * words.length);
  wordToGuess = words[random];
}

char[] chars;
{
  chars = new char[wordToGuess.length()];
  for (int i = 0; i < chars.length; i++) {
    chars[i] = '-';
  }
}

Now the program is well formatted and just by looking at dependencies we have improved the organisation (we did not have to know what the program does). Further improvements can come from rethinking some of how the program does its task. There seems to be quite a bit happening in the while-loop so I want to consider that first.

Reading the code and doing some string searching, I have determined what the while-loop reads and writes.

Reads & Writes

isGuessed
counter
maxGuess
chars
input

Reads Only

wordToGuess

Writes Only

N/A

Lets discover the purpose of each variable which is both read and written. Why these particularly? If a variable is only read it is invariant (unchanging) during the loop. If a variable is only written it has no effect on the loop behaviour.

input is used to read through stdin a character at a time, once each iteration.
counter is increased once per iteration. This is used to print the number of guesses thus far and to terminate the loop if !(counter < 7).
maxGuess is decreased once per iteration. This is used to print the number of guesses remaining.
chars is updated with the guessed letter once per iteration.
isGuessed is set to true only if the guessed word is complete. This is used to terminate the loop if !!isGuessed.

I see a redundancy between counter and maxGuess. counter = 7 - maxGuess or maxGuess = counter + 7. I think counting down to zero from maxGuess makes more sense than counting up to 7, so I will replace counter with maxGuess. Also I rename maxGuess to guessesRemaining and introduce a final variable maxGuesses assigned to 7.

boolean isGuessed = false;
final int maxGuesses = 7;
int guessesRemaining = maxGuesses;

while (!isGuessed && guessesRemaining > 0) {

  System.out.println("Enter your guess: ");

  char guess = input.next().charAt(0);

  guessesRemaining--;

  for (int i = 0; i < wordToGuess.length(); i++) {
    if (wordToGuess.charAt(i) == guess) {
      chars[i] = guess;
    }
  }

  if (doesContain(chars)) {

    for (int j = 0; j < wordToGuess.length(); j++) {
      System.out.print(chars[j] + " ");
    }

    System.out.println("Guess left: " + guessesRemaining);

  } else {

    System.out.println("Good job! The word is: ");

    for (int j = 0; j < wordToGuess.length(); j++) {
      System.out.print(chars[j] + " ");
    }

    System.out.print("Number of tries: ");
    System.out.print(maxGuesses - guessesRemaining);

    isGuessed = true;

  }

}

Final variables cannot be changed, so we know automatically the most the while-loop does with this variable is read it, which it does. Thus we have reduced the number of variables the loop both reads and writes and this can simplify comprehension.

While reading I found the method name doesContain does not suggest its purpose well. Thus I renamed it to isSolved. I also thought chars was too generic of a name so I renamed it to incompleteWord.

I found '-' was used as a placeholder letter in both main and isSolved. We want to avoid magic literals in our program. A "magic literal" is some literal (such as a string, character, or number) which occurs in one or more places and has an non-obvious and unstated reason for being the value it is. When reading code with magic literals we are not sure what the code does. When updating code with magic literals we are not sure where all we need to make the replacement, especially because there may be different reasons for a particular literal. To fix this we can simply name the literal.

static final char placeholderLetter = '-';
...
incompleteWord[i] = placeholderLetter;
...
if (incompleteWord[i] == placeholderLetter) {

There is much from here we can still do. However, I think this is a good place to stop seeing as this is your first substantial program.

I do not think giving advice or answers on how to implement a program from the abstract is on topic. Rather, this Q&A service is for suggesting improvements to code which is already working and understood. If you want to know how to add some ASCII art to your program then I suggest Stack Overflow.

This is my final version of your program after moving a couple more declarations around.

import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;

public class Main {

  static Scanner input = new Scanner(System.in);

  static final char placeholderLetter = '-';

  static final final int maxGuesses = 7;

  static final String[] words = {"java", "hello"};

  public static void main(String[] args) {

    String wordToGuess;
    {
      int random = (int)(0 + Math.random() * words.length);
      wordToGuess = words[random];
    }

    char[] incompleteWord;
    {
      incompleteWord = new char[wordToGuess.length()];
      for (int i = 0; i < incompleteWord.length; i++) {
        incompleteWord[i] = '-';
      }
    }

    boolean isGuessed = false;
    int guessesRemaining = maxGuesses;

    while (!isGuessed && guessesRemaining > 0) {

      System.out.println("Enter your guess: ");

      char guess = input.next().charAt(0);

      guessesRemaining--;

      for (int i = 0; i < wordToGuess.length(); i++) {
        if (wordToGuess.charAt(i) == guess) {
          incompleteWord[i] = guess;
        }
      }

      if (isSolved(incompleteWord)) {

        for (int j = 0; j < wordToGuess.length(); j++) {
          System.out.print(incompleteWord[j] + " ");
        }

        System.out.println("Guess left: " + guessesRemaining);

      } else {

        System.out.println("Good job! The word is: ");

        for (int j = 0; j < wordToGuess.length(); j++) {
          System.out.print(incompleteWord[j] + " ");
        }

        System.out.print("Number of tries: ");
        System.out.print(maxGuesses - guessesRemaining);

        isGuessed = true;

      }

    }

  }

  public static boolean isSolved(char[] incompleteWord) {

    for (int i = 0; i < incompleteWord.length; i++) {
      if (incompleteWord[i] == placeholderLetter) {
        return true;
      }
    }

    return false;

  }

}


Turning relativenumber option off/on when opening/closing the gdb terminal window

Two things off the top of my head:

Use mode-specific mappings, so nnoremap limits the mapping to normal mode. (Great job on the use of non-recursive mappings.)

You can access options as vimscript variables with &relativenumber. SetRelNum is sort of unecessary: I would have written

tabdo windo let &relativenumber = a:flag

(And if that doesn’t work because of some odd scope rule, you can exec it with everything but a:flag in quotes. You may have to pass 0/1 instead of v:false/v:true etc.)


Database schema for holding game save files

Here are a few suggestions, many of which are just "best practices" I've picked up along the way (or simplifications that would make things a bit more concise and easier to read).  There are also a few ideas that will likely prevent common errors from happening to the code as it's maintained in the future (that I've run across in many code reviews).

I'd create an id column on the accounts table:

CREATE TABLE accounts(
  account_id INT UNIQUE NOT NULL,
  AccountName VARCHAR(50) UNIQUE NOT NULL,
  Password BLOB NOT NULL,
  PRIMARY KEY(account_id)
) Engine=InnoDB;

Then the tables that reference accounts like game_searching_player will reference an INT instead of VARCHAR(50) - (I think I see at least 4 references to that column, which would be much simpler if they were ints.)  You may also likely get a small amount of performance improvement by using INT for these keys instead of VARCHARs.
MySQL automatically indexes PRIMARY KEYs, so no need for those explicit INDEX lines.

For example, this:

PRIMARY KEY (maps_id),
INDEX(maps_id)

would become just

 PRIMARY KEY (maps_id)

MySQL's InnoDB engine automatically indexes FOREIGN KEYs, so no need for those explicit INDEX lines either (player and troop_class and game_searching_player).

For example, this:

CREATE TABLE player(
  ...

  PRIMARY KEY (GameID, Player),
  FOREIGN KEY (GameID) REFERENCES games(games_id)
              ON DELETE CASCADE ,
  INDEX(GameID)

) ENGINE=InnoDB;

becomes this:

CREATE TABLE player(
  ...

  PRIMARY KEY (GameID, Player),
  FOREIGN KEY (GameID) REFERENCES games(games_id)
              ON DELETE CASCADE

) ENGINE=InnoDB;

You don't have AUTO_INCREMENT on all your table IDs, but I suspect that you actually want it on them all, since it will simplify your insertion code.
In MySQL all PRIMARY KEYs are also guaranteed to be UNIQUE and NOT NULL, so those attributes aren't really needed on those columns, though my personal preference is that it adds to the readability to leave those attributes on the columns, but thought I'd mention it for reference.
Your player table should probably reference the (new) id in the  accounts table (with a ON DELETE CASCADE setting too).  It also looks like players can have names up to 30 characters long, but accounts can have names up to 50 characters.  (The difference in lengths may also of course indicate that I completely mis-understand the purpose of the player and account tables, and that they really shouldn't be related in any way.)
While it will work perfectly fine the way you have it shown here, in most of the environments and organizations I've worked with/in, it has been standard best practice to make the name of every table's "id" column be id, rather than including the table name in the column name (like maps_id).  This "coding style" choice allows the code to be more concise and since this is a very common practice, it doesn't add any "cognitive load" as maintainers read your queries/schema/code.


JavaScript program to count lines of Java code

Sorry, don't really have the time to do a comprehensive review (maybe later I'll edit!) but for now:

Your code actually fails on some cases.

The way that you're finding whether a line counts as a LOC or not is too greedy. (Alternatively, your comment regexes are too strict.) You're reading in basically the whole line as a line of code. This fails for relatively simple cases:

a/*
b*/

should be one line of code, but you treat it as two, since your code regex absorbs the /*. In fact, I'd argue that the way that you choose to count lines of code is odd; it took me a few reads to see what you were doing and find that error. The more natural way perhaps would be to strip spacing and comments, then count non-empty lines.

That also has the advantage of being way faster: you're calling String#substr() a lot, which is pretty expensive.

Aside from that, I only have a few comments:

Keep spacing consistent. Choose either function() or function (); don't use both.
Be consistent in your choice of indentation character. This is easier if you enable showing whitespace in your editor.
Be consistent in string delimiters; don't switch between ' and " without a good reason.
Since you're using a bare object, you can iterate over it with a for..in. If you're really concerned that somebody will put properties into the prototype of Object (which, by the way, should NEVER EVER happen), then add the hasOwnProperty check:

    for (var tokenType in patterns) {
    //  if (patterns.hasOwnProperty(tokenType)) ...
        if (m = source.match(patterns[tokenType])) {
            var token = m[0];
            source = source.substr(token.length);
            //DEBUG
            console.log('Found token (%s): %s', type, JSON.stringify(token));
            return type;
        }
    }
    throw new Error('Unknown code pattern!');


Script that makes an API call to and parses the response to get a URL from where to download another file

Don't repeat yourself

The two curl commands have significant repeated parts.
You can extract that to a function.

For example:

mycurl() {
    curl -X GET \
         -H 'Accept: application/vnd.xxxxx+json; version=3.0' \
         -H 'Authorization: Bearer RCexxxxxxxxxxxxxxxxxxxxxxxxxcVefI5mWy' \
         -H 'Content-Type: application/json' \
        "$@"
}

And then use it like this:

exportsData=$(mycurl https://api.xxxx.com/apps/9xxxxxxxxx15f96fe/exports)
...
mycurl -o "$ENCRYPTED_TARBALL" https://storage.googleapis.com/someUrlWhereTheFileIsBeingDownloadedFrom

Use here-strings instead of echo ... | ...

Instead of this:

echo $exportsData | jq '.[0].status'

It's better to use here-strings, like this:

jq '.[0].status' <<< "$exportsData"

Small bug

Instead of this:

export ENCRYPTED_TARBALL=encryptedChatDump.tar.gz.enc
 $(curl -X GET -o ENCRYPTED_TARBALL \
...

You probably meant to write this:

export ENCRYPTED_TARBALL=encryptedChatDump.tar.gz.enc
 $(curl -X GET -o "$ENCRYPTED_TARBALL" \
...

Pointless variables?

These variables are set at the end of the script, but what for?

export OUTPUT_TAR=finalChatDumpUnencrypted.tar.gz
export PRIVATE_KEY_PATH=~/.ssh/id_rsa


Composing an HTML email body in PHP swiftmailer

As you're using the Twig template engine already, I would recommend to use it for your email-templates as well. It will have all the advantages like:

easy to maintain
easy to localize
template and its content is separated from your logic
all templates are in one place

Symfony has a manual, how to use Twig together with Swiftmailer. This will work also without the Symfony framework.

In your case you can simply store the rendered template in $message and pass it on to Mail::send():

$message = $twig->renderView(
    'resources/views/emails/password_reset.html.twig', [
    'first_name' => $user["first_name"],
    'reset_link' => $resetLink,
]);

In your template you have all the advantages and simplicity of Twig:

Hello {{ first_name }},

Please click here to reset your password

You could take it one step further and include the subject as well in the template:

{% if true == get_subject %}
    {% spaceless %}
        Password reset link
    {% endspaceless %}
{% else %}
    Hello {{ first_name }}
{% endif %}

You need spaceless in this case for the subject, so that Twig will remove all whitespaces, tabs etc. before and after the subject.


What's the best name for a service object in Rails?

You could use modules to group them which would potentially shorten the names too. You'd probably need to look at the types of service methods you have before deciding how to group them (e.g. by model: Runner::MembershipStatus or activity: Statistics::RunnersWithGoals).

Presumably you've already decided you don't want these methods on your models? For me a service method makes most sense if it's performing an action rather than just retrieving some information. So GetCurrentGoalOfRunner would probably sit on my Runner model as runner.current_goal rather than being a separate service.

Possibly also worth looking at Mutations (which I was introduced to recently): https://eng.uservoice.com/blog/2013/02/27/introducing-mutations-putting-soa-on-rails-for-security-and-maintainability/


You could use this code for checking whether it has an uppercase/lowercase:

if s.lower() == s:
    # doesn't have any uppercase
if s.upper() == s:
    # doesn't have any lowercase

This way, you don't have to iterate through the entire string.


Configurable synchronization approach in Java

I just don't see a point in this factory. It has nothing in common with locking except class name, getLock method and "lock.properties" string inside. It's just a global hash map.
You always can (should) use synchronized with this or even better with private ivar. Any need too use your factory makes me think there is a bad design.