Program to print the multiple occurrence of numbers in a list

Welcome to code review.
Style
Check PEP0008 the official Python style guide for maintaining code within Python acceptable standards.

Class names: Apart from the fact that this is a bad use of classes, class names should be UpperCaseCamelCase which implies that since this
delete_duplicates is a class, then the name should be DeleteDuplicates.
Method/function/variable names: should be lowercase and words separated by underscores ex: flagarray=[] is flag_array = []
Space around operators: a space should be left on both sides of a binary operator: a=[] is a = [] and flagarray=[] is flag_array = []
Descriptive variable names: names should reflect the objects they represent and not names like j, c, i which are confusing because j could be a variable, a string, a number ...
f-strings: (Python 3.6 +) are better used for combining strings and variables in a single statement. ex: print(str(c)+"ocuurs"+str(len(ca))+"times") can be print(f'{c!s} occurs {len(ca)} times')

Code

Functions: A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Since this a bad use of classes because a class is usually used for an object with multi-attributes and multi-methods and this is not the case here, you might use a regular function.
Augmented assignment: Python supports augmented assignments ex: i=i-1 is i -= 1, count=count+1 is count += 1 ...
Semicolons: are for combining multiple short statements on the same line, this j=0; (line 15) is an invalid use of semicolons.
Comparison to True and False: is usually done using if something: and if not something_else: ex: flagarray[i]==False: is if not flag_array[i]:. Non-empty sequences and non-zero variables evaluate to True ex: if  len(ca)>0: is if ca:
Inefficiency: If you need to print duplicates of a list you shouldn't be entering each of the list members manually (what if you have a list of size 10,000,000 items? will you be manually entering one by one?)
Counter() You could use counter dict from the collections library for counting list members

An improved version:
If you want to get duplicates and print them:
from collections import Counter

def get_duplicates(numbers: list):
    """Return list duplicates."""
    num_duplicates = Counter(numbers)
    return {item for item in num_duplicates if num_duplicates[item] > 1}

if __name__ == '__main__':
    list_of_duplicates = [1, 2, 2, 3, 4, 3, 5, 2, 7, 1, ]
    print(get_duplicates(list_of_duplicates))

If you want to delete duplicates then use a set
print(set(list_of_duplicates))

output: {1, 2, 3, 4, 5, 7}


Using a BaseController in MVC asp.net to reuse the repository

This sounds exactly like a desire for Dependency Injection (using an IoC container).  ASP.NET MVC is perfectly setup for this already with plenty of containers out there for you to use!

You can still have a base constructor take arguments if you wish but I would try and limit how many.

So your controllers would look like:

public StudentController(IRepository repo,IStudentRepository studentRepo)
        : base(repo)
{
      StudentRepo = studentRepo;
}

So by using the IoC framework these will be automatically resolved to your desired class.  By doing this, it opens up the opportunity to more easily inject mock classes into your controllers and further separates them conceptually from implementation detail of the repositories.  Although I typically do not Unit test my controllers (as I try to keep them as skinny as possible), it would also make unit testing easier.

Typically you might do this in the Global.ascx or in the App_Start folder.  You can get most DI frameworks by using Nuget packages (which I would recommend).  There are many out there but here are a couple of examples from ones I have dealt with in the past.

Autofaq

public class AutofaqConfig
{
    public static void Configure()
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();

        RegisterRepositories(builder);

        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }

    private static void RegisterRepositories(ContainerBuilder builder)
    {
        builder.RegisterType<StudentRepository>().As<IStudentRepository>();
        // And any other repositories here
    }
}

And in your global ascx

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        AutofaqConfig.Configure();
    }
}

Ninject (Using the MVC3 ninject module)

public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);

        // Install our Ninject-based IDependencyResolver into the Web API config
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<StudentRepository>().To<IStudentRepository>();
    }
}

Using Unity (Using Unit.MVC4)

public class UnityConfig
{
    #region Unity Container
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    /// <summary>
    /// Gets the configured Unity container.
    /// </summary>
    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }
    #endregion

    /// <summary>Registers the type mappings with the Unity container.</summary>
    /// <param name="container">The unity container to configure.</param>
    /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
    /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
    public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // Repositories
        container.RegisterType<IStudentRepository, StudentRepository>();
    }
}


Fractional knapsack implementation in Python

I think some better organization will help.  Also, a slightly different algorithm will help simplify.

Separation of concerns (e.g. code splitting)

I think the way you have split everything up could use some work.  You only split out two bits of functionality to separate functions, and both are so simple they would probably just be better off inline.  This one in particular:

def replace_max_value(values_per_unit, idx):
    values_per_unit[idx] = -1

Used as:

replace_max_value(values_per_unit, value_and_index["index"])

This total combination is much more verbose then simply doing it inline:

values_per_unit[value_and_index['index']] = -1

The same is really true for your other method, get_max_value_per_unit.  To be clear, I'm not saying that you shouldn't split up parts of your program into separate functions.  However, splitting a single line (or even just three lines) is usually a sign of choosing the wrong "seams" to break up your application on, unless that functionality is needed in different places.  Obviously, that isn't the case here.

Although, this is simple enough that you might not really have to break anything apart, especially after some simplifications (coming soon).  The division between your __main__ calling function and your get_optimal_value is probably sufficient.

Separate input and output

Regarding that replace_max_value() method, even though it should go away, there is another lesson here.  I'm generally not a fan of using function parameters for output.  I.e., you are relying upon pythons pass-by-reference style to modify the passed in list.  As a general rule of thumb this is often error-prone in the long run.  Having a return value makes it clear what is getting modified and when it is being modified, but relying on modification of a function parameter is much less obvious.  As a result, it is easy to come back later and get confused about how/where your values_per_unit variable is being modified.  This syntax, however, is much more clear (even if more verbose):

values_per_unit = set_max_value( values_per_unit, value_and_index['index'] )

It is obvious exactly what is input, and what is being changed.  Now with python this is mildly trickier because you have no choice but to pass-by-reference, but a simple copy operation fixes the issue:

def set_max_value( values_per_unit, idx ):
    new_list = list( values_per_unit )
    new_list[idx] = -1
    return new_list

Granted, this is slightly slower (because of the array copy), but unless performance is known to be an issue, I think it is better for long-term code maintenance to do the copy and have a clear input/output for your function.

Sort!!

In cases like this sorting is your friend.  Before starting your loop take your values_per_unit and sort it.

sort_indexes = reversed( [i[0] for i in sorted(enumerate(values_per_unit), key=lambda x:x[1])] )
weights = [ weights[i] for i in sort_indexes ]
values = [ values[i] for i in sort_indexes ]
values_per_unit = [ values_per_unit[i] for i in sort_indexes ]

for ( weight, value, value_per_unit ) in zip( weights, values, values_per_unit ):

    weight_to_use = min( weight, remaining_capacity )
    remaining_capacity -= weight_to_use
    value += weight_to_use*value_per_unit

    if remaining_capacity <= 0:
        break

return value

Although it is worth noting that I am looping over sort_indexes three times.  Some might prefer doing that with one loop for performance, but I find this easier to read, and would stick to it as long as I knew performance wasn't going to be a big concern.


Is this a good algorithm for 2D collision, or will it allocate too much memory?

Your constructor arguments and defaults are unusual.
What does radius mean for a Rectangle?
Should there be an argument for initializing mass?
I suggest:

    static const Vec2f& defaultCenter();
    static const Vec2f& defaultSquareDimensions();
    static const Vec3f& defaultColor();

    Rectangle(
        const Vec2f& center = defaultCenter(),
        const Vec2f& widthheight = defaultSquareDimensions(),
        // Assuming rotation angles are supported...
        const Vec2f orientation = defaultOrientation(),
        const Vec3f& color = defaultColor()
    );

and/or maybe:

    Rectangle(
        const Vec3f& color,
        const Vec2f& center = defaultCenter(),
        const Vec2f& widthheight = defaultSquareDimensions(),
        // Assuming rotation angles are supported...
        const Vec2f orientation = defaultOrientation()
    );

    inline const Vec2f& getWidthHeight() const {
        return mWidthHeight;
    }

The static methods can return "static objects" that are constructed once each instead of always constructing new temps.

I can't tell what the return value of the following function represents.
What is the north direction vector of a rectangle?
Can you give examples for different rectangles?
Can you explain how you would use the returned vector?

    inline Vec2f getDirection(V2D_DIRECTION dir) const {
        switch(dir) {
        case V2D_NORTH:
            return mNorth;

        case V2D_SOUTH:
            return mSouth;

        case V2D_EAST:
            return mEast;

        case V2D_WEST:
            return mWest;

        }
    }

This seemed missing?

    virtual bool Intersects( const Circle& s ) const;

There should be some good reason not to make these private:

   Vec2f mCenter;

There seems to be no reason to make this a pointer.
There might be an argument for making it const.

   Vec2f mWidthHeight;
   Vec2f mOrientation;

If rectangles tend to come in a small selection of colors,
you may be better off storing an index into a central
pallette vector or possibly a pointer into a pool of shared colors.

There might be an argument for making this const if they don't change color.

   Vec3f mColor;

The following seem expensive to store and maintain and they also seem like they may be at least partly redundant? If they are redundant (derivable from a smaller set of parameters)
you should probably run benchmarks on code that stores these values
and code that calculates them on the fly as needed.

private:
   Vec2f mNorth;
   Vec2f mSouth;
   Vec2f mEast;
   Vec2f mWest;
   void InitDirections();

It may be that there is a better way to express orientation and/or these other values that is more useful in finding intersections.
It seems strange to me to be considering even more of these vectors for NW, etc. but I'm not even sure yet what they mean.

To speed up intersection, I thought you MIGHT also want to store
an additional widthheight representing the bounding box -- the smallest x/y
aligned rectangle that contains this rectangle in its current orientation.

SO MUCH depends on how your actual intersect logic uses all of these values.
Storing them all and more MIGHT be worthwhile.

CPU vs. memory trade-offs can be very tricky to predict.


Function to count rows in a database query result

require

Incorporating code by file inclusion is a bad idea — especially code that has side-effects.  At the very least, db.php seems to have the side-effect of defining $db.  It makes me suspicious of what other things happen in there.

Recommendations:

move the require() call outside countRows()
change it to require_once()
make the side-effects explicit

require_once('include/db.php');

