Constructors should be class methods

Your method suggests, that an instance of the respective class is being created using the given text.
Thus you should make it a classmethod:

@classmethod
def create_from_text(cls, text):
    …

Comments vs. docstrings

Your multi-line comment describes the underlying algorithm.
You should summarize it in the method's docstring and move the complete description to your respective documentation docs.

Useful comments

This is useless:

# Easiest part, just set the transition to the next state
# Now do that check we spoke of earlier

while that may be helpful:

# Make every transition in the last state point to itself

Loop variables

While the i in for i in range(len(text)) is pretty self-explanatory, the j in for j in self.alphabet: is not.
What is j? Another index? A word? A character?
Consider renaming j to index, word or char respectively.

PEP 8

You follow it consistently with the exception of self.addTransition.

Iteration over strings.

Instead of

for i in range(len(text)):
    …
    if j == text[i]:

Use enumerate:

for index, char in enumerate(text):
    …
    if j == char:


Google Drive folders properties caching to file

Other than the fact that it's hard to read because your variables are not in Englishref, your code appears solid. Two observations:

Some comments would be beneficial, even if only function, parameter and return descriptions. Use of recursion should be clearly explained in comments, for the next poor soul who needs to figure out why they ran out of memory.
You have not explicitly handled the case of an invalid folder ID parameter in gerarJqTree().

The only optimization I'd suggest would be to do what you think would take longer; get all folders at once - but do it with the advanced Drive service so you have the container information as well. While you'll need to traverse the returned items to construct the output, you will eliminate several hundred service calls.


Unpacking tuple from Django's get_or_create function

I'd say this is a good example on how to not use DB.

The problem here is that for each keyword you will call a DB instead of perform this as a single call, so if you list of keywords is 1000 items then you will do 1000 calls to DB.

You can avoid this by splitting your call to:

1. Get existing keywords

existing_keywords = Keyword.objects.filter(keyword__in=keywords).values_list('keyword', flat=True)

2. Get list of not existing keywords

keywords = set(keywords)
not_existing_keywords = keywords.difference(existing_keywords)

3. Create objects with no existing keywords

Keyword.objects.bulk_create(Keyword(keyword=key) for key in keyword))

4. Now finally query your data from DB

keywords_qs = Keyword.objects.filter(keyword__in=keywords)

Note: If you are running on django 1.10+ and using Postgres then step 4 is not needed, since bulk_create will populate your keyword objects with PKs, otherwise you should do step 4


Project Euler Problem 3: Largest prime factor

Is there merit in removing {} on the if blocks?

If you are the kind of person who is likely to write bugs without the braces, then leave them in.

Other notes:

static long LargestPrimeFactor(long number)

Good naming.

Long will do you for the first few Euler problems but you might have to install System.Numerics and use BigInteger for some problems coming up soon.

long largestFactor = 1;

More good naming.

for (long i = 2; i<= Math.Sqrt(number); i++)

i is not descriptive.  possibleFactor perhaps?

i <= Math.Sqrt(number) is much slower than i * i <= number.

static bool IsFactorOf(long numerator, long denominator)
{
    return numerator % denominator == 0 || numerator == denominator;
}

Why numerator and denominator? There are no fractions.

What is the point of the right side of the ||? How can !(n%d==0) and (n==d) both be true?

static bool IsPrime(long value)
{

Your implementation is adequate now, but will be too slow for later problems.  Think about how you might optimize this. For example: if you've already checked divisibility by 2, then why are you checking 4, 6 and 8?

But more generally: Under what circumstances in your existing implementation is IsPrime ever false?  Suppose you are factorizing 840.

You start by throwing out the twos -- a prime -- and get down to 105.  Then you throw out the threes -- a prime -- and get down to 35. Then you check fours -- why? You've already checked twos, so four cannot be a factor.  Then you check fives, you have a factor, and surprise, 5 is a prime.

Your algorithm only finds prime factors because it has already thrown out all the composite factors who have smaller factors! So you don't have to check for primality at all in your algorithm.

Finally: you don't need it for this problem, but for later problems you will benefit greatly from having a method:

static IEnumerable<long> PrimeFactors(long number)

Can you implement such a method? If you can, then you can reimplement

static long LargestPrimeFactor(long number)
{
  return PrimeFactors(number).Max();
}

and you're done. In Euler problems it often pays to solve a more general problem, and then write a query against the more general solution.


Get count of digits of a number that divide the number

Do one thing

Let's start with your top level:

def count_div_digits(l):
    for number in l:

Firstly, l is a terrible variable name. It looks like 1. Avoid it at all costs. Secondly, this function is less useful than it could be simply because it requires a list of numbers. It'd be better if the function took a single number, then you could call it on a list separately if you want:

def count_div_digits(number):
    ...

for number in lst:
    count_div_digits(number)

Return, don't print

Right now, your count_div_digits simply prints its result. That's all well and good, but it'd be better if you just returned the number. If you want to print it, you can always just do:

print count_div_digits(number)

And this way, you can store the results somewhere else for further analysis later.

Avoid continue:

The less weird hops your loops make, the easier it is to follow along the logic. Right now you have:

if digit=='0':
    continue
else:
    # stuff

But it'd be clearer to just do:

if digit != '0':
    # same stuff

Proposed Solution

def count_div_digits(number):
    count = 0
    for digit in str(number):
        if digit != '0' and number % int(digit) == 0:
            count += 1
    return count

Generator Expressions

You could also write the above with the help of a generator expression by factoring out a length:

def sizeof(iterable):
    return sum(1 for _ in iterable)

def count_div_digits(number):
    return sizeof(digit for digit in str(number)
                  if digit != '0' and number % int(digit) == 0)

Whether you consider that an improvement or not is a matter of opinion.


As already mentioned there are formulas for enumerating the pythagorean triples, but your solution can be made quite fast by bounding the search space more. You have already taken care of the symmetry in the solutions by letting a be less then b (a <- [1..b]), but note that since a + b + c == 1000, once you know the value of a and b you know that c = 1000 - a - b so you only need to check that one case:

[(a,b,c) | a <- [1..500], b <- [1..a], let c = 1000 - a - b, a^2 + b^2 == c^2]

The above code runs in less then a second on my machine with GHCi.


You don't need to initialize the keys of results_map to 0. You can do it on the fly. Here is a generic example:

counts = {}
for value in values:
    if value in counts:
        counts[value] += 1
    else:
        counts[value] = 1

Even better, use collections.Counter instead. Generic example:

from collections import Counter

counts = Counter()
for value in values:
    counts[value] += 1

Refactor the method to check if app_name is in resource_name. Put APPS_MAP outside the functions so it can be accessed as a global variable.

def get_category(resource_name):
    for key, app_names in APPS_MAP.items()
        for app_name in app_names:
            if app_name in resource_name:
                return key
    return 'other'

Now you can rewrite the loop in count_resources_per_category() like this:

from collections import Counter

results_map = Counter()
for resource_name in resource_names:
    results_map[get_category(resource_name)] += 1
return results_map

It seems like determine_if_resource_count_issue() is checking to make sure only one field is non-zero. Here's a quick one-liner replacement. Put the print() statements outside this function.

def determine_if_resource_count_issue(results_map):
    return [v != 0 for v in results_map.values()].count(True) == 1

get_category() as implemented above is computationally expensive. Depending on your use case, you may want to consider using regex.
Don't pad your question with lorem ipsum lol.


Dataset and frequency list generation by looping over files

Styling
Some minor edits, but you should import each module on a new line, especially if you're assigning them different names.
import os
import numpy as np
import pandas as pd

It seems redundant here to assign subdir for just a single use. If there's plans to use it later sure, but as it stands this should be fine.
path = os.path.abspath(os.path.join(os.getcwd(), os.pardir, "rawdata"))

I know you said that you wanted to save on performance, but when you instantly call this function anyway you're always going to run these imports, so they should be at the top with the rest.
import regex as re
from html import unescape

The p_quote regex string is unnecessary when you can just use '"'. Python sees no real difference between strings bound in single or double quotes, meaning you can easily reference them like this.
p_quote = re.compile('"')

Don't use path + '/' + filename to set a file path. Use the os module. It performs certain operations based on the OS Python is being run on. os.path.join(path, filename) will work cross platform.
Also there's no real point to opening the file in r+ mode, as that allows you to read and write but all you ever do is read the file anyway.
As for your naming conundrum, I'd just use the actual column names. They're not going to actually clash since you call the columns with strings so there's a clear delineation from what is a list and what's a string. And what can be clearer than using the same name. Also generally you can leave list out of a variable name except if you actually need to distinguish it from others.
The exception to both in your case of course being that you have a separate list of filenames, so I've given that a different name but you might find a different name more suitable.
filenameDataList.append(filenameData)
components.append(component)
precedingWords.append(precedingWord)
nodes.append(node)
leftContexts.append(leftContext)
sentences.append(sentence)

...

df['sentence'] = sentences

Minor Performance
These are two notes that wont significantly reduce your speed from file to file because they're not affecting the regex but they will save you a fraction of a second per file which can build up if you're running it on many files.
You don't need to set n and c as part of a list, you can just comma separate them and python will understand. And it's faster to not create an unneeded list.
[n, c] = p_filename.split(filename.lower())[-3:-1]

There's also no reason to use join here. It's slower than just string concatenation since it's just two items and you're creating the list for the sake of the join.
fn = n + "." + c

Refactoring
I would put all the imports together as I said above. Also I would put all the regex compilations near the top. They're effectively a constant so it's best to always keep constants near the top of the file rather than in a function where they'll be recreated the exact same (not that this affects your performance). This would mean that you have this all before your data frame is created:
import numpy as np
import os
import pandas as pd
import regex as re

from html import unescape
from datetime import datetime

start_time = datetime.now()

p_filename = re.compile(r"[./\\]")
p_last_word = re.compile(r"^.*\b(?<!-)(\w+(?:-\w+)*)[^\w]*$", re.U)
p_sentence = re.compile(r"<sentence>(.*?)</sentence>")
p_typography = re.compile(r" (?:(?=[.,:;?!) ])|(?<=\( ))")
p_non_graph = re.compile(r"[^\x21-\x7E\s]")
p_quote = re.compile(r"\"")
p_ellipsis = re.compile(r"\.{3}(?=[^ ])")

As for splitting up functions, I don't personally think that's necessary as your functions aren't overly long and it's a relatively specific process without a lot of repeating code, so I would keep to the two separate ones you have here.


Validate the inputs and perform actions accordingly

I think you have some great questions here!

You asked:

  Is there any better way to do the above things so that the code looks clean?

I'm not sure that's your only consideration here because it looks like this code is designed to be as efficient as possible. I say that because of the fact that the validation logic skips over the record as soon as a problem is found and the packetBuilder is only created after the initial validation - thereby avoiding the cost of creating the object every time through the loop regardless of the validity of the data.

So, with all of this in mind I'm afraid that my answer to your question will have to be: there might be slight improvements you can make but you can't avoid the null checking unless the Exception thrown by the builder is very detailed about what exactly went wrong and you can use it to gather your metrics.

If you want to make the code more modular you could split the validation logic into separate methods - perhaps one for each field. I'm not sure exactly how efficient you're trying to be and there is some cost involved with calling methods, so this might not be a good change for you. However, if peak performance is required then I'm sure you're familiar with profiling so just use whatever tool you typically use and determine whether the change impacts performance.

Along the same line of thinking you might even create an object to hold the fields and provide methods for validating each of them as well as a method to validate the data in general (this method could call each of the field validation methods and determine a result based on the results for the fields). Note that this approach also has overhead cost as you would create this object each time through the loop.

Here is what the class to hold the fields might look like:

public class PacketValidation {
    private String clientId, deviceId, payId, crossId;
    private Map<String,String> appPayload;
    // Not sure how you initialize the logger, so just added it as a field.
    private Logger logger;

    public PacketValidation(GenericRecord payload){
        clientId = (String) DataUtils.parseRecord(payload, "clientId");
        deviceId = (String) DataUtils.parseRecord(payload, "deviceId");
        payId = (String) DataUtils.parseRecord(payload, "payId");
        crossId = (String) DataUtils.parseRecord(payload, "crossId");
        appPayload = (Map<String, String>) DataUtils.parseRecord(payload, "appPayload");
    }

    public boolean isValid(){
        return isValidClientIdDeviceId() && isValidPayId() && isValidAppPayload();
    }

    private boolean isValidAppPayload() {
        if (MapUtils.isEmpty(appPayload)) {
            DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
                MetricName.INVALID_PAYLOAD);
            logger.logError("dropping records. invalid payload is coming.");
            return false;
          }
        return true;
    }

    private boolean isValidPayId() {
        if (payId == null) {
            DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
                MetricName.MISSING_PAY_ID);
            logger.logError("dropping records. invalid payId is coming.");
            return false;
          }
        return true;
    }

    private boolean isValidClientIdDeviceId() {
        if (clientId == null && deviceId == null) {
            DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
                MetricName.INVALID_ID);
            logger.logError("dropping records. invalid clientId and deviceId is coming.");
            return false;
          }
        return true;
    }

    public String getClientId() {
        return clientId;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public String getPayId() {
        return payId;
    }

    public String getCrossId() {
        return crossId;
    }

    public Map<String, String> getAppPayload() {
        return appPayload;
    }
}

