improvements to this php function to calculate monthly returns from a set of price data

If there are now performance constraint I always prefere a readable solution over a compact one. So I would go with the following: (assuming $prices is sorted and there are no gaps in the months)

<?
date_default_timezone_set('Europe/Berlin');

//Put the data into a assoc array. If necessary I would maybe create a separate
//method to create this input or put it also to extractMonthlyFinalPrice()
$prices=array();
$prices['2013-01-29']='25.69';
$prices['2013-02-28']='27.62';
$prices['2013-03-02']='13.53';
$prices['2013-03-07']='16.53';
$prices['2013-03-30']='26.53';
$prices['2013-03-30']='26.53';
$prices['2013-04-29']='28.45';

$monthlyFinalPrice=extractMonthlyFinalPrice($prices);
/*
array(4) {
  ["2013-01"]=> string(5) "25.69"
  ["2013-02"]=> string(5) "27.62"
  ["2013-03"]=> string(5) "26.53"
  ["2013-04"]=> string(5) "28.45"
}
*/

$monthlyReturns=calculateMonthlyReturn($monthlyFinalPrice,new DateTime("2013-02"));
/*
array(3) {
  ["2013-02"]=>  float(1.93)  //with '2013-01' as start
  ["2013-03"]=>  float(-1.09)
  ["2013-04"]=>  float(1.92)
*/

function extractMonthlyFinalPrice($prices)
{
    $monthlyPrice=array();
    foreach ($prices as $date=>$price)
    {
        $month=substr($date,0,7);
        $monthlyPrice[$month]=$price; // just overwrite existing value and use the last
    }
    return $monthlyPrice;
}

//Be careful with timestamps. Think about using DateTime.
function calculateMonthlyReturn($monthlyFinalPrice, DateTime $startDate=null, DateTime $endDate=null)
{
    if ($endDate==null) $endDate=new DateTime();
    $monthlyReturns=array();
    $lastMonthPrice=null;
    foreach ($monthlyFinalPrice as $month=>$price)
    {
        $date=new DateTime($month);
        $inRange = $date>=$startDate && $date <=$endDate;
        if ($lastMonthPrice!=null && $inRange)
        {
            $monthlyReturns[$month]=$price-$lastMonthPrice;
        }
            //assuming that there are no gaps in the list.
            //Otherwise some date magic is required.
        $lastMonthPrice=$price;
    }
    return $monthlyReturns;
}

As you see, there is no much "logic" left. I get rid of a bunch of ifs and could split the bigger problem in two smaller own. Now you could write tests independently.


Stream file to OpenCSV with the least amount of I/O possible

Switch to uniVocity-parsers as it is twice as fast as OpenCSV and the input is read in parallel.

    final BeanListProcessor<MyObject > clientProcessor = new BeanListProcessor<MyObject>(MyObject .class);

    CsvParserSettings settings = new CsvParserSettings();
    settings.getFormat().setLineSeparator("\n");
    settings.setRowProcessor(clientProcessor);

    settings.setReadInputOnSeparateThread(true); // this enabled by default

    CsvParser parser = new CsvParser(settings);
    parser.parse(new InputStreamReader(new ZipInputStream(inputStream)));

    List<MyObject> rows = clientProcessor.getBeans();

If you are not using all columns of your CSV input, you can select the rows you want as well to make the process even faster:

    settings.selectIndexes(4, 6, 3);
    settings.selectFields("Field A", "B", "and C");

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).


JWT authentication between Django and ReactJS

UX concern: refresh period

I wonder if you are confusing the access token expiration setting (JWT_EXPIRATION_DELTA) with the refresh token expiration (JWT_REFRESH_EXPIRATION_DELTA). In either case, your t < 13 check should be related to the refresh token expiration, not the access token expiration. 13 seems to be chosen because it is almost 14; hence my comment. At the very least these refreshes should never go beyond your refresh expiration (7 days), or they will fail, which defeats the purpose of providing a refresh token (because the user would always have to authenticate after the expiration).

Security concern: access token expiration

On a slightly similar note, but this one is a security concern -- you typically want the access token to have a much shorter life than the refresh token. Yours is reversed, as the access token (JWT_EXPIRATION_DELTA) is 14 days vs. the refresh token (JWT_REFRESH_EXPIRATION_DELTA) at 7 days. Note the default JWT_EXPIRATION_DELTA for the djangorestframework-jwt library is a much more conservative and standard 5 minutes:

  Default is datetime.timedelta(seconds=300)(5 minutes).

Per OAuth 2 spec:

  access tokens may have a shorter lifetime and fewer permissions than
  authorized by the resource owner

Per Auth0 guidance:

  Access tokens carry the necessary information to access a resource directly.

  ...

  Access tokens usually have an expiration date and are short-lived.

  ...

  Common implementations allow for direct authorization checks against
  an access token. That is, when an access token is passed to a server
  managing a resource, the server can read the information contained in
  the token and decide itself whether the user is authorized or not (no
  checks against an authorization server are needed). This is one of the
  reasons tokens must be signed (using JWS, for instance). On the other
  hand, refresh tokens usually require a check against the authorization
  server. This split way of handling authorization checks allows for
  three things:

  Improved access patterns against the authorization server (lower load, faster checks)
  Shorter windows of access for leaked access tokens (these expire quickly, reducing the chance of a leaked token allowing access to a
  protected resource)

  ...

Security concern: refresh token revocation

It is difficult for me to tell whether that djangorestframework-jwt library will revoke all previous refresh tokens for a given session once a new refresh token is issued for that session. Ideally it should, especially if you are using unauthenticated clients, which it looks like you are (assuming that React app is just a public web app; if it's instead packaged in a native client you may and probably should be authenticating that client). You may want to verify that behavior of the library with your own testing.

If the library does not revoke previous refresh tokens, then you should probably mitigate the risk of having so many outstanding valid refresh tokens per session (~= expiration time divided by refresh period, or currently 7 / 1 = 7 valid tokens!!!) by making the refresh period much closer to the refresh token expiration. So if you keep the refresh expiration at 7 days, then only refreshing at 6 days would make sense. Then you would typically have 1 or at most 2 outstanding valid refresh tokens for a session. However, if given a choice, it is much more secure to have automatically revoked refresh tokens and shorter refresh periods; that way a compromised refresh token is much more likely to be invalid -- and you still wouldn't have to lose the benefit of the authorized user having a long refresh expiration. (The whole point of the long expiration is for situations such as an unattended laptop or mobile browser.)

Per OAuth 2 spec:

  The authorization server MUST verify the binding between the refresh
  token and client identity whenever the client identity can be
  authenticated.  When client authentication is not possible, the
  authorization server SHOULD deploy other means to detect refresh
  token abuse.

  For example, the authorization server could employ refresh token
  rotation in which a new refresh token is issued with every access
  token refresh response.  The previous refresh token is invalidated
  but retained by the authorization server.  If a refresh token is
  compromised and subsequently used by both the attacker and the
  legitimate client, one of them will present an invalidated refresh
  token, which will inform the authorization server of the breach.

  The authorization server MUST ensure that refresh tokens cannot be
  generated, modified, or guessed to produce valid refresh tokens by
  unauthorized parties.


There is no need to return a copy of the variablesUsed set. It's actually wrong to do so, because naming conventions for your method imply an autoreleased object to be returned. Thus I would rewrite your return as:

return [variablesUsed autorelease];
// or in case of ARC just
return variablesUsed;

See the Advanced memory management programming guide

Also set contains a useful method to filter using a block. In my opinion this results in slightly nicer code. You can convert your incoming array to a NSSet using + setWithArray:.

The if statement to return nil can be combined in your return.

Combining this results in the following implementation

+ (NSSet *) variablesUsedInProgram:(id)program {
    NSSet *programSet = [NSSet setWithArray:program];
    NSSet *variablesUsed = [NSSet objectsPassingTest:^(id object, BOOL *stop) {
        return !([object isKindOfClass:[NSNumber class]] || [self isOperation:term])
    }];
    return ([variablesUsed count] > 0) ? variablesUsed : nil;
}


import random

def Markov(text_file):

Python convention is to name function lowercase_with_underscores. I'd also probably have this function take a string as input rather then a filename. That way this function doesn't make assumptions about where the data is coming from

    with open(text_file) as f:    # provide a text-file to parse
        data = f.read()

data is a bit too generic. I'd call it text.

    data = [i for i in data.split(' ') if i != '']     # create a list of all words
    data = [i.lower() for i in data if i.isalpha()]    # i've been removing punctuation

Since ''.isalpha() == False, you could easily combine these two lines

    markov = {i:[] for i in data}    # i create a dict with the words as keys and empty lists as values

    pos = 0
    while pos < len(data) - 1:    # add a word to the word-key's list if it immediately follows that word
        markov[data[pos]].append(data[pos+1])
        pos += 1

Whenever possible, avoid iterating over indexes. In this case I'd use

   for before, after in zip(data, data[1:]):
       markov[before] += after

I think that's much clearer.

   new = {k:v for k,v in zip(range(len(markov)), [i for i in markov])}    # create another dict for the seed to match up with

[i for i in markov] can be written list(markov) and it produces a copy of the markov list. But there is no reason to making a copy here, so just pass markov directly.

zip(range(len(x)), x) can be written as enumerate(x)

{k:v for k,v in x} is the same as dict(x)

So that whole line can be written as

  new = dict(enumerate(markov))

But that's a strange construct to build. Since you are indexing with numbers, it'd make more sense to have a list. An equivalent list would be

 new = markov.keys()

Which gives you a list of the keys

    length_sentence = random.randint(15, 20)    # create a random length for a sentence stopping point

    seed = random.randint(0, len(new) - 1)    # randomly pick a starting point

Python has a function random.randrange such that random.randrange(x) = random.randint(0, x -1) It good to use that when selecting from a range of indexes like this

    sentence_data = [new[start_index]]     # use that word as the first word and starting point
    current_word = new[start_index]

To select a random item from a list, use random.choice, so in this case I'd use

   current_word = random.choice(markov.keys())

    while len(sentence_data) < length_sentence:

Since you know how many iterations you'll need I'd use a for loop here.

        next_index = random.randint(0, len(markov[current_word]) - 1)    # randomly pick a word from the last words list.
        next_word = markov[current_word][next_index]

Instead do next_word = random.choice(markov[current_word])

        sentence_data.append(next_word)
        current_word = next_word

   return ' '.join([i for i in sentence_data])

Again, no reason to be doing this i for i dance. Just use ' '.join(sentence_data)


The same behaviour can be achieved using sed as follows:

echo -e 'TestRecord001\tNULL\tNULL\tAge\t29\tNULL\tNULL\tName\tJohn' | sed '
s/$/\t/;
s/\(\tNULL\)\+\t/\t/g;
s/^NULL\t//';

Explanation:

sed s/SearchPattern/Replacement/g. Here s indicates that replacement operation is to be done. Strings matching SearchPattern will be replaced by Replacement. g indicates that the operation will have to be performed on every match and not just on the first occurrence in a line.

s/$/\t/ adds a tab to the end of each line. [$ matches the end of a line]
\(\tNULL\)\+\t matches a string of the form \tNULL\tNULL...NULL\t. This is replaced with \t.
After this the only remaining NULL is the one at the beginning of a line (without \t to its left). This is matched by ^NULL\t and replaced with the empty string. [^ matches the beginning of a line]


Whew, this is quite a tricky one. The main problem here is that you really, really need to keep Haskell from allocating anything in the relatively spacious inner loop. Otherwise, you are looking at a dozen bytes going through the garbage collector for every byte you escape.

As you note, blaze-builder has a reputation for being fast, mainly for being pretty good at this. Let's start off with an explanation why that is. Here's roughly how a Builder is defined (see Blaze.ByteString.Builder.Internal.Types):

newtype Builder = Builder (forall r. BuildStep r -> BuildStep r)
newtype BuildStep a = BufRange -> IO (BuildSignal a)
data BufRange a = BufRange !(Ptr Word8) !(Ptr Word8)

The compiler will replace all newtype wrappers with simple "casts", and un-box BufRange where possible. So this means that, say, your escape1 function would actually have an after-optimization type closer to:

escape1 :: Word8 -> (BufRange -> IO (BuildSignal a)) -> BufRange -> IO (BuildSignal a)

So this actually just takes the pointers from BufRange to write data using the IO monad, then finally calls the continuation. Ideally, we even know the continuation in question and can jump directly to the code. At no point does this require heap-allocation, everything gets nicely optimized out.

So, what's the problem in your case? The trouble is the "glue code". Let us look at the source of ByteString's foldl, with some additional type annotations:

lgo :: Builder -> Addr# -> Addr# -> IO Builder
lgo !z !p !q | p == q    = return z
             | otherwise = do c <- peek p
                              lgo (f z c) (p `plusPtr` 1) q

For every byte, this worker loop forces f in order to get the new "accumulated value". Unfortunately, that's a pretty bad idea here, as our accumulator is a Builder - a closure (as we saw above). Therefore this will actually allocate a huge list of closures, but not start producing anything of value until the very end.

So, how to improve this? Remember again that our f has type ... -> BuildStep r -> BuildStep r somewhere deep down. We would actually like to pass lgo as the BuildStep continuation, so after inlining it becomes a simple jump. We also don't really need the accumulation parameter, as the Builder is taking care of accumulating its result by itself.

Going through with this, we actually get a lazy right fold:

lgo :: Addr# -> Addr# -> BuildStep r -> BuildStep r
lgo !p !q | p == q    = v
          | otherwise = f (inlinePerformIO (peek p)) (lgo (p `plusPtr` 1) q)

(Note I also removed the IO by using inlinePerformIO, which might be unsafe in other usage scenarios, as any addresses escaping due to lazy evaluation might point to a garbage-collected buffer later!)

The type signature looks a lot better now - and from my testing this actually performs roughly twice as fast as the original version. Where does the rest of the performance get lost? Well, a look at the Core shows code like

lgo = \p q -> case p == q of
                True -> \r -> let ... in \stp -> ...
                False ->

This means that GHC is generating a lot of partially-applied functions - primarily because the optimizer doesn't want to lose sharing in case we want to call lgo with the same p and q, but different BuildSteps (which we never will, but GHC can't prove that).