function countRows($sql, $parameters) {
    $db = connect();    # connect() is defined in db.php
    …
}

Even that is problematic, though: you shouldn't open a new connection for each query.  It's probably better to have the caller pass a database connection as a parameter.

function countRows($db, $sql, $parameters) {
    …
}

Purpose

This function is probably a bad idea to begin with.  The database sends back a lot of data just so that your PHP code can retrieve the row count.

If you just want to know how many rows that satisfy some criterion exist, then you should run a SELECT count(…) FROM … query, and the database will tell you just the count.

On the other hand, if you are also interested in the data itself, then you should just note the size of the result set when you run a "real" query.


The best way to close a Connection is... not doing it yourself,
but using try-with-resources, which is the best practice as of Java 7:

public String getStory(String id) throws Exception {
    try (Connection conn = MysqlDb.getConn(dbName)) {
        for (Publisher p : Publishers) {
            PreparedStatement prpStmt = conn.prepareStatement("SELECT story FROM " + p + " WHERE id='" + id + "'");
            ResultSet rs = prpStmt.executeQuery();

            while (rs.next()) {
                String story = rs.getString(1);
                rs.close();
                return story;
            }
            rs.close();
        }
    }
    return null;
}

There are a couple of other issues in your code:

You're not using the prepared statement properly and to its full advantage. Don't create a query string as a concatenation of variables used in the WHERE clause. Those values should be set via the prepared statement. In its current form, your query may be vulnerable to SQL injection attacks.
The inner while loop is not actually looping. You should replace the while with an if.
You should use try-with-resources for the prepared statement and the result set too
"Publishers" looks like a collection, a variable, but by the naming conventions of Java only class names should start with a capital letter. So this should be renamed to publishers.

With the above suggestions applied, the code becomes:

public String getStory(String id) throws Exception {
    try (Connection conn = MysqlDb.getConn(dbName)) {
        for (Publisher p : publishers) {
            String sql = "SELECT story FROM " + p + " WHERE id = ?";
            try (PreparedStatement prpStmt = conn.prepareStatement(sql)) {
                prpStmt.setString(1, id);
                try (ResultSet rs = prpStmt.executeQuery()) {
                    if (rs.next()) {
                        return rs.getString(1);
                    }
                }
            }
        }
    }
    return null;
}


Hint: think about whether you can combine the two if statements into one.


Squaring an integer by repetitive addition

Improving square

There are several bad practices in square:

Multiple calls to abs(integer) when it could be calculated just once and reused
Instead of range(1, x + 1) you could write range(x)
When you don't need to use the loop variable element for anything, a common convention is to name it _ instead
Converting integer and result to string is tedious. It would better to use a formatted string expression

Making the appropriate changes the method becomes:

def square(integer):
    result = 0
    abs_integer = abs(integer)

    for _ in range(abs_integer):
        result += abs_integer
    return 'Square of {} is {}'.format(integer, result)

Improving is_integer

In addition to what @Jamal already pointed out, the method has other problems too:

The way you check if the user input is numeric is overly tedious
Naming the input as "number" is not great, because it might be text

A better way to write it (also fixing the name and making it non-recursive):

def prompt_integer():
    while True:
        text = raw_input('Enter an integer: ')

        try:
            return int(text)
        except ValueError:
            print '%r is not an integer' % text
            print 'To try again, press Enter key'
            print 'Otherwise, press Ctrl+C keys to abort'
            raw_input('>>> ')

Why Python 2.7 ?

You're using Python 2.7.
Note that there are no more planned releases for Python 2.7 beyond 2015 June.
Consider migrating to Python 3, it's the future.


Time Limit Exceeds [HS11DIVS] - How to make it faster?

First you need to correct first()

unsigned long long int first(unsigned long long int a,unsigned long long int b,int x)
{
  // Removed b
  return a;
}       ^^^ otherwise the main loop will run through everything in the main loop (from 0).

Though first() looks efficient because you are doing it only once. The questioner may carefully craft a,b,x to take a long time. So you can optimize its evaluation:

unsigned long long int m = a%x;
a = a - m + x;  // a now first valid value.

Your summing of the digits does a lot of extra work.

99   = 18
199  = 19 1 + sum_of_digits(99)

You can use this to cache results and re-use them in later calculations.

Pre compute the following array and compile it into your application.

sum_cache[10000]   cache  = {
               /* Generated code goes here */

                            };

int sumOfDigits(int number)
{
     int sum=sum_cache[number % 10000];
     for(number = number/10000;number != 0; number/= 10)
     {
         sum    += (number%10);
     }
     return sum;
}

Edit (based on comments below)

int sumOfDigits(int number)
{
  int sum=0;
  while(number!=0)
  {
     sum = sum + (number%10);
     number = number/10;
  }
  return sum;
}
int main()
{
    std::ofstream data("data.d");

    data << 0;
    for(int loop=1; loop < 10000; ++loop)
    {
        data << ", " << sumOfDigits(loop);
    }
}

Then change the code above too:

sum_cache[]   cache  = {
               /* Generated code goes here */
 #include "data.d"
                       };

Edit 2:

Improved: (I was hopping you would see the simple optimization)
Does this help?

int sumOfDigits(int number)
{
     int sum=0;
     for(;number != 0; number/= 10000)
     {
         sum    += sum_cache[number % 10000];
     }
     return sum;
}

Max Loop:

Original Version (your Code)       100      = 100
First Cache Version                100-4    = 96
Second Cache Version               100/4    = 25


There are two main issues with your code.

Comments

Explain your code and what you are trying to do. If you keep developing this game, after some time you will have problems to understand what you are doing.

Especially explain the move_snake(), kill_snake() and feed_snake() functions, but also the usage of the variables.

Constants

Rename all constants, like keys to KEYS.

Access all constants with e.g. Snake.KEYS because they are constants, no class variables that are different for every instance.

To improve readability, you can change the indention for KEYS like this:

KEYS = {"GO": pygame.KEYDOWN,
        "UP": pygame.K_UP,
        "DOWN": pygame.K_DOWN,
        "LEFT": pygame.K_LEFT,
        "RIGHT": pygame.K_RIGHT }


welcome to Code Review!

I would write your code like this:

def find_boundaries(lista):
    if not lista:
        return None

    int_list = [x for x in lista if type(x) == int]
    return (max(int_list), min(int_list))

Notice a few things:

If you test your parameters for validity at the beginning of the function, it's perfectly fine not to use an else afterwards because the return statement exits the function (short-circuiting). This saves one level of nesting and makes the function more simple.
Python is designed to let you avoid writing loops as much as possible. Loops are a nuisance to write, take longer to read and increase cognitive load. You should get familiar with Python's list and dict comprehensions. Notice how much clearer the code for filtering out the values that aren't integers is.
Again, the max and min functions are built-in in Python and take any iterable (like a list) to return the largest and smallest element respectively. You don't need to deal with loop indices, the length of the list, etc. You just express what it is you want to return: a tuple that contains the largest and the smallest elements.


Generic pass_many(vals, pass_one) to unroll and call pass_one(val)

I'd make a few changes:

1) Take the if v check out of the inner loop into the function body (if not vals: return) - seems more consistent that way, unless you want pass_many(0,print) to print something but pass_may([0], print) not to?

2) I'm not sure there's any reason to use args=None and then check for it being None, rather than just doing args=() to start with, and the implementation's shorter that way.

3) There are definitely better ways to check whether something is a tuple/list/set/etc than using type.  Unfortunately none of them are perfect... I really wish there was a good clean way of distinguishing these things from strings and dictionaries.
Probably he most general thing I can come up with, using Abstract Base Classes from the collections module - it goes over all elements of iterable objects except for mappings (dictionaries etc - unless you want to include those?) and strings (I think the basic string type/s may be different in python3? Not sure.)

from collections import Iterable, Mapping

def pass_many(vals, some_funct, args=()):
    if not vals:
        return
    if isinstance(vals, Iterable) and not isinstance(vals, (basestring, Mapping)):
        for v in vals:
            pass_many(v, some_funct, args)
    else:
        some_funct(vals, *args)

Still, the ABCs aren't perfect - maybe using hasattr checks for whether something is an iterable or a mapping would be better. Not sure. Probably every possible way will have some downsides.

If you want to be more stringent and just accept plain lists and tuples and no other iterables, isinstance(vals, (list, tuple)) will be fine. It just won't work on things like iterators - whether that matters depends on the intended use.


The first thing I see is concatenating a string in a loop. This will create a new string every loop. You don't want that.

Instead use a StringBuilder:

public static String calc(long n1, long n2) {
    long temp, i = 0, result = 0;
    StringBuilder s=new StringBuilder();
    while (n2 != 0) {
        if ((n2 & 1) == 1) {
            temp = n1;
            if(s.length()!=0)s.append("+ ");
            s.append("(").append(i).append("-").append(i).append(") ");
            result += (temp<<=i);
        }
        n2 >>= 1;
        i++;
    }
    return s.toString();
}


complicated pascal triangle using JavaScript

You are not properly calculating the pascal triangle. Here is my solution, in this code I take advantage of the function .splice() to modify the content of every row. You know that the outter elements of each row are 1s and in between you make the calculations of the sum of the top "root elements", and just like that you get the Pascal's Triangle.

function pascalTriangle(level) {
  let matrix = [[1]];

  for (let row = 1; row < level; row++) {
    matrix.push([1, 1]);
    for (let col = 1; col < row; col++) {
      matrix[row].splice(col, 0, matrix[row - 1][col - 1] + matrix[row - 1][col]);
    }
  }

  return matrix;
}

console.log(pascalTriangle(7));

┌─────────┬───┬───┬────┬────┬────┬───┬───┐
│ (index) │ 0 │ 1 │ 2  │ 3  │ 4  │ 5 │ 6 │
├─────────┼───┼───┼────┼────┼────┼───┼───┤
│    0    │ 1 │   │    │    │    │   │   │
│    1    │ 1 │ 1 │    │    │    │   │   │
│    2    │ 1 │ 2 │ 1  │    │    │   │   │
│    3    │ 1 │ 3 │ 3  │ 1  │    │   │   │
│    4    │ 1 │ 4 │ 6  │ 4  │ 1  │   │   │
│    5    │ 1 │ 5 │ 10 │ 10 │ 5  │ 1 │   │
│    6    │ 1 │ 6 │ 15 │ 20 │ 15 │ 6 │ 1 │
└─────────┴───┴───┴────┴────┴────┴───┴───┘


