To summarize, the things I expect could be improved include documentation (docstrings and/or comments), variable names (especially the ones that don't convey much, or convey things that don't match behavior), the coupling of functions (write_file may misbehave if sys.argv[1] is wrong, or if its input isn't sorted), and a couple of places that using some specialized collections could clean things up.

The first things I dwell on as a reader are the names. What in the world is iln vs ili, etc. Is this a foreign language? An acronym in heavy usage in your field? If neither, it's generally considered more pythonic to use longer with more obvious meanings. (Note that even the longer attribute names these get on SkuSequence instances are a little abbreviated for my taste.) This can be mitigated with comments or docstrings, but I prefer to have the code stand on its own as much as possible.

The use of OrderedDict in sort_sequence seems fishy to me. Typically OrderedDict is used to remember the insertion order, but here you are sorting the items to create essentially a SortOrderedDict. What utility does this provide that a regular dict does not? Perhaps this should be documented in sort_sequence's docstring, or perhaps the sorting should be handled in convert_to_csv. By the way, the dance to ensure that dict[sku.inv_loc_id] exists would be better written by using a collections.defaultdict(dict) and just pretending it's already there. It also shouldn't be called dict as that shadows the builtin of the same name.

The interface or name of consume_data seems a little off. Calling it consume_data suggests that it could take the output of csv.readlines() instead of taking the name of the file that it then reads. Furthermore, if the file is truly csv, you're better off using a real csv parser such as that in the csv module, especially if any values could ever contain a comma. Finally, unless you are discarding some of the values, the creation of SkuSequence could take SkuSequence(*attrs) or even SkuSequence(line.split(",")).

Alternately SkuSequence could be rewritten to accept a list or tuple, or perhaps even a collections.namedtuple. Using a namedtuple might clean up some code I don't particularly like - namely the very repetitive parts of __init__ and get_str_attrs. My gut tells me it is worth exploring using namedtuple more closely, but I haven't proven it yet.

Referring directly to sys.argv[1] in write_file also seems a little unusual to me; it tightly couples it to the script rather than letting it be used in library, or even with a better command-line parser. Note that by contrast consume_data accepts the name of the file, but write_file magically divines it. It doesn't bother me as much that write_file modifies the name by adding _resequence (although it should probably use helpers from os.path for dicing and splicing the filename); make sure the parameter (that it doesn't yet take reflects) this in its name, say source_file or base_name. Coupling would probably be even lower (better) if main decided the name (even if by calling a new helper function); as this would allow the script to function "in place" if ever directed to.


Algorithm to calculate semi perfect integers, lack of efficiency

Funny enough I was working on the same problem.  My performance issue is not the Semi-Perfect part, but the check of abundancy.