So we need to force GHC to use higher arity for this function's implementation. Unfortunately, I am somewhat out of ideas how to accomplish that in an elegant way. So here's the manual solution -- writing our lambdas out at the top of the expression:

foldBuilder :: (Word8 -> Builder) -> B.ByteString -> Builder
foldBuilder f (PS x s l) =
  fromBuildStepCont $ \cont range ->
    withForeignPtr x $ \ptr -> do
      let lgo !p !q !range'
            | p == q    = cont range'
            | otherwise = do
                c <- peek p
                let p' = p `plusPtr` 1
                    step = unBuilder (f c) (BuildStep $ lgo p' q)
                runBuildStep step range'
      lgo (ptr `plusPtr` s) (ptr `plusPtr` (s+l)) range

I get decent performance out of this version here, and I suppose it's slightly better than implementing it completely by hand. It also happens to not require inlinePerformIO at all any more, which is a nice plus.

Code can be found at GitHub. I hope this helps in some way :)


As the comment says on the less-obfuscated version on Rosetta Code, their implementation is based on the Extended Euclidean Algorithm.  Your implementation works by brute force to test every element in the field, so of course it's going to be slow.


This is actually a 1-liner with the built-in split function:

ClassifiedrDataSplit <- split(rData, rClass)

You can confirm this returns the same result as your original code:

identical(ClassifiedrData, ClassifiedrDataSplit)
# [1] TRUE

In addition to being a lot less code, this will result in sensible speedups for larger datasets. For instance, consider the performance with 10 million elements and 10 classes:

rData <- sample(x = as.integer(c(1:1e7)), size = 1e7)
rClass <- sample(x = c(1:10), size = 1e7, replace = TRUE)
system.time({i <- 0
ClassifiedrData <- CreateEmptyDictionary(names <- sort(unique(rClass)))

for (a in rData) {
    i <- i + 1
    #ClassifiedrData[[rClass[i]]] <-  append(ClassifiedrData[[rClass[i]]], a)
    ClassifiedrData[[rClass[i]]][length(ClassifiedrData[[rClass[i]]])+1] <- a
}})
#    user  system elapsed
#   5.248   0.435   5.749
system.time(split(rData, rClass))
#    user  system elapsed
#   0.258   0.083   0.357

The solution with split is about 10x faster.


Web-crawler for yellowpage designed using python

If you've got a single method, there is probably not much sense in having a class and just have a separate function instead. More info at Stop Writing Classes.
If you do need a classmethod, the first argument to such a method is agreed to be named cls and not self.
Crawl should be named crawl according to Python PEP8 naming practices.
Use string formatting instead of string concatenation to make the final URL.
Or, you can use params to pass GET parameters.
Use if __name__ == '__main__':.
I would return from the crawl() method instead of printing.

Modified code:

import requests
from lxml import html

class YellowPage:
    URL_TEMPLATE = "https://www.yellowpages.com/search?search_terms={name}&geo_location_terms={state}"

    @classmethod
    def crawl(cls, name, state):
        page = requests.get(cls.URL_TEMPLATE.format(name=name, state=state)).text
        tree = html.fromstring(page)
        for items in tree.xpath("//div[@class='info']"):
            name = items.findtext(".//span[@itemprop='name']")
            address = items.findtext(".//span[@class='street-address']")
            phone = items.findtext(".//div[@itemprop='telephone']")
            yield (name, address, phone)

if __name__ == '__main__':
    for result in YellowPage.crawl("pizza", "florida"):
        print(result)

Another version (with params):

import requests
from lxml import html

class YellowPage:
    SEARCH_URL = "https://www.yellowpages.com/search"

    @classmethod
    def crawl(cls, name, state):
        page = requests.get(cls.SEARCH_URL, params={'search_terms': name, 'geo_location_terms': state}).text
        tree = html.fromstring(page)
        for items in tree.xpath("//div[@class='info']"):
            name = items.findtext(".//span[@itemprop='name']")
            address = items.findtext(".//span[@class='street-address']")
            phone = items.findtext(".//div[@itemprop='telephone']")
            yield (name, address, phone)

if __name__ == '__main__':
    for result in YellowPage.crawl("pizza", "florida"):
        print(result)

Version without a class:

import requests
from lxml import html

SEARCH_URL = "https://www.yellowpages.com/search"

def crawl(name, state):
    page = requests.get(SEARCH_URL, params={'search_terms': name, 'geo_location_terms': state}).text
    tree = html.fromstring(page)
    for items in tree.xpath("//div[@class='info']"):
        name = items.findtext(".//span[@itemprop='name']")
        address = items.findtext(".//span[@class='street-address']")
        phone = items.findtext(".//div[@itemprop='telephone']")
        yield (name, address, phone)

if __name__ == '__main__':
    for result in crawl("pizza", "florida"):
        print(result)


Check of a traffic light sequence using an array and if statements

you don't ever use the strings in colors, but use them only as kind of id, what you are showing: an index would be sufficient, even the better solution.
you don't use the order in colors but instead you jump manually; sub-optimal, especially since you don't have any logic in there but just run a simple loop
And you repeat yourself excessively.

You have three lights, that are either on or off. To me this screams for the use of a bit-mask: The State is represented by an integer, and each bit of this integer represents one of the lights: it's either 1 or 0.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(0, 0, 200, 300);
ctx.fillStyle = "grey";
ctx.fill();

//an array of the states, the code loops through
var activeLights = [0b100, 0b110, 0b001, 0b000, 0b010];
//var activeLights = [4, 6, 1, 0, 2];   //if your browser doesn't get the binary-notation
var currentIndex = 0;

function drawLight(index, color){
    ctx.beginPath();
    ctx.arc(95,50+index*100,40,10,12*Math.PI);
    ctx.fillStyle = color;
    ctx.fill();
    ctx.stroke();
}

function changelight(){
    var state = activeLights[currentIndex];

    //check the bit and draw the respective light
    drawLight(0, state & 0b100? "red": "black");
    drawLight(1, state & 0b010? "yellow": "black");
    drawLight(2, state & 0b001? "green": "black");
    //drawLight(0, state & 4? "red": "black");
    //drawLight(1, state & 2? "yellow": "black");
    //drawLight(2, state & 1? "green": "black");

    //the loop
    if(++currentIndex === activeLights.length) currentIndex = 0;
}

setInterval(changelight, 1000);


Check if more engineers are happy than not happy

Consider

private boolean isMajorityHappy(List<Engineer> engineers) {
    int netHappiness = 0;

    for (Engineer engineer : engineers) {
        if (engineer.isHappy()) {
            netHappiness++;
        } else {
            netHappiness--;
        }
    }

    return netHappiness > 0;
}

Name the method based on what it does.  What it does is check if the majority of the members of the list are happy.  The fact that the list is of engineers is mostly beside the point.

I would expect areEngineersHappy to return false if any engineer is unhappy.

Note that we don't need two variables to tell if the majority is happy.  We can use a single variable and subtract for unhappy members of the list.  If netHappiness is positive, then the majority of the members of the list are happy.

