Fast comparison of molecular structures and deleting duplicates

I probably get what your friend meant when they said that your code wasn't particularly well-structured: your program has a main double for loop and ought to be broken into more small functions with names that could be understood at first glance (at least for somebody fluent in the application domain). Putting that aside, there are many small things that could be improved:

Iteration over numpy arrays is slow. While numpy arrays can help to write much faster code than with regular Python lists, iterating over them is slower than iterating over a regular Python list. The trick to numpy arrays is to use functions designed for them when possible, time, convert them to Python lists when you really need to iterate over them, time again, read the documentation to find the most useful functions from numpy and scipy, then time again and in the end you will know which solution is the fastest. Agreed, that's not the nicest thing in the world to do.

I didn't time your code, but I guess that it would be more performant if you used regular Python lists while you read files, still use Python lists in drmsd since you only iterate over the arrays, but use numpy arrays in ecd since you have to use np.linalg.norm.
Instead of manually calling close on file instances, use with instead:

with open('some_file') as f:
    # do things with f
# Here, f is automagically closed

The file will be closed when you leave the scope of the with. That ensures that your file is always closed, even if an exception is thrown while you are doing things with it. It prevents resource leaks without having to use cumbersome try/catch/finally clauses.
Instead of putting your main code directly in the file, try to do this:

if __name__ == '__main__':
    # Here your main code

It will ensure that your main is only called if the file containing it is the one launched by the Python interpreter. That, you can reuse its functions from other modules without risking to launch the main code when you don't want to. This feature is generally used to provide example code in modules.
You seem to be using Python 2.7. If this is the case, then you can turn your range into xrange. While range produces a full list, xrange only produces a lightweight generator object that will produce a return a new integer at every iteration. It is much more memory efficient than using range for the purpose of iterating.


Check bitstamp.net exchange rate, compare it with previous rate

Id make your code more functional (if your not going to use OOP) the fact that this code is slow is probably your internet connection (as mentioned in the comments)

First as the api is returning common keys I would just make the rounding & ternary operator as one function you can pass a response to,

Also because you aren't using full names and just short codes the whole code works in a loop, this way you can just add more coin short codes into the $coinsToFetch array

<?php
function fetchAndDecodeData($url)
{
  return json_decode(@file_get_contents($url), true);
}

function getValuesFromBinanceData($data)
{
  return [
    "priceChange"=>$data["priceChange"] > 0 ? "up" : "down",
    "lastPrice"=>round($data["lastPrice"], 1)
  ];
}

$coinsToFetch = ["BTC", "LTC"];

foreach ($coinsToFetch as $coin) {
  $coinData = fetchAndDecodeData('https://api.binance.com/api/v1/ticker/24hr?symbol=' . $coin . 'USDT');
  $data = getValuesFromBinanceData($coinData);
  echo "<h2> $coin " . $data['lastPrice'] . $data['priceChange'] . "</h2>";
}

To address the issue of the speed of your script in relation to your internet you could cache the results (redis) or store them in database (mysql) this would allow you to do some sort of code like this (psudeo code)

If its less than 5 minutes sinse the cache
  Load the data from the cache
Else
  Load from binance api

If you are going to use the caching / storage I would convert this into two scripts;

That runs as cron job to populate cache / storage every x number of minutes
To display the data


The hashCode method can be simplified down to (just simply restructuring your logic and removing redundancy):

@Override
public int hashCode() {
    return id == null ? 0 : id.hashCode();
}

The equals method is a bit more complicated. Your code does appear to keep the hashCode/equals contract, so that is good, but, sometimes there are better ways than others to test for things. For example, often when you override hashCode and equals it is because these instances are used in a Set or Map. A shortcut is to often check for identity before checking for equality.... i.e. if (other == this) return true; This can (often/sometimes) save a lot of internal processing to resolve equality.

I have a template I tend to use for equals(...) and it goes like this:

@Override
public boolean equals(final Object other) {
    if (this == other) {
        // nothing declared for simplest case.
        return true;
    }
    if (!(other instanceof MyClass)) {
        // other is null or not one of us.....
        return false;
    }
    // Code appropriate for **your** class goes here
    final Myclass their = (MyClass)other;
    if (this.id == their.id) {
        // identity goes first.
        // this works for both values null too.
        return true;
    }
    if (this.id == null) {
        // we are null, they are not.
        return false;
    }
    return id.equals(their.id);
}

This method is longer than yours, but it makes the logic clear.

When you have to conform to 'bigger' contracts like the hashCode/equals contract (or the Comparable contract), it is often better to make the logic progression very obvious....


Thread safe enqueue and dequeue method in Queue

It is apparent that you have put some thought in to this implementation, and apart from the not-synchronized isEmpty() method, it all looks functional.

I have some minor nit-picks though, and please bear in mind that these are just my opinion...

I prefer to have the notifyAll method to be the last thing in a synchronized block, where possible... You have:

....
  }
  notifyAll();
  size++;
}

I would always put the notifyAll() after the size++. This does not make a functional difference to the program, but it makes the logic more apparent (that size++ will happen before any other thread can read the size value):

....
  }
  size++;
  notifyAll();
}

As I say, this does not affect the logic of the code, but it does affect the readability.

A second nit-pick I have is that you 'leak' logic from your synchronized blocks. What I mean by this, is that you should try to avoid any method calls from inside the block. When you call other methods from a block it becomes much easier to introduce synchronization bugs and deadlocks. Additionally, the methods you call are also synchronized, so you introduce a readability/complexity (and perhaps even a slight performance) issue by having nested synchronization calls.

EDIT: I would add another nit-pick here which is you do not use 'final' enough. 'final' is a good hint to the optimizer in Java and it allows it to make smarter choices when inlining and otherwise rearranging/compiling your code

Finally, I would choose just one mechanism to manage the empty/full condition of the queue. Currently you have a few: isEmpty depends on first == null; isFull() depends on size == MAX_QUEUE_SIZE; in your enqueue(...) you test for isFull() and isEmpty(); and in your dequeue() you test for 0 == size() and isEmpty(). I would reduce all of these to tests on size only. That way there is only one condition that you need to mentally track when you read the code.

So, if it were me, I would replace your code as follows:

public synchronized boolean isEmpty() { return size == 0; } // replace first == null
public synchronized boolean isFull()  { return size == MAX_QUEUE_SIZE; } // replace size()

public synchronized void enqueue(final T item) throws InterruptedException { // add final
  while (size == MAX_QUEUE_SIZE) {  // replace isFull() call.
    wait();
  }

  final Node oldLast = last; // add final
  last = new Node();
  last.item = item;
  last.next = null;

  if (size == 0) { // remove isEmpty()
    first = last;
  } else {
    oldLast.next = last;
  }
  size++; // move before notifyAll()
  notifyAll();
}

public synchronized T dequeue() throws InterruptedException {
  while (size == 0) { // remove size() call.
    wait();
  }

  final T item = first.item; // add final
  first = first.next;

  size--; // move size-- up a bit to make the logic below more transparent
  if (size == 0) { // remove isEmpty() call
      last = null;
  }
  notifyAll();
  return item;
}

Finally, if it really was me, I would recommend that you consider ReentrantLocks and Conditions to manage the queue.... There's a good example (almost identical to this exact problem) of how to do it in the JavaDoc.


You can use querySelectorAll how @Pavlo says in his comment. It would work:


Perl script to rename files in a directory tree

It seems correct to me except these lines:

$s1 =~ s/\.cxx/\.cpp/g;
$s1 =~ s/\.hxx/\.h/g;
$s1 =~ s/\.(cxx|hxx)//g;

There're no needs to do the substitution g lobal and also you need to anchor the regex at the end:

$s1 =~ s/\.cxx$/.cpp/;
$s1 =~ s/\.hxx$/.h/;
$s1 =~ s/\.(cxx|hxx)$//;


This is a bad habbit stop doing it.

using namespace std;

Once your programs are more than 10 lines long it starts adding complexity including the whole namespace. SO best not to do it. Get into the habit of not using now otherwise breaking the habit is hard latter.

Don't put bad comments in you code (in fact try not to put comments). A comment should explain what you are trying to achieve (or potentially why) (NOT HOW). The code explains how so don't duplicate the code in comments. The worst thing to find in code is comments that don't match the code.

char a2z[26]={0};//Hash

This is not a hash. A hash has a very specific meaning and this is not what you are doing.

Prefer to use [] when declaring the array. This means the compiler will try and establish the length of the array for you.

char input[100] = "abcbbbcdegh";//sample input, only small case english alphabets

While we are here. Stop using C stuff in C++. Learn to use C++ constructs and don't mix the languages up. Another bad habbit you should fall into.

int n = strlen(input);

C++ has its own string class.

std::string  input("abcbbbddddd");
// size is input.size()

Learn how to use iterators.

for(int i=0; i<n; ++i)

It will allow you to be more versatile with your code. Potentially allowing your code to work with multiple container types (not just string). But more importantly it is the first step to using the standard algorithms.

You are making the assumption that your input only contains lower case letters. You should always code defensively. You MUST validate your input.


Ted's answer is quite readable to me.

You could use some to detect if you need to submit changes as that is semantically closer to what you are doing:

if (['activeBaseNode', 'filterOID', 'quickFilterRequest']
    .some(prop => state[prop] !== props[prop])

It's perhaps nicer to reverse the logic with every and early exit, then extract all the properties only when you need them. Here I'm doing it with a function, avoiding defining three consts:

static getDerivedStateFromProps(props, state) {
  if (['activeBaseNode', 'filterOID', 'quickFilterRequest']
    .every(prop => state[prop] === props[prop]) return null

  return (({activeBaseNode, filterOID, quickFilterRequest}) =>
         ( {activeBaseNode, filterOID, quickFilterRequest}))(props)

That's cryptic and short approach.

I don't really like that the names of the properties are repeated three times in all the solutions. To avoid that, a reduce can be used to build the properties that need to be updated:

const toUpdate = ['activeBaseNode', 'filterOID', 'quickFilterRequest']
  .find(prop => state[prop] !== props[prop])
  .reduce((m,k) => m[k] = props[k], {})
return Object.keys(toUpdate).length == 0 ? null : toUpdate

Once you get used to it, I think that's the clearest. It's got the essence of the problem and nothing more: the names of the properties, that the state != the props, and that you return null if nothing is changing.


Search script for autocomplete suggestions

Upgrading PHP

Upgrade your PHP version. After reading this code I determined that you are running at the most 4.0.6. key_exists() was replaced with array_key_exists() in 4.1.1, and this was some time ago. An old version of PHP runs the risk of having security issues, and you won't be able to get much help because everyone is using the newer version. Some of these suggestions might still work, but others may not be supported in your version, such as this first one.

REQUEST vs. POST/GET

You should stop using $_REQUEST. It is insecure, being that you are running an older version of PHP this is understandable, but if you upgrade, you should definitely update this as well. If you know where the information is coming from, and you should, then you should just use that array. For example, if it is coming from POST use the $_POST array, if it is coming from GET use the $_GET array, etc...

switch vs. if/else

Think of using a switch. It is faster than if/else statements and, in my opinion, cleaner looking and more legible.

$searchFrom = array(
    'tuotesarjat' => array('sarjanimi', 'laattatyyppi'),
    'tuotteet'    => array('varikategoria1', 'varikategoria2', 'pinta', 'hakupinta')
);

if( isset( $_REQUEST[ 'type' ] ) {
    $type = $_REQUEST[ 'type' ];
    switch( $type ) {
        case 'admin':
            $searchFrom = array(
                'tuotesarjat' => array('sarjanimi', 'laattatyyppi'),
                'tuotteet'    => array('tuotenumero', 'kuvaus1', 'varikategoria1', 'varikategoria2', 'pinta', 'hakupinta')
            );
        break;
        //Use a case for each "type", exclude customer as it was defined above as a default
    }
}

Foreach Keys

No need to return $key in your foreach loop, especially since you're not using it. Just remove $key => from the declaration. You can also just use array_filter() after exploding it into an array to remove any empty array members. This will relieve some overhead and is cleaner. Also, since you probably don't want to search for the same term twice you can use array_unique() to remove duplicates.

Repetition

Try to make it so that you repeat yourself as little as possible. This is so that if you ever need to change something, you'll only have to do so once. So...

$term .= '%';
if (strlen($term) > 2) { $term = "%$term"; }

$sql .= "LIKE '$term' $andWhere GROUP BY $column";

You'll also find, if you upgrade your PHP version, that mysql() is being deprecated. mysqli() and pdo() are now the preferred methods.

Error Suppressors

DON'T USE ERROR SUPPRESSORS. This is a sign of bad code. If there is an error fix it. If you are doing it just so you don't have to type a couple extra lines, don't. Always ensure your code works 100%. The error suppressor should only be used during debugging.

Incrementing

There's got to be some better way to increment the "found" array... I thought of using a ternary operator, but that got a little messy, and at the moment, I can't think of anything else... I'll update this if I think of anything...

Question

How are there empty strings in $found?

MAX_LIVESEARCH_SUGGESTIONS

Not sure what the MAX_LIVESEARCH_SUGGESTIONS is, but would it not make more sense to perform this before creating the $found array?

$length = count( $terms );
while ( $length > MAX_LIVESEARCH_SUGGESTIONS) { array_pop( $terms ); }

Notice I moved count() out of the loop. With it in the loop, it will run it every time, which means more overhead. Remove it from the loop to remove the overhead. I'm having difficulties following the program, so unless $found ends up with more elements than $terms the above should work. If there are more, then you should limit how many are recorded by breaking out of the loops once that limit is reached.

$length = count( $found );
if( $length == MAX_LIVESEARCH_SUGGESTIONS ) { break 4; } //I think its 4... might be 3...
//perform actions to set $found here

JSON

Updating your PHP will also mean that you can use the JSON library that is now standard instead of needing to recreate it.

Hope this helps!


How to increase the efficiency of DLA algorithm?

You might consider to use a tuple of directions, something like this:

directions = ((1,0), (0,1), (-1,0), (0,-1))

In your while loop, you can do:

direction = directions[np.random.randint(4)]
A += direction[0]
B += direction[1]

If you switch from tuple to numpy arrays (direction and your current position), you could also use numpy.add which might be faster. If this really improve performence you have to measure. To do this, you might use a seed for your random generator, to get reproducible code.

The border check might be faster with NumPy too, using abslolut - if its ok, to change the behavior that way (your praticles wont "clue" at the border, but bounce back).

Precalculation

You could go a step further, by precalculating all posible paths for several steps.

# each direction has same propability - making things easier
# you could simply create a list with an entry for each path of a tree diagram,
# as each path has the same probability
def add_one_step(steps: list):
    random_step = [(1,0), (0,1), (-1,0), (0,-1)]
    if steps == []:
        return random_step
    result = []
    for i, steps_entry in enumerate(steps):
        for step in random_step:
            a = steps_entry[0]+step[0]
            b = steps_entry[1]+step[1]
            result.append((a, b))
    return result

def get_multiple_steps(n=5):
    final_directions = []
    while n > 0:
        final_directions = add_one_step(final_directions)
        n -= 1
    return final_directions

# be careful about how many steps to precalculate! The list lengths go with 4**n
precalculated_steps = []
for i in range(12):
    precalculated_steps.append(get_multiple_steps(i))

You could use such precalculated values, to do several steps in one go.

n = 10
direction = precalculated_steps[n][np.random.randint(4**n)]
A += direction[0]
B += direction[1]

Thats the most simple aproach. If you want to go to higher n values, you have to think about how to reduce precalculation time (this is just a simple brute force calculation of all paths), and how to safe each result only once (and how many times it occurs).

The tricky part is your border and the stick. You have to chose a fitting matrix size depending on your current distance to border and stick.

Outlook - binomial distribution and minimal distance matrix

If you understood the above and really want to speed up your code, I would suggest to look at:

Binomial distribution

you can split stepping in two seperate movements (x and y) - than your radom walk over n steps is simply a binominal distribution
with this, you could precalc a quadratic matrix for each n = 1 .. 249 with the probability to reach a  position

precalc minimal distance from sticking and border for each position; you have to update this only when a particle finally sticks - and you only need to check for each position, if this stick-position is closer than the previous value; This matrix is used to get the max number of steps you can do in one go.

By using the minimal distance matrix to determine the maximal number of steps allowed to do, and then using the fitting precalculated stepping matrix the solution should be ready in minutes or seconds. If you can be more lax with the border condition, it would speed up the algorithm even more.

Further disscussion and code example can be found in another question.

Errors

After understanding what your code is intended to do, I think your for-loop over all paricles is broken.

First:

pos = np.random.randint(0, len(arr))  # will set pos to 0 or 1
# should be:
pos = np.random.randint(0, arr[0])
# or better
random_pos_x = np.random.randint(0, arr[0])
random_pos_y = np.random.randint(0, arr[1])

Also, you only start particles at the upper and left border?

walk(pos,-1,canvas)  # why -1?
...
walk(-1,pos,canvas)  # why -1?

# should be:
walk(random_pos_x ,arr[1]-1, canvas)
walk(arr[0]-1, random_pos_y, canvas)

The name arr is an example for a bad name, because it hints to "array" (thus it was hard to spot the mistake above). Better would be samething like area. Or use h and w (personally I would prefer to name thus as height and width; thats easier to read in most cases)


C++ simple password-protected console app

Using namespace std isn't a good practice in header files, where your program should at least partially reside, because you introduce potential name conflicts. So don't do that, and prefix the names you're importing with std::, you'll get used to it in no time.
Your function keyExists can be improved upon. First, its name is not the best you could have found, because it suggests you're looking for the existence of a particular key, whereas what you really want to know if the program has been launched before. So is_first_use, or is_first_visit as an analogy to a website, would tell more. Besides, it doesn't have to be that verbose:

Original version

bool keyExists() {
    bool keyExists = false; // the homonymy is a bad idea
    ifstream inFile("key.txt");

    if (inFile) {
        keyExists = true; //
    }

    return keyExists;
}

first trimming

bool keyExists() {
    bool keyExists = false;
    ifstream inFile("key.txt");

    keyExists = inFile; // because streams can be converted to bool as you know

    return keyExists;
}

second trimming

bool keyExists() {
    ifstream inFile("key.txt");
    return inFile; // you specified the return type, so the conversion will occur
}

third trimming

bool keyExists() {
    return ifstream("key.txt"); // no need for a named object
}

So do you really need a function? It depends. If you want to let your program evolve from here, it's a good idea to keep the function, and implement a more viable test at a later point without disturbing the rest of your code. Otherwise it isn't worth the burden of finding a name for it.

Your function isMatch suffers from the same issue.

original version

bool isMatch(string key, string confirmKey) {

    bool match = false;
    if (key == confirmKey) {
        match = true;
    }

    return match;
}

suggested implementation

bool isMatch(const string& key, const string& confirmKey) { // pass it by reference to avoid a potentially costly copy
    return key == confirmKey; // no need to store that in a `bool` before returning it
}

Then again I'm not sure it needs a function of its own...

What's a valid key?

It might be a design choice, but it's very rare to allow for tabs, spaces and such inside a password. Is this really what you want? Is it compatible with every way to store passwords that you can think of? How would you constrain the choice of a password?


Set-uid root program that runs a program as the user "restrict"

Stay away from variable length arrays. First, they are optional in C11  (in C99 they were mandatory). Second, there is no way to detect allocation failure. A malicious user may invoke the program with a command line long enough to cause stack overflow.
Why sudo? You are root already, so you may set the user and group ID directly.


Powershell cmdlet authenticating to Aerohive API

You are writing a powershell commandlet... are you sure you want to hardcode the url?

client.BaseUrl = new Uri("very.long.url/to/authenticate/against");

I think it would be better to provide a parameter for this one too. At least make it optional with a default value if you don't want to type it everythime but hardcoding it - well, I woudn't.

It doesn't take long and you'll find another use for it but then you'll say if I only made a parameter for this :-)


How about this for some madness:

function weekday($a, $b){global $days; return "$a $b".join(" $b", $days);};
$out = explode(' ', trim(array_reduce($week_no, 'weekday')));

(Urm, yes well maybe not...)

Sometimes to attain elegance you have to change the way your code is working, i.e. what are your reasons behind generating such an odd array? From my experience something like this would be more useful:

$out = array_fill(reset($week_no),count($week_no),$days);

Which generates the following:

Array
(
    [2] => Array
        (
            [0] => TU
            [1] => WE
            [2] => TH
        )

    [3] => Array
        (
            [0] => TU
            [1] => WE
            [2] => TH
        )

    [4] => Array
        (
            [0] => TU
            [1] => WE
            [2] => TH
        )

)

The above would be much easier to traverse and would be more extendable.

In sticking with your question however the foreach method is by far the best as stated in the comments... but it was fun trying odd work arounds ;) Am surprised that there is no php function to directly prepend or append array items with another set of array items... probably because it's quite easy and fast to do so with a few foreachs.


Checking proper English sentences of user's input with grammar using C++

You could learn how to use bison. It designed specifically for this.

Boiler plate for flex/bison project:

Eng.l

%option c++

%{
#define IN_EXPR_LEXER
#include "EngYac.hpp"
%}

SpaceChar     [ \t]
Space         {SpaceChar}+
SpaceTerm     {SpaceChar}|<<EOF>>
FullStop      {SpaceChar}\.{SpaceTerm}

%%

and                     {return yy::parser::token::Conjunction;}
or                      {return yy::parser::token::Conjunction;}
but                     {return yy::parser::token::Conjunction;}

the                     {return yy::parser::token::Article;}

birds                   {return yy::parser::token::Noun;}
fish                    {return yy::parser::token::Noun;}
C\+\+                   {return yy::parser::token::Noun;}

rules                   {return yy::parser::token::Verb;}
fly                     {return yy::parser::token::Verb;}
swim                    {return yy::parser::token::Verb;}

{FullStop}              {return yy::parser::token::FullStop;}

{Space}                 {/*Ignore*/}
.                       {std::cerr << "Error unknown character\n";}

%%

int yyFlexLexer::yywrap(void)
{
    return 1;
}

int yylex(int* /*type*/, yyFlexLexer& lexer)
{
    return lexer.yylex();
}

Eng.y

%{
    #ifndef IN_EXPR_LEXER
    #include <FlexLexer.h>
    #endif
    int yylex(int* type, yyFlexLexer& lexer);
%}
%skeleton "lalr1.cc"
%defines
%parse-param {yyFlexLexer& lexer}
%lex-param   {yyFlexLexer& lexer}

%token      Noun
%token      Verb
%token      Article
%token      Conjunction
%token      FullStop

%%
Input:      Sentence FullStop

Sentence:   Noun Verb
        |   Article Noun Verb
        |   Sentence Conjunction Sentence

%%

void yy::parser::error(yy::location const&, std::string const& msg)
{
    std::cerr << "Error: " << msg << "\n";
}

main.cpp

#include <FlexLexer.h>
#include "EngYac.hpp"

int main()
{
    yyFlexLexer     lexer(&std::cin, &std::cout);
    yy::parser      parser(lexer);

    std::cout << (parser.parse() ? "FAIL" : "OK") << "\n";
}

Makefile

FLEX_SRC    = $(wildcard *.l)
BISON_SRC   = $(wildcard *.y)
FLEX_CPP    = $(patsubst %.l, %Lex.cpp, $(FLEX_SRC))
BISON_CPP   = $(patsubst %.y, %Yac.cpp, $(BISON_SRC))

SRC         = $(filter-out $(BISON_CPP), $(filter-out $(FLEX_CPP), $(wildcard *.cpp))) $(FLEX_CPP) $(BISON_CPP)
OBJ         = $(patsubst %.cpp,%.o,$(SRC))

eng:       $(OBJ)
    g++ -o eng -O3 -Wall -Wextra -Werror $(OBJ)

clean:
    rm EngLex.cpp EngYac.cpp EngYac.hpp location.hh position.hh stack.hh $(OBJ) expr

$(OBJ): $(FLEX_CPP) $(BISON_CPP)

%Lex.cpp:       %.l
    flex -o $*Lex.cpp $^

%Yac.cpp:       %.y
    bison -o $*Yac.cpp $^

Usage:

> make
> echo "birds rules but fish swim." | ./eng

OK
> echo "A test of English." | ./eng
A test of English
Error: syntax error
FAIL


There's a lot that can be improved in your code, especially if you are using C++. The more advanced features of C++ actually help you organize your code better, help you write less code to do what you want, and remove a lot of tedium that you find in C-style code.

Use proper names for variables and functions

Names should accurately reflect what the purpose is of a variable or a function. Of course, names should be concise, but apart from some well established conventions such as using i for a loop index, or x and y for coordinates, don't abbreviate names.
Here are some suggestions for improvements in your code:

Instead of circle(), name the function draw_circles().
Instead of square(), name the function print_result().
Instead of comp, name the variable angle, or perhaps phi.

Use '\n' instead of std::endl

std::endl is in fact equivalent to '\n', but in addition it also forces a flush of the output stream, which will slow down the output if it is used a lot.

Don't store unnecessary data

You have added a member variable circ to struct vec2. First of all, it is rather strange to name something vec2 when it contains 3 elements. But it is also unnecessary to store the radius of the circle in that struct at all.

Avoid using global variables

As already mentioned in the comments, don't use global variables if you can easily avoid them. Keep the array v inside main(), and pass it as a parameter to the other functions. It does not seem like a big deal now, but once your code grows you will appreciate keeping the global namespace tidy, and by passing references/pointers to your data to functions, you make those functions more reusable.

Stick to radians when possible

All trigonometric functions in <cmath> use radians, and any calculations done involving angles are usually simpler when done in radians than in degrees. Instead of:

int comp = j*30;
double rad = comp * (pi / 180);

Write this:

double angle = j * (2 * pi / 12);

Use a proper value for π

If your <cmath> library provides it, use M_PI for the value of π, or if not, write double pi = std::acos(-1) (see this question). Just don't make unnecessary approximations; it costs you nothing to do it properly, and you never know when an approximation might actually cause you problems.

Store the image, not the coordinates of the X'es.

Building a list of coordinates of where the X'es are, and then checking for each position in the output whether it matches the coordinates of one of the X'es is not efficient. This algorithm scales with O(width * height * number_of_Xes). You either want to write the X'es directly to the screen at the right position, or keep an array of width * height characters in memory, write the X'es to that array, and then at the end print the contents of that character array. Let's use the latter method, which brings us to:

Use a class to represent the output image

You are using C++, so make use of its features! Make a class that manages an ASCII-art image for you, like so:

#include <cassert>
#include <iostream>
#include <vector>

class Image {
    std::vector<char> pixels;

    public:
    const unsigned int width;
    const unsigned int height;

    // Create a w * h image, fill it with spaces
    Image(unsigned int w, unsigned int h):
            width(w), height(h), pixels(w * h, ' ') {}

    // Return a reference to the character at coordinates x, y
    char &at(unsigned int x, unsigned int y) {
        assert(x < width && y < height);
        return pixels[y * width + x];
    }

    // Print the image
    void print(std::ostream &out) {
        for (unsigned int y = 0; y < height; y++) {
            for (unsigned int x = 0; x < width; x++)
                out << at(x, y);
            out << '\n';
        }
    }
};

This class will store the characters that make up the image in a std::vector, which acts mostly like an array, but it has the nice property that it also allocates and cleans up memory for you behind the scenes.

The function at() will return a reference to the character in the vector at the given coordinates. You can use this to both read and write to that character.

The function print() takes a std::ostream reference as an argument, so you can have it print to any stream you want.

Using this class you can create an ASCII-art image, draw to it, and then print it like so:

int main() {
    // Create a 10x10 character image
    Image image(10, 10);

    // Draw a diagonal line
    for (int i = 0; i < 10; ++i)
        image.at(i, i) = '\\';

    // Print the results to the standard output
    image.print(std::cout);
}

Now you can rewrite your circle() function to write to a class Image, like so:

void draw_circle(Image &image, double radius, int steps) {
    static const double pi = std::acos(-1);

    for (int i = 0; i < steps; ++i) {
        double phi = i * (2 * pi / steps);
        double x = image.width / 2 + radius * cos(phi);
        double y = image.height / 2 + radius * sin(phi);
        image.at(x, y) = 'X';
    }
}

And then you can draw 3 circles with increasing radii like so:

int main() {
    Image image(40, 40);

    for (auto radius: {8, 12, 16})
        draw_circle(image, radius, 12);

    image.print(std::cout);
}

Of course, this will look like an ellipse on the screen, so you will have to find some way to correct the aspect ratio. You could create a draw_ellipse() function which takes two parameters for the radius, one for the horizontal direction and another for the vertical.


Optimizing simple prime number function test

You have both <cmath> and <math.h>, but you only need the former.  The latter is a C library.
You can have main() at the bottom, allowing you to eliminate the function prototype.
Do not use single-character variable names (except for simple loop counters, which can be simple).  They are hard to understand for others, and may even leave you confused in the future, especially if you expand on the program quite a bit.

As such, X should be renamed to something like number.
PrimeTest() should return bool, not int.  Returning an int is more common in C, but is not done in C++ (it's only done in main(), but it is special).  You'll then return either true or false and compare them as such.  This will also eliminate the need for Answer.
The final output can be simplified to a single-line ternary (?:) statement:

std::cout << X << " is " << ((PrimeTest(X)) ? "prime" : "NOT prime");

This is essentially a shorter way of writing an if/else statement, but is best done with simple cases such as this one.  If you'll ever need to expand on these conditions, then it would be better to go back to using curly braces.


Views Counter made in Python, Gevent and MongoDB

Instead of using a list comprehension, I would simply use a for-loop. It will do the exact same thing and save having to allocate a temporary list.

Also, in run_buffer_op, you first check the number of views. If that value isn't >5000 (almost a DBZ joke) then you sleep for 15min. Once it wakes up, you IMMEDIATELY flush_to_db no matter what. Based on your comments,  it seems you only want to flush_to_db if there are >5000 views. Thus, the flush_to_db call immediately after the gevent.sleep(900) seems a little redundant.


Huge Fibonacci modulo m optimization in Python 3

Fibonacci numbers grow exponentially. It means that the number of bits representing them grows linearly, and so does the complexity of computing nextFibonacci. It results in the overall quadratic complexity of your loop.

Good news is that you don't need to compute Fibonacci numbers at all. You only need to compute Pisano numbers. They obey the similar recurrence,

    p[n+1] = (p[n] + p[n-1]) % m

and by virtue of the modulo they never exceed m. A complexity of an individual addition stays constant, and the overall complexity becomes linear.

(Tiny additional: \$ (a + b)\ \textrm{mod}\ c\equiv a\ \textrm{mod}\ c\ + a\ \textrm{mod}\ c\$)


Recursively patching the properties of an ORM model and related models

If we assume that either for loop can come before or after the other for loop.
Then you should check if anhaenge is not None.
As your except TypeError is to guard against that.
You can then return from the function after you log the error, remove the except TypeError, remove the duplicate for loop,
and finally, put the duplicate for loop after the if, as you wish to perform the loop here on either branch. EG:

try:
    anhaenge = d['anhaenge']
except KeyError:
    self.logger.debug('anhaenge unchanged')
else:
    if anhaenge is not None:
        try:
            anhang = anhaenge['anhang']:
        except KeyError:
            self.logger.debug('anhaenge.anhang unchanged')
            return
        else:
            for anhang_ in anhang:
                with suppress(EmptyDict):
                    for record in Anhang.from_dict(anhang_, immobilie=self):
                        yield record, PatchMode.CREATE
    for record in self.anhang:
        yield (record, PatchMode.DELETE)

But this is not possible if the duplicated for loop has to occur before the other for loop.

Either way, I honestly don't think you're input is right.
Your input is strange, None is normally used to say it's not there, and so dict.get('a', None) is a common occurrence.
However your code performs differently whether it's None or not there.
And so I'd say you should restructure the input so you can use say:

anhang = d.get('anhaenge', {}).get('anhang', None)
if anhang:
    for record in self.anhang:
        yield (record, PatchMode.DELETE)

    for anhang_ in anhang:
        with suppress(EmptyDict):
            for record in Anhang.from_dict(
                    anhang_, immobilie=self):
                yield (record, PatchMode.CREATE)
else:
    self.logger.debug('anhaenge or anhaenge.anhang is unchanged')

If you can't adapt either of the above, then I'd say your code is good for your situation.


Extracting keywords from 3 billion CSV records

def fileparser_worker(filename, start, end, c):
    with open(filename) as inFile, open(outName + str(c),'w') as outFile:
            inFile.seek(start)
            #lines = inFile.readlines(end-start)

because readlines calls readline multiple times it can be replaced with
read.

If the text should be split by newline and each split line should be splitted by a tab character, there are two ways to do it depending on the input text.

    for title in (line.split('\t') for line inFile.read(end-start).splitlines()):

Here title is list of strings.

Another one is to call str.split() or str.split(None) in which case the string is split by white spaces (space, tab or newline), this is best if it's ok to split by space character or the text has no space character.

    for title in inFile.read(end-start).split():

Here the title is string.

If the read().split() becomes a memory hog, I think a generator will give
better result.

    #def get_title():
    #   yield next((line.split('\t') for line inFile.read(end-start).splitlines()))

    for title in (line.split('\t') for line inFile.read(end-start).splitlines()):
        try:
            keywords = rake.execute_rake(title[2])
        except:
            print('Index out of bound error due to NULL Values')
            continue

If we could build a sequence of strings out of keywords we can call
writelines straight.

        else:
            outFile.writelines((keyword[0] + '\n' for keyword in keywords))

~


Bugs

The loop header is wrong:

for(i=0;line[i]!=NULL;i++){

Here, you want to scan until you find a byte with ASCII value 0 (also called an ASCII NUL, and written in C as '\0').  However, you wrote NULL, which is supposed to represent a null pointer (a pointer to memory address 0).

In practice, you might get away with confounding the two, since they are both zero-like in nature, but it is not semantically correct.
The result of this comparison is thrown away:

pile[pilepointer]==NULL;

Did you intend to write pile[pilepointer] = NULL?  That wouldn't be quite right either, since you've confused NULL and '\0' again, as above.  In any case, that statement was unnecessary.
Stack underflow is possible.  If the input is simply ")", for example, you will immediately try to peek at the top of an empty stack (pile[-1]), resulting in out-of-bounds memory access.

Style

Flag variables suck; flag variables named flag are even worse.  At the least, rename it to something meaningful, such as mismatch_found.
When you do

flag = 1;
break;

You are breaking out of the case.  However, you need not bother analyzing the rest of the line.
Pushing and popping are clumsily expressed.  I would write:

char pile[10001];
int pile_size = 0;

To push:

pile[pile_size++] = '(';

To pop:

if (!pile_size || pile[--pile_size] != '(') {
    // Mismatch detected
}

You can coalesce all of the popping cases, if you push the expected matching closing delimiter when you encounter each opening delimiter.

for (char *c = line; *c && !mismatch_found; c++) {
    switch(*c) {
    case '(':
        pile[pile_size++] = ')';
        break;
    case '[':
        pile[pile_size++] = ']';
        break;
    case '{':
        pile[pile_size++] = '}';
        break;
    case ')':
    case ']':
    case '}':
        if (!pile_size || pile[--pile_size] != *c) {
            mismatch_found = 1;
        }
        break;
    }
}
printf((pile_size == 0 && !mismatch_found) ? "Yes\n" : "No\n");


To reduce the repetitions you could make use of lists by doing something like:

labels = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'stades']

rows = []
for label in labels:
    rows.append(e.loc[label])

# or even shorter with list comprehension
rows = [e.loc[label] for label in labels]

for row in rows:
    row.plot()

Edit: The labels list can also be used as first argument of the legend function to show the correct labels.


Critique sanitized user email PHP Script

Ok, this may come across as blunt or harsh, but IMO, that's what CodeReview has to do, as I explained earlier here.
So please, keep that in mind while reading this post.

Before I even start dealing with your code, I'd like to point out to you that you're using an unreliable, incomplete and misleading resource: w3schools. Sure, it may get some things right, but IMO, it's a misleading site. Many think the site is condoned, or even part of the W3C org. This is not the case, Please check the criticisms.
You are, of course, free to use w3schools, but be aware that it's not the best resource out there.

Is it secure?
No. I'd like to be kind about this, but that wouldn't help you. No, your code is still vulnerable to things like mail injection. I could easily copy paste some mail headers into your form and have your server, seemingly, forward a message sent yesterday by your rich, recently so tragically deceased alienated uncle in Barbados who left you his entire fortune.
I've included a link on mail injection in the bottom of this answer. This is an important issue that you need to address, still.

Now, the code:

I'll be going over your code block by block, sometimes even line-by-line:

<?

Don't use the short tag! Never. Period. It's not a lot of effort to write <?php instead, and it's far more reliable (<?php won't be confused with the odd <? xml...), and doesn't rely on the short-tags being enabled on your server.

$name = filter_var($_POST[name], FILTER_SANITIZE_STRING);
$email = filter_var($_POST[email], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST[phone], FILTER_SANITIZE_NUMBER_INT);
$usermessage = filter_var($_POST[message], FILTER_SANITIZE_STRING);
$businessmessage = filter_var($_POST[businessmessage], FILTER_SANITIZE_STRING);

Ok, this block is essentially doing the same thing several times, and suffers from the same issue throughout.
First off, when setting the error reporting level to the Correct debugging levels of E_STRICT | E_ALL, you'll see a ton of notices and warnings pop up:

PHP Notice: Use of undefined constant name - assumed 'name'

This means you forgot to quote the array keys, PHP will helpfully assume you meant 'name', but it will issue a notice. This makes your code look sloppy and amateurish. More over, it costs resources, slowing your code down.

PHP Notice:  Undefined index: name

If your script is being executed and none, or not all of the post parameters have been sent, you're still accessing those keys in the $_POST super global. At no point are you checking if there has been a POST request.
This can produce the notice above, for each time you access the POST array. Add some basic checks:

<?php//full tag
if (!$_POST) exit();//no post request, no magic!
$name = isset($_POST['name']) ? filter_var($_POST['name'], FILTER_SANITIZE_STRING) : null;

Don't "over-filter"!

Where your usage of filter_var($email, FILTER_VALIDATE_EMAIL) is to be commended, your code:

$phone = filter_var($_POST[phone], FILTER_SANITIZE_NUMBER_INT);

is not the best of ideas. Now I don't know how you get the input from the user, but if I were to punch in "+10800123456", I'd translate that + to double 0, to standardize the input.
Apart from that FILTER_SANITIZE_NUMBER_INT will clean up input like "123.313.456,1", removing the comma and dots, but it will leave the dashes and plusses in "+123-313+456-1" untouched. If I were you, I'd simply do something like:

if ($phone{0} == '+')
    $phone = '00'.$phone;
preg_replace('/[^0-9]+/','',$phone);

This expands a leading + to double zeroes and removes everything Except digits from the string. You can then easily check the length, to determine (roughly) the validity of the input. If it's 3 digits long, it probably isn't valid.

mail is good for testing, less so for production

Sure mail is easy (once you get your server settings worked out), and does what it says on the tin: it sends an email.
However, sometimes you might require an alt-body (text and HTML), sometimes you may want to add attachments. Writing those headers all the time is a bit of a faff, and has been done before. Good programmers are lazy: they won't bother writing code that exists, and is free to use. The PHPMailer class is in common usage and is very easy to set up, and quite versatile. Though, as you can see here, still somewhat open to mail injection.

In terms of security, PEAR::Mail is still the better option (though not in terms of clean code IMO). Read through the link, and learn about mail injection some more.


Don't do unnecessary work. You have the count variable, but you also have the dictionary which has a size() method. There's no need for the count.
Android supports Java-7 language features, use them. In this case, the try-with-resources would be your friend.
guess the size of the ArrayList that yoy may need. In this case, you should be a little generous, and say, pre-size it at 300,000 entries.
Android now supports (since KitKat) the diamond operator, there should be no need to declare the generic type of the ArrayList as <String>.
I actually like the while loop you have. It is my preferred way of doing line-by-line IO too.

Here's a 'cleaned up' version of your code:

private static final int INITIALSIZE = 300000;

....

long start = System.currentTimeMillis();
dictionary = new ArrayList<>(INITIALSIZE);
try (BufferedReader bufferedReader = new BufferedReader(
          new InputStreamReader(context.getAssets().open("words.txt")));) {

    String word;
    while((word = bufferedReader.readLine()) != null){
        dictionary.add(word);
    }
}catch(IOException e){
    e.printStackTrace();
}
long end = System.currentTimeMillis();
double t = ((end - start) / 1000.0);
System.out.println("Time to read database from file " + dictionary.size()
      + " items " + t + " seconds");

So, that's a "simplified" version, how to make it faster?

Well, there's a few things. First up, nothing can be for sure unless you test it, so, run some experiments. Things I would try:

Specify a buffer-size on the BufferedReader, something large like 1024 * 1024 (a megabyte). This should increase the size of IO's
The pre-sized ArrayList will help
Consider reading the whole data file in to a ByteArrayOutputStream, and then converting that in one go in to a large String, then splitting the string on line-breaks.

In essence, the larger the IO sizes the better, and the larger the cache sizes are, the better.


Warning

Enabling your compiler's warnings would tell you that c is unused.

Variable declarations

Following previous comments, I consider it good practice to declare your variable in the smallest possible scope and as late as possible. This makes things clearer (and prevent you from having unused variables). Using a "recent" version of C allows you to declare your variable in the for loop.

While/for

Your loop over Q is written as a while loop but could be written as a for loop.

i=i++

This is pretty weird code and according to my compiler warnings, might be undefined behavior.

  expand.c:10:25: warning: operation on ‘i’ may be undefined [-Wsequence-point]

More about this here.

Ascii values

You are mixing literal characters (like 'a') that are easy to understand and ascii values (like '97') for no obvious reason. I'd rather have the literal characters used everywhere. It makes clearer the fact that we try to convert chars to indices in once case and to numbers in the other case.

Using temp variable

It would probably make sense to use a temporary variable for str[i] in order to make things clearer.

Variable names

The variable names you are using could probably be improved. Among other things m seems pretty cryptic to me.

Draft

At this stage, I have the following code:

#include<stdio.h>

int main()
{
    int ar[26] = {0};
    char str[10000];
    scanf("%10000[^\n]", str);

    int last_char = 0;
    int nb_occ = 0;

    for(int i=0;str[i];i=i++)
    {
        int c = str[i];
        if((c>='a' && c<='z'))
        {
            ar[last_char] += nb_occ;
            last_char = c-'a';
            nb_occ=0;
        }
        else
        {
            int chint=(int)c-'0';
            nb_occ=(nb_occ*10)+chint;
        }
    }
    ar[last_char] += nb_occ;

    int Q = 0;
    scanf("%d",&Q);
    while(Q--)
    {
        int K = 0;
        scanf("%d",&K);
        for(int i = 0; i<26; i++)
        {
            K = K - ar[i];
            if(K<=0)
            {
                printf("%c\n", (i+97));
                break;
            }
        }
        if(K>0)
            printf("-1\n");
    }

    return 0;
}

Code organisation

On this kind of task, it is usually worth trying to split the input/output logic from the actual computing logic. Here, you could define 2 functions : one to initialise some object like structure from a string, one to use the structure to get the Kth character (K being the argument to the method).

This would allow you to write unit tests which would help you improve your algorithm.

Algorithm

You have used the correct ideas : use the proper data structure to store the different values used.

An improvement you could implement is to define a structure with the cumulated numbers that you compute once so that then you can get the kth element with a simple array lookup (actually as suggested by ChrisWue, maybe you'd need a binary search and not a single lookup). When multiple queries are performed (which is I think what is happening in your case), this should make things much faster.

The idea of doing some ("long") preprocessing once to make (multiple) queries much faster is a pretty classic solution in real life and in programming challenges.


Your function is called parse_polish(), but it actually does much more: it evaluates the expression too!
pop() takes no arguments, and push() takes just one argument, so I deduce that they must be operating on a global variable, which is bad practice.
Your function returns -1 on error, but that could very well also be the result of a legitimate calculation.  I recommend one of the following strategies:

Passing the calculation result as an out-parameter.
Requiring the caller to initialize the stack and pass it to your evaluator.  The caller can then pop the result off the stack (which could be empty in case of an error).
Using floating-point calculations.  Not only do you get floating-point division, but you also have the possibility of returning positive infinity, negative infinity, or NaN.

Why do you test that *expression[1] and *expression[2] are digits?  What if the expression consists of a single token { "5" } — shouldn't the result be 5?
Perhaps you want to allow negative integers as inputs too?


I took the liberty of rewriting most of this from scratch for a few reasons.

First, this very difficult to actually test. All your embedded if statements... oh my! Second it's also difficult to add new checks into if you want other filter conditions.

Code like your original code starts out well intentioned but becomes a giant spaghetti mess fairly quickly - you only have three conditions and it's already a complex and hard to read and quickly understand function.

I moved each conditional check into a separate, small function:

# Convention: returns true if should be removed, based on criteria
def contains_numbers(s):
    return any(char.isdigit() for char in s)

Any is a great use for things like this. It will return True if any condition in the list matches.

def single_word_is_not_all_caps(s):
    if len(s.split(' ')) == 1:
        return s.upper() != s
    return False

def contains_multiple_words_not_uppercase(s):
    words = s.split(' ')
    if len(words) > 1:
        return words[0][0].upper() != words[0][0]
    return False

Fairly straightforward here. Both these test specific conditions that can be optimized a bit better in single functions.

This can streamline your main logic significantly (using any again):

 filters = [contains_numbers,
       contains_multiple_words_not_uppercase,
       single_word_is_not_all_caps]

def filter_strings(strs):

    filtered = []
    for s in strs:
        if not any(foo(s) for foo in filters):
            filtered.append(s)

    return filtered

Notice how easy it is now to add new check conditions, you just need to make/test a small function and add it to your filter list. Then iterate over that list, checking if any of them return true for the current string.

You could make this a list comprehension and even simpler if you want:

def filter_strings_list_comp(strs):
    return [s for s in strs if not any(f(s) for f in filters)]

Adding new logical checks is suddenly trivial. Changing existing ones, similarly. With one main "if tree to end all if trees" you will over time end up with a complete mess.

This approach also has the added feature/benefit of making testing much more trivial (I used basic assert statements here):

assert(True == contains_multiple_words_not_uppercase('foo bar'))
assert(False == contains_multiple_words_not_uppercase('Foo bar'))
assert(False == contains_multiple_words_not_uppercase('Foo'))

assert(True == contains_numbers('123'))
assert(True == contains_numbers('1asdf23'))
assert(False == contains_numbers('Foo bar'))
assert(False == contains_numbers(''))

assert(False == single_word_is_not_all_caps('FOO'))
assert(False == single_word_is_not_all_caps('foo bar'))
assert(False == single_word_is_not_all_caps('Foo bar'))
assert(True == single_word_is_not_all_caps('Foo'))

assert(['FOO'] == filter_strings(['Foo', 'FOO']))
assert(['BAR', 'Foo bar'] == filter_strings(['Foo', 'foo', 'BAR', 'Foo bar', '123']))

assert(['FOO'] == filter_strings_list_comp(['Foo', 'FOO']))
assert(['BAR', 'Foo bar'] == filter_strings_list_comp(['Foo', 'foo', 'BAR', 'Foo bar', '123']))

This is a lot easier to isolate problems, particularly if this ends up with many filters.

I would recommend adding more tests here, there are conditions I'm not sure how you want to test or what they should return.


Finding matches in Excel files, adding to a Pandas Dataframe

The issue has been resolved.

The problem was I was creating the pattern r = pattern(keys) for each keyword (remind you i had 600 keywords) for each cell of the excel which was completely unnecessary.

So if i had a 10(rows) * 10 (columns) excel file, the same 600 pattern was getting created 600 * 10 * 10 times.

So I created one dictionary of patterns just once and used the same 10 * 10 times.

for cat,key in keyword_dic.items():
    temp = [pattern(keyword) for keyword in key]
    list_of_patterns[cat] = temp

Thanks everyone, for taking the time to go through the post!


Is there any way to improve (shorten) this F# code?

Most of your code can be replaced with a comprehension:

type Comment = { Author: string; Body: string }

let readAllComments () =
  [|for line in System.IO.File.ReadAllLines("comments.txt") do
      match line.Split ';' with
      | [|author; body|] -> yield {Author=author; Body=body}
      | _ -> ()|]


Persistent, dictionary-like object ensurance

Ideally you would want to use Python's with ... as syntax, which creates a context that calls the exit method of whatever object you create. For this, the shelve.Shelf classes would need to implement the dunder methods __enter__ and __exit__ (which they don't).

At this point you basically have three options:

Inherit from them and implement it yourself:

class Shelf(shelve.Shelf):

    def __new__(cls, file_name):
        return shelve.open(file_name)

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

Or just write a simple wrapper class like this:

class Shelf(object):

    def __init__(self, file_name):
        self.file_name = file_name

    def __enter__(self):
        self.obj = shelve.open(self.file_name)
        return self.obj

    def __exit__(self, *args):
        self.obj.close()

Both can be used like this:

import os
import shelve

def get_document_info(current_dir):
    shelf_path = os.path.join(current_dir, 'document_info.shelve')
    with Shelf(shelf_path) as token_shelf:
        return token_shelf.get('token_mapping')

When you use try..except you should always guard against as specific exceptions as possible (so that unexpected exceptions can still rise to the top). In this case this would probably be a KeyError. Here I used the get method instead, which will return None if the key is not found.

I also removed the return False, because you should check for falsiness in the calling code. In other words, if you are doing if token_mapping is False or  if token_mapping == False in the calling code, you are doing it wrong. Just have the if not token_mapping/if token_mapping there.

Use Python's contextlib.closing, which already implements something like option 2:

from contextlib import closing
import os
import shelve

def get_document_info(current_dir):
    shelf_path = os.path.join(current_dir, 'document_info.shelve')
    with closing(shelve.open(shelf_path)) as token_shelf:
        return token_shelf.get('token_mapping')


Here are some general things you should be doing differently. These suggestions don't change the functionality of your slider, and are suggestions you can apply to your future projects.

First and most important

var wrapper = $('.portfolio-inner-wrapper');
//As a rule of thumb, if you use a selector more than once, you should cache it.
    //Now use 'wrapper' everywhere you used $('portfilo...') instead.
    //Cache it outside if you want to use it in other functions as well.
//Ex:
wrapper.css('width', sliderWidth);

Next:

if (autoSlide) { //Don't need == 1. Zero is a falsy value.
    setInterval(function() {
        slide_right();
    }, slideDuration); //You don't need setInterval either. jQuery has a built in queue.
}

When you have multiple 'animate' calls, jQuery puts them in a queue to execute them one by one. This goes for the rest of your slider as well.

Save function calls. Do it like this:

$('a.next').on('click', function() {
        if ( (sliderWidth - Math.abs(marginLeft)) > containerWidth ) {
           wrapper.stop().animate({
            'margin-left': '+=-' + containerWidth
           }, slideSpeed, function() {
            marginLeft += -containerWidth;
        });
     } else {
        wrapper.stop().animate({
            'margin-left': '0' //Zero doesn't need a unit of measure (ie. px, em, %, etc)
        }, slideSpeed, function() {
            marginLeft = 0;
        });
    }
});

When you use the .click() method, jQuery calls the .on() method. Then if you still call another function inside that, that's three function calls that could be spared if you simply used this:

$('a').on('click', function() {
    do.stuff
});

Finally, I'll be happy to answer any other questions you might have.


Swift iOS rewrite a function that use Firebase database without updating a global variable

A typical way to write an asynchronous function is to have it take a function as an argument that will be called with the results when they are ready. Such a function is often called a completion handler.
private func getNumberOfRecords(category: String, completion: (Int) -> Void) {
   ...
            default: print("Error loading record from category \(category)")
            }
        }
    }
    completion(records.count)
}