Then your code might look something like:

try {
  GenericRecordDomainDataDecoder decoder = new GenericRecordDomainDataDecoder(config);
  while (true) {
    ConsumerRecords<byte[], byte[]> records = consumer.poll(1000);
    for (ConsumerRecord<byte[], byte[]> record : records) {
      DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
          MetricName.TOTAL_NUMBER);
      GenericRecord payload = decoder.decode(record.value());

      //Replaced validation logic with the following 3 lines:
      PacketValidation validation = new PacketValidation(payload);
      if(!validation.isValid())
          continue;

      DataMetricHolder.getInstance().increment(validation.getPayId(), MetricName.TOTAL_NUMBER);

      Builder packetBuilder = new DataPacket.Builder(payload);
      if (validation.getClientId() != null) {
        packetBuilder.setClientId(validation.getClientId());
      }
      if (validation.getDeviceId() != null) {
        packetBuilder.setDeviceId(validation.getDeviceId());
      }
      if (validation.getCrossId() != null) {
        packetBuilder.setCrossId(validation.getCrossId());
      }
      DataPacket packet =
          packetBuilder.setPayId(validation.getPayId()).appPayload(validation.getAppPayload()).build();
      System.out.println(packet);
    }
  }
} catch (Exception ex) {
  // logging error
}

Some final thoughts:

I'm not sure how often you use the field names, but it's generally a good idea to use constants of some kind if you're going to use them in more than one place. So for something like this:

clientId = (String) DataUtils.parseRecord(payload, "clientId");

I would typically expect to see something more like:

clientId = (String) DataUtils.parseRecord(payload, Constants.CLIENT_ID);

This helps to avoid spelling mistakes, whitespace issues, case sensitivity issues, etc.

I also noticed that your code has the following if statement:

Map<String, String> appPayload...
if (MapUtils.isEmpty(appPayload))

I'm assuming that Map is java.util.Map in which case I'm not sure why you don't simply use Map.isEmpty() unless MapUtils is doing a null check at the same time - meaning treating null as being empty.

I hope this helps you!

EDIT

Regarding your comment about having multiple consumers, I think you'll probably want to use a combination of the composite pattern and the strategy pattern so that you can try to reuse as much code as possible.

As for implementing a solution to this problem - if your consumers all use the GenericRecord class you could do something like the following:

public class PacketValidation {
    //Added a collection of Validatable objects to the class
    private Collection<Validatable> validationList;
    private String clientId, deviceId, payId, crossId;
    private Map<String,String> appPayload;
    private Logger logger;
    private GenericRecord record;

    public PacketValidation(GenericRecord payload){
        record = payload;
        clientId = (String) DataUtils.parseRecord(payload, "clientId");
        deviceId = (String) DataUtils.parseRecord(payload, "deviceId");
        payId = (String) DataUtils.parseRecord(payload, "payId");
        crossId = (String) DataUtils.parseRecord(payload, "crossId");
        appPayload = (Map<String, String>) DataUtils.parseRecord(payload, "appPayload");

        //Added logic in constructor to create the validators
        // only created one as this is a quick example.
        validationList = new ArrayList<Validatable>();
        validationList.add(new ClientIdAndDeviceIdValidator());
    }

    //Determine if the data is valid by calling `isValid` on all validators
    public boolean isValid(){
        for(Validatable validate: validationList){
            if(!validate.isValid(record))
                return false;
        }
        return true;
    }

    //Getters removed for brevity
}

The validator class would look something like:

public class ClientIdAndDeviceIdValidator implements Validatable {

    // Again, not sure how you're initializing this so just added a field for now.
    private Logger logger;

    @Override
    public boolean isValid(GenericRecord record) {
        String clientId = (String) DataUtils.parseRecord(record, "clientId");
        String deviceId = (String) DataUtils.parseRecord(record, "deviceId");

        if (clientId == null && deviceId == null) {
            DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
                    MetricName.INVALID_ID);
            logger.logError("dropping records. invalid clientId and deviceId is coming.");
            return false;
        }
        return true;
    }

}

and the Validatable interface may look like this:

public interface Validatable {
    public boolean isValid(GenericRecord record);
}

Now what you'll notice is that the implementation, ClientIdAndDeviceIdValidator, has to get the fields out of the GenericRecord because of the way the isValid method is written. Sometimes you want to validate that two fields together and other times just one field so in order to process all of the Validator objects generically we have to go one level above the fields and use the GenericRecord. Also note that I'm assuming you'll have one class for each consumer - therefore PacketValidation is not a generic class but rather one that is specific to the consumer.

Another possible solution would involve using Java Generics; here is an example:

public class PacketValidationGeneric {
    //Added a generic validatable object field
    private GenericValidatable<String> clientIdDeviceIdValidator;
    private String clientId, deviceId, payId, crossId;
    private Map<String,String> appPayload;
    private Logger logger;

    public PacketValidationGeneric(GenericRecord payload){
        clientId = (String) DataUtils.parseRecord(payload, "clientId");
        deviceId = (String) DataUtils.parseRecord(payload, "deviceId");
        payId = (String) DataUtils.parseRecord(payload, "payId");
        crossId = (String) DataUtils.parseRecord(payload, "crossId");
        appPayload = (Map<String, String>) DataUtils.parseRecord(payload, "appPayload");

        //Creating the specific validator here:
        clientIdDeviceIdValidator = new ClientIdAndDeviceIdGenericValidator();
    }

    public boolean isValid(){
        //Obviously there is more to be done that just validate the two fields, but this is just a quick example.
        return clientIdDeviceIdValidator.isValid(clientId, deviceId);
    }

    //Removed some code for brevity
}

Here is the validator implementation:

public class ClientIdAndDeviceIdGenericValidator implements GenericValidatable<String> {

    // Again, not sure how you're initializing this so just added a field for now.
    private Logger logger;

    @Override
    public boolean isValid(String ... fieldList) {
        //Since the parameter is very generic, you need to validate the input.
        if(fieldList.length < 2)
            throw new RuntimeException("Not enough fields provided, minimum 2 fields required - clientId and deviceId in that order.");
        String clientId = fieldList[0];
        String deviceId = fieldList[1];

        if (clientId == null && deviceId == null) {
            DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
                    MetricName.INVALID_ID);
            logger.logError("dropping records. invalid clientId and deviceId is coming.");
            return false;
        }
        return true;
    }

}

This is the interface:

public interface GenericValidatable<T> {
    public boolean isValid(T ... fieldList);
}

You'll notice that the PacketValidationGeneric.isValid() method can no longer invoke each validator in the same way because the parameters can differ. However, if you're going to have one class for each consumer then maybe it doesn't matter so much that you have to invoke each validator this way. Also notice, however, that you need to validate the input to each validator as the parameter to GenericValidatable.isValid is generic.

Once again, I hope this helps!


Is this correct way to setup DB Infrastructure with repository pattern and Dapper

Quick remarks:

Why do you convert a string to a string: Convert.ToString(ConfigurationManager.ConnectionStrings["MyDBConn"].ConnectionString);? It's even called a ConnectionString.

Why do you use Dapper and then don't use it properly? Why return a DataSet? Why use SqlMapper and DynamicParameters? Why make life so hard for yourself when Dapper is making things so easy? Look at the homepage of Dapper Tutorial and Documentation:
 using (var conn = new SqlConnection(connectionString))
 {
     var invoices = conn.Query<Invoice>(sql);
 }

That is all you need. No endless checking of the state of your connection, no opening and closing it yourself, no try...finally blocks which completely ignore any exception that might occur. Write the correct query and let Dapper map the results to your class.


I see nothing wrong with what you already have. Assuming of course that you meant to append identical data to each $arrSource element. You are already doing the shorthand by using the reference operator. The only other way would be to write it all out manually, which would be pointless, unless you are looking for more novice readable code. I would hesitate to add, however, that unset should be called tithin the first foreach loop. Though I could not confirm 100% because I don't use the reference operator to know its quirks :)


I think my original comment in regards to using OrderBy could still possibly still even with your latest edits (and BTW that code does not compile, there is no declared task object :)).

How about something like:

var query = from task in tasks
            let helperTask = task.getHelperObject()
            select new
            {
               Completed = helperTask != null && helperTask.Completed,
               Task = task
            };

return query.OrderBy(p => p.Completed).Select(p => p.Task).ToList();

UPDATE:
Another excellent option suggested by svick to further refine and remove the anonymous object selection is something along the lines of:

var query = from task in tasks
            let helperTask = task.getHelperObject()
            orderby helperTask != null && helperTask.Completed
            select task;

return query.ToList();

I guess if I could I would do away with ToList() altogether and return IEnumerable but that depends on the context of the operation.  I also personally like using an intermediate variable here (query) as I think it just helps readability.  All to their own on that front though.