I would try to avoid constructs like if (! notHappy) {.  It would be much simpler to change the logic around so that you can say if (happy) { instead.

You don't need to say if (happy) and if (! happy).  This is exactly the situation for which an else is designed.


A small note first, please do not double-space all lines in code, it just makes it harder to read, rather than easier.

Integer overflow

Using an int primitive type for i and j is causing the number to go through integer overflow and go back to its minimum value -2,147,483,648 (or \$-2^{31}\$),  once it exceeds the maximum value 2,147,483,647 (or \$2^{31}-1\$), then finally all the way back from there to \$0\$, resulting in a java.lang.ArithmeticException: divide by zero. To correct this, use a long type for the iterators instead:

    // this is to see if num is factorable
    for (long i = 2; i < num; i++) {
        //if i is a factor, check if its prime
        if (num % i == 0) {
            for (long j = 2; j < i; j++) {

Algorithm

With the above problem fixed, we can now see that the algorithm you use has a few problems. Given the number \$n = 600851475143\$

It checks every number \$i\$ in the set \$[2,3,4, \ldots, n-1]\$ to see if it is a factor of \$n\$.
For each \$i\$, it then checks every number \$j\$ in the set \$[i, i+1, i+2,\ldots, n-2]\$ to see if it is prime.
It returns each number that matches both criteria, e.g., 71, 839, 1471 and finally the answer, and then it just keeps on going until \$i = 600851475143 - 1\$, which takes a very long time.

The "right" algorithm is very simple, and involves no primality testing. I left an explanation of it in the code comments. This finds the right answer in less than 1 second. There would be other ways to improve it to be more Java/object-oriented, but for the sake of a math exercise like this it should do pretty nicely. Here is a live demo as well.

class LargestPrimeFactor  {

    public static void main(String[] args) {

        long N = 600851475143L;

        // First, start from the maximum number and divide by 2
        // until you can no longer divide evenly by 2, i.e., the number is odd
        while (N % 2 == 0) {

            // in the case of 600851475143 this will be skipped entirely since it is an odd number,
            // but for the sake of generality we will keep it so it can be used on any number
            N /= 2;
        }

        // the next prime number is 3, and all prime numbers from there are odd numbers,
        // so we can safely just add 2 to the factor each time and only test for odd numbers
        // note that this has a small inefficiency in that it will also test for a few non-prime odd numbers
        // like 9, 15, 21, etc. but it's much less computational work to try dividing by a candidate factor than to test for primality.
        for (long factor = 3; factor < N; factor += 2) {

            // if N is evenly divisible by the factor, then we just divide it, and we keep going
            // until N can no longer be divided by a number smaller than itself,
            // in other words, until N is a prime number
            while (N % factor == 0 && factor < N) {
                N /= factor;
            }
        }
        System.out.println("The answer is " + N);
    }
}


Cyclomatic complexity for method is too high

[x].include?(y) is the most roundabout way I've ever seen of saying x == y.
You're repeating val.length >= args[:limit] for almost every. single. case.
Why is there an instance variable called @args? That smells like you didn't bother to actually handle things in the constructor, and instead just store everything for later. Also, why are you using @args directly, when it seems you also have a reader/accessor method, args? Using the accessor is better, though you can use either - just don't mix them.
Why isn't there code after the calls to valid_numeric? and valid_date?? The prefix valid_... and the ? in the names indicate that those methods (should!) return boolean values. But if they do, you're ignoring it - which doesn't make sense. So it smells like those methods don't so much validate anything, but actually set @value to something. No thanks.
You're overwriting the argument val, which isn't pretty. Make a new local variable instead, or write to @value directly.
What if val is just false? Not the word, but the boolean? In that case all the logic will be skipped, and you'll go straight to @val = false. It doesn't matter whatever @type is, or whatever args[:limit] is. I think you want your if to check for val.nil? specifically.

It seems like what you really want is 4-6 different classes to handle different datatypes. Whatever you're trying to do, you're doing too much of it in one method and one class.


split string into container on char; efficiently?

First, consider passing potentially expensive-to-copy objects such as std::string as const reference rather than by-value. The obvious approach is to use std::istringstream and std::getline.

std::vector<std::string> split_uri(const std::string uri&, char chr)
{
    std::istringstream iss(uri);
    std::vector<std::string> vec;

    for(std::string token; getline(iss, token, chr); )
        vec.push_back(token);

    return vec;
}

With the input being \bar\can, the output is {"", "bar", "can"}.

However, std::istringstream is not known for its speed. If you don't want to use std::istringstream, you don't have to. The following should be much faster:

std::vector<std::string> split_uri(const std::string& uri, char chr)
{
    std::string::const_iterator first = uri.cbegin();
    std::string::const_iterator second = std::find(first+1, uri.cend(), chr);
    std::vector<std::string> vec;

    while(second != uri.cend())
    {
        vec.emplace_back(first, second);
        first = second;
        second = std::find(second+1, uri.cend(), chr);
    }

    vec.emplace_back(first, uri.cend());

    return vec;
}

With the input being \bar\can, the output is {"\bar", "\can"}.


Refactor code to find four co-linear points

The easiest way to flatten this kind of a structure is to reverse the sense of the if.  That is, where you have

if (first.equals(next)) {
    // do stuff
}

Instead write

if (!first.equals(next)) {
    continue;
}
// do stuff

This only works where you don't have an else clause (so unfortunately I chose a bad example), but it can work wonders in bringing your code closer to the left margin.

From there I would start seeing where I could extract methods, especially but not exclusively where there is duplication in the code.  The block of code beginning with

SortedSet<Point> line = new TreeSet<Point>();

looks like a good candidate for this.


Finding Repeat and missing numbers in an array

The problem lies in these 2 lines of code:

 for i in number_array:
  if(number_array.count(i)==2):

Here for each number you are counting the number of occurrences in the array. Now, by doing that, You are reiterating over the numbers which are already counted. The call to number_array.count() searches the entire array, which means even for the last element, it will start from the first and calculate the count. This makes the time complexity \$O(n^2)\$. But, it can be done in \$O(n)\$ time.

Instead of using count, store the numbers in a hash table. And for each new number check, if it already exists in the hash table. If so, that's your duplicate number - A.

Also, while iterating through the loop, add each number to the other, and get their sum (omitting the double occurrence of A). And since you have a series from 1..n,

sum(1..n) = n * (n + 1) / 2

So, the missing number is:

sum(1..n) - actual sum


Evaluating a series of Legendre polynomials

Compute legendre(n) once per loop iteration instead of twice.
Use np.hypot instead of np.sqrt(x**2 + z**2).
Don't use phivec, just pass the arrays X and Y directly to phi, which is already almost vectorized. The only change that's needed is to use np.minimum and np.maximum instead of min and max respectively.

Revised code:

def phi(x, z, nlimit=35):
    r = np.hypot(x, z)
    costh = z / r
    rmin = np.minimum(r, 1)
    rmax = np.maximum(r, 1)
    dr = rmin / rmax
    suma = 0.0
    for n in range(nlimit):
        Ln = sp.legendre(n)
        suma += dr**n * Ln(costh) * Ln(0.0)
    return suma / rmax

X, Y = np.meshgrid(*[np.linspace(-2, 2, 50)] * 2)
Z = phi(X, Y)

I find that this takes about 0.05 seconds, which ought to be fast enough for you.


Error handling

Some would argue that it's unacceptable to exit() in case of an "out of memory" error occurring in a library function. I would invite them to tell me how to actually recover in those situations, because I doubt many "well-designed" applications do so.

That said, many libraries indeed have the courtesy of telling the caller that they can't complete their task, rather than killing the process. For a language like C (which lacks support for sum types and exceptions), I'm currently undecided between a few approaches, but I'd always make sure that the caller can distinguish between success and failure by a simple inspection of the return value.

The easiest approach would be to change the return value of bubblesort to a library-specific enum of error codes, which includes exactly one 'success' value (in C libraries, the common value would be 0) and at least one 'generic failure' value. If you want your users to be able to distinguish between failure reasons, just add more reason to the enum.

Once you have done this, you can also explicitly signal for other error conditions (arr == 0, size == 0), if you consider them errors.

Note: for some pet projects, I used to just return a bool, where true would mean success. Since I realised that this runs counter to the UNIX tradition of "zero means success", I no longer use that in public APIs.

Swapping

By introducing a memswap function

void memswap(void *restrict left, void *restrict right, size_t length);

we can move a lot of logic out of bubblesort itself. This also means we would move the malloc and free to it, which seems like a bad idea for a function in the inner loop.

But don't worry: you can implement memswap in any way you like. For instance, memswap could swap the data between aaaa and bbbb byte-by-byte:

void memswap(
    void *restrict left,
    void *restrict right,
    size_t length
) {
    char *left2 = (char *)left;
    char *right2 = (char *)right;

    for (size_t cursor = 0; cursor < length; cursor++) {
        char tmp = left2[cursor];
        right2[cursor] = left2[cursor];
        left2[cursor] = tmp;
    }
}

Now that you have no more malloc, you won't have to deal with the possibility of it returning a null pointer.

Of course, a robust memswap would not ever cause any UB (which could imply exit()), so you should add some checks for null pointers here. Whether that's an error condition, or that it causes memswap to do nothing is up to you as a library designer. The same goes for the check that left and right don't overlap.

Other functional remarks

You forgot a trailing newline in your error message.
Checking for the cases num == 0 or num == 1 is an attempt at optimisation (right?). I wouldn't do this, unless a benchmark shows that clients of the library are getting significant poor performance because of it (but then it might be a better idea to figure out why these calls are made to begin with).
In the line

right = (char *) arr + num * size;

you should definitely protect yourself against a potential integer overflow in num * size.

Stylistic remarks

Don't cast malloc's return value.
I assume that this isn't all code, but I want to clarify that the structure of files matters. My specific remark here would be that I always make a forward declaration to the functions I define.
Positive conditions, even when negated, are easier to understand than negative ones. For instance, the condition in

if (arr != NULL && size > 0 && num > 1) {

takes me more time to understand than

if (!(arr == NULL || size == 0 || num <= 1)) {

In terms of code real estate, vertical size is cheaper than horizontal size. With that, I mean that I think a failure check like

if (!(arr == NULL || size == 0 || num <= 1)) {

is more readable (and more VCS-friendly ;)) when it's split into multiple blocks, or that the clauses in the condition at least get their own line. Yes, your code grows in length, but I'd prefer boring-looking code that's obvious over "elegant" short code that takes effort to get through (and I say that as a Haskell user).
As of C99, 0 is the (canonical) null pointer constant (meaning that when you convert a constant integer expression with value 0 to a pointer, you get a null pointer; the actual "address" of that null pointer is implementation-defined, though). NULL is still valid, but I wouldn't use it.
const char *arr is confusing, as you know for a fact that you will modify arr. Just use char *arr, avoiding pointer casts later on.
The comments around the swap are not particularily helpful. I prefer many functions and named constants over comments and magic.
You could turn either loop into a for loop, but I recommend to keep this as a while here. The for-notation only helps readability when it concerns a single iterator, and has no performance benefit over while.
Thank you for using EXIT_SUCCESS and EXIT_FAILURE :)

Putting it together (without memswap itself)

enum your_library_status_code {
    your_library_success = 0,
    your_library_failure = 1,
};

/**
 * Bubblesort algorithm. Compatible with any data type.
 * @param base A void pointer to the array's first element.
 * @param num The number of elements in the array.
 * @param size The size of the data type.
 * @param compar A pointer to the comparison function.
 */
enum your_library_status_code bubblesort(
    void* base,
    size_t num,
    size_t size,
    int (*compar)(const void*, const void*)
) {
    if (base == 0) {
        // TODO: introduce error code for "invalid argument"
        return your_library_failure;
    }

    if (size == 0) {
        // TODO: introduce error code for "invalid argument"
        return your_library_failure;
    }

    size_t total_size = num * size;

    if (total_size / size != num) {
        // TODO: introduce error code for "invalid argument (due to overflow)"
        return your_library_failure;
    }

    char *arr = base;
    char *left, *current, *right;

    right = (char *) arr + total_size;

    while (right > arr) {
        left = (char *) arr;
        current = left + size;

        while (current < right) {
            if (compar(left, current) > 0) {
                memswap(left, current, size);
            }

            left += size;
            current += size;
        }

        right -= size;
    }

    return your_library_success;
}

(Caveat: not tested.)


The first thing I would do to make the code shorter is to take advantage of the fact that many jQuery methods like .attr() accept a function as the second argument, allowing you to replace this:

var src = $(this).attr("src").replace("1.jpg", "2.jpg");
$(this).attr("src", src);

...with this:

$(this).attr("src", function(i, v) { return v.replace("1.jpg", "2.jpg"); });

(and similar in the other function.) What this does is call the function in the second argument with the current value of the attribute as the v argument, so you don't need a separate call to .attr() to find out what the current value is, and you don't need the src variable.

Then I'd change the .hover() code to pass a single function to run on mouseenter and mouseleave, and use the event object to check whether it is mouseenter or mouseleave:

$(document).ready(function(){
  $("img").hover(function(e) {
    $(this).attr("src", function(i, v) {
      return v.replace(/[12]\.jpg/, (e.type === "mouseenter" ? "2" : "1") + ".jpg");
    });
  });
});

This uses a regular expression /[12]\.jpg/ with .replace() to find a string ending with "1.jpg" or "2.jpg", and replace it with a value depending on the event.type.

Demo: https://jsfiddle.net/g5ncjjxo/


Given a String and dictionary of words, break the string in minimum space sentence

Advice 1

You can get a substantial speed up by setting input = input.toLowerCase() and removing word = word.toLowerCase().

Advice 2

What comes to code, I suggest you separate the actual algorithm from the standard output. That way you can reuse your solution on larger string without getting overwhelmed with all the output. Also, it allows passing the result to some other processing routines, etc:

public static String[] opGetShortestTokenizationV2(String text,
                                                   Set<String> vocabulary) {
    text = text.toLowerCase();
    int left = 0;
    int right = text.length();
    List<String> result = new ArrayList<>();

    while (left < right) {
        for (int i = 0; i <= right; i++) {
            String word = text.substring(i, right);
            if (vocabulary.contains(word)) {
                right = i;
                result.add(word);
            }
        }
    }

    Collections.reverse(result);
    return result.toArray(new String[result.size()]);
}

Advice 3

left is not used. Your while loop condition becomes right != 0.


Sometimes it is easy to forget that the simplest logical constructs like boolean are comparable with the == operator, and that, in Java, (false == false) is true.

With this in mind, your code could become:

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    return aSmile == bSmile;
}

It may be easier to see how to get there if you first transform your original code into

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    if ((aSmile && bSmile) || (!aSmile && !bSmile)) {
        return true;
    } else {
        return false;
    }
}

… which could become

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    return (aSmile && bSmile) || (!aSmile && !bSmile);
}

From there, you may come to the realization that "both true or both false" is equivalent to "both the same".

Here is a verification of the output:

public static boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    return aSmile == bSmile;
}

private static void testTruth(boolean a, boolean b) {
    System.out.printf("monkeyTrouble(%s, %s) = %s\n", a, b, monkeyTrouble(a, b));
}

public static void main(String[] args) {
    testTruth(true, true);
    testTruth(true, false);
    testTruth(false, true);
    testTruth(false, false);
}

This produces:

monkeyTrouble(true, true) = true
monkeyTrouble(true, false) = false
monkeyTrouble(false, true) = false
monkeyTrouble(false, false) = true


More Revealing Module Patter in Javascript

There's nothing really wrong with variation 1, but there's also no point in putting things in pr. Sure you can chain it, but why chain something where this only refers to half the stuff you need (the private stuff)? You might as well just use function declarations. And you can get rid of PU, since it's kind of a meaningless variable name:

var MyModule = (function(){
    function fetch(obj){}; // fetching data
    function build(obj){}; // building DOM of module
    function show(obj){};  // showing our object
    function hide(obj){};  // hiding our object
     //... Other private methods
     return {
         // Public methods
         init: function(){
             show(build(fetch(this)));
             return this; // for making chains
         },
         update: function(){}
         // ... other Public methods
     };
})();

The problem with variation two is that you create those functions whenever the constructor is called (so, more than once).

The normal way to avoid this is to do something like

var MyModule = (function(){

    function fetch(obj){}; // fetching data
    function build(obj){}; // building DOM of module
    function show(obj){};  // showing our object
    function hide(obj){};  // hiding our object

    function MyModule(){
        // constructor code
    };

    MyModule.prototype.init = function(){
        show(build(fetch(this)));
        return this;
    };

    MyModule.prototype.update = function(){};
    //... other Public methods

    return MyModule;

}());

Does that make sense?

This is not really a "module" anymore, by the way, just a normal constructor with some function properties attached to the prototype. But it looks like that's what you want, since you need multiple instances of it.


Dictionary with ISet key as a collection of names

You can just use a single class with a generic Create method which has constraints for IEqualityComparer<string>:

internal class NameSetGeneric : HashSet<string>
{
    private NameSetGeneric(IEnumerable<string> keys, IEqualityComparer<string> keyComparer)
        : base(keys ?? throw new ArgumentNullException(nameof(keys)), keyComparer)
    {
    }

    public static NameSetGeneric Create<T>(T comparer, params string[] keys)
        where T : IEqualityComparer<string> => new NameSetGeneric(keys, comparer);
}

You can even go further and make the whole class generic, but that's only if you want to work with different data types.

Example usage:

var dic = new Dictionary<NameSetGeneric, string>(new SetComparer());
dic.Add(NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, "foo", "bar"), "fb");
dic.Add(NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, "qux"), "q");
dic[NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, "baz")] = "b";
dic[NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, "bar")].Dump(); //fb
dic.Add(NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, "foo"), "f"); // bam!