Then at the call site you can write:
getNumberOfRecords(category: "classical", completion: { count in ... })

or better written with trailing-closure syntax:
getNumberOfRecords(category: "classical") { count in ... }

You still have the problem of three asynchronous things, and instead of chaining them together, you can also avoid looping over the data 3 times, you can loop over the data once and remember the counts for each item, using a dictionary:
private func getNumberOfRecords(completion: ([String: Int] -> Void)) {
    var categoryCounts: [String: Int] = [:]

    {
    ... loop over the data here and instead of switch category ...
    categoryCounts[category] = (categoryCounts[category] ?? 0) + 1
    }

    completion(categoryCounts)
}

getNumberOfRecords { categoryCounts in
    for (category, count) in categoryCounts {
       loadDataFromDB(records: count, category: category)
    }
}


"The most Pythonic way to check the type of an object is... not to check it." The pythonic way to do this is to assume that the calling code/user is sensible enough to pass an object which can be handled by the callee. This allows for subclass items or simply any object with the correct properties to be used in the code.

For maintainability you should:

use self explanatory names such as numpy, matrix, determinant etc.,
use descriptively named constants for any magic numbers such as 288,
split the function into one for sides and one for vertices (one may end up calling the other or they may both call a third, internal function for the final calculation),
run the code through pep8 and possibly a cyclomatic complexity checker like radon, and
in general, go through all comments, and for every comment see if you can refactor the code to make the comment unnecessary. For example, instead of "Set up the Cayley-Menger determinant" create a function get_cayley_menger_determinant.


