You can definitely optimize this query. If list has M items and excelViolations has N items, the query will iterate excelViolations M*5N times.

It is possible to reduce this to M*N iterations by consuming excelViolations only once per item in list. You can do this with a subquery on excelViolations that checks all five conditions for each excelVio, then ORs each of the five conditions across all excelVio instances.

If that is not clear, hopefully this walkthrough is:

from vio in list

// Perform all five checks for each excelVio

let checks = excelViolations
    .Select(excelVio => new
    {
        HasVioID = vio.VioID.Formatted.Equals(excelVio.VioID.ToString()),
        HasRuleType = vio.RuleType.Formatted.Equals(excelVio.RuleType),
        HasVioType = vio.VioType.Formatted.Equals(excelVio.VioType),
        HasXCoordinate = vio.EtchVects.Any(x => x.XCoordinate.Equals(excelVio.XCoordinate)),
        HasYCoordinate = vio.EtchVects.Any(y => y.YCoordinate.Equals(excelVio.YCoordinate))
    })

// From left to right, OR each of the five results (equivalent to .Any)

    .Aggregate((left, right) => new
    {
        HasVioID = (left.HasVioID || right.HasVioID),
        HasRuleType = (left.HasRuleType || right.HasRuleType),
        HasVioType = (left.HasVioType || right.HasVioType),
        HasXCoordinate = (left.HasXCoordinate || right.HasXCoordinate),
        HasYCoordinate = (left.HasYCoordinate || right.HasYCoordinate)
    })

// Filter to only those that pass every check

where checks.HasVioID
    && checks.HasRuleType
    && checks.HasVioType
    && checks.HasXCoordinate
    && checks.HasYCoordinate

// Same projection

select new EtchVectorShapes
{
    VioID = Convert.ToInt32(vio.EtchVects.Select(x => x.VioID)),
    ObjectType = vio.EtchVects.Select(x => x.ObjectType).ToString(),
    XCoordinate = Convert.ToDouble(vio.EtchVects.Select(x => x.XCoordinate)),
    YCoordinate = Convert.ToDouble(vio.EtchVects.Select(x => x.YCoordinate)),
    Layer = vio.EtchVects.Select(x => x.Layer).ToString()
};


Game where you guess whether an article is from theOnion or notTheOnion

Avoid repetitive code

Dair has covered this already above. Basically, whenever code looks like it's been copy-pasted, it needs to be rewritten.

Another case of unnecessary repetition is the lines:

    post_title.innerHTML = rand_post.content;
    score_display.innerHTML = score;

You use these to display the first post and the starting score. These two lines are also present in your onclick methods. This means if you or someone else needed to change how these elements are displayed, for example, they would have to repeat making the same changes to your code but in multiple places. Well-written code never forces anyone to do this. Essentially, each task accomplished by your code should be written down once, and only once!

Use your data when you have it

Your generateNewPost function accesses json_data using a random number as the index:

var rand_post = json_data[rand_num];

But after calling generateNewPost, you search json_data  again for the index that 'generateNewPost' has already used:

var index = json_data.indexOf(rand_post);

As a result, your code does an unnecessary search of json_data every time the user clicks an answer. To save doing this search, generateNewPost should return the index as part (or all) of its output:

function generateNewPost(json_data) {
    var rand_num = generateRandNum(0, json_data.length);
    var rand_post = json_data[rand_num];
    return [rand_post, rand_num];
}

Which would be accessed like this:

var new_post = generateNewPost(json_data)
var rand_post = new_post[0]
var index = new_post[1]

This is not necessary here as shown below. But it might be helpful to remember it when creating more complex functions.

Keep things abstract until you need them

The two actions you want for json_data, that is, reading a random entry, and deleting an entry, both need only an index. So it makes sense to keep an integer index as your rand_post, rather than passing around the post content as a string. Further, as generating random numbers and accessing entries in a JSON object are fairly standard methods, they do not need to be wrapped in a function.

tl;dr

Your code can be simplified by:

Using a single function to initialize the display and handle both onclick events.
Trusting future readers of you code to understand a one-line version of your generateNewPost function, which is fairly standard.

As below:

var post_title = document.getElementById("post-title");
var onion_button = document.getElementById("onion-chosen");
var not_onion_button = document.getElementById("not-onion-chosen");
var score_display = document.getElementById("score");

var req = new XMLHttpRequest();
var json_url = "https://api.myjson.com/bins/s474n";
var score = 0;
var index = -1;
var options = ["nottheonion", "theonion"]

req.open('GET', json_url);
body.onload = function() {
    var json_data = JSON.parse(req.responseText);
    onion_button.onclick = update(1);
    not_onion_button.onclick = update(0);
    update(null);
}