First, move these into well-defined functions:

def bubble(l):
    i = 0
    while i < len(l) - 2:
        if l[i + 1] < l[i]:
            tup = l[i], l[i + 1]
            l[i + 1], l[i] = tup
        i += 1

def partial_bubble_sort(l, iterations):
    ic = 0
    while ic < icount:
        bubble(l)
        ic += 1

def main():
    s = '36 47 78 28 20 79 87 16 8 45 72 69 81 66 60 8 3 86 90 90 | 2'
    ls = s.split('|')
    l = [int(n) for n in ls[0].split(' ') if n.isdigit()]
    icount = int(ls[1].strip())
    print("list is", l, len(l))
    print("count is ", icount)

    partial_bubble_sort(l, icount)
    print(' '.join(str(i) for i in l))

main()
#>>> list is [36, 47, 78, 28, 20, 79, 87, 16, 8, 45, 72, 69, 81, 66, 60, 8, 3, 86, 90, 90] 20
#>>> count is  2
#>>> 36 28 20 47 78 16 8 45 72 69 79 66 60 8 3 81 86 87 90 90

Your while i < len(l) - 2 should be while i <= len(l) - 2; currently you are missing the last element.

Change the i = 0; while i < x; i += 1 loops to for i in range(x).

Your tup = l[i], l[i + 1]; l[i + 1], l[i] = tup would be faster on one line; CPython won't optimize out the intermediate for you.

Since you only want to split the string into two, I recommend:

in_string = '36 47 78 28 20 79 87 16 8 45 72 69 81 66 60 8 3 86 90 90 12 | 2'

numbers, sep, iterations = in_string.rpartition('|')
assert sep

numbers = [int(n) for n in numbers.split()]
iterations = int(iterations.strip())

...although I don't see why you're not just doing

numbers = [36, 47, 78, 28, 20, 79, 87, 16, 8, 45, 72, 69, 81, 66, 60, 8, 3, 86, 90, 90, 12]
iterations = 2

Anyhow, I'm finding this takes 30-50% less time than the original.

There are still more optimizations you can do. This is a more efficient bubble which avoids shifts by holding the moving element. This can be further improved by using enumerate to avoid the indexing.

def bubble(lst):
    held, rest = lst[0], lst[1:]

    for i, v in enumerate(rest):
        if v > held:
            v, held = held, v

        lst[i] = v

    lst[-1] = held

Each pass of bubble, one more element on the end of the array is already sorted. This means we can give bubble a paramenter of how many elements to skip.

def bubble(lst, skip):
    held, rest = lst[0], lst[1:len(lst)-skip]

    for i, v in enumerate(rest):
        if v > held:
            v, held = held, v

        lst[i] = v

    lst[-skip-1] = held

def partial_bubble_sort(lst, iterations):
    for skip in range(iterations):
        bubble(lst, skip)

You need len(lst)-skip here instead of just -skip since skip could be 0.

This explicitly checks lst[0], so you should cap iterations in partial_bubble_sort to len(lst) - 1 to prevent it ever being called for empty lists (or do a check in the function itself):

def partial_bubble_sort(lst, iterations):
    for skip in range(min(iterations, len(lst)-1)):
        bubble(lst, skip)

This should all end up several times (4-5) as fast as the original.


Here are some changes I would make:

Your snake_body class (which should be called SnakeBody, according to PEP8), does not need to initialize its attributes before the initialization, so you can just have:

class SnakeBody:

    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "SnakeBody({self.x}, {self.y})".format(self=self)

I also gave it a __repr__ method so it prints nicer.

Currently, your full snake is just a list of body parts. While this is nice, you also have a few functions that just operate on a snake, so it would be nice to add these two things together and make snake a class as well. I would do something like this, which inherits from list so the rest of your code stays basically unchanged, except that instead of draw_snake() you now have snake.draw(), etc:

class Snake(list):

    def __init__(self, start_x, start_y, n):
        list.__init__(self, [SnakeBody(start_x, start_y + i * factor)
                             for i in range(n)])

    def move_head(self, dx, dy):
        self[0].x += dx
        self[0].y += dy

    def update(self, score):
        for i in range(len(self) - 1, 0, -1):
            self[i].x = self[i - 1].x
            self[i].y = self[i - 1].y

    def check_death(self):
        if not (1 <= self[0].x <= display_width and 1 <= self[0].y <= display_height):
            return True
        return any(body_part.x == self[0].x and body_part.y == self[0].y for body_part in self[1:])

    def draw(self):
        for body_part in self:
            pygame.draw.rect(game_display, teal,
                             (body_part.x, body_part.y, factor, factor))

Note that I also simplified the check_death function. It now returns True if the snake needs to die. I used the fact that Python can do multiple comparisons, so a <= x <= b is legal in Python.

The actual game code I would put into a main function which you can call within a if __name__ == "__main__": guard to allow importing this from another script. With these changes, your code becomes:

Final code:

import pygame
import time
import random

pygame.init()

# defines the width and height of the display
display_width = 800
display_height = 600

white = (255, 255, 255)
d_white = (250, 250, 250)
black = (0, 0, 0)
teal = (0, 128, 128)
blue_black = (50, 50, 50)
game_display = pygame.display.set_mode((display_width, display_height))

factor = 10

clock = pygame.time.Clock()

class SnakeBody:

    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "SnakeBody({self.x}, {self.y})".format(self=self)

class Snake(list):

    def __init__(self, start_x, start_y, n):
        list.__init__(self, [SnakeBody(start_x, start_y + i * factor)
                             for i in range(n)])

    def move_head(self, dx, dy):
        self[0].x += dx
        self[0].y += dy

    def update(self, score):
        for i in range(len(self) - 1, 0, -1):
            self[i].x = self[i - 1].x
            self[i].y = self[i - 1].y

    def check_death(self):
        if not (1 <= self[0].x <= display_width and 1 <= self[0].y <= display_height):
            return True
        return any(body_part.x == self[0].x and body_part.y == self[0].y for body_part in self[1:])

    def draw(self):
        for body_part in self:
            pygame.draw.rect(game_display, teal,
                             (body_part.x, body_part.y, factor, factor))

def main():
    food_x = random.randrange(5, display_width - 5)
    food_y = random.randrange(5, display_height - 5)
    print(food_x, food_y)
    score = 60

    snake = Snake(20, 20, 16)

    x = 0
    y = 0
    x_change = 0
    y_change = 0
    first_time = True
    eat = True

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                first_time = False
                if event.key == pygame.K_a:
                    if x_change != 10:
                        x_change = -10
                        y_change = 0
                elif event.key == pygame.K_d:
                    if x_change != -10:
                        x_change = 10
                        y_change = 0
                elif event.key == pygame.K_w:
                    if y_change != 10:
                        x_change = 0
                        y_change = -10
                elif event.key == pygame.K_s:
                    if y_change != -10:
                        x_change = 0
                        y_change = 10
                elif event.key == pygame.K_c:
                    x_change = 0
                    y_change = 0

        if not first_time:
            snake.update(score)
        if score % 10 == 0 and eat:
            snake.append(snake_body(
                snake[len(snake) - 1].x, snake[len(snake) - 1].y))
            print(len(snake))
            eat = False
        snake.move_head(x_change, y_change)

        if snake[0].x < food_x + 10 and snake[0].x > food_x - 10 and snake[0].y < food_y + 10 and snake[0].y > food_y - 10:
            score += 10
            food_x = random.randrange(5, display_width - 5)
            food_y = random.randrange(5, display_height - 5)
            eat = True

        if snake.check_death():
            pygame.quit()
            quit()

        # update game display
        game_display.fill(white)

        pygame.draw.rect(game_display, black, (food_x, food_y, factor, factor))
        snake.draw()

        pygame.display.flip()
        time.sleep(0.035)
        clock.tick(60)

if __name__ == "__main__":
    main()

                                        <br>


Creating input when checking/clicking radio button

There's no need to use a while loop, as you only want to add the element once, after which the condition won't hold anymore. That's what if is for.
There's a shorter way to create a new element

So I get to:

$(function() {
    $("#others").click(function() {
         if ($("#others").val() == "Notice") {
            var newElement = $('<input>')).attr({name:"noticeweeks", id:"noticeweeks"});
            newElement.appendTo("#inputplace");
            $("#others").val("Notice me in...");
        }
    });
});


So I would make some changes:

let returnValue =
    match arglist with
        | path :: _ -> convert path
        | _ -> "Wrong number of arguments supplied"

should probably be something like

let returnValue =
    match arglist with
        | path :: _ -> convert path
        | _ ->failwith "Wrong number of arguments supplied"

which would simplify some logic

I would also change the printing to use sprintf

"{\"X\": \"" + bitmap.Width.ToString() +
"\", \"Y\": \"" + bitmap.Width.ToString() +
"\", \"values\":[" + results + "]}"

becomes

sprintf "{\"X\": \"%i\", \"Y\": \"%i\", \"values\":[%s]}" (bitmap.Width.ToString() ) (bitmap.Width.ToString() ) results


value.getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by a Date object.

You don't need a ConvertToTimestamp method, just call value.getTime() / 1000 to get the seconds.


We can improve readability of your code as follows:

using type annotations partially looks incomplete, when we can be more descriptive:

from typing import (Iterable,
                    TypeVar)

ElementType = TypeVar('ElementType')

def iter_group(iterable: Iterable[ElementType],
               batch_size: int) -> Iterable[Iterable[ElementType]]:
    ...

checking if object has given type should be done using isinstance built-in function, so instead of

iterable_type = type(iterable)
...
if iterable_type == list:
    ...

we can simply write

if isinstance(iterable, list):
    ...