Displaying contacts in PHP, with options to omit some information

The answers you'll get will be highly opinion-based, I guess. So, here a few points in favor of the first type of templating as the approach of inserting short PHP-elements into the template has some advantages.

Easier to read and follow

For a developer, the latter approach might be easier to follow. But often it's important to understand the structure and hierarchy of the markup. Your approach makes it quite hard:

echo '
'. $this->escape($tparams->get('page_heading')) . '
';
echo '
';
echo '
';
if ($this->item->published == 0){
    echo '' . JText::_('JUNPUBLISHED') . '';
}
echo ''. $this->contact->name . '';
echo '
';
echo '
';

It looks like everything is on one level and only the span-element is nested. This might be ok for a short passage like we see here. But consider a complex component with lots of nested elements.

Somebody who understands HTML can maintain the template

The first point brings us straight to this: A fronted-developer, who is not familiar with PHP can maintain and update your template. Taking the example from above, the person knows easily where to adjust the code, without breaking anything, if it would be written like this:

<?=$this->escape($tparams->get('page_heading'))?>

    <?=($this->item->published ? JText::_('JUNPUBLISHED') : '')?>
    <?=$this->contact->name?>

Also removing parent wrappers or inserting new elements is much easier.

Too much logic in the templates

I would say, that with the latter approach one might tend to include too much logic into the template. "Oh, I forgot to load the all products and categories from the database. Well, I'll just include it right here." And yes, this could happen with the first approach as well:

<?php elseif ($show_contact_category === 'show_with_link') : ?>
    <?php $contactLink = ContactHelperRoute::getCategoryRoute($this->contact->catid); ?>

This should happen somewhere in the controller or any other part before the template. However, I find it easier, to keep logic out of the presentation layer, if I'm filling and not creating a template.

Help from the IDE

Your IDE will find problems in the template, like unclosed elements, if you're actually writing HTML instead of creating strings containing HTML.

Switching to a different template engine or even language

At some point you might want to switch from PHP templating to a template engine  like Twig or Moustache. It's way easier when you have everything ready for this:

<?=$this->escape($tparams->get('page_heading'))?>

Can easily become this in Twig – as it automatically escapse strings:

{{ page_heading }}

Or if you switch to Moustache you aren't even coupled to PHP anymore. You could use your template with a lot of other languages. Or you might even want to include the template in a native APP in the future.


Allow certain IP addresses to run a C++ program

It took me a while to figure out what the code was trying to do.  I guess that http://www.myWebServer.com/ip/index.php serves a purpose similar to http://www.whatismyip.com, echoing the HTTP client's IP address.  That is better than just enumerating the IP addresses on the client machine's interfaces, as it ensures that you pick an address that is actually routable.

Like all DRM schemes, this one is crackable too.  One simple workaround is to use a transparent HTTP proxy that intercepts the call-home message and fakes a response.  Using HTTPS with server certificate validation would help prevent that man-in-the-middle attack.

