Uniform random numbers in an integer interval in C

There are many good reasons to not use modulo for random numbers like this:
LCGs have poor entropy in lower bits
It's well known that the lower bits on Linear Congruential Generators (LCG) have poor entropy. And although not required to be, rand() is typically an LCG.
This means that using:
rand()%range + min

has even worse entropy as it is only using the lower bits due to the modulo operator.
Using modulo skews the distribution
As if low entropy wasn't enough, using modulo in this way also skews the distribution of numbers.
To see this, imagine RAND_MAX=3 and you do rand()%3 then the possible outcomes are:
0%3 = 0
1%3 = 1
2%3 = 2
3%3 = 0

Zero is twice as likely as any other outcome. This is clearly not uniform! Even for larger RAND_MAX and range values the problem persists. There are some special cases where it works but in general it doesn't.
So how should you do it?
Unfortunately though you see the approach with modulo shown everywhere on the internet because it's easier to understand. Or because people don't know better. Whatever the reason using modulo is not the way to limit the range of a random number generator.
There are a few different ways:
Use all the bits - Floating point rescale
As rand() returns a some what uniform random number in the range [0,RAND_MAX] and we want all numbers to be used; So we can re-scale this range to [0,1[ and multiply it by our desired range and quantize it. This requires a bit of care so that we don't introduce additional bias around the edges of the range:
// Use whatever c equivalent of next_after get one ULP larger than
// RAND_MAX. This transforms the range from to [0,1[ with minimal
// skew in the distribution.
double normalized = rand() / std::next_after(double(RAND_MAX), DOUBLE_MAX);

int rnd = min + int(normalized * (max - min + 1));

This method while better than the modulo in the aspect that it has higher entropy as it uses the high bits of the rand() call still suffers some bias problems. Consider again if RAND_MAX=3, min=0 and max=2;
rand()=0 -> norm = 0                       rnd = 0
rand()=1 -> norm = 0.333333333333333332    rnd = 0
rand()=2 -> norm = 0.666666666666666665    rnd = 1
rand()=3 -> norm = 0.9999999999999999998   rnd = 2

the good news is that as RAND_MAX grows larger, the bias approaches (but never reaches) zero as 1/x (which is also true when using the modulo approach but exaggerated by the bad entropy in the lower bits).
For example for RAND_MAX=3000 you will have 1001 trials that result in rnd=0 and 1000 trials each that result in rnd=1 or rnd=2.
Depending on your requirements, this may or may not be enough.
Use all the bits - Integer only w/ re-rolls
So we want to use the whole range and use integers only, if we split the range of random numbers from rand() into equally large "chunks" and depending on which chunk we "land in" we determine the outcome. In the general case there will be some slack at the end of the range as the chunk size doesn't evenly divide the range, if we roll a value in the slack we just roll again:
int range = max - min + 1;

// Largest value that when multiplied by "range"
// is less than or equal to RAND_MAX
int chunkSize = (RAND_MAX + 1) / range;
int endOfLastChunk = chunkSize * range;

int r = rand();
while(r >= endOfLastChunk){
    r = rand();
}
return min + r / chunkSize;

We have to be careful about the inequalities and off by ones here as any error adds a bias. Lets check:
RAND_MAX = 5;
min = 0;
max = 2;

range = 3;
chunkSize = (5 + 1)/3 = 2;
endOfLastChunk = 2 * 3 = 6;

r = 0 -> return       0;
r = 1 -> return 1/2 = 0;
r = 2 -> return 2/2 = 1;
r = 3 -> return 3/2 = 1;
r = 4 -> return 4/4 = 2;
r = 5 -> return 5/4 = 2;

Yay! No bias! Lets try again with RAND_MAX = 4;
chunkSize = (4 + 1)/3 = 1;
endOfLastChunk = 1 * 3 = 3;

r = 0 -> return       0;
r = 1 -> return 1/1 = 1;
r = 2 -> return 2/1 = 2;
r = 3 -> reroll
r = 4 -> reroll

As you can see no bias here.
The things to take note of: The reroll takes care of the bias; and using the largest possible chunkSize and thus using the largest part possible of the output range of rand() avoids the issue with the low bits being of poor quality (unless you have a very large range but then you're SOL anyway).
The probability of a re-roll is:
(RAND_MAX + 1 - endOfLastChunk) / (RAND_MAX + 1)

note that: (RAND_MAX + 1 - endOfLastChunk) < range
otherwise chunkSize would be bigger. So we have:
 range / (RAND_MAX + 1)

chance of a re-roll.
In closing
That all being said and done, linear congruential generators are generally poor choices for any kind of serious pseudo random numbers overall, you should look into a better generator like for example the widely used Mersenne Twister.


Trying (and failing) to implement the best conventions on OOP Swift

Please consider follow recommendations:

Make habit of extracting each struct/class/enum in separate files which brings more readability and clarity. Code looks less cluttered.

Please try getting used to of not using semicolons :)

You have defined Events as a class with empty implementations of functions. Are you sure you want to do that, I think it could be converted as a protocol instead
To be able to inject different type of calendar APIs, you should define your own protocol and make concrete implementations for each calendar (Adapter Pattern).

You must use dependency injection. For example even things like EKEventStore() should be injected.
final class iCal: Events {

    private let eventStore: EKEventStore

    init(with eventStore: EKEventStore = EKEventStore()) {
        self.eventStore = eventStore
    }
}

Using force unwrap is a bad practice, you should use guard let or if let to unwrap the optional value and only then use that unwrapped value for whatever purpose you want. By using forced unwrapping your app can crashes unexpectedly where it will find a nil value inside any optional variable.

Please make use of Swiftlint to make sure that your code is following standard convention. It will force you to think swift way :)

You should make class final when don't want to allow subclassing it (even if when you are not sure for now). If you do need subclassing later, you can remove final keyword.

All the best!


Mirrors number at borders of interval, untill it lays in the interval

__device__
mirror(int index , int lB, int uB)

You've got an extra space before the first comma, and I think you're missing the function's return type entirely. You should always compile your code with -Wall and fix all the warnings before posting it (or before running it). There's no point in shipping code with bugs.

Similarly funky whitespace on this line:

            index = uB-1 -(index-uB);

Anyway, if you're looking to speed up a piece of code with loops in it, your first thought should be, "How do I get rid of these loops?"

Consider that after you "mirror" index off of both boundaries, you'll simply have reduced its overall value by 2*(uB - lB). Proof:

index = uB-1 - (index-uB);
index = lB + (lB-index);

means

index = lB + lB - (uB - 1 - index + uB);

means

index = 2*lB - 2*uB + 1 + index;

means

index = index - (2*(uB - lB) - 1);

Hmm... I see you have an extra -1 in there. Was that intentional? Let's see if we can reproduce it in a test case.

assert(mirror(0, 0, 3) == 0);
assert(mirror(1, 0, 3) == 1);
assert(mirror(2, 0, 3) == 2);
assert(mirror(3, 0, 3) == 2);
assert(mirror(4, 0, 3) == 1);
assert(mirror(5, 0, 3) == 0);
assert(mirror(6, 0, 3) == 1);
assert(mirror(7, 0, 3) == 2);
assert(mirror(8, 0, 3) == 2);

Yep, the two boundaries behave differently! The moral of the story is: Always test your code.

Now that we know how the code behaves (which, honestly, probably isn't how you intended it to behave) — we can modify it safe in the knowledge that we won't introduce bugs. We just have to keep all our test cases passing. (Of course we should write some test cases with negative inputs, too.)

Any time you have code with repeated addition, you should think about whether it can be replaced with multiplication; and any time you have repeated subtraction, you should think about whether it can be replaced with division (which is to say, modulus).

int mirror(int index, int lB, int uB) {
    int n = uB - lB;
    int period = 2*n - 1;  // the pattern repeats with this period
    int mod_p = (index - lB) % period;
    if (mod_p < n) {
        return lB + mod_p;
    } else {
        return uB - 1 - (mod_p - n);
    }
}


Switching between tabs inside of a web application

The if statement doesn't do what you think it does.

Optional details about the .css() function:

   The .css() function is overloaded in a number of ways. It can take one string, two strings, or an object.

 In the first form, it returns the current value of the specified property. This will probably not be exactly as you specified it. For example, $("body").css("background-color", "red").css("background-color") returns "rgb(255, 0, 0)" for me.

 In the second, it sets the specified property (first string) to the given value, and returns the jQuery object. In the third, it sets the specified properties (given as keys of the object) to their respective values. This form also returns the jQuery object, for more method chaining.

 As you can see, if you're intent on using the .css() function to check a value, the first form is what you want.

A better way of checking visibility would be to use the .is() function in conjunction with the :visible selector.

Here's my revision. I took the liberty of renaming the parameters. I also used the common practice of naming jQuery variables using Hungarian notation.

function switchTab(toActivate, toDeactivate) {
    var $toActivate = $(toActivate);
    var $toDeactivate = $(toDeactivate);

    if (!$toActivate.is(":visible")) {
        $toActivate.css("visibility", "visible");
        $toDeactivate.css("visibility", "hidden");
    }
}

Another way:

If there's some common selector between the tabs (for example, if they all have the class .tab) and you're fine with display: none; instead of visibility: hidden;, you can simplify to the following:

function switchTab(toActivate) {
    $(".tab").hide();
    $(toActivate).show();
}


Class Module to wrap up classic ADO call to SQL-server

Suggestions:

Don't assume the cursor type of the recordset, the user might want a different type.
Consider making a ConnectionString class that lets the user use properties to get and let the individual parameters, but allows assigning or returning a complete string
Don't force the connection to close, as the user might intend to make subsequent calls.


D-flop with enable and clear, translated from VHDL to Haskell

I actually think your first attempt is the most readable. The advantage over the VDHL implementation is that you're annotating each case with a function name. This makes it more self-documenting.

I would just multi-line your if-statements, like this:

onTrue :: St -> PIn -> Bool -> St
onTrue st PIn{..} edgeDetect = shouldReset
  where
    nullState = St 0
    shouldReset =
      if _reset
        then nullState
        else risingEdge
    risingEdge =
      if edgeDetect
        then shouldClear
        else st
    shouldClear =
      if _clear_n
        then nullState
        else enabled
    enabled =
      if _enable
        then st{ _out_1 = _in_1 }
        else st


Using Poor Man's DI to inject helper class dependencies

I don't see anything wrong with your implementation - if it works for you, and does not interfere with the system - go for it!

I will even go further and claim that the guard conditions in your internal constructor are redundant because the constructor will only be used by the single public constructor, or by a test which:

Either counts on the helper - in which case a NullPointerException will occur and fail the test, or
Does not need the helper, in which case there is no need to mock it...

Final note: I guess that the public constructor actually uses resourceService and serializer in some code you deleted from it, otherwise, the guard conditions there are also redundant...


Substitute Excel-Workbook reference for another

Try adding Application.Calculation = xlManual where you turn updating off, and then turn it back to xlAutomatic at the end.

In addition, turn events off (and then on again): Application.EnableEvents = False and Application.EnableEvents = True.

I suspect that everytime you change a file name in a cell, the workbook tries to access the link and update the cell.

Small point - doesn't affect speed:

If Mid(DateiName, 1, 1) <> "[" Then
    DateiName = "[" & DateiName
    DateiName = DateiName & "]"
End If

could be

If Mid(DateiName, 1, 1) <> "[" Then
    DateiName = "[" & DateiName & "]"
End If

Instead of Set wb = ActiveWorkbook, you could use ThisWorkbook - it is a little more assertive if that is what you need. I don't have the context on how this function is used, so it may be called when another workbook is active.


Creating a Python namedtuple class that forces some of its fields to be floats

In order to reuse code (that is, namedtuple) it should be okay to use
this approach.  It might also make things harder in the long run, so it
could be easier to use a regular meta-/class or decorator to enforce this kind of
logic.  I also see a problem with automatic conversion of values, as
that needs to be communicated/debugged later on, but if it fits the use
case, why not.  Since the tuple is immutable there's no normal way to
circumvent this, so I guess it is less of an issue than with a mutable
class.

Also, have you looked at the collections.py source?  I mean it's good
that it works, but honestly that code generation is a bit scary.  It is, however, a way to generate all this stuff at runtime.  If you don't have to have separate Python classes you could also just use a single class and pass in the valid fields as a separate parameter, then use functions to create the separate tuple "types".

For the presented code / your questions I have some other suggestions:

You can override __repr__ to fix the "wrong" printed
representation.  I'm not quite sure exactly why it is kind of
hardcoded in collections.py, but generally I'd prefer things to
print their own class name instead, as written below.  The
formatting is copied from the standard namedtuple.
If it's happening once, that is not nice, but certainly not the
biggest issue.  Again, you could follow the code generation model
and pass it in as a parameter,
e.g. typednamedtuple('TypedNamedTuple', FIELDS_AND_TYPES).
Use izip to prevent allocating a new list.  Otherwise looks good?
I can't see how you would otherwise do the conversion.
Subclass and override the field?  Note the AnotherTypedNamedTuple
below.  Otherwise see above.

Also:

Don't assign to self.  That looks super wrong.

from collections import namedtuple, OrderedDict
from itertools import izip

# This list is built at runtime in my application
_FIELDS_AND_TYPES = [("num1", True), ("num2", True), ("label", False)]
FIELDS_FORCE_FLOAT = OrderedDict(_FIELDS_AND_TYPES)

_MyNamedTuple = namedtuple("_MyNamedTuple", FIELDS_FORCE_FLOAT.keys())
class TypedNamedTuple(_MyNamedTuple):
    fields_force_float = FIELDS_FORCE_FLOAT

    def __new__(cls, *values_in):
        super_obj = super(_MyNamedTuple, cls)
        superclass = super_obj.__thisclass__
        values = [float(value) if cls.fields_force_float[fieldname] else value
                  for fieldname, value in izip(superclass._fields, values_in)]
        return super_obj.__new__(cls, values)

    def __repr__(self):
        return "{}({})".format(
            self.__class__.__name__,
            ', '.join("{}=%r".format(name) for name in self._fields) % self)

print TypedNamedTuple("1.0", "2.0", "3.0")
# TypedNamedTuple(num1=1.0, num2=2.0, label='3.0')

class AnotherTypedNamedTuple(TypedNamedTuple):
    fields_force_float = OrderedDict([("num1", False), ("num2", False), ("label", False)])

print AnotherTypedNamedTuple("1.0", "2.0", "3.0")
# AnotherTypedNamedTuple(num1='1.0', num2='2.0', label='3.0')


PANDAS code for calculating distance between waypoints

Your code can be greatly simplified when using pandas.DataFrame.groupby. This function groups a dataframe by some key(s) and then allows performing functions that act on the whole sub-dataframe (henceforth called group) using apply or apply some aggregating function to single columns of that group using aggregate.

For this to work, we need to define a dist function that can take a DataFrame and calculate the total distance of that DataFrame. Note that I will assume that each trip is sorted within the csv, otherwise you will have to add this there as well.

To make the dist function, we need to make sure all functions it uses are vectorized, so I will be using np.cos and np.sqrt instead of the math ones. I also defined a constant, EARTH_RADIUS, because you might want to change the precision on that at some point. In any case, it is currently a magic number and giving it a name helps a lot. Or maybe you move to Mars at some point and need to use a different radius :)

import pandas as pd
import numpy as np

EARTH_RADIUS = 6371  # km

def total_dist(group):
    lat = np.radians(group.Lat)
    lon = np.radians(group.Lon)
    endLon = lon.shift(-1)
    endLat = lat.shift(-1)
    x = (endLon - lon) * np.cos(0.5 * (endLat + lat))
    y = endLat - lat
    D = EARTH_RADIUS * np.sqrt(x**2 + y**2)
    return D.sum()

Note that the conversion to radians is not as nice anymore, but we gain the ability to process a whole trip at a time!

Now we define a helper function to output not only the dist, but also the number of waypoints (by using len):

def trip_statistics(trip):
    return pd.Series({"Distance": total_dist(trip),
                      "No. of Waypoints": len(trip)})

Now the only thing left to do is apply this function to all groups and reset the index to get TripID back as a column and not just as an index:

waypoint = pd.read_csv('TripRecordsReportWaypoints.csv', sep=',',
                       header=None, usecols=[0, 3, 4],
                       names=['TripID', 'Lat', 'Lon'])
output = waypoint.groupby("TripID").apply(trip_statistics)
output.reset_index().to_csv('TripDistances.csv', sep=',', index=False)

Note that I added index=False to avoid writing the row index to the output file.


Codility voracious fish are moving along a river

This is an example of a situation where good naming is your friend. Instead of parameters A and B, and magic numbers 0 and 1, and the rather long-winded expression stack.Peek(), I suggest you start by installing some useful names:

const int UPSTREAM = 0;
const int DOWNSTREAM = 1;

public static int solution(int[] size, int[] direction)
{
    var stack = new Stack<int>();
    var updateStack = false;
    for (int i = 0; i < size.Length; i++)
    {
        if (stack.Count <= 0) //initial data
            stack.Push(i);
        else
        {
            var lastFish = stack.Peek();

            if (direction[i] == direction[lastFish]
             || direction[i] != direction[lastFish]
                && direction[lastFish] == UPSTREAM
                && direction[i] == DOWNSTREAM)
            {
                stack.Push(i);
            }
            else
            {
                while (stack.Count > 0
                       && size[lastFish] < size[i]
                       && direction[lastFish] == DOWNSTREAM
                       && direction[i] == UPSTREAM)
                {
                    updateStack = true;
                    stack.Pop();
                    lastFish = stack.Peek();
                }
                if (updateStack)
                    stack.Push(i);
            }
        }

    }
    return stack.Count;
}

This shows me there is some confusion on your part. You are allowed to assume that a logical or (||) fails because it's false - there's no need to repeat the test in a false mode:

if (direction[i] == direction[lastFish]
 || direction[i] != direction[lastFish] && ...

Instead, just assume that failure implies failure, and go on:

if (direction[i] == direction[lastFish]
  || direction[lastFish] == UPSTREAM
     && direction[i] == DOWNSTREAM)

Furthermore, you can assume that since you know the directions are different, and since you know there are only two directions, testing one of them is enough:

if (direction[i] == direction[lastFish] || direction[i] == DOWNSTREAM)

That said, I notice that you initialize updateStack to false outside of your loop and never reset it to false anyplace else. This means that once you've set updateStack = true, it will stay true forever (inside you loop, anyway). That's probably the source of your error, because it should stop being true once you've updated the stack.


How to convert my classes to Dependency injection?

First, a few minor comments:

Class properties should almost always be protected or private.  This forces you to use a known tested interface (the class methods) to interact with the state stored in the class.  The properties section, something and validation should have all been protected or private.

Your method add does not add, it sets.  add might be appropriate for concatenation (although I'd prefer append or prepend).  It is best used for real addition.  Your add implementation would have been better named set.

I have added to your example class to highlight the benefits of Dependency Injection.  I have used text and title in place of your something.

Validation Interface

The validation interface defines the way to check for validity.  If we need to check for validity and we are passed an object that implements this interface we can be sure that it will work.  By relying on an interface rather than a specific object we reduce our coupling from a specific object to any object that implements the interface.

interface IValidation
{
    public function isValid($str);
}

Section Class

The constructor accepts all of the parameters that the class needs (the dependencies are injected).  I have used an array in the constructor (as a personal preference to remove a required order of parameters and to use named parameters with the associative array).  Standard SPL exceptions are thrown if the validation objects do not match the Validation interface.

class Section
{
    // Text for the section.
    protected $text;

    // Validation for the text.
    protected $textValidation;

    /// Title for the section.
    protected $title;

    // Validation for the title.
    protected $titleValidation;

    public function __construct(Array $setup)
    {
        $setup += array('Text'             => '',
                        'Text_Validation'  => NULL,
                        'Title'            => '',
                        'Title_Validation' => NULL);

        if (!$setup['Text_Validation'] instanceof IValidation)
        {
            throw new \InvalidArgumentException(
                __METHOD__ . ' requires Text_Validator');
        }

        if (!$setup['Title_Validation'] instanceof IValidation)
        {
            throw new \InvalidArgumentException(
                __METHOD__ . ' requires Title_Validation');
        }

        $this->text            = $setup['Text'];
        $this->textValidation  = $setup['Text_Validation'];
        $this->title           = $setup['Title'];
        $this->titleValidation = $setup['Title_Validation'];
    }

    public function setText($text)
    {
        $this->text = $text;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    // Return whether the section is valid.
    public function isValid()
    {
        return $this->textValidation->isValid($this->text) &&
            $this->titleValidation->isValid($this->title);
    }
}

Validation Class

Notice how this class implements the interface.

class Validation implements IValidation
{
    // The regex for a valid match.
    protected $validMatch;

    public function __construct($validMatch)
    {
        $this->validMatch = $validMatch;
    }

    public function isValid($str)
    {
        return preg_match($this->validMatch, $str);
    }
}

Usage

We can see from the usage some of the benefits of dependency injection.  There is no hardcoded dependencies in any of the classes and we can glue the components together when they are used.  This allows us to define the exact type of validations that we require and pass them to the Section class with injection.

$alphanumUnderscores = new Validation('/^[[:alnum:]_]*$/');
$digits = new Validation('/^[[:digit:]]+$/');

$section = new Section(array('Text_Validation'  => $alphanumUnderscores,
                             'Title'            => 'InvalidTitle',
                             'Title_Validation' => $digits));

if (!$section->isValid())
{
    // The title should be digits.
    echo 'As expected the title is invalid.' . "\n";
}

$section->setTitle(9876);

if ($section->isValid())
{
    echo 'As expected the title is valid with digits.' . "\n";
}


I'm not sure what you're trying to do, so I'll just review the code itself, not what you're trying to do.

I looked into the whole script on GitHub and was shocked to see that you didn't use strict; use warnings. This would usually abort any review, but let's continue for the sake of the argument.

I think it's very nice that you've used POD documentation for your script.

Let's look at this excerpt for a moment:

unless ($type) {
    $ref=~s/\n/\r/isg;
    $ref=~s/\"/\\"/isg;
    return $ref;
}

ref $foo can be false, but a reference (consider $foo = bless \$bar, "0"). Use either length ref $foo or reftype $foo, where reftype is imported from Scalar::Util.
unless is widely considered to be half a design error. if (not ...) is cleared most of the time.
On each of your regexes you specify the flags /isg.

The /i does case insensitive matching  but you don't match anything that has a case. As this flag reduces performance, you should use it sparingly.
The /s flag causes the . to match any character including newlines. It is generally a good idea to use this flag (the default behavior of . is better written as [^\n]). However, you do not use the . metacharacter, so /s is useless here.

In the pattern, " does not have to be escaped as it isn't a metacharacter.
Use proper spacing around operators (usually a single space) to improve readability.

Suggested refactoring:

if (not length $type) {
    $ref =~ s/\n/\r/g;
    $ref =~ s/"/\\"/g;
    return $ref;
}

Now let's take a look at unless ($name) {$name = "REF".++$hash2rdf_count;}:

As per Larry's style guide, you shouldn't use a semicolon if the closing brace is on the same line.
Never use the conditional (...) {BLOCK} form on a single line. Either put the statement on a line of its own, or use the statement modifier form:

$name = "REF" . ++$hash2rdf_count unless length $name;

or

if (not length $name) {
    $name = "REF" . ++$hash2rdf_count;
}

If you only want to overwrite $name if it is undef, you could either test for definedness: if (not defined $name) or since perl 5.10, you can use the defined-or operator //:

$name //= "REF" . ++$hash2rdf_count;

What to do about the $has2rdf_count? The simplest solution that does not involve globals is to declare it outside of the subroutine:

my $hash2rdf_count = 0;
sub hash2rdf {

A better solution (since perl 5.10) is to use state variables:

use feture 'state';
...
state $hash2rdf_count = 0;
$name //= "REF" . ++$hash2rdf_count;

A state variable belongs to a certain scope like my variables, but is initialized only at the first execution.

However, it may be better to take this as another argument (will be discussed later).

my(@l) = @{$ref}  there is no need to perform a copy of the array, and even if you feel the need to do that, please don't use a bad variable name like @l. Especially the charcterl l should be avoided on its own. Also, variable names don't have to be so short. Given an array reference, we can access an entry like $ref->[$i] and get the highest index like $#$ref (or with curlies: $#{$ref}).

By now we know how a line like for $i (0..$#l) {push(@triplets, [$name, $i, hash2rdf($l[$i])]);} can be improved. But I would like you to call builtins like push without parens: They aren't subroutines, but operators.

With a statement modifier:

push @triplets, [$name, $_, hash2rdf($ref->[$_])] for 0 .. $#$ref;

Without:

for my $i (0 .. $#ref) {
    push @triplets, [$name, $i, hash2rdf($ref->[$i])];
}

And then there is a variant with map:

push @triplets, map { [$name, $_, hash2rdf($ref->[$_])] } 0 .. $#$ref;

The same holds for the HASH-reference case. Recommended refactoring there:

for my $key (keys %$ref) {
    push @triplets, [$name, $key, hash2rdf($ref->{$key})];
}

Note that I'm not using $i here, as the hash key won't generally be an integer.

How can we solve the problem that @triplets is a global? We take a reference to that array as another argument:

sub hash2rdf {
    my ($ref, $triplets, $name) = @_;
    ...
    push @$triplets, ...

This means that we have to change the way how we call ourselves when recursing:

hash2rdf($ref->[$i], $triplets)

On the outside, we call the subroutine like

hash2rdf(\@releases, \my @triplets, "root");

Eww, that is ugly (out-arguments always bother me). Let's rename hash2rdf to hash2rdf_inner, and create a wrapper. This is also a good opportunity to pass $has2rdf_count as an argument, and to rename the wrapper to something better.

sub ref2rdf {
  my ($data, $name) = @_;
  my $count = 0;
  my @triplets;
  ref2rdf_inner($data, \@triplets, $name, \$count);
  return @triplets;
}

sub ref2rdf_inner {
  my ($ref, $triplets, $name, $count_ref) = @_;
  ...
  $name //= "REF" . ++$$count_ref;
  ...
  ref2rdf_inner($ref->[$i], $triplets, undef, $count_ref)
  ...
}

We could now dump a data structure like

use feature 'say'; # say is like print, but with newline

for my $triplet (ref2rdf(\@releases, "root")) {
  say join "\t", @$triplet;
}

Happy refactoring!

Edit: This code still has unresolved issues, e.g. hash keys can contain arbitrary strings which may include NUL, LF, tabs, spaces, or quotes. Those would have to be properly sanitized as well.


Selecting attributes corresponding to the most frequent entries in a junction table

Observe that this expression is almost repeated:

SELECT a_field, COUNT(a_field) AS amount
    FROM JunctionTable
    GROUP BY a_field

That is an indication that you could use a Common Table Expression.  Given the limited information I have about your situation, I would call it JunctionCount.  I would rename amount, which is ambiguous, to occurrences.

To obtain all junctions that have the maximal number of occurrences, you can use the RANK() window function.

WITH JunctionCount AS (
    SELECT a_field, COUNT(*) AS occurrences
        FROM JunctionTable
        GROUP BY a_field
), MostJunctions AS (
    SELECT a_field, RANK() OVER (ORDER BY occurrences DESC) AS occurrence_rank
        FROM JunctionCount
) SELECT b_field
    FROM MyTable
        INNER JOIN MostJunctions
            ON MyTable.a_field = MostJunctions.a_field
    WHERE MostJunctions.occurrence_rank = 1;


Modifying a random String stored in the clipboard

main :: IO ()
main = traverse_ doNoise =<< getClipboardString where
 doNoise = setClipboardString <=< traverse randCap
 randCap x = bool id toUpper <$> (randomIO :: IO Bool) <*> pure x

Edit: Each change was arrived at through pattern-matching from my experience; compact code is usually easier to work with further. Looking at this again makes me think there ought to be a more lensy solution, one that fuses getting and setting, and indeed:

main = modifyClipboardString =<<
  zipWith (bool id toUpper) <$> getRandoms

We are fortunate to not actually need side effects depending on clipboard contents, but if we did, I would recommend writing a monadic variant of modifyClipboardString.


Your function fails to calculate \$x^0\$ correctly. I would expect it to return Double.NaN when \$x = 0\$, and 1 otherwise.


I suggest you use a Set when checking for duplicates:

Set<Integer> set = new HashSet<>();

for(int i : selectedWordIds) {
    if(!set.add(i)) {
        repeatedTime++;
    }
}

This is much simpler that what you have.

Here:

 if(repeatedTime > 1)
 {
     notDuplicate = false;
     RandomizeFunction(selectedWordIds, answersTempId);
 }

The assignment notDuplicate = false is not necessary because notDuplicate is already false.

About recursion: It is possible. With it, here is the final code:

private void CheckForDuplicates(int[] selectedWordIds,
        List<Integer> answersTempId) {

    int repeatedTime = 0;

    Set<Integer> set = new HashSet<>();

    for(int i : selectedWordIds) {
        if(!set.add(i)) {
            repeatedTime++;
        }
    }
    if (repeatedTime > 1) {
        RandomizeFunction(selectedWordIds, answersTempId);
        CheckForDuplicates(selectedWordIds, answersTempId);
    }

}


How can I configure Vee Validator so that it evaluates the oneChecked validator with the call of this.$validator.validateAll();?

Yes, you can use validateAll(), you're just not passing the fields for it to validate. Here's an example on how to do this:

methods: {
  validateBeforeSubmit(e) {
    this.$validator.validateAll({
      name0: true
    });
    console.log('validator', this.errors);
    if (!this.errors.any()) {
      alert('succesfully submitted!');
    }
  }
}

Taken from here.

  Is it possible to pass the this.options array into validate method of oneChecked validator? (Would be more re-usable. I've tried passing as array with JSON.stringify but couldn't get it to work.)

Why pass it as a parameter when it's already a constant?

Consider this:

created() {
  this.$validator.extend('oneChecked', {
    getMessage: field => 'At least one ' + field + ' needs to be checked.',
    validate: (value, [testProp]) => {
      return value || Checkboxes.data().options.some((option) => option[testProp]);
    }
  });
},

This also provides you some protection for when data().options inevitably has more than 3 elements in it.


Some comments on your code. Overall you are using a lot of unnecessary variables.

another_word = " "
sentence1 = " "
new_list = []
another = " "

You really don't need these variables declared outside of your functions, they add no value and just pollute the namespace.

def trans_one_word (i):

PEP8 doesn't recommend a  before the args. And you should consider having more meaningful arg names.

    global another_word

Unnecessary global, you are returning this variable from the function so don't need it to be global

    pyg = 'ay'

    original = (i)

Parens are unnecessary and you could just call the arg original as you don't need this assignment.

    if len(original) > 0 and original.isalpha():
        word = original.lower()
        first = word[0]
        new_word = word + first + pyg
        another_word = new_word[1:len(new_word)]

You don't need len(new_word) on a slice an empty slice implies to the end of the word, e.g. new_word[1:]

        first = word[0]
        new_word = word + first + pyg
        another_word = new_word[1:len(new_word)]
        return another_word

This whole block can be simplified to return word[1:] + word[0] + pyg

    else:
        print('empty')

You don't need the else: clause because the previous block returned. You should also return the original word.

def input_state():

    sentence = input("enter a word to be translated: ")

Assume you meant to ask for a words or a sentence given the variable name:

    list = sentence.split()

list is a python type, so shouldn't be used for a variable name.

    for i in list:
        trans_one_word(i)
        new_list.append(another_word)
    s = " "

You should look into list comprehensions and generators as this can be significantly simplified, e.g. print(" ".join(trans_one_word(i) for i in sentence.split()))

    print (s.join( new_list ))

It's probably better to return this result and let the caller print it.

input_state()

another = input("Would you like to enter another sentence to be     translated? \n Y/N")

if (another == 'y') or (another == 'Y'):
    input_state()

This condition can be replaced with if another in 'yY':
You should really put this all into a loop so with an exit clause.

Simplifying the code:

def trans_one_word(word):
    pyg = 'ay'

    if word and word.isalpha():
        word = word.lower()
        return word[1:] + word[0] + pyg
    return word

def input_state():
    sentence = input("enter a sentence to be translated: ")
    return " ".join(trans_one_word(word) for word in sentence.split())

while True:
    print(input_state())
    another = input("Would you like to enter another sentence to be translated?\nY/N")
    if another not in 'yY':
        break


Displaying categories and subcategories in php having different tables

Yes, let's see:

You are vulnerable to SQL injection: By including variables directly in the query, you are making yourself vulnerable to SQL injection attacks. Use prepared statements. Further reading: How can I prevent SQL Injection in PHP?
Don't use
 for vertical spacing control. You should use proper semantic elements, for example:

Subcat 1

Subsubcat 1

Subsubcat 2

Subsubcat 3

Aside from that, LGTM. Good job! :)

Example for prepared statements:

$stmt = mysqli_prepare($connect, "SELECT subcategories.subcat_name, subsubcategories.subsubcat_name, subcategories.subcat_ID FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = ? OR subcategories.extra_cat_ID = ? ORDER BY subcategories.subcat_name, subsubcategories.subsubcat_name ASC");
mysqli_stmt_bind_param($stmt, "ii", $cat_ID, $cat_ID);
mysqli_stmt_execute($stmt);


Alright, first some styling remarks.

Indent correctly

Opening braces of your method should be at the same level below of the method signature, not indented. You seem to have done it correctly elsewhere so that might be a copying error.

Follow naming conventions

Parameters and local variables are lowerCamelCase. This means XCoordinate becomes xCoordinate and likewise for YCoordinate.

Positive beats negative beats battlestar galactica

Always prefer using "positive" expressions rather than "negative". If I'd want to use your code to say the coordinate is valid, I'd have to use if(!invalidCoordinate). Nobody likes double negation.

I can see why you might have done this (invalid input sets invalidCoordinate to true) but in that case I would just use a break; statement to exit your loop.

Change it to validCoordinate and your loop becomes while(!validCoordinate).

Braces around if statements

Some will argue this but to avoid misconceptions or problems with future changes: always place {} brackets around statements that can have it to very clearly mark their scope. Your else statements don't have this which makes it prone to logical errors (forgetting to add the braces when the else block actually needs more than just that statement).

Don't overassign

Your while loop already stops when invalidCoordinate is true. There is no point in explicitly setting it to false.

No typos

Yuck.

Don't repeat yourself

It seems to me that both x and y have to be between 1 and 3? Let's put that in a method instead of copy-pasting it and changing where needed.

Useful comments

I know that is the end of GetMoveCoordinates because your favorite awesome best-in-the-galaxy IDE - Visual Studio - will show you that. Place your cursor behind the closing brace and it will popup the method definition at the top of your editor window.

As has been noted in the comments: make sure that your comments explain why you do something. It is not clear why things have to be between 1 and 3 exactly so this is a good place to start.

After applying all this, we have this situation:

public static void GetMoveCoordinates(ref int xCoordinate, ref int yCoordinate)
{
   bool validCoordinate = true;

   do
   {
       try
       {
            Console.Write("Enter x coordinate: ");
            GetCoordinate(ref validCoordinate, ref xCoordinate);

            if (validCoordinate)
            {
                Console.Write("Enter y coordinate: ");
                GetCoordinate(ref validCoordinate, ref yCoordinate);
            }
       }

       catch
       {
           Console.WriteLine("Invalid coordinates, please try again.");
           break;
       }
       Console.WriteLine();
   } while (!validCoordinate);
}

private static void GetCoordinate(ref bool validCoordinate, ref int coordinate)
{
    coordinate = int.Parse(Console.ReadLine());
    if (coordinate < 1 || coordinate > 3)
    {
        validCoordinate = false;
        Console.WriteLine("Invalid coordinates, please try again.");
    }
}

Now it's easy to see what you can do with that try block: you move it to the helper method! And the result is this:

public static void GetMoveCoordinates(ref int xCoordinate, ref int yCoordinate)
{
   bool validCoordinate = true;

   do
   {
    Console.Write("Enter x coordinate: ");
    GetCoordinate(ref validCoordinate, ref xCoordinate);

    if (validCoordinate)
    {
        Console.Write("Enter y coordinate: ");
        GetCoordinate(ref validCoordinate, ref yCoordinate);
    }

    Console.WriteLine();
   } while (!validCoordinate);
}

private static void GetCoordinate(ref bool validCoordinate, ref int coordinate)
{
    try
    {
        coordinate = int.Parse(Console.ReadLine());
    }
    catch
    {
        Console.WriteLine("Invalid coordinates, please try again.");
        validCoordinate = false;
        return;
    }

    if (coordinate < 1 || coordinate > 3)
    {
        validCoordinate = false;
        Console.WriteLine("Invalid coordinates, please try again.");
    }
}


Instead of children = new Node[11], I would use a Map<Integer, Node>.  I'm not sure how you came up with 11.
Sorting is quite expensive.  Maybe you can solve it with a trie alone without sorting, or with sorting alone without a trie.
Small detail: you have random gaps of 2, 3 or 4 empty lines all over the place.

EDIT:
So, instead of arguing, here is my implementation, without sorting and without a terminal value:

    public static class Node<T> {
        private T value;
        private Map<T, Node<T>> children = new HashMap<>();

        public Node(T value) {
            this.value = value;
        }

        public Node<T> getChild(T t) {
            return children.get(t);
        }

        public boolean hasChildren() {
            return !children.isEmpty();
        }

        public void addChild(T t, Node<T> child) {
            children.put(t, child);
        }
    }

    public static boolean hasConflictingPrefixes(String[] numbers) {
        Node<Byte> trie = new Node<>(null);
        for (String number : numbers) {
            Node<Byte> currentNode = trie;
            for (Byte byt : number.getBytes(Charset.forName("UTF-8"))) {
                Node<Byte> childNode = currentNode.getChild(byt);
                if (childNode == null) {
                    childNode = new Node(byt);
                    currentNode.addChild(byt, childNode);
                } else {
                    // current number is longer (or equal) to existing word
                    if (!childNode.hasChildren())
                        return true;
                }
                currentNode = childNode;
            }
            // current number is a prefix to another one
            if (currentNode.hasChildren())
                return true;
        }
        return false;
    }

I'm not necessarily proud of this code, but it solves this problem.

Note that duplicate numbers are considered as conflicting prefixes, ie. {"911", "911"} has a conflict just as {"911", "9112"}.


While this function does what you want, it can be greatly simplified.

function letterDetector(str) {
  if (!str) { //Handles both undefined and the empty string
    return "Please input an argument"
  }
  // Replace everything that isn't the letter, then get the first letter.
  const firstLetter = str.replace(/[^a-z]/gi, '').charAt(0)
  return "Your first name letter is " + firstLetter.toUpperCase()
}

for (const str of ["Adam", "£1%Adam", "", undefined]) {
  console.log("'" + str + "'", "-->", letterDetector(str))
}

A few things to note about your implementation:

return is not a function, there is no need to wrap what you are returning with parenthesis (and generally you shouldn't).
Be consistent. Should this function log to the console or return the result? Personally, I prefer returning to avoid side effects, which will help keep your code simpler when working on more complex projects.
Uncovered edge case: What if I input 123?
Don't use (near) keywords as variable names. string looks very close to String and could easily be mistaken for it.
Though in this case it seems you aren't handling non-ascii characters, it is a good idea to use toLocaleLowerCase() and toLocaleUpperCase() instead of toLowerCase() and toUpperCase() to avoid a multitude of problems with languages other than English.
Don't define variables you don't use, result is never used and thus can be dropped.
Since you use arrow functions, you can use const and let instead of var. This is a good switch to make in order to easily avoid any future pain where variables aren't scoped as you expect (especially if you work with other languages like C or Java where everything is block scoped, var is function scoped)


Summer camp cost calculation using Google Sheets

Short and partial answer

Instead of the use nested IF() use INDEX(), MATCH() and IFERROR()

Notes for a complete answer

It could be possible to do a further refinement of the formula by using arrays but the patterns should be understood deeply before to proceed on the implementation of such tools.

EDIT: An array formula was added to the bottom.

Explanation of the short and partial answer

The formula has 34 outer IF(), each of them:

having a cell reference as the value to return when the test returns true. The three values are in the same one column range.
having a nested IF() with another IF()  as the value to return when the test returns false
The last IF returns 0 in when the test returns false.

In cases like the above, using lookup functions will help to have concise formulas that also are usually easy to read and debug.

Formula pattern

IF(AA2=Frais!$B$17,Frais!$C$9,IF(AA2=Frais!$B$18,Frais!$C$10,IF(AA2=Frais!$B$19,Frais!$C$11,0)))

IFERROR(Index(Frais!$C$9:$C$11,Match(AA2,Frais!$B$17:$B$19,0)),0)

Resulting formula

Remark: Google Sheets allow the insertion of breaklines in formula. This could be helpful in complex formulas like the discussed in this Q&A.

=SUM(
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AA2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AB2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AC2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AD2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( AE2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AF2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AG2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CC2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CD2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CE2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CF2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( CG2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CH2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CI2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DI2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DJ2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DK2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DL2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( DM2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DN2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DO2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( EO2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( EP2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( EQ2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( ER2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( ES2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( ET2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( EU2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FU2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FV2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FW2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FX2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( FY2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FZ2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( GA2, Frais!$B$17:$B$19, 0)))
)

Array formula

The following formula makes use of the array notation and capability of SUM() and VLOOKUP() to work with array formulas.

=ArrayFormula(
    SUM(
        IFERROR(
        VLOOKUP({
            AA2,AB2,AC2,AD2,AF2,AG2,
            CC2,CD2,CE2,CF2,CH2,CI2,
            DI2,DJ2,DK2,DL2,DN2,DO2,
            EO2,EP2,EQ2,ER2,ET2,EU2,
            FU2,FV2,FW2,FX2,FZ2,GA2
        },
        {Frais!$B$17:$B$19, Frais!$C$9:$C$11},2,0),0),
        IFERROR(
            VLOOKUP({
                AE2,
                CG2,
                DM2,
                ES2,
                FY2
            },
            {Frais!$B$17:$B$19,Frais!$D$9:$D$11},2,0),0)
    )
)


Given a set of closed intervals, find the smallest set of numbers that covers all the intervals

Naming
First point is that I think the naming is getting a little verbose smallestIntervallCoveringAllIntervalls and getLargestMinAndSmallestMax

getLargestMinAndSmallestMax get largest min and smallest max, don't you mean get "range"? And its not get, the range is not known, you need to "find" it. findRange

smallestIntervallCoveringAllIntervalls This is when comments come into play. If you were part of a team that functions name would already be defined in the interface spec. However if it was an internal call (your code) you would use a smaller name and add a comment to give it the missing meaning as a reminder to you, or for someone that may later need to modify your code.

Spelling
intervalls should be intervals
Bad spelling is a gateway to bug hell. Others can not guess how you have misspelled a name, so always check if you are unsure as to the spelling of a name.
The spec
No project starts without a detailed specification regarding the problem. Part of a programmers job is to ensure that the spec is unambiguous.
If you have any questions that the spec can not answer then you should not start working on a solution. Rather a memo to the team leader, or email to the client with the points that need to be resolved.
So lets restate the problem

Given an array of intervals find the smallest interval that covers all intervals.

The intervals array will always contain one or more valid intervals.

An interval is covering another interval if one or more values in its range are the same. Examples A = [0, 1], B = [1, 2], C = [3, 4]. A covers B, C does not cover A and B

An interval is an array containing two unsorted integers, that have a range from min to max value inclusive. Examples [0, 1] has a range 0, 1. [3, -2] has a range  -2, -1, 0, 1, 2, 3. [2, 2] has a range 2.
The following [], [0], [1,2,3] are not valid intervals

The return must be a valid interval

Your code
You have a bug and return incorrect intervals in some cases.
Two examples of the bug

Given  the intervals [[10, 20], [10, -20]] your function returns [-20,10] which is in fact the largest range, the correct solution is [10, 10] (Yes unfair as [10,-20] is A over T)

Given intervals [[10,20]] you incorrectly return [10,20]. There are 11 possible correct solutions. Any of  [10,10], [11, 11], ..., [n, n] (n = 20)

The reason you are returning incorrect intervals is that you do not treat the first interval correctly, as shown in the second example above.
When finding min and max values of a set of anything with at least one item, you always treat the first item differently. The first items initializes the min or max.
You use Array.reduce so that means you need to include a test to see if you have the first interval.
The interval that covers a single interval always has a range length of one and is any of the values in the intervals range. eg [[10,20]] is covered by [10,10] or [20,20]
Fix using your logic
// int for interval
const smallestRange = (res, int) => {
    if (res.length === 0) {  return [int[0], int[0]] }
    if (int[0] > res[1]) { res[1] = int[0] }
    if (int[1] < res[0]) { res[0] = int[1] }
    return res;
};
const findSmallestRange = ints => ints.reduce(smallestRange , []);

If we now solve to include intervals that are backward (the other question said use Array.sort. NEVER! use sort for a two item array, in fact you only use sort if you can find no other way to sort any items)
Solve new spec
Solution using while loop and to spec outlined above.
Note that I use lowIdx + 1 & 1 as it is slightly faster than (lowIdx + 1) % 2. This is not a micro optimization, this is a known optimization, when all things equal always use the fastest method. (also note that % has lower precedence than + so requires the ()
Using Math.min and Math.max
"use strict";
// Renamed interval to set
function findCoveringInterval(sets) { // finds smallest
    var i = 0, min = sets[i][0], max = min;
    while (++i  < sets.length) { // must be ++i not i++
        const set = sets[i], lowIdx = set[0] < set[1] ? 0 : 1;
        max = Math.max(set[lowIdx], max);
        min = Math.min(set[lowIdx + 1 & 1], min);
    }
    return [max, min];
}

I prefer using ternary min max because Math.min/max has additional overhead checking against the length of its argument array. However this makes the function longer so it counts as a micro optimization. (I would need to test performances as I add JS complexity competing against native complexity)
"use strict";
function findCoveringInterval(sets) {
    var i = 0, min = sets[i][0], max = min;
    while (++i < sets.length) {
        const set = sets[i];
        let idx = set[0] < set[1] ? 0 : 1;
        max = set[idx] > max ? set[idx++] : (idx++, max);
        min = set[idx &= 1] < min ? set[first] : min;
    }
    return [max, min];
}


Executing certain code from a spreadsheet

Suggestion #1: Use Option Explicit and/or use fewer global variables

Either MaxNumber, MaxPriority are never explicitly defined, which is a very bad idea and is why you should use Option Explicit, or they're Global Variables, which is redundant, because they're self-contained within this subroutine.

Suggestion #2: Don't work directly with worksheet ranges

Accessing a worksheet is slow. You don't notice because doing it once is almost-instant, but do it a thousand times and it starts adding up really fast.

Whenever I'm working with worksheet data, the first thing I do is read all of it into an Array:

Dim wsData As Variant
    wsData = Array()

Dim dataTable As Range
Set dataTable = "" '/ Define your worksheet range

    ReDim arrWsData(1 To Rows, 1 To columns)  '/ Same size as the range

    wsData = dataTable

Now you have a 2-dimensional array, with all your worksheet data laid out in exactly the same way as it was on the sheet. Excel can iterate over an Array orders of magnitude faster than over a range because it doesn't have to access the worksheet object every time.

You can print an array to a sheet by doing the same in reverse: Define your range to be the same size as your array. Range = Array.

Suggestion #3: Recursion

Assuming you put the range A1:F50 from WS1 in an array, you can now iterate over it like so:

Dim i As Long, j As Long, n As Long
Dim testValue As Variant

Dim printData As Variant
    printData = Array()

ReDim printData(1 To lastRow, 1 To 5)

For j = 1 To lastRow
    If wsData(j, 1) <= MaxPriority Then
        n = n + 1
        For i = 1 To 5
            testValue = wsData(j, i + 1)
            If testValue <> "(blank)" Then printData(j, i) = testValue
        Next i
    End If
Next j

you can now change the size of your data, or the progression of the sequence, or a whole host of other things by changing 1 or 2 numbers. And 20 lines of code just became 4.

You can now pick any range on WS3 and print your output data there.

I don't know why your output columns on WS3 Jump a column from 6 to 4, but you can always write specific parts of your array to specific parts of the output sheet if needed.

Suggestion #4: Meaningful Variable Names

What is WS1? What is WS3? I know they're worksheets, but which worksheets? They appear next to each other in multiple places in this subroutine. If you accidentally put a 1 instead of a 3 somewhere, you can't tell at a glance where you've gone wrong. Give your variables names

Even a simple wsInput, wsOutput would be so much better.

MaxNumber Sounds like it should be, well, a number. Except it's a range. variables should say what they are. Even if that means writing VariableThatHoldsThisThing, it'll save you so much time down the road in debugging and maintaining and less technical debt.

Here, I recommend something like dataTable<description> (I don't know the context of your data, so you can think of a much more succinct name yourself).

On the other side, MaxPriority is a good variable name. It holds a number which represents the maximum priority from some table of priority numbers.

Also NestedIfStatement is a terrible procedure name. It tells me nothing about what the procedure does. Procedure names should be of the form <DoThing> or Perfom<Action>On<Thing> or any larger combination thereof. If you can't describe your procedure in a (reasonably) short name, then it's a good sign that it's trying to do too much, and should be split into several smaller procedures.


Don't indent the open line differently to the surrounding lines.

Always check the result of open, or use autodie.

Why do you use the + modes to open the file? Just use plain < and > if you don't need to read and write, respectively.

Don't use bareword filehandles, use variables:

open my $fh, '<', $filename or die $!;

There's no need to use the variable $i, you can just push to the array.

If the input file is very large, your code could run out of memory. You don't need to store all the lines in an array, you can print them to a different file and rename it to the original name at the end.


First of all, your PalindromeChecker does not contain any state, it is a simple input --> output operation not depending on outer factors. This makes it an ideal candidate for being a static method.

Your naming is okay overall, but I would use the name Palindromes for your class.

String str = new Integer(input).toString();

It is better to use String.valueOf here. There's no need to create an Integer object.

for (int j = 999; j>100; j--){

Technically, you're off by one here. You're missing the case when j == 100, which is also a three-digit number (the same goes for i btw).

Correct would be (also with improved spacing)

for (int j = 999; j >= 100; j--) {

So, here's how I would make your class:

public class Palindromes {

    public static boolean isPalindrome(int input) {
        String str = String.valueOf(input);
        int len = str.length();

        for(int i = 0; i < Math.ceil(len/2.0); i++) {
            if (str.charAt(i) != str.charAt(len - i - 1)) {
                return false;
            }
        }
        return true;
    }

}

All your test cases contains pretty much the same code, but with different parameters.

With the change to a static method, the test cases will look more like:

assertFalse("10 failed", Palindromes.isPalindrome(10));

This is ideal for a Parameterized test, which will make it significantly easier to add more tests.

@RunWith(Parameterized.class)
public class PalindromeTest {
    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                 { 10, false },
                 { 100, false },
                 { 909, true },
                 ...
           });
    }

    private final int input;

    private final boolean expectedPalindrome;

    public PalindromeTest(int input, boolean expectedPalindrome) {
        this.input = input;
        this.expectedPalindrome = expectedPalindrome;
    }

    @Test
    public void test() {
        assertEquals("Failed for " + input,
            expectedPalindrome, Palindromes.isPalindrome(input));
    }
}


Headers

Use the standard headers, not #include<bits/stdc++.h>. This is intended solely for gcc's internal use, and gratuitously renders your code completely non-portable.

Oh No! Not using namespace std;!

Please don't use using namespace std; It can, will, and does declare an unknown and almost unbounded set of names, many of which 1) you may not know about (it grows constantly), and 2) many of which are really common names that can collide with all sorts of reasonable code, leading to no end of potential problems.

Use the Library

If you're using a current compiler, you probably have std::gcd defined in <numeric>, so you probably don't need to define your own.

Improved Algorithm

To fit the criteria, each number you try must be a multiple of the given gcd (otherwise that wouldn't be the gcd of the number in question). As such, you can start from the smallest number that's a multiple of the gcd, but greater than your lower bound.

For example, if you're given a gcd of 21 and a lower bound of 30, you can quickly find that your starting point is 42, because that's the next number larger than 30 that's also a multiple of 21.

From there, you have to multiply each candidate by numbers that are coprime with each other--if the multipliers weren't coprime, then the common factors would become part of the gcd, and the gcd of the two would no longer be what you were given. So, for example, given a gcd of 21, you could try 21*2 = 42 with 21*3 = 63. Since 2 and 3 are coprime, that would gcd(42,63) would still be 21 (as required).


The use of that many classes is a sign of incorrect CSS usage, but not because of performance.  I doubt eight or ten classes on an element will be a noticeable performance issue.

I've never heard of an explicit limit on the number of classes assigned to an element, but that may due to a common understanding that it is not correct to create a class for every visual attribute.

An important (and possibly the primary) purpose of CSS is to associate rendering characteristics with conceptual (semantic) markup.  Classes should be named for the concepts they represent, not their appearance.  Like this:

.tableofcontents {
    padding-left: 10px;
    padding-top: 5px;
}

If the goal is to avoid duplication (though I honestly don't think duplicating a few lines of declarations in various blocks is harmful), one can assign multiple conceptual classes to a block:

.menu,
.logo,
.heading,
.tableofcontents {
    padding-top: 5px;
}

.menu,
.tableofcontents {
    padding-left: 10px;
}


Android TCP server that maps data to an object and sends it to a service

When messageLength happens to be too large the code just loops around to the next messageLength = in.readShort();. However, the message body is still there, and readShort will pull the short from it. Chances are, it would be interpreted as a valid message length, and the stream gets irrecoverably out of sync.

You must discard the entire message by reading it.
DataInputStream.read() hey return less bytes than requested. Yet again, the stream gets out of sync. You must read the message body in the loop, until it is consumed entirely.
Closing the server socket every time a data socket fails seems drastic. There is nothing wrong with the server socket, and could be reused. It may need to be reopened only if accept fails.
I recommend to move openSocket call to the exception clause:

    while (True) {
        try {
            messageLength = in.readShort();
            ....
        } catch(Exception e) {
            closeSocket();
            Log.d(APPNAME, e.toString());
            openSocket();
        }

One nesting level down.
You may want to be more precise about exceptions. It is very well possible that the exception has nothing to do with the socket (e.g. may sendMessage throw? was it a keyboard interrupt? ObjectMapper throw? something else? It is impossible to tell from the given code). In such cases different recovery is necessary, but the socket should likely remain intact.


This test case generation method produces cases where the result is sometimes sub-optimal. Thus there is a flaw in the algorithm.

strings = []
sigma = ["a", "b", "c", "d"]
#sigma = ["a", "b"]
sigmax = ["e", " f", "g"]
import random
Nx = 8
N = 16
M = 5 # Number of strings
x = ""
for i in range(Nx):
    x += random.choice(sigmax)
for i in range(M):
    string = ""
    for j in range(N):
        string += random.choice(sigma)
    indexes = list(range(N))
    random.shuffle(indexes)
    indexes = sorted(indexes[:len(x)])
    for j in range(len(x)):
        string = string[:indexes[j]]+x[j]+string[indexes[j]:]
    strings += [string]

So, back to the drawing board, so to speak.


Arithmetics in Bash

You're doing some math in Bash, some in Awk, some in a combination of both. You can do all of that in Bash alone. Most notably, instead of this:

echo $(($(date +%s) - START)) | awk '{print int($1/60)":"int($1%60)}'

This would be equivalent, but all in Bash, without additional processes:

((delta = $(date +%s) - START))
((minutes = delta / 60))
((seconds = delta % 60))
echo $minutes:$seconds

Don't use seq

seq is not portable, I suggest to avoid it. Instead of this:

 for i in `seq 1 $max`; do ...; done

You can write:

for ((i = 1; i < max; i++)); do ...; done

Don't use `...`

This syntax is obsolete today, always use $(...) instead.

Other minor things

This would be clearer as two echo lines, or a here-document with cat <<EOF:

echo "url: $2
rate: $max calls / second"

The trailing semicolon is unnecessary:

START=$(date +%s);

The quoting is unnecessary in date +'%r', but it does no harm.


Checking number of words in a string and assigning them to a value

The code is pretty clean, if you started coding very recently, you can be quite happy with it.

But please note that some of your variables names start with an uppercase letter, as a reminder java use SCREAMING_SNAKE_CASE for static final variables, CamelCase for class name (or object type if you prefer), and camelCase (aka lowerCamelCase) for local variables, fields and method name.

Also if the user input only one word then your code fails (which is not necessarily bad nor wrong)... silently (which is bad).

You should print a warning message in such case.

Step by step review

public class CreateUserName {

CreateUserName sounds like a complete sentence which you should avoid for a class name. Consider renaming your class to UserNameCreator, UserNameParser, etc...

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

That's quite complicated just to read something from the console consider using Scanner for such a simple use case

char[] arr = Username.toCharArray();
int i = 0;
boolean notCounted = true;
int counter = 0;
while (i < arr.length)
{
    if (arr[i] != ' ')
    {
        if (notCounted)
        {
            notCounted = false;
            counter++;
        }
    }
    else
    {
        notCounted = true;
    }
    i++;
}

First and foremost, you should put that into its own function.
Secondly, good job in considering the case where multiple space are following one another :) sadly, if you indeed have multiple space it'll fail later in your code :( maybe you shouldn't only consider space but also tab ? (char for tab is '\t')

Thirdly, you didn't have to use an array, there is the method charAt inside String.

String FirstName = "";
String firstLetterSurname = "";
String Surname = "";
String WindowsUsername = "";
String EmailID = "";

Copying this part just to remind you to use camelCase ;)

if(counter == 2)
{
    //...

Use if / else if and consider adding a else to print a warning message if the input of the user is invalid. Never trust user inputs ;)

As said earlier, if the user input multiple space in a rows, this part may fail as you'll use charAt(0) on the empty string.

Also, firstLetterSurname is never written to if counter is 3 which is likely a bug.

Lastly, you shouldn't split the variable twice. Use split once and store the result in a temporary variable like this :

String[] splitted = userName.split(" ");
FirstName = splitted[0];
Surname = splitted[1];

Special note

Remember that people's names aren't as easy to manipulate as they seem : some people have space in their first name, others have multiple "middle name" (in France for example, we can have as many surname as wanted, though we use only one).

Also some family name may not be case sensitive (Victor D'Hondt is sometime written Victor d'Hondt or even Victor D'hondt). Something to consider if you ever want to add name comparison.


Kohana newbie: setting a layout view and variables for layout in before()

Your code is violating the "Don't Repeat Yourself" (DRY) Principle, which is why it seems like you have "too many" $this->* lines. As the name implies, your code should not repeat. Usually, in an instance such as this, I would say to use the constructor and inject those values you need; However, I don't know for sure if the class you provided is also a factory, in which case you would use a wrapper method.

//non-factory method
public function __construct( $view, $text ) {
    $this->view->content = View::factory( $view );
    $this->view->content->text = $text;
    $this->response->body( $this->view );
}

//no other methods need, simply inject while instantiating

//factory method
public function render( $view, $text ) {
    $this->view->content = View::factory( $view );
    $this->view->content->text = $text;
    $this->response->body( $this->view );
}

public function action_index() {
    $this->render( 'index', 'some index text' );
}


You can modify the recursive code to use an explicit stack:

#include <stack>

void display_widgets(control& controls)
{
    std::stack<widget*> widgets;
    for(auto &widget : controls.getWidgets()) {
        widgets.push(widget);
    }

    while(!widgets.empty()) {
        widget* w = widgets.top();
        widgets.pop();
        if(!widget->visible) {
            continue;
        }
        widget->draw();
        for(auto& component : widget->components) {
            widgets.push(component);
        }
    }
}

  I know iteration is better.

This is highly dependent on language and usage. It is "better" in that recursion can use O(n) stack space (although not always - tail call optimization gets rid of this limitation), and won't blow your stack. However, in this case, assuming the recursive algorithm actually did what you wanted, it would be better and easier.

You can always turn a recursive solution into an iterative one by replacing the call stack with an actual stack of your own, as above. For very deeply nested recursive calls, this may save you from stack overflows, however, it is more fiddly to code, and in this case, doesn't gain you anything.

Having written the code above, my advice would be to stick with the recursive solution.


Object comparison method as an example of using the functional style

Functional and OO mix

This is kind of a mix of functional and OO programming because the class is carring a state. In a pure functional way you would provide the method with all it needs this means it would require the generic <T> parameter and it would be an extension:

public static IEnumerable<DifferenceBag> CompareTo<T>(this T source, T target)
{
    // perform the T reflection etc
}

or with pre-reflection you could have another function that takes a collection of properties that you want to compare:

public static IEnumerable<DifferenceBag> CompareTo<T>(this T source, T target, IEnumerable<PropertyInfo> properties)
{
    // perform the T reflection outside
}

this means you could later jus say:

var differences = foo.CompareTo(bar);

or

var comparableProperties = typeof(T).GetComparableProperties();
var differences = foo.CompareTo(bar, comparableProperties);

or even

var differences = foo.CompareTo(bar, GetComparableProperties);

if you designed the CompareTo method in such a way that it can take a Func for the reflection part:

public static IEnumerable<DifferenceBag> CompareTo<T>(this T source, T target, Func<T, IEnumerable<PropertyInfo>> getProperties)
{
    // perform the T reflection outside
}

where

static IEnumerable<PropertyInfo> GetComparableProperties<T>() {}

Implementation

You could improve the current implementatio to be more functional by using more LINQ. The Compare method could work like this

var differences =
    from p in _properties
    let pair = (left: p.GetValue(source), right: p.GetValue(target))
    where !pair.left.Equals(pair.right)
    select new DifferenceBag(p.Name, pair.left, pair.right, p);

if (_properties.Count == 0)
  return EmptyBag;

These lines are unnecessary because if there are not properties the resulting collection will be empty anwyway.

The extreme C# 7 solution could be implemented like this

public delegate IEnumerable<PropertyInfo> GetPropertiesCallback<T>();

public static IEnumerable<DifferenceBag> CompareTo<T>(
    this T source,
    T target,
    GetPropertiesCallback<T> getProperties)
    where T : class // required if you want to use "?? throw"
{
    var differences =
        from p in getProperties()
        let pair = (
            left: p.GetValue(source ?? throw new ArgumentNullException(nameof(source))),
            right: p.GetValue(target ?? throw new ArgumentNullException(nameof(source)))
        )
        where !pair.left.Equals(pair.right)
        select new DifferenceBag(p.Name, pair.left, pair.right, p);

    return differences;
}

Possible bug

var immutable = propertySet[i].GetCustomAttribute<ImmutableAttribute>();

if (immutable != null && immutable.IsTargetMutable)
{
    builder.Add(propertySet[i]);
}

var ignore = propertySet[i].GetCustomAttribute<IgnoreCompareAttribute>();

if (ignore != null && !ignore.SkipProperty)
{
    builder.Add(propertySet[i]);
}

If a property is decorated with both attributes you'll end up having it twice in the final list.


Finding the relationship between two values

public class Method1 {

Since this will be the name of the file too, (if you save it) I would recommend naming it something descriptive so that you don't have to open it in order to know what it hides.

public static float a, b, t;
public static Scanner scanner;

Try and declare as close to the use of the variables as possible. There is also no need for these to be globals, since they are only used in one place.

Next, read the question very carefully. It states that A and B are both integers, so a float is the wrong type to use. It may also give rounding errors, and comparing floats is trickier because of how floating point numbers are stored. 0.1 + 0.1 does not always equal 0.2, it may give 0.200000001, so this can lead to a bug.

Lastly, t is also going to be an integer. You can tell this is the case because it is a count of how many test cases there are, 2.3 testcases doesn't make sense.

HINT TOWARDS AN ERROR

System.out.println("Type your first Value please.");

Why is this here? Does the question ask for it in the output?

Now onto the code overview. Strictly speaking, your code doesn't work at all. You never actually took in all the input. If its input looks like

3
10 20
20 10
10 10

You scan 3, and 10. That is it. All the rest of the input is ignored. There is a reason it tells you how many test cases there will be, its important to use that information.

if (a == b) {
    System.out.println('=');
}
if (a > b){
    System.out.println('>');
}
if (a < b){
    System.out.println("<");
}

This is the perfect time for if/else statements.

One good piece of logic here is if they aren't equal, and a isn't bigger than b, we know the answer to a < b without needing to check.

There are more things to mention, like moving the check if two numbers are equal to a method, and making use of the library of methods available, but get it working first, then post a follow up. Best of luck


Copy two properties from one array item to matching index in another array

if (arrItems.Length != newItems.Count())
        // --> BAD throw new Exception("Item counts do not match.");
        // Do not throw the Exception base here look for the real exception for example ArgumentException(if the arr come from arguments) or your custom exception:
        throw new ArgumentException();

      //Copy Did and KeyDid from old items to newItems
      for (var index = 0; index < newItems.Length; index++)
      {
        arrItems[index].Did = newItems[index].Did;
        arrItems[index].KeyDid = newItems[index].KeyDid;
      }

I do not think LINQ will give you a better solution than what you have above; you can use group by or select to create a new element in the linq query and than put it back to object! "For" in this case is very fast and it solve the problem.


Note: I do not advocate this to be used, it is definitely wrong, untested, horrible and confusing.

But it should give you a start in using the associative array method that Alexander Kludt noted in his comment.

<?php
class Smth
{
    protected $marks = array(
        'Undefined' => 0, 'ECTS-F' => 0.31, 'ECTS-FX' => 0.60, 'ECTS-E' => 0.65,
        'ECTS-D' 0.71, 'ECTS-C' => 0.85, 'ECTS-B' => 0.95, 'ECTS-A'
    );

    public function getEctsMark($rate, $current, $examRate)
    {
        $color = reset($this->marks);
        $percent = $rate / $current;

        if($current > 0 && $examRate < 22) {
            return "ECTS-FX";
        }

        /**
         * This is where the explanation is required. This *should* *maybe*
         * compare the percent to the current start band and the next band. So
         * say for example the percent is 0.78(78%) this would foreach through
         * the  marks array and eventually return true on >= $percentStart(0.71)
         * and <= the next band start up which is 0.85.
         */
        $i = 0;
        foreach($this->marks as $key => $percentStart) {
            if($percent >= $percentStart && $percentStart <= $this->marks[$i+1]) {
                $color = $key;
                break;
            }
            $i++;
        }

        return $color;
    }
}

If you are wanting feedback on your original code, I made a few changes which might satisfy your criteria of simplification over at this 3v4l.


Implementation of insertion sort in Ruby, code correctness

Your block usage yield arr, compare, curr is rather weird:

custom_insertion_sort(array){ |_, i, j| _[i].abs > j.abs }

I would do yield arr[compare], curr:

naki_insert_sort(array){ |i, j| i.abs > j.abs }

You may use ...n syntax instead of ..n-1
You are sorting inplace, operating with an array like with a memory pointer, so you don't have to return arr from the function.
Instead of writing comparision code twice you can either define lambda or put it just inside while condition.

And after a bit more golf I've got this:

def naki_insert_sort arr
    for i in (1...arr.length)
        curr = arr[compare = i]
        while 0 <= (compare -= 1) && ( block_given? ?
            yield(arr[compare], curr) :
            arr[compare] < curr
        )
            arr[compare + 1] = arr[compare]
        end
        arr[compare + 1] = curr
    end
end

But looks like Insertion sort and Ruby don't actually suit each other, because using indexes isn't functional.


Your questions

Functions can be function arguments, too.
You can add a parameter for that.
See additional comments. I think it's fine that you use a class.
That is usually not in the range of codereview. That should be asked in StackOverflow (but I think I know what you want - just look at the code).

Additional comments

Add a shebang. If you do, you can directly execute the script. See What does #!/usr/bin/python mean?
Read PEP8 or at least use pep8online.com to make your coding style standard conform and hence easier to read. It's mostly about setting whitespaces correct.
Use docstrings and eventually doctest. That makes your code again easier to read and you can easily verify if it works as you expect.
If you don't use a variable, you should remove it at all. If that is not possible (e.g. in the case of unzipping values) you should name the variable _.

The code

#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    """An (arbitrary) quadratic mathematical function.
       It has fixpoints 0 and 0.5.

    >>> f(0)
    0
    >>> f(0.5)
    0.5
    """
    return 2*x*(1-x)

def g(x):
    """An (arbitrary) quadratic mathematical function.
       It has fixpoints 0 and (+/-) 1/sqrt(2)

    >>> g(0)
    0
    >>> "%0.4f" % g(-0.7071)
    '-0.7071'
    """
    return 2*x*(1-x)*(1+x)

class fixpt(object):
    """Find fixed points of a given function f."""
    def __init__(self, x, f, xmin=0, xmax=1, epsilon=1.0E-100):
        """Constructor
        @param x float - where to start search
        @param f function - function that should get evaluated
        @param xmin float - Interval that gets examined
        @param xmax float - Interval that gets examined
        @param epsilon float - comparison when floats are considered to be
                               the same
        """
        self.x = x
        self.f = f
        self.xmin = xmin
        self.xmax = xmax
        self.epsilon = epsilon

    def search(self, N=1000, store=False):
        """Search fixed points.
        @param N int - number of iterations
        @param store - bool - if set, return ????
        @return I did not understand that. It seems to depend on 'store'

        >>> fixpointiter = fixpt(0, f)
        >>> fixpointiter.search()
        (0, 0, 0)
        """
        # Set initial values
        x = self.x
        y = self.f(x)
        n = 0
        if store:
            values = [(x, y)]  # Why?
        while abs(y-x) >= self.epsilon and n < N:
            x = f(x)
            n += 1
            y = f(x)
            if store:
                values.append((x, y))
        if store:
            return y, values
        else:
            if n >= N or x == -float('inf') or x == float('inf'):
                # No fixed point for given initial condition
                return None
            else:
                return x, n, y

    def plot(self):
        """Draw a cobweb plot."""
        _, points = self.search(store=True)
        xaxis = np.linspace(self.xmin, self.xmax, 1000)
        plt.plot(xaxis, f(xaxis), 'b')
        plt.plot(xaxis, xaxis, 'r')

        for x, y in points:
            plt.plot([x, x], [x, y], 'g')
            plt.plot([x, y], [y, y], 'g')

        plt.show()

    def scan(self):
        """Scan for all fix points in xmin / xmax."""
        x_range = np.linspace(self.xmin, self.xmax, 1000)
        fixpoints = []
        for x in x_range:
            self.x = x
            ret = self.search()
            if ret is not None:
                fixpoints.append(ret[0])
        # Get rid of duplicates
        fixpoints = sorted(fixpoints)
        final = []
        for x in fixpoints:
            # It's not the same as the last fixpoint
            if len(final) == 0 or abs(final[-1]-x) >= self.epsilon:
                final.append(x)
        return final

if __name__ == '__main__':
    # Automatic doctest
    import doctest
    doctest.testmod()
    # Usage example
    fixpointiter = fixpt(0, g, -2, 2)
    print(fixpointiter.search())
    print(fixpointiter.search(store=True))
    print(fixpointiter.scan())


Do not use string formatting to pass parameters to SQL queries.

This way you are not only getting type conversion and quotes balancing/escaping issues, but also making your code vulnerable to SQL injections. Mandatory XKCD:

(source)

Instead, parameterize your query - put placeholders into the query and let your database driver worry about the Python to database type conversions.

In this case, you should be able to pass your data list of dictionaries directly to executemany() specifying dictionary-based query placeholders:

import psycopg2
from psycopg2.extras import Json

def insert_into_table(data):
    # preparing geometry json data for insertion
    for item in data:
        item['geom'] = Json(item['geometry'])

    with psycopg2.connect(database='testdb', user='postgres', password='password', host='localhost') as conn:
        with conn.cursor() as cursor:
            query = """
                INSERT into
                    data_load
                    (iso_code, l_postcode, r_postcode, link_id, geom)
                VALUES
                    (%(iso_code)s, %(l_postcode)s, %(r_postcode)s, %(link_id)s, st_geomfromgeojson(%(geom)s));
            """
            cursor.executemany(query, data)

        conn.commit()

Also note how I'm using cursor and conn as context managers.


You could use some linq to do this fairly easily. Converting the array to a HashSet will allow Contains to operate faster

public List<IDenomination> GetInventory(int[] denominations)
{
    var denoms = new HashSet<int>(denominations);
    return Account.Where( a => denoms.Contains(a.Currency) ).ToList();
}

This assumes that Account : IDenomination though, as does your original code. If that were not the case, you would use a .Select() prior to .ToList() in order to select the IDenomination from Account.


Before we get into deep performance concerns, let's do a quality pass:

Global code

Lines like

x=plt.imread("s2.png")    #the file name
#x=color.rgba2rgb(x)
y=x
n=int(input())     #"n" is the level of blurring(typical values=5,10,20,50)
le=y.shape[0]
bd=y.shape[1]

should be in a function and not in global scope.

Mystery input

Pass a prompt to input, such as Please enter the level of blurring.

Extraneous parens

This:

y2=np.ones(shape=(le+(2*n),bd+(2*n)))
for i in range(0,le):
    for j in range(0,bd):
        y2[(i+n),(j+n)]=y[i,j]
return(y2)

can be

y2 = np.ones(shape=(le + 2*n, bd + 2*n))
for i in range(le):
    for j in range(bd):
        y2[i + n, j + n] = y[i, j]
return y2

Also note the default value for the start of range.

In-place division

This:

k=k/(np.sum(k))
return(k)

can be

k /= np.sum(k)
return k

Empty, not zero

Your blur method should definitely be vectorized, which I'll get to later, but for now, since it's clear that you're overwriting every entry: use empty rather than zeros.

Add another dimension

This:

r=blur(y[:,:,0],kernel(p),frame(y[:,:,0]))
g=blur(y[:,:,1],kernel(p),frame(y[:,:,1]))
b=blur(y[:,:,2],kernel(p),frame(y[:,:,2]))

should not be three separate calls. Your data should have a dimension (y already does) of length 3, and y should be passed in its entirety.

Variable names

le, bd and p mean nothing to me, and in three months they might not mean anything to you, either. Write these out with longer, more meaningful names. I promise that it will not slow the program down.


Hackerrank "Queues: A Tale of Two Stacks" Javascript Solution

You've pretty much nailed it.
You don't really need the len variable here though,
you could use a condition on inQueue.length directly.

len = inQueue.length;
while (len-- > 0) {
    outQueue.push(inQueue.pop())
}

The other thing I notice is the inconsistent use of semicolons.
Sometimes you add at the end of statements,
sometimes not.
You could choose whichever way, but do it consistently.

Lastly, the empty default statement of the switch is unnecessary, you can drop it.


I think you don't need to check for errors twice, and that will make your code cleaner.

bool MyClass::IsCorrectPath (const DWORD dwPid, const std::string &strPath) const
{
    DWORD dwError = 0 ;
    NormalHandle hModSnap ; // RAII wrapper for HANDLE
    ::SetLastError (0) ;

    do {
        // repeat while the expected error occurs
        hModSnap = ::CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, dwPid) ;
        dwError == ::GetLastError () ;
    } while ((hModSnap == INVALID_HANDLE_VALUE) && (dwError == ERROR_BAD_LENGTH)) ;

    if (dwError == ERROR_PARTIAL_COPY) {
         // This occurs when trying to read a 64 bit process from a 32 bit process.
         return false ;
    }

    if (hModSnap == INVALID_HANDLE_VALUE) {
        ThrowFunctionFailure ("MyClass::IsCorrectPath ()",
            "::CreateToolhelp32Snapshot ()", ::GetLastError ()) ;
    }

    MODULEENTRY32 me ;
    me.dwSize = sizeof (me) ;
    if (::Module32First (hModSnap.Get (), &me) == FALSE) {
        ThrowFunctionFailure ("MyClass::IsCorrectPath ()", "::Module32First ()", ::GetLastError ()) ;
    }

    return (::_stricmp (strPath.data (), me.szExePath) == 0) ;
}

So, instead of checking for all errors in every step of the loop, only check for the expected error.

Once you're out of the loop, it means you received a different error or you have a valid handle. Check if success and continue.

Does that make sense to you?

edit: Changed dwError == ERROR_SUCCESS to dModSnap == INVALID_HANDLE_VALUE.


Balanced smileys check algorithm (part 3)

Correctness

I suggest you add a test case for :)(.  It should be False, but is not.

Testability

Consider adding assert tests for ease of testing and evaluation.  Perhaps something like

def verify(test_input, expected_result):
    actual_result = check_balance(test_input)
    assert actual_result == expected_result, "{} expected {} failed".format(test_input, expected_result)
    print(test_input, actual_result)

if __name__ == "__main__":
    verify(':)(', False)
    verify(':()', True)
    verify('abc(b:)cdef(:()', True)
    verify('a)', False)
    verify(')(' , False)

Besides, if provided, it is easier to refactor and propose alternatives when providing feedback. :)

Clarity

A key part of the challenge is that smiles and frowns are optionally allowed to balance parens.  This is an important not immediately obvious point that is worth documenting in the code.

Though somewhat minor for this simple example, I prefer not to repeatedly test for pre == ':' since ":" is the only character you care about.  Instead I would opt for something like eyes_flag which can be set at the end of loop as eyes_flag = c == ':'.

Though the criteria may change after fixing the implementation, expressions like this

if left > right + smile:
    return False
return True

can be simplified to

return left <= right + smile

Naming

This is a matter of opinion, but for me smiley and frown require too much effort to map to open and close parens.  I prefer calling them optional open parens (opt_open) and optional close parens (opt_close).


Simple function to verify if a number is integer

In ES6, the next version of Javascript, there will be a function exactly for this purpose called Number.isInteger(). Currently, MDN offers the following polyfill which I assume therefore does the best Javascript can to determine whether something is an integer. There are edge cases of course, but for most everyday use it will do the trick:

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === "number" &&
           isFinite(value) &&
           Math.floor(value) === value;
};

I think this is the best we will do in the meanwhile, as passing string to a number function is an effective way of doing it, but calling toString on a number makes it go through conversion as well, resulting in potential issues.

There are already a couple of browsers that support it like Chrome and Firefox, but the big one (Safari) doesn't yet and neither does IE/Edge, so the polyfill will have to do. For more info, see MDN's writeup, it's quite insightful:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger#Browser_compatibility

Note: Polyfills like this are useful, but there are some concerns about amending these core features of JS. As I say in the comments, as long as you implement something that doesn't exist or replace anything, I think it's alright. Use in moderation.

You can always wrap it in it's own function and call it as a global function if you prefer not to use this polyfill.


Find the max number in list after m operations between indices a and b

For the record, don't ask us to write code for you. Writing the code is your responsibility; we will just critique it.

Why are you concerned about how long it takes to process each operation? The only thing that matters is the overall time and space requirement, and it's not a given that the best solution is going to operate by processing each operation in sequence. Thus, the timing does not belong in the loop. And I would even make the case that the timing does not belong in the run_testsn() functions. The timing belongs in your main function, which will call each of the run_testsn() in sequence. Each function should have one purpose only. It shouldn't be "Do this in this particular way and then time subunits of it.".
You've got a lot of unnecessary #includes. That just clutters up the code. Only use the ones you need.
Kudos to you for qualifying your C++ types with std::. But as @Morwenn said, don't forget to do it for functions from the C standard library too.
Is it necessary to take your input as a vector of vectors? It would make a lot more sense to build a struct with members int a; int b; int k; and then pass vectors of that around.
A map is pretty good for representing a sparse array; there are several other libraries out there that do better. See https://stackoverflow.com/questions/4306/what-is-the-best-way-to-create-a-sparse-array-in-c and https://stackoverflow.com/questions/21310680/sparse-array-in-c
You have two (soon-to-be three) functions that take the same parameter list and do the same thing. This looks like a job for an abstract base class (specifying the interface/params) and three subclasses of that class that each have implementations.
In run_tests2 you have

       std::pair<std::map<int, int>::iterator, bool> status =
         LIST.insert(std::make_pair(i, 0));

       status.first->second += k;

What's wrong with LIST[i] += k;? If the item doesn't exist yet, it will be auto-created with the default value (0). (And even if not, please declare it using auto status = as that type is just plain ugly and doesn't add anything. You're using C++11, take advantage of ways it can produce better code)


1. Bugs

Supposing that I want to specify an interval of time spanning midnight, for example starting at 23:00 on Monday and ending at 01:00 on Tuesday, how do I do it? The best I can do seems to be:

2300-2359 (mon); 0000-0100 (tue)

but this leaves the minute between 23:59 and midnight on Monday uncovered! One way to fix this would be to allow the input "2400" to represent the midnight at the end of the day.
datetime.now() is called several times during the validation. This could lead to an incorrect result if the code is called at the wrong moment. For example, suppose that my specification is:

1200-1300 (mon); 1100-1200 (mon)

and the function is called just before 12:00 on Monday. When the first window is checked, datetime.now() returns 11:59:59.999, and so the window does not match. But when the second window is checked, datetime.now() returns 12:00:00.001 and so the second window does not match either! But these two windows ought to cover the whole interval from 11:00 to 13:00 on Monday.

If you were to fix the midnight problem in §1.1 above, then there would be a similar race condition in the day handling logic.

So it is necessary to call datetime.now() exactly once and remember the result. Or better still, change the function so that it takes the time to be tested as a parameter.
If the day specification consists of a single day then the code tests for a matching day like this:

datetime.now().strftime('%a').lower() == day[0]

However, strftime is affected by the current locale:

>>> import datetime, locale
>>> locale.setlocale(locale.LC_TIME, 'fr_FR')
>>> datetime.datetime.now().strftime('%a')
'Sam'

so this will go wrong if the locale is not English. It would be more reliable to use:

now.weekday() == days.index(day)

2. Review

The Python style guide (PEP8) recommends four spaces per indentation level, and a maximum of 79 characters per line. You're not obliged to follow this guide, but it'll make it easier to collaborate with other Python programmers if you do. (For example, we wouldn't have to scroll the code horizontally to read it here at Code Review.)
In the pp.delimitedList call, the keyword argument delim defaults to ',' so this can be omitted in the definition of dayspec.
The ParserElement class has an abbreviated syntax for the setResultsName method:

  You can also set results names using the abbreviated syntax, expr("name") in place of expr.setResultsName("name")

Using this would help make the grammar more readable.
The correspondence between grammatical elements and names is inexact. It seems to me that it would make more sense for the hour element to be named 'hour', like this:

hour = pp.Regex('[01]\d|2[0-3]')('hour')
minute = pp.Regex('[0-5]\d')('minute')
time = hour + minute

Assigning a few more grammar elements would make things clearer and help to keep the code within 79 columns, for example:

windows = pp.delimitedList(pp.Group(window), delim=';')
spec = pp.StringStart() + windows + pp.StringEnd()