Ok, the following isn't necessarily about making your code more efficient (in the sense it executes faster), just a couple of quick observations/pointers.

Duplicate code like your two identical report() functions should
be avoided.
Your if..else if..else if statement may be better suited as a switch()/case.  Under some conditions, switch() can be more efficient than if/else-if/.. (depending on the javascript engine, etc.)   I should note that developers have been fighting the "switch-vs-if-else-if war for a while now.  https://stackoverflow.com/questions/2922948/javascript-switch-vs-if-else-if-else
Your dice values appear fixed (ie. they do not change).  Perhaps this is as intended, but I would suggest a rollDice() function is missing.
Closures (nested functions, or "functions within functions" if you like) may be a difficult concept for beginners...  It can introduce problems with variable scope that can be difficult to understand/deal with.   Disclaimer:  I am not saying closures are bad, they are powerful - but perhaps overkill for your current purposes, that's all.


Call center escalation excercise, using Chain of Responsibility pattern

Review

Well done, there isn't much I would change in this implementation. I would grant you the humble badge for putting yourself as LowLevel employee :)

The lazy and null pattern are well implemented (except a small issue that could possibly introduce null -> see minor issues). The chain of responsibility looks to be by the book. You've even used a visitor pattern between the handler and the employee. Each specific employee yields different behavior handling a phone call.

Minor issues

IPhoneCall as interface seems overkill to me. This is just a POCO.
Check arguments against null in public entry points such as public PhoneCallHandler(Employee employee).
GetPhoneCall could be written more compact: return _employee.Resolve(phoneCall) || _nextCallHandler.GetPhoneCall(phoneCall);.
RegisterNext should not allow null, as this bypasses your EndOfChainHandler.Instance pattern to avoid null handling.


Optimizing this 'print up to the nth prime number' script

Welcome to programming and code review!

Your code is pretty good especially for a beginner, but I'm going to be picky:

from time import time

I recommend putting at least one blank line between the imports and the code proper

odd = 1

You don't use this until much later. Don't declare variables until you actually need them. It will make the code easier to read.

primes = [2]
n = input("Number of prime numbers to print: ")