update = function(user_entry) {
    if (user_entry != null) {
        if (options[user_entry] == json_data[index].sub) {
            score++;
        } else {
            score--;
        }
        json_data.splice(index, 1);
    }
    index = parseInt((Math.random() * (json_data.length - 1), 10)
    post_title.innerHTML = json_data[index].content;
    score_display.innerHTML = score;
}

Note:
It can also help anyone who needs to modify or work with your code to include a comment block showing the expected format of any objects passed from elsewhere, eg. from your url api.myjson.com. It might look like this:

/*
[
  { content: #string#, sub: "notheonion" / "theonion" }, ...
]
*/


Check if a directed graph contains a cycle

1. Review

There's no docstring. What does the function do? What arguments should I pass? What does it return?
This is the kind of function that would make an ideal candidate for a doctest or two.
The function does not actually determine if a graph contains a cycle. It determines if the graph contains a cycle starting at a given vertex. To detect a cycle, it would be necessary to call the function for each vertex in the graph.
The function uses a global variable for state. This makes it impossible to use the function in a multi-threaded program. It also makes it difficult to debug, because whenever anything goes wrong, you have to reset cur_path to the empty set before you can re-run the function. It would be better if all state were encapsulated inside the function.
else: if ...: can be abbreviated to elif ...:.
In British English the word is spelled "neighbour", and in American English it's spelled "neighbor".
It's better to use the empty tuple () as the default value if vertex is not found in g, instead of the empty list []. That's because the empty tuple is a singleton: each time () is evaluated you get the same object. But each time you evaluate [] a new empty list has to be allocated.
Testing neighbour in g is unnecessary since you already handle the case where vertex is not in g.

2. Revised code

Applying all the comments above:

def cyclic(g):
    """Return True if the directed graph g has a cycle.
    g must be represented as a dictionary mapping vertices to
    iterables of neighbouring vertices. For example:

    >>> cyclic({1: (2,), 2: (3,), 3: (1,)})
    True
    >>> cyclic({1: (2,), 2: (3,), 3: (4,)})
    False

    """
    path = set()

    def visit(vertex):
        path.add(vertex)
        for neighbour in g.get(vertex, ()):
            if neighbour in path or visit(neighbour):
                return True
        path.remove(vertex)
        return False

    return any(visit(v) for v in g)

3. Analysis

The function follows all simple paths in the graph, stopping when it encounters a cycle. Unfortunately, a graph may have exponentially many simple paths without containing any cycles, so the runtime is exponential in the size of the input.

For example, this function constructs a graph with exponentially many simple paths:

def test_graph(n):
    """Return an acyclic graph containing 2**n simple paths."""
    g = dict()
    for i in range(n):
        g[3 * i] = (3 * i + 1, 3 * i + 2)
        g[3 * i + 1] = g[3 * i + 2] = (3 * (i + 1),)
    return g

The graphs it constructs look like this:

Experimentally we can check that the runtime is exponential:

>>> for i in range(10, 20):
...     print(i, timeit(lambda:cyclic(test_graph(i)), number=1))
...
10 0.017517157015390694
11 0.03172751097008586
12 0.06926556502003223
13 0.1300737849669531
14 0.25352559401653707
15 0.5073735360056162
16 0.9933696809457615
17 2.004867063020356
18 3.9877060829894617
19 7.927054518950172

You can see that each increment of i doubles the runtime.

4. An efficient algorithm

To make the algorithm efficient, we must make sure not to visit any vertex more than once, which we can do by keeping a separate set of vertices that have been visited so far. For example:

def cyclic(g):
    """Return True if the directed graph g has a cycle.
    g must be represented as a dictionary mapping vertices to
    iterables of neighbouring vertices. For example:

    >>> cyclic({1: (2,), 2: (3,), 3: (1,)})
    True
    >>> cyclic({1: (2,), 2: (3,), 3: (4,)})
    False

    """
    path = set()
    visited = set()

    def visit(vertex):
        if vertex in visited:
            return False
        visited.add(vertex)
        path.add(vertex)
        for neighbour in g.get(vertex, ()):
            if neighbour in path or visit(neighbour):
                return True
        path.remove(vertex)
        return False

    return any(visit(v) for v in g)

This visits each vertex at most once, and considers each edge at most once, so its runtime is \$ O(V + E) \$.

Experimentally we can check that the runtime is roughly linear in the size of the graph:

>>> for i in range(10, 20):
...     print(i, timeit(lambda:cyclic(test_graph(i)), number=1))
...
10 0.00017403007950633764
11 0.00014279899187386036
12 0.00015402096323668957
13 0.00016507902182638645
14 0.00017680192831903696
15 0.00019660103134810925
16 0.00020132900681346655
17 0.0002140760188922286
18 0.00022624700795859098
19 0.00023716699797660112

5. Avoiding the recursion limit

The implementation uses recursion to search the graph. This means that it uses as many stack frames as there are nodes in the longest path it visits in the graph. But Python has a limited number of stack frames (see sys.getrecursionlimit). To get round this limit, we can use the stack of iterators pattern, like this:

def cyclic(graph):
    """Return True if the directed graph has a cycle.
    The graph must be represented as a dictionary mapping vertices to
    iterables of neighbouring vertices. For example:

    >>> cyclic({1: (2,), 2: (3,), 3: (1,)})
    True
    >>> cyclic({1: (2,), 2: (3,), 3: (4,)})
    False

    """
    visited = set()
    path = [object()]
    path_set = set(path)
    stack = [iter(graph)]
    while stack:
        for v in stack[-1]:
            if v in path_set:
                return True
            elif v not in visited:
                visited.add(v)
                path.append(v)
                path_set.add(v)
                stack.append(iter(graph.get(v, ())))
                break
        else:
            path_set.remove(path.pop())
            stack.pop()
    return False


Read multidimensional array from file in C

You have written everything in one function (main probably) but it is better
split into its components.  Essentially what you want to do is:

open input file
get column count
get line count
rewind file
allocate memory for the array
read array data

Some of these stages could and probably should be in separate functions.

Taking it from the top, you open the input file, with the file name
hard-coded.  A better approach is to get the filename from the command line -
argv[1].  You have checked for failure to open the file, which is good.
The normal error handling is to use perror and the name of the failed file:

FILE *f = fopen(argv[1], "r");
if (!f) {
    perror(argv[1]);
    return EXIT_FAILURE;
}

You then allocate buffer data (again the error handling should use
perror).  You then use this buffer in a read loop to count the entries in
each line, but you really don't need to save the values in the buffer at all
at this stage - you discard them anyway. Your read loop could equally be:

while (sscanf(line+cur, "%*lf%n", &read) == 1) {
    cur += read;
    columCount++;
}

Notice that the format string uses a '*' to suppress assignment of the
floating point value read.  Note also the improved formatting and the use of
++ in columCount++.  Note also that you don't check for failure in reading
the first line.

Edit: Abbas pointed out that adding the '*' to suppress assignment means that we must check for 0 returned from sscanf, not 1. But sscanf also returns 0 when it fails to read anything (in this case the read count in read would also contain 0). Hence a bad character in the line will cause the loop to hang. So we must either not suppress the assignment:

double d;
while (sscanf(line+cur, "%lf%n", &d, &read) == 1) {
    cur += read;
    columCount++;
}

or we must check read.

while ((sscanf(line+cur, "%*lf%n", &read) == 0) && (read != 0)) {
    cur += read;
    columCount++;
}

I think I would go for the first.  End of edit.

You then count the lines by looping through them.  Note that you use a fixed
size buffer line, allocated at the beginning, to read each line.  To be
completely flexible, you should handle lines of arbitrary length.  Your lines
are fixed at 1000 chars and anything beyond that breaks the code.  Since you
are using getline (which is non-standard, but useful) I would make use of its
ability to allocate a line for you by passing a zero size.

char *line = NULL;
size_t count = 0;            // EDIT: Abbas pointed out we need to add count=0
getline(&line, &count, file);
// use the line
free(line);

In this, line is just a pointer. getline allocates a buffer large enough
to hold the line of text and places a pointer to the buffer in line.  You
must free that line later.

So now you have the column and row count.  Those two stages (reading the two
sizes) would be better extracted into a separate function.

You now rewind the file and allocate the real array.  As stated above, this
should be the first allocation of the program.  Following this you read the
data into the array.  This might be better split into a separate function.
The read loop can be simpler than yours - you
don't need to get a line and then scan it - just scan it directly:

int ndata = 0;
while (scanf("%lg", &data[ndata++]) == 1) {
    // nothing
}
ndata -= columCount * rowCount;
if (ndata != 0) {
    printf("%s data values in input\n", ndata > 0 ? "Too few" : "Too many");
    return EXIT_FAILURE;
}

And remember to check that the number of doubles read matches what you were
expecting.

Note that scanf and its associates do not react well to malformed input.  There are other ways of reading text but in the simple case (of properly formed data) they are more complicated.  Someone else might give you some examples/alternatives.

Finally note that your formatting is inconsistent, as if bits have been cut
and pasted from elsewhere.  Copying code from your previous work is not
necessarily bad, but make sure you make the whole thing looks as if it belongs
together.


Wrapper class for system dialog to allow for dependency injection

unit tests

You can use fakes (stubs vs shims) to mock third-party classes. It is not as lightweight as your regular mocks, but it does the job.

exception handling

catch (Exception)
{
    return false;
}

Why don't you do something like Microsoft tends to do often in their framework? You make some internal convenience method IsCriticalException that checks whether to rethrow the exception or swallow it.

catch (Exception ex)
{
    if (IsCriticalException(ex)) throw;
    return false;
}

clean code

Use var when you can.

  Microsoft.Win32.SaveFileDialog dlg = new
  Microsoft.Win32.SaveFileDialog

 var dlg = new Microsoft.Win32.SaveFileDialog


Implementing feature hashing using guava

Simplified code:

List<Double> guavaCollisions = Arrays.stream(hashDimensions)
    .map(dimension -> {
        HashFunction hashFunction = Hashing.murmur3_32(runif.sample());
        Map<Integer, Long> guavaCounts = Arrays.stream(runif.sample(sampleSize))
            .collect(Collectors.groupingBy(key -> Hashing.consistentHash(hashFunction.hashInt(key), dimension),
                 Collectors.counting());
        return guavaCounts.values().stream().mapToLong(id -> id).average().getAsDouble();
    }).collect(Collectors.toList());

Reasoning:

Inlined the seed. Keeping the seed variable there isn't necessary since we don't use it anymore, not even in the logging-statement.
Used collect instead of forEach(el -> collection.add(el)) to create Collections which is more idiomatic.
Dropped the Set<Integer> from the Map, since we don't actually ever use the Integers we keep in memory here, but instead only want the number of unique integers. (Note that currently I don't check for uniqueness, which means the semantics changed)
Simplified the calculation of average from guavaCounts by not streaming the entry-set and then mapping to value, which could be simplified by using Entry::getValue, but directly streaming the values().
Dropped the System.out because it's incredibly slow in comparison, a side-effect that shouldn't be happening in a Stream and doesn't add viable information to the "final" result of the code.
Renamed hds, hd and hf because shortening names is pointless. I'd have preferred to also rename runif, but didn't find a better name, which would remain succinct.


Generating three-letter strings from five-letter words

Your program can be simplified to something like this:

System.out.println("Please enter a five letter word");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();

for (int i = 0; i < input.length(); i++) {             // pos. of 1st letter
    for (int j = 0; j < input.length(); j++) {         // pos. of 2nd letter
        for (int k = 0; k < input.length(); k++) {     // pos. of 3rd letter
            if (i == j || i == k || j == k) continue;  // any letter taken twice? -> skip
            System.out.printf("%c%c%c\n", input.charAt(i), input.charAt(j), input.charAt(k));
        }
    }
}

Some more pointers:

while this works for combinations of three letters, for combinations of more letters (or arbitrary numbers of letters) you should use some sort of recursive function
you might want to check whether the entered word is actually five letters long
before printing, you could store the three-letter-words in a Set<String> to filter out duplicates
the question is a bit unclear whether it's about three-letter strings or three-letter words; in the latter case you might want to get some dictionary of valid three-letter words and check whether the combinations are in that list


Calling percentileofscore for every distinct value is rather inefficient vs. the alternative of making just one call scoreatpercentile(col_data, [0,20,40,60,80,100]). You could directly compare the column values against the limits returned by that function.
Apart from the above you are mostly doing disk I/O. You may have made matters worse by using multiprocessing. In particular, because you lauch as many processes as you have input files, you may have way too many processes competing for RAM and disk access.


Program that converts a number to a letter of the alphabet

C++ does not mandate a particular character coding, so while your code is functionally correct on ASCII and ISO-8859 systems, it won't work in EBCDIC environments, for example.  Even with the obvious fix to add 'A'-1 in place of the magic constant 64, the program assumes that English letters have consecutive values, which just isn't the case in BCD encodings.

The portable approach is to index a string literal:

    static const std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if (letter > 0 && letter <= alphabet.size()) {
        std::cout << "Letter " << letter << " is '"
                  << alphabet[letter-1]
                  << "'\n";
    }

Other issues:

Don't use letter before checking whether std::cin >> letter succeeded.
Instead of an infinite loop, prefer a finite loop for reading inputs.
Consider accepting input as command-line argument(s) as a more convenient alternative to using standard input.
Spelling: "corresponds".


Mutualising multi-threaded calls to EJB from Servlet

The concurrency looks complete to me in the sense that I cannot see any places it can fail, or block significantly. The static LOCK and Future make sense. The getLocalRosterRequest itself is technically correct in the sense that it returns the right results, without logic problems. There is no need for the double-check locking though. It saves nothing, and solves nothing, other than creating two separate lock points.

Additionally, methods should not return concrete-types when interface-types would be available. Your method (and Future should be of type List<String> and not ArrayList<String>

Your code pulls the writeLock() from the LOCK, and locks on that. There are only two places where you use LOCK (one in the call, the other in the get). Neither of them need a sub-lock of the LOCK, they can both operate on the LOCK itself.

Your code would be simpler, and slightly faster, as simply:

  private Future<List<String>> getLocalRosterRequest() {
        LOCK.lock();
        try {
            if (currentRosterRequest == null) { //if there isn't a current request, create a new one
                currentRosterRequest = ROSTER_FETCH_EXECUTOR_SERVICE.submit(ROSTER_FETCH_TASK);
            }
            return currentRosterRequest; //return a reference to the current request
        } finally {
            LOCK.unlock();
        }
  }

and then, in the call method, you would have:

      try {
          return rosterEJB.getRoster();
      } finally {
          //one way or another the roster request has terminated
          LOCK.lock();
          try {
              //clear out the static variable
              MyServlet.currentRosterRequest = null;
          } finally {
              LOCK.unlock();
          }
      }


Minor

You should get rid of the Class suffix. There is no value in attaching the type as a suffix to the name.
You don't need to write this everywhere to access members.
You have an Elapsed property which is not used.

Bugs/Major

Your Reset() method will break the stopwatch because you create a new timer but you do not re-attach the timer tick event handler.
You have a Reset() method which sets up the timer but you also do this in the constructor which is some code duplication and in fact has introduced a bug (see previous point). DRY - Don't Repeat Yourself. Make use of a common method which can get called in both places.
Instead of "polling" your stopwatch in a continuous loop your StopwatchClass should expose an event like TimeUpdated to which any interested party can hook up to.

In general this can pose problems when interacting with UI because if the callback happens on a different thread then you need to marshal UI access across to the UI thread. However you have used a DispatcherTimer which is evaluated at the top of every dispatcher loop - which means the callbacks are happening on the UI thread and it is safe to access UI elements from within the callback (see the MSDN example).

So basically you can expose an event which gets fired on the timer callback and whatever code hooks up to it can update the UI.
In general MVVM has established itself as a very useful pattern. Which means that rather than updating UI elements directly you would update an observable view model to which the UI is bound. This decouples the UI better from the data and decoupling is always good.
The timer is guaranteed to not fire before the interval has elapsed - but there is no guarantee about how long after the interval has elapsed it will fire. This means your stopwatch will start falling behind the real time as you assume each tick is 1 second while in fact it might be 1.01 sec or so. This means after 100 seconds you could be easily 1 sec off or more. A thread time slice in windows is typically around 10ms so I'd suspect the timer to be around that accuracy. Although on Windows Phone you might get better performance (couldn't find any documentation in that regards).

The way to overcome this is to take a timestamp at Start and compute the difference to the current time on each tick. While this will probably also give you an approx. 10ms accuracy it will be constant while your solution will accumulate an error on each tick.

This will also alleviate the need to compute the seconds, minutes and hours since passing as you can get that from the Timespan.

With the changes from above your code could look like this:

public class StopwatchClass : IDisposable
{
    DispatcherTimer _timer;

    public int Interval { get; set; }

    public int Seconds { get; set; }
    public int Minutes { get; set; }
    public int Hours { get; set; }

    public bool IsRunning { get { return _timer.IsEnabled; } }
    public TimeSpan Elapsed { get; set; }
    public List<TimeSpan> Splits { get; set; }

    private DateTime _StartTimestamp = DateTime.MaxValue;

    public event EventHandler TimeUpdated;
    private void OnTimeUpdated()
    {
        var handler = TimeUpdated;
        if (handler != null)
        {
            TimeUpdated(this, EventArgs.Empty);
        }
    }

    public StopwatchClass(int interval)
    {
        Reset();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        var timeSinceStart = DateTime.Now - _StartTimestamp;
        Seconds = (int)timeSinceStart.Seconds;
        Minutes = (int).timeSinceStart.Minutes;
        Hours = (int)timeSinceStart.TotalHours;
        OnTimeUpdated();
    }

    public void Start()
    {
        _StartTimestamp = DateTime.Now;
        _timer.Start();
    }

    public void Stop()
    {
        _StartTimestamp = DateTime.MaxValue
        _timer.Stop();
    }

    public void Reset()
    {
        Seconds = 0;
        Minutes = 0;
        Hours = 0;
        Splits = new List<TimeSpan>();
        _timer = new DispatcherTimer();
        _timer.Interval = new TimeSpan(0, 0, interval);
        _timer.Tick += timer_Tick;
    }

    public void Split()
    {
        var timeSpan = new TimeSpan(Hours, Minutes, Seconds);
        Splits.Add(timeSpan);
    }

    public void Dispose()
    {
        _timer.Tick -= timer_Tick;
    }
}


You could reduce duplication by using an object mapping the selectors (class names in this case) to their responses

const selectorToResponse = {
  '.ottogi': 'Ottogi',
  '.sajo': 'Sajo Hapyo',
  '.natura': 'Natura Bogata',
  '.maloo': 'TOO Maлy',
  '.dongush': 'Dongsuh',
  '.may': 'OOO Maй'
}

Note, that for the first case (.ottogi) you are changing the text to Ottogi if it is Ottogi which has no change, so it can be removed.

const selectorToResponse = {
  '.sajo': 'Sajo Hapyo',
  '.natura': 'Natura Bogata',
  '.maloo': 'TOO Maлy',
  '.dongush': 'Dongsuh',
  '.may': 'OOO Maй'
}

From here you could loop over the object entries using a for...in loop and define the event handlers. This way you only have to add further entries to selectorToResponse instead of duplicating.

const selectorToReponse = {
  '.ottogi': 'Ottogi',
  '.sajo': 'Sajo Hapyo',
  '.natura': 'Natura Bogata',
  '.maloo': 'TOO Maлy',
  '.dongush': 'Dongsuh',
  '.may': 'OOO Maй'
}

// Prefixing with $ to denote that is an element, not text etc
const $header = $('.inner-container h1')

for (const selector in selectorToResponse) {
  $(selector).click = function () {
    // using $header.text() inside function so that is current header text
    // `text` never changed in your example
    if ($header.text() === 'Ottogi') { // using === instead of ==
      const response = selectorToResponse[selector]

      $header.text(response)
    }
  }
}

Notes

Above uses strict equality comparison (===) instead of abstract equality comparison (==). https://developer.mozilla.org/en/docs/Web/JavaScript/Equality_comparisons_and_sameness

Solution uses const, an ES6 feature. The benefits are that selectors scope is confined to the for loop and that the variable identifier cannot be reassigned.

Depending on your desired browser compatibility it may or may not be available.

As @IcePickle pointed out, using var in the for...in loop would mean that selector is always .may in the click handlers due to var having different socping rules. See Creating closures in loops - A common mistake for a detailed explanation.

Using var and another closure:

var selectorToReponse = {
  '.ottogi': 'Ottogi',
  '.sajo': 'Sajo Hapyo',
  '.natura': 'Natura Bogata',
  '.maloo': 'TOO Maлy',
  '.dongush': 'Dongsuh',
  '.may': 'OOO Maй'
}

var $header = $('.inner-container h1')

for (var selector in selectorToResponse) {
  $(selector).click = (function (selector) {
    return function () {
      if ($header.text() === 'Ottogi') {
        var response = selectorToResponse[selector]

        $header.text(response)
      }
    }
  })(selector)
}


There are a lot of takes on how to structure things in Objective-C, largely based on the age of the language.  It used to require you to use x, but now it lets you use y, kind of things.  I like to go with the minimalist/OOAD-purist approach.

Your Header File

Your header file (CalculatorViewController.h) is your public interface for your class.  This is what every other class sees when it compiles against it and has access to.  As such, I keep it light.  You don't want another class to set your fatTextField and if you did, you wouldn't want them to know the intimate details of how your form works so you'd pass a model object or something.  I like my header to look like this:

@class ImportantStuff; // 4
@protocol CalculatorViewControllerDelegate; // 5

@interface CalculatorViewController : UITableViewController
- (id)initWithImportantStuff:(ImportantStuff *)importantStuff; // 1
@property (nonatomic, weak) id<CalculatorViewControllerDelegate> delegate; // 2
@property (nonatomic, readonly) ImportantStuff *importantStuff; // 3
@end

@protocol CalculatorViewControllerDelegate <NSObject> // 6
- (void)calculatorViewController:(CalculatorViewController *)calculatorViewController
    didFinishWithImportantStuff:(ImportantStuff *)importantStuff;
@end

Highlighted lines:

Create an initializer with everything you need to get the class started on work.
Add a delegate or some other message passing pattern to send notifications back.
Maybe, have some exposed properties for information that interfacing classes may want.
As general practice, you should only reference the bare minimum number of headers in your header since it reduces circular dependencies and compile time. @class tells the compiler that a class with that name exists and it shouldn't worry about the details.
With delegates you often have a chicken and egg scenario.  The class references the protocol and the protocol references the class.  Like with @class you can say you'll inherit it later.
Populate your delegate with meaningful hooks.

Your Implementation File, Class Extension

Now that you've removed all those properties from your public header, you're getting compiler errors and need to stick them somewhere.  The right spot is in your class extension, the thing that looks like a category but isn't.  Xcode should have generated it as follows at the top of CalculatorViewController.m

@interface CalculatorViewController ()
@end

Just stick all your @property's there.

As far as the method declarations, you don't need them.  In C you need to declare functions ahead of time, but not with modern Objective-C.  The only reason you need to declare them is if you're trying to expose them outside of your implementation.

Your Implementation File, Implementation

Things look good here.  Just a couple things:

Directly accessing instance variables (ivars), e.g. _pointsLabel has gone out of fashion.  There's a lot of reasons for this with potential risks associated with both doing it and not doing it, but there's even a pedantic compiler warning you can turn on to catch it.  Generally, you should use ivars only in getters, setters, and initializers, places where you need direct access or want to suppress side effects.
There's no reason to have both -reset: and -resetCalculator.  There are two interesting points here: First, somewhere in the codebase exists #define IBAction void so you can turn any void returning function into an IBAction assuming it has the right arguments. Second, controller actions support three structures: -(IBAction)myAction:sender, -(IBAction)myAction:sender event:event and -(IBAction)myAction with no arguments.  You can just use -(IBAction)resetCalculator.
addToTracker, with camel case. Probably just a typo considering everywhere else.  Be aware that Interface Builder provides zero compile time checking so if you change the signature or remove a method you must edit it in Interface Builder or it will crash your app.

The most important thing

No matter what style, or principles, or philosophies you adopt as an iOS developer, every other iOS developer will disagree with you, and you with them.  Maybe it's the awesomeness/awfulness of the language or the tools or the platform or the status, but its a very opinionated group of developers.


Code Review for Adding two numbers without using the + operator

Your algorithm looks good, but the best algorithm (as far as I know) is following:

Add 2 binary numbers without considering carry (an xor operation)
Construct the difference with the actual solution, i.e., construct a number in the carry positions (a and operation then a left shift)
Add the result of step 1 with step 2 (by recursion), until step2 is 0.

The code will look like this:

int add(int a, int b) {
    if (b == 0) return a;
    return add(a ^ b, (a & b) << 1);
}


Prime number sequence supporting repeated iteration

I don't like the idea of returning an inline object that inherits Sequence<Long> like this. Kotlin has several features to help you build stuff, including one for sequences.
Using the fantastic power of the sequence builder in Kotlin, which underneath the surface is using a suspendable function internally, we can yield numbers one by one instead of implementing an Iterator.
We can rewrite your code to use an outer object to keep the global state in, and then use a function to generate the sequence.
object Primes {
    private val knownPrimes: MutableList<Long> = mutableListOf(2L, 3L)
    private fun Long.isMultipleOf(n: Long) = (this % n == 0L)

    private fun Long.isPrime() = knownPrimes
            .takeWhile { it * it <= this }
            .none { this.isMultipleOf(it) }

    fun sequence(): Sequence<Long> {
        var lastPrime: Long? = null
        return sequence {
            while (true) {
                val nextPrime = when(val actualLastPrime = lastPrime) {
                    null -> 2L
                    2L -> 3L
                    else -> {
                        if (knownPrimes.last() > actualLastPrime) {
                            knownPrimes[knownPrimes.binarySearch(actualLastPrime) + 1]
                        } else {
                            val np = generateSequence(actualLastPrime + 2) { it+2 }
                                .first { it.isPrime() }
                            knownPrimes.add(np)
                            np
                        }
                    }
                }
                lastPrime = nextPrime
                yield(nextPrime)
            }
        }
    }
}


Testing whether a given string has unique characters

You can do it in linear time via frequency counting. Make an array that is indexable by characters and initialise it with 0. Run over the string, incrementing the frequency for each character until that results in a value greater than 1 or the string is exhausted. Done.

EXTENDED EXPLANATION

Here is the algorithm expressed in pseudo code, which makes it easy to assess its complexity:

var seen: array [char] of boolean

seen = false

for each c in string_to_be_tested
   if seen[c]
      return false    // string is not free duplicates
   seen[c] = true

return true           // no character occurs more than once

That is the algorithm as such. CodeYogi has already posted a short and succinct pythonic approximation of it (first as a post scriptum, later it was moved into the question body):

len(set(strr)) == len(strr)

This compares the cardinality of the set of characters contained in the string to its length.

The set contains each character at most once, regardless how often it was added. This means that the cardinality of the set can only be equal to the length of the string if each of the characters occurred exactly once. This is not an algorithm as such, it is a functional expression whose algorithmic complexity is more difficult to assess than that of the simpler - if more verbose - imperative pseudo code.

When I wrote the first paragraph of the answer I was thinking along the lines of its most natural/efficient expression, which is in terms of the operation BTS ('bit test and set', or _bittestandset() as a C intrinsic). Here is a rendering of the algorithm in C, for the usual null-terminated strings:

// allocation and zeroing of the bitmap elided - too ugly and not relevant

bts(bitmap, 0);  // pretend we've seen the terminator, so that we drop out at the end

while (!bts(bitmap, *s++))
   ;

return s[-1] == '\0';   // arrived at the end - unique, no duplicate characters

However, the BTS operation tends to be available only in assembly languages and C/C++; hence the description of the algorithm with an array of integer counts, which is much more widely available and which allows a compact approximation of the 'test and set' as 'increment and test':

if (++counts[string[i]] > 1)
   return false

That array is a (partial) frequency count, of course. It is possible to do it exactly like this in python, but that would do neither the algorithm nor the language any justice; it would be ugly and inefficient.


Compressing time series by removing repeated samples

You want to keep points where the value for \$y\$ is different from either the preceding or succeeding value. So in NumPy you can write:

import numpy as np

def compress_2D_signal(x, y):
    """Compress signal y(x) by omitting repeated values for y.

    Takes a signal y(x) as two array-likes x and y. Returns the
    compressed signal y1(x1) as the tuple x1, y1, where y1 contains
    the first and last values of y, and values of y that are different
    from the preceeding or succeeding value, and x1 contains the
    corresponding values from x.

    """
    x, y = np.asarray(x), np.asarray(y)
    keep = np.empty_like(x, dtype=bool)
    if len(x) > 0:
        keep[0] = keep[-1] = True
        keep[1:-1] = (y[1:-1] != y[:-2]) | (y[1:-1] != y[2:])
    return x[keep], y[keep]

Notes on this code:

This returns NumPy arrays (not Python lists), so you'll need to revise your test cases to use numpy.testing.assert_array_equal instead of unittest.TestCase.assertEqual.
If you pass it Python lists, then much of the runtime will be in the numpy.asarray call (converting the input to NumPy arrays) and not in the compression code. So for a fair test I think it makes sense to update test_time_self so that it calls numpy.arange instead of range.

With this change, I find that the revised code is about 30 times faster than the original code.

A couple of other review points:

There's no docstring for compress_2D_signal. It's hard to use and maintain code when there's no documentation.
The test case code is very repetitive — it would be simpler to loop over a list of cases, like this:

from numpy.testing import assert_array_equal

class Test2DSignal(TestCase):
    _CASES = [
        # x, y, x1, y1
        ([1, 2, 3, 4], [0, 1, 2, 3],
         [1, 2, 3, 4], [0, 1, 2, 3]),
        ([1, 2, 3, 4, 5], [0, 2, 2, 2, 0],
         [1, 2, 4, 5], [0, 2, 2, 0]),
        ([1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 2, 2, 0, 0, 1, 1, 1],
         [1, 2, 4, 5, 6, 7, 9], [0, 2, 2, 0, 0, 1, 1]),
    ]

    def test_2D_signal(self):
        for x, y, x1_expected, y1_expected in self._CASES:
            x1_found, y1_found = compress_2D_signal(x, y)
            assert_array_equal(x1_expected, x1_found)
            assert_array_equal(y1_expected, y1_found)

This makes it easier to add new cases. In particular, I would add tests for edge cases such as empty and single-element inputs, like this:

    _CASES = [
        # x, y, x1, y1
        ([], [], [], []),
        ([1], [1], [1], [1]),
        ([1, 2], [1, 1], [1, 2], [1, 1]),
        ([1, 2, 3], [1, 1, 1], [1, 3], [1, 1]),
        # etc.


the idea being that any other class can access a game_object by name if given a reference to main_scene, even if it doesn't hold a reference to the actual object

You've stated that one of your primary goals is speed. Based on your description above, you can still achieve object lookup and avoid the performance hit of a string dictionary.

One of the easiest ways to do this is to add a header file to the application that defines an enum of numeric, sequential object IDs. This will allow for much faster lookup, and depending on how you define and load your data, you wouldn't even need a map - simply a fixed array.


There is not much to be done about the random selector.  However, I would make the function accept an explicit parameter.

That input loop, though, is too complicated. It also fails to handle the "Cancel" button in any way.

function winner(names) {
    return names[Math.floor(Math.random() * names.length)];
}

let names = [];
for (let name; name = prompt('Enter a name:'); ) {
    names.push(name);
}
console.log(winner(names));


Is calling a function only twice a good use of recursion?

Yes, every function which calls itself is considered a recursive function.

Recursion is really useful when traversing trees and such.

As I don't fully understand Perl, I can't really tell whether this case is proper use of recursion, perhaps also provide the intent of your code.

UPDATE

If you simply want to see whether data is passing (or not passing) through a queue, I wouldn't find recursion to be a suitable implemention.

I would expect a function which returns either true or false after a given amount of time, or immediately when data is passing through.

Consider the following pseudo code:

function isDataPassing( queue, time )
{
   headOfQueue = queue.peek();
   dataPassing = false;
   while ( timePassed < time )
   {
       if ( headOfQueue != queue.peek() )
       {
           dataPassing = true;
           break;
       }
   }

   return dataPassing;
}

I can't help you with how you would go about implementing this in Perl. StackOverflow is a better location to ask such a question.


Thumbnail caption in vue.js with possibly missing fields in caption

By using v-if I was able to come up with a solution I am comfortable with.

<template>

{{ post.make }}

{{ post.model }}

{{ post.price }}

{{ post.user.name }}

</template>

I also considered not allowing null in the database so I would not have to check for it but that needed some special attention.


Here are my observations:

List<BacktestResult> data: Please try to use more expressive names than data. It is way too general and it does not help the reader / maintainer of the code. (same apply to table and query)

Populating columns: Your implementation has a lot of repetition in it: tables.Columns.Add.

One way to reduce that by using the AddRange:

var table = new DataTable();
table.Columns.AddRange(new []
{
    new DataColumn("Pair"),
    new DataColumn("Buys"),
    new DataColumn("Avg Profit %"),
    new DataColumn("Cum Profit %"),
    new DataColumn($"Tot Profit {_backtestOptions.StakeCurrency}"),
    new DataColumn("Tot Profit %"),
    new DataColumn("Avg Duration"),
    new DataColumn("Wins"),
    new DataColumn("Draws"),
    new DataColumn("Losses"),
});

We are almost there, here we have repeated the new DataColumn. With the following technique you can separate data and logic:
var columns = new[]
{
    "Pair", "Buys", "Avg Profit %", "Cum Profit %", $"Tot Profit {_backtestOptions.StakeCurrency}",
    "Tot Profit %", "Avg Duration", "Wins", "Draws", "Losses"
};

table.Columns.AddRange(columns.Select(name => new DataColumn(name)).ToArray());

data.GroupBy(e => e.Pair): This has been called twice, but unnecessarily.

Materialize it by calling the ToList or ToArray on it:
With this approach we could get rid of the maxOpenOrders variable.

var resultsGroupByPair = data.GroupBy(e => e.Pair).ToArray();
var query = resultsGroupByPair.Select(br => new { Pair = br.Key, Count = br.Count(), Value = br });
//...
var _profitTotal = _profitSum / resultsGroupByPair.Length;

query: Same applies here, Possible multiple enumeration

Materialize it by calling the ToList or ToArray on it

if there are no rows, it throws an exception..: This comment is not align with the code. Try to comment the Whys and Why nots, not the what and how. The latter two should be clear by the code itself, but the chosen strategy (and the excluded alternatives) might not be obvious from the code.
profitMean, profitSum, profitTotal: They are unused. If they are not needed then delete them.
trades > 0 ?: This condition has been repeated several times.

Introduce a local variable and refer to that one instead: bool isTradesPositive

result.Value.Average, result.Value.Sum: Same as in the previous case. If you use the same expression multiple times then save its result into a variable.
wins, draws, losses: Instead do 3 iterations you can do it with a simple one.

For example with Aggregate:

var (wins, losses, draws) = result.Value.Aggregate((0, 0, 0), (outcome, e) =>
{
    if (e.ProfitAbs > 0) outcome.Item1++;
    else if (e.ProfitAbs < 0) outcome.Item2++;
    else outcome.Item3++;
    return outcome;
});

or
var (wins, losses, draws) = result.Value.Aggregate((0, 0, 0),
    ((int winCount, int loseCount, int drawCount) outcome, BacktestResult e) =>
    {
        if (e.ProfitAbs > 0) outcome.winCount++;
        else if (e.ProfitAbs < 0) outcome.loseCount++;
        else outcome.drawCount++;
        return outcome;
    });


Python script to update a cPanel zone record with my public IP

Before anything else, I'd like to point out that there is probably an error with your indentation. I've fixed it in my code assuming that only one line was not indented properly..

Simple is better than complex.

You don't need the classes (you can also have a look at this video). After taking this simple comment into account, your code looks like this (I put everything in the same place for the sake of simplicity)

#!/usr/bin/python3

from http import client
from base64 import b64encode
from sys import argv
from netutils import PollIP
from urllib import request
from re import compile

#Use the dyndns web-site to poll my public IP address
def publicIP():
    myReq = request.urlopen('http://checkip.dyndns.com')
    html = str(myReq.read())
    myReg = compile('[\d.]+')
    myMatch = myReg.search(html)
    print(myMatch.group())
    return myMatch.group()

def updateIP (passedIP):
    newIP = passedIP
    conn = client.HTTPSConnection('mydomain.com', 2083)
    myAuth = b64encode(b'username:thepassword').decode('ascii')
    authHeader = {'Authorization':'Basic ' + myAuth}
    conn.request('GET', '/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=ZoneEdit&cpanel_jsonapi_func=edit_zone_record&domain=mydomain.com&line=28&class=IN&type=A&name=homenet.mydomain.com.&ttl=3600&address=' + newIP, headers=authHeader)
    myResponse = conn.getresponse()
    print(myResponse.getcode())
    data = myResponse.read()
    if myResponse.getcode() != 200:
        print('did not succeed')
    print (data)

############################################

if __name__ == "__main__":
    if len(argv) > 1:
        newIP = argv[1]
        print(argv[1])
    else:
        newIP = publicIP()
    updateIP(newIP)

Your variables names are probably not that good. What do you mean by 'new' ? Also, many variables are not even required (I've been pretty far in the cleanup as it helped me to understand the code, you might want to keep some of the variables I've removed). Also, your function names are not really well chosen as it doesn't really describe what they do : updateIP does not seem to update the IP at all.
Separate the concerns : do you want publicIP() to return a string or to print it ? It should probably just return it and then you print it from the main if you want. Please note that doing this introduces an interesting pattern : you print newIP from the 2 branches of your if. You can easily get rid of this duplicated code. In the same spirit, updateIP(ip) seems to be printing things and does not return anything. Let's name the function to make this easier to understand. Please note that : 1) you'd probably want this to return a string in a real life situation 2) you might want it to throw an exception if something fails 3) my functions names are terrible 4) there are naming convention for Python that you'll find in PEP 008 (it's worth a read).
You can get rid of values (urls, ports, login, password, etc) in the middle of the code. This can be useful if you need to reuse them in different places. In any case, it's worth replacing 200 by client.OK which is much clearer.