The parseAllowableIPs() function is misnamed.  It's not just parsing — it's also fetching, reading, and making an allow/deny decision.  A more appropriate name would be isClientIPAuthorized().

compareIPs() is doing more than its fair share.  Instead of returning a std::string, getIPlist() should also split the text into a std::vector<std::string>.  There should also be a getMyIP() function.  Then, compareIPs() would be a simple verification of whether an item is in a list.

In summary, the outline should be more like:

bool isClientIPAuthorized()
{
    std::string me = getMyIP();
    std::vector<std::string> allowed = getAllowableIPs();
    return std::find(allowed.begin(), allowed.end(), me) != allowed.end();
}

int main()
{
    //... blah blah blah

    // If not an authorized IP, just exit the game.
    if (!isClientIPAuthorized())
    {
        MySQL__disconnect();
        exit(588924);
    }
}

However, I'd go a step further.  The dotted-quad parsing code in compareIPs() has some minor issues, such as superfluous pointer dereferencing.  (Note that it would be better to write U++; rather than *U++;, even though the effect is the same.)  It would be better to avoid reinventing the wheel, and using a standard IP address parsing routine.  (It's such a common task, a few minutes with Google and MSDN is worth it.)  There's the Winsock function inet_aton(), which parses a IPv4 dotted-quad address into a long, and the newer InetPton() that also handle IPv6.  So, getMyIP() and getAllowableIPs() should probably return long and std::vector<long>, respectively, instead of strings.


In general, when trying to reimplement basic collections like this, you're going to have a lot of difficulty getting near the performance of the in-built .NET collections. As others have said, removing frequently from the beginning of a List<T> has very poor performance. However, just looking at the circular buffer article already linked, my immediate reaction is "yeesh, that is not complexity I'd want to add to my code!" Especially when I know somebody's already done it for me in the existing Queue<T>!

So in situations like this, the answer is usually to either be willing to sacrifice performance, or to try to make use of the actual collection as much as possible. In fact, all you want is a queue that has a little extra functionality, so why not do just that, using composition? There's no IQueue<T> interface in .NET, so we can't implement the decorator pattern, but we can get close:

class MyQueue<T>
{
    private readonly Queue<T> _inner = new Queue<T>();

    public int Count
    {
        get
        {
            return _inner.Count;
        }
    }

    public T Last { get; private set; }

    public void Enqueue(T item)
    {
        _inner.Enqueue(item);
        Last = item;
    }
    //...
}

In more general review terms, the code you wrote looks good. A few minor points:

index and _items follow different naming schemes.
MyQueue is not a good class name. Try to pick a name that actually describes the class
As firda said, you shouldn't try to keep track of the index yourself, it's just Count - 1. You're tracking the same thing in two different ways.
You may want to consider implementing IEnumerable<T>. Using iterator methods, this wouldn't be too complicated, and it'd allow the full power of LINQ to be used with your class. However, I would definitely file this under YAGNI until it actually comes up as something you find yourself wanting, unless your intention with this code is to put it in a public library for others to use.


Multithreading to allow multiple clients on to a server and client requests handling

Note:
It is easier to provide a more complete answer when faced with a complete problem. There are several //other code areas that you may be omitting for the sake of brevity, but these could very well be providing more context to the review, and their presence could likely improve the quality of answers received.

I would recommend posting complete code as is, using a more descriptive place holder of the logic there than //other code and/or perhaps an explanation of why the missing code is considered irrelevant to the reviewer

/rant

Request for clarification
I noticed that in your AcceptingClients Thread you make a call to new ClientRequests(socket, inputStream, outputStream). However, you also define the similarly named ClientRequest with constructor public ClientRequest(Socket socket). Are these meant to be the same class, just with the latter being un-implemented? or are these differing classes, in which case I would recommend better names

On to your questions 3:

  1) Is it good to put all those thread in one class

Having a class ServerOperations containing each of your Operation threads IMO is actually good design (so long as each operation is reasonably simple).

When it comes to denser and thus more complex logic, I would instead opt for grouping each Operation class into a subdirectory /operations and using ServerOperations like a repository; a layer for accessing your collection of operations, something like ServerOperations.getOperationThread("acceptClients").

The benefit here is readability and maintainability. IMHO It is easier to understand and thus maintain the individual processes if they are in separate class files, but this would only be recommended for a collection of non-trivial Operations. If they are super simple, feel free to group them up like this!

  Using this way may give me problems if I have a lot of clients connected?

Short answer, yes. Based on the present code, I would highly recommend using non-daemon threads for these purposes. This question on SO has a TON of discourse on daemon threads but IMO the most relevant information therein is :

  Daemon threads are service providers for user threads running in the same process.

This means any Thread with setDaemon(true) should be considered a service, something that is running in the background and waiting to service a request from another, non-daemon thread. This leads the most annoying impact:

  Daemon threads can shut down any time in between their flow, Non-Daemon i.e. user thread executes completely.

Normally, if your program were ending, it would hang on exiting the JVM until all user threads are complete. As these threads are daemons, the JVM will drop these Threads and exit immediately. This means that in the edge case of a request still processing on shutdown, you will lose requests processing in these daemons.

Without information on how this daemon is used in these //other code sections, I can only conclude that you might not need to use daemonThreads

  2) If i don't extend the class AcceptingClients with Thread I have problem with JavaFX UI thread

I am unfamiliar with JavaFX so I won't offer advice I am unqualified to give

  3) To let everything run I have a method in my model where this method serverConnection() is called. [..] Good or not?!