Rather than using input, I recommend using int(raw_input(. Input actually interprets the text entered as a python expression which means it can do anything. If you really just wanted a number, using int(raw_input is better. Also, input has been modified in python 3 to be like raw_input.

clock = time()
def isPrime(number):

Typically functions are defined before the actual code not in the middle of it.

    global primes

global is only necessary if you want to modify the primes. Since you don't modify it, you don't need it.

    for i in primes:
        if i*i > number:

It's not immediately obvious why you can stop here. A comment would be helpful.

            return True
        if number%i is 0:

Put spaces around your operators: %

            return False
while len(primes) < n:
    odd += 2
    if isPrime(odd):
        primes += [odd]

When adding a single element to a list use primes.append(odd)

print primes
clock -= time()

That's kinda confusing. I'd suggest doing start_time = .., end_time = ..., time_spent = end_time - start_time. That ways it clear what you are doing, whereas what you've done with the clock is unusual and not immeadiately obvious.

print "\n", -clock
raw_input()

Also, don't put logic in the top level scope of your program. Put all logic especially loops inside a function. It'll run faster in the function, and will keep the program neater.


Project Euler #4 - Largest Palindrome Product

Your function palindrom just "reverses" your number without actually checking it is a palindrom. It would probably be more appropriate to give this function a proper name like reverse_number() and to use it in a different function which can be called is_palindrome().

Please note that a faster implementation for this could be done differently as one could stop as soon as 2 digits do not match but we can consider that this is good enough: it's easy to test and it's easy to understand how it works.

Also, you could get rid of the magic number 10. You could for instance provide the base with a default argument.

You should always try to define your variable in the smallest possible scope.

Here's what I have for the helper function :

int reverse_number(int num, int base = 10)
{
    int new_num = 0;

    while (num != 0)
    {
        int digit = num % base;
        new_num = new_num*base + digit;
        num /= base;
    }
    return new_num;
}

bool is_palindrom(int num)
{
    return num == reverse_number(num);
}

You should compile your code with all warnings activated as they can provide you good hints :

euler3.cpp:28:18: warning: unused variable ‘n’ [-Wunused-variable]

The way you are iterating is super weird. If you want to iterate over a range with n1 and iterate over another range with n2, just use two nested for loops:

for (auto n1 = 999u; n1>=100; n1--)
for (auto n2 = 998u; n2>=100; n2--)

Also, without any loss of generality, one can assume that n1 >= n2 :

for (auto n1 = 999u; n1>=100; n1--)
for (auto n2 = n1;   n2>=100; n2--)

Because the values will get smaller, you can break when you find a value smaller that the one you have already found.

At the stage, my code looks like:

int main()
{
    unsigned int largest = 0;

    for (auto n1 = 999u; n1>=100; n1--)
    {
        for (auto n2 = n1;   n2>=100; n2--)
        {
            auto prod = n1*n2;
            if (prod < largest)
                break;

            if (is_palindrom(prod))
            {
                cout << "n1 << " << n1 << " n2 " << n2 << " -> " << prod << endl;
                largest = prod;
            }
        }
    }
    cout << "Largest" << largest << endl;
    return 0;
}


Logic

I find it counterintuitive that your main loop doesn't look like this:

for (int bottles = limit; bottles >= 0; bottles--) {
    …
}

The way you build the song backwards (with some index arithmetic), followed by two special cases, makes the code hard to follow.

You have a pluralization bug:

2 bottles of beer on the wall, 2 bottles of beer
Take one down, pass it around, 1 bottles of beer on the wall...

You used a special case for SENTENCE_FORMAT_1. Because the text happens to be constant, you call malloc() and strcpy() instead of createCouplet().  I don't recommend doing anything so drastically different. In fact, createCouplet() should be made responsible for choosing the right template to use based on the bottle count, such that the function "just works" for any i.

Memory management

I don't understand the appeal of storing all of the verses in a variable-length array. If you want to have the entire song at once, it would be better to build one huge contiguous string. Alternatively, if you are willing to write a loop that prints each verse (like my countdown loop above), then you don't even need to have the entire song in memory at any given time; you can just work one verse at a time.

In particular, the one-verse-at-a-time approach gives you the option to use one buffer, whose contents are overwritten repeatedly. I would just use a static buffer. In general any design in C that avoids malloc() altogether is highly appealing.

I'm not a fan of the technique you used to calculate the length of the output. It's a very manual process, requiring you to tell it how many numbers appear in the template, and calculating how many digits should be rendered. Rather, what you could do is take advantage of the return value of snprintf(), which tells you how long the output should be — and that technique works in general. (The whole issue would be a moot point with a static buffer: you just generously estimate the required space for any verse.)

Suggested design

  int bottleVerse(int bottles, int init_bottles, char *buf, size_t bufsize)

  This function generates one verse from the song 99 Bottles of Beer on the Wall, writing it to the given buffer.  The output ends with a newline and a NUL terminator.

  Parameters

  bottles: The number of bottles of beer at the start of the verse
  init_bottles: The initial number of bottles (traditionally 99)
  buf: Pointer to a buffer to which the output should be written (possibly NULL, to obtain the output length without writing the output anywhere).
  bufsize: The size of the buffer

  Return value

  On success, a positive value is returned, indicating the length of the string that was written to the buffer.  A negative value indicates the number of bytes by which the buffer is undersized.

This design mimics the pattern followed by many functions in the C library.  The caller is responsible for providing the buffer and its size; the function merely fills it in.  The return value acts as a status indicator.

The memory management is very in-your-face.  It seems more inconvenient to use than your createCouplet().  However, it has many advantages:

This function obviously allocates no memory.  It's very clear what the memory ownership policy is: the caller provides and "owns" the memory.
The caller has the flexibility to provide several kinds of memory:

It could be a static buffer, reused between verses.
The caller could malloc() a buffer.
The caller could append this verse to the previous verse in one huge buffer for the song.

It can avoid some drawbacks of malloc() and free():

malloc() is a mildly expensive operation.
malloc() might allocate memory in non-consecutive chunks, reducing the efficiency of the memory cache.
Allocating many small chunks of memory with malloc() can lead to memory fragmentation, wasting memory.
Forgetting to free() a newly allocated string would cause a memory leak.
Accidentally using memory that has already been free()d could cause a security vulnerability.

Many of these issues are negligible concerns for a tiny program like this.  However, if many functions in a large program were designed to use malloc(), then you would have a chaotic mess.  For these reasons, idiomatic C functions generally have this kind of design where the caller provides the memory.

Here is an example of what the code might look like if you wanted to compose the entire song as one long string.  Using a static buffer to print one verse at a time would result in a slightly simpler program.

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

// Left as an implementation exercise for you, using snprintf()
int bottleVerse(int bottles, int init_bottles, char *buf, size_t bufsize);

int main() {
    const int initBottles = 99;
    char *song, *verse;

    // Overestimate the length by one verse
    // (better than underestimating by one byte!)
    int estimatedVerseLen = -bottleVerse(initBottles, initBottles, NULL, 0);
    int bufsize = estimatedVerseLen * (initBottles + 2) + 1;

    if (NULL == (verse = song = malloc(bufsize))) {
        return 1;
    }
    for (int bottles = initBottles; bottles >= 0; bottles--) {
        int len = bottleVerse(bottles, initBottles, verse, bufsize);
        assert(len >= 0);
        verse += len;
        bufsize -= len;
    }
    fputs(song, stdout);
    free(song);
}


There is nothing overtly incorrect with your code.

However, one thing that makes PHP nice to work with for web development is it's ability to interpolate variables.  When you use double quotes around a string, PHP will interpolate (replace variables with their value).  When you do not want that behavior, then you should use single quotes.  You should also use single quotes to delimit keys in arrays, rather than double quotes, which will also interpolate variables, should they be found.

Here's what I'd do in your case, inside the foreach.

$html .= "

{$post['title']}
{$post['text']}
";

This looks more like html, and doesn't require dropping in and out of the string output or concatenating all over the place.

You might wonder why you need the blocks around the $post array variables.  This is so that you can include the single quotes around the array key without confusing the php parser.  If you were to try this:

$html .= "

$post['title']
$post['text']
";

You'll find you get a parse error.  The block tells php to parse that code and insure it works fine.  You can actually omit the single quotes and the code will parse, but it's better stylistically to always include them when dealing with array keys.  This works without the block.

$html .= "

$post[title]
$post[text]
";

Whilst this might be a micro-optimization, when you omit the single quotes, php has to determine whether or not 'title' or 'text' are actually constants you've defined.  It's also just in general, good practice to always reference variables in the same manner, for consistency and readability.

If you want your html markup to look a bit cleaner, it's also easy enough to add newlines using "\n".

$html = "
\n";
foreach($posts as $post) {
    $html .= "

{$post['title']}
{$post['text']}
\n";

}
$html .= "
\n";

One final note, since this is a code review -- what this code does, is intermix markup and data in a way that they can not be separated.  There is a school of thought in the design pattern world, that data (models) should be pure, and that "views" should be responsible for output.  For example, let's say that you want to provide this same data in json format for an ajax call you're doing someplace else in your code.  This routine is not going to work, because you baked in the html markup.

One of the hallmarks of a spaghetti/php application is rampant intermixing of logic and HTML code, and views are a great way to avoid that from the get-go.

Your code will work, but it inherently has the weakness of intermixing your logic and data with your markup.

Template systems like smarty or twig to name a few (although most all of the PHP frameworks that provide MVC have a template system) encourage you to put your presentation (view) code into separate files.  When it comes time to output your code, you inject the data into the view, and your view code can then create your output.  You can do this in a lot of different ways, including using pure old PHP scripts, and alternative PHP syntax.  I'd encourage you to look at some examples in the manuals of these template/view libraries.

As a simple example, here's how you could have your code in a php "view" file that you could require or include.

/* You might name this file postView.php */
/* You'll start in HTML mode */

<? foreach($posts as $post): ?>

<?=$post['title']?>
<?=$post['text']?>

<? endforeach; ?>

Now your logic looks like:

<?php
// Fill your $post from the $_POST super glob.
// Do whatever other logic you need

// Time for output
require_once(postView.php);


There's an easier way.
We have the num2words module which can be easily installed via pip:
pip install num2words

The advantage of this module is that it supports multiple languages:

en (English, default)
fr (French)
de (German)
es (Spanish)
lt (Lithuanian)
lv (Latvian)
en_GB (British English)
en_IN (Indian English)
no (Norwegian)
pl (Polish)
ru (Russian)
dk (Danish)
pt_BR (Brazilian Portuguese)

More, you can even generate ordinal numbers like forty-second.
A small python example for converting numbers to words using num2words looks like this:
>>> from num2words import num2words
>>> num2words(42)
forty-two
>>> num2words(42, ordinal=True)
forty-second

You can read more about what you can do using this module here

NOTE: In case somebody is wondering why this is not a code review (such as comments on the posted code), is because in the unedited question the author specifically asked if there is already a library for this.


Preliminaries: there's strategy, and there's tactics.
A somewhat common procedure to tackle performance problems is to look at "inner" loops first - not entirely wrong, but the golden rule is
measure.
(And, when turning to others for support, provide measurement results and a test data generator or test data.)

Some statements regarding edit distance:
• difference in length gives a lower bound on insertions+deletions
• accumulated differences in frequency gives a lower bound on 2*replacements+insertions+deletions

Review proper using m = len(str1) and n = len(str2):

Document your code. In the code.
design
• I don't like heavyweight constructors
 From the preparation possible, I'd prefer a constructor taking a set of words and
• a "query function" with a word as a parameter (String rather than char[]) -
 too bad returning a multipart result gets verbose, ugly or both in Java
program against interfaces, not implementations
List<String> closestWords;
dynamicEditDistance()

I can guess what's dynamic about it, but that's an implementation detail; such does not belong in a method name: editDistance()
does not use any instance member: make it static
with "the usual" cost model you don't need a full m×n array
If your edit cost is symmetric (cost(insertion) == cost(deletion) && cost(replace(a, b)) == cost(replace(b, a))), you don't need previous row(s) and previous column(s).
you iterate the first index in the outer loop and the second one in the inner:
That's the sequence I'd arrange initialisation
(I'd even use j in the 2nd loop)

work currently done in ClosestWords():

code the way you think about the procedure/solution
- I'd think w doesn't change, let's get the chars exactly once
 (a nifty language system might be doing this for you)
prefer List.clear() over instantiation
(today,) I'd prefer redundantly checking for minimum distance over repeating the add():

          closestWords = new LinkedList<>();
          closestDistance = Integer.MAX_VALUE;
          char[] chars = w.toCharArray();
          for (String s : wordList) {
            int dist = editDistance(chars, s.toCharArray());
            if (dist < closestDistance) {
              closestDistance = dist;
              closestWords.clear();
            }
            if (dist == closestDistance)
              closestWords.add(s);
          }

A "slightly" weirder approach is to handle words from the word list in order of length, first descending from same length, then above and increasing; terminating both when "more extremal length words" can't possibly have a smaller edit distance.
Trying to avoid duplicating the code now extracted as handleDistance() "in line" got out of hand - not pleased, still.
Don't do like I do (not documenting tally (, words) & init()),
do like I say (better than handleDistance() & query(), still)

    final Comparator<String> tally = new Comparator<String>() { @Override
            public int compare(String l, String r) {
                if (l.equals(r))
                    return 0;
                final int ll = l.length(), rl = r.length();
                return ll < rl ? -1
                    : rl < ll ? 1
                      : l.compareTo(r);
            }
        };
    String[] words;
    void init(Collection<String> allWords) {
        words = allWords.toArray(NOSTRINGS);
        Arrays.sort(words, tally);
    }
    /** handles the distance between one pair of Strings
     *  updating closestDistance and closestWords
     * @param chars chars of the query String
     * @param s String from words
     */
    void handleDistance(final char[] chars, String s) {
        // System.out.println(">>>" + s + '<');
        final int dist = editDistance(chars, s.toCharArray());
        if (dist < closestDistance) {
            closestDistance = dist;
            closestWords.clear();
        }
        if (dist == closestDistance)
            closestWords.add(s);
    }

    /** queries words for lowest edit distance to w
     *  updating closestDistance and closestWords
     * @param w String to find closest words to
     * @return closest words
     */
    public Collection<String> query(String w) {
        final char[] chars = w.toCharArray();
        int sameLength = Arrays.binarySearch(words, w, tally);
        if (0 <= sameLength) {
            closestDistance = 0;
            return closestWords = Collections.singletonList(words[sameLength]);
        }
        closestDistance = Integer.MAX_VALUE;
        sameLength = -sameLength; // insert index + 1
        for (int i = sameLength ; 0 <= --i ; ) {
            final String s = words[i];
            if (closestDistance <= chars.length - s.length())
                break;
            handleDistance(chars, s);
        }
        for (int i = sameLength ; ++i < words.length ; ) {
            final String s = words[i];
            if (closestDistance <= s.length() - chars.length)
                break;
            handleDistance(chars, s);
        }
        return closestWords;
    }


Display the n terms of even natural numbers(between 1 and 100) and their sum

It is neither good nor bad. It does the job: it shows a list of even numbers up to a limit lesser than or equal to 100. But the design or architecture of the program is ugly, even for a small program like this.

Previous it was common to declare all variables at the top of the scope (function or other bracketed section) (and some languages require that), but now in C# it is considered standard to declare the variable when they are used the first time.

  numberOfEvenNumbers = Convert.ToInt32(Console.ReadLine());

This is quick and dirty and will crash the program if the user enters a non numeric string.

So you'll have to check the input and react to an invalid such:

  int numberCount = 0;
  string prompt = "How many even numbers [Enter a number lesser than or equal to 50]: ";
  string errorMessage = "";
  do
  {
    Console.Write($"{errorMessage}{prompt}");
    errorMessage = "Invalid input. ";
  }
  while (!int.TryParse(Console.ReadLine(), out numberCount) || numberCount <= 1 || numberCount > 50);

Here I validate (> 1 and < 100) the input in the UI which is preferable to do compared to validating while running the algorithm.

The header of the question says

  numbers between 1 and 100

(excluding 100) but you iterate potentially up to and including 100:

  while (counter <= 100) { ... }

so what do you really mean?

if (counter % 2 == 0)
{

Even numbers can be found by checking if a number is divisible by 2 as you do, but the sequence of even numbers from 2 and upwards can be found like this:

  for (int i = 2; i <= limit; i += 2)
  {
    Console.WriteLine(i);
  }

in this way you are almost done with one variable (i) and a limit, you just need a sum to sum up with:

// The 6 first even numbers:
int numberCount = 6 * 2;
int sum = 0;

for (int i = 2; i <= numberCount; i += 2)
{
  Console.WriteLine(i);
  sum += i;
}
Console.WriteLine(sum);

So all in all it ends up like this:

static void EvenNumberCount()
{
  int numberCount = 0;
  string prompt = "How many even numbers [Enter a number lesser than 50]: ";
  string errorMessage = "";
  do
  {
    Console.Write($"{errorMessage}{prompt}");
    errorMessage = "Invalid input. ";
  }
  while (!int.TryParse(Console.ReadLine(), out numberCount) || numberCount <= 1 || numberCount > 50);

  numberCount *= 2;
  int sum = 0;

  for (int i = 2; i <= numberCount; i += 2)
  {
    Console.WriteLine(i);
    sum += i;
  }

  Console.WriteLine();
  Console.WriteLine($"Sum: {sum}");
}

But here I do too much in the same method:

The program has 3 steps:

User input
The algorithm
Display of result

This calls for 3 separate methods or functions:

limit = GetCountOfNumbers();
result = EnumerateAndEvenNumbers(limit);
ShowResult(result)

Which could result in something like:

static int GetCountOfNumbers()
{
  int numberCount = 0;
  string prompt = "How many even numbers [Enter a number lesser than or equal to 50]: ";
  string errorMessage = "";
  do
  {
    Console.Write($"{errorMessage}{prompt}");
    errorMessage = "Invalid input. ";
  }
  while (!int.TryParse(Console.ReadLine(), out numberCount) || numberCount <= 1 || numberCount > 50);

  return numberCount;
}

static (int Sum, IEnumerable<int> EvenNumbers) EnumerateAndSumEvenNumbers(int numberCount)
{
  int sum = 0;
  List<int> evenNumbers = new List<int>();
  numberCount *= 2;

  for (int i = 2; i <= numberCount; i += 2)
  {
    evenNumbers.Add(i);
    sum += i;
  }

  return (sum, evenNumbers);
}

static void ShowResult(int limit, int sum, IEnumerable<int> evenNumbers)
{
  Console.WriteLine();
  Console.WriteLine($"The first {limit} even numbers are: ");
  foreach (int number in evenNumbers)
  {
    Console.WriteLine(number);
  }

  Console.WriteLine();
  Console.WriteLine($"Sum: {sum}");
}

static void TestNumberCount()
{
  int numberCount = GetCountOfNumbers();
  (int Sum, IEnumerable<int> EvenNumbers) = EnumerateAndSumEvenNumbers(numberCount);
  ShowResult(numberCount, Sum, EvenNumbers);
}

By the way: The sum of any number n of even numbers from 2 and upwards can be found as: sum = n * (n + 1). This could simplify the above "algorithm" a bit.


Collect maximum fruits in two baskets of at most 2 types of fruits

Your second solution is good and fast, but you asked about more elegant solution, so I am suggesting mine. Firstly, I solved this task by Python, then convert all logic into Javascript. It is a little slower, than your (20 ms) and use more memory, but I think it more straightforward and understandable.

The code only answers do not liked on this site, so I add some comparisons:

Algorithm. Both algorithms are similar but:

Mine: keeps track of every number changing positions. The start1 position changes every time the number was changed, so I always know the position, where the previous number was started. The start2 position changes only when third number occurs, so I just subtract the start2 from the current index and get the needed two number sequence length.
Your: keeps track of last occurrences the first and second numbers, so you miss their start positions, and thus, you should use the count variable for storing the length of the current two number sequence. When the third number appears, you need to calculate the value of the last uninterruptible one number sequence by Math.abs(first - second). Also, you don't know which number was last - first or second, so the Math.abs function is needed.

The way of access to array items.

Mine: uses the iterator - for...of statement and Array.entries(). It relieves us from tree[i] and tree[second] like constructions.
Your: Uses counter and array indexes to access the needed item.

The Javascript code:

var totalFruit = function(tree) {
    let n1 = -1;
    let n2 = -1;

    let start1 = 0;
    let start2 = 0;

    let maxim = 1;
    # Add extra element in the end of array (which is not occured in array)
    # to get rid of the second 'Math.max(maxim, k - start2)' call
    tree.push(-2);

    for (let [k, num] of tree.entries()) {
        if (num !== n1) {
            if (num !== n2) {
                maxim = Math.max(maxim, k - start2);
                start2 = start1;
            }

            n2 = n1;
            n1 = num;

            start1 = k;
        }
    }

    return maxim;
}

The original Python code:

class Solution:
    def totalFruit(self, tree):
        n1 = -1
        n2 = -1

        start1 = 0
        start2 = 0

        maxim = 1
        tree.append(-2)

        for k, num in enumerate(tree):
            if num != n1:
                if num != n2:
                    maxim = max(maxim, k - start2)

                    start2 = start1

                n2 = n1
                n1 = num

                start1 = k

        return maxim


Here is an O(mn) solution.  Given that haystack is about 1000 in length and needle is 5 or smaller, the simplest code to do the search is probably the best.  But if testing for equality is expensive, there are things we can do to mitigate that, although I'm not sure switching to KMP or BM will help so much given that we're dealing with Object here.

// assumes no null entries
// returns starting index of first occurrence of needle within haystack or -1
public int indexOf(final Object[] haystack, final Object[] needle)
{
    foo: for (int a = 0; a < haystack.length - needle.length; a++) {
        for (int b = 0; b < needle.length; b++) {
            if (!haystack[a+b].equals(needle[b])) continue foo;
        }
        return a;
    }
    return -1;
}


Minimum window substring using python containing substr in any order

Overview

Interesting algorithm.  I looked over it and tried to find a bit simpler of a way.    Basically, I implemented the modified version with a dictionary.  The dictionary stores the data in the formation char:index.  Every time we run into a relevant character we update the dictionary.  This eliminates all need for back tracking via trim_left. Every time we updated our dictionary of character locations, we would get a string by finding the min and max of the dictionary. If that string is smaller, then we assign it to the smallest variable.

Performance

Typically the newer version performs a lot faster.  This can be explained by referring to big O notation.  Yours, because of back tracking, performs at O(n^2) or worse. However, the newer version doesn't back track so much, and it sticks to only modifying one dictionary so the new version worst case scenario is O(n) efficiency. (Or, to be more specific, it is O(nm) where n is the length of your string and m is the length of the substring; however there is a very logical limit to the length of substring m, so it will probably never be worse than O(64n) [note: we convert the string to a set to remove duplicates]).

New Code

def newShortest(subString, string):
  myChars = set(subString)
  smallest = ""
  current={}
  for i, char in enumerate(string):
    if char in myChars:
      current[char] = i
      if len(current) == len(myChars):
        temp = string[current[min(current,key=current.get)]:current[max(current,key=current.get)]+1]
        if len(temp) < len(smallest) or len(smallest) == 0:
          smallest = temp
  return smallest

Code used to time your version vs modified version

I switched out the args for smaller and larger sizes:

import time

args = ["hello","I would like to all over you hehhhhhkkkkkkkkkklo"]

def timeIt(func,args):
  then = time.time()
  for _ in range(10000):
    func(*args)
  print("{} timing: {:.2f}".format(func.__name__, time.time()-then))

timeIt(newShortest,args)
timeIt(get_shortest_unique_substring,args)


Checking the status of a website by hitting a PHP script

When you say checkStatus($domain), the parameter should either be actually just a domain (without protocol identifier), or you should just specify the full URI. When in doubt, you shouldn't hardcode /transponder.php.

As for the task of status monitoring - testing the database connectivity is certainly not wrong, but keep in mind that far more can go wrong. If you really want to check if the site is working, don't test against a minimal test script, but a real page of that site. Preferably one which does involve as many systems as possible, and check if the output is the expected.

Why? As I said before, there are more possible errors than just the database connection. Commonly you can also run into problem with the session storage, failing server side caches (APC, memcached and alike), resource shortages (e.g. PHP going OOM), and various more.

You should probably also record response times, not only response status. If your server fails to respond timely, it's a warning sign that you should react to immediately before there is a complete outage.

Last, but not least, don't just test a single status page. If you have access to it, rather check the error logs if there were any events in the past interval. Especially during load spikes, not necessarily every request is going to fail. But an accumulation of failures can be easily read from the logs, and should be dealt with. Make sure your application does log warnings and errors properly.


How to put a lot of information in the class?

Please provide some more information, like the example contents of $infos. It is hard to find any other solution if we are not able to understand your current solution in the first place.

However, there already are some issues with your code:

avoid using variable names like $i and $k. They should be named according to their meaning (see example for $k)
$i seems not to be read in your code
$k and all arrays seem to be used uninitialized

Your while loop seems a bit too clever to me. All you want to do is iterate $k so you should instead use a for loop:

for($childIndex = 0; $size = $sizes_info->children($childIndex); ++$childIndex)
    $sizes_arr[] = $size->plaintext;

The foreach loops look as if they could be better implemented by array_map:

$item_infos = $infos->find('.products-list-item product-label, .products-list-item .products-list-item__brand, .products-list-item .products-list-item__type,.products-list-item .price');
$get_plaintext = function($item_info) { return $item_info->plaintext; };
$item_info_arr = array_map($get_plaintext, $item_infos);

A foreach loop could be as readable however then you should at least use named variables (like $item_infos but with better names (I have no idea what this find returns)) to keep the head of the loop short and readable.


Some suggestions:

Rewrite the line of code app.get(['/bio', '/contact', '/login', '/works', '/404', '/bug', '/edit-bio', '/edit-works'] ... to be readable and maintainable and debuggable.  It should likely be broken into at least two separate routes.
Separate into different route definitions the paths that care about calling verify() and the ones that don't.
Use express.static for routes that don't appear to have any special processing such as ['/bio', '/contact', '/login', '/works', '/404', '/bug'].
Use res.sendFile() instead of repeating this err ? res.status(500).end() : res.end(data) over and over again.
Put your verify logic into a middleware format so it can easily be attached to any route.


It took me a while to realize that you must be considering a poll to be a single question (posted on a web page) that allows people to pick from a series of options for that single question.

Some things to consider:

[options] Consider reversing the index field order. It would seem probable that you will want to query up the options for a poll without specifying the option_id.
[questions] There appears to be no real point to indexing the deleted bit. When pulling questions up for a poll you can certainly exclude those that are deleted without needing an index.
[votes] I'm guessing that 'nick' is the login name of the user choosing an option from a single question poll?
Look at an explain to see if MySQL has optimized your sub-query into a single lookup. If not, do your own explicit query or consider using group by modifiers to do a rollup when you pull up poll stats. Then, in either case, as you load records for a poll (as you'll have some code for web display purposes) do the percentage calculation as you generate the output table.

Finally, it is customary to "select count(*) from tab" when you don't care about the columns involved.


Most common letter in string, trying to use idiomatic Ruby

Your solution has common code smell: A block that modifies closed over variables (i.e. your block has side-effects, which should be avoided).

The code is also quite inefficient. For each character in a string, you loop through the entire string in an inner loop - even if you've done it for that letter already. E.g. a string like "aaa" will be doing a lot of unnecessary work. Besides, you could get the number of occurrences with some_string.count(some_letter).

It would be much better to run through the string once, and count letter occurrences by adding them, one by one, to a hash, and when seeing a letter you've seen before, incrementing its count. After that you have each letter and its number of occurrences, making it simple to pick out the most common.

In terms of style, that and line is... not very nice at all. You seem to be insisting on post-fixing conditionals (i.e. ... if x). And that'd be ok for small stuff, like x += 1 if y. But here, you have two separate lines of code, and you're glueing them together with and instead of just, well, using two lines:

if letter_count > most_common_letter_count
  most_common_letter = letter
  most_common_letter_count = letter_count
end

The and operator has its place, but it isn't this. You should read up on it.

For your second question: No, #delete does not alter the string. It returns a new string without the parts you asked to have deleted.

Anyway, an overall much more Ruby'esque approach would be something like this:

def most_common_letter(string)
  string
    .gsub(/[^a-z]/, '')  # remove non-letters
    .chars               # get characters
    .group_by(&:itself)  # group them
    .map { |letter, list| [letter, list.count] } # get their counts
    .max_by(&:last)      # get the most common letter and its count
end

It will return nil where yours returns [nil, nil] for an empty string. I prefer the former, rather than getting a array that has to be inspected more closely to see if it contains anything. But if the method should always return an array, you can do this:

def most_common_letter(string)
  most_common = string
    .gsub(/[^a-z]/, '')  # remove non-letters
    .chars               # get characters
    .group_by(&:itself)  # group them
    .map { |letter, list| [letter, list.count] } # get their counts
    .max_by(&:last)      # get the most common letter and its count
  most_common || [nil, nil]
end


Filtering a dictionary by subject of definitions

Updated answer:

Thanks for clarifying the question, the examples helped. Here is my new attempt:

(defn update-subjects [dict subj]
  (map (fn [[k {val :definitions}]]
         [k {:definitions
             (filter (fn [{s :subject}]
                       ((into #{} (flatten [s])) subj)) val)}]) dict))

(defn my-filter [dict subj]
  (into {} (->> (update-subjects dict subj)
                (remove (comp empty? :definitions second)))))

(= (my-filter dictionary "IT") (filter-by-subject dictionary "IT"))
=> true

in this solution, I first remove all the definitions which subjects do not match, and then I remove all the entries with empty definitions. I used the threading macro (->>) for readability.

original answer:

Here is another way of implementing your subject filter:

(defn subject-filter [p m]
   (filter (fn[[k {v :definitions}]]
               (some (fn [{x :subject}]
                        ((into #{} (flatten [x])) p)) v)) m))

This implementation makes use of two important features:

Destructuring - an idiomatic method of extracting items from a data structure in clojure. I highly recommend keeping the following link handy at all times http://blog.jayfields.com/2010/07/clojure-destructuring.html
Sets as a predicate - in clojure, if a set is in a function position, it acts as a function that returns true iff the first argument is in the set. So it is very idiomatic to write (if (#{1 2 3} i) .. ..) to know if i is either 1, 2 or 3. Perhaps you could even use sets instead of arrays in your data definition for :subject, which will make this code even shorter and faster, and your DS more "correct" - you could never keep two identical subjects and :subject will be a predicate of a query subject.

Just a note, you could also do without so much destructuring, and get a more concise function:

(defn my-filter [p m]
   (filter (fn[[k v]] (some (fn [x] ((into #{} (flatten [(:subject x)])) p)) (:definitions v))) m))


There are some improvemants possible but they are rather of technical nature then about performance as I don't think you can do much about it until you have measured it either with benchmarks or a profiler.

products.Data.AsEnumerable()

This looks like you are working with a DataTable, aren't you? If the data comes from a database then you should group it on the server.

CodigoServico = int.Parse(string.IsNullOrEmpty(x["CodigoServico"].ToString()) ? "0" : x["CodigoServico"].ToString()),
CodigoPeca = int.Parse(string.IsNullOrEmpty(x["CodigoPeca"].ToString()) ? "0" : x["CodigoPeca"].ToString()),
CodigoFamilia = int.Parse(string.IsNullOrEmpty(x["CodigoFamilia"].ToString()) ? "0" : x["CodigoFamilia"].ToString()),

You should create a helper extension or function for such lines, it's pretty ugly to repeat it so many times. Even two times is already too many.

.GroupBy(x => new { x.CodigoPeca, x.CodigoFamilia, x.Familia, x.Peca })

You are grouping by the same properties as the object has that you create in the next step:

Produto = new Produto
{
  CodigoPeca = x.Key.CodigoPeca,
  CodigoFamilia = x.Key.CodigoFamilia,
  Familia = x.Key.Familia,
  Peca = x.Key.Peca
},

Instead of doing this twice you should implement the IEquatable<Produto> interface on this object and use this instance as a key so that you only have a single new.

Servicos = x.Select(y => new ProdutoServico
{
  CodigoServico = y.CodigoServico,
  Hash = y.Hash,
  Servico = y.Servico,
  Valor = y.Valor
}

You can replace this with Servicos = x if you use another overload of GroupBy and project each item right away.


Code improvement suggestions for cost calculation

The first thing that would benefit this code, beside removing the useless initialization for cost, is to save the models.OperatorCostAsia.objects.filter(country=country_code) queryset for reuse instead of rebuilding it each time. It feels easier to understand and filtering twice is identical to using two parameters in a single filter anyway:

def get_cost_by_location(country_code: str, city=None) -> Optional[models.OperatorCost]:
    asian_country = models.OperatorCostAsia.objects.filter(country=country_code)
    if asian_country.exists():
        cost = asian_country.filter(city__icontains=city).first()
        if cost is None:
            cost = asian_country.first()
    else:
        cost = models.OperatorCost.objects.filter(country=country_code).first()

    return cost

Now there are a few other changes that I would perform but these may change the behavior of the function so it's a bit of guessing territory on how you use this function.

For starter I would use iexact instead of icontains when searching for the city name, it feels less error prone.

Second, I would use .get(...) instead of .filter(...).first() when applicable to check for wrongly constructed inputs that would return more than the one result they are expected to return:

def get_cost_by_location(country_code: str, city=None) -> Optional[models.OperatorCost]:
    asian_country = models.OperatorCostAsia.objects.filter(country=country_code)
    if asian_country.exists():
        try:
            return asian_country.get(city__iexact=city)
        except models.OperatorCostAsia.DoesNotExist:
            return asian_country.first()
    else:
        return models.OperatorCost.objects.get(country=country_code)


Here are some comments/notes about the code and potential improvements:

use with context manager when opening files
parsing HTML with regular expressions has always been a very controversial thing to do. I would switch to an HTML parser like BeautifulSoup and lxml.html. For example, getting all the PyPI links with BeautifulSoup can be as straightforward as:

from bs4 import BeautifulSoup

with open('list.html') as directory:
    soup = BeautifulSoup(directory, "html.parser")
    for link in soup.select("a[href*=pypi]"):
        print(link.get_text())

where a[href*=pypi] is a CSS selector that would match all a elements that has pypi substring inside an href attribute.
instead of using requests.get() directly, initialize a "session" to reuse the underlying TCP connection:

  ..if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase..

If you want to scale this up, you would need to switch for a synchronous and blocking code/approach to asynchronous - look into using Scrapy web-scraping framework which is based on the twisted networking library.


Specific suggestions

Using command-line arguments is the idiomatic way to collect input. This makes the code scriptable and reusable as a library.
The idiomatic way to run main is this:

if __name__ == "__main__":
    main()

Several bits of code are duplicated, such as min(teamG_beybladePowers). Pull those out into variables to avoid re-iterating through the whole list more than necessary.

Tool support suggestions

black can automatically format your code to be more idiomatic. It'll do things like adjusting the vertical and horizontal spacing, while keeping the functionality of the code unchanged. In your case the code does look decently formatted, so it may not change much (or at all).
flake8 can give you hints to write idiomatic Python. I would start with this configuration:

[flake8]
max-complexity = 4
ignore = W503,E203


As there's not all that much code here to review, I've reviewed some style points:

You have some strange use of whitespace throughout your code:

handleOnClick(key, event) {

    event.preventDefault();

    this.setState({
        activeIndex : key
                // ^-- whitespace shouldn't be before a property colon
    });
}

and not necessarily that it's wrong, but there's a lot of empty whitespace lines that make your program look a lot beefier than it should.

child.props.active === true ? true : (active == index++)

You don't need to compare properties to booleans as simply specifying the variable without comparison performs a boolean comparison:

var thing = true;
console.log(thing === true ? 1 : 2); // identical
console.log(thing ? 1 : 2);          // identical

You've also got some inconsistency in your use of semicolons:

constructor() {

    super();

    this.state = {
        activeIndex : 0
    }
}


Well you can use typeid.

printf("%zu", typeid(MyFirstClass).hash_code());

Not sure how

TypeIdentifier::get_identifier<MyFirstClass>()
     //                       ^^^^^^^^^^^^    Compile time type.
     //  This will not help with runtime
     //  type checking.

is going to help you.

Assuming the above is in a single header file (because of include guards).

Then this:

Identifier TypeIdentifier::next_identifier = 0;

Is in the wrong place. It will be defined for every compilation unit that includes the header. Personally I would use a function rather than a static value.

class TypeIdentifier {
public:
    template<class T>
    static Identifier get_identifier() {
        static const Identifier current_identifier = getNext();
        return current_identifier;
    }

private:
    static Identifier getNext() {
        static Identifier next_identifier = 0;
        return next_identifier++;  //
    }
};


Sum Of Two Arrays element by element and arrays can be of unequal length

Instead of reviewing your code as is, I'll propose an alternative solution that should be a tad simpler than yours:

We don't need to know which array of the two is the larger, we only need our result array to be able to contain it:

int[] result = new int[Math.max(arr1.length, arr2.length) + 1];

Note that we need an extra element to adjust for possible "overflow" (aka. carry in the last added digit).

Now since we need to sum things, let's just copy over one of the two arrays into our result:

System.arraycopy(arr1, 0, result, result.length - arr1.length, arr1.length);

Now the only thing that remains to be done is doing the addition with the other array. We'll need something to store the carry in. Luckily by nature of a carry, it's maximum value is always 1 (it seems you didn't notice that). So we either have a carry-flag or not:

boolean carry = false;

Now let's walk the other array, and perform the addition. Note that I use the conventional iteration indexing \$\{1,\ldots,length-1\}\$ instead of the backwards indexing you used to simplify the reasoning in the addition:

for (int i = 0; i < arr2.length; i++) {
    int digitResult = result[result.length - 1 - i] + arr2[arr2.length - 1 - i];
    // usually you'd write this on properly separate lines
    if (carry) { digitResult += 1; }
    if (digitResult >= 10) {
        carry = true;
        digitResult -= 10;
    } else {
        carry = false;
    }
    result[result.length - 1  - i] = digitResult;
}

This was the "interesting part" already. The only thing remaining to be done is cleaning up a possibly remaining carry:

int i = arr2.length;
while (carry) {
    int r = result[result.length - 1 - i] + 1;
    if (r >= 10) { // could also be == 10
        r -= 10;
    } else {
        carry = false;
    }
    result[result.length - 1 - i] = r;
    i++;
}

Theoretically we might need to check the array access, but it's mathematically provable we don't need to, so I won't do checks. An explanatory comment could help for doing that.

Now as Timothy Truckle already mentioned in his answer your method is responsible for too many things. You should at this point just return the result array to the caller, and that's the extent of the method.

There's some repetition and "uncleanliness" in this code, that I left in on purpose. I'm pretty sure with some thinking you should be able to clean the code up a bit, and it's hard to learn it just from a person telling you what's wrong. Find out :)


Handling shared state between actix and a parallel thread

Answering your questions:

Depends on the nature of the error.

Panics will make the thread exit. If the creator called join on the result of thread::spawn, the result of that join will be Err(boxed_any). The boxed_any is the argument given to panic!. This is one common way to signal and handle an error.
If the panic occurs while a mutex's lock is in scope, the mutex will be poisoned and therefore return Err for all locking attempts on all threads indefinitely.
In case you'd like to notify another thread about an event, let's say, an occurence of a meaningful error, it's best to use channels. You can read more in "Using Message Passing to Transfer Data Between Threads": https://doc.rust-lang.org/book/ch16-02-message-passing.html

I'm not sure what you meant by exiting cleanly. You need the thread to run indefinitely. The thread will exit "cleanly" when the server is closed (and so when the main thread exits).

Minor points:

calls to Arc::clone can be simply .clone(). Quoting the docs:

// The two syntaxes below are equivalent.
let a = foo.clone();
let b = Arc::clone(&foo);

the second (and last) data.clone() is unnecessary. This is often seen in code. Just pass the value.

You still have ownership of that original value. That original value can be spent by passing it to actix.

-> () in a function signature is never meaningful; just cut it out.


Finding answers where happy customers commented "thanks"

Answers

Your Answers CTE is convenient, but it should be doing a lot more of the heavy lifting for you, and it is also over-generous with the selection.

Your intention is to report on answers for the specified user (UserID or Display Name). You should be filtering those answers out immediately. Also, the inner join to the Users table is just for the display name is a problem too. Also, there's a little trick with CommunityWiki or a couple of other posts types, where the DisplayName is actually populated on the Post table.

So, your Answers CTE is:

Answers AS (
  SELECT * FROM Posts WHERE PostTypeId = 2
)

I would make it do all the heavy lifting, as:

Answers AS (
  SELECT Id,
         OwnerUserId
  FROM Posts
  WHERE PostTypeId = 2
    AND (@userId < 0 OR OwnerUserId = @userId)
    AND (@username = '' OR OwnerUserId in (
        SELECT Id
        FROM Users
        WHERE DisplayName = @username))
)

With that CTE, the only answers returned are ones that are valid for the input conditions on who to report for.

Note that it only selects the two columns needed for the remainder of the query.

Selection

Your column selection returns the Comment text twice, once as a link, and again for the text. In some conditions this is useful (like getting the data as a CSV report) but I don't believe this is the intention here. Additionally, you do not report the actual User who created the answer either. I would find that useful.

SEDE allows you to return the Id for the user, but display the name (as a link). Your regular join to the Users table is not necessary for that.

So, with the previous Answers CTE, I would have the much simpler final selection as:

SELECT TOP ##Limit:int?100##
  a.Id AS [Post Link],
  c.Id AS [Comment Link],
  a.OwnerUserId as [User Link],
  c.CreationDate as [Comment Date]
FROM Answers a
  INNER JOIN Comments c ON a.Id = c.PostId AND c.UserId != a.OwnerUserId
WHERE LOWER(c.Text) LIKE '%thank%'
  AND (
    @SpecialThanks <= 0 OR (
      LOWER(c.Text) LIKE '%excellent%'
      OR LOWER(c.Text) LIKE '%awesome%'
      OR LOWER(c.Text) LIKE '%awesum%'
      OR LOWER(c.Text) LIKE '%awsum%'
      OR LOWER(c.Text) LIKE '%wonderful%'
      OR LOWER(c.Text) LIKE '%fantastic%'
      OR LOWER(c.Text) LIKE '%amazing%'
      OR LOWER(c.Text) LIKE '%great%'
      OR LOWER(c.Text) LIKE '%best%'
      OR LOWER(c.Text) LIKE '%impressive%'
      OR LOWER(c.Text) LIKE '%master%'
      OR LOWER(c.Text) LIKE '%guru%'
      OR LOWER(c.Text) LIKE '%wizard%'
      OR LOWER(c.Text) LIKE '%ninja%'
      OR LOWER(c.Text) LIKE '%grateful%'
      OR LOWER(c.Text) LIKE '%appreciat%'
      OR LOWER(c.Text) LIKE '%by far%'
      OR LOWER(c.Text) LIKE '%!!!%'
    )
  )
ORDER BY c.CreationDate DESC

Observations

Note that your query (and my suggestion above) will return the answer multiple times if there are multiple 'thank you' comments.

I would consider adding a join back to posts to only consider comments made by the owner of the question that was answered too. At the moment, anyone can add a 'thanks' comment to any post, and make that answer appear.

Joining back to the questions would also allow you to remove closed questions as well.

In general, the code style is consistent, and that's always good.

I considered recommending an in-memory table containing the values to search for in the comments, something like:

create table @words (
    word NVarchar(50)
)

insert into @words values
    ('awesome'),
    ('amazing'),
    .....

and then using that in a join like:

AND INDEXOF(LOWER(text), word) >= 0

but that will produce even more duplicates if the comment is something like:

  Amazing answer, Thanks!!! That was awesome.

It could be cured with a 'distinct', but I am not sure it's worth it.


Long-term archiving + encrypting shell script

It's a fine script. Even shellcheck doesn't find anything in it. Well done!

I only have minor comments.

You can safely omit the sha512sum -c.
It would only fail if the previous command failed.
For the rest, I cannot say it's complete paranoia.

The password file used with openssl commands is buried in the script and repeated twice.
It would be better to put that value in a variable and define at the top of the file.

A helper function would be more convenient to print the headers for the steps, instead of blocks of echos.

  before I take another step and restructure it with printf and better error reporting, structure, exit codes, etc. I would like you to have a look first

I don't see what benefits printf will bring,
and the error reporting, structure, exit codes look just fine.

I would rename bold_red and bold_yellow to be more about the purpose than presentation.
Like <em> in HTML is for emphasis,
and <strong> for strong emphasis,
And the stylesheet (in this case the actual value of the variables) define the presentation, nicely segregated from the code.


Generating all 6-digit palindrome numbers in C++

I have checked your "brute force" algorithm and though it solves the problem (I have not run it to check), it will have to deal with a lot of work. Why not narrowing the problem a bit? What do we know about palindroms? They read the same from left to right than from right to left.

So if we use that and the fact that our palindroms are six digits long, we would only have to generate all the combinations for the first three digits, then make sure the next three are the same reversed. So:

for( int iter=100; iter<=999; iter++ ) {
  stringstream ss;
  ss << iter;
  string pal1 = ss.str();
  string pal2 = pal1;
  reverse(pal2.begin(), pal2.end());

  cout << pal1 << pal2 << endl;
}


How to break up long lines of code. (Example Line: Results of method call added to list.)

I would break it up something like this:

shippedItems.AddRange(
    OrderItem.Fetch(market: this.MARKET,
                    shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,
                    orderPlacedAfter: serverTime.AddDays(-7),
                    orderPlacedBefore: serverTime.AddHours(-85)));

Depending on previous indentation, some lines might flow over the "max line length", but I think that characters per line is more of a suggestion and there are good times to break that rule because breaking it leads to code that is more readable than code that doesn't.

Rules that I find helpful:

New line after an open paren.
Line breaks after commas.
Indent the inner method calls.
Line up parameters to a method that are on new lines.
Break "max line length" rules if it means the code is more readable.


Optional base class template to get conditional data members

I only have a few comments. First, you probably want to inherit your bases privately:

template<class T>
class Test
:
    private Base0, // unconditional base class
    private xstd::optional_base<Trait1_v<T>, Base1>,
    private xstd::optional_base<Trait2_v<T>, Base2>
{ };

After all, your design is about adding data members. That's something that you probably don't want to expose to the outside world.

Secondly, what happens if you want to potentially have multiple different members of the same type? That's definitely going to come up and so should be supported. In order to do that, you might want to add some kind of ID to differentiate them and then additionally wrap the non-empty case. That is:

template <class, int >
struct empty_base { ... }; // same as before

template <class T, int >
struct wrapped {
    T val;
};

template <bool Condition, class T, int UniqueID = 0>
using optional_base = std::conditional_t<Condition,
                                         wrapped<T, UniqueID>,
                                         empty_base<T, UniqueID>>;

This will additionally let you use non-class types as optional data members (since you couldn't inherit from, e.g. int). So you can now do something like:

template <class T>
class Test
: private xstd::optional_base<Trait1_v<T>, int, 0>
, private xstd::optional_base<Trait2_v<T>, int, 1>
{ ... };

That adds an inconvenience that you have to explicitly add the sequence 0, 1, ...

You can get around that by making a linear inheritance list of all your optional bases. I'm not sure if it's worth it, but I'll present the idea just as an option. At its core, we have OptionalBasesImpl which will inherit from all the optional bases and provide a getter so that the derived class can actually use them:

template <typename... >
struct typelist { };

template <int, typename... >
struct OptionalBasesImpl;

The root case is empty:

template <int ID>
struct OptionalBasesImpl<ID>
{
    OptionalBasesImpl() = default;
    template <typename... Args>
    OptionalBasesImpl(Args&&... ) { }

    void get(typelist<> ) { }
};

And we recurse over each pair of type trait/type:

template <int ID, typename Cond, typename T, typename... Rest>
struct OptionalBasesImpl<ID, Cond, T, Rest...>
: private xstd::optional_base<Cond::value, T, ID>
, OptionalBasesImpl<ID + 1, Rest...>
{
    using Base = xstd::optional_base<Cond::value, T, ID>;
    using Root = OptionalBasesImpl<ID + 1, Rest...>;

    OptionalBasesImpl() = default;

    template <typename Arg, typename... Args>
    OptionalBasesImpl(Arg&& a0, Args&&... args)
    : Base{std::forward<Arg>(a0)}
    , Root(std::forward<Args>(args)...)
    { }

protected:
    using Root::get;

    // by conditional/type pair
    Base& get(typelist<Cond, T> ) { return *this; }
    Base const& get(typelist<Cond, T> ) const { return *this; }

    // by index
    Base& get(std::integral_constant<int, ID> ) { return *this; }
    Base const& get(std::integral_constant<int, ID> ) const { return *this; }
};

Now we just have the top-level class to start us off at 0:

template <typename... T>
struct OptionalBases : OptionalBasesImpl<0, T...> {
protected:
    using OptionalBasesImpl<0, T...>::OptionalBasesImpl;
    using OptionalBasesImpl<0, T...>::get;
};

which lets you write something like:

template <typename T>
struct Test
: private OptionalBases<std::is_integral<T>, int,
                        std::is_same<T, int>, int>
{
    using Bases = OptionalBases<std::is_integral<T>, int,
                        std::is_same<T, int>, int>;
    using Bases::Bases;

    void printFirst() {
        std::cout << Bases::get(typelist<std::is_integral<T>, int>{}).val << std::endl;
    }

    void printSecond() {
        std::cout << Bases::get(std::integral_constant<int, 1>{}).val << std::endl;
    }
};

int main() {
    Test<int> t{1, 2};
    t.printFirst();
    t.printSecond();
}

That's a lot of extra boilerplate for just avoiding writing a sequence of integers, so YMMV.


This code looks pretty clean to me. Here are a few thoughts:

I'm not sure what your ORM is (or even that City is database backed), but most have a way to fetch more then one record at a time. Making a single call will save time and Database resources.

Another thought is that you are inducing a lot of local vars: city_ids, city, cities. What about trying to build up the array of ids in params[:package][:cities]? e.g.

#if cities is not an array, it is bad date get rid of it.
params[:package].delete 'cities' unless params[:package][:cities].kind_of? Array
params[:package][:cities] ||= []
params[:package][:cities] << (params[:package].delete 'city') if params[:package][:cities].to_i > 0
params[:package][:cities] = params[:package][:cities].map{ |c| City.get(c) }.compact

The code above doesn't seem very DRY because it has all this params[:package] stuff.  If you do things like this a lot (your question makes it sound like you do) factor the operation out into a separate method:

def extract_nested_reference(hash,values) # change name as appopriate
  if hash
    hash.delete values unless hash[values].kind_of? Array
    hash[values] ||=[]
    hash[values] << hash[values.singularize] if hash[values.singularize].to_i > 0

    hash[values] = hash[values].map do |x|
      Object.const_get(values.singularize.constantize).get(c)
    end.compact
  end
end

This method could then be called with extract_nested_reference(params[:package],'cities'). Refactoring like this will also encourage you to be consistent in how you build you params hash, and allow you to reuse code.

Finally, your question asked about better ways of dealing with hashes.  I don't think there is.  You will find code very similar to this living in most popular gems.  AS you say, it is kind of clunky, and therefore and excellent candidate for a code redactor.


Find a positive integer within range using only elementary operations

My first thought was to try a binary search but was stumped because I can't use floor/ceil.

I'm not sure why you thought that would matter.  Once you have a maximum number, all you need is to divide the difference between max and min in half and add it to min on each iteration.  Here's a simple example that works for your test case.  It might need tweaking for some edge cases.
const int MAX_SECRET = 400000;
public static decimal Find()
{
    decimal max = MAX_SECRET;
    decimal min = 0;
    while(max - min > 0)
    {
        decimal temp = ((max - min) / 2) + min;
        if(BlackBox(temp,"=="))
        {
            return temp;
        }
        if(BlackBox(temp, "<"))
        {
            max = temp;
        }
        else
        {
            min = temp;
        }
    }
    return max;
}

EDIT
Did some more thinking on the efficiency of this algorithm.  The problem mainly stems from using a decimal to represent an int.  A decimal doesn't want to do integer math.  One way around this is, to use the rounding functionality when the maximum precision is exceeded, to make a floor function.  This greatly reduces the iterations to find the target number.
Here's one way that uses the max precision of C#:
const int MAX_SECRET = 400000;
public static decimal Find()
{
    decimal max = MAX_SECRET;
    decimal min = 0;
    decimal count = 0;
    while(max - min > 0)
    {
        decimal temp = floor((max - min) / 2) + min;
        if(BlackBox(temp,"=="))
        {
            return temp;
        }
        if(BlackBox(temp, "<"))
        {
            max = temp;
        }
        else
        {
            min = temp;
        }
    }
    return max;
}
const decimal MAX_PRECISION = 10000000000000000000000000000M;
static decimal floor(decimal num)
{
    decimal temp = (num / MAX_PRECISION) * MAX_PRECISION;
    if(temp > num)
    {
        --temp;
    }
    return temp;
}

This cuts the iterations down to the same level as using int's instead of decimal's.  To use this in a different language the MAX_PRECISION constant may need to adjusted.


One thing you can improve on is the getting of the absolute value. In some browsers, bitwise absolute is faster than Math.abs. But it depends on the browser's implementation.

//bitwise absolute
function abs(n){
  return (n^(n>>31))-(n>>31);
}

You could also factor this part out into a variable for readability. The result of this is a boolean. The explanation will be in the next part:

//foo true if less than or equal to 0, false if greater
var foo = dist - (c1.getR() + c2.getR()) <= 0;

Also, in this bit of code, since done and invinc are boolean, there's no point comparing them to true and false. You can use them directly in the condition.

if (done === false && invinc !== true) //when false, and not true (false)

if (!done && !invinc)                  //when not true (false) and not true (false)

In JS, assignment operations "spill left". You can do the following, assigning true to done and "spill" the same value over to game_over.

game_over = done = true;

Also, due to the structure of the code, the previous only happens when our condition assigned to foo is less than or equal to zero or true. So let's modify the condition to this:

if(foo && !done && !invinc) game_over = done = true;

So in the end, your code will look like this:

var dx = Math.abs(c1.getcx() - c2.getcx());
var dy = Math.abs(c1.getcy() - c2.getcy());
var dist = Math.sqrt((dx * dx) + (dy * dy));
var foo = dist - (c1.getR() + c2.getR()) <= 0;

if (foo && !done && !invinc) game_over = done = true;


Loop to extract json from dataframe and storing in a new dataframe

Finally I got an amazing improvement thanks to stack overflow, regarding two things:
https://stackoverflow.com/questions/10715965/add-one-row-to-pandas-dataframe
https://stackoverflow.com/questions/37757844/pandas-df-locz-x-y-how-to-improve-speed

Also, as hpaulj pointed, changing to json.loads slightly increases the performance.

It went from 16 hours to 30 seconds

row_list = []

for i in range(len(df)):
    dict1 = {}
    dict1.update(json.loads(df.at[i,'raw_content']))
    row_list.append(dict1)

df1 = pd.DataFrame(row_list)

df2 = pd.concat([df['email_id'],df1],axis=1)


Add user star function triggering PHPmailer email optimisation

Lock the UI until a response comes back (or a reasonable timeout
occurs) to prevent the multiple clicking.
Don't send emails directly from the code, push them to spool or MQ and process separately

As for the code itself - there's nothing much to comment except that it's completely out of touch with modern best practices in PHP world. Consider using a proper framework, ORM or at least a DBAL. See phptherightway for more details.


Saving the Universe - Code Jam 2008 Qualification problem A

#Feels wrong having four prints

Indeed.

    print "Case %d: %d" % (i, solve(inFile))

is good enough.
#Feels wrong but queue=set(temp) doesn't work

Yes. The set constructor requires an iterable. Consider queue = set([temp]).
#Feels wrong doing this one at a time

I don't think you can do anything about this. As a side note, what really feels wrong is that these parts of the test cases are totally irrelevant to the solution; only the number of engines really matter. Kudos for realizing this.

As usual, a no naked loops principle dictates to factor this loop out into a function:

    def discard_names_as_useless(inFile, S):

Naming

Q and S only make sense for those who read the problem statement. Consider instead something like number_of_queries and number_of_engines.
import fileinput

Using fileinput seems like an overkill. It is only useful if you need to process multiple files in a row. In this case an unadorned raw_input() would work just fine.
PS

Be careful describing the problem statement. Your description

  The program should return the minimum number of batches required.

raised an immediate red flag: this code must be off-by-one. I had to read the original to realize that they ask for the number of _engine switches__.


Converting strings into lists of characters, then reassembling strings, is quite wasteful of memory. The usual implementation technique for this function should be to scan for the character you're looking for, and then use substring to extract the substring.

However, as the OP correctly points out, in R7RS, string-ref should be avoided because it's O(n). The only sensible fast solutions involve string cursors (which are not portable) and string ports. The below implementation uses the latter:

(define (string-split str delim)
  (define in (open-input-string str))
  (let recur ((out (open-output-string)))
    (define c (read-char in))
    (cond ((eof-object? c)
           (list (get-output-string out)))
          ((char=? c delim)
           (cons (get-output-string out)
                 (recur (open-output-string))))
          (else
           (write-char c out)
           (recur out)))))

That's a left-unfolding (non-tail-recursive) solution. It's easy enough to adapt to a right-unfolding solution using an accumulator:

(define (string-split str delim)
  (define in (open-input-string str))
  (let loop ((rv '()) (out (open-output-string)))
    (define c (read-char in))
    (cond ((eof-object? c)
           (reverse (cons (get-output-string out) rv)))
          ((char=? c delim)
           (loop (cons (get-output-string out) rv)
                 (open-output-string)))
          (else
           (write-char c out)
           (loop rv out)))))

For reference, here's the "ideal" solution using Chibi's string cursor interface:

(import (chibi string))
(define (string-split str delim)
  (define start (string-cursor-start str))
  (let loop ((rv '())
             (cur (string-cursor-end str))
             (last (string-cursor-end str)))
    (if (string-cursor=? cur start)
        (cons (substring-cursor str cur last) rv)
        (let ((prev (string-cursor-prev str cur)))
          (if (char=? (string-cursor-ref str prev) delim)
              (loop (cons (substring-cursor str cur last) rv) prev prev)
              (loop rv prev last))))))

Notice that I iterate through the string backwards so that I can use a right-unfolding implementation (tail-recursive) that does not require reversing at the end. This is the ideal no-compromises implementation, but of course it's Chibi-specific.