Once you've done so, here what you code is like :

#!/usr/bin/python3

from http import client
from base64 import b64encode
from sys import argv
from netutils import PollIP
from urllib import request
from re import compile

#Use the dyndns web-site to poll my public IP address
def getPublicIP():
    html = str(request.urlopen('http://checkip.dyndns.com').read())
    reg = compile('[\d.]+')
    match = reg.search(html)
    return match.group()

def printIPFromIP(ip):
    conn = client.HTTPSConnection('mydomain.com', 2083)
    conn.request('GET', '/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=ZoneEdit&cpanel_jsonapi_func=edit_zone_record&domain=mydomain.com&line=28&class=IN&type=A&name=homenet.mydomain.com.&ttl=3600&address=' + ip,
        headers={'Authorization':'Basic ' + b64encode(b'username:thepassword').decode('ascii')})
    response = conn.getresponse()
    print(response.getcode())
    if response.getcode() != client.OK:
        print('did not succeed')
    print (response.read())

############################################

if __name__ == "__main__":
    ip = argv[1] if len(argv) > 1 else getPublicIP()
    print(ip)
    printIPFromIP(ip)

It's probably not perfect but I think I hilighted the main issues.


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

Use a state machine

The approach you currently have uses bool variables keeping track things such as whether a section has been found, whether a character is the last one and weaves the interpretation int a long series of nested if statements.  That approach may work for small, simple grammars such as this, but it's not going to scale well as you move on to a larger set of things your program can parse.