(btw I don't understand why are you treating list as a special case)
if you want negate a number then we can use - unary operator, no need to multiply by -1, so instead of

start = batch_size * -1

we can write

start = -batch_size

no need in parentheses for while-loop condition, we are not in C/C++/JAVA, we can simply write:

while end < length:
    ...

setting start to -batch_size and end to 0 and change them right after that seems redundant when we can set them to 0 and batch_size respectfully and increment at the end of the while loop body, so instead

start = batch_size * -1
end = 0
while end < length:
    start += batch_size
    end += batch_size
    ...

we can write

start = 0
end = batch_size
while end < length:
    ...
    start += batch_size
    end += batch_size

If I understood correctly what you are trying to achieve is to split iterable into evenly sized chunks, which is a well-known StackOverflow question, but accepted answer works only for sequences (str/list/tuple) and so does your solution. For example it won't work for potentially infinite sequences like classic Fibonacci numbers generator

>>> def fibonacci():
        a, b = 0, 1
        while True:
            yield a
            a, b = b, a + b
>>> next(iter_group(fibonacci(), 5))
Traceback (most recent call last):
    ...
        length = len(iterable)
TypeError: object of type 'generator' has no len()

If you want to work with arbitrary iterables (e.g. generators), we may use itertools module and this brilliant solution which uses iter built-in function form with sentinel value

from itertools import islice
from typing import (Iterable,
                    Tuple,
                    TypeVar)

ElementType = TypeVar('ElementType')

def chunks(iterable: Iterable[ElementType],
           batch_size: int) -> Iterable[Tuple[ElementType, ...]]:
    iterator = iter(iterable)
    return iter(lambda: tuple(islice(iterator, batch_size)), ())

but if we make a simple benchmark with

def sequence_chunks(iterable: Sequence[ElementType],
                    batch_size: int) -> Iterable[Sequence[ElementType]]:
    for start in range(0, len(iterable), batch_size):
        yield iterable[start:start + batch_size]

like

import timeit

...
print('original solution',
      min(timeit.repeat('list(iter_group(iterable, 1000))',
                        'from __main__ import iter_group\n'
                        'iterable = range(0, 10001)',
                        number=10000)))
print('Ned Batchelder\'s solution',
      min(timeit.repeat('list(sequence_chunks(iterable, 1000))',
                        'from __main__ import sequence_chunks\n'
                        'iterable = range(0, 10001)',
                        number=10000)))
print('senderle\'s solution',
      min(timeit.repeat('list(chunks(iterable, 1000))',
                        'from __main__ import chunks\n'
                        'iterable = range(0, 10001)',
                        number=10000)))

on my laptop with Windows 10 and Python 3.5 we'll have

original solution 0.07320549999999999
Ned Batchelder's solution 0.06249870000000002
senderle's solution 2.6072023999999994

so how can we have both speed and handle cases with non-sequence iterables?

Here comes functools module with singledispatch function decorator. We can use it like

import timeit
from collections import abc
from functools import singledispatch
from itertools import islice
from typing import (Iterable,
                    Sequence,
                    TypeVar)

ElementType = TypeVar('ElementType')

@singledispatch
def chunks(iterable: Iterable[ElementType],
           batch_size: int) -> Iterable[Iterable[ElementType]]:
    iterator = iter(iterable)
    return iter(lambda: tuple(islice(iterator, batch_size)), ())

@chunks.register(abc.Sequence)
def sequence_chunks(iterable: Sequence[ElementType],
                    batch_size: int) -> Iterable[Iterable[ElementType]]:
    for start in range(0, len(iterable), batch_size):
        yield iterable[start:start + batch_size]

after that call to chunks will end up in sequence_chunks for sequences and in general chunks for all other cases.

But

print('single-dispatched solution',
      min(timeit.repeat('list(chunks(iterable, 1000))',
                        'from __main__ import chunks\n'
                        'iterable = range(0, 10001)',
                        number=10000)))

gives

single-dispatched solution 0.0737681

so we lose some time during dispatching, but we can save some time and space if we will use itertools.islice for sequences as well like

@chunks.register(abc.Sequence)
def sequence_chunks(iterable: Sequence[ElementType],
                    batch_size: int) -> Iterable[Iterable[ElementType]]:
    iterator = iter(iterable)
    for _ in range(ceil_division(len(iterable), batch_size)):
        yield islice(iterator, batch_size)

def ceil_division(left_number: int, right_number: int) -> int:
    """
    Divides given numbers with ceiling.
    """
    # based on https://stackoverflow.com/a/17511341/5997596
    return -(-left_number // right_number)

which gives

complete single-dispatched solution 0.03895900000000002

P.S.

@AJNeufeld's solution gives

0.0647120000000001

on my laptop


Can't help with the speed question but some generic remarks:

Both ManagementClass and ManagementObjectCollection are IDisposable and should therefore be wrapped in a using block to make sure any unmanaged resources are properly released.
Prefixing all your local variables with obj smells like hungarian notation and is generally discouraged. It adds not value and just clutter. Your variable names should indicate what they represent and not what type they are.
In C# land the common naming convention for methods is PascalCase and not camelCase. It pays to stick to general naming conventions for the ecosystem you are working in as it will make your code look more familiar to other developers.


Pointers seem more complicated, but they're usually faster and more correct.

Faster

For example, perhaps you have a function like this:

CMatrix add(CMatrix left, CMatrix right)
{
     ... add the matrices ...
}

In the above you're passing matrix parameters by value instead of by pointer. That means that you're passing a copy of each matrix (instead of a pointer to each matrix).

Assuming you have 32-bit pointers, each matrix is 12 bytes in size (4 bytes for the pointer and 4 bytes for each integer), so you're passing 24 bytes (for two matrices) instead of 8 bytes (for two pointers-to-matrices).

That (24 bytes instead of 8 bytes) is not a big difference (i.e. not much slower); but it's a bigger difference when your structs are larger and more complicated.

More correct

Another problem is that subroutines are operating on a private, local copy of the matrix; for example:

void transpose(CMatrix matrix)
{
    ... height becomes width and vice versa ...
    uint32_t oldWidth = matrix.width;
    uint32_t oldHeight = matrix.height;
    matrix.width = oldHeight;
    matrix.height = oldWidth;
    ... and transpose the data ...
}

This function changes the width and height of its local copy of the matrix, not the width and height of the caller's copy of the matrix.

Summary

Your code happens to work because:

You have a simple structure
You don't alter height and width in a subroutine, after you create the matrix
The data itself within the matrix (i.e. the double *m pointer) is a pointer (and is therefore shared between subroutines)

However it's bad practice: if you're coding in C, you should become familiar with using pointers.

There's nothing wrong with the newCMatrix function you showed in the OP. What I'm criticizing is your statement that pointers complicate things, because they're usually necessary, e.g. for other functions; for example, the 'add' function above should (in order to be idiomatic) be declared more like the following:

CMatrix add(const CMatrix *left, const CMatrix *right)
{
     ... add the matrices ...
}


There's probably a faster way to grab the display like with DirectX or something. WinGDI (BitBlt) is probably pretty slow.
GetDC has no effect on class or private DCs, so it is always sensible to call ReleaseDC after GetDC.
Watch out GetClassInfoEx function.
HBITMAP hbm_Buffer = CreateCompatibleBitmap(hdcMain, bmScreenBuffer->GetWidth(), bmScreenBuffer->GetHeight());: assuming your machine is running in 32-bit color, this generates a 32-bit bitmap (ie: compatible with the current display). Don't use CreateCompatibleBitmap here. Use CreateBitmap instead. Also note that you no longer really need hdcMain for this.
Remember that the Graphics class itself is a managed object and it will be garbage collected sooner or later. This class also uses unmanaged memory, the garbage collector doesn't "see" that memory and doesn't know that the actual memory used by the Graphics class may be much higher than the size of a Graphics instance. But fortunately you did it correctly: it's better to delete such objects as soon as you no longer need them, deleting will free any unmanaged memory or any other resources like opened files.


You asked about efficiency, which I am not an expert in. However, if you are going to share your code here, it would be nice if you could adapt it to the Java code style conventions.
In short: you should use PascalCase for your class names, so...

Main.java instead of main.java
Time.java instead of time.java
Window.java instead of window.java

Also, using single-letter names for your parameters is discouraged (borderline in the case of the fairly obvious int h and int m, bad in the case of String t). Why not hours, minutes, and halfOfDaySuffix? I'm sure you could find an even better term for the latter with a little research.

If you haven't already, make sure you organize your code into one or more package(s), e.g. put package com.jackwilsdon.TimeConversion; at the beginning of your files. This helps avoid name clashing problems (for instance with java.sql.Time).

In regard to to24h(): Never compare two Strings with the == (reference equals) operator in Java. This will only work in a narrow range of scenarios, read the full explanation on StackOverflow. You need to use the String.equals method instead.

But while we are at it, you shouldn't be using a String to represent AM/PM anyway - it will stop working if you pass in the wrong string, for instance pm instead of PM by mistake. Instead, restrict the possible values by creating an Enum:

public enum DayHalf {
    AM,
    PM
}

Then (in Window), you can change tAMPM's type from String to DayHalf - the following line will stop working:

tAMPM = (String)combo.getSelectedItem();

So you need to use combo = new JComboBox(DayHalf.values()); instead of combo = new JComboBox(times); and change the above line to

tAMPM = (DayHalf)combo.getSelectedItem();

If you are passing in AM or PM, hours above 12 are not acceptable - neither are minutes above 59! Hence, your conditions are erroneous; also, silently failing by setting the fields to 0 isn't a robust solution. You should throw an IllegalArgumentException if the values are out of range.

Your updated setTime method would look something like this:

public void setTime(int hours, int minutes, DayHalf halfOfDaySuffix) {
    if (hours < 0 || hours > 12 || minutes < 0 || minutes > 59)
        throw new IllegalArgumentException("hours or minutes out of allowed range!");
    hour = hours;
    minute = minutes;
    dayHalf = halfOfDaySuffix;
}

Regarding your JFrame (Window.java, should probably be called TimeConversionWindow.java), you should adjust the obviously copied-and-pasted error message:

else if (tMinutes > 60) {
    output.setText("Please enter a 12 hour number!");
}

to "Please enter less than 60 minutes!" or similar. Note that your condition (tMinutes > 60) is incorrect once again and should be changed to > 59.

A couple of other adjustments will be required, but they are easy to figure out. I'd argue that performance is nearly irrelevant in this scenario, read up on bottlenecks.


Use an existing invoice if one exists, else create one

The refactor goal was to make clear the logic for getting an invoice.

THIS IS THE MOST IMPORTANT POINT: Original code tells me there are 2 kinds of invoices so I knew I wanted a "if" that stated very simply and high level the logic for deciding which. So I wrote that and worked all the rest of the code around it.
Moving code into the get_xxx methods I saw that fetching the existing invoice was in both methods.
The above had me realize that no matter what, we use an pre-existing invoice if it's there. So I pulled that line out and put it at the top. Now it is obvious what's really going on.
I renamed invoice_obj because that sounds like it's an invoice too. But it's not. Its properties are used for fetching an actual invoice. So I thought of invoice_obj as metadata of a real invoice.
Make both "if" branches the same "level of abstraction". I'm trying to express that there are 2 kinds of invoices. I'm hiding the detail code that actually does it - that's a different level of detail.

I want it to say this:

if ...
  get_initial_invoice(metadata)
else
  get_invoice(metadata)

and not this:

if ...
  get_initial_invoice(metadata)
else
  Invoice.find_by(metadata[:id])

Refactored Code

 return existing_invoice if existing_invoice.present?

 invoice = nil

 if initial_invoice?(invoice_metadata)
    invoice = get_initial_invoice(invoice_metadata)
 else
    invoice = get_invoice(invoice_metadata)
 end

 return invoice

 private

 def get_initial_invoice(invoice_metadata)
    ac = Account.find_by(stripe_customer_id: invoice_metadata[:customer])
    create_initial_invoice(invoice_metadata, ac)
 end

 def get_invoice(invoice_metadata)
    return Invoice.find_by(invoice_metadata[:id])
 end

 def initial_invoice?(invoice_metadata)
   return false if invoice_metadata[:subscription].nil?

   sub = Stripe::Subscription.retrieve(invoice_metadata[:subscription])
   invoice_metadata[:period_start] == sub[:created] ? true : false
 end


I really feel bad about recommending this, but based on what you're doing you should investigate the use of Webforms in ASP.NET.

Webforms are the most straightforward way to provide easy CRUD operations on a database in C# while exposing the operations safely to the user. You also will work entirely with C# and the ASP.NET elements in html, so there's no need to manually use javascript with most basic tasks.

If you want to get more advanced then you can go with MVC5 in ASP.NET but that doesn't have the same level of builtin controls, data table displays, and similar that webforms has baked into itself. MVC5 does give you more power and flexibility in return, but if you need to get something done in a hurry or in a very basic form then you'll probably be fine with Webforms.

The problem with webforms, and why I feel bad recommending it, is that it tends to not encourage good N-Tier design because it both allows you to do things like embed SQL queries in your views (which is blasphemy) and a lot of the examples display exactly that behavior.

It is possible to setup a good distribution of responsibilities into multiple tiers with webforms, which is what I'm doing at my current job, but it doesn't do a great job of encouraging good design. That being said, it does encourage getting things done in a hurry, so that can sometimes outweigh the drawbacks.


Arithmetic expression parsing, and converting infix to postfix notation

If the condition order changes ( check the stack empty later), there'll be a segmentation fault (because I'm calling operators.top() which is NULL)

Calling top() on an empty queue is even worse then returning NULL. It is actually undefined behavior. Which means your code is broken.

This though:

while ((!operators.empty())&&(order(operators.top()) >= order(token[0])))

Is fine: The && operator evaluates the left hand side first and only if this evaluation returns true will it evaluates the right hand side. So the above expression is well formed and correct.

  Convert from char to string using: which I think constantly create a new variable s and delete it.

Yes it creates a new variable s.

s will be destroyed(and its destructor called) when it goes out of scope (just like all variables are destroyed when they go out of scope). This is not a big deal.

Personally I would have used Flex/Bison to implement the parser.


There are already the functions std::min and std::max that you should use. It either takes 2 elements or an std::initializer_list, so you could use

int min_1 = std::min({first_char, second_char, third_char});

There is also std::minmax to get both the minimum and the maximum, possibly more efficiently than calling std::min and then std::max. Not that it matters for your application, but it is a good habit to get into.

There is also std::none_of to check if none of first_char, second_char and third_char are -1, but the use is awkward because it needs a predicate.
Use range based for when possible. In this case you iterate over all the chars in the string, so it is easy:

//while (*pstring != '\0')
//for (const char c : string1)
for (const char c : "adobecodebanc")

If you initialize first_char, second_char and third_char with std::numeric_limits<int>::min() you could leave out the check if all of them are not -1. You need to be careful for when printing though.
I assume this is supposed to be a general function for any string. If that string is "erf" the function prints "e". That doesn't seem right.
main(void) is considered bad style in C++. In C a function void f(); takes any number of arguments, so f(234, 2) compiles fine. To make that fail to compile you have to write void f(void). In C++ f(234, 2) doesn't compile and void f(void) is redundant, making you look like a C programmer trying out C++.
final_distance is initiated to "some big number". It makes sense to use std::numeric_limits<int>::max() instead of 1000.
Use const when it makes sense, for example for min_1, max_1 and distance.
Putting it all together it looks like this:

#include <iostream>
#include <stdio.h>
#include <algorithm>

int main()
{
    char string1[] = "adobecodebanc";
    int first_char = -1;
    int second_char = -1;
    int third_char = -1;
    int final_distance = std::numeric_limits<int>::max();
    int final_min = 0;
    int final_max = 0;
    int counter = -1;

    /* iteratre over the string and compare each characeter*/
    for (const char c : string1)
    {
        counter++;
        /* if any character matches substring condition
           assign index value of the string to that variable  */
        if (c == 'a')
        {
            first_char = counter;
        }
        else if (c == 'b')
        {
            second_char = counter;
        }
        else if (c == 'c')
        {
            third_char = counter;
        }
        else{
            continue;
        }

        if (first_char != -1 && second_char != -1 && third_char != -1)
        {
            /* get the min and max index value difference*/
            const auto minmax = std::minmax({first_char, second_char, third_char});
            const int distance = minmax.second - minmax.first;

            /*track the minimum substring so far*/
            if (distance < final_distance)
            {
                final_distance = distance;
                final_min = minmax.first;
                final_max = minmax.second;
            }
        }
    }

    int temp = final_min;

    while (final_max >= temp)
    {
        std::cout << string1[temp];
        temp++;
    }
    std::cout << std::endl; //should not be needed since the program exits
    return 0; //gets implicitly added if you leave it out
}

I feel like I'm missing an obvious improvement, so I'll take a look again later.


well, calculating all the primes from 2 through 1000000000 will take too long.

Suggest pre-calculating (offline) all those primes and output them into a .txt file.

Then edit that file into a C data table of size_t values.

then in your program, paste that text file into the file scope of your program. I.E. outside of any function.

remove those massive 60000 arrays from your program.  All you really need is a counter to count the primes in the range n...m

In the offline program, use the Sieve of Eratosthenes algorithm (use google to find the algorithm)

using scanf() and 'printf()` burns LOTs of precious time.

suggest using the following functions for fast read/write of a Number.  Use repeated calls to putc_unlocked() to output a string.  Note: Be sure to output a final '\n' so the output ends in a blank line.

#include <stdio.h>

void fastRead( size_t *a );
void fastWrite( size_t a );

inline void fastRead(size_t *a)
{
    int c=0;
    // note: 32 is space character
    while (c<33) c=getchar_unlocked();

    // initialize result value
    *a=0;

    // punctuation parens, etc are show stoppers
    while (c>47 && c<58)
    {
        *a = (*a)*10 + (size_t)(c-48);
        c=getchar_unlocked();
    }
    //printf( "%s, value: %lu\n", __func__, *a );
} // end function: fastRead

inline void fastWrite(size_t a)
{
    char snum[20];
    //printf( "%s, %lu\n", __func__, a );

    int i=0;
    do
    {
        // 48 is numeric character 0
        snum[i++] = (char)((a%10)+(size_t)48);
        a=a/10;
    }while(a>0);

    i=i-1; // correction for overincrement from prior 'while' loop

    while(i>=0)
    {
        putchar_unlocked(snum[i--]);
    }
    putchar_unlocked('\n');
} // end function: fastWrite

Then your program only needs to do the following:

in English:

input numbertestcases
while decrement numbertestcases > 0
    input 'n'
    input 'm'

    set primescount = 0

    for ( size_t x=0;
          m <= primestable[x]
          &&
          x < sizeof( primestable )/ sizeof( *primestable );
          increment x)
        if primestable[x] >= n
             increment primescount
        endif
    end for

    output primescount
    output '\n'
end for

output '\n'

then:

the code will be VERY fast
no need for #include <string.h>
no need for #include <math.h>
probably no need for #include <stdlib.h>


Printing even and odd using two concurrent threads

public class Odd implements Runnable{

private Monitor sharedObject;

public Odd(Monitor monitor){
    this.sharedObject = monitor;
}

You implemented the class as a Runnable - great first step.  You are injecting the shared Monitor in the constructor, which is good; the member variable should be final though -- you aren't intending to change it after initialization.  Also, it should be named "monitor".

@Override
public void run() {

    try {
        printOdd();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

If you are trying to learn about using multiple threads, one of the things you must come to understand is what InterupptedException means.  In particular, printStackTrace isn't likely to tell you anything interesting (yup, the exception was thrown by sharedObject.await()), and if you are going to catch the exception, you must reset the interrupt flag so that the function that called you can know that cancellation is in progress.

private void printOdd() throws InterruptedException {
    synchronized(sharedObject){
        for(int i=1; i< 10; i++){
            if(i%2!=0){
                while(!sharedObject.isOdd()){
                    sharedObject.wait();
                }
                System.out.println("Odd: "+ i);
                sharedObject.setOdd(false);
                sharedObject.notifyAll();
            }
        }
    }
}

You are testing your condition in a while() loop -- good job, that's really important.  You are also notifying all threads that are blocked on the sharedObject, which is another Good Thing.

There's a generalization to your code that might be appropriate to make explicit:

for(int i=1; i< 10; i++){
    if(i%2!=0){
        ...
    }
}

The for loop is... well, here's the thing.  The threads are supposed to be taking turns counting the same numbers, right?  That is more clearly expressed in the code by having the two threads share a data structure

for(int i : this.numbersToCount){

Where possible, you should use functions to clarify the intent of complex boolean expressions:

if( isOdd(i))

The big problem I see is that you then duplicate all of your code to create Even.  Something has gone very badly wrong.  Let's generalize your loop, by replacing the thread mechanics with functions that express your intent.

synchronized(sharedObject){
    while(this.notFinished()) {
        this.waitForMyTurn();
        this.takeMyTurn();
        this.endMyTurn();
    }
}

Notice what this exposes - the monitor isn't "even or odd", it's a entity that is responsible for coordinating the activity of the two threads.  You've modeled its internals as true / false, but that's wrong -- it's really two different states that flip back and forth.

public class Monitor {

    private volatile State currentState;
    private final EnumMap<State,State> transitions;

    public boolean isInState(State state) {
       return currentState.equals(state);
    }

    public void changeState() {
        currentState = transitions.get(currentState);
    }

    public enum State {
        Odd, Even
    }
}

Or better:

public class Monitor<State> {

    private volatile State currentState;
    private final Map<State,State> transitions;

    public boolean isInState(State state) {
       return currentState.equals(state);
    }

    public void changeState() {
        currentState = transitions.get(currentState);
    }
}

If you imagine something like

interface Task {
    boolean isFinished();
    void doNext();
}

Then it should be clear that your current Even and Odd are both instances of the same class, with a different State and a different Task, which might look like

class CountingTask implements Task {
    private final int [] numbersToCount;
    private int nowAt;

    CountingTask(int [] numbersToCount, int startAt) {
        ...
    }

    boolean isFinished () {
        return nowAt >= numbersToCount.length;
    }

    void doTask () {
        System.out.println(numbersToCount[nowAt]);
        nowAt += 2;
    }
}


Find the index of a tuple in a list of tuples in Python


Avoid re-initialize values in javascript

You could remove the need for your xAxis variable through using the index when mapping:

vm.pnLreportingPlotData.push(plotModel.map(function (o, i) {
  return { x: i + 1, y: o.PnLreporting }
}

vm.var95Plotdata.push(plotModel.map(function (o, i) {
  return { x: i + 1, y: o.VaR95Total }
}

vm.var99PlotData.push(plotModel.map(function (o, i) {
  return { x: i + 1, y: o.VaR99Total }
}

Array.prototype.map provides three arguments, currentValue (o), index, and array (which isn't needed in our example)

N.B. you did not need to keep declaring xAxis after you had done so the first time (no need for the multiple var declarations, they could simply become xAxis = 1)

While the above answers your question of how to avoid redeclaring xAxis, I've added a few additional comments below:

Naming

You could possibly benefit from using more descriptive variable names. It is not immediately obvious what variables such as o represent. Likewise, i could be changed to index if you found it helped readability.

Consistency:

var95Plotdata uses lowercase 'd' for 'data', however var99PlotData capitializes it (is this a typo?)
VaR95Total capitalizes both 'V' and 'R' - can this be changed to be consistent with your view model or is this coming from an external api?

Extracting logic

Since the logic is almost identical besides property names, you could extract the logic if you wanted:

function getPlotData(property) {
  // Ideally renaming `o` to whatever it represents
  return plotModel.map(function (o, index) {
    return { x: index + 1, y: o[property] }
  }))
}

vm.pnLreportingPlotData.push(getPlotData('PnLreporting'))
vm.var95Plotdata.push(getPlotData('vaR95Total'))
vm.var99PlotData.push(getPlotData('VaR99Total'))


DailyProgrammer Balancing Words Challenge

General Coding Advice

Do not use using namespace std.  See here and here.
Wrap your logic into a function.  This typically allows for better control flow.

// Returns the position that the word balances
// Returns 0 if the word does not balance (since words can never balance at 0)
int balances(const std::string& word)
{
    // Some loop
        // If it balances return the position
        // Also note that a word can only balance in one position
    // End of loop
    // Return 0 since it does not balance
}

for (string&& word : input) {
    int pos = balances(word);
    if(pos)
    {
        // print something
    }
    else
    {
        // print something else
    }
}

Personally I would prefer using unsigned int or better yet size_t to index the string but you can run into problems using unsigned int so you can stick to int for now.

Faster stop condition

leftWeight is monotically increasing while rightWeight is monotonically decreasing.  So a faster stop condition is leftWeight > rightWeight

Algorithm hint

You do not need to recompute everything each iteration.

Note that \$A\$, \$B\$, \$C\$, ... arbitrary values here and not letters in the alphabet.

Assume we have some number \$N_i = 5A + 4B + 3C + 2D + E\$ and we desire some number \$N_{i+1} = 4A + 3B + 2C + D\$.

It sure would be nice if we had some number \$M_i = A + B + C + D + E\$ so that \$N_{i+1} = N_i - M_i\$

But then how do we update \$M_i\$ to \$M_{i+1}\$ so that \$N_{i+2} = 3A + 2B + C = N_{i+1} - M_{i+1}\$?

And if for some reason we had \$N_{i+1}\$, \$M_{i+1}\$, and some new value \$E\$ could we use these to compute \$N_i\$?

If we could do all of the above \$O(1)\$ then our overall algorithm would be \$O(n)\$ instead of the \$O(n^2)\$ solution where you recalculate everything.


Advice 1: getting the job done the C++ way

You can check whether the input string is a palindrome in one line:

bool is_palindrome(std::string& text) {
    return std::equal(text.cbegin(), text.cend(), text.rbegin());
}

For Incomputable has spoken: You can make the above run in the worst case faster by the factor of two:

bool is_palindrome(std::string& text) {
    return std::equal(text.cbegin(),
                      std::prev(text.cend(), text.length() / 2),
                      text.rbegin());
}

For Deduplicator has spoken: In is_palindrome, change std::string& to std::string const&; this will guarantee that the input string is not modified.

Advice 2

Whatever you implementation of the palindrome checker is, have a dedicated method that does not output the result to std::cout, but rather returns a boolean indicating whether the input string is a palindrome or not.

Advice 3

void main() does not compile on modern Xcode; change to int main().

Advice 4

Please avoid

using namespace std;

since it pollutes your namespace by importing quite a lot of identifiers/type names.

Advice 5

cout << "Your string is: "; cout << str << endl;

You can write:

cout << "Your string is: " << str << endl;

Alternative implementation

I had this in mind:

#include <algorithm>
#include <iostream>
#include <string>

bool is_palindrome(std::string& text) {
    return std::equal(text.cbegin(), text.cend(), text.rbegin());
}

using std::cin;
using std::cout;
using std::getline;
using std::string;

int main()
{
    string str;
    cout << "Enter a string: ";
    getline(cin, str);
    cout << "Your string is: " << str << "\n";
    cout << "Palindrome: " << std::boolalpha << is_palindrome(str) << "\n";
}


Update only modified fields in Entity Framework

Why bother checking if the value/property has been changed? You are just adding additional complexity for no reason. Sure, it might be slightly! faster to only update modified values, but in return you are adding an overhead to keep track of the modified values, which will diminish whatever performance boost you got.

Just invoke Update on the entire object... All values that has not been changed will remain the same and the values that has been modified will, well, update.

If it's speed you're looking for you are most likely looking at the wrong place to squeeze ms from.


Shift and merge numbers as in 2048 game code

With both scoring and merging

Oops! I did indeed neglect to include merging. This is my mistake; I'm not a big fan of returning values via mutable parameters, so I think my brain shut off. Fortunately, while working on the merging logic, I made the scoring logic shorter.

// Comment #1
fn compress_zeroes(line: [u8, ..4]) -> (u8, u8, u8, u8) {
    let mut nums: Vec<_> = line.iter().map(|x| *x).filter(|x| *x != 0).collect();
    nums.resize(4, 0);
    (nums[0], nums[1], nums[2], nums[3])
}

// Comment #2
fn score_line(line: [u8, ..4]) -> u64 {
    let line = compress_zeroes(line);
    let line = (line.0 as u64, line.1 as u64, line.2 as u64, line.3 as u64);

    let r = match line {
        (a, b, c, d) if a == b && c == d && a != 0 && c != 0 => a+1 + c+1,
        (a, b, _, _) if a == b && a != 0                     => a+1,
        (_, a, b, _) if a == b && a != 0                     => a+1,
        (_, _, a, b) if a == b && a != 0                     => a+1,
        _                                                    => 0,
    };

    (r as f32 * SCORE_MERGE_FACTOR).round() as u64
}

fn squish_line(line: [u8, ..4]) -> [u8, ..4] {
    let line = compress_zeroes(line);

    // Comment #3
    match line {
        (a, b, c, d) if a == b && c == d && a != 0 && c != 0 => [a+1, c+1, 0,   0],
        (a, b, c, d) if a == b && a != 0                     => [a+1, c,   d,   0],
        (a, b, c, d) if b == c && b != 0                     => [a,   b+1, d,   0],
        (a, b, c, d) if c == d && c != 0                     => [a,   b,   c+1, 0],
        (a, b, c, d)                                         => [a,   b,   c,   d],
    }
}

This is probably the best enhancement. Since we don't care about zero values, we can simply remove all the zeroes and then add them back at the end of the array. This removes 3 cases from each match statement!
Conceptually unchanged from the earlier solution, just smaller due to being able to ignore zeroes.
Similar to score_line, we use pattern matching to combine consecutive values that are the same (and non-zero). In this case, we need to track all of the values, so I changed up the naming a bit to leave each letter in the same position.

I definitely prefer having two distinct methods here. In the original, the method is called score_line, but it should actually be called score_and_merge_line. I think that added to my original confusion.

Original answer

There's a lot of code in the original to move things around, just to ignore all that and count how many squares would be merged. I made use of Rust's pattern matching to express the small number of interesting cases that exist in a given line.

fn score_line(line: [u8, ..4]) -> u64 {
    // Comment #1
    let a0 = line[0] as u64;
    let a1 = line[1] as u64;
    let a2 = line[2] as u64;
    let a3 = line[3] as u64;

    // Comment #2
    let r = match (a0, a1, a2, a3) {
        (a, b, c, d) if a == b && c == d && a != 0 && c != 0 => a+1 + c+1,
        (a, b, _, _) if a == b && a != 0 => a+1,
        (_, a, b, _) if a == b && a != 0 => a+1,
        (_, _, a, b) if a == b && a != 0 => a+1,
        (a, 0, b, _) if a == b && a != 0 => a+1, // Comment #3
        (a, 0, 0, b) if a == b && a != 0 => a+1,
        (_, a, 0, b) if a == b && a != 0 => a+1,
        _ => 0, // Comment #4
    };

    (r as f32 * SCORE_MERGE_FACTOR).round() as u64
}

We start by unpacking each of the 8-bit numbers and casting them to a larger type. When we add two squares together, it's possible to require more than 8 bits. A u16 would suffice here, but the original method returned a u64, so we will stick with that.
We've unpacked the array to separate variables, but we actually want to pattern match against all of them at once. We create a tuple to cram them all back together and match on that.
All the pattern match lines are similar, but this one has the most variety. a and b will be bound to the value of the number in the respective position in the tuple. _ means that we don't care about the value in that position, and 0 requires the literal value 0 in that position. We also use a pattern guard (if a == b...) to further restrict the pattern match to pairs of numbers that equal each other. The expression after the => will be the result of the match if that particular branch is chosen.
This is the catch-all branch, which is taken when none of the above branches are picked.

I think that this solution is improved from the original because:

Removed unneeded mutability. No variables are required to be mutated after they are created, which helps me as a programmer reason about the code better.
Removed unused functionality. The function is designed to return the score, it doesn't need to actually move numbers around into the future positions. This relates to the lack of mutability.
Pattern matching replaces what could be a complicated series of if-else checks with something that has more concise and has a visual component. The pattern matching looks like a line of numbers would.
There's no loops or nested loops. Again this helps me as a programmer see the logic clearer.

I tried to stay close to the original code in terms of types, but I would probably make a few more changes if I kept going:

Make a Line type or type alias.
Make a newtype or type alias to indicate that the u8 is to be interpreted as a power of two.
Use Option for missing values, instead of zero.
Remove the 1.2x factor, since I don't currently see the benefit of multiplying every value. If everything has the same weight, it doesn't affect anything.

Additionally, I believe there is a bug in the original code when two adjacent cells have 255. I found this because I compared this code against the original for every possible value. This only took a few minutes, so I believe my code is performant enough for the simple case.


I need code review on using singleton to access local database

Based on your provided code, this is the correct way to create a singleton object.

In such, here's a reference link from Matt Gallow's site showing the same singleton setup as you're doing.

However, there is not enough information provided to determine the cause of your performance issues (whether or not caused by accessing the database). In general, writing efficient database code is hard, which is why Core Data exists.

You might consider looking into Core Data to see if this will work better for your app or perhaps creating a question on StackOverflow describing the issue you're seeing in more detail and asking for help on how to implement what you're trying to do.


It will be a bit shorter and simpler without the duplicated else blocks:

if (plusZoomPercentage > 0)
{
    /*Check for overflow or otherwise going out of bounds*/
    if (newZoomPercentage > 100 || newZoomPercentage < currentZoomPercentage)
    {
        newZoomPercentage = 100;
    }
}
else if (newZoomPercentage > currentZoomPercentage)
{
    newZoomPercentage = 0;
}
zoomToPercentage(newZoomPercentage);
return AER_REQ_RESPONSE_READY;


Keras stacked LSTM model for multiclass classification

If I understand your problem, your samples are 150-dimensional vectors
which is to be classified into one of four categories. If so, an LSTM
architecture is a very poor fit because there are no relations
between your samples. I.e what is in the n:th sample doesn't impact
what is in the n + 1:th sample.

Try something like this instead:

from keras.layers import Dense
from keras.models import Sequential
from keras.utils import to_categorical
import numpy as np

n = 38607
d = 150
k = 4

# Generate data
X = np.random.randn(n, d)
Y = to_categorical(np.random.randint(k, size = n), k)

model = Sequential()
model.add(Dense(128, input_dim = d, activation = 'relu'))
model.add(Dense(64, activation = 'relu'))
model.add(Dense(4, activation = 'softmax'))
model.compile(
    loss = 'binary_crossentropy',
    optimizer='adam', metrics=['accuracy'])
model.summary()

model.fit(X, Y, epochs = 100, batch_size = 128, verbose = 1)

I haven't used any test data so the model quickly overfits (accuracy >
25% implies overfitting). Which brings me to my next point. On your
graphs, you get better performance on the test data than on the
training data which is very suspect. I suggest you try and train your
network without any dropout first to see if it behaves as expected
before adding it back.


In first for loop we can stop when i*i>=n. As we need two different divisors, smallest must be less than Math.sqrt(n)
Second for loop looks like simple integer division.

Whole code is equivalent to this:

    private static int[] provideFactorsSmallest_v(int n) {
        for (int firstTerm = 2; firstTerm*firstTerm < n; firstTerm++) {
            if (n % firstTerm == 0) {
                int secondTerm = n / firstTerm;
                return new int[]{
                        (firstTerm + secondTerm) * firstTerm,
                        (firstTerm + secondTerm) * secondTerm
                };
            }
        }
        return null;
    }