If I am understanding this correctly, you are asking if it is good to call this method from the Model at creation (IMO that isn't a bad choice in the general sense). This question is incredibly difficult to answer without having the Model code available for context.

IMHO, this last is a question belonging in a review of the Model, or of the project as a whole, as without seeing the complete context of HOW this method is used, any feedback would basically be personal opinions about the proper use of MVC models

Hope some if not all of this helps!


If you don't call your function recursively from C, you don't need to have separate defition and declaration:

extern "C" __declspec(dllexport) int test(int val)
{
    return val * 2;
}

And if you have more than one function you want to export, you can use extern "C" as a block:

extern "C"
{
    __declspec(dllexport) int test(int val)
    {
        return val * 2;
    }

    // more functions here
}

As to what does it all mean:

extern "C" tells the compiler not to mangle the name of the function; this is normally necessary to support C++ function overloading
__declspec(dllexport) means that this function will be exported from the DLL, so that you can use it from outside this library


Docstrings: You should include a docstring at the beginning of every method, class, and module you write. This will help any documentation identify what your code is supposed to do.
Simplified boolean comparisons:

You have code like:

if repeat == "y":
    self.on_repeat = True
else:
    self.on_repeat = False

Instead of having an if/else and setting the boolean condition based on that, you can simply set the value of self.on_repeat based off the first check, like so:

self.on_repeat = repeat == "y"

Meaningful method names: Method names should be based off what the code inside them does. While some of your methods do (main_scene, end_scene), some of them do not. make_from_defeat for example. I had no clue what the same was trying to suggest about the method, and it doesn't seem to correlate to what the method does. I left them unchanged so you could figure out for yourself what those method names should be.
Constant Variable Naming: All constant variables in your program should be UPPERCASE, to distinct them from non-constants and make it clear to you/a reviewer that they are constants.

Updated Code

"""
Module Doctring:
A description of your program goes here
"""
import json
import random
from os import system, name
import msvcrt
import colorama

class Hangman:
    """
    Class for storing properties of the object `Hangman`
    """
    def __init__(self):
        self.level = ""
        self.word = ""
        self.wrong_chars = []
        self.from_victory = 0
        self.from_defeat = 0
        self.game_state = ""
        self.on_repeat = True

    @staticmethod
    def cls():
        """ Clears the console """
        system('cls' if name == 'nt' else 'clear')

    def difficulty_scene(self):
        """ Prints the difficulty options """
        print("""
  DIFFICULTY LEVEL:
  ------------------

  (1) Very easy.
  Very long words (10+ characters) and 10 lives

  (2) Easy.
  Long words (8 or 9 characters) and 8 lives

  (3) Standard.
  Medium words (6 or 7 characters) and 6 lives

  (4) Hard.
  Short words (4 or 5 characters) and 4 lives

  (5) Impossible.
  Tiny words (3 characters) and 3 lives.

    """)
        self.level = input("  Select difficulty (1-5): ")

    def game_prep(self):
        """ Prepares the game """
        self.word = WORD_LIST[-int(self.level) + 5][int(random.random()
                                                        * len(WORD_LIST))]
        self.wrong_chars = []
        self.from_victory = len(self.word)
        self.from_defeat = self.make_from_defeat()
        self.game_state = ""

    def make_from_defeat(self):
        """ Retuns the length of the word to guess """
        return {
            "1": 10,
            "2": 8,
            "3": 6,
            "4": 4,
            "5": 3
        }.get(self.level, 6)

    def main_scene(self):
        """ Determines if letter is inside word """
        colorama.init()

        print(f"\n  {'_' * len(self.word)}")

        while True:
            char = msvcrt.getch().decode('UTF-8')
            if char in self.word:
                for i in range(len(self.word)):
                    if char == self.word[i]:
                        print(f'\x1b[2;{i+3}H', end="")
                        print(char, end="")
                        self.from_victory -= 1
            else:
                self.wrong_chars.append(char)
                print(f'\x1b[4;{((len(self.wrong_chars) - 1) * 2) + 3}H', end="")
                print(char, end="")
                self.from_defeat -= 1
            if self.from_victory == 0 or self.from_defeat == 0:
                break

    def end_scene(self):
        """ Determines if the player has won or list """
        if self.from_victory == 0:
            print("\n  YOU HAVE WON")
        elif self.from_defeat == 0:
            print("\n  YOU HAVE LOST")
            print(f"  your word was {self.word}")
        repeat = input("\n  Try again? (y/n):\n  ")
        self.on_repeat = repeat == "y"

    def run(self):
        """ Runs the game """
        self.cls()
        self.difficulty_scene()
        self.cls()
        while self.on_repeat:
            self.game_prep()
            self.main_scene()
            self.cls()
            self.end_scene()
            self.cls()

if __name__ == '__main__':

    GAME = Hangman()

    with open("words.json", "r") as read_file:
        WORD_LIST = json.load(read_file)

    GAME.run()


A version of operator<< that returns ostringstream instead of ostream

Bjarne gives a pretty succinct description of why this (and many similar) features aren't in the standard. He points out that virtually everybody who talks to him about C++ has essentially the same thing to say: "C++ is way to big and way too complex. You should really work at making it a lot smaller and simpler. Oh, but while you're at it, you should add this one really great feature I thought of"

It kind of reminds me of things I've seen about how questions of political polls can be/ are phrased. If I ask: "Do you think this country should do more to [increase jobs | help the needy | etc.]?" I can count on a large majority of people saying "yes." If I ask "Do you think we should raise taxes by X%?", I can count on an equally large majority saying "No". I can give nearly a guaranteed outcome from my poll just by choosing whether to ask about the hoped-for outcome or the cost.

Bottom line: Each feature you add has a cost, and focusing on the outcome doesn't remove the cost. To design a usable language/library, you need to restrict features to the few that provide the greatest positive outcome for the lowest cost. In the case of the C++ committee, they've been pretty clear about a few things, and one is that most new features will barely be considered at all unless they enable fairly substantial improvements in code that uses the new feature and have extremely minimal cost, especially in terms of breaking any existing code.


I see a few things that can be done to tweak this:

Cache your selectors instead of re-querying the DOM each time. Anything you use more than once should be cached.
Since all of the form fields use ID's you can use the native getElementById for faster performance.
Use strict equality when your are evaluating to reduce the chance of a gotcha.
Use 'use strict;' if you aren't already.
Surround your code by an IIFE, to encapsulate it and create a private scope.
Namespace your code

`

(function($){
  'use strict';
  var validateForm = {};

  //shortcut functions to simplify code below
  function isEmpty(str) { return str === ''; }
  function isNotSelected(num) { return num === 0; }
  function id(str) { return document.getElementById(str).value+''; }
  function getNum(str) { return document.getElementById(str).value-0; }

  function onSubmit( buttonId ) {
    var disableButton = false;
    var formType = getNum('formType');

    //cache selectors below
    var contact= id('contact');
    var newAccount =  id('newAccount');
    //assuming this is a dropdown
    var el = document.getElementById('select2-entityId');
    var entityId = el.options[ el.selectedIndex ].value -0;

    switch( formType ) {
       case 1:
        if ( isEmpty(id('CreateEntityName')) && isEmpty(id('newAccountGroup')) ) {
          disableButton = true;
        }
        break;

       case 2:
        if ( isEmpty(newAccount) && isEmpty(id('lastName')) ) {
          disableButton = true;
        }
        break;

       case 3:
        if ( isNotSelected(entityId) &&  isEmpty(contact) ) {
          disableButton = true;
        }
        break;

       case 4:
        if ( isNotSelected(entityId) && isEmpty(contact) && isEmpty(id('need')) && isNotSelected(getNum('candidates')) ) {
          disableButton = true;
        }
        break;

       case 5:
        if ( isEmpty(newAccount) && isEmpty(id('country')) ) {
          disableButton = true;
        }
        break;
    }

    if ( disableButton ) {
      $('#' + buttonId + '').prop('disabled', true);
    }

    return disableButton;
  }

  validateForm.init = onSubmit;
  window.validateForm = validateForm;

  //document.ready if you need to do something else
  $(function(){
    if ( validateForm.init() ) {
      //do something here
    }
  });

})( jQuery );

I am sure there are other things that can be done.  Hope that helps!


Because you’re allowing path traversal, your function doesn’t restrict even system paths. To exemplify the danger of your function, check examples below, where realpath('.') points to /web/users/alice:

DesiredRealPath('files/photos'); # It returns `/web/users/alice/files/photos` and this is OK
DesiredRealPath('/etc/passwd'); # It returns `/etc/passwd` and it’s very BAD
DesiredRealPath('../bob/photos'); # It returns `/web/users/bob/photos` and this is also BAD

To protect against Path Traversal Attack, you should ignore “dot” directories. For example, consider this function:

function basepath($rel_path)
{
    $base = str_replace('\\', '/', realpath('.'));
    $parts = explode('/', str_replace('\\', '/', $rel_path));

    foreach ($parts as $part) {
        if ($part && $part != '.' && $part != '..') {
            $base .= "/{$part}";
        }
    }
    return $base;
}

Testing the same paths as in the example above, no one escapes the /web/users/alice directory:

basepath('files/photos'); # /web/users/alice/files/photos
basepath('/etc/passwd'); # /web/users/alice/etc/passwd
basepath('../bob/photos'); # /web/users/alice/bob/photos

For better security, make sure to configure the open_basedir directive correctly.

By the way, if you have a script for which you want prevent path traversal, add the following at the top of your script:

ini_set('open_basedir', __DIR__);


C code to calculate the binary period of an integer

I see some things that may help you improve your program.

Use the appropriate #includes

In order to compile and link, this code requires at least #include <stdio.h>.  For the program to be complete, all appropriate #includes should be listed, too.

Check your assumptions

For this code to work, the int on your platform must be at least 32 bits.  For that reason, this assumption should be checked at compile time:

static_assert(sizeof(int) >= 4), "int must be at least 32 bits");

Format your code consistently

It doesn't matter as much what style you use as it matters that you have a consistent style. In particular, there seems to be inconsistent indenting and inconsistent placement of braces.  Using a consistent style helps readers of the code understand it.

Use better variable names

Generally, single letter variable names other than i and j for loop variables, are best avoided in favor of longer, more descriptive names.  The variable p is not too terrible, but the variable l is definitely a poor choice, not least because it's easily mistaken for the digit 1 or the letter i.  I changed it to len in the rewrite I did.

Fix the bug

Right now, if we have the program calculate solution(8), it returns 1 instead of -1.  That is not correct.  There are other values within the range that also return incorrect values.

Write a test program

Right now the main routine just tries three values.  It would be better to try other values, maybe even every value in the range, and test it for accuracy.  You can do that by creating a function bool verify(int n, int p) that returns true if the condition stated at the beginning of the problem is true.


import quantumrandom

The problem is that you should not trust third parties when importing random numbers. Furthermore, getting the randomness requires a secure connection in the first place. The secure connection relies on random numbers to remain secure. A secure random number generator that has been seeded by the OS is generally the best way to go.
HMAC_KEY = "738525cf1f8acd06beb4cf6cd816d1dc"

Generally keys should not be strings, not even hexadecimal strings. Strings are easy to find. I'd rather even use a Python \b string than hexadecimals, but preferably you'd use a keystore, or keys derived from a password supplied by the user. Which brings us to the next point:
hashed = pyscrypt.hash(
    password=password,
    salt="2df2e24c76d4d7b37e7ffcdf787e426b",
    N=16384,
    r=8,
    p=1,
    dkLen=16)

Don't use single-person unmaintained libraries. Never ever use a static salt. A salt, again, is a binary string, not a normal string. 16Ki iterations is on the short scale of things.
iv = quantumrandom.binary()[:16]

If you'd have used a random salt for each encryption then you can simply derive the keys (the encryption and MAC key) and IV from it. As the salt is unique, the key and IV combination will be unique as well.
data = iv.encode("hex") + cipher.encrypt(plaintext).encode("hex")
sig = hmac.new(HMAC_KEY, data, hashlib.sha512).digest().encode("hex")

I applaud you for having the IV authenticated as well. I also applaud you for using encrypt-then-MAC which is generally considered more secure than encrypt-and-MAC or MAC-then-encrypt.
I cannot applaud you to perform the HMAC over the hexadecimal representation of the bytes though; you've just doubled the required effort for calculating it. Never confuse binary with the representation of the binary in some textual format (hex, base64).
And while we're at it, hex requires an overhead of 100% when viewed as bytes (assuming an 8 bit encoding). Base 64 is a lot more efficient. Generally: first concatenate the binary, then encode; this will generate fewer characters as well. Or keep it as binary of course; a lot of ciphertext is encoded unnecessarily (leading to so called "stringified" code).

One improvement would be the use of an authenticated cipher such as AES-GCM instead of performing the encryption and HMAC separately.
For larger plaintext / ciphertext you could think about piecemeal updates / streaming so that the entire plaintext / ciphertext doesn't need to be in memory all at once.


Euler Project 14 (Longest Collatz Sequence)

Using a 3.5 interpreter, things yielding "negative speed-up" included:

@functools.lru_cache(None) (mainly due to explicit base-case handling?)
substituting cache.get() and is not None for in and []
divmod(n, 2) instead of %2 and //2
"inlining the even case"

Negligible speed-up:

Binary operators instead of %2 and //2
Global cache instead of an explicit parameter

Slight speed-up:

rec_col((3*n+1) >> 1)+2

Of 1588206 cache entries, almost half are not used at all, not even one eighth twice, none more often.


The speed issue can be fixed by using PyPy 3  as it is faster (at least in most codeforces type problems, I don't know in general)

However this will result in a WA verdict. To fix this just modify the break condition as follows and it will work:

if(st!=-1 and x!=int(s[i])):

This is because the current version can sometimes break out of the loop prematurely when \$x == int(s[i])\$ because it may be better to make the segment longer.

Finally, I consider you are using too many flag variables, only one is required. Here is how I would change the code:

n = int(input())
s = input()
f = list(map(int,input().split()))
result = []
flag = 1
for i in range(len(s)):
    x=f[int(s[i])-1]
    if(x>int(s[i])):
        result.append(str(x))
        if(flag==1):
            flag = 0
    else:
        result.append(s[i])
        if(flag!=1 and x!=int(s[i])):
            break
for j in range(i+1,len(s)):
    result.append(s[j])
#print(result)
r = int(''.join(result))
print(r)


How can this LINQ query using SqlFunctions.Datediff and LINQKit's PredicateBuilder be improved

First of all.  Is _queryLeadsByHeat supposed to represent a method?  If so I would steer away from using underscore in it's method name unless that's your naming convention in which case I guess your stuck with it.  Underscore is traditionally mainly reserved for fields (if at all as there are large debates for this practice).

I don't have Visual studio in front of me so not sure if this will even compile (or is even possible) but my initial thought would be to try and consolidate the Predicates into one method.

Expression<Func<T, bool>> GetHeatCondition(DecreaseUnitTime period)
{
    string periodAsString = period.ToString();

    return predicate.Or(x => x.LeadPool.DecreaseByUnit == (int)period
                               &&
                               (
                                   (x.LastHeatValue - SqlFunctions.DateDiff(periodAsString, !x.LastContactDate.HasValue
                                                              ? x.InitialContactDate
                                                              : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) > 0 && warmLeads ||

                                    (x.LastHeatValue - SqlFunctions.DateDiff(periodAsString, !x.LastContactDate.HasValue
                                                              ? x.InitialContactDate
                                                              : x.LastContactDate.Value, DateTime.Today) *
                                    x.LeadPool.DecreaseLeadBy) <= 0 && !warmLeads
                                )
                           );
}

private IQueryable<Lead> QueryLeadsByHeat(int? ownerUserId, bool warmLeads)
{
    var predicate = PredicateBuilder.False<Lead>();
    predicate = predicate.Or(GetHeatCondition<Lead>(DecreaseUnitTime.Day));
    predicate = predicate.Or(GetHeatCondition<Lead>(DecreaseUnitTime.Month));
    predicate = predicate.Or(GetHeatCondition<Lead>(DecreaseUnitTime.Year));

    var query = _activeLeads(ownerUserId)
                        .AsExpandable().Where(predicate);

            return query;
}

I'm pretty sure that Linq query could be better optimized.  Have to think some more on that one...


Parse File or String input in a uniform way: Is it possible with Generics?

Yup - that's an abomination.

What you are really looking for is

void parse(Scanner sc) {...}

which can be called from parse(), which passes it the File scanner; and from parse(String), which passes it the string scanner.

It's likely - but not certain - that this method should really be

HashMap<String,String> parse(Scanner sc) {...}

The clue that this might be so is here in your constructor

public Parser(final File path){
    /*initialise stuff*/
    val=new HashMap<>();
    source=path; //throws exception if null but omitted for brevity
    /* and finally parse the file */
    parse();
}

You're doing verbing in the constructor, which is a bad sign.  It suggests that Parser is (at different times) responsible for parsing the file and acting as a value type.  Those are two different concerns, and should have two different representations.

Another bad sign is that you are creating Scanners in the same class that is doing work.  Given that in your current interface, you need to create a Scanner, I'm inclined to guess that the refactoring you need is to create a new class that provides the parse(Scanner) implementation.  The existing Parser delegates the work while providing the backward compatible behavior.

If the existing Parser needs more than just key/value pairs, then you might really be looking for

ParseResult parse(Scanner sc) {...}

where ParseResult contains the Map and whatever other state the application needs after the parsing is completed.


Get rid of antipatterns like

parseInt(1)

Just say 1 instead.

Factor out common code like

$(this).parent().children('.post-votes')

and

$(this).css('background-color')

into variables.

Combine the two handlers thus

function vote(isUpvote) {
    var control = $(this);
    var otherControl = control.parent().children(
        isUpvote ? ".post-downvote" : ".post-upvote");
    var postVotes = control.parent().children(".post-votes");
    var ajaxHandler = isUpvote ? "upvote/" : "downvote/";

    // ajax(url + ajaxHandler + control.attr('data-postid'), false, false);

    // user voted so let's delete the other control
    if (otherControl.css("background-color") == yellow()) {
        postVotes.text(+(postVotes.text()) + 1);
    }
    control.parent().children(otherId).css("background-color", "white");

    // if it's yellow, user is cancelling their vote
    if (control.css("background-color") == yellow()) {
        control.css("background-color", "white");
        postVotes.text(+(postVotes.text()) - 1);
    } else {
        control.css("background-color", "yellow");
        postVotes.text(+(postVotes.text()) + 1);
    }
}

$(".post-upvote"  ).click(function() { vote.call(this, true); });
$(".post-downvote").click(function() { vote.call(this, false); });


Permute and count between nested dictionaries

Here's a first pass at compacting your code, it should provide some speed improvements too:

cnv_loss_total = {cell: set(gene for gene in genes if genes[gene] < 0) for cell,genes in cnv.iteritems()}

total_link_counter = collections.Counter()
for cell,genes in rna.iteritems():
    cell_combo = itertools.product(cnv_loss_total[cell], set(genes.keys()))
    for comboC, comboR in cell_combo:
        total_link_counter[comboC+'+'+comboR] += genes[comboR]

By turning the first loop into a list comprehension, it avoids temporary variables and is more efficient in creating a set.  Also, using iteritems() avoids generating the entire list of dictionary items and yields one pair at a time.

In the second loop, the rna_gene_gain variable is eliminated by using set(genes.keys), which is again more efficient in building the set.


Project Euler # 35 Circular primes in Python

Let's start with a quick analysis of your current algorithm. For each number less than n (1000000 in your case) it does sqrt(n)log(n) operations (sqrt for is_prime*logcycles). However, some fairly simple things about this problem make it much easier to solve.

As you probably know, any 2 digit or greater number ending in 2,4,6,8 or 5 is not prime since it is divisible by 2 or 5. Thus when constructing circular primes, you don't even have to check numbers that have these digits in them (and add 2 to the result for 2,5)

Thus by changing the main bit of code to only generate reasonable candidates, you do significantly less work.

def digit_combinations(digit_list, n):
    if n == 1:
        for digit in digit_list:
            yield digit
        return
    for digit in digit_list:
        for part in digit_combinations(digit_list, n-1):
            yield digit + 10*part

def circular_primes(digits):
    if digits == 1:
        return 4 # 2,3,5,7

    all_circulations = [2,3,5,7]
    for i in range(2, digits):
        for num in digit_combinations((1,3,7,9), i):
            if is_prime(num):
                check = 0
                if circulate(num):
                    circulations = circulate(num)
                    for circulation in circulations:
                        if not is_prime(circulation):
                            check += 1
                    if not check:
                        all_circulations.extend(circulations)
    return all_circulations

By my timings, this code can return the 8 digit or less ones in 3 seconds, where yours took 7 seconds to do only up to 1 million.