For that reason, I'd recommend a more data-driven approach in which you write out a state machine and have the code execute according to the data within it rather than via a code-driven approach.  This makes things more compact and easier to read.

An example of such an implementation for a parser is in this answer.

Consider using regular expressions

I've given this advice before.  It's a lot easier in C++ because there's library support within the standard, but since it appears you're using POSIX-based libraries, you may already have a regular expression library available to you.

Consider using compiler tools

Another approach to consider is to use standard tools such as lex and yacc (or flex and bison) to create a much more readable and maintainable version of the parser.  These tools have a steep learning curve, but once you've mastered them, you'll be better able to see and understand how to write unambiguous parsers from scratch as well.  IMHO, this is time well spent.

Don't comment out debug statements

Just as with assert, I'd suggest that creating a version of dbg that either expands to nothing (for production code) or to a routine that prints debugging messages (for development) may be very useful.  It's much easier than commenting and uncommenting such debugging statements during the debugging process.

Don't leak memory

There is, potentially, a malloc within the code but no corresponding free.  I assume that's because it's intended that's because the caller is supposed to free it if it's allocated, but the problem is that the routine doesn't set name to NULL if it doesn't happen to allocate memory, making it incumbent on the caller to also pre-set the pointer to NULL.  This would be easier to use if, instead, the pointer were a return value that would either be NULL or a pointer that the caller is expected to free.