We're missing an include of <stdint.h>.  On the other hand, we include  <time.h> which we're not using.
The code doesn't compile here because of the use of Annex K scanf_s() without checking for its availability.  There's no reason not to use ordinary scanf() here (but do examine its return value - that's important!)
There are a lot of magic constants sprinkled throughout the code, with no indication whether they relate to each other.  That makes this an unmaintainable program, because you can't change any of those individually without understanding the whole program.
Also, with all the functionality thrown together in main(), that makes it harder to understand the purpose of each part of the code.  Please divide the code into well-named functions (probably with static linkage).
I recommend fixing those before posting another review request to look at this in any depth.


One Time Pad algorithm for encryption and decryption

I have a few suggestions regarding performance:

Choosing between 2 things n times is slow, especially when factoring in the fact that you are appending to an array n times.

I would take advantage of the random module's getrandbits method like so:

def gen_random_key(n):
"""Generates a random key of bits (with 0s or 1s) of length n"""
return bin(getrandbits(n))[2:].zfill(n)

A full explanation:

bin produces a binary string from an integer
getrandbits(n) produces an integer from n random bits
[2:] cuts out the '0b' that is put at the start of the string by bin
.zfill(n) pads the resulting string with 0's to force a length of n

With shorter strings you won't notice the performance difference but with a larger string the speed difference is immense.

I used timeit to get the following timings on my machine:

10000 bits, called 100 times:
1.12 seconds vs 0.003 seconds

100000 bits, called 100 times:
11.5 seconds vs 0.003 seconds

As you can see, my method is orders of magnitudes faster.

For xor, you can use a similar approach:

def xor(m, k):
"""Given strings m and k of characters 0 or 1,
it returns the string representing the XOR
between each character in the same position.
This means that m and k should be of the same length.

Use this function both for encrypting and decrypting!"""
a = int(m, base=2)
b = int(k, base=2)
return bin(a ^ b)[2:].zfill(len(m))

Now ignoring that, let's discuss your general approach.

You convert a string of characters into a string of 0's and 1's. This is actually wasteful, as you are multiplying your memory usage immensely. The reason is that most characters take many bits to store. Thus, you are replacing one character with many 0 or 1 characters. Assuming pure ASCII, you might be using up to 7x the memory, and it will be quite a bit worse with arbitrary Unicode characters.

There's also another issue. Once you have your ciphertext, there isn't really a good way to recover the original string. Sure you can get the original bits back, but how do you know which how many or which bits correspond to which letter? You could solve this with padding, but that is an ugly solution that wastes even more memory.

Instead I propose the following solution:

Generate a string of characters (ASCII is fine, doesn't really matter too much) as a key. The key should have the same number of characters as the string. Then xor the ord of the characters in the same spot and make a new character with the result (by using chr). Join all these characters to form the cipher text.

My version of this (without comments/tests) is this:

def gen_key(string):
    return "".join(choice(string.printable) for _ in s)

def encrypt(string, key):
    return "".join(chr(ord(i) ^ ord(j)) for (i, j) in zip(string, key))

def decrypt(ciphertext, key):
    return encrypt(ciphertext, key)


Your code is not reliable because Counter is unordered.  In many cases, it comes up with the right result, but do not depend on it.  I will not give an alternate solution because Code Review is for improvements on existing code, not for writing new code.  Although your code should not be used for sorting, I have a couple comments on what you did.

You aren't using length, so why require it for an argument?

Instead of creating a copy of a list and then changing each index, create an empty list and add things to it.

Your implementation of Counter does not take advantage of it.  You use it very similarly to how you would use a dictionary.  Just use Counter(aList)

You can simplify your for key in c: loop by using itertools.repeat.  Note: don't use it for mutable objects.

Your naming is inconsistent.  PEP 8 recommends snake_case, but you use both snake_case and pascalCase.  You aren't required to comply with PEP 8's recommendation, but you should at least be consistent.  You should also use more descriptive names than c, for example.

The new code:

from collections import Counter
from itertools import repeat

def counting_sort(number_list):
    """
    counting sort does not work for negative numbers
    counting sort assumes that each element is SMALL INTEGER

    running time is O(maxVal - minVal) ---> Linear

    (Useful only when the difference between maxVal and minVal is not large)
    """

    sorted_list = []
    for value, amount in Counter(number_list).items():
        sorted_list.extend(repeat(value, amount))

    return sorted_list


Is there a better or more concise way to do this?

the best javascript is no javascript ;-)

you could use css3 columns, see http://jsfiddle.net/bjelline/JWnaz/ for the result

ul {
-moz-column-count: 2;
-moz-column-gap: 20px;
-webkit-column-count: 2;
-webkit-column-gap: 20px;
column-count: 2;
column-gap: 20px;

}

if you are worried about browser support: there's a polyfill for that
http://www.csscripting.com/css-multi-column/
that falls back to javascript if the browser doesn't honor the css yet.


Calling individual classes for navigation items

I think that all you are looking for is:

//assumes sidr is top level container for menu
//you should consider adding a generic class to menu items when page is assembled
jQuery('#sidr > ul > li').click(function() {
     $this = jQuery(this);
     $this.find('ul').slideToggle(200);
});

If you cannot rely on a selector (like I used above) to find the elements that you are interested in, or if you cannot add classes to the elements when the page is assembled then you could add the class in code:

jQuery('#sidr ul li').has('ul').addClass('hasSubMenu');

Now you can use:

jQuery('.hasSubMenu').click(function() {
     $this = jQuery(this);
     $this.find('ul').slideToggle(200);
     $this.toggleClass('clicked');
});

This also saves re-evaluating the various selectors, which is much more efficient.


Creating instances of all subclasses in Python

You might try this:

myTechniques = [cls() for cls in Technique.__subclasses__()]

Note that it does not return indirect subclasses, only immediate ones. You might also consider what happens if some subclass of Technique is itself abstract. Speaking of which, you should be using ABCMeta and abstractmethod.


Forming combinations of a 16 bit binary number

Give your operators some breathing space, e.g.:

for (int i = 0; i < possible.length; i++)

possible is not very good name (it implies that something is impossible. I recommend alphabet instead.
possible never changes. It makes it a good candidate for a final class member. Passing it down recursively wastes some stack space.
I don't think overloading formCombinations is warranted.
I see nothing obviously wrong performance wise. After all, you generate all permutations, and you generate each permutation exactly once. Of course, StringBuilder may impose some hidden penalties; Java experts would give an authoritative answer.

In any case, an iterative solution requires less space, doesn't need a StringBuilder, and may serve as an iterator (in a sense of supporting has_next() and next() methods). I highly recommend implementing it: it is simple and instructive. Hint: think of next permutation as adding 1 to a binary number.


Molybdenum2019 challenge efficient implementation

Nice solution, find below my suggestions.

Creating a list from a set:
List<Integer> listaLideresOrdenada = new ArrayList<Integer>();
listaLideresOrdenada.addAll(listaLideres);

The set can be passed directly to the constructor of ArrayList:
List<Integer> listaLideresOrdenada = new ArrayList<Integer>(listaLideres);

Copying the input array A to B:
B = Arrays.copyOf(A, array_lengh);

This can be avoided since A can be modified in place in this problem.

Getting a value of a map or a default:
int repeticones = counter.get(B[n]) == null ? 0 : counter.get(B[n]);

Since Java 8 Map offers getOrDefault:
int repeticones = counter.getOrDefault(B[n], 0);

Optimization
The current solution uses this approach:

For each sliding window in A
Increment all elements of the sliding window by 1
Calculate the frequencies of all elements in A
Update the result if a leader is found

It can be considered a \$O(n^2)\$ brute force approach, typically not enough to solve a HARD problem on Codility.
Consider this approach: every time the sliding window moves to the right, the element on the left leaves the window, and the element on the right enters the windows. Therefore it is enough to update the frequencies of only these two numbers.
This approach improves the complexity to \$O(n*log(n))\$. The sorting operation is now the bottleneck.
A trick to avoid sorting is to use an array (for example, leaders) of size M (which is the value of the biggest element in A). Every time a leader x is found add it to leaders like leaders[x] = true. Finally, iterate on leaders and collect the results in order.
Getting rid of the sorting operation improves the complexity to \$O(m)\$, but it's still too slow! The solution needs to run in less than 0.1 seconds for an input array A of 100K elements.
So as a last optimization we can get rid of the map for counting the frequencies and use a simple array freq. Although updating a map is a very quick operation, updating an array is faster.
Reworked code
public static int[] solution(int K, int M, int[] A) {
    boolean[] leaders = new boolean[M + 2];
    int[] freq = new int[M + 2];
    int threshold = A.length / 2;

    // Increment initial sliding window by 1
    for (int i = 0; i < K; A[i]++, i++);

    // Calculate frequencies of all elements in A
    for (int i = 0; i < A.length; freq[A[i]]++, i++);

    // If there are leaders save them
    for (int i = 0; i < freq.length; i++) {
        leaders[i] = freq[i] > threshold || leaders[i];
    }

    for (int i = 1; i < A.length - K + 1; i++) {
        // Update frequency of element (on the left) leaving the sliding window
        int left = i - 1;
        freq[A[left]]--;
        A[left]--;
        freq[A[left]]++;

        // Update frequency of element (on the right) entering the sliding window
        int right = i + K - 1;
        freq[A[right]]--;
        A[right]++;
        freq[A[right]]++;

        // If there are new leaders save them
        leaders[A[right]] = freq[A[right]] > threshold || leaders[A[right]];
        leaders[A[left]] = freq[A[left]] > threshold || leaders[A[left]];
    }
    // Collect the leaders (in order)
    return IntStream.range(0, leaders.length)
            .filter(i -> leaders[i])
            .toArray();
}


It looks good to me. I would change

    if (!preyDead[i])
    {

To

    if (preyDead[i])
            continue;

Just so its less nested. Same with preyDead[j]. But everything looks fine to me.
A tip I once saw on SO is, if your list order doesn't matter you can sort the preyDead so all the dead would be at the beginning or end and that will help branch prediction. However thats assuming its not really expensive to sort it and that its a very erratic bool and it isnt true/false 90% of the time already.

Thats a uber optimize that may not help, it shouldn't be done less you really really want to


Here are some things that may help you improve your program.
Separate interface from implementation
The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate .cpp file.  The reason is that you might have multiple source files including the .h file but only one instance of the corresponding .cpp file.  In other words, split your existing data.hpp and util.hpp files into a .h file and a .cpp file.
Understand the use of namespaces
Your code is correctly using <cmath> instead of <math.h>.  The difference between the two forms is that the former defines things within the std:: namespace versus into the global namespace.  So this implies that instead of using cos and sin, the code should be using std::cos and std::sin
Use const where practical
There are a number of named constants in the program such as unsigned int n_dims = 2;.  It's very good practice to name these, but even better is to declare them const or better still constexpr.  The reason is that it allows the compiler to perform better optimizations without sacrificing readability.
Don't use std::endl if you don't really need it
The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
Use "range for" and simplify your code
The code currently includes these lines:
for (std::vector<Point>::iterator it = d.begin(); it != d.end(); ++it) {
    std::cout << it->x << " " << it->y << " " << it->label << std::endl;
}

Since C++11, however, we have a range for which simplifies it to this:
for (const auto& point : d) {
    std::cout << point.x << " " << point.y << " " << point.label << '\n';
}

Write a stream inserter for your class
We can further refine the for loop above by creating a custom inserter for the Point class:
std::ostream& operator<<(std::ostream& out, const Point& point) {
    return out << point.x << " " << point.y << " " << point.label;
}

Now our loop in main is even simpler:
for (const auto& point : d) {
    std::cout << point << '\n';
}

Use standard library algorithms
We can use std::copy to copy from the vector to std::cout, replacing the loop with a single statement:
std::copy(d.begin(), d.end(), std::ostream_iterator<Point>(std::cout, "\n"));

Consider using a better random number generator
If you are using a compiler that supports at least C++11, consider using a better random number generator.  In particular, instead of rand, you might want to look at std::uniform_real_distribution and friends in the <random> header.  Also, instead of doing this:
if (random.rand() < 0.5) {
    it->x = r1;
    it->y = r2;
    it->label = 1;
} else {
    it->x = -r1;
    it->y = -r2;
    it->label = 0;
}

I would suggest using a std::bernoulli_distribution.
Rethink the classes
Rather than having the vaguely named Data class creating Points, I'd suggest moving that functionality into the Point class.  Since this is actually creating a Point, it makes sense to me to create a custom constructor with this functionality:
Point::Point() {
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_real_distribution<> spread(0.0, 4.0*3.14);
    static std::uniform_real_distribution<> noise(0.0, 1.0);
    static std::bernoulli_distribution type(0.5);
    static constexpr double multiplier[]{-1.0, +1.0};

    label = type(gen);
    double r = spread(gen);
    x = multiplier[label] * (-std::cos(r) * r + noise(gen));
    y = multiplier[label] * (+std::sin(r) * r + noise(gen));
}

Minimize memory use
It's not critical for this program, but rather than storing everything in a vector only to print it and then destroy the vector, a more memory efficient approach would be to generate each point as needed and emit it directly.  Using the Point constructor and stream inserter as defined above, this becomes trivial.
Result
Here's the entire program as rewritten with all of these ideas:
#include <random>
#include <iostream>
#include <iterator>
#include <cmath>

struct Point {
    Point();
    double x;
    double y;
    unsigned int label;
};

Point::Point() {
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_real_distribution<> spread(0.0, 4.0*3.14);
    static std::uniform_real_distribution<> noise(0.0, 1.0);
    static std::bernoulli_distribution type(0.5);
    static constexpr double multiplier[]{-1.0, +1.0};

    label = type(gen);
    double r = spread(gen);
    x = multiplier[label] * (-std::cos(r) * r + noise(gen));
    y = multiplier[label] * (+std::sin(r) * r + noise(gen));
}

std::ostream& operator<<(std::ostream& out, const Point& point) {
    return out << point.x << " " << point.y << " " << point.label;
}

int main() {
    for (auto i{3000}; i; --i) {
        std::cout << Point() << '\n';
    }
}


Checking if a string parameter contains only digits

There is one major flaw that will come back and haunt you with this code. If you enter an invalid number, there is absolutely no indication whatsoever that it was invalid.

If it is not valid, you should do this:

throw new IllegalArgumentException("Invalid mobile number: " + mobile);

Incorporating Heslacher's suggestions I would do this:

public void setMobile(String mobile) {
    if (!containsOnlyDigits(mobile)) {
        throw new IllegalArgumentException("Invalid mobile number: " + mobile);
    }
    this.mobile = mobile;
}

Another edge case that should be handled is the empty string. I assume you don't want to classify that as a valid mobile number? Then handle it also in containsOnlyDigits or handle it in setMobile.

if (mobile.isEmpty()) {
    throw new IllegalArgumentException("Empty string is not a valid mobile number");
}


There are two points where you can improve the performance. This is more related to the algorithm itself, but I guess the answer fits better here than in crypto.SE...

When computing m and u, you are using mod(r) and divide(r). But since r is a power of 2, these are just a bitwise and (with r - 1) and a right shift (by n.bitLength()), which should be much faster. It also helps reducing t modulo r (also using and) before multiplying by nPrime.
Montgomery works better at the word level. If n has w words, then your code takes 2 * (w^2) word multiplications when computing m and u, but could take w^2 + w when using word-level Montgomery. So if you really need speed, you'll need to use an array of integers instead of BigInteger.


MATLAB's documentation about the scatterInterpolant function actually mentions in passing how one would do this in https://www.mathworks.com/help/matlab/ref/scatteredinterpolant-object.html#bvkm1tv-4. In short, you would set F.ExtrapolationMethod to None so that F returns NaN for points that do not lie inside the convex hull of the points defined by x and y. This way, you can avoid writing for loops and a bunch of reshape commands, which can take a while for large vectors and matrices.

x = [3 3 3 4 4 4 4 4 5 5 5 5 5]';
y = [1 2 3 0 1 2 3 4 0 1 2 3 4]';
z = [.5 .505 .51 .51 .51 .51 .51 .515 .535 .528 .53 .53 .53]';

F = scatteredInterpolant(x,y,z,'natural');

delta = 0.5;
ti = 0:delta:5;
si = 0:delta:4;
[xq,yq] = meshgrid(ti,si);
zq = F(xq,yq);

figure
hold on
mesh(xq,yq,zq)
plot3(x,y,z,'r.','MarkerSize',10)
hold off
view(3)
axis([0 5 0 4 0.46 0.54])

F.ExtrapolationMethod = 'none';
zqe = F(xq,yq);

figure
hold on
mesh(xq,yq,zqe)
plot3(x,y,z,'r.','MarkerSize',10)
hold off
view(3)
axis([0 5 0 4 0.46 0.54])

Plot of all points, including extrapolated ones:

Plot of points inside convex hull, excluding extrapolated ones:


Notes:

Any reason not to set the attributes in a single create step?
DRY by using procs for short-lived functions.
Methods should return meaningful values. Here it makes sense to return the newly created object.
(As Mark pointed out) The mismatch names between attributes makes the code more verbose that it should be. However, I guess part of this mismatch already comes from the app you are patching.
:provider => person.provider. Note that this can break referential integrity. Person may change its provider in the future, but this model will remain as it is.

I'd write:

def self.create_from_person!(person)
  code = lambda { |value| value ? 1 : 2 }
  create!({
    :person => person,
    :provider => person.provider,
    :age_eligible_code => code[participant.age_eligible?(person)],
    :county_of_residence_code => code[participant.psu_county_eligible?(person)],
    :first_prenatal_visit_code => code[participant.first_visit?(person)],
    :pregnancy_eligible_code => code[participant.pbs_pregnant?(person)],
  })
end


Generally what you do is dangerous. More dangerous as you might expect. As soon as you have something odd like a line break in a package or import line, a double semicolon or multiple import statements in a line, the code will break. If your keywords ("package", "import", "Generated") are used somewhere inside the interface, it will break as well (note that these words could appear e.g. in comments).

If you don't want to use a "real" Java parser, there are some things you can do to improve your code: If you don't find a closing semicolon for package or import, add the next line as long as you don't have one - or throw at least a meaningful error. You can also check if you have two semicolons in a package or import line. But I think the most important point is to break your loop in 4 parts in order to make your changes as "local" as possible. The first loop deals with the package, the second with the imports, the third with Generated and the fourth just adds the rest without changing. So your are safe that after a step is done, it can't do any harm to the following code. Another thing you could try is to preprocess the code with some formatter / pretty printer, which could get rid of some quirks.

Before the code gets at least a little bit more secure, I wouldn't care about performance too much. Consider adding some JUnit tests (ask your colleagues for some "mean" input classes - you will be surprised which weird monsters they can imagine - and use the more realistic examples).


What's the point of string input = value;? Why not work with value directly?

Comments should tell me why,  not what. If you suspect I cannot detect //splitting of string into substrings from your code, then your code is bad.

testModel is a class and thus should be PascalCase;.

cmdText is a collection of commands? That variable name doesn't suggest so at all. No wonder you need to preface it with //list of commands. If it is a list of commands, call it commands. Or considering the context, validCommands.

What's the point of this:

if(cmdText.Contains(payload.CommandText))
{
    //return valid
}

This doesn't do anything.

You start out using var, yet later on you get more explicit: HttpResponseMessage message, string result. Be consistent.

Same for your if...else:

if (message.IsSuccessStatusCode)
{
    string result = message.Content.ReadAsStringAsync().Result;
    return message.Content.ReadAsStringAsync().Result;
}
else
return message.StatusCode+"kindly contact to administrator";

The bad indentation hide that return message.StatusCode+"kindly contact to administrator"; is actually your else. Always use brackets!

What's the point of string result = message.Content.ReadAsStringAsync().Result;? Why not simply return message.Content.ReadAsStringAsync().Result;?

Quite frankly this code looks very unfinished. Your style is inconsistent, indentation is all over the place, there are superfluous blank lines (after using (var httpClient = new HttpClient()) for instance), the comments are superfluous, there's code in there that doesn't do anything,...

This also looks like a method in a Controller, and that's worrying. Because even if it's a mere 50 lines, if you have several methods like this pretty soon your controller class will be very bloated. Moreover this one method does three things:

convert the incoming data into a payload
checking the payload against a list of values
posting the payload to another API

Each of these should be their own method, and thus the body of this controller should be its own class, split into multiple methods. Look for instance at MediatR to "un-bloat" your controllers.


Groupby and moving average function in pandas works but is slow

Iterating in Python is slow, iterating in C is fast. So, it's best to keep as much as possible within Pandas to take advantage of its C implementation and avoid Python.

You can use apply on groupby objects to apply a function over every group in Pandas instead of iterating over them individually in Python.

df["metric1_ewm"] = df.groupby("person").apply(lambda x: x["metric1"].ewm(span=60).mean())

This gives me a run time of

  3.21 ms ± 181 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

You can then also apply this over multiple columns:

df[["metric1_ewm", "metric2_ewm"]] = df.groupby("person").apply(lambda x: x[["metric1", "metric2"]].ewm(span=60).mean())

With that being said, you could generalize and reduce your run_ewm function by passing it a dataframe and a list of columns to apply ewm to:

def set_ewm(df, cols):
   df.sort_values("timestamp",inplace=True)
   df[[c+"_ewm" for c in cols]] = df.groupby("person").apply(lambda x: x[cols].ewm(span=60).mean())

You could also just return the columns or copy the dataframe before setting ewm, then returning the new dataframe to avoid modifying the dataframe inplace.


The obvious problem with this is it will detect any function that uses TranLock calling any other function that also uses TranLock (since there is only a single global count). That is, if func() (which uses TranLock) calls bar() (which also uses TranLock) then bar() will erroneously fail.

In order to make a lock like this that can be used with multiple functions, create a class with no static members, then in each function where you want to use a lock, create a static instance of the class. That way, each function will have its own independent counter. However, you can't rely on the class destructor in this case because the destructor of static objects is not called when the object goes out of scope.

You could use a hybrid of these two techniques, for example

struct TranLock
{
    int &count;
    TranLock(int &count): count(count) { failed = count; if (!failed) ++count; }
    ~TranLock() { if (!failed) --count; }
};

void func()
{
    static int TranLock_count;
    TranLock lock(TranLock_count);
    if (lock.failed) {
        ...
    }
    ...
}

Finally, you don't really need to maintain an int count at all. Since you only ever increment count when it is zero, a bool flag would do equally well.


Correct use of MVVM and MouseEvent Handling

Looks OK to me. You do leak views to your viewmodel though. Some better approaches:

Handle event on rectangle itself. It will allow you to bind it's DataContext directly to command parameter. This should eliminate the leak.
Use items control that supports selection, i.e. ListBox. Then you will be able to bind to SelectedItem property directly without any events.

Other minor things:

Base postfix is normally used to indicate an abstract class. Might want to remove it from your command class, since it is clearly not abstract.
I'm not sure where this whole thing with lazy initialization is coming from (it is not the first time I see it), but it makes no sense to me. What's the point in lazy initialization for commands? Just use regular readonly property:

public ICommand MouseTestCommand {get;}

And initialize it in constructor. It is cleaner and requires less code to write. Also you might want to create another constructor for your command, that passes null for CanExecute by default.


Get an object with null values from an array of nested objects

Performance.

map and flatMap create copies of the arrays.
For each new item added to the result you rebuild the whole results object ({ ...ac, [a]: null})
For each property in the result you create a temp object to hold the key value pair.

These CPU, memory allocation, and GC burdens that can be avoided.

Some will argue that the overhead for small data sets is trivial and thus inconsequential.

Performance always matters and coding without though of performances leads to poor design habits that will bite. Many small inconsequential performance extras can quickly sum up to overall poor performance. Especially true in JavaScript where the target platform's capabilities vary so greatly. What is inconsequential on a top end desktop can be unusable on a $15 tablet.

Design

If you have followed the Code Review posting rules and your code is production code then it is very poor quality, as it is flat, in the global scope, and not reusable at all.

You should always write code inside a function. Even if its just an example writing functions will result in better design.

Style

The indenting is poor and obscuring the logic.
You have redundant code. Unneeded brackets () in headersMap.
Poor naming of the _.reduce callbacks arguments

Rewrite

Using your algorithm and rewriting into a named function your code is more readable, reusable, and cleaner (name space wise) as

function namedEvents(eventList) {
    const map = ({onClick, children}) => onClick ? {onClick} : _.map(children, map);
    const reduce = (result, child) => ({...result, [child]: null});
    return _.reduce(
        _.map(_.flatMap(eventList, map), 'onClick'),
       reduce,
       {}
    );
}

Avoiding the needless re-creation of results for each entry you get

function namedEvents(eventList) {
    const map = ({onClick, children}) => onClick ? {onClick} : _.map(children, map);
    const reduce = (result, child) => (result[child] = null, result);
    return _.reduce(
        _.map(_.flatMap(eventList, map), 'onClick'),
       reduce,
       {}
    );
}

Redesign

To avoid the CPU overhead the code can be written as a simple recursive function. The functions below are an order of magnitude quicker than your algorithm.

There is no need to load lodDash.js thus improving the page load time.

As you already use recursion I will assume that there are no cyclic references in the dataset.

Your code ignores children if onClick is truthy so will do the same

For the best re-usability the key "onClick" name can be passed as an argument.

function namedEvents(eventList, results = {}, key = "onClick") {
    for (const child of eventList) {
        if (child[key]) { results[child[key]] = null }
        else if (child.children) { namedEvents(child.children, results, key) }
    }
    return results;
}

or

function namedEvents(eventList, results = {}, key = "onClick") {
    for (const child of eventList) {
        if (child[key]) {
            results[child[key]] = null;
        } else if (child.children) {
            namedEvents(child.children, results, key);
        }
    }
    return results;
}

Or not having an adaptive key name

function namedEvents(eventList, results = {}) {
    for (const {onClick, children} of eventList) {
        if (onClick) { results[onClick] = null }
        else if (children) { namedEvents(children, results) }
    }
    return results;
}

Or

function namedEvents(eventList, results = {}) {
    return eventList.reduce((result, {onClick, children}) =>
            onClick? (results[onClick] = null, results) :
                children ? namedEvents(children, results) : results,
        results
    );
}


Send messages in TCP-based communication system

Networking Concerns

I'm going to assume that stream is a NetworkStream in the Server. It is really really important that you understand that stuff which 'just happens to work' with a 'normal' stream, won't work with a NetworkStream, which also doesn't provide a 'complete' Stream implementation (being non-seeking and such it can't).
Your code currently could behave very oddly and somewhat non-deterministically depending on the interface between the server and client computers, and likely the lengths of messages.
I'm going to provide a full-enough answer here, because I can't find any that I really like on SO (I'm sure there are good ones, I just can't find them). Networked code is hard enough to write that I won't say anything about buffering and the performance implications thereof (not least because I don't really understand it myself, and have never bothered to properly profile any of my code).
Note that there are loads of examples of this deficiency all over the web (and not enough explanations of the problem, I hope mine isn't too painful).

Unfortunately, network programming isn't quite so easy: because TCP is stream based, you never really know when a 'message' has ended. The problem with your code is a result of the lone call to stream.Read(byte[], int, int)... and unfortunately the MSDN example has the same problem!
Essentially, this code is insufficient:
byte[] msg = new byte[4096];
var count = stream.Read(msg, 0, msg.Length);
string returnData = Encoding.ASCII.GetString(msg, 0, count);
string command = returnData.Substring((returnData.IndexOf("%") + 1), (returnData.IndexOf("&") -1));

I imagine you will never see this problem if you test the code on a single machine; however, over the internet I suspect it will become somewhat apparent with longer messages. As I said, Read can't know when the message your client has sent ends... so when should it return? The answer is... I don't know, it just does at some point: I don't know if there are any guarantees, and it's most certainly OS/Configuration dependant, so you shouldn't make any assumptions.
Currently you are just hoping that when calling "Read" you will receive a full message: you could well receive only part of a message, or even two messages (or parts of two messages, etc.). TCP ensures that you will receive the stream of bytes in the right order, or know that you have lost communications, but it has no concept of 'packets' (or messages) like UDP does, which is why TcpClient exposes a NetworkStream.
Example:
Client Sends "%DisplayRemoteMessageBox&Hello, World!#"
Server Received "%DisplayRemoteMessageB" -> print to console
Server Received "ox&Hello, World!#" -> print to console

The server can cut-up the stream any way it likes, so you have to design a protocol so that you can work out where stuff starts and ends (if necessary, which it is for you).
How exactly you want to 'fix' this depends on your system. You are using ASCII explicitly, so you could easily enough do a byte-by-byte (char-by-char) 'text' stream analysis to extract messages (e.g. look for % to start a message, and wait for # to end it). This is how some older protocols like IRC work, where they use some method to identify new-lines in communications, which defines the separation between messages. This involves looking at each byte you read, deciding if it has a special meaning, and acting on it accordingly. This can be fiddly and is easy to make inefficient.
A cleaner solution is to define a simple protocol which allows you to determine the length of a 'message' before you read it. The main advantage of this is that you no longer need to know what a message 'looks like' to read it: this means it can look like )anything_ (note that your current code doesn't allow you to send a # as part of a message, because # has meaning). This will (probably) be a binary protocol, where you define each message as a 'packet', which starts by declaring its length, and then streams the message.
On the client, you simply have to work out how long your messages are, and send the length before you send the message. On the server, you start by reading the length, and then you read that many bytes so you know that you have the full message. You could process the message as you receive it (e.g. for file transfer, you wouldn't wait until you've received all the bytes to start writing it disk), but for small messages you can just accumulate all the bytes in a buffer and process it in one.
I always use this binary 'packet' method for networking - not least because I have no desire to think about Unicode and its implications - so here is a rough sketch of how you might implement it to send individual strings (with lots of comments for in-line explanation). I'll make no guarantees that this code will work out-of-the-box.
Notice about BinaryWriter and friends
Much of what I have just described (and below implement) is facilitated by the BinaryReader and BinaryWriter classes in the BCL. However, both these classes assume/enforce little-endian byte order, which is not ideal when most of the networking world has agreed on big-endian. I present the below because I forgot that BinaryWriter was little-endian to show the concepts above explicitly, and to show a viable solution for big-endian communications (e.g. when interoping with existing big-endian protocols / variable endian protocols (I'm sure they exist))
Client Side
As suggested by BKSpurgeon, factor out the message writing in your two event handlers: the code is basically the same at the moment. What you want is a new method to send a string to the server, a very simple API indeed (which is no bad thing).
/// <summary> Sends a length-prepended (Pascal) string over the network </summary>
private void SendMessage(string message)
{
    NetworkStream networkStream = client.GetStream();

    // turn the string message into a byte[] (encode)
    byte[] messageBytes = Encoding.ASCII.GetBytes(message); // a UTF-8 encoder would be 'better', as this is the standard for network communications

    // determine length of message
    int length = messageBytes.Length;

    // convert the length into bytes using BitConverter (encode)
    byte[] lengthBytes = System.BitConverter.GetBytes(length);

    // flip the bytes if we are a little-endian system: reverse the bytes in lengthBytes to do so
    if (System.BitConverter.IsLittleEndian)
    {
        Array.Reverse(lengthBytes);
    }

    // send length
    networkStream.Write(lengthBytes, 0, lengthBytes.Length);

    // send message
    networkStream.Write(messageBytes, 0, length);
}

// example calls
private void btnSend_Click(object sender, EventArgs e)
{
    msg = "%" + txtMsg.Text + "&";
    SendMessage(msg);
}

// example calls
private void btnMsgBox_Click(object sender, EventArgs e)
{
    msg = "%DisplayRemoteMessageBox&" + txtMsg.Text + "#";
    SendMessage(msg);
}

Hopefully this is mostly pretty easy to follow. Note the 'endian flip' of the length: Endianness is a nightmare on its own, and the .NET libraries do not help much. Note the remarks for BitConverter.GetBytes(int): to be efficient, this will just be a blit, which means the result depends on the hardware you are using. This is fine if the destination has the same endianness, but with networking you can't assume that, so we agree to send big-endian, which means flipping the bytes if we are on a little-endian machine. We don't use a BinaryWriter because it is little-endian only, so it's harder to change the endianness (useful for demonstration and compatibility). This is only necessary for primitives like integers; ASCII (and UTF) are both defined the same way for a big- or little-endian system, so there is no issue with the string.
When you start writing more and more code like this, you'll end up writing dedicated methods for sending integers, strings (the protocol above is basically just sending a length-prefix 'Pascal' string), and other primitives; similarly for the server.
Server Side
on the client, we provide a method to 'send' a string. Duly, on the server, we should probably provide a message to 'receive' a string. I will sketch a very simple blocking solution. For real code, you probably won't something asynchronous, and that facilitates buffer reuse.
Reading a string requires reading the length, and then the string itself. This is two separate reads, so let's write one method to do this:
Essentially, because we can't trust NetworkStream.Read(,,) to give us the right number of bytes, we have to repeatedly call NetworkStream.Read(,,) and accumulate the bytes it gives us into a buffer. We only return the buffer to the caller when it is full (i.e. we have read exactly the requested number of bytes).
/// <summary> Reads a number of bytes from the stream </summary>
private byte[] ReadBytes(int count)
{
    NetworkStream networkStream = client.GetStream();

    byte[] bytes = new byte[count]; // buffer to fill (and later return)
    int readCount = 0; // bytes is empty at the start

    // while the buffer is not full
    while (readCount < count)
    {
        // ask for no-more than the number of bytes left to fill our byte[]
        int left = count - ReadCount; // we will ask for `left` bytes
        int r = networkStream.Read(bytes, readCount, left); // but we are given `r` bytes (`r` <= `left`)

        if (r == 0)
        { // I lied, in the default configuration, a read of 0 can be taken to indicate a lost connection
            throw new Exception("Lost Connection during read");
        }

        readCount += r; // advance by however many bytes we read
    }

    return bytes;
}

There are few ways that the code above can go wrong depending on the configuration (timeout, lost client, etc.), most of which involving a complete breakdown in communication, so the exception thrown will be a welcome one, and can be handled as appropriate. It is 'blocking', which means that it will not return until it has read count many bytes. Asynchronous versions can be written using async or simple call-backs (again, I can't find a good SO reference for this at the moment, but I'm sure I've seen one in the past). With the while loop, it looks like this code will cook your computer, but in reality NetworkStream plays 'nicely' with the TCP stack, and will block until at least the first byte is read.
Using this ReadBytes(int) method, we can write the ReadMessage method we really want:
/// <summary> Reads the next message from the stream </summary>
private string ReadMessage()
{
    // read length bytes, and flip if necessary
    byte[] lengthBytes = ReadBytes(sizeof(int)); // int is 4 bytes
    if (System.BitConverter.IsLittleEndian)
    {
        Array.Reverse(lengthBytes);
    }

    // decode length
    int length = System.BitConverter.ToInt32(lengthBytes, 0);

    // read message bytes
    byte[] messageBytes = ReadBytes(length);

    // decode the message
    string message = System.Text.Encoding.ASCII.GetString(messageBytes);

    return message;
}

Note that there is an obvious read -> decode -> consume process going on here. For anything but the most simple system, I would write a separate ReadInt method which the ReadMessage method would call.
With ReadMessage written, you can refit the server code, which becomes much tidier:
while(client.Connected)
{
    string message = ReadMessage();

    string command = message.Substring((message.IndexOf("%") + 1), (message.IndexOf("&") -1));

    switch(command)
    {
        // ...
    }
}

Note that not much has changed in the server or client: they are still using the same protocol you have set up for sending a command: all that has been added is a robust mechanism for sending and receiving a single string. Breaking the code up so that each unit of work is its own method makes it much more maintainable.
As this is really meant to be a code review, I should point out that the second argument for message.Substring(,): it is meant to be a length, so you need to subtract the start position for this to work as intended). I have also taken the liberty of renaming returnData as suggested in BKSpurgeon's answer.
I put the above into a petty test program to content myself that it compiles and isn't completely broken: example gist; it starts a simple server which just prints messages to the screen, and demonstrates simple lost connection handling (which can be jolly annoying)
More comments on BinaryWriter and friends in the context of the question
Essentially, the above SendMessage and ReadMessage methods perform a big-endian 32bit-length-prefix string transmission. If you can accept little-endian encoding, and the particulr prefix regime that they use, then you can get away with just wrapping your NetworkStream  with a BinaryReader/BinaryWriter and using ReadString() and Write(String). Note that these classes use UTF-8 by default, but this is configurable in the constructors. These methods use a variable prefix length for efficiency purposes: you can see an implementation on source.dot.net. Note also that length-prefixing is invaluable when sending any discrete packet, and using these built-ins will only help if you are exclusively sending strings. If you do only need strings (e.g. if you are serialising everything as text/XML/JSON before transmitting it), and you can get way with the other constraints (e.g. if you control the protocol so can choose the endianness and prefix regime), then the following may suffice for you:
public void SendMessage(string message)
{
    NetworkStream networkStream = TcpClient.GetStream();
    using (var binaryWriter = new System.IO.BinaryWriter(networkStream, System.Text.Encoding.UTF8, leaveOpen: true))
    {
        binaryWriter.Write(message);
    }
}

public string ReadMessage()
{
    NetworkStream networkStream = TcpClient.GetStream();
    using (var binaryReader = new System.IO.BinaryReader(networkStream, System.Text.Encoding.UTF8, leaveOpen: true))
    {
        return binaryReader.ReadString();
    }
}

The parameter leaveOpen is important here, because the code creates a new BinaryReader/Writer each call, and otherwise it would close the stream when it is disposed. Ideally you would create and hold onto a single instance of each, and dispose them along with the TCPClient.
Other
This SO answer about detecting a lost TCP connection while reading may be of general interest: note that it uses a combination of BinaryRead and a ReadBytes style loop to read a length-prefixed packet for a specific purpose.


C++ implementation of depth-first search

What further improvements can I make to this code?

The code is rather bad - the site you read it from tends to have lots of bad/amateur articles.

The graph class:
std::map<int, bool> visited;
std::map<int, std::list<int>> adj;

This is extremely poor and inefficient graph implementation. std::map creates a new memory allocation for each element. So you do it twice for both the boolean and the list. Also std::list allocates a piece of memory for each element as well.
Overuse of memory allocation means both memory fragmentation issues as well as performance issues due lots of unmanageable RAM access and indirections. Memory loading is currently one of the slowest operations on modern processors. But compilers tend to optimize it quite well if the memory is contiguous - which is furthest from the truth in this case.
To simplify the structure you'd better use std::vector<Node> where Node contains vertex's information + std::vector<size_t> of neighbors. In general, I don't believe there is a perfect solution for graph representation - instead there are numerous ways to represent and each suitable or more attuned to specific types of graphs. For instance, solutions that are good for sparse graphs are surely very poorly suited for dense graphs. Also certain additional optimizations can be made assuming that graph is fixes. The question is complex and I cannot provide an answer without knowledge of the use-case.

DFS() implementation is also pretty bad. It relies on recursion and I assure you, that for large enough connected graphs with it will blow the stack resulting in UB.

Proper DFS/BFS implementation store states-to-be-visited in a std::stack or std::queue or something similar while the visit routine occurs in a single loop instead of recursion.
Also, I presume you want some kind of output or action made on vertices from the DFS, no?


Binary search algorithm for non-overlapping time spans and possible gaps

Flatter code is less arrow-shaped

In cases like this:

if( $max < $min )
{
    return false;
}
else
{
    // more deeply nested conditions ...
}

When the if branch ends with a return statement,
you can eliminate the else branch,
making the code flatter and less arrow-shaped,
which often makes it easier to read:

if( $max < $min )
{
    return false;
}

// more code ...

Fishy comparison

Although this is apparently valid PHP, comparing a date against a null value using the > operator seems like a dirty hack:

else if( $date > $finish )
{
    if( $finish == null )

I would reorganize the conditions in that piece of code:

if( $max < $min )
{
    return false;
}

$mid = floor( $min + ( ( $max - $min ) / 2 ) );
$node   = $this->nodes[ $mid ];
$start  = $node->getStart();
$finish = $node->getFinish();

if( $date < $start )
{
    return $this->binarySearch( $date, $min, $mid - 1 );
}

if( $finish == null )
{
    return $node;
}

if( $date > $finish )
{
    return $this->binarySearch( $date, $mid + 1, $max );
}

return $node;

Minor optimization

The find method recalculates the size of $this->nodes,
even though it cannot change after construction.
It would be better to calculate the size once,
at construction time.


Spelling a word with chemical elements in Rust

Overall

Don't explicitly import Vec or Option, they are part of the prelude.
Basically always want to implement Debug on any type.
I see two types that aren't there: something that holds the elements, something that contains results.
This allows you to implement Display for Spelling. This is more flexible and participates in the ecosystem better.

read_elements

No need to use Path explicitly, &str implements AsRef<Path>.
Can collect iterator of tuples into a HashMap, no need to muck about with a mutable variable.
Don't use unwrap. Prefer expect or return a Result. expect has words that will help you or the user find the problem. Note that we can collect into a Result.
Don't hardcode the filename inside the function.

spell_word

Should not take elem_map by value. Take a reference as we aren't making use of the allocated data.
I'd split the string and just track the string pieces, not the distance into the string.
No explicit return at the end of function.
Return references to the element instead of cloning.

show_result

Don't specify the types on a variable binding; let inference take care of it.
Don't take ownership of Vec, instead take a slice.
I'd avoid allocating in the printing function. I used Itertools to help with the comma separating.

main

Don't specify the type of a collection, let inference take care of it (let foo: Vec<_> = bar.collect()).
Don't check for the argument and then implicitly check again (via indexing). A match or unwrap would be better.
No need to collect into a vector. Instead, skip the program name and just iterate over all the arguments - bonus feature!
No need to explicitly convert String to &str, a &String can be coerced to a &str.
Use raw strings to avoid escaping quotes

extern crate csv;
extern crate itertools;

use std::{env, fmt};
use std::collections::HashMap;

use itertools::Itertools;

type Error = Box<std::error::Error>;

#[derive(Debug, Clone)]
struct Element {
    number: u16,
    symbol: String,
    name: String
}

impl Element {
    fn new (number: u16, symbol: &str, name: &str) -> Element {
        Element {
            number: number,
            symbol: symbol.to_string(),
            name: name.to_string()
        }
    }
}

struct Elements {
    elem_map: HashMap<String, Element>
}

impl Elements {
    fn read_from_file(name: &str) -> Result<Self, Error> {
        let mut csv_reader = csv::Reader::from_file(name)?;

        let elem_map: Result<_, Error> = csv_reader.decode().map(|record| {
            let (number, symbol, name): (u16, String, String) = record?;
            let symbol = symbol.trim();
            let name = name.trim();
            Ok((symbol.to_lowercase().to_string(), Element::new(number, symbol, name)))
        }).collect();

        Ok(Elements { elem_map: elem_map? })
    }

    // Try to spell target_word using elements from elem_map
    fn spell_word(&self, target_word: &str) -> Option<Spelling> {
        let mut result = Vec::new();
        let target_word = target_word.to_lowercase().to_string();
        let mut target_word = target_word.as_str();

        while !target_word.is_empty() {
            // Try matching the next two letters first
            if target_word.len() >= 2 {
                let (head, tail) = target_word.split_at(2);

                if let Some(elem) = self.elem_map.get(head) {
                    result.push(elem);
                    target_word = tail;
                    continue;
                }
            }

            // Try matching one letter if two letters failed
            let (head, tail) = target_word.split_at(1);

            if let Some(elem) = self.elem_map.get(head) {
                result.push(elem);
                target_word = tail;
                continue
            }

            // If no one letter element could be found,
            // this word cannot be spelled using elements
            return None;
        }

        Some(Spelling(result))
    }
}

struct Spelling<'a>(Vec<&'a Element>);

impl<'a> fmt::Display for Spelling<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for elem in &self.0 {
            write!(f, "{}", elem.symbol)?;
        }

        write!(f, " (")?;

        for elem in self.0.iter().map(|e| e.name.as_str()).intersperse(", ") {
            write!(f, "{}", elem)?;
        }

        write!(f, ")")
    }
}

fn main() {
    let elements = Elements::read_from_file("./elements.csv").expect("Unable to read elements");

    for target_word in env::args().skip(1) {
        match elements.spell_word(&target_word) {
            Some(spelling) => println!("{}", spelling),
            None => println!(r#"Could not find a match for word "{}"."#, target_word)
        }
    }
}


Another possible solution is to use a DataGridView.  You may define a column to be read only and it will appear as normal, i.e. not grayed out when the control is not enabled.  Plus I think a DataGridView would be a better solution overall given that you apparently want to displays rows of data.


ezxml has a variadic function which allows you to traverse directly to a specific node, terminated by either -1 as the index, or an empty string for the node name:

pxUpnpSubChild  = ezxml_get(pxUpnp, "device", 0, "friendlyName", 0, "");

This would give you directly the first friendlyName node of the first device node. Internally, it does mostly the same as what you did manually.

The more elegant solution would to use standard XPath expressions, however that isn't supported by ezxml. Libraries for C supporting XPath would e.g. libxml2 or Expat


The capitalization rules say:

  Do capitalize both characters of two-character acronyms, except the first word of a camel-cased identifier.

  A property named DBRate is an example of a short acronym (DB) used
  as the first word of a Pascal-cased identifier. A parameter named
  ioChannel is an example of a short acronym (IO) used as the first word
  of a camel-cased identifier.
  Do capitalize only the first character of acronyms with three or more characters, except the first word of a camel-cased identifier.

  A class named XmlWriter is an example of a long acronym used as the
  first word of a Pascal-cased identifier. A parameter named htmlReader
  is an example of a long acronym used as the first word of a
  camel-cased identifier.
  Do not capitalize any of the characters of any acronyms, whatever their length, at the beginning of a camel-cased identifier.

  A parameter named xmlStream is an example of a long acronym (xml)
  used as the first word of a camel-cased identifier. A parameter named
  dbServerName is an example of a short acronym (db) used as the first
  word of a camel-cased identifier.

You violate these rules numerous times: dataISO, TPDU, BITMAP, cboISOCommand, SendISO, etc.

What is the point of this:

string dataLength = "019A";
string TPDU = "6001010000";
string MTI = "0100";
string BITMAP = "3020078020C00204";
string ProCode = "380000"; // 3
string Amount = "000000010000"; // 4
string STAN = "000031"; // 11
string POSEM = "051"; // 22
string PANSequence = "001"; // 23
string FunctionCode = "101"; // 24
string ConditionCode = "00"; // 25
string Track2 = "36484200000000009=15000000000000000000"; //35
string TerminalID = "00000000"; //41
string IdentificationCode = "000000000000000"; //42
string ReservedISO = "2725F2A02045882023C008407A0000000031010950500000080009A031407229C01009F0206000000000010";
ReservedISO +="9F03060000000000009F0902008C9F100706010A03A0A0029F1A0204589F1E0831313731313534399F26";
ReservedISO +="081344604C7E2C7B589F2701809F3303E0B0C89F34031E03009F3501229F360204379F3704746733F19F4";
ReservedISO +="104000000079F530152"; //55
string ReservedPrivate = "006000019"; //62

string total = dataLength + TPDU + MTI + BITMAP + ProCode + Amount + STAN + POSEM + PANSequence + FunctionCode + ConditionCode + Track2 + TerminalID + IdentificationCode + ReservedISO + ReservedPrivate;

Are all of those string const? If so, why aren't they defined as such?
The comments make no sense: //55, //42
To me this feels like code that should be in a separate class, with the likes of dataLength, TPDU etc. being properties or const, and total being a get-only property with a more meaningful name.
What is the point of total, considering you immediately assign its value to dataISO?
They're currently all local variables, yet most of them are PascalCase when they should be camelCase.

Is ControllerErrorArguments a class you control? If so: why not have a version with the String.Format() functionality built-in?

Twice you do this cast: (IPEndPoint)client.Client.RemoteEndPoint. Do it once, store it in a variable, use that variable.


Checking for JSON or YAML file with promises

Interesting question,

since you need to evaluate both Promises, I would use Collections.
Something like this:

Promise.all([yml(),json()]).then(function( results ) {
  // Return the results of yml() if truthy, or json() if truthy, or false
  return results[0] || results[1] || false;
});

Other than that, for the love of readable code:

Use newlines in your if statements
Use curly braces in your if statements
Dont stretch your code too much horizontally

I like your 2nd approach far more than the 1st approach, the 1st approach is simply head ache inducing.


Uploading photos: Domain Model and Repository classes

Working with images is always a messy adventure. The PhotographRepository#create method is doing a number of things:

Creating a new record in the database
Testing to see if the file upload exists
Moving the uploaded temp file into a permanent location

The challenge in this scenario is how to handle database problems as well as file I/O problems in a manner that allows the user to try again.

Database operations are inherently safe in that if an INSERT fails on commit, the transaction gets rolled back. File operations are permanent and therefore destructive in nature. You can "undo" a file move operation, but it is not as simple is issuing a "rollback" to the file system. Due to the increased risk of losing information in I/O operations, I would recommend ensuring the database INSERT succeeds first, then attempt to move the file.

While a "photograph" seems to be just one thing, at a code level it is two things: A record in the database and a file on disk. The I/O operation should be placed in its own repository. What exists on a shared drive today might need to move to The Cloud® tomorrow. You actually have a need for two repositories:

PhotographRepository to handle the CRUD operations in the database
ImageFileRepository to handle the CRUD operations of storing the file on disk (or in The Cloud®)

The question becomes how to marry the two.

Dependent Repositories

There are times when one repository requires another repository in order to make one complete "transaction" (INSERT a record into a database, move a file on disk). There are two approaches here:

Use Constructor Injection to pass the ImageFileRepository object into PhotographRepository

$photos = new PhotographRepository(new PDO(...), new ImageFileRepository());

Create a "repository context" object that gives you easy access to all the other repositories in your system

Which approach you take depends on how dependent each repository is on the others. If the PhotographRepository is the only one that needs another "repository" object, then go for option #1. If you have a number of repository objects that need each other, for example you need to save a parent record in the database and insert child records in other tables, then go for option #2.

Whichever direction you take, you want the file storage decoupled from the meta data stored in the database.

Using Constructor Injection for Dependent Repositories

This is the easiest to implement, but doesn't scale well as your application grows and repositories increasingly become dependent on one another. Part of our goal is to decouple the file storage from the database operations, which is a prime example of how interfaces are beneficial. The PhotographRepository class will require a second constructor argument:

class PhotographRepository
{
    private $connection;
    private $images;

    public function __construct(PDO $connection, ImageRepository $images) {
        $this->connection = $connection;
        $this->images = $images;
    }

The ImageRepository object is actually the following interface:

interface ImageRepository
{
    public function create($file);
}

The PhotographRepository#create method gets a refactoring job so the database INSERT occurs first, and then the image is moved:

class PhotographRepository
{
    // ...

    public function create($file, $caption) {
        $imageInfo = new SplFileInfo($file['tmp_name']);
        $photo = new Photograph($imageInfo->getFileName(), $file['type'], $file['size'], $caption);

        if (!isset($this->statements[__METHOD__])) {
            $this->statements = $this->connection->prepare("INSERT INTO photographs (filename, type, size, caption) VALUES (:filename, :type, :size, :caption)");
        }

        $stmt = $this->statements[__METHOD__];

        if ($stmt->execute([':filename'=>$photo->getFilename(), ':type'=>$photo->getType(), ':size'=>$photo->getSize()])) {
            $photo->setId($this->connection->lastInsertId());
            $stmt->closeCursor();
            $this->images->create($file);

            return $photo;
        } else {
            $stmt->closeCursor();

            throw new RuntimeException('Failed to save Photograph');
        }
    }

Two differences:

The database operation is completed first, then the file operation is performed
If the database operation fails, an exception gets thrown. being unable to insert into the database is a catastrophic problem, so throw an exception

Now let's implement the ImageRepository interface to perform the file move operation:

class ImageFileRepository implements ImageRepository
{
    private $root;

    public function __construct($root) {
        if (!file_exists($root)) {
            throw new InvalidArgumentException('Root image directory does not exist: ' . $root);
        } elseif (is_writable($root)) {
            throw new InvalidArgumentException('Root image directory "' . $root . '" is not writable');
        }

        $this->root = $root;
    }

    public function create($file) {
        $this->ensureValidFile($file);
        $targetPath = $this->root . basename($file['name']);

        if (file_exists($targetPath)) {
            throw new InvalidArgumentException('The file "' . $targetPath . '" already exists');
        }

        if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
            throw new RuntimeException('Failed to move upload file from "' . $file['tmp_name'] . '" to "' . $targetPath . '"');
        }

        return new SplFileInfo($targetPath);
    }

    private function ensureValidFile($file) {
        if (!$this->isValidFile($file)) {
            throw new InvalidArgumentException('File is not valid');
        } elseif (!is_readable($file['name'])) {
            throw new InvalidArgumentException('File is not readable');
        } elseif ($file['error'] != 0) {
            throw new InvalidArgumentException('File error: ' . $file['error']);
        }
    }

    private function isValidFile($file) {
        return $file
            && !empty($file)
            && is_array($file);
    }
}

If the any file operation cannot be completed (reads or writes) throw an exception. This is a hard-stop in your application. If your application cannot write to the public/images directory, fail early and fail loudly. A server admin needs to fix this.

Now it only takes 3 lines of code to create the photograph record and move the image:

$photos = new PhotographRepository(
    new PDO(...),
    new ImageFileRepository(__DIR__ . '/../public/images/')
);
$caption = $_POST['caption'];
$photo = $photos->create($_FILES['input_name'], $caption);

The first line of code is where you glue the two repositories together. This works well, architecturally, but if you need PhotographRepository objects in multiple places, you'll have a lot of repeated code. This is where a "Repository Context" comes in handy.

Using a Repository Context

When interdependent relationships between repositories become more commonplace, an object wrapper for your repositories is beneficial:

class RepositoryContext
{
    public $photos;
    public $images;

    public function __construct() {
        $this->images = new ImageFileRepository($this, __DIR__ . '/../public/images/');
        $this->photos = new PhotographRepository($this, new PDO(...)));
    }
}

The key feature is that each repository gets passed a reference to its $context.

Now ImageFileRepository becomes:

class ImageFileRepository implements ImageRepository
{
    private $context;
    private $root;

    public function __construct(RepositoryContext $context, $root) {
        if (!file_exists($root)) {
            throw new InvalidArgumentException('Root image directory does not exist: ' . $root);
        } elseif (is_writable($root)) {
            throw new InvalidArgumentException('Root image directory "' . $root . '" is not writable');
        }

        $this->context = $context;
        $this->root = $root;
    }

And PhotographRepository becomes:

class PhotographRepository
{
    private $context;
    private $connection;
    private $images;

    public function __construct(RepositoryContext $context, PDO $connection) {
        $this->context = $context;
        $this->connection = $connection;
        $this->images = $images;
    }

    public function create($file, $caption) {
        // ...

        if ($stmt->execute([':filename'=>$photo->getFilename(), ':type'=>$photo->getType(), ':size'=>$photo->getSize()])) {
            $photo->setId($this->connection->lastInsertId());
            $stmt->closeCursor();
            $this->context->images->create($file);

            return $photo;
        } else {
            $stmt->closeCursor();

            throw new RuntimeException('Failed to save Photograph');
        }
    }
}

After the database insert, we delegate to $this->context->images->create($file); to access the image file repository. Then it's just a slight change to the code creating the photograph:

$context = new RepositoryContext();
$caption = $_POST['caption'];
$photo = $context->photos->create($_FILES['input_name'], $caption);

Moving Image Files To The Cloud®

Later, when the Business decides to spend money on the next big buzzword, you can write another image repository to store those images on a cloud-based hosting provider:

class CloudImageRepository implements ImageRepository
{
    private $url;
    private $apiKey;

    public function __construct(RepositoryContext $context, $url, $apiKey) {
        $this->context = $context;
        $this->url = $url;
        $this->apiKey = $apiKey;
    }

    public function create($file, $caption) {
        // ...
    }
}

And just create a different repository in your context:

class RepositoryContext
{
    public $photos;
    public $images;

    public function __construct() {
        $this->images = new CloudImageRepository($this, $url, $apiKey);
        $this->photos = new PhotographRepository($this, new PDO(...)));
    }
}

Nothing else in your code needs to change.


The essence of the algorithm used by a sieve is removing the factors of the number. eg. first we remove the factors of 2 ie. 4,6, 8,10... , and then factors of 3 ie. 9 12, 15... so on and so forth.

But applying the same logic for bigger constraints would result in TLE. Thus segment sieve comes into picture.

The segment sieve also applies the same logic BUT on the segment. Thus, Segment Sieve works only if the segment length is within manageable constraints.

Consider a segment given by [m,n]. We remove all the factors which are greater than m but less than n. To check whether a number between m and n is a factor, we use a boolean array(is_factor)...whereis_factor[i] denotes whether the number which at a offset of i from lower bound of the segment(m). Now the factors are eliminated by considered all the numbers which are less than the sqrt(n).

Let's consider an example to illustrate my point.

Suppose m=1000 and n=1100 So we will remove all the factors of x( where x ranges from 2 to sqrt(1000)).

Therefore, When x=2---> 1000,1002,1004,....1100 get crossed..(corresponding is_factor gets marked).

When x=3 --> 1002,1005,1008,....1098 get crossed.. And the process continues.

So the ones which  remain unmarked are the primes in the interval [m,n].
This link illustrates a C++ program for solving the problem Prime 1 SPOJ
. Hope this helps mate :)


Finding the first stream of non-repeating elements in Scala (without recursion or side-effects)

This is a fold, not a scan. A scan produces something with the same number of elements, and change the elements. A fold produces something new.

def firstDistinct[T](s: Seq[T]) = s.foldLeft(Seq[T]() -> false) {
  case (result @ (_, true), _)           => result
  case ((seq, _), el) if seq contains el => seq -> true
  case ((seq, _), el)                    => (seq :+ el) -> false
}._1