You can call this (C#) function to check for a number being SemiPerfect.

static bool IsSemiPerfect(BigInteger delta, BigInteger[] d, BigInteger[] dSum, int index, BigInteger sum)
{
    if (sum == delta)
        return true;

    if (index >= d.Length || sum > delta || delta > (dSum[index] + sum))
        return false;

    for (int i = index; i < d.Length; i++)
    {
        if (IsSemiPerfect(delta, d, dSum, i + 1, sum + d[i]))
            return true;
    }

    return false;
}

The parameters are the following:

delta: sum of the divisors - n
d: divisors, descending sorted!
dSum: a cached calculation of the remaining sum

BigInteger[] dSum = new BigInteger[d.Length];
for (int i = d.Length - 1; i > -1; i--)
{
    BigInteger sum = 0;
    for (int j = divsIndex - 1; j >= i; j--)
        sum += d[j];
    dSum[i] = sum;
}

index: 0, used for recursion
sum: 0, used for recursion

The code runs much faster compared to the other answer, because of 3 major cuts in the search tree and a slightly different approach of the problem.  It is also optimised to find an answer in a progressive way.

A check of a big N = 190000006875 with 119 divisors runs well below 1 second.  I didn't do real profiling but my performance bottleneck is really somewhere else.  It might be NP, but very well doable this way.

It seems that posting a reply in C# code on a Java topic is a bit of bad behaviour.  To make it up I'll give some slightly off-topic but cool code to find really big record breaking weird numbers in Java, using Sidney Kravitz's algorithm.

public static BigInteger getPossibleWeirdNumber(int bits)
{
    BigInteger q = BigInteger.probablePrime(bits, new Random());
    int k = q.bitLength() - 1;
    BigInteger power2k = BigInteger.valueOf(2).pow(k);
    BigInteger r = ((power2k.multiply(q)).subtract(q.add(BigInteger.ONE))).divide(q.add(BigInteger.ONE).subtract(power2k));
    if(r.compareTo(power2k) > 0)
    {
        if(r.isProbablePrime(1000000) && q.isProbablePrime(1000000)) //Some final checking on primes
        {
            BigInteger weirdNumber = (BigInteger.valueOf(2).pow(k-1)).multiply(q).multiply(r);
            return weirdNumber;
        }
    }
    return null;
}

public static BigInteger getWeirdNumber(int bits)
{
    BigInteger r = getPossibleWeirdNumber(bits);
    while(r == null)
        r = getPossibleWeirdNumber(bits);

    return r;
}

The only problem is that this algorithm does not find odd weird numbers. It's easy to see why: The \$2^{k-1}\$ always will be an even number. Multiplying with an even number always results in an even number, so Sidney Kravitz's trick will help you find large weird numbers, but no odd ones. That's why I manually started looking.

By the way, the reason I used C# is the more clean look of the code when using BigInteger. The operator overloading in .Net is lovely.


Keeping track of byte count in a binary protocol handler

Some variables, such as socketAlive and hexforlog, aren't being used.

Another quirk I noticed is that you don't really take advantage of the capabilities of DataInputStream.  If you just want to read a byte at a time, any InputStream can accomplish that.  DataInputStream gives you the ability, for example, to read two bytes and interpret it as an unsigned 16-bit number using .readUnsignedShort().  I'm guessing that that is what your twoBytesToInt() does.  Hopefully, the protocol uses big endian numbers so that you can take advantage of .readUnsignedShort().

Your loop is structured such that any 0xfe byte in the input stream will be treated as the end of a packet.  That means that no 0xfe byte can ever appear in the payload of a message.  Most binary protocols are not designed that way — you should obey the message length fields instead.

Anyway, your code is one long function!  It desperately needs some kind of abstraction.  bytecounter and all of the concerns surrounding it can go away!  The code proposed below compiles, but obviously I can't test it.

Packet.java: This is just a "dumb" struct.

public class Packet {
    public byte som,
                packetClass,    // "class" is a Java keyword
                source,
                dest,
                msgPrgNumber,
                spare1,
                spare2,
                spare3;
    public int  length,         // 2-byte unsigned short
                numMsgs;        // 2-byte unsigned short

    public static class Message {
        public int msgId,
                   length;
        public byte[] payload;
    }
}

PacketInputStream.java: This constructs Packets from the data stream.

import java.io.*;

public class PacketInputStream {

    //////////////////////////////////////////////////////////////////////

    public static class MalformedPacketException extends Exception {
        public MalformedPacketException(String errMsg) {
            super(errMsg);
        }
    }

    //////////////////////////////////////////////////////////////////////

    private DataInputStream in;
    private Packet packet;
    private int messageNumber;

    public PacketInputStream(DataInputStream in) {
        this.in = in;
    }

    /**
     * Reads a 12-byte packet header.
     */
    public Packet readHeader() throws IOException {
        this.packet = new Packet();
        this.messageNumber = 0;
        do {
            this.packet.som       = in.readByte();
        } while (this.packet.som != 0xfd);
        this.packet.packetClass   = in.readByte();
        this.packet.source        = in.readByte();
        this.packet.dest          = in.readByte();
        this.packet.msgPrgNumber  = in.readByte();
        this.packet.spare1        = in.readByte();
        this.packet.spare2        = in.readByte();
        this.packet.spare3        = in.readByte();
        this.packet.length        = in.readUnsignedShort();
        this.packet.numMsgs       = in.readUnsignedShort();
        return this.packet;
    }

    public boolean hasMoreMessages() {
        return this.packet != null && this.messageNumber < this.packet.numMsgs;
    }

    public int getMessageNumber() {
        return this.messageNumber;
    }

    public Packet.Message readMessage() throws IOException {
        Packet.Message msg = new Packet.Message();
        msg.msgId   = in.readUnsignedShort();
        msg.length  = in.readUnsignedShort();
        msg.payload = new byte[msg.length];
        in.read(msg.payload);
        return msg;
    }

    /**
     * Requires the next input byte to be the end-of-packet marker.
     */
    public void readEndOfPacket() throws IOException, MalformedPacketException {
        byte b;
        if ((b = in.readByte()) != 0xfe) {
            throw new MalformedPacketException(String.format("Expected 0xfe, got 0x%02x", b));
        }
    }
}

PacketOutputStream is left as an exercise for the reader.

Consumer:

private void processMessage(Packet.Message msg) {
    switch (msg.msgId) {
      case 50:
        this.processMessage50(msg);
        break;
      case 70:
        this.processMessage70(msg);
        break;
    }
}

public void run() {
    try (DataInputStream  dataIn   = new DataInputStream(in);
         DataOutputStream dataOut  = new DataOutputStream(out)) {
        PacketInputStream  packIn  = new PacketInputStream(dataIn);
        PacketOutputStream packOut = new PacketOutputStream(dataOut);

        while (true) {
            Packet p = packIn.readHeader();

            // Read one message before writing the acknowledgement,
            // because that's what the original code did.  You
            // could simplify this by acknowledging immediately
            // after reading the header instead.
            Packet.Message msg = packIn.readMessage();
            packOut.writeAck(p);
            this.processMessage(msg);

            while (packIn.hasMoreMessages()) {
                this.processMessage(packIn.readMessage());
            }
            packIn.readEndOfPacket();
        }
    } catch (PacketInputStream.MalformedPacketException mpe) {
        mpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}


This is mostly personal preference, but, I usually stack the @matches  in descending size:

// @match *://*.stackexchange.com/review*
// @match *://*.stackoverflow.com/review*
// @match *://*.superuser.com/review*
// @match *://*.serverfault.com/review*
// @match *://*.askubuntu.com/review*
// @match *://*.stackapps.com/review*
// @match *://*.mathoverflow.net/review*

into:

// @match *://*.stackexchange.com/review*
// @match *://*.stackoverflow.com/review*
// @match *://*.mathoverflow.net/review*
// @match *://*.serverfault.com/review*
// @match *://*.askubuntu.com/review*
// @match *://*.stackapps.com/review*
// @match *://*.superuser.com/review*

Just looks nicer, I suppose.

var title = document.title.split(' - ');:

You don't use title for anything other than title[1], so just use var title = document.title.split(' - ')[1] instead.

.replace(',',''): You should have a space after ','.

You could consider replacing the .length style for loop with a for (var i in reviewItems) style loop. If not, you can also declare reviewCount in the for loop like: for (var reviewCount = 0, i = 0;.

var details = {
        title: document.title,

Desktop Notifications - Code Review Stack Exchange sounds a little bulky and over-the-top. Review Items is a better name for it, and you could consider removing Stack Exchange, but, consider the effect that would have on MSE.

I can't see the point in using notifications as an array, as it should really just have the one notification.

if (reviewCount > 0) {
    notifications.push(reviewCount + ' Review Items');
}
if (notifications.length) {
    var details = {
        text: notifications.join('\n'),

if (reviewCount > 0) {
    notification = reviewCount + ' Review Items';
}
if (notification) {
    var details = {
        text: notification,

or even just move reviewCount + ' Review Items' into details, like:

if (reviewCount > 0) {
    var details = {
        text: reviewCount + ' Review Items',

As of ECMAScript 5, the default radix used in parseInt is supposed to be \$10\$, before that, \$0\$ would get parsed as a octal number instead of a decimal number, and, as it seems, you can just omit that optional radix argument entirely. Although, as @EthanBierlein pointed out in the comments; MDN recommends not to omit it.


Drilldown navigation menu by replacing divs

By dropping in some generic classes and data attributes like so:

Choose a Department

Technology

Vehicles

menuContainer marks everywhere that's needs to be hidden or shown

menuItem marks everything links somewhere else in the menu

data-target is your link data

Now you can reduce your javascript to this:

$(document).ready(function () {
    $('.menuContainer').hide();
    $('.first').show();

    $('.menuItem').click(function () {
        var target = $(this).attr("data-target")
        if(target){
            $('.menuContainer').hide();
            $('.'+target).show();
        }
        return false;
    });
});


Remove redundant code

    if (s.length() < 2) {
      return false;
    }

This is unnecessary.  If s.length() is less than two, then 1 <= s.length() / 2 will be false, as 1/2 is 0 in integer math.  So it will drop through to the final return.

Say what you'll do

      if (value == 0) {
        break;
      }

You could write this more readably as

      if (value == 0) {
        return false;
      }

But it's not necessarily so that this would ever be called.  It's also not clear that this is correct behavior.  For example, this would break an octal or hexadecimal integer that is formatted with a leading zero.

Don't repeat work

     while (sb.length() < s.length() && sb.toString().equals(s.substring(0, sb.length()))) {
        sb.append(++value);
      }

This doesn't require a StringBuilder.  Consider

      int i = 0;
      while (i < s.length()) {
        String number = String.valueOf(value);
        if (!s.substring(i, i + number.length()).equals(number)) {
          break;
        }
        i += number.length();
        value++;
      }

Instead of comparing two ever lengthening strings, this compares just the string representation of the current value.

Does this matter?  You choose to parse into a long value.  That only matters if the number is more than ten digits.  Every single nine-digit value will fit into an int.  This suggests that the beautiful number can be at least twenty digits long.

This doesn't quite fit in the logic of your original program, so I rewrote it as a helper method.

    public static boolean isValidBeautifulNumber(String s, long prefix) {
        for (int i = 0; i < s.length(); ) {
            String number = String.valueOf(prefix);
            if (!s.substring(i, i + number.length()).equals(number)) {
                return false;
            }

            i += number.length();
            prefix++;
        }

        return true;
    }

    public static boolean isValidBeautifulNumber(String s) {
        for (int substringSize = 1; substringSize <= s.length() / 2; substringSize++) {
            if (isValidBeautifulNumber(s, Long.parseLong(s.substring(0, substringSize)))) {
                return true;
            }
        }

        return false;
    }

This significantly simplifies the logic.

If each \$a_i\$ matches the original string, we make it through the loop and return true.  If any fail to match, we return false.


The basic structure isn't bad, but is more structured programming in the C or PASCAL tradition than OOP.
OOP discussion
You currently have three types of expressions that need different evaluation behaviour, but use only one class Expression. You implement this differing behaviour in your main class, using a switch on a type code.
Instead, make Expression an interface (or a super class if you aren't comfortable yet with interfaces) with an evaluate() method, and three classes implementing that interface: NumberExpression, SumExpression, and ProductExpression, each with its own way of doing the evaluate() method, with its own fields, and its own constructor (using only the parameters necessary to that type of expression).
Then, there's no need for a type code any more. The Java OOP system does the switch for you. The evaluation of an expression happens where it should happen, in the expression's own class, and you can eliminate the main evaluate() method. And it's totally easy to create additional expression types like difference, quotient or power. You just add another class.
The main idea of OOP is that an object's behaviour should be implemented in the corresponding class, especially if the behaviour depends on something you'd call a type.
Minor points
The type code you are currently using (if it weren't made obsolete by the OOP refactoring) should not be a list of integer constants, but become an enum.
Avoid public fields, make them private, and if really needed, create getter and setter methods. Fields represent some internal state of an object, and nobody outside should manipulate that state, or even have any assumptions on the inner workings of a class. Communication should only happen by calling public methods. (Fields can be viewed as private sticky notes of some clerk, they're not meant to be seen or modified by anybody else, and even asking this clerk about one of these notes seems like bad habit.)
If you have distinct cases how to create instances of a class, create multiple constructors. Your single Expression constructor is a "one-size-fits-all" one. When creating a constant number, you still have to supply two irrelevant Expressions (given as null in your example), and when creating a sum or a product, you are forced to provide an equally irrelevant value parameter.


Reading three rows of six tab-separated numbers

the first use can be replaced with:

while(in >> s) {
    data.push_back(s)
}

the second case is much more readable with a simple if else:

std::ifstream f;
if(argc >= 2 && 0 != strcmp("-", argv[1])) {
    f.open(argv[1]);
    if (!f) {
        std::cerr << "Error opening " << argv[1] << ": "
                  << strerror(errno) << std::endl;
        return 1;
    }

}
std::istream &in = f.is_open() ? f : std::cin;


Doubly linked list reimplemented with smart pointers

Summary

This is obviously a personal opinion, but I don't really like the interface you've defined for your list.  By defining your methods in terms of a shared_ptr<Node>, you're making the caller responsible for constructing Nodes.  It seems like Node should be an implementation detail of your list.  Otherwise, since the caller has complete access to the Node they can iterate the list and modify it without the LinkedList class being called at all.

I'd define the interface in terms of the Data that is to be stored, currently this is an int, so you would have something like this:

void append(int newValue)

Or you may want to define your list in terms of a template and take in a pointer of the relevant type.  This could be a shared_ptr if ownership of the data doesn't pass solely to your list, or it could be a unique_ptr if the node that references it will be the owner of the Data.

Append

Looking at your current implementation, what happens if a Node is passed in that already has its prev and next pointers populated (with the given interface I could assume that I could insert a Node chain).  These pointers aren't checked, they're overwritten.  This is part of why I don't like the interface...

Remove

What happens if you're asked to remove a node that isn't in the list?  Currently nothing.  It feels like this method should either be returning an indicator that the object has been removed, or more likely throwing an exception to indicate that it hasn't..


Calculating area of different figures on a case by case basis

First, note that finding the area of an isosceles triangle is the same formula as finding the area of right triangle.  Both are 1/2 * base * height.

You are mixing object oriented classes and imperative programming.  This usually happens as you are first learning about classes.  Here is are two alternate structures to your code:

First option, you can ignore classes.   The only commonality between a triangle and an octagon is that both have an area() method.   There is no common data: a triangle has no radius and an octagon has nothing but a radius.  You can make functions like triangle_area(base, height), octagon_radius(radius).  Both return areas.  Just doing this would simplify your code.

Second option, you use classes anyway.  You might do this if you expect more commonality in the near future.  For example, if this is becoming a drawing program then a Figure might be a class that "has a x,y center, current color, a move command, a draw command and an area function."  This code would have code common to all figures in class Figure and would have empty (or virtual) routines that are 'parts any subclass needs to implement to considered a Figure'.

Here is some a code outline to ponder:

 class Figure:
     def area(self):  # return the area of this figure
         raise NotImplementedExeception('subclass must have an area() function')

 class Triangle(Figure):   # inheritence is the promise to follow the superclass API
     def __init__(self, base, height):
         super().__init__()   # this is boilerplate
         self.base, self.height = base, height

     def area(self):
         return self.base * self.height / 2

     @classmethod  # used for custom constructors
     def ask_right(cls):
        print("Это нахождение площади прямоугольного треугольника")
        a1 = float(input("Введите первый катет  "))
        b1 = float(input("Введите второй катет  "))
        return cls(a1, a2)   # return a new triangle

     @classmethod
     def ask_isosceles():
        ...

def main():
        print("Для выхода нажмите Enter")
        a = int(input("1. Площадь прямоугольного тр. \n2. Площадь равнобедренного тр. \n3. Площадь квадрата \n4. Площадь ромба  "))
        if a == 1:
            fig = Triangle.ask_right()
        elif a == 2:
            fig = Triangle.ask_isosceles()
        elif a == 3:
            fig = Octagon.ask()

        print f"Area is {fig.area()}")

In summary, using classes to organize your code makes more sense if you are doing more than just one item.   The real power comes from being able to write functions like:

def redraw(list_of_figures):
    clear_screen()
    for fig in list_of_figures:
        fig.draw()   # which might be Circle.draw(), Triangle.draw() or another subclass

and adding a new subclass, say Pentagon(Figure), without having to change the redraw() function.

Classes can be hard to get your head around; that is normal.

Keep hacking!  Keep notes.


Checkered flag: a modular usage of Tkinter's geometry management

OOP is not merely creating classes: it is also about a thoughtful design. This becomes even more true when it comes to tkiner. I mean you created 2 separate classes to refer to tk.Label() and tk.Frame() classes. This is not the best option for your context as that design is misleading in that it makes the reader of your code think you are trying to create custom Label() and Frame() widgets (which is not what the application actually does).
Also, from the OOP perspective, the lines of code spanning from mainWindow = tk.Tk() to the end do not comply with the OOP philosophy (they are mere sequential instructions not even wrapped within a function)
You say the goal of your application is to play with the tkinter geometry managers. Actually there are 3 of them: place(), pack() and grid(). You are using only one of them. The ideal  is to use the 3 of them, but in my solution below I will use only 2 of them as the context is not suitable for a smart use of place().
You can use pack() for the frames and grid() to manage the labels.
It is better that you attach your widgets to a parent widget instead of the instance of the class you use. Example: instead of coding something like self.frame1 = tk.Frame(self), it would be more appropriate to write self.frame1 = tk.Frame(self.some_more_specific_parent)
There is an easier way to play with the flag (color) you are using as a background color for the label widgets (see my solution below)
It is hard, when launching your application, to see where is the main window and stretch it to make it visible. So for the sake of a better user experience, you should set default dimension to it and keep it resizable (see my solution below)
No need to use the pack() geometry manager the way you did.

Based on the elements stated above, and based on some of Tkinter best practices, I would like to suggest you the solution below which requires, logically, only one class, and refactors your code in a cleaner way:

import tkinter as tk

class SimpleGeometryManagersDemo(tk.Frame):

    def __init__(self, master):
        self.master = master
        super().__init__(self.master)
        self.configure_gui()
        self.create_widgets()

    def configure_gui(self):
        self.master.title('Simple Geometry Managers Demo')
        self.master.geometry('400x200')

    def create_widgets(self):
        self.create_two_frames()
        self.create_two_labels_per_frame()

    def create_two_frames(self):
        self.frame1 = tk.Frame(self.master)
        self.frame2 = tk.Frame(self.master)
        self.frame1.pack(fill=tk.BOTH, expand=1)
        self.frame2.pack(fill=tk.BOTH, expand=1)

    def create_two_labels_per_frame(self):
        self.create_two_labels(self.frame1, 'black')
        self.configure_columns_and_rows(self.frame1)
        self.create_two_labels(self.frame2, 'white')
        self.configure_columns_and_rows(self.frame2)

    def create_two_labels(self, parent, color):
        self.label1 = tk.Label(parent, bg=color)
        bg_color = 'white' if color == 'black' else 'black'
        self.label2 = tk.Label(parent, bg=bg_color)
        self.label1.grid(row=0, column=0, sticky='nswe')
        self.label2.grid(row=0, column=1, sticky='nswe')

    def configure_columns_and_rows(self, parent):
        parent.rowconfigure(0, weight=1)
        parent.columnconfigure(0, weight=1)
        parent.columnconfigure(1, weight=1)

def main():
   root = tk.Tk()
   geometry_managers_demo = SimpleGeometryManagersDemo(root)
   root.mainloop()

if __name__ == '__main__':
   main()


Getting rid of HTML file inputs once and far all

I know my answer comes a bit late, but I thought I'll share. I don't really get the problem you're facing. What's wrong with doing the regular styling of label, as in my example?

Answering your questions:

  @CᴴᵁᴮᴮʸNᴵᴺᴶᴬ Does it work for all browsers?

<label> was introduced in HTML4, even IE6+ can support it.

  My reason for creating this script is to allow the buttons on a jQueryUI dialog to work as file upload triggers (...)

Don't use JavaScript (and especially it's libraries) for elements and functionalities that you can create with pure (X)HTML and CSS. But if you have to do the file upload with a jQuery UI buttons or any other element and you don't want to create and style a <label>, you can simply do:

var fileInput = document.querySelector('input[type="file"]');

document.querySelector('input[type="button"]').onclick = function() {
  fileInput.click();
}
fileInput.onchange = function() {
  this.form.submit();
};

Where input[type="file"] bear display: none and input[type="button"] can be any element that we'd like to trigger file upload action. Take a peak into my working example.


Socket connect realization: gethostbyname or getnameinfo

This works for me:

int connect2(const CStringA& address, int port) {
  struct sockaddr_in servAddr;
  /* open socket */
  SOCKET handle;
  if((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    return ERROR;
  //gethostbyname by getaddrinfo replacement
  ADDRINFO hints;
  ZeroMemory(&hints, sizeof(hints));
  hints.ai_flags = AI_ALL;
  hints.ai_family = PF_INET;
  hints.ai_protocol = IPPROTO_IPV4;
  ADDRINFO* pResult = NULL;
  int errcode = getaddrinfo((LPCSTR)address, NULL, &hints, &pResult);
  if(errcode != 0)
    return ERROR;
  memset(&servAddr, 0, sizeof(servAddr));
  servAddr.sin_family      = AF_INET;
  servAddr.sin_addr.S_un.S_addr = *((ULONG*)&(((sockaddr_in*)pResult->ai_addr)->sin_addr));
  servAddr.sin_port        = htons(port);
  if(::connect(handle, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0)
    return ERROR;
  return OK;
}


Simple PHP Router for home grown MVC framework

Welcome to code review!  Don't worry, we don't get tired of these things (or at least I don't).  In retrospect I would have loved to have something like this in my early days - and it's still useful to me now even though I'm well past my early years.

I'll just start from small items and work my way up.  To be fair, I'm a stickler for the little things.  You'd be surprised how often the little things can make a big difference in the long run, especially when you are talking about the core part of a system (such as this).  So let's start with the little stuff:

You don't have to use braces and indent after a namespace.  This is actually the only place I suggest not indenting or including braces.  The reason is because it simply pushes the indentation of your entire file up one level unnecessarily.  Just end your namespace declaration with a semi-colon and leave the use lines and class definition without indentation.
The usage of the redirect method in your router is unclear, and as such I'm not even 100% sure if your redirect method even belongs in the router.  That sounds more like something that should be part of the object that manages the HTTP response (which would also handle things like 404 errors and what not).  Then again it seems like the only part that actually does routing, so maybe the issue is your name.  Perhaps it should be called route()?  That makes sense to me: in your index file you would call $router->route() and expect a controller to be executed.
In the redirect method you use a loop over the routes, which is costly (in terms of performance).  A better option would simply be to do a lookup via isset.  if (isset($this->_url[$url])) {}.
You have no handling of error conditions.  What happens if someone tries to redirect to a route that doesn't exist?  What happens if there is no @ in the route?  It is best to explicitly check for such situations and throw an exception so that you can provide clear details to the developer.
Similar, enforcing some consistency in your data can be helpful.  Your router obviously assumes that routes start with a slash, so you should enforce that in the addRoute method.  This will take care of a whole class of subtle but hard-to-identify bugs down the road.
Your names are a bit inconsistent.  See addRoute vs parsecommand.  Camel case for one but all lowercase for the other.  Pick a convention and stick to it.  If in doubt use PSR.
Your variables names could use a bit more consistency too. Instead of using a private variable named _urls in your router, I think routes would make much more sense.  Also (this could be a matter of preference), you don't really need the leading underscore in the name of private variables.  IMO, that's a convention that primarily belongs in languages that don't have enforced visibility rules.
Writing docblocks will help a lot in the long run.
Your parsecommand method returns whatever the controller returns, but the redirect method ignores the return value.  This makes sense because your controllers don't actually return anything.  If the controllers will always print directly, then there is probably no reason for paresecommand to return anything.

Some larger suggestions:

Dependency Injection:

As I mentioned before, you don't really want to access the $_GET super global (or other super globals) directly.  It is better to use a separate class to get that information out.  It all boils down to separation of concerns.  As a simple example of where this can break down, how would your current setup handle things if you decided to add a command line component?  Perhaps that would have a completely separate router, but perhaps you would rather use the same system you already have in place.  In that case your current setup simply won't work - it is hard-coded to look at $_GET, which doesn't exist in the command line environment.  Instead you could have your router expect to receive a request object in the constructor, and that request would tell it the requested URL.  In the case of a normal web request the request object would simply get the URL out of the $_GET super global, but for a command line request you would perhaps send in a different request object that gets the url out of the command line arguments.

This all boils down to the concept of dependency injection - instead of directly creating/managing your own dependencies, you let the person in charge of you give the necessary dependencies.  This makes the code much more flexible.  It also allows you to create integration and unit tests, which is otherwise impossible when you are directly hooked into the request itself.  For the moment of course I wouldn't suggest switching completely over to managing your system with a full dependency injection container.  However, if you get in the habit of separating out your services a bit more and (in this example), expecting a request object to come in with the constructor, you'll start getting in much better habits.  While you are keeping things simple, now is the time to start learning about dependency injection and test writing.

Autoloading

In your router you require the controller PHP file directly.  This implies that you don't have autoloading setup.  Setting that up in your bootstrap process will save you a lot of trouble.  For instance, your current setup requires your controllers to all live in the same directory.  With an autoload setup that maps namespaces to file directories, you can remove that requirement and make it easier to organize your app.  Then you could do things like:

$routes->addRoute('/shopping/products', '\Shopping\ProductController@index');
$routes->addRoute('/support/contact', '\Support\ContactController@index');

Presumably your files would then be located in (something like) Controllers/Shopping/ProductController.php, Controllers/Support/ContactController.php, etc...  This will help you keep your app organized better if it starts growing larger than a handful of controllers.

Performance

I don't think this is either a surprise or a problem for you, but just to say out loud, this setup will start to cause (performance) trouble if you start to add dozens/hundreds of endpoints.  It doesn't sound like that is your intention, but for something like this to scale to large apps you may need a different routing mechanism or some caching mechanism (or a completely different solution).

That's what I have for now!  Let me know if you have any followup questions/comments.


Removing duplicates from an unsorted Array

Improving removeDuplicates

It's recommended to use an enhanced for-each loop instead of a counting loop when possible:

for (int num : arr) {
    if (lastFound == num) {
        totalDuplicates++;
    } else {
        lastFound = num;
        uniqueArray[currPos] = num;
        currPos++;
    }
}

And you can get rid of totalDuplicates, as currPos already contains that same information:

int currPos = 1;
for (int num : arr) {
    if (lastFound != num) {
        lastFound = num;
        uniqueArray[currPos] = num;
        currPos++;
    }
}

return Arrays.copyOf(uniqueArray, currPos);

I noticed later that your original code does an unnecessary comparison for the first element or arr: it would be enough to iterate from the 2nd element. Unfortunately, for that we need to bring back the counting loop:

int currPos = 1;
for (int i = 1; i < arr.length; ++i) {
    int num = arr[i];
    if (lastFound != num) {
        lastFound = num;
        uniqueArray[currPos] = num;
        currPos++;
    }
}

return Arrays.copyOf(uniqueArray, currPos);

Reduce allocations

Note that removeDuplicates allocates an array to collect the unique elements (uniqueArray),
and finally returns a clone of that array, with the appropriate size,
thus allocating for one more array.
If you don't mind modifying the input array, then you can avoid the allocation of uniqueArray by overwriting the content of the input array:

private static int[] removeDuplicates(int[] arr) {
    if (arr.length <= 1) {
        return arr;
    }

    int lastFound = arr[0];

    int currPos = 1;
    for (int i = 1; i < arr.length; ++i) {
        int num = arr[i];
        if (lastFound != num) {
            lastFound = num;
            arr[currPos++] = num;
        }
    }

    return Arrays.copyOf(arr, currPos);
}

Unit testing

To verify the implementation works,
and for safe refactoring,
it's good to have some unit tests around, for example:

@Test
public void test_1_2_3() {
    int[] orig = {1, 2, 3};
    assertArrayEquals(orig, removeDuplicates(orig.clone()));
}

@Test
public void test_empty() {
    int[] orig = {};
    assertArrayEquals(orig, removeDuplicates(orig.clone()));
}

@Test
public void test_single() {
    int[] orig = {3};
    assertArrayEquals(orig, removeDuplicates(orig.clone()));
}

@Test
public void test_1_1_1() {
    int[] orig = {1, 1, 1};
    assertArrayEquals(new int[]{1}, removeDuplicates(orig.clone()));
}

@Test
public void test_1_1_1_2_2_3_3_3() {
    int[] orig = {1, 1, 1, 2, 2, 3, 3, 3};
    assertArrayEquals(new int[]{1, 2, 3}, removeDuplicates(orig.clone()));
}

@Test
public void test_1_2_3_3_3() {
    int[] orig = {1, 2, 3, 3, 3};
    assertArrayEquals(new int[]{1, 2, 3}, removeDuplicates(orig.clone()));
}

@Test
public void test_1_2_2_2_3() {
    int[] orig = {1, 2, 2, 2, 3};
    assertArrayEquals(new int[]{1, 2, 3}, removeDuplicates(orig.clone()));
}


// Should header files always be included in root.h as opposed to

You should include all header files that are required (no more than are required).

In your case you use the following types in the header file.

std::ifstream
std::string
Json::Value

So you should include the appropriate header file for these types.

#include <fstream>
#include <string>
#include "json/json.h"

The only curve ball is that if you only use a type reference then you can technically get away with a forward declaration (rather than including the header file). So you could use a forward declaration of std::string, unfortunately its not your class and you don't actually know how to forward declare it because that is not defined in the standard, so you have to include the header file.

  // Seems like I do not need to include this string container, why?

It may be included indirectly via <fstream> or "json/json.h". BUT you should still include the <string> header file because these dependencies may not always hold (on different platforms or different versions of the compiler it may including things differently). So do not assume because it worked on this platform it will always work. Think worst case and explicitly include <string>

The include guard seems a bit too generic:

ROOT_H

Seems like somebody else may use this. You need to make sure your guards are unique. I always use guards that include the namespace

// I own the domain name thorsanvil.com
// and I put all my classes in the namespace ThorsAnvil
// So my include guards go like this.
#define THORSANVIL_<Optional Nested Namespace>_ROOT_H

  // Is std::ifstream::binary ok to put it in here like this ^?
  // It's working, but would that be good practice?

Sure. That's totally fine.

You just have to understand what it mean and the difference between binary and text mode (the default). In Text mode: => "Platform Specific" "End of Line Sequence" is converted into '\n' when reading from a file. In Binary mode: no conversion is performed and you get the raw bytes.

So in the constructor:

Root::Root(const std::string & filename) : m_json(filename, std::ifstream::binary)

{
    m_json >> m_root;
    m_json.close();  // Do I need .close() here?

                     // Yes probably.
                     // Closing it releases the related OS resources.
                     // If you don't the resource will be held until
                     // the whole object is destroyed.

}

I don't see the need for the m_json object to be part of the object. It is only every going to be used inthe constructor. Once the data is loaded it will never be used again. So just declare it as an automatic variable that is local to the constructor.

Root::Root(const std::string & filename)
{
    std::ifstream  m_json(filename, std::ifstream::binary)

    m_json >> m_root;
}
// Now we don't need `close()` because the object goes out of scope
// and the `std::ifstream` destructor calls close for us.

  // Is it ok to assign member to a member like so,
  // as opposed to just a variable?

It is. But why. It seems much more logical to use a local variable.

Json::Value query = rate.m_root["query"]["items"];

Prefer '\n' over std::endl

The difference is that std::endl forces the buffer to flush. The buffer will flush automatically when it needs to. Forcing it to flush is only going to make your code inefficient.

  // How can I instantiate my object like the line below?
  // Root rate("test.json", ["query"]["results"]["rate"]);

You can define the operator[]. You can make it take a string as an argument.

class Root
{
    public:
        JsonValue operator[](std::string const& index)
        {
            return m_root[index];
        }
        // Other stuff in your class.
};

Now it can be used:

Root    json("file.name");
Json::Value = json["query"]["results"]["rate"];


the introduction of enum Bracket is good and idiomatic. However, this is not the only useful form, there are at least 2 other forms that would work just fine.
brackets_are_balanced can be simplified when we notice that all Brackets in Vec<Bracket> are of the Open variant, so we do not need to store Brackets, just their chars.
the introduction of fn new is against standard practice. A conversion constructor should not be called fn new and every constructor should return only Self (= Bracket). That's why the function should be renamed to from_char.
it's common practice to name enum variants with PascalCase, in your program, Bracket::Open and Bracket::Close. Not sure why you did all uppercase.
the result of brackets.pop() does not need matching, it can be simply compared.

The refactored code is
#![warn(missing_crate_level_docs)]
#![warn(missing_docs)]
//! # Matching Brackets
//!
//! `matching_brackets` is a collection of utilities to solve [this exercise](https://exercism.io/my/solutions/8ecfdc024536471a8c36ac2a3ff4b119).

enum Bracket {
    Open(char),
    Close(char),
}

impl Bracket {
    pub fn from_char(c: char) -> Option<Bracket> {
        match c {
            '{' | '[' | '(' => Some(Bracket::Open(c)),
            '}' => Some(Bracket::Close('{')),
            ']' => Some(Bracket::Close('[')),
            ')' => Some(Bracket::Close('(')),
            _ => None,
        }
    }
}

/// Check if the input `string` has balanced brackets.
///
/// # Examples
///
/// ```rust
/// use matching_brackets::brackets_are_balanced;
/// assert!(brackets_are_balanced("(((185 + 223.85) * 15) - 543)/2"));
/// assert!(brackets_are_balanced("([{}({}[])])"));
/// assert!(!brackets_are_balanced("{[)][]}"))
/// ```
pub fn brackets_are_balanced(string: &str) -> bool {
    let mut brackets: Vec<char> = vec![];
    for c in string.chars() {
        match Bracket::from_char(c) {
            Some(Bracket::Open(char_bracket)) => {
                brackets.push(char_bracket);
            }
            Some(Bracket::Close(char_close_bracket)) => {
                if brackets.pop() != Some(char_close_bracket) {
                    return false;
                }
            }
            _ => {}
        }
    }
    brackets.is_empty()
}
```


Print binary search tree by levels function implementation

General Notes

Let me preface this section with the fact that I have not looked at Java conventions in a while. Some of these suggestions may stray from classic Java conventions.

With that off my chest, visually your code looks pretty good, though mixture of underscores in your hungarian notation is a little bit odd (Thanks Vogel612).

// Could you not just have 'currentNode.mRightNode'?
if(currentNode.m_RightNode!=null)

You also have several loops or if-statements with only a single line of code in them. This may just be preference, but if you remove the braces in those cases:

if(currNodeHasChild)
{
    q.add(new TreeNode(-1)); // sign of next level
}

becomes

if(currNodeHasChild)
    q.add(new TreeNode(-1)); // sign of next level

which makes the code more compact without reducing readability.

NOTE: When using no-brace notation, only ONE LINE after the if-statement, for-loop, etc. will be considered 'inside' that block of code. As Vogel612 pointed out in a comment below, there have been cases where this notation was misused. Keep an eye out for these bugs, as they can pop up relatively easily.

One final thing: I do not prefer in-line comments. To my eyes, they break up the flow of the program visually.

BFS Solution

Now onto code improvements.

This problem is built to be solved by recursion. Combining recursion and a breadth-first search yields a relatively simple solution:

public void printTreeByLevels(Queue<TreeNode> nodes, int level)
{
    System.out.println("Level " + level);

    // New queue to hold child nodes
    Queue<TreeNode> newNodes = new ArrayDeque<TreeNode>();

    // Loop through all nodes in the queue
    for(TreeNode node : nodes)
    {
        System.out.println("\t" + node.m_Data);

        // Add child nodes if they exist
        if(node.m_LeftNode != null)
            newNodes.add(node.m_LeftNode);
        if(node.m_RightNode != null)
            newNodes.add(node.m_RightNode);
    }

    // Call this function again only if one or many child node(s) were found
    if(!newNodes.isEmpty())
        printTreeByLevels(newNodes, level+1);
}

A single for-loop and some if-statements solve this problem quite simply and easily.

NOTE: I originally wrote this in Python as its been a while since I wrote Java. However, the syntax should all be correct.


How to make DRY logger class with debug, info, warn and error methods that extends private method

Interesting question;

getting the logType and then unshifting it seems complicated, why not
console.log(logLevels[logLevel], ...messages)

The mapping from an integer to a string and back from string to integer must be addressed to make this DRY

This code seems a good fit for monads, which can also help with making this DRY

Other than that there is not much to say.

function Logger() {

  const logLevels = ['debug', 'info', 'warn', 'error'];
  this.logLevel = 0;

  this.log = function log(logLevel, ...messages) {
    if (logLevel >= this.logLevel) {
      console.log(logLevels[logLevel], ...messages)
    }
  }

  for(let i = 0; i< logLevels.length; i++){
    this[logLevels[i]] = this.log.bind(this, i);
  }

}

const myLogger = new Logger()
const dateNowHex = () => Date.now().toString(16)
//debugger;
myLogger.debug('this is a test', dateNowHex())
myLogger.info('this is a test', dateNowHex())
myLogger.warn('this is a test', dateNowHex())
myLogger.error('this is a test', dateNowHex())


There are quite few things to note in your code.

First of all, you are using deprecated $HTTP_POST_FILES where as you should use $_FILES

You are not using mysql_real_escape_string function in your query variables and therefore are vulnerable to sql injection which is caused through poor sql queries.

You are not checking whether or not the submit button was clicked, you should wrap your entire code in between:

if (isset($_POST['go'])){
  // your code
}


Project Euler code evaluation - digit fifth powers

Here is a little simpler way to write your code:

list = (2..1_000_000).select do |num|
  num.to_s.chars.map {|digit| digit.to_i ** 5}.inject(:+) == num
end

Using map twice is not big issue here, you operate on small collection and memory is not an issue (for really big collections you would probably want to use lazy, it's slower but somehow smarter).
The ampersand converts a symbol to a proc.

Inject without ampersand works pretty much the same, see documentation for details:

  If you specify a symbol instead, then each element in the collection will be passed to the named method of memo

Given memo = 0 and element 12 ruby does: 0 passed-symbol 12.
I'm not sure improvements are worth it, you can't really make it shorter or easier to read and performance or design is not necessary an issue here.


Missing return
Code may even fail the last rt == INT_MAX and then no return is specified.
  if (rt == INT_MAX)
    return parent_node -> data;

  // Missing return.
  }

Use const
Using const, as able, provides more information as to what the code does and does not do.  This also allows greater usage and potential optimization.
// int find_successor_h(BSTNode * rootPtr, int data, BSTNode * parent_node) {
int find_successor_h(const BSTNode * rootPtr, int data, const BSTNode * parent_node) {

Mis-matched comments
Comment does not match parameter names nor order: node val vs.  data.
* @param rootPtr root pointer of BST
* @param parent_node parent node of the subtree (root node should be passed by default)
* @param nodeValue node val to find successor

BSTNode * rootPtr, int data, BSTNode * parent_node

Missing include
NULL not defined.
Spelling
* @return succsor vs. * @return successor
Name error?
Why h in int find_successor_h()?
{ block }
Consider using {} even for simple blocks.  Little need for else
//if (rootPtr -> right_child != NULL)
//  return minBST(rootPtr -> right_child);
//else if (rootPtr != parent_node)
//  return INT_MIN;
//else
// return data;

if (rootPtr -> right_child != NULL) {
  return minBST(rootPtr -> right_child);
}
if (rootPtr != parent_node) {
  return INT_MIN;
}
return data;

Deeper review
More support and test drive code needed for a deeper review.


First, I would move out that equation to its own function. It takes an input number (your value), and returns a result (the text). Doing it this way makes easily testable functions a habit.

function getTextFromRangeValue(value){
  return maxValue - (value * coef);
}

With this comes separation of your DOM handler logic. This allows your logic (the calculation code) to be very reusable as it is now detached from the DOM-handling code.

slider.addEventListener('change', function(event) {
  result.value = getTextFromRangeValue(event.target.value);
});

maxValue and coef are constants, fixed values. It's a programming convention to name constants with uppercase characters separated with underscores. Additionally, lift them out the handler scope so they're not recreated on every call. They should be named in full, avoid abbreviations.

var slider = document.querySelector('#slider');
var result = document.querySelector('#result');
var MAX_VALUE = 2000;
var COEFFICIENT = 18;

If I were to rewrite this code, here's how I'd do it.

const slider = document.querySelector('#slider');
const result = document.querySelector('#result');
const MAXIMUM_VALUE = 2000;
const COEFFICIENT = 18;

function getTextFromRangeValue(value){
  return MAXIMUM_VALUE - (value * COEFFICIENT);
}

slider.addEventListener('change', function(event) {
  result.value = getTextFromRangeValue(event.target.value);
});

Lastly, as mentioned in the comments, if this code isn't in a module or in its own scope, consider wrapping in an IIFE to avoid cloberring and being clobbered in the global scope.


Thread synchronization and happens-before relation in simple examples

Your code here is pretty mixed up and is not representative of a decent test of concurrency. It will work and give you the results you expect, but the reason is a bit polluted.

The internal code for System.out.println() looks like:

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

As a result, there are many more synchronizations than you expect. These are nested inside another synchronization block.

In essense, any time there is a println() you have a possibly conflicting synchronization problem.

In this case, it does not make much of a difference, but your code concerns me.

Additionally, it is traditional to incorporate the wait-conditions in the while-loop, and not as a break condition. Your code:

   synchronized (object) {
        while(true) {
            try {
                object.wait();
            } catch (InterruptedException e) {
                System.out.println("Interrupted!");
            }

            System.out.println("Notified!");

            if(result1 != null && result2 != null) {
                System.out.println(result1 + " " + result2);
                break;
            } else {
                System.out.println("Not ready");
            }
        }
    }

Would be better as:

   synchronized (object) {
        while(result1 == null && result2 == null) {
            object.wait();
        }
    }
    System.out.println(result1 + " " + result2);

Note that I have stripped out your InterruptException handling. It was not sufficient for "real" code, and if you replace it, should probably go outside the calls. If someone interrupts your code, continuing in a loop is probably not the right thing to do.


Calculating the area of various 2D shapes

Since you're not using shape extensively I would get rid of that data structure all together. It would be easier to read inline then having to look to the margin for comments.

For example:

  if target_shape == 'square':
     l = float(input("give the length: "))
     area_square = l ** 2
     print("the area of the square is %.2f" % (area_square))

When comparing strings if you don't want to be strict you should normalize them before compare.

For example:

'Square'.lower() == 'square'

so your code would become:

  if target_shape.lower() == 'square':
     l = float(input("give the length: "))
     area_square = l ** 2
     print("the area of the square is %.2f" % (area_square))

You're not accounting for any errors. What if the user hits enter without giving a length?

ValueError: could not convert string to float


Animated progress bar in C++ | How to simplify or alternatives using strings

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

Use consistent formatting

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

Think carefully about requirements

You wrote:

  a friend of mine said that this code will have a bad performance because of my use of string, is that true ?

Maybe, but it's important to think about the requirements first before chasing phantoms of imagined performance gains.  The first question is, "does it matter how fast it is?"  I'd say that any code that contains usleeep(50000); within a loop probably isn't performance-critical and so it doesn't much matter.

So then that leads to the question of what does matter which directly leads to the topic of requirements.  What does the code need to do?  Is there a performance requirement?  A memory footprint requirement?  An efficiency requirement?  My usual advice is to create the simplest thing that works.  This allows you (and others) to more easily understand the code and to avoid wasting your time on "optimizing" things that don't need to be optimal.

Use object-oriented programming

In this case, there's a thing called a "progress bar" that is expected to indicate the progress of some user-controlled process.  This suggests that it might be better to create a ProgressBar object.  That way, the current state of the bar, including the particular characters used, and its representation could be separate aspects of the same object. This would be much cleaner and also have the advantage of making it easier to create alternative output formats.

Consider the user(s)

Consider the user of this progress bar (presumably another programmer, or perhaps yourself).  You might want to have some actual lengthy work done by the computer, and the progress bar is just an indicator.  However, with the loop and usleep in the printProgressBar function, it's entirely possible that the progress bar itself would take up more time than the lengthy process that led the user to want a progress bar in the first place!  There are a couple of ways to address this.  The simplest would be to abandon the current look of the progress bar with its animation-like bar and adopt a simpler proportional bar.  Another option would be to keep the existing visual effect, but to allow the percentage complete to be indicated by both how many stars are to the right, but also where the advancing star is within the empty space.

That leads to the next consideration, which is the other user of this code, which is not the programmer, but a person using the program that includes this progress bar.  For that person, how clear is the intent of this progress bar?

Eliminate unused variables

This code declares main with arguments argc and argv in the usual way, but neither argc nor argv are actually used.  This could be addressed by either declaring int main() or by modifying the code to actually use the variables.


Some points about your code

extract the code to create an account to a separate class. In this way you can reuse it without problems. This can even be a static method.
variables should be named using camelCase casing. See the naming guidelines.
as you don't use neither the TemporaryCookie nor the CreateAccountCookie you should remove these varaibles.
the assignment of POSTRequest.KeepAlive = true; is superflous because the default of the KeepAlive property is true.
string POSTRequestCode = POSTRequestReader.ReadToEnd(); is superflous because it is never used.
because Stream is implementing IDisposable you should enclose it in a using statement. This will take care that the Stream is closed and disposed.
you don't use the HttpWebResponse POSTResponse so you can remove it too

Implementing the mentioned points will lead to:

private static string postDataToFormat = "op=reg&dest=https%3A%2F%2Fwww.reddit.com%2F&user={0}&passwd={1}&passwd2={1}&email=&api_type=json";
public static void CreateRedditAccount(string userName, string passWord)
{
    string postData = string.Format(postDataToFormat, userName, passWord);

    UTF8Encoding Encoding = new UTF8Encoding();
    byte[] postValue = Encoding.GetBytes(postData);

    HttpWebRequest POSTRequest = (HttpWebRequest)WebRequest.Create("https://www.reddit.com/api/register/" + userName);
    POSTRequest.Method = System.Net.WebRequestMethods.Http.Post;
    POSTRequest.ContentType = "application/x-www-form-urlencoded";
    POSTRequest.Referer = "http://www.reddit.com/";
    POSTRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
    POSTRequest.ContentLength = postValue.Length;

    using (Stream POSTRequestStream = POSTRequest.GetRequestStream())
    {
        POSTRequestStream.Write(postValue, 0, postValue.Length);
    }

}


Mini Test testing save on one and many trips

If you're writing verbose tests, your test suite will skyrocket in length.

There are worse problems to have but your best asset to address this problem is a comprehensive test_helper class.

It doesn't matter what you call the file. Just load it up into your main test file with a require_relative.

In your example, it's fairly obvious which code is being repeated between methods. So you could refactor your code as follows:

# in test_helpers.rb
module TestHelpers
  def initialize_sample_trip(options={})
    Trip.new(
      departure_date: options[:departure_date]   || "2040-03-24"
      default_airport: options[:default_airport] || "DHW"
      arrive_airport: options[:arrive_airport]   || "ABC"
      invoice_id: options[:invoice_id]           || 123534
    )
  end
end

...

# in your main test file
require_relative './test_helpers.rb'
class TripTest < ActiveSupport::TestCase
  include TestHelpers
  def setup
    @trip = trips(:one)
    @invoice = invoices(:one)
  end

  test 'trip can save' do
    trip = initialize_sample_trip
    assert trip.save, "Error message: #{trip.errors.full_messages}"
  end

  test "one invoice can have multiple trips" do
    trip1 = initialize_sample_trip
    @invoice.trips.push(trip1)
    @invoice.save
    trip2 = initialize_sample_trip(
      depart_airport: ICN, arrive_airport: "XYZ"
    )
    @invoice.trips.push(trip)
    @invoice.save
    assert @invoice.trips.size > 1
  end

This can be considered a "factory" design pattern. There are also various gems which can assist with this such as factory_girl or faker.


Method Ordering - Readability / Maintainability

I don't have strong feelings, but I keep methods in calling order.  The argument for "public up top" seems to be that someone wants to see what methods they can call on an Object as opposed to what a particular method does.  However in today's world, this is generally accomplished by an IDE or javadoc.  If that's not possible, the time lost jumping through a file looking for the public methods is minimal.

When I'm looking at code for a class I haven't written, I'm inevitably trying to find out how it works.  And when reading the content of a method, jumping to private methods becomes more important, and slightly more time is lost if the class isn't ordered for callability.


Efficient file I/O

By default, files opened with fopen() are buffered, meaning that not every call to fread() or fwrite() will result in a system call. Instead, the C library has an internal buffer and will try to read and write larger chunks at a time. However, you are still paying for the overhead of a regular function call each time you call fread() and fwrite(). To avoid this, it is best that you read and write in large chunks in your own code as well.

While you could try to read in the whole file at once, or even use technique like mmap() to memory map the file, you can already get very good performance by reading and writing blocks of say 64 kilobytes at a time. This avoids using a lot of memory.
Of course, you have to handle the last block not being exactly 64 kilobytes large, but that is quite easy to deal with.

Furthermore, fread() and fwrite() allow you to specify the size of an element and the number of elements you want to read, this comes in handy to ensure you read in a whole number of 4-byte codepoints.

I would structure your code like so:

uint32_t bufferIn[16384]; // 16384 4-byte code points = 64 kB
char bufferOut[65536];

size_t countIn;

while ((countIn = fread(bufferIn, sizeof *bufferIn, sizeof bufferIn / sizeof *bufferIn, ptr)) > 0) {
    // There are countIn codepoints in the buffer
    for (size_t i = 0; i < countIn; i++) {
         uint32_t codepoint = ...; // Convert bufferIn[i] to native endian here.

         // Write UTF-8 to bufferOut here.
         // If bufferOut is almost full, fwrite() it and start writing to it from the start.
    }
}

// Flush the remaining bytes in bufferOut here.

Don't use floating point math for integer problems

Avoid using floating point math when you are dealing with integers. It is hard to get it right, and converting int to double, doing some math operation, and then converting back again can be quite slow.

There are several ways to get the highest set bit in an integer. If you want a portable one, I recommend using one of the bit twiddling hacks. Sometimes compilers will even recognize such a bit twiddling hack and convert it to a single CPU instruction if possible.


Passing private variable in JavaScript nested class?

Teams have members, so it almost seems natural to put the Member class into the Team class. But projects also have members. How are you going to implement that? You can't nest Member in both classes. Another problem with nested classes is that you have to traverse through Company -> Department -> Team -> Employee hierarchy just to get everyone's name or email.

Answering your question, how can you pass some variable that can't change outside of the class. Create a getter method:

function Team() {
    var teamId = 4; // not changeable from outside
    this.getId = function() {
        return teamId;
    }
}

Now you can access teamId from outside of the class, but can't change it.

Or instead of creating truly private properties and functions, you can simply prefix them with an underscore to denote they are private and should never be accessed from outside. While nothing really stops you from accessing them, nothing also stops you from redefining the Team class and accessing anything you want.


Python - Predicting the probability of 6 Heads or Tails in a row from a set sample size

Eliminating useless code
Enumerating a range is really pointless
In [6]: sample_size = 5

In [7]: for i, experimentNumber in enumerate(range(sample_size)):
   ...:     print(i, experimentNumber)
   ...:
0 0
1 1
2 2
3 3
4 4

So we can easily replace one by the other. We do not even need to replace as experimentNumber is not used anywhere. Next we notice that i is also used only once where we can replace results[i-5:] by superior construct results[-6:].
We also eliminate the superfluous exception handling. So far this is already covered by @ppperys answer.
Efficiency
you create a complet list of length sample_size of random values in memory. This is not required and may be a problem on big sample sizes. As you always need the last 6 values only you could go for collections.deque which can maintain a maxlen.
from collections import deque
results = deque(maxlen=6)

For the evaluation made easy we do not use ('H', 'T') but numbers. We do not need to comare with a streak any more but do it arithmetically. Here is the only pitfall - we must check if the queue is filled completely to not accidentally accept a short sequence of zeros.
for _ in range(sample_size):
    results.append(random.choice((0, 1)))
    if len(results) == 6 and sum(results) in (0, 6):
        numberOfStreaks += 1

This not only saves memory but we also get rid of a temporary temp and the predifined head_streak and tail_streak. We notice the magic number 6 appearing multiple times - use a variable. We also make a testable function. We end up with
import random
from collections import deque

def streak_probability(streak_len, sample_size):
    results = deque(maxlen=streak_len)
    numberOfStreaks = 0
    for _ in range(sample_size):
        results.append(random.choice((0, 1)))
        if len(results) == streak_len and sum(results) in (0, streak_len):
            numberOfStreaks += 1
    return numberOfStreaks / sample_size

print('Chance of streak: %s%%' % (streak_probability(6, 1000000))

Algorithm
This simulation will give good results for big numbers of sample_size. However if the sample size was smaller than 6 it will always return 0. As you divide the final streak count by the sample size you indicate, that you would like to get the probability of a streak per "additional" coin toss. So we should fill the queue before starting to count. That way an average of a large number of runs with a small sample size would match a single run of a large sample size. If we prefill we do not have to check the fill state of the queue (yes I filled to the max while one less would be sufficient).
def prefilled_streak_probability(streak_len, sample_size):
    results = deque((random.choice((0, 1)) for _ in range(streak_len)), maxlen=streak_len)
    numberOfStreaks = 0
    for _ in range(sample_size):
        results.append(random.choice((0, 1)))
        if sum(results) in (0, streak_len):
            numberOfStreaks += 1
    return numberOfStreaks / sample_size

Now test the difference - we compare the original sample size of 1.000.000 to 100.000 repetitions of sample size 10
s=10
n=100000
print('no prefill')
print('Single big sample - Chance of streak: %s%%' % (streak_probability(6, s*n)))
probs = [streak_probability(6, s) for _ in range(n)]
print('Multiple small samples - Chance of streak: %s%%' % (sum(probs)/len(probs)))

print('with prefill')
print('Single big sample - Chance of streak: %s%%' % (prefilled_streak_probability(6, s*n)))
probs = [prefilled_streak_probability(6, s) for _ in range(n)]
print('Multiple small samples - Chance of streak: %s%%' % (sum(probs)/len(probs)))

we get
no prefill
Single big sample - Chance of streak: 0.031372%
Multiple small samples - Chance of streak: 0.01573599999999932%
with prefill
Single big sample - Chance of streak: 0.031093%
Multiple small samples - Chance of streak: 0.031131999999994574%


Return value related to file content header

Usually if I have a big list of mappings from one string to another, that is likely to be later enhanced on, I use a generic mapping method, that is fed a static mapping constant.

So the first iteration would be something like:

type ExpectedMimeTypes =
  'image/png' |
  'image/jpg' |
  'image/jpeg' |
  'application/pdf' |
  never;

type ExpectedMagicOutput =
  'Photo' |
  'Document' |
  'Unknown' |
  never;

type MimeTypeMapping = {
  [key in ExpectedMimeTypes]?: ExpectedMagicOutput
}

const MAP_MIME_TYPE_TO_MAGIC_STRING: MimeTypeMapping = {
  'image/png': 'Photo',
  'image/jpg': 'Photo',
  'image/jpeg': 'Photo',
  'application/pdf': 'Document'
}

function getAttachmentType(attachmentTypeHeader: ExpectedMimeTypes): ExpectedMagicOutput {
  if (attachmentTypeHeader in MAP_MIME_TYPE_TO_MAGIC_STRING) {
    return MAP_MIME_TYPE_TO_MAGIC_STRING[attachmentTypeHeader]!;
  } else {
    return 'Unknown';
  }
}

If you are using TypeScript, go all in, meaning be as specific as possible. You do not expect arbitrary string as a result from getAttachmentType() but specific ones. You should explicitly model them, either by using unions or string-based enums. This fosters reusability.

The above solution gives you full type-safety, while being easily enhanced for other types; simply add them to the ExpectedMimeTypes and then you can easily add them to the constant MAP_MIME_TYPE_TO_MAGIC_STRING and vice versa, you cannot add mappings there, that have not been mentioned in the types above.

You could make ExpectedMimeTypes configurable by putting them into a dedicated file and let that be generated via a config and a simple script. That way you get both - configurable mime types and static compile type safety.


Pop() has problem
Consider what happens if your queue is in the following state with two jobs:
m_top    = 0
m_bottom = 2

The owner thread calls pop(), and loads in to local variables:
top    = 0
bottom = 2

Now, before the owner thread does anything else, two stealer threads call steal(), leaving the state of the queue like this:
m_top    = 2
m_bottom = 2

When the owner thread continues inside of pop(), it will go into this case and return a job that no longer exists:

    if(top < (bottom - 1))
    {
        m_bottom.fetch_sub(1, std::memory_order_release);
        return job;
    }

Your code deviated from the code you linked.  In the linked code, the first thing that pop() did was to decrement m_bottom so that the stealer threads could not steal the bottom job.


SQL injection

First of all, your PDO code is a straw plane that never flies. Using prepare() like that makes very little sense, leaving all your queries widely exposed to SQL injection attacks.

prepare() doesn't protect your queries by itself, making them immune by means of some magic. It helps only if you take out every single variable from your query and substitute it with a placeholder, then prepare your query and then finally execute, adding variables separately.

Therefore, all methods in DSSql should be changed in order to accept two variables - a query and an array with data:

public function read($sql, $params = [])
{
    $stmt=$this->bd->prepare($sql);
    $stmt->execute($params);
    $response = $stmt->fetch(PDO::FETCH_ASSOC);
    return $response;
}

Code duplication

As you may notice, the code in DSSql class' methods is heavily duplicated. Why not to create a basic method to run an arbitrary query, an then call this method with only different return formats?

public function query($sql, $params = [])
{
    $stmt=$this->bd->prepare($sql);
    $stmt->execute($params);
    return $stmt;
}

public function read($sql, $params = [])
{
    return $this->query($sql, $params)->fetch(PDO::FETCH_ASSOC);
}

public function readAll($sql)
{
    return $this->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}

public function save($sql, $params)
{
    return $this->query($sql, $params);
}

Existing PHP classes' code reuse

As you may notice, your methods now bear very little difference. Why not to take them out at all and make use of the powerful PDOSTatement class already exists in PHP?

public function searchById($id)
{
    $sql = "SELECT  * FROM clients WHERE id=?";
    return $this->ds->query($sql, [$id])->fetch();
}

public function searchAll()
{
    $sql = "SELECT * FROM clients";
    return $this->query($sql)->fetchAll();
}

ORM

The code in the save() method is not really does the save but rater runs an arbitrary query, which could be quite confusing. If you want a real save, read and such methods, consider using an ORM, a class that constructs SQL queries for you, and in such a case it will be indeed save() or find() with no other meaning

Questions

  Is correct to form queries at repository classes?

yes, it's the place where SQL belongs

  Where should I handle SQL errors? Having an SQLError

Wherever you are handling all other errors. There is nothing special in SQL errors, handle them the same way as others.

  How should I handle access to APIs?

That is somewhat too wide question for a comment, especially without any context given. May be you should ask on Stack Overflow.

  As my app has role based access for users, how does this impacts my design/implementation? Based on logged user role I've create different classes using same interface but implementing different queries to database.

Well, this is somewhat a key question. Consider using an existing framework instead of rolling up a your own. Established frameworks already have all you need out of the box, including ORM, a template engine and of course a user management module with role based authorization. I would suggest Symfony as being the most popular PHP framework that encourages best coding practices.


Faster way to copy rows of data to different sheets by column value

Your for () loop is unnecessarily calling SpreadsheetApp.getActiveSpreadsheet() in every single iteration. You can define a varible outside of the loop for chaining:
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
for (let i = 1; i < columnRoom.length; i++) {
  // something...
  spreadsheet.insertSheet("No Room")
}


Daily SQL job to delete records older than 24 hours

From Comments

Have you tested performance of copying data of a single day to a temporary table, truncating the target table, and re-inserting the copied data back to the target table?

  Yes, it's not taking much time to copy or insert, it is taking time to delete and select. One of the column has huge XML string.

Proposed Solution

Since inserting and copying data does not seem to yield a performance penalty, I would suggest to:

copy to data of today to a staging table
truncate the existing table (much faster than delete, no transaction logs)
copy staged data back to existing table

Or alternatively, as Dannnno suggests:

Potentially faster than copying the data twice would be to copy data to a staging table, truncate the existing table, then rename them both to swap places. This minimizes latches required for DDL, and also only requires a single copy. Snapshot isolation would also help this be as non-invasive as possible for anyone hitting the database.

Links

Similar problem: non-clustered index bottleneck on delete
Enlists a couple of possible solutions


Finding an element in an array that occurs a given number of times

Style

Codding

I suggest you to make use of white space so your code is more readable; as it stand, it seems like a bunch of thoughts thrown away without even trying to organize them. Read PEP 8 too, which will make you code look a bit more like Python to people that are used to read some Python code.

It is also good practice to organize your code into functions, so you can extract out logical steps, name them and, as such, make it clearer to everyone what it is you are trying to accomplish. Read about PEP 257 to make it even more clear.

At the very least, if you can't find out good functions, you may want to put all your top-level code into a main function and have, at the bottom of your script:

if __name__ == '__main__':
    main()

You can read a bit more about this idiom in this SO post.

Reading input

In challenges like that, where the input is highly regularly formatted, I have a tendency to favor raw_input rather than manipulating stdin directly.

It lets you more easily parse each line independently; for instance:

def parse_data():
    raw_input()  # Skip the first line containing number of elements
    items = raw_input()
    return items.split()

def run_queries(data):
    count = int(raw_input())
    for _ in range(count):
        type_, element = raw_input().split()
        result = compute_query(int(type_), element, data)
        print(result)

def compute_query(type_, item, data):
    # TODO

if __name__ == '__main__':
    data = parse_data()
    run_queries(data)

You will note that I don't try to convert the elements to integers as there is no added value doing so. Equality of two strings is as valid than equality of two integers to know that two elements are the same.

Algorithm

You know about Counter which is a good way to count elements from an iterable. You can use that at your advantage to reverse the keys and values so you know, for each "number of repetitions", which items corresponds.

from collections import Counter

def count_elements(array):
    counts = Counter(array)

    indexor = {}
    for element, count in counts.iteritems():
        indexor.setdefault(count, []).append(element)

    return indexor

There are several improvements to this snippet. First of, indexor will only let you answer queries of type 1 where you need the exact amount of elements. You can easily create a second dictionary to answer type 0 queries where you decrease count and append to each entry in the range \$[0, count]\$. The second improvement is to use a defaultdict(list) from collections to avoir the call to setdefault.

But the main thing is: this snippet can't answer the question as Counter is a dictionnary and thus doesn't take the order of insertions into account. Luckily, collections also provides OrderedDict which do. So your best friend for this challenge will most likely be:

from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

Replace the use of Counter by OrderedCounter and voilà, you're done. Each query can be simplified to getting the right dictionnary based on the query type and then getting the first element of the list accessed by the element count.

Putting all that together

from collections import Counter, OrderedDict, defaultdict

class OrderedCounter(Counter, OrderedDict):
    pass

def count_elements(array):
    counts = OrderedCounter(array)

    strict_indexor = defaultdict(list)
    loose_indexor = defaultdict(list)

    for element, count in counts.iteritems():
        strict_indexor[count].append(element)
        for c in range(count, 0, -1):
            loose_indexor[c].append(element)

    return loose_indexor, strict_indexor

def parse_data():
    raw_input()  # Skip the first line containing number of elements
    items = raw_input()
    return items.split()

def run_queries(items_counts):
    queries_count = int(raw_input())
    for _ in range(queries_count):
        type_, number_of_elements = raw_input().split()
        result = compute_query(int(type_), number_of_elements, items_counts)
        print(result)

def compute_query(type_, count, items_counts):
    indexor = items_counts[type_]
    return indexor[count][0]  # Assume there is no query having no answer

if __name__ == '__main__':
    items = parse_data()
    counts_by_query_type = count_elements(items)
    run_queries(counts_by_query_type)


what's the best method for such purpose to simplify below logic?

With a helper function as there is  repetitive code.

#include <stdint.h>

// Write 32-bit integer in little endian order to buf
unsigned char *u32tobuf(unsigned char *buf, uint32_t value) {
  buf[0] = value;
  buf[1] = value >> 8;
  buf[2] = value >> 16;
  buf[3] = value >> 24;
  return buf + 4;
}

I'd also 1) add some error checking, 2) drop the unneeded cast 3) prevent int overflow 4) use const.

// Return error status
int send_packet(int connfd, const INFO* info, int len) {
    uint32_t buflen = len*8lu + 8;
    unsigned char* buf = malloc(buflen);
    if (buf == NULL) {
      return 1; // or perhaps some enum
    }
    unsigned char* p = u32tobuf(buf, 0x55555555);
    p = u32tobuf(p, buflen);
    for (int i=0; i<len; i++) {
      p = u32tobuf(p, info[i].pid);
      p = u32tobuf(p, info[i].score);
    }
    ssize_t write_count = write(connfd, buf, buflen);
    free(buf);
    if (write_count != buflen) [
      return 1; // or perhaps some enum
    }
    return 0;
}


Remove elements existing in a list built from an enum

What I like about the method is that it's implementation is straight forward and easy to understand. There are, however, a few things that may be done done differently.

The name of the method is misleading, as it does not actually check keys, but it build/returns a list of keys not pressed at the current moment.
The result of Enum.GetValues(typeof(enumType)) should never change during runtime, thus running it on every method call must be sub-optimal on recurring calls.
Using the ForEach method and using List<T>.Remove to remove the items looks fine, but List<T> might not be the best data type to remove items from. You could also use a HashSet<T>, which would not go all the way to Array.IndexOf<T>.

I tested around a bit and found that another option - not removing items from a list - is actually marginally faster.

    private readonly IReadOnlyList<Keys> keysToPress = Enum.GetValues(typeof(Keys)).Cast<Keys>().ToList();

    private List<Keys> CheckKeysToPressWithExcept()
    {
        // You could just use LINQ - the method probably won't get any simpler than this.
        return this.keysToPress.Except(GetKeyList()).ToList();
    }

    private List<Keys> CheckKeysToPressWithSet()
    {
        var keysPressed = new HashSet<Keys>(GetKeyList());

        // Or you can construct the resulting list manually.
        // Performs better, but is more code to read.
        var result = new List<Keys>(this.keysToPress.Count);
        foreach (var key in this.keysToPress)
        {
            if (!keysPressed.Contains(key))
            {
                result.Add(key);
            }
        }

        return result;
    }

In a quick benchmark, CheckKeysToPressWithSet was the fastest, a modified version of your CheckKeysToPress that uses the IReadOnlyList<Keys> keysToPress instead of re-creating the enum value list every time, was 2% slower and the LINQ was 14% slower.


Producing full list of Fibonacci numbers which fit in an Int

object Euler002 extends App{
  // Infinite List (Stream) of Fibonacci numbers
  def fib(a: Int = 0, b: Int = 1): Stream[Int] = Stream.cons(a, fib(b, a+b))

  // Take how many numbers you want into a List
  val fibsAll = fib() takeWhile {_>=0} toList
  fibsAll reverse
}

Take a look at this.


Array indexing with copy constructor, assignment operator and index operator overload

This isn't really a code review so much as help on how to get this to compile.

Array::Array(int *p = NULL, int s = 0){ default parameters go on the declaration, not the definition.*
Array::Array& operator=(Array other){ Qualify the operator with Array::, not the return type. You're not returning an Array::Array**, you're defining the operator= member function of Array
void Array::swap(Array& first, Array& second){ swap is not a member of array, it's a friend. Remove the Array::

*This is because the client (caller) to the method needs to know what the defaults are supposed to be, since default parameters are mostly a syntactic shortcut. If you put the defaults into the definition (e.g. a cpp/.o file), a client which includes the header cannot see the definition and thus cannot use them. In other words, there exists no Array::Array() constructor right now, there's only the Array::Array(int *, int), but through C++ magic it can look as though Array::Array() is being called.

** An Array::Array type is impossible because you can't name a child type the same as its parent type. It would be ambiguous with the constructor.


@sc_ray pretty good effort if you are new to C programming.

A few points in your code which you can improve:

Taking array values from command-line is not good. Its better you use scanf and proper data-type. Below are logs when I pass a very long int value as cmd-line argument. It fails to store the value and gives garbage.

./a.out 7 999999999999 0 123
Reading input value 7 into array
Reading input value 2147483647 into array
Reading input value 0 into array
Reading input value 123 into array
Printing out the original array
7  2147483647  0  123
.....

Hope this is a code pasting mistake. Remove this arr array not needed.

int arr[] = { 47, 71, 5, 58, 95, 22, 61, 0, 47 };
identifyTheIndices(arr,sizeof(arr)/sizeof(arr[0]));

The searching of elements in array can be improved using Binary Search Algo rather than sequential search.

Rest all looks good.


Deeply extract all used symbols from a hash of nested symbols in an array

Some notes:

The flattening should be performed where the non-desired nesting is being introduced, not later. Use flat_map instead of map:
Why e for the value name instead of v?

I'd write:

def all_keys(hash)
  hash.keys + hash.values.flat_map { |v| v.is_a?(Hash) ? all_keys(v) : [v] }
end

Another way to do it, slightly shorter, is to iterate directly the pairs. Pick the one which is more declarative to you:

def all_keys(hash)
  hash.flat_map { |k, v| [k] + (v.is_a?(Hash) ? all_keys(v) : [v]) }
end


Nested values copies from one object to another

Why bother with libraries? This doesn't need anything more than pure JS. Assuming the incoming data is stored in fields:

var keys = Object.keys(fields);
for(var i = 0; i < keys.length; i++) {
    var key = keys[i];
    if(directory_model[key]) {
        directory_model[key].value = fields[key];
    }
}


Performing an action which may return other actions to be performed, concurrently

I think yours works, but async specializes in this stuff.

recurseAsync :: (a -> IO [a]) -> a -> IO [a]
recurseAsync f a = do
  xs <- f a
  fmap concat $ mapConcurrently (recurseAsync f) xs


Python startswith and then look a word in a conditional block

Unless there is an indentation issue,

        dataBlock = ''
        dataBlock = dataBlock +  line

can be written:

        dataBlock = line


Optimize Performance of Region Checking in List Comprehension

Loops over large arrays are not really a good idea in Python. This is why your original list comprehension is not terribly fast.

Your numpy version is loop free, but as far as I know, np.repeat actually makes copies of your data, which again, is really inefficient. An alternative would be to use np.tile, which maybe does not need to copy the data. But we don't really need to bother since numpy has a great feature called broadcasting, which often makes np.repeat/np.tile completely unneccessary. Broadcasting basically does np.repeat/tile automatically.

To evaluate the performance, I created a more abstract version of your list comprehension:

def get_valid_op(arr, lowers, uppers):
    return np.asarray([any((val >= lowers) & (val < uppers)) for val in arr])

and also a broadcasting version

def get_valid_arr(arr, lowers, uppers):
    valid = np.logical_and(arr.reshape(1, -1) >= lowers.reshape(-1, 1), arr.reshape(1, -1) < uppers.reshape(-1, 1))
    return valid.any(axis=0)

The second one is virtually the exact same algorithm as your repeat/reshape code.

With some test data modeled after your description above

arr = np.linspace(0, 1000, 70000)
starts = np.linspace(0, 150, 151) * 400
ends = starts + np.random.randint(0, 200, region_starts.shape)  # I assumed non-overlapping regions here

we can first assert all(get_valid_op(arr, starts, ends) == get_valid_arr(arr, starts, ends)) and then time:

%timeit -n 10 get_valid_op(arr, starts, ends)
511 ms ± 5.42 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit -n 10 get_valid_arr(arr, starts, ends)
37.8 ms ± 3.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

An order of magnitude faster. Not bad to begin with ;-)

Since working with large arrays (valid has a shape of (150, 70000) before reduction) also has a cost, I then took a step back and returned to loopy-land (just a little bit).

def get_valid_loop(arr, lowers, uppers):
    valid = np.zeros(arr.shape, dtype=bool)
    for start, end in zip(lowers, uppers):
        valid = np.logical_or(valid, np.logical_and(start <= arr, arr < end))
    return valid

In contrast to your list comprehension, this version now only iterates over the shorter region limit vectors, which means about two orders of magnitude fewer iterations.

We can then again assert all(get_valid_op(arr, starts, ends) == get_valid_loop(arr, starts, ends)) and time it:

%timeit -n 10 get_valid_loop(arr, starts, ends)
18.1 ms ± 865 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

As the results show, this version is even faster on my "synthetic" benchmark inputs.

In the end you will have to check the versions in your application and see which one performs best.


You can pass all of the properties of your dataPull class in a single line which will also pass any future properties you decide to add to your object, using Reflection:

var values = data.GetType().GetProperties().Select(p => p.GetValue(data))
    .Concat(new object[] {gg, ff, ee, dd});
SQLHelperTable.Rows.Add(ro.Alpha, values);


Unsigned integer division ARM Cortex-M0+ Assembly

You have at least a couple bugs.  The LT condition is signed less-than.  You need BLO to branch on the unsigned Lower-Than condition (branch if Carry is unset).  See also this article about carry vs. overflow.
Also, I think you forgot to put the remainder into R1.

Your custom calling convention makes life difficult.  Flag return values appear to be cumbersome in Thumb mode, because many instructions are only available in flag-setting form.  (Cortex-M0 only supports Thumb mode, with these instructions.)  It's also strange to not let your function clobber R2 and R3 like the standard calling convention allows.  This would reduce code-size for the function, although it would increase overall code size if there are many call sites.
It's normal to arrange a loop so the conditional branch is at the end. That reduces the instruction-count by one (removing the unconditional branch). Sometimes you need to test if the loop should even run once before falling into it, or jump to the test at the end, if you can't guarantee that it should always run at least once (do{}while() style).
You can combine the exit code-paths around AnsZero.  You have MOV R0, #0 / BX  LR twice, so you should just put AnsZero pointing at the first one and leave out the second.  You also have two consecutive BX  LR instructions, where you previously had a B to the next line at the end of the function.  Never branch to the instruction that normal fall-through execution would take you to anyway.

The comment character in ARM asm is @.  ; is used in x86 NASM / MASM, but the GNU assembler uses it to separate multiple instructions on the same line.  Maybe there are ARM assemblers that use ; as a comment character, but making your code assemble with GAS seems like a good idea.  Note that mov r3, #0 won't assemble with -mcpu=cortex-m0, because movs is the only immediate-mov instruction it supports.  Cortex-M0 has very limited instruction choices.
Further style points: use : after label names, even if your assembler syntax doesn't technically require it.  Some people may like to omit it when assembling data sections, but I don't think anyone likes it for code sections.
All-upper-case for asm instructions and register names is a valid choice.  I don't like it, but I guess it doesn't hurt.  Using it for symbol names is a bad idea, because you don't want to have to use all-caps names to call it from C.
Avoid useless comments like CMP   R0,#0       ;compares R0 to 0.  asm mnemonics are not that hard to decipher (except PowerPC).  Comment space is limited, don't waste it saying the same thing the reader learned from reading the code itself.
Leave blank spaces between logically-separate blocks of code, even when there aren't branches.  This improves human-readability.
I like to leave a space between operands in the operand list, like cmp  r0, #0 instead of cmp r0,#0.
My version:
Always comment the top of your function with some high level description of input/output register usage.  Just like in a higher-level language, describe the contract the function makes with its caller.
My asm code usually ends up littered with comments about alternatives I decided against.  It's not an ideal example of good style.
.syntax unified     @ allow 2 or 3 operand forms of instructions.
.cpu cortex-m0
.thumb              @ this is probably implied already by the .cpu

@@ input:  R0=divisor,  R1=dividend
@@ calculate R1/R0 by repeated subtraction
@@ output: R0=quotient, R1=remainder, C flag unset.
@@    or on division by zero: R0,R1 unchanged, C flag set.
@@ Other regs unmodified (even r2 and r3, which the normal calling convention allows functions to use as scratch regs)
.globl divu
divu:
      CMP   R1, #0         @ return 0,0 instead of divide error for the 0/0 corner case.
      BEQ   zero_dividend @ label names that describe why you go there are usually good.  Comments at the label can describe what happens there.

      CMP   R0, #0
      BEQ   div_by_zero

      @CMP   R0, R1        @ let this case fall through the loop once, instead of slowing down the common case to speed up this special case.
      @BLO   QuotientZero

      PUSH  {R3, LR}         @ LR doesn't make a good scratch reg, since many insns can only use low regs (R0-R7).  Push/popping it saves a BX LR
      MOVS  R3, #0           @ R3 = quotient = repeated-subtraction counter
@      LDR   R3, =#-1        @ account for the loop overshoot up-front.  But don't do this because cortex-m0 can't encode it in one insn other than a PC-relative load

sub_loop:                  @do{
      ADDS  R3, #1         @ quotient += 1.  (init is zero, so 0+1=1 if one successful loop)
      SUBS  R1, R0         @ dividend -= divisor and set flags,
      @ CMP   R0, R1       @ ...avoiding this cmp instruction.  Potentially a significant speedup for a tight loop.
      BLO   sub_loop       @} while(that didn't carry)@ i.e. while divisor was lower (unsigned) than the old value of dividend.

@EndWhile:
      @@ now we've subtracted one too many times.  Detecting that carry is the loop exit condition.
      @@ It's worth extra instructions outside the loop to save one inside the loop.
      @@ BUGFIX: original forgot to put the remainder in R1
      ADD   R1, R0         @ remainder, undoing the overshoot
      SUBS  R0, R3, #1     @  quotient, undoing the overshoot and clearing the C flag.
      @  Except that this will carry for 0xFFFFFFFF / 1.
      CMP   R0, R0         @ clear C flag.  TODO: avoid this otherwise-redundant instruction

      POP   {R3, PC}           @ return by popping straight into the PC

div_by_zero:      @@ We only get here with r0 == 0
      SUBS  R0, #1         @ Set the C flag and fall through to a mov the restores R0 to its original value

zero_dividend:    @@ CMP cleared the C flag
      MOVS  R0, #0         @ doesn't affect the C flag.   MOV Rd, #imm isn't available for Cortex-M0
      BX    LR

I'm not an ARM expert, and there may be a slight difference between popping into PC vs. running BX LR.  BX LR can return from Thumb code to ARM code, or vice versa, but popping into PC can't.  AFAIK, either is fine for Thumb -> Thumb returns which are your only option on a Cortex-M0.
This really does assemble.  I didn't test it, but the disassembly looks like we'd expect (which is a useful sanity check):
$ arm-linux-gnueabi-objdump -d arm-divu.o

arm-divu.o:     file format elf32-littlearm

Disassembly of section .text:

00000000 <divu>:
   0:   2900            cmp     r1, #0
   2:   d00a            beq.n   1a <zero_dividend>
   4:   2800            cmp     r0, #0
   6:   d007            beq.n   18 <div_by_zero>
   8:   b508            push    {r3, lr}
   a:   2300            movs    r3, #0

0000000c <sub_loop>:
   c:   3301            adds    r3, #1
   e:   1a09            subs    r1, r1, r0
  10:   d3fc            bcc.n   c <sub_loop>
  12:   4401            add     r1, r0
  14:   1e58            subs    r0, r3, #1
  16:   4280            cmp     r0, r0
  18:   bd08            pop     {r3, pc}

0000001a <div_by_zero>:
  1a:   3801            subs    r0, #1

0000001c <zero_dividend>:
  1c:   2000            movs    r0, #0
  1e:   4770            bx      lr

I don't know much at all about tuning for Cortex-M0, but perhaps aligning the top of sub_loop would be good.  Maybe to a 16-byte boundary, or at least so all three instructions are in the same 16-byte block.  (Currently the branch is in the next block after the ADDS/SUBS.)