Avoid ssize_t if possible

Because you're initializing match_pos with -1, I see why you've chosen to make it of type ssize_t (which is signed) versus size_t which might not be signed.  However, this limits portability and there's no reason you couldn't use another sentinel value instead, such as SIZE_MAX


Idiomatic way to construct a SQL INSERT query in Python

There is a neater, more Pythonic way of doing this using the str.format function. However, it is not the way you should do it.

Currently, the way you are building your query, you are vulnerable to SQL injection. This is the point @Mat's Mug was getting at in his comment. What if a malicious user decides to give the following as a user ID:

user_id = "1,1,99,'today');DROP TABLES;INSERT INTO words (word, user_id, game_id, score, time_stamp) VALUES ('Goodbye', 1"

If this happens, a disaster beyond your imagination will occur*!

To prevent this, the cursor from the MySQLdb module (which I assume you are using) allows you to pass in a tuple or dict of the parameters to the execute function:

time_stamp = datetime.datetime.now().isoformat()
sql = "INSERT INTO words (word, user_id, game_id, score, time_stamp) VALUES {}"

# Create the query
sql = sql.format(','.join(["('%s', %s, %s, %s, '%s')" for _ in words]))

# Create the parameter tuple.
params = ()
for word in words:
    params += (word['str'], user_id, game_id, word['score'], time_stamp,)

# Sending a tuple is easiest in this situation
cur.execute(sql, params)

If you want to look at another database solution for Python, take a look at SQLAlchemy. Its a pretty powerful framework that makes working with databases much simpler.

*=Sorry for the Phantom of the Opera quote. I'm feeling oddly dramatic right now.

Update

To answer your question about removing the for-loop, the best you can hope for is to use a list comprehension. In many situations, list comprehensions are typically the Pythonic way of iterating over a collection. However, in your situation, this probably is not the case.

The comprehension for your current code would look like this:

','.join([str(tuple([word['str'], user_id, game_id, word['score'], time_stamp]))
          for word in words])

This is really only effective creating the end to your query. Unfortunately, in addition to being hard to read, it is still vulnerable to SQL injection.

In your case, I think a for-loop would be the cleanest way to implement what you want.


Your use of the counting system using a HashMap is a functional approach to solving the problem, and algorithmically it's relatively good (has time complexity of \$O(N)\$). But, for a prolem like this, it's easier to normalize each input value in to a sorted array or string, than in to a counting HashMap.

Consider the following function:

public static final String normalize(value) {
    if (value == null) {
        return null;
    }
    char[] chars = value.toCharArray();
    Arrays.sort(chars);
    return new String(chars);
}

Now, all values that are anagrams will have the same normalize result (they have the same characters in the same sorted order).

Your code would simply become:

private static String isAnagram (String str1, String str2) {
    return Objects.equals(normalize(str1), normalize(str2));
}

Note that in this case, Objects is java.util.Objects.

Further, by putting the normalization in to a separate function it reduces the amount of logic duplication in your code.

Now, you ask if there are any grave violations... and I have to answer "yes". In Java it is common practice to put { braces on the same line as the code block definition. For example your code:

        for (char ch: str1.toCharArray())
            {
                if (!(occurs.containsKey(ch)))
                    {
                        occurs.put(ch,1);
                    }
                else
                    {
                        int count = occurs.get(ch);
                        occurs.put(ch,count + 1);
                    }
            }

should be:

        for (char ch: str1.toCharArray()) {
            if (!(occurs.containsKey(ch))) {
                occurs.put(ch,1);
            } else {
                int count = occurs.get(ch);
                occurs.put(ch,count + 1);
            }
        }


The keyword explicit should be used with constructors taking a single argument in classes when automatic instantiation is not a universally valid operation (details and examples here).

The code review part

The packet_registry can just be an array of std::function (as you seem to be OK with paying for the virtual dispatch overhead) — std::array<std::function< packet const&, ArgTypes...>, 256>
processor-s, given they are created just once, are better be created by value. Then you will be able to have a very hackable syntax — registry[x] = [...](auto&& packet, auto&& arg) { ... actual code ...};
if for some reason you do need shared pointers, prefer make_shared over direct usage of the new operator — x = std::make_shared<type>(args...).


Some brief comments:

Your variable names are quite short (often one letter), which makes the code harder to follow. Longer and more descriptive variable names would make it easier to read and debug (e.g., trg to triangle, r1 to row1).

The input to the function printTrg is rows, but we also have variables like r, r1 and r2 which look like rows. Perhaps this would be better named as row_count?

The main style guide for Python is PEP 8, which is very readable and friendly. It gives advice on how you choose variable names, functions, and so on. In particular, for function names, it says:

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.

So you should rename the function printTrg to be print_trg, or even better print_triangle, to match the Python conventions.

There's also something called a docstring, which is used in Python functions to explain what the function is supposed to do.
This usually occurs in triple quotes, directly below the def line.
For example, you might write:

def printTrg(rows):
    """Prints Pascal's triangle up to the (rows)th row."""
    ...

There's a more detailed explanation of docstrings in PEP 257.
Right now the code which generates Pascal's triangle, and the code which prints it to the console, are tightly bound together.
You might be better off splitting the two into two functions:

generate_pascals_triangle(row_count), which would return the list of lists trg which your function already creates.
print_pascals_triangle(triangle), which could take the output from generate and print it to the console.

The elif rows == 2 block is redundant, as the else block does exactly the same thing. The range(2, rows) never executes if rows is 2.

While we're in the else block, I’m unclear why your range goes to rows in the first for loop, but to len(trg) in the second. Unless I've confused myself, these are always the same thing. And later in the same loop, you use rows to count the number of spaces you need.
The way you generate the next row of Pascal's triangle (insert a list of 1s, update the entries, then put an extra 1 on the end) could be simplified. Since you’re making a list for the entries in that row, you could use a list comprehension. (If you're not familiar with these, then there are lots of good explanations on Google.)

Here's a simple example of a function which takes the previous row of Pascal's triangle, works out which row you're in now (by looking at the length of the previous row), then generates the new row with a list comprehension:

def next_row(row):
    """Returns the next row of Pascal's triangle."""
    n = len(row)
    new_row = [row[0]] + [row[i] + row[i+1] for i in range(n - 1)] + [row[-1]]
    return new_row

We're still doing essentially the same thing, but this looks cleaner, and we've split up some more of the logic. This can make life easier when it comes to debugging.

This also works if we give it the first row [1], so we don't need to consider the cases rows == 1 and rows != 1 separately when we generate Pascal's triangle. Again, we're able to simplify some of the code.
As you’ve pointed out, things get out of line if you print a large number of rows, as two and three digit numbers come in to play. If you split this into two functions, then you can play around with the printing without affecting the arithmetic (which works perfectly).

So with all that in mind, here's how I might rewrite your code.
First I have the function which I mentioned above, which takes one row of Pascal's triangle and returns the next:

def next_row(row):
    """Returns the next row of Pascal's triangle."""
    n = len(row)
    new_row = [row[0]] + [row[i] + row[i+1] for i in range(n - 1)] + [row[-1]]
    return new_row

Next, we have a function which just generates the entries of Pascal's triangle. Since we're not printing anything (that will come later), and the arithmetic for generating new rows is in another function, this is much shorter than before:

def generate_pascals_triangle(row_count):
    """Returns the entries of Pascal's triangle."""
    row1 = [1]
    triangle = [row1]
    for i in range(1, row_count):
        triangle.append(next_row(triangle[-1]))
    return triangle

If we wanted, we could supply the first entry (or even a whole first row) as an argument. You could see what happens if you make 2 the top entry, or started several levels deep. This is left for you to play with. (You may find this explanation of optional and named arguments useful.)

Finally, we come to the printing problem. We can use the logic from your else block, almost unmodified (just with more descriptive variable names):

def print_pascals_triangle(triangle):
    """Prints the entries of Pascal's triangle."""
    for row_no in range(len(triangle)):
        row = triangle[row_no]
        printed_row = []
        for entry in row:
            printed_row.append(str(entry))
        print (' ' * (len(triangle) - (row_no + 1)), ' '.join(printed_row))

If you wanted, that could become a little shorter using list comprehensions (I leave that as an exercise).

Here's an idea for how you could solve the spacing issue: first, find the longest number in your triangle. (You don't need to examine every entry: which row will always contain the longest entry?) Then, add spaces to every number you print, so that they're always the same length.

For example, if the longest entry was 2704156 (which you get in a 25-triangle), you would transform

1 -> _ _ _ 1 _ _ _

15 -> _ _ 1 5 _ _ _

165 -> _ _ 1 6 5 _ _

and so on. I haven't tried that, so I don't know how good it looks, but it might be something for you to get you started.

ETA: One more comment, based on your updated code:

At the end of the script, you have a little “interactive” section, which gets the user to give you a row count, and then you print their Pascal’s triangle.

If you load this file with import pascal-triangle in a larger script, then you immediately get asked to start drawing Pascal triangles. This can be unhelpful (imagine if everything you imported did that!).

Instead, you can put this code inside a special if statement:

if __name__ == '__main__':
    again = 'y'
    while again == 'y':
        rows = int(input('Enter the number of rows you want in your Pascal`s Triangle: '))
        print_pascals_triangle(generate_pascals_triangle(rows))
        again = input('Do it again ? <y/n> ')

Any code within this if statement is only used if the script is run directly; that is, if somebody types

$ python pascal-triangle.py

at a command prompt. If it gets loaded as import pascal-triangle in another script, then any code inside this if statement won’t be run. This means that you can reuse these functions later without any hassle.

You can find out more in this Stack Overflow question: https://stackoverflow.com/questions/419163/what-does-if-name-main-do


PEP-8 Violations

Variables (unseenNodes, currentNode) should be snake_case, not camelCase.

Infinity

99999999999 is no where near infinity.  If you want to use infinity, use the real infinity: float("+inf"), or in Python 3.5+, math.inf

Conversion to strings

Python's print() statement automatically converts any non-string object into a string, for printing.  You don't have to.  This:

    print('Shortest distance is ' + str(shortest_distance[goal]))
    print('And the path is ' + str(track_path))

can be written as:

    print('Shortest distance is', shortest_distance[goal])
    print('And the path is', track_path)

which is slightly shorter to type.  As a bonus, it is slightly more efficient, as it does not need to create, and subsequently deallocate, a new string object which is the concatenation of the the strings.

If you are using Python 3.6+, you might want to use f-strings:

    print(f'Shortest distance is {shortest_distance[goal]}')
    print(f'And the path is {track_path}')

which interpolates values directly into the strings.

Return Value

Your function finds the path, prints the result, and does not return anything.  This is not useful if you wish to use the discovered path in any other fashion.  The function should compute the result and return it.  The caller should be responsible for printing the result.

Document the code

True, you have plenty of comments.  But the caller can only guess at what the functions arguments are supposed to be, and what the function returns.  You should document this with type-hints, and """doc-strings""".  Something like:

from typing import Any, Mapping, Tuple, List

Node = Any
Edges = Mapping[Node, float]
Graph = Mapping[Node, Edges]

def dijkstra(graph: Graph, start: Node, goal: Node) -> Tuple[float, List]:
    """
    Find the shortest distance between two nodes in a graph, and
    the path that produces that distance.

    The graph is defined as a mapping from Nodes to a Map of nodes which
    can be directly reached from that node, and the corresponding distance.

    Returns:
        A tuple containing
            - the distance between the start and goal nodes
            - the path as a list of nodes from the start to goal.

    If no path can be found, the distance is returned as infinite, and the
    path is an empty list.
    """

Avoid multiple lookups

In this code:

    min_distance_node = None
    for node in unseenNodes:
        if min_distance_node is None:
            min_distance_node = node
        elif shortest_distance[node] < shortest_distance[min_distance_node]:
            min_distance_node = node

you continuously look up shortest_distance[min_distance_node].  In compiled languages, the compiler may be able to perform data-flow analysis, and determine that the value only need to be looked up again if min_distance_node changes.  In an interpreted language like Python, where a lookup action can execute user-defined code and change the value, each and every lookup operation must be executed.  shortest_distance[min_distance_node] is two variable lookups plus a dictionary indexing operation.  Compare with:

    min_distance_node = None
    min_distance = infinity
    for node in unseenNodes:
        distance = shortest_distance[node]
        if min_distance_node is None:
            min_distance_node = node
            min_distance = distance
        elif distance < min_distance:
            min_distance_node = node
            min_distance = distance

This code will run faster, due to less lookups of shortest_distance[min_distance_node] and shortest_distance[node].

But finding the minimum of a list is such a common operation, that Python has a built-in function for doing this: min(iterable, *, key, default).  The key argument is used to specify an ordering function ... in this case, a mapping from node to distance.  The default can be used to prevent a ValueError if there are no nodes left, which is unnecessary in this case.

    min_distance_node = min(unseenNodes, key=lambda node: shortest_distance[node])

In the same vein:

    for child_node, weight in path_options:
        if weight + shortest_distance[min_distance_node] < shortest_distance[child_node]:
            shortest_distance[child_node] = weight + shortest_distance[min_distance_node]
            track_predecessor[child_node] = min_distance_node

repeatedly looks up shortest_distance[min_distance_node]; again, two variable lookups and a dictionary indexing operation.  Again, we can move this out of the loop:

    min_distance = shortest_distance[min_distance_node]
    for child_node, weight in path_options:
        if weight + min_distance < shortest_distance[child_node]:
            shortest_distance[child_node] = weight + min_distance
            track_predecessor[child_node] = min_distance_node

Reducing the Working Set

The code to find the min_distance_node: how many nodes does it check?  In your toy graph "a" to "h", on the first iteration, it needs to search 8 nodes.  With 480 000 nodes, it would need to search 480 000 nodes!  In the second iteration, one node has been removed from unseenNodes, so the it would search one node less.  7 nodes is fine, but 479 999 nodes is a huge number of nodes.

How many nodes does "a" connect to?  Only 3.  The min_distance_node will become one of those 3 nodes.  Searching the remaining nodes (with infinite distances) isn't necessary.  If you added to the unseenNodes only the nodes which can be reached at each step of the algorithm, your search space would reduce from several thousand nodes to a couple of hundred.

Moreover, if you maintained these unseenNodes in a sorted order by distance, the min_distance_node would always be the first node in this “priority queue”, and you wouldn’t need to search through the unseenNodes at all.

Maintaining the unseen nodes in a priority queue is easily done through a min-heap structure, which is built into Python (heapq):

from math import inf, isinf
from heapq import heappush, heappop
from typing import Any, Mapping, Tuple, List

Node = Any
Edges = Mapping[Node, float]
Graph = Mapping[Node, Edges]

def dijkstra(graph: Graph, start: Node, goal: Node) -> Tuple[float, List]:
    """
    Find the shortest distance between two nodes in a graph, and
    the path that produces that distance.

    The graph is defined as a mapping from Nodes to a Map of nodes which
    can be directly reached from that node, and the corresponding distance.

    Returns:
        A tuple containing
            - the distance between the start and goal nodes
            - the path as a list of nodes from the start to goal.

    If no path can be found, the distance is returned as infinite, and the
    path is an empty list.
    """

    shortest_distance = {}
    predecessor = {}
    heap = []

    heappush(heap, (0, start, None))

    while heap:

        distance, node, previous = heappop(heap)

        if node in shortest_distance:
            continue

        shortest_distance[node] = distance
        predecessor[node] = previous

        if node == goal:

            path = []
            while node:
                path.append(node)
                node = predecessor[node]

            return distance, path[::-1]

        else:
            for successor, dist in graph[node].items():
                heappush(heap, (distance + dist, successor, node))

    else:

        return inf, []

if __name__ == '__main__':
    graph = {
        'a' : {'b':3, 'c':4, 'd':7},
        'b' : {'c':1, 'f':5},
        'c' : {'f':6, 'd':2},
        'd' : {'e':3, 'g':6},
        'e' : {'g':3, 'h':4},
        'f' : {'e':1, 'h':8},
        'g' : {'h':2},
        'h' : {'g':2}
    }

    distance, path = dijkstra(graph, 'a', 'e')
    if isinf(distance):
        print("No path")
    else:
        print(f"Distance = {distance}, path={path}")

OSM

By 'OSM' do you mean "Open Street Maps"?  If so, you are using the wrong algorithm.  Map nodes have coordinates, which can be use as "hints", to direct the search in a given direction.  See A* Search Algorithm


List objects in a Amazon S3 folder without also listing objects in sub folders

In the ListObjectsRequest javadoc there is a method called withDelimiter(String delimiter).  Adding .withDelimiter("/") after the .withPrefix(prefix) call then you will receive only a list of objects at the same folder level as the prefix (avoiding the need to filter the returned ObjectListing after the list was sent over the wire).

Some notes about the code:

1, I'd extract out to a local variable for the ListObjectsRequest instance:

final ListObjectsRequest listObjectRequest = new ListObjectsRequest().
    withBucketName(AWSConfiguration.BUCKET).
    withPrefix(prefix);
final ObjectListing objectListing = s3.listObjects(listObjectRequest);

It's easier to read.

2, root_size should be rootSize. (Regarding to the Java Coding Conventions.)

3, I would use String.contains instead of indexOf. It's more meaningful, easier to read since you don't have to use the -1 magic number.

4, In the last snippet I'd create a local variable for the key:

for (final S3ObjectSummary objectSummary: objectListing.getObjectSummaries()) {
    final String key = objectSummary.getKey();
    if (S3Asset.isImmediateDescendant(prefix, key)) {
        final String relativePath = getRelativePath(prefix, key);
        System.out.println(relativePath);
    }
}

5, Furthermore, I'd move the length call inside the helper method:

public String getRelativePath(final String parent, final String child) {
    if (!child.startsWith(parent)) {
        throw new IllegalArgumentException("Invalid child '" + child
            + "' for parent '" + parent + "'");
    }
    // a String.replace() also would be fine here
    final int parentLen = parent.length();
    return child.substring(parentLen);
}

public boolean isImmediateDescendant(final String parent, final String child) {
    if (!child.startsWith(parent)) {
        // maybe we just should return false
        throw new IllegalArgumentException("Invalid child '" + child
            + "' for parent '" + parent + "'");
    }
    final int parentLen = parent.length();
    final String childWithoutParent = child.substring(parentLen);
    if (childWithoutParent.contains("/")) {
        return false;
    }
    return true;
}

Note the input check. (Effective Java, Second Edition, Item 38: Check parameters for validity)

The multiple calls of length could look redundant and slow but premature optimization is not a good thing (see Effective Java, Second Edition, Item 55: Optimize judiciously). If you check the source of java.lang.String, you will find this:

/** The count is the number of characters in the String. */
private final int count;

...

public int length() {
    return count;
}

String is immutable, so it's easy to cache its length and JDK does it for you.


Every 4th measurement fails is a pretty high error rate. The preferred course of action would be to root cause the error and fix it. Meanwhile, since the error seems to be transient, you may want to read the sensor again, and again, until it reads cleanly. Another strategy is to read more often, and maintain the running average (discarding the failures).
For a proper review, DRY. The GPIO setup shall be lifted out of the if/else:
while True:
    GPIO.setmode(GPIO.BCM)
    RELAIS_1_GPIO = 17
    GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
    if  measure_temp() < 8:
        GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
        print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
        print('Heating on')
        print()
    else:
        GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
        print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
        print('Heating off')
    time.sleep(900)
    GPIO.cleanup()

I also recommend to factor the printing out to the function, e.g.
def log_heating_status(status):
    print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
    print('Heating {%s}'.format(status))

to be called as log_heating_status('on') and log_heating_status('off').
It is also very unclear why do you setup/cleanup GPIO on every iteration. I'd expect it to be done once, outside the loop.


Flags

It's not very problematic for very short programs like this, but better get good habits: flags should be outside of all code blocks; so that you detect immediately if you have a flag naming conflict between different files.

var (
    shiftF = flag.Int("shift", 13, "Cipher shift")
    decodeF = flag.Bool("decode", false, "Decode input")
)

func main() {
    …
}

Code organization

You're checking for the value of the -decode flag every time you scan a line, and recomputing -shift+26 every time as well: not very efficient, nor super readable. As you noticed, the only difference between encoding and decoding is the value of shift. Why not do something like:

func main() {
    flag.Parse()

    // we could also directly change the value of the flag, but I find it
    // less readable — it's better to treat flag values as immutable.
    var shift int
    if *decode {
        shift = 26 - *shiftF
    } else {
        shift = *shiftF
    }

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        cipher(scanner.Text(), shift)
    }
}

Type conversions

bufio.Scanner holds bytes internally: the doc for Scanner.Bytes says:

  The underlying array may point to data that will be overwritten by a subsequent call to Scan. It does no allocation.

while Scanner.Text indicates that it returns:

  a newly allocated string.

So here, you allocate a string to copy bytes; and then you allocate a new slice of type []byte to copy this string, which is also an expensive operation.

So you're saving two conversions by not dealing with strings at all:

func main() {
    …
    for scanner.Scan() {
        fmt.Printf("%s\n", cipher(scanner.Bytes(), shift))
    }
}

func cipher(bytes []byte, shift int) []byte {
    var line []byte
    for _, b := range bytes {
        if b >= 'A' && b <= 'Z' {
            b = byte((int(b-'A')+shift)%26 + 'A')
        } else if b >= 'a' && b <= 'z' {
            b = byte((int(b-'a')+shift)%26 + 'a')
        }
        line = append(line, b)
    }
    return line
}

Note the slight change in the way you print the result: using fmt.Println on a []byte variable will print the numeric value of each byte, something like [116 104 101 32 103 97 109 101], so you have to use fmt.Printf to tell it to print it like a string.

You're also wondering whether the conversions from byte to int are inefficient: kind of, yes. Arithmetic operations work on bytes, so you could do instead:

shiftB := byte(shift)
b = ((b-'A')+shiftB)%26 + 'A'

However, this is just a simple type conversion: the performance gain from it will be much lower than when avoiding memory allocations, so you shouldn't worry about it too much =)

Optimizations

Initializing a []byte variable and appending char by char to it is not great: the slice is going to be re-sized every time it hits its maximum default size. It's even worse in your code: you're initializing a string variable and appending char by char to it, which will reallocate the string each time. In cipher, you know in advance which size line is going to be: the same as the original slice. So you can initialize directly with the correct allocated capacity:

    line := make([]byte, 0, len(bytes))

okay, now let's go even further: calling append at each iteration means that under the hood, there will be a check to see if the slice over capacity. We know it's not going to happen, because the sizes are the same: why not always allocate the exact amount of memory that we need and write at the right place directly?

func cipher(bytes []byte, shift int) []byte {
    shiftB := byte(shift)
    line := make([]byte, len(bytes))
    for i, b := range bytes {
        if b >= 'A' && b <= 'Z' {
            b = ((b-'A')+shiftB)%26 + 'A'
        } else if b >= 'a' && b <= 'z' {
            b = ((b-'a')+shiftB)%26 + 'a'
        }
        line[i] = b
    }
    return line
}

We can go even further by noticing that the bytes argument won't be used after we call cipher. So we can re-use this slice instead of allocating a new one!

func cipher(bytes []byte, shift int) []byte {
    shiftB := byte(shift)
    for i, b := range bytes {
        // shift b…
        bytes[i] = b
    }
    return bytes // optional: callers could simply reuse the argument
}

Final words

The code we obtain is more readable, definitely more efficient; and has the same behavior as yours. However, there are still two potential issues with it:

Encoding: we're considering every byte of the input separately, as if it were ASCII; so it will probably not do what you want if the input is in UTF-8.
Input size: if the input has very long lines, then using bufio.NewScanner is a bad idea; see for example this SO question.


First off, as dreza said, work on your variable names.  Secondly, you should really think about using more than one method for solving these types of problems.

All of my suggestions are assuming this is inside a class meant to hold this information.

Now to your code.

The line int group = 5; should be a constant.  I would also rename it to something like numberOfServiceGroups.  So the code line looks like:

const int numberOfServiceGroups = 5;

I would move the dictionary to a class variable and instantiate it in the constructor.  I would also rename it to something like _serviceLookup.  The _ signifying it is a class variable

Instead of using GetRange and RemoveRange, I would change it to use the linq statements Skip([int items]).Take([int items]) and because you are using a for loop, the Skip count can be calculated:

for (var i = 0; i < numberOfServiceGroups; i++)
{
    var servicesToProcess = service.Skip(i * servicesPerGroup).Take(servicesPerGroup);
    // More on this in a minute
}

The nice thing about Take() is that it will not blow-up if you go over bounds, it will just return what is left.  Doing this will eliminate the need to have the catch loop at the end of your method.

I would move the processing of the services into the group to another method.  This reduces nesting.

private void ProcessGroup(IList<Service> services)
{
    var serviceClass = new ServiceClass(services);
    foreach (var currentService in services)
    {
        _serviceLookup.Add(currentService, serviceClass);
    }
}

So your method now looks like:

private void Group()
{
    const int numberOfServiceGroups = 5;

    List<Service> services = FileIO.ReadFeatureFile(@"D:\C Drive\Desktop\input.txt");
    var servicesPerGroup = service.Count/numberOfServiceGroups;
    var serviceToServiceClass = new Dictionary<Service, ServiceClass>();

    for (var i = 0; i < numberOfServiceGroups; i++)
    {
        var servicesToProcess = services.Skip(i * servicesPerGroup).Take(servicesPerGroup);
        ProcessGroup(servicesToProcess.ToList());
    }
}

And your class:

public class ClassName
{
    public IDictionary<Service, ServiceClass> _serviceLookup;

    public ClassName()
    {
        _serviceLookup = new Dictionary<Service, ServiceClass>();
    }

    private void Group()
    {
        const int numberOfServiceGroups = 5;

        List<Service> services = FileIO.ReadFeatureFile(@"D:\C Drive\Desktop\input.txt");
        var servicesPerGroup = service.Count/numberOfServiceGroups;

        for (var i = 0; i < numberOfServiceGroups; i++)
        {
            var servicesToProcess = services.Skip(i * servicesPerGroup).Take(servicesPerGroup);
            ProcessGroup(servicesToProcess.ToList());
        }
    }

    private void ProcessGroup(IList<Service> services)
    {
        var serviceClass = new ServiceClass(services);
        foreach (var currentService in services)
        {
            _serviceLookup.Add(currentService, serviceClass);
        }
    }
}

This should be a good start.  I see a few more things I'd like to do, but they are beyond this scope.

Also note, I have not tested this due to missing classes / information.


Your code runs instantly on my system with 1 million randomly generated numbers. are you sure you are searching for n - x in num_set and not in nums?

Anyway, a couple of Python style pointers:

You can iterate over the set directly, no need to pass both the set and the list:

def has_two_sum(n, num_set):
    res = any(((n-x) in num_set) and 2*x != n for x in num_set)
    return res

Not much point in storing a value to immediuately return it:

def has_two_sum(n, num_set):
    return any(((n-x) in num_set) and 2*x != n for x in num_set)

Boolean values are converted to 0 or 1 when used in an integer setting, so your adding of values is typically written as:

two_sum = sum(has_two_sum(n, num_set) for n in range(-10000, 10001))

If you are going to have a function that contains a single liner, you better give it a great, descriptive name. I don't think that has_two_sum really fits the bill. Perhaps has_two_items_that_sum_to_n or has_two_that_sum_to_n? Alternatively, I think my preferred option here would be to get rid of the function altogether and let code speak by itself, writing the whole thing as two nested comprehensions:

two_sum = sum(any(n - x in num_set and 2*x != n for x in num_set)
              for n in range(-10000, 10001))

There is a school of thought that considers nested comprehensions to be confusing (e.g. the Google Python style guide doesn't allow them), but I think this case is simple enough, YMMV.


I don't know of any coding standards or other reasons why you should have to move it higher. Generally it's just personal preference and whichever is more readable.

As for the fact that you'd need to create a variable unnecessarily in some cases, creating a variable like this uses very little memory so it shouldn't be an issue unless the function is being looped over thousands of times.

You could also consider another option, which is to use a ternary rather than mutating a variable:
let prefix = phoneNumberString.startsWith('49') ? '49' : ''


How to find position (array index ) of a number in a given array?

Indent the Code

Most computer code is indented, in some languages indentation is used to show the level of complexity of the code, in other languages the code won't work properly unless it is indented.

Declare the Variables as They are Needed

The integer variable i can be declared in the for loop and that will limit the scope to just the for loop.

for(int i = 0; i < 10; i++)
{
    if(arr[i] > num)
    {
        position = i - 1;
        break;
    }
}

Horizontal Spacing

To make the code more readable, put spaces between the operators and the operands as shown above in the for loop example. Squashing all the code together makes it very difficult to understand what the code is actually doing.

Performance

First run the -O3 optimizer during compilation and linking. If the program were more complicated than it is then use a profiling tool such as gprof.

Linear searches are known to be a slower way to do things.

I think the position reported is off by one, if I was using this code to do an insertion sort, I wouldn't subtract one from position.

Shorten the Code.

There are 2 shorter ways to subtract 1 from position.

    --position;

and

    position -= 1;


There are a number of things that I see that may help you improve your program.

Avoid needless recalculation

There is a lot of calculation within the calc_even routine that doesn't need to be repeated for every step through the loop.  Also, there are two separate loops in main -- one the calculates and stores the results and another that prints them.  There is no reason that the results couldn't simply be generated and printed within a single loop.  In addition to being more efficient in terms of computation, it would also use less memory since there would be no need to save the results.  They can simply be calculated and discarded.

Prefer const to #define

The use of #define A 19 is better expressed as const int A = 19; because the latter has a defined type, while a #define does not enforce any notion of type.

Think of the user

The program as currently coded needs to be recompiled if we want to try any other pair of numbers.  It would be better to accept those parameters from the command line rather than making them fixed.

Use library functions

The program calculates both a quotient and remainder for a given pair of numbers.  There is already a library function div that does that in a single step.

Understand integer conversion rules

This code can be greatly simplified:

int extra_add = 1;
if (no > remain) {
    extra_add = 0;
}

A boolean value, when converted to an int in C is defined as 0 if it is false and 1 if it is true, so that bit of code can be expressed instead as:

int extra_add = (no <= remain);

Use more descriptive names

The names you have chosen are generally not too bad, but A, B and no are not very good names.

Reduce complex logic

The calc_even calculations are entirely too complex for the requirements of the program.  Think first about how you'd do this with pencil and paper.  If we have 5 bins and 19 numbers, we divide to get a quotient (3) and remainder (4).  So that means that all bins will have at least 3 numbers and 4 of the bins will have one extra.

Putting it all together

Applying all of these suggestions, an alternative might look like this:

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

int main(int argc, char *argv[])
{
    if (argc < 3) {
        puts("Usage: divide number bins");
        return 0;
    }
    int number = atoi(argv[1]);
    if (number <= 0) {
        puts("Error: number must be >= 0");
        return 1;
    }
    int bins = atoi(argv[2]);
    if (bins <= 0) {
        puts("Error: bins must be >= 0");
        return 1;
    }
    div_t qr = div(number, bins);
    int begin = 0;
    for (int i=0; i < bins; ++i) {
        int end = begin + qr.quot + (i < qr.rem);
        printf("Grp %d: %d %d\n", i+1, begin, end-1);
        begin = end;
    }
}


Bug
Letters J & K, U & W, and V & X have the same pattern. This is not what the specification says: either I & J and U & V shares the same pattern, or none of the letters do.
Style
String literals ain't comments. If you want two lines of comments, you start your two lines with a # each. Also take the habit to put a space after the # sign, it eases readability.
You also don't need to put parentheses around simple conditions.
Lastly, PEP 8 recommends to use ALL_CAPS to name constants, like LOOKUP.
Generators
Concatenating strings using += is slow as strings are immutables and Python need to copy the whole string each time you add a bit at the end. For better performances, it is advised to use ''.join. To do this, it is easier to separate each function into two: one that iterates over the input and joins the converted output, the other that generates the converted output. Something like:
def encrypt_letter(letter):
    """Convert a plain-text ascii letter into its Bacon's form.

    Let symbols and non ascii letter fail through gracefully.
    """
    return LOOKUP.get(letter.upper(), letter.lower())

def encrypt(message):
    """Encrypt a message using Bacon's cipher"""
    return ''.join(map(encrypt_letter, message))

One more thing to note with this implementation: you shouldn't require that the input is properly formatted, you should enforce it in your functions (usage of upper and lower within your function, not before its call)
Do-while
In Python, a do-while loop is emulated using something along the lines of:
while True:
    do_something()
    if ...:
        break

In your case, having the if directly as the first action of the while and an else: break, you just need a simple while loop:
while i < len(message) - 4:
    substr = message[i:i + 5]
    ...


Avoid recursion, avoid putting the accumulator out of the function that fills it.

My favourite phrase: Every recursive algorithm can be rewritten without recursion. In worst case, using one (extra) stack.

function renderRoutes(menuItems) {
  let accumulator = [];
  let queue = [];
  queue.concat(menuItems);
  while (queue.length > 0) {
    const item = queue.shift();
    accumulator.push(route(item))
    queue.concat(item.children);
  }
  return accumulator;
}

The route(item) is the same as your <Route....


You never use slider.selector, so what's the point?
jQuery instances should be "cached", otherwise you are creating new jQuery object each time you call $() function.
This code permits only one slider per page. What if you need more? Will you copy-paste the whole thing?
This is not configurable at all. You have to change the objects source, just to change the way animation works.
jQuery is not really necessary here. You actually need it only for animations, which is not jQuery's strong point.
Slider object ends up in global scope.


Ruby script to deactivate or add users to database table

Some high level advice:

Fix your indendation.  For example, the indentation is randomly increased on this line: choice_client_ice = gets.chomp.to_i.  I mention this only because there is a lot of deep nesting here, which is confusing enough without incorrect indentation. Which brings me to...
Try to rewrite this entire thing, allowing yourself only 1 level of indentation (or 2, at most).  This will force you to separate high level logic and implementation detail, by pulling implementation out into its own functions.
Try to rewrite it, keeping your program logic and "views" separate.  All the puts statements are "view" code -- they are to your command line app what html files are to web apps.  Think about writing functions with names like main_menu_selection, which do nothing but present the user with his choices, get his selection, and return it.


Writing null-safe code to set form values

(document.getElementById(arr[i].id) || 0).value = arr[i].value;

In this code there is a pointless assignment when the element is not found.
In this case, the 0 gets wrapped into a temporary object,
and the assignment will work, but it will be pointless,
it's result will be thrown away.
This assignment is merely a side effect of the shortcut,
it has no purpose of its own.

Every operation in a program should be intentional, purposeful, and this shortcut violates that. As such, I consider this a dirty hack. Don't use it.

When in doubt,
go for the more intuitive and readable solution.
The first example in your post is slightly longer,
but it's simple and clear: there's no question about what will happen.

The second way,
although shorter,
may not be obvious for everyone.

Keep in mind that code is read far more times than it’s written.
It's better to favor a technique that's clear and easy to understand to something "clever" but potentially confusing / obscure.

Additional excellent recommendation by @GameAlchemist, verbatim:

  1) for optimisation purposes, the if is faster. and more importantly 2) a piece of code should be as much self-documenting as possible. Even if (element) is better written if (element != null) (which makes obvious the defensive check against getElementById returning null)


Finding an item name starting or ending with from a list

Use first class functions, not hardcoded strings:

def _isobjectInList(lst, name, criteria=str.startswith):
    """
    >>> _isobjectInList(['foobaz','null'],'foo')
    ['foobaz']
    """
    return [i for i in lst if criteria(i, name)]

also give it a better name


Yes, the guards make !! safe, but your code has other issues, stylistic and functional:

Unneeded pointful style

First, it's often a good idea to try running your code through HLint.  Doing so, you get the following suggestion:

  pushToTop.hs:9:52: Error: Avoid lambda
  Found: \x -> snd x
  Why not: snd
  1 suggestion

Indeed, why not. If we're to use point-free style for this, we could also simplify

filter (\x -> fst x /= i)

to

filter ((/= i) . fst)

At some point, point-free style can get difficult to read, but in this case I think it is still readable.

Parentheses that can be replaced with a use of $

Right here:

(map (\x -> snd x) . filter (\x -> fst x /= i)) zipped

Using $, you could also inline zipped non-awkwardly:

map snd . filter ((/= i) . fst) $ zip [1..] xs

Incorrect base case

Shouldn't any index on an empty list be considered an error? As is, you're completely ignoring the index. For consistency, I would make the first case return Nothing.

Unnecessary case

This case is already handled by the latter case:

  | i == 0 = Just xs

It can be safely removed.

Failure to work on infinite lists

The operation you have defined (move an element at a certain index to the front) is well-defined on infinite lists, but your code fails to handle the case. In particular, length will not terminate on infinite lists. The current structure of your code cannot handle this. Rewriting it to make explicit the recursion and to avoid calculating the length should make it work on infinite lists.

Test case:

ghci> fmap (take 20) $ pushToTop [0..] 12
[12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19]