Class to verify if a rectification is upgradable

This looks as if it is part of the upgrade code itself.  I think you have too low a level of abstraction in here and you are also mixing different concerns.  Also, your workflow just seems fragile.

Cars and certificates

You check that there is a car, then you check that it has any certificates, then you pass the rectification to getValidCertificate.  Either you only need to pass the certificate list or you don't need to do the "has car/certificates" check yourself, since getValidCertificates clearly has to do that itself to be able to return a CarPassCertificate (or null).

(Since starting this question, we've discussed this issue in comments and I see you've agreed that only getValidCertificates needs to do the check.  Nice.)

Workflow

How can a rectification be both open and in progress and yet not even have a car?  Even if it is legitimate to have one open with no car, I can't see how it is valid for an in-progress task.  I really think your type hierarchy may not properly model your workflow.

If a rectification may exist for a period without a car (let's think of it as a rectification request) but

Rectifications can only be actioned once a car is added
Cars are not removed from Rectifications once added

then you should have two different classes to represent them. The first type should not have a car field at all.  The second should not be creatable without being passed a non-null car object. Depending on the rest of your code, the second class could be a subclass of the first (with the addition of a car field amongst other things) or share an interface with the first (preferred option of those two) or the request could be an entirely separate class, replaced with a car-containing rectification by a factory.

Either way, isRectificationUpgradable only need specify the second type as input. And immediately a whole category of errors is eliminated.  There is no need to check for the existence of a car when it is guaranteed to be present.

If you do it this way, you never have to check for the presence of a real car.  Any method that depends on the existence of a car simply has to specify the car-owning type.

I would not be surprised if other stages in the lifecycle of rectifications can be treated this way.  If you create a common rectification interface but

only the OpenRectification class/interface (which has no employee field) has a toAssigned method which requires an employee object and returns an assignedRectification object
only the assignedRectification type has changeAssignedEmployee method and toInProgress methods
only thetoInProgress type has methods which can be used to (for example) log work done

then many more categories of error evaporate.


Calculating total number of calories burned

First, not the most important point but first to grab my attention, prefer static final instead of final static in the name of least surprise.

Make everything private that can be made private, as @maartinus said.

This is a constant so make it final also:

private static double value = 0.0175;

Also name value is too generic, use the term from the field if available, you can name it CALORIES_PER_MET_PER_KG_PER_MINUTE, or at least SCALING_FACTOR.

This is not used anywhere other than main therefore should be a local variable there:

private static double totalCaloriesBurned = 0;

Then you do not need to initialize it to an unused value.

In main unnamed constant 150 is used repeatedly. You should name it weight or even better weightInPounds.

In:

public static double caloriesPerMinute(int met, double weight, double time)

caloriesPerMinute name is wrong, as it does not compute a per minute value. It could be renamed calories or caloriesBurned.

double weight, double time can be named weightInPounds and timeInMinutes to remind the user to do necessary conversion beforehand.

After renamings I suggested above the formula: value * met * poundToKilogram(weight) * time reads:

CALORIES_PER_MET_PER_KG_PER_MINUTE * met * poundToKilogram(weightInPounds) * timeInMinutes

So that it is easier to verify you did not mess up the units.


Agreed, this is not the Sieve of Eratosthenes. This is trial division by primes. (As long as you're doing trial division, you can do it slightly better, and only test up to the square root of the number.)
Replace the while loop, making it clearer and more pythonic: for test in num_list:
It is inefficient to delete from the middle of a list in python, which takes O(n) time.
It is generally unsafe, and will give wrong results to delete from an collection WHILE iterating through it. In this case it seems to work, but be careful. I would instead keep a binary flag for each number, with whether we've found a factor already or not (array of True/False).


I can't say what CodeEval's time limits are, or why this code should particularly slow. There are a lot of things you could do differently, though:

Instead of readlines, you can use each_line to iterate the lines, instead of reading all of them into an array, and then iterating.
You can get the values and k in a single line:

*values, k = line.chomp.split(/[,;]/)

Look up each_slice; it'll iterate an array in "chunks" of the given length
Don't do "manual" string concatenation. You already use join in one place, but you can use it anywhere you need a string representation of an array.
You're shifting k items off of the array, and you then check if the number of shifted items is divisible by k. But shift will either shift exactly k items or fewer, so the modulus operator is a really roundabout way of saying current.count == k.
You code fails if there are blank lines. CodeEval doesn't say whether the file can contain blank lines, but, if it does, well...

All in all, you're approaching this very procedurally. A nicer approach would be something like

Chunk the items in k-sized arrays (the last chunk may be smaller)
Reverse the chunks that are k items long
Put the arrays back together into one
Join with commas and print

Or, in code:

File.open(ARGV.first).each_line do |line|
  *items, k = line.chomp.split(/[,;]/)
  next unless k # skip empty lines
  puts items.each_slice(k.to_i).map { |group| group.count < k.to_i ? group : group.reverse }.flatten.join(",")
end

Edit: As Naklion points out in the comments, using flat_map is of course better than using map and flatten separately, i.e.:

items.each_slice(k.to_i).flat_map { |group| group.count < k.to_i ? group : group.reverse }.join(",")

I've update the rest of the code blocks to use flat_map

That 3rd line is a bit long, though, so to spell it out:

File.open(ARGV.first).each_line do |line|
  *items, k = line.chomp.split(/[,;]/)
  next unless k
  chunks = items.each_slice(k.to_i)
  reversed = chunks.flat_map { |chunk| chunk.count < k.to_i ? chunk : chunk.reverse }
  puts reversed.join(",")
end

You can also do pop off the last chunk if you know it to be smaller than k, which lets you say simply map(&:reverse) on the remaining elements

File.open(ARGV.first).each_line do |line|
  *items, k = line.chomp.split(/[,;]/)
  next unless k
  k = k.to_i
  chunks = items.each_slice(k).to_a
  tail = items.count % k == 0 ? [] : chunks.pop
  puts chunks.flat_map(&:reverse).concat(tail).join(",")
end

Last alternative: Pop off enough items that the remaining ones are cleanly divisible by k before slicing

File.open(ARGV.first).each_line do |line|
  *items, k = line.chomp.split(/[,;]/)
  next unless k
  k = k.to_i
  tail = items.pop(items.count % k)
  puts items.each_slice(k).flat_map(&:reverse).concat(tail).join(",")
end

But frankly, I like the first code block the best.

All of these are a little faster than your code, by the way. It's not a huge difference, but it's faster.


Print all possible codes for a given string

Your code is a reasonably neat use of recursion to solve the problem, and recursion is a good solution to this problem. I prefer it for people to make it obvious that a function is used recursively to prepare myself for what to expect, I tend to use "recursive" in the name. You don't show how you set up the recursive method, though, and in general it's poor form to embed print statements inside functions that do other things too (single responsibility principle: https://en.wikipedia.org/wiki/Single_responsibility_principle).

A better solution would be to return a collection of results that you can print in a separate place.

What really bothers me, though, is two things:

the hard-coded assumption that all codes are either 1 or 2 characters/digits. I realize that in your input problem it's true, but I feel there's a better way, or a more general way to solve this problem
the conversion to integers, and integer parsing of strings

Personally I am not too concerned about the string-concatenation you use for computing the ans value when recursing, but there may be a better way with using a pre-computed array, with tracking indices. I would consider the array/index solution a "phase 2" thing if performance is an actual, proven problem.

So, having said the above, it's best to explain it with code... I would do two significantly different things... I would set up a lookup table of string-based "digit" keys, and the corresponding character value. I would then loop through that table in the recursive function to determine the matches....

Setting up the table is relatively complicated, but it's a 1-time thing consisting of 2 correlated string arrays:

private static final String[] keys;
private static final String[] values;

static {
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    keys = new String[alphabet.length()];
    values = new String[alphabet.length()];
    for (int i = 0; i < alphabet.length(); i++) {
        keys[i] = String.valueOf(i + 1);
        values[i] = alphabet.substring(i, i + 1);
    }
}

Now, with those two arrays, we can decode the values "easily":

public static List<String> decode(String input) {
    List<String> results = new ArrayList<>();
    decodeRecursive(input, "", results);
    return results;
}

private static void decodeRecursive(String input, String current, List<String>results) {
    if (input.length() == 0) {
        results.add(current);
        return;
    }

    for (int i = 0; i < keys.length; i++) {
        String key = keys[i];
        if (input.startsWith(key)) {
            decodeRecursive(input.substring(key.length()), current + values[i], results);
        }
    }
}

Note that all the work is basically in the "string" space, and not parsing integers, etc. Also, the presentation/printing is done somewhere else.

I put this together in a program on ideone so you can see it working: https://ideone.com/sozgXb


First, there is a simple way to flatten out those loops, but it is not what I would suggest.  Here is the simple way:

if ((sizeof($var) == sizeof($content))) {
    $count = sizeof($var);

    for ($i =0; $i < $count; $i++) {
        $this->template = str_replace(
            '{' . $var[$i] . '}', $content[$i], $this->template);
    }
}

Note that you are currently silently doing nothing when the size of your arrays don't match.  I think that is a bug.

My Suggestions

$var and $content are not very descriptive: I would suggest $match and $replacement.

str_replace can handle arrays as input.  I would suggest filling your match with the '{' and '}' beforehand.  The code then becomes:

public function set($match, $replacement)
{
   $this->template = str_replace($match, $replacement, $this->template);
}

I would place any sanity checks before the str_replace that you require.  str_replace uses blank replacements when the matches array is larger than the replacements.  If you want to avoid that use:

   if (is_array($match) && is_array($replacement) &&
       sizeof($match) > sizeof($replacement))
   {
      throw new InvalidArgumentException(
         __METHOD__ . ' Each match must have a replacement');
   }

This avoids arrow code which will make the code easier to test, reduce its complexity and make it easier to maintain.


Joining two KeyedTuple objects in SQLAlchemy

Your basic problem is you want to combine...erm, join... similar data from your database. There are a couple different angles we can take to solve this problem:

We could do as you are, but a more simple way.
We can let the database do the work.

The second way is the preferred solution. Databases are designed to solve this problem and they solve them very efficiently. They are meant to be a powerful tool to store, update, and eventually relate data.

If you are set on the first solution, this post describes several ways to combine two dicts. Combine any one of those solutions with the KeyedTuple._asdict function can simplify your code:

try:
    # In Python 3, you cannot use the + operator. You can use the | operator instead.
    joined_result = dict(res.one()._asdict().items() + res_t.one()._asdict().items())
except NoResultFound:
    return None

Now, the preferred solution would be to use a JOIN to combine the two queries into one. SQLAlchemy's join documentation has a quite a few examples of how join can be used. The basic example should suffice for your purposes:

joined_result = session.query(t_marketing_mailing_stats_tbl)\
                       .join(t_marketing_time_stat_tbl)\
                       .filter(t_marketing_mailing_stats_tbl.c.mailing_id==mid)

try:
    return joined_result.one()
except NoResultFound:
    return None

To wrap up, I have a few style comments:

Be consistent with your spacing. For the most part you have a single space before and after operators. This is good. However, in a few locations, you have one or both of the spaces missing.
Don't truncate words in variable names (unless they are very long). Typical Python convention tries to be more verbose than brief. Thus the variable name res would better named as result.

Also, make sure that your names are unambiguous: what does res_t do different than res? What does the prefix t_ mean in your table names mean? Given the context, t_ could easily mean 'table'; however, wouldn't the suffix _tbl then be redundant?


Major Issues

The class access modifier does not allow public access, so your class is not usable by third party consumers. Make it public.
Your class should be generic to be usable.
You should always provide unit tests when providing a class to consumers of your API.
Pop is ill-defined. It does not return anything. It can throw a NullReferenceException when the stack is empty. It does not decrement the count. It should throw InvalidOperationException when empty.
A class representing a collection should always implement the correct interfaces. Implement IEnumerable<T> to let consumers iterate the items. Implement IReadOnlyCollection<T> to provide a property Count. Don't be fooled by its name, collections implementing this interface are not stipulated to be immutable. They provide a Count to indicate eager iteration is provided (Interesting Discussion about IReadOnlyCollection).

Review

The name of a class should tell you what it is, not how it's implemented. Call it LinkedStack (conform naming convention LinkedList).
Node could be made public, but then its state should be private or internal at best. Given the few operations you provide, it could be made private. Consider making it public if you would provide mehods as Remove(Node<T> node). This would remove a specific node, even if multiple nodes hold the same value as the specified node.
Push has a redundant creation of a node. Create the node before the first if statement.
Print has no purpose in this class. It should be an extension method declared elsewhere.
Node should be a nested class for better encapsulation.
A property IsEmpty, as suggested in another answer, is syntactic sugar that improves readability.

Refactored

In this solution the Node remains private. Some API's allow it to be public.

public class LinkedStack<T> : IReadOnlyCollection<T>, IEnumerable<T>
{
    private class Node
    {
        internal Node next;
        internal T Value { get; }

        public Node(T value) => Value = value;
    }

    private Node head;

    public void Push(T item)
    {
        var node = new Node(item);
        if (IsEmpty)
        {
            head = node;
        }
        else
        {
            node.next = head;
            head = node;
        }
        Count++;
    }

    public T Pop()
    {
        if (IsEmpty)
        {
            throw new InvalidOperationException();
        }
        var value = head.Value;
        head = head.next;
        Count--;
        return value;
    }

    public int Count { get; private set; }
    public bool IsEmpty => Count == 0;

    public IEnumerator<T> GetEnumerator()
    {
        var node = head;
        while (node != null)
        {
            yield return node.Value;
            node = node.next;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Unit Tests

[TestClass]
public class LinkedStackTests
{
    [TestMethod]
    public void LinkedStackTest()
    {
        var stack = new LinkedStack<int>();

        stack.Push(0);
        stack.Push(0);
        stack.Push(1);

        Assert.AreEqual(3, stack.Count);

        Assert.AreEqual(1, stack.Pop());
        Assert.AreEqual(0, stack.Pop());
        Assert.AreEqual(0, stack.Pop());

        Assert.AreEqual(0, stack.Count);
    }
}


Implementation of linear regression in Python

Just reviewing normalizeFeatures.

Instead of a comment explaining what the function does, write a docstring. (Docstrings are available from the interactive interpreter via the help function.)
The function operates on the global variable X. This makes the function inflexible (you can't use it for anything other than modifying the particular variable X), and hard to test. It would be better if the function received the array as an argument, so that it could be used on any array:

def normalize_features(a):
    """Given array a with shape (m, n), update it so that each column
    (except column 0) has mean 0 and standard deviation 1. Return
    arrays mu, sigma with shape (1, n) where mu[0,i] is the original
    mean of a[:,i] and sigma[0,i] is the original standard deviation
    of a[:,i].

    """

This complicated specification can be simplified. First, we can avoid the "(except column 0)" bit and let the caller pass X[:,1:] if they want to leave column 0 alone. Second, we can return mu and sigma with shape (n,) instead of (1, n) and let the caller reshape if necessary (which it probably isn't).

def normalize_features(a):
    """Given array a with shape (m, n), update it so that each column has
    mean 0 and standard deviation 1. Return arrays mu, sigma giving
    the original mean and standard deviation of each column of a.

    """

The loop over the columns is unnecessary because numpy.mean and numpy.std take an axis argument. So the body of the function can be:

mu = a.mean(axis=0)
sigma = a.std(axis=0)
a[...] = (a - mu) / sigma
return mu, sigma

It might be better not to update the array X, but to compute a new array containing the normalized data (this uses twice the memory, but that's only a concern if X is really big). If you did this, then you wouldn't need to remember the original mean and standard deviation (because you still have the original data) and so the normalization becomes a one-liner:

def normalize_features(a):
    """Return copy of a with each column normalized so that it has mean 0
    and standard deviation 1.

    """
    return (a - a.mean(axis=0)) / a.std(axis=0)

Consider using scipy.stats.zscore instead of writing your own.


If you are sanitizing your input just for the sake of sanitizing your input, you're wasting time (both yours in coding and the computer in execution). Do you need to sanitize $_COOKIE if you never use it? What about $_SESSION?

Only sanitize what you need, when you need it. Switching to a PDO system to have it sanitize your database queries would solve that aspect (and the #1 reason to sanitize).


Reduce boilerplate with RepositoryPattern

If you must keep the code the same way, I can think of only reducing the repeated

var client = GetServiceStackClient();
return client.PostAsync(request);

by doing something like this:

public class DiagnosticsRepository : DefaultRepositoryBase, IDiagnosticsRepository
{
    public Task<IList<MasterDiagnostic>> GetMasterDiagnosticsFromType(int type)
    {
        var request = new MasterDiagnosticRequest()
        {
            MasterType = type
        };

        return Refactor<IList<MasterDiagnostic>, MasterDiagnosticRequest>.Get(request);
    }

    public Task<DiagnosticoDataResponse> GetMasterDiagnostic(string storedProcedure)
    {
        var request = new DiagnosticoDataRequest()
        {
            StoredProcedureName = storedProcedure,
            Data = DateTime.Today
        };

        return Refactor<DiagnosticoDataResponse, DiagnosticoDataRequest>.Get(request);
    }

    // get rid of the repetition...
    private class Refactor<TRespone, TRequest>
    {
        public static Task<TRespone> Get(TRequest request)
        {
            var client = GetServiceStackClient();
            return client.PostAsync(request);
        }
    }
}

Frankly, I don't think you should have all these various methods and signatures at all. You could reduce the repository to just the methods that are usually found in a repository (ex: Add, Update, GetById, Delete, Etc...

Which would mean your repository would potentially just look like this instead:

public class DiagnosticsRepository<T> : IDiagnosticsRepository
{
    public static Task<T> Get(object request = default(object))
    {
        var client = GetServiceStackClient();
        return client.PostAsync(request);
    }
}

-The below is unconfirmed for your particular library, but based on my quick read of the documentation, this should work-
With the above minimized repository,  if you like, you could go even further and swap your requests to anoymous types to reduce the amount of classes you are generating -- which is not uncommon especially for JSON requests. For example:

string storedProcedure = "...";
object request = new { StoredProcedureName = storedProcedure, Data = DateTime.Today };
var response = DiagnosticsRepository<DiagnosticoDataResponse>.Get(request);


Try to use scopes, its a lot nicer

def search
  @products = Products.scoped
  if !params[:search_keywords].blank?
    @products = @products.where("name LIKE ?", "%#{params[:search_keywords]}%")
  end
  if !params[:product].try(:[], :type).blank?
    @products = @products.where(:product_type_id => params[:product][:type])
  end
  @products # maybe @products.all if realy needed
end


Update HTML4 to new HTML5 Semantic/Structural Elements

You can’t decide which sectioning elements to use without taking the actual content into consideration. So the following is meant for the home page of http://www.habbo-heaven.de/ (sub pages might differ!).

Your header (#outer-nav) is fine. It contains the h1 for the whole site. Therefore it is a child of body (and no other sectioning element).

Your nav (#outer-nav) is fine. It contains the site-wide navigation, therefore it is a child of body (and no other sectioning element).
You could use a ul for the links, though.

Using aside is fine. It contains content related to the whole page. Therefore it is a child of body (and no other sectioning element). However, your use of the headings inside of it is not correct for your content. The first heading inside the aside will be the (only!) heading of that sectioning element. But you use several h1 and, assuming that my understanding of your content is correct, there should be no top heading for all the blocks in the sidebars, because semantically they are all on the same level. There would be 2 possible solutions:

use one aside for all blocks and use section elements for each block (if you need containers for styling, use div elements around the aside elements)

Zuletzt gesetzte Gebote

Zuletzt hinzugefügte Möbel

Top Trader

Neusten User

Zuletzt hinzugefügte Angebote

use a separate aside for every block in the sidebar

Zuletzt gesetzte Gebote

Zuletzt hinzugefügte Möbel

Top Trader

Neusten User

Zuletzt hinzugefügte Angebote

Note that these two variants don’t generate the same document outline. The first variant will open another heading level for the aside, even if you don’t specify a heading explicitly. In the second variant all aside headings will be on the same (top) level as e.g. the main content. I’d prefer the first variant with one aside as container, because it doesn’t clutter the document outline and all your sidebar blocks are related content-wise anyway. If possible, find a suitable heading (you could hide it visually), like "Recent activity" or similar.

For the two forms you could use an article element for each (as you already do on the live site). section would work, too, of course. And it would also be possible to use no sectioning element at all (just headings), because you marked up all other content appropriately (header, footer, aside), so it’s clear what the main content is. For this content (just these two forms), it’s mostly a question of taste.

Your footer (#disclaimer) is fine. It contains the footer for the whole page/site, not only for the main content. Therefore it is a child of body (and no other sectioning element).


Checking for palindromes using dynamic memory allocation

You should consider making this more modular (more functions).  It's not good to implement an entire program in main() as it could hurt readability.  While the separate comments are helpful, it's not a substitute for utilizing functions.

Essentially, you should just do the user-input and the function-calling in main().  In general, try to have main() do as less as possible.  For instance, the string-copying and palindrome check should be done in separate functions, and main() should pass the strings to them at the calls.

void copyIntoString(char* str_san) {
    // ...
}

void checkForPalindromes(char* str_san) {
    // ...
}

The deallocation should still be done in main() since the allocation was done in there.  Also, the last output can be put into checkForPalindromes() since it's part of that functionality.

I also have some additional notes:

If you need a separate variable like len, consider giving it a more accurate name so that it's known which length is being stored.  You have two strings, so the reader could easily forget which string to which it belongs.  Adding additional strings would then make it worse.
Instead of using printf() for unformatted outputs:

printf("Enter a message: \n");

use puts():

puts("Enter a message: ");

It also gives you a newline, so you can leave out yours (unless you want two).
It's clearer to have each declaration or initialization done on a separate line, so instead of this:

int i = 0, k = 0, len;

you should have this:

int i = 0;
int k = 0;
int len;

However, as the first two are loop counter variables, they should be placed right in front of the respective for loops (or in the for loops if you have C99 or above).  This will help with keeping close scope, which is good for readability and maintenance.
This doesn't need to be a while loop:

while (str[i] != '\0') {
    if (str[i] >= 'A' && str[i] <= 'Z') {
        str_san[k] = str[i] + 32; //changes uppercase to lowercase
        k++;
    }

    if (str[i] >= 'a' && str[i] <= 'z') {
        str_san[k] = str[i];
        k++;
    }

    i++;
}

Since i is being incremented each time, it can just be a for loop:

for (int i = 0; str[i] != '\0'; i++) {
    if (str[i] >= 'A' && str[i] <= 'Z') {
        str_san[k] = str[i] + 32; //changes uppercase to lowercase
        k++;
    }

    if (str[i] >= 'a' && str[i] <= 'z') {
        str_san[k] = str[i];
        k++;
    }
}

In addition, you can use isupper() instead of your own check:

if (isupper(str[i])) {

You can also use tolower() to change a character to lowercase:

str_san[k] = tolower(str[i]);

The second if can then use islower():

if (islower(str[i])) {

Lastly, those two if can be consolidated into one.  This can be done by calling tolower() whenever any letter is encountered (the character will remain intact if it cannot be made lowercase).  Since all these operations only apply to letters, each character can first be checked with isalpha().

All of these function calls may add slight overhead, but if you don't care too much about efficiency or will mostly work with smaller strings, then it shouldn't matter.

Taking each point into consideration, you should end up with this:

for (int i = 0; str[i] != '\0'; i++) {
    if (isalpha(str[i])) {
        str_san[k] = tolower(str[i]);
        k++;
    }
}


I was wondering if I used the static variable correctly? If not, how could I make it non-static so I could instantiate it in the main method whilst being able to access its getter methods in the listener inner class?

I would prefer to not use a static variable for this, which you could easily achieve by passing the animation object to the panel:

public class AnimationPanel extends JPanel {

    private SimpleAnimation animation;

    public AnimationPanel(LayoutManager layout, SimpleAnimation animation) {
        super(layout);
        this.animation = animation;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.ORANGE);
        g.fillOval(animation.getX(), animation.getY(), 100, 100);
    }
}

With a simple animation class (in a real project, setcoordinates would more likely be updateCoordinates, as the animation model should contain its logic itself, ie it should know what to animate, instead of having the main class/controller manage this. the main class would just be a loop constantly calling updateCoordinates on the model, and repaint on the view):

public class SimpleAnimation {
    private int x = 5;
    private int y = 5;

    int getX(){
        return x;
    }

    int getY(){
        return y;
    }

    void setCoordinates(int newX, int newY){
        x = newX;
        y = newY;
    }
}

And then use it in your main like this:

public class AnimationMain {

    public static void main(String[] args) {
        SimpleAnimation animation = new SimpleAnimation();
        AnimationPanel animationPanel = new AnimationPanel(new BorderLayout(), animation);

        buildGUI(animation, animationPanel);

        for (int i = 0; i <= 300; i += 1) {
            animation.setCoordinates(i, i);
            animationPanel.repaint();
            try {
                Thread.sleep(10);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
        }
    }

    public static void buildGUI(SimpleAnimation animation, AnimationPanel animationPanel) {
        JFrame frame = new JFrame("Simple animation");
        SwingUtilities.invokeLater(
                new Runnable() {
                    @Override
                    public void run() {
                        frame.setContentPane(animationPanel);
                        frame.setSize(400, 500);
                        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);
                    }
                }
        );
    }
}

The main reason I would prefer this approach is that it follows the MVC approach (separating the code by model (SimpleAnimation), view (AnimationPanel), and controller (AnimationMain)). This seems a lot more flexible (with your approach, I even have problems extracting the main method to its own class, for example).

Misc

don't import *, instead make all your imports explicit, so readers know what classes you use.
your methods should be explicitly declared as private or public.
your spacing is sometimes off (eg i+=1; it should be i += 1, or the more customary i++).


A minimalistic kind of read-copy-update class

Serious issues with this:

Memory Management.
Not using RAII to lock/unlock

Memory Management
Don't pass pointers it does not indicate owners. Always wrap pointers in a smart pointer. Have a look at std::unique_ptr.
But for types like Data there is no need to use pointers. Simply use Data as the object type (not Data*).
RAII
Look up the concept of RAII.
A good example is std::lock_guard https://en.cppreference.com/w/cpp/thread/lock_guard This shows you how to use RAII to automate the processes of lock/unlock so it is exception safe.


Elegant way to do the dataframe operations twice

You're indeed doing a lot of stuff twice. The first step is recognizing that you have a problem :D

The following collection of functions could be used to decrease the repetition:

def load_df(item_name):
   return df[df['item_name'] == item_name]

def get_hr_op(predicate):
   """ Predicate is a lambda """
   hr = final_df[predicate(final_df['total_hr'])]
   min_hr = hr.groupby(['subject_id','date'])['value'].min().reset_index()
   op = hr.merge(min_hr, on = ['subject_id','date','value'],how = 'inner')
   return op.set_index(['subject_id','date'])

def make_con(add_qty):
   def con(x):
      return (
         x.shift(2).ge(x.shift(1))
      ) & (
         x.ge(x.shift(2).add(3))
      ) & (
         x.shift(-1).ge(
            x.shift(2).add(add_qty)
         )
      )
   return con

def apply_field(name, title, add_qty):
   con = make_con(add_qty)
   op[name] = op.groupby('subject_id')['value'].transform(con).map({True:title,False:''})

You get the idea. Basically, functions are your friend. There may be some fancier way of cleaning this up using Pandas-specific stuff, but this is the Python way.


Reducing memory usage when comparing two iterables

This should do it:

def dbcheck(cursor):
    cursor.execute("SELECT COLUMN FROM TABLE")
    with open(dbdump) as f:
        for item in cursor:
            if f.readline() != item + '\n'
                print("DB content does not match original data!")

No need to read either the whole column nor the whole file before iterating.


Convert decimal to binary and find the maximum number of consecutive 1's in the binary

You solution looks good for a procedural one -- something similar would be the correct way to do this in, say, C.

That said, and assuming this isn't considered "cheating" for the problem at hand, if you're using ruby, you might as well take advantage of ruby's facilities.  Assuming the input number is n, all you need to do is:

n.to_s(2).scan(/1+/).max_by(&:size).size

or, even more tersely, taking advantage of how strings are compared (ie, "11" > "1" and "111" > "11", etc):

n.to_s(2).scan(/1+/).max.size

to_s(2) converts to the binary string, scan finds all runs of 1s, max_by finds the longest of those, and the final size tells you how long that is, as a decimal.


Wrote a package in Go. What did I do wrong? What did I do right?

This is fairly bare-bones as far as packages go, but there are thing that can be improved here.

Firstly, to create a player object, someone is going to need to do the equivalent of:

player := new(Player)
player.SetPlayer(...)

This is a bit annoying. I'd much rather create a function that constructs a fully initialised Player:

func NewPlayer(name string, race string) *Player {
    ...
}

We can also use some syntactic sugar to shorten the actual initialisation:

func NewPlayer(name_ string, race_ string) *Player {
    rand := rand.New(rand.NewSource(time.Now().UnixNano()))
    return &Player{name: name_, race: race_, id: rand.Int63(), pos: Position{0: 0},
                   facing: 0, health: 100, wpn_id: 0, is_buf: false, buf_mt: 0.0}
}

I don't really understand what the point of the function:

func (P *Player) GetPlayer() *Player {
    return P
}

is supposed to be. It takes a player, and returns the same player - a no-op.

I'm also not sure why you use a map for position, when 2 integers will do:

type Position struct {
    x int64
    y int64
}

In the following function:

func (P *Player) SetHealth(amount int64, direction string) {
    if direction == "down" {
        P.health = P.health - amount
    } else {
        P.health = P.health + amount
    }
}

direction could be an enum-like type:

type Direction uint8

const (
    DOWN Direction = iota,
    UP   Direction = iota
)

func (P *Player) SetHealth(amount int64, direction Direction) {
    switch direction {
    case DOWN: P.health -= amount
    case UP: P.health += amount
    default: panic("Unknown direction type!")
    }
}

Although this is overkill here, and I'd go with @WinstonEwert's suggestion and just pass in either a positive or negative number that can be used to modify the player health.

A type with a lot of getters and setters doesn't really fit with the Go "mantra". In fact, I'd consider this a bit of an anti-pattern in most languages - if you're going to write both Get and Set functions, without really checking arguments or enforcing constraints, you may as well just give direct access to the underlying variable. This is debatable, however, and I know some people will disagree, so I'll won't belabour the point.


A completely different approach to your answer is a concept called Actors.

Rather than having multiple threads, and having these threads await each other, Actors are like tiny little processes that communicate with each other by sending messages. When you're done with a piece of work, you can send a message to another actor, telling it to go and do something else.

The Actor Model as it's known is both highly performant and simple to reason about.

Scala is fortunate enough to have an incredible implementation of the Actor Model known as Akka.

Akka allows you to very simply build large and complex systems - it can even handle distribution across many machines!

Here's a really simple example from the Akka website:

case class Greeting(who: String)

class GreetingActor extends Actor with ActorLogging {
  def receive = {
    case Greeting(who) ⇒ log.info("Hello " + who)
  }
}

val system = ActorSystem("MySystem")
val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
greeter ! Greeting("Charlie Parker")

How easy is that? :-)

I strongly recommend using the Actor Model instead of using conventional threads and locks. Scala provides us with an incredibly powerful toolkit, I encourage you to use it!


Summing durations associated with each MAC address in a MongoDB result

You can do this in only one foreach, making it faster and intelligible for future modification or reuse. The approach  I propose is as follows:

//(some sort of pythonish pseudocode)
// let cursor be the array with the mac addresses and duration
result = [] // empty array
for each element in cursor as document:
  document['mac'] is not a key of result then:
    result[ document['mac'] ] = document['duration']
  otherwise
    result[ document['mac'] ] += document['duration']

This way you can quickly check your data, it is very handy. The only difference is that you'll get an array like this:

[
   'mac1' => 'total duration in integer type',
   'mac2' => 'total duration in integer type for mac2'
   ... etc ..
]

In case you really need the current result array structure, you can do this after the first loop:

//(some sort of pseudocode)
arr = [] //initialize the array
for each element in result as mac => duration:
  arr[] = [ 'mac' => mac, 'assoc_time' => duration ]

The difference between nesting two (possibly) big loops and just checking if a key exists in an array is significant. Now let's write a few lines of PHP code:

<?php
$result = array(); // maybe just $result = []; in case you have a proper PHP version.
foreach ($cursor as $document):
  if ( isset( $result[ $document['mac'] ] ) ):
    $result[ $document['mac'] ] += $document['duration']
  else:
    $result[ $document['mac'] ] = $document['duration']
  endif;
endforeach;

You can just replace the endforeach, endif with the traditional brackets.


Mutex and condition variable implementation using futex

I have no particular experience of Futex code, so take this with caution:

Looking at mutex_lock, I think some comments would have been useful.  As I
understand it, this is what it does:

Firstly let's define what your values 0, 1, 2 mean.  I understand them to
mean 'free', 'locked', 'locked and contested' respectively.  Some #defined
constants would have made that clear (assuming it is right).
The first compare-and-swap  tries to lock the mutex.

if((c = __sync_val_compare_and_swap(m, 0, 1)) != 0)  {

If this succeeds, the
function exits with the mutex locked (ie. its value is 1).  However if the
mutex was not unlocked (0) this fails and we enter the do...while loop.
At this point we know the mutex is (or was, to be precise - it might have
changed) either locked or contested.  If it was contested we want to make a
futex system call to wait for it to be unlocked.

    if((c == 2) || __sync_val_compare_and_swap(m, 1, 2) != 0)
        syscall(SYS_futex, m, FUTEX_WAIT_PRIVATE, 2, NULL, NULL, 0);

Hence we make the system
call either if we know the mutex was contested (c == 2) or if it was
only locked and we succeeded in setting it contested.  But because the mutex
might have changed since the first compare-and-swap, we have to do another
compare-and-swap to swap its locked 1 for a contested 2.  If the mutex
changed state and is no longer locked, this will fail and we don't make the
system call.  (Note that the system call itself has protection against the mutex changing state before it is entered, hence the '2' parameter which ensures that if *m is not 2 the kernel will not be entered.)
If we either didn't make the system call (because the mutex had changed) or
we made the call and it returned (again because the mutex state had changed)
we reach the while part of the loop.

} while((c = __sync_val_compare_and_swap(m, 0, 2)) != 0);

We can expect the mutex to be free
(0) at this point and that we can try to lock it.  But instead the code
tries to set it to contested (2).  If it succeeds the loop and function exit
with the mutex set to contested, not just locked.   This seems wrong - the
last compare-and-swap should be setting '1', not '2'.  If we replace the 2
with a 1, the loop exit condition is the same as the condition at the start
of the function and we can simplify to:

enum mutex_state {
    FREE = 0,
    LOCKED,
    CONTESTED
};

void mutex_lock(mutex *m)
{
    enum mutex_state c;
    while ((c = __sync_val_compare_and_swap(m, FREE, LOCKED)) != FREE)  // set locked
    {
        if ((c == CONTESTED) ||
            __sync_val_compare_and_swap(m, LOCKED, CONTESTED) != FREE)  // set contested
        {
            syscall(SYS_futex, m, FUTEX_WAIT_PRIVATE, CONTESTED, NULL, NULL, 0);
        }
    }
}


Optimization - Prime Factorizations of Numbers <= 10^7

I did this a while ago, in the interest of reducing ratios of factorials

#include <utility>
#include <vector>

std::vector< std::pair<int, int> > factor_table;
void fill_sieve( int n )
{
    factor_table.resize(n+1);
    for( int i = 1; i <= n; ++i ) {
        if (i & 1)
            factor_table[i] = std::pair<int, int>(i, 1);
        else
            factor_table[i] = std::pair<int, int>(2, i>>1);
    }
    for( int j = 3, j2 = 9; j2 <= n; ) {
        if (factor_table[j].second == 1) {
            int i = j;
            int ij = j2;
            while (ij <= n) {
                factor_table[ij] = std::pair<int, int>(j, i);
                ++i;
                ij += j;
            }
        }
        j2 += (j + 1) << 2;
        j += 2;
    }
}

std::vector<int> factor( int num )
{
    std::vector<int> factors;
    factors.reserve(30);
    do {
        factors.push_back(factor_table[num].first);
        num = factor_table[num].second;
    } while (num != 1);
    return factors;
}

I believe it will be much faster than yours, because I was able to avoid ever using division (/ and %).  As a matter of fact, I don't use any multiplies either.

(It's about 6x faster with g++ than the code in the question, and the actual factor generation part is marginally faster, about 10%, than lol4t0's.  Returning factors in a std::vector<int> takes 5x as long as the factor generation.)

Test program: http://ideone.com/pt9nu

Original application:

http://ideone.com/Weeg6


The efficiency of your algorithm is fine, however there are a couple of other things you should take care of:

First of all do not free memory, which was allocated with malloc, using delete. delete is for freeing memory which was allocated with new. To free malloced memory use free. Using delete on malloced memory is wrong and leads to undefined behavior.

Also there is almost never a good reason to use malloc in C++ code. If in doubt use new and delete.

Another serious bug in your code is that you allocate memory for prev in deletenode, but never free it.

I also don't see why you pass in first as a reference to a pointer. Since you never change first, I see no reason not to pass it in as a plain pointer (or a plain reference which you then take the address of to assign to current).

Another thing is that you don't need to add the struct keyword when declaring variables or parameters containing structs in C++ - that's a C thing. You should remove it as it only adds noise.


How can I Shorten and Simplify Ajax callback processes?

Here is a jsfiddle where I cleaned it up for you

I did not actually test it so there might be a syntax error here and there but its how you would do it overall.
It might not be 100% but it should get you started as far as the techniques you should look into such as:

Module pattern to create reusable code
Callback or options to support the ability to pass in a simple callback or a more complex object
Defaults with $.extend
Functions returning callbacks

That's a lot of stuff and a bit overkill on this example but I wanted to showcase the techniques for you. Feel free to ask any questions.

A couple additional notes

You generally want to use the expression context parameter to limit your selectors
You probably want to avoid using ids and use classes instead since things get wierd if you accidentally end up with 2 of the same id on the page. This is something that happens more often as you start to make your views more composable. This is something that using the expression context can help with.
submit is only available on forms anyways, you could denote that explicitly $('form#add_question_member')
Do you really want to be returning false?
Consider using the form's action and method properties instead of hardcoding them - $(this).prop('action'), $(this).prop('method') at the same level as you serialize the form

//****This part can be in a seperate script file **********//
(function() { //use an immediately executing function to limit scope
    var submitFormDefaults = { //set up all the defaults to be used the function
        type: 'post',
        url: '/posts_in.php',
        dataType: "json",
        myAppUnWrapData: true //a custom option to unrwap your returned data by default
    };

var standardSubmitForm = function(successFnOrOptions) {
    // This allows your input to be just the success function or a richer object
    var options = $.isFunction(successFnOrOptions) ? {
        success: successFnOrOptions
    } : successFnOrOptions;

    // return the actual submit handler
    return function() {
        var op = $.extend(true, //deep clone
          submitFormDefaults, //use defaults unless overridden
          { data: $(this).serialize() }, //not in the defaults cause it needs access to 'this'
          options //any overrides specified
        );
        if (op.myAppUnWrapData && op.success) { //if unwrap data custom option is truthy and there is a success callback
            var _oldSuccess = op.success;
            op.success = function(data) {
                _oldSuccess(data[0]);
            }
        }
        $.ajax(op);
        return false;
    }
}

//Export the local function to the gloabl namespace using Module pattern
window.MyApp = window.MyApp || {}; //create a global MyApp namespace
$.extend(window.MyApp, { //add some global functions. I prefer to use $.extend rather than directly assigning it - I have no good reason for this
    submitForm: standardSubmitForm //export our function to the global namespace
});

window.MyApp.submitForm.defaults = submitFormDefaults //export the defaults as a global property on this function

})(); //Invoke the above immediately invoking function

//******************** Elsewhere ********************************//
$("#add_question_member").submit(window.MyApp.submitForm(function(response) { //this will return a function handler
    if (response !== 1) {
        $("#msg0").stop().fadeIn("slow").delay(8000).fadeOut("slow", function() {
            $("#entry_area").stop().fadeIn("slow");
        });
    } else {
        $("#msg1").stop().fadeIn("slow").delay(8000).fadeOut("slow", function() {
            $("#entry_area").stop().fadeIn("slow");
        });
    }
}));

// or...
$('form.blah').submit(window.MyApp.submitForm({
    url: '/somewhere/else',
    success: function() {
        console.log('ok', this, arguments);
    }
});

// or...
window.MyApp.submitForm.defaults.action = 'GET'; //changes it globally
$('form.blah').submit(window.MyApp.submitForm({
    url: '/somewhere/else',
    myAppUnWrapData: false,   //keep it from doing the data[0] thing
    success: function(data) {
        console.log('ok', this, arguments);
    }

});


so just 2 things here:

if(task=="") alert("Are you sure you do not have any task to do?");
such comparison is a bit risky in JS. In case of checking for empty values it's better to do if(!condition) {} else {} or at least if(task ==="") (strong type checking). Not saying it's wrong in this case, just a rule of a thumb. Read more about issues with JS comparison / type casting, you'll find out what I mean.
Creating UI in code is fine of course, and it's nice to understand what's going on under the hood, but for readability of your UI you mind find it better to define everything up-front in HTML and than later just show / hide parts of it or add remove classes, depending on your application state. This is not a general guideline, because it only makes sense for small-medium apps, for larger, more complex, you probably will use some framework anyway (angular or such).
Other than that, fine simple app (assuming it works, didn't run it to be honest) ;).


Does my classes contain right destructors

General Comment on Style

This is probably not what you want.

Bank* bank = new Bank();
Person* thomas = new Person("thomas", 34);

You actually want:

Bank   bank;
Person thomas("thomas", 34);

This creates automatic variables. That are properly destroyed automatically at the end of scope.

It is very rare to use RAW pointers in C++ Bank* or Person*. When you dynamically allocate objects using new you want to make sure that the returned pointer is put into an object that controls their lifespan and garbage collects the values when you are finished using them.

std::shared_ptr<Bank> bank = new Bank;  // This is the closest to a Java object
                                        // that C++ has. It allows multiple users
                                        // and it is correctly destroyed when nobody
                                        // has a reference to it anymore.

Looking at the code:

Don't do this:

using namespace std;

I know all the shitty C++ books you read have it in. Its fine for 10 line long programs you type out of a book. But once you get past those programs it can cause problems with namespace pollution. Its thus a very bad habit and one you should break as soon as possible. See: https://stackoverflow.com/q/1452721/14065

Person

Pointers are bad.

    char* name;

Unless you do a lot of validation and know the ownership of the thing you are pointing at and it is not going to be cleaned up behind you then you should be very weary of using pointers. I have checked your code and you are fine in this simple program but this is not a good design outside of a small toy project. C++ also has its own string type std::string so you don't need to know or use C-String. So I would change this to

    std::string  name;

In constructors prefer to use the initializer list to initialize the members.

    Person(char* name, int age){
        this->name = name;
        this->age = age;
    }

Second point about pointers here. Its not normal to pass pointers to around in C++ (this is very common in C but modern C++ you should basically never do it (with a few exceptions that you will work out when you have more experience)). Pass objects by reference if you want to retain ownership; otherwise pass a smart_pointer to transfer ownership of the object.

In this case you want to pass a std::string. As you don't want to change the original but make your own copy pass a const reference (if you are in C++11 you may want to also add a move constructor (but this is advanced so don't worry about it)).

So it should look more like:

    Person(std::string const& name, int age)
        : name(name)
        , age(age)
    {}

If a destructor does not do anything then don't declare it.

    ~Person(){
    }

Its fine to have a public show() method. But any method that does not change the state of the object should be declared as const. This allows you to call the object from const objects (useful technique later). And if you add a parameter so it can be any stream it makes it more versatile. But you should also declare a stream operator for your Person type. Thus you can stream your person just like any other type.

    void show(std::ostream& out = std::cout) const {
                                        //   ^^^^^    Does not change the state
                                        //            so make the method const.
          //  ^^^^^^^^^^^^^^^^^  Pass stream to print on.
          //                     You may want to print in other places.
          //                     rather than std::cout (like a file).

        out<<name<<" "<<age<<" yo";  // A few spaces to make it readable
                                      // would be nice.
    }

// Pass person by const reference so the compiler
// knows you are not going to modify the object.
// This means you can only call const methods (so `show()` must be const.
std::ostream& operator<<(std::stream& stream, Person const& person)
{
    person.show(stream);
    return stream;
}

int main()
{ std::cout << Perons("Loki", 962) << "\n";
}

Account

This is fine.

Person& owner;

It means you have a reference to a person that is stored somewhere else. But you need to be careful of lifetimes. Make sure the Person object is still alive while you are alive.

Passing by pointer again.

Account(Person* owner, double money):

This is dangerous. Especially since you de-reference without checking. Since you are storing a reference. Pass the value in by reference.

Account(Person& owner, double money)
    : owner(owner)
    , money(money)
{}

Make the show() method const and pass a stream.

 void show(std::ostream& out = std::cout) const {
                                      //  ^^^^^
    out<<"\n-------------\n" << owner << std::endl << money<<"USD\n-------------";
    return out;
}

Add a stream operator

std::ostream& operator<<(std::stream& stream, Account const& account)
{
    account.show(stream);
}

Destructor does nothing so remove it.

  ~Account(){
}

Bank

Ok. Obviously a java (or java inspired language user).

list<Account*>* v;

You don't want to use pointers here. By making this a pointer you need to do all sorts of memory management (and make sure you obey the rule of three (look it up)). But you don't need to do that just make it a normal object and all those problems go away.

list   v;

When the bank object is created. It automatically creates a list now. When the bank is destroyed it automatically cleans up its members (including the list). When the back is copied it automatically copies the accounts to the new Bank.

Second; don't make the Account's inside the list pointers. Again you will need to manage the each object and control its lifespan. Much easier to put Account objects into the list.

list   v;

There is also a principle called Separation of Concerns. Basically this says that an type should either be Business Logic or Resource Management you should not do both in the same type. Since Bank is obviously business logic you should not be doing resource management in the Bank. If you were using pointers then you would delegate the memory management of those pointers to anther type that would correctly do the clean up. C++ already has a whole bunch of smart pointers explicitly for managing pointers.

BUT in this situation I would defiantly sidestep the memory management by using automatic objects and make the changes I described above as ALL your memory management issues disappear.

Remember use initializer list.

Bank(){
    v = new list<Account*>();
}

But if you change the type as (described above) you don't need to do anything. The object automatically creates and initializes all members.

Again passing pointers is bad:

Account* openNewAccount(Person* client, double money){
    Account* r = new Account(client, money);
    v->push_back(r);
    return r;
}

If you return a pointer Account* you don't specify any ownership semantics. If you don't specify ownership semantics then you are very liable to leak as nobody knows who is supposed to clean up. In this situation the Account obviously belongs to the Bank object (The Bank will do the memory management). So here you should return a reference. This is an indication you can use the account. But the account will be managed by the Bank.

Account& openNewAccount(Person const& client, double money)
{
    Account  newAccount(client, money);  // Create a new account.
    v->push_back(newAccount);            // Not when you push objects into containers
                                         // they make a copy of the object.
                                         // So you have a copy of `newAccount`

    return v.last();   // return a reference to the last member of `v`
                       // that you just pushed there via `push_back`
                       // The user can now operate on the referenc
                       // Also the reference will never be NULL
                       // so the user needs to check for that.
}

Pass by reference. You don't need to check for NULL

void zmienWlasciciela(Person& o, Account* r)

// Becomes.
void zmienWlasciciela(Person& o, Account& r){
    r.owner = o;
}

Pass by reference (that's how it was given to you).

void usunRachunek(Account* r)

// Becomes
void usunRachunek(Account* r){
    cout<<"\n\n\nUSUNALEM"<<endl;
   v.remove(r);
}

Make show() const and take a stream

void show(std::ostream& out = std::cout ) const {
for (list<Account*>::iterator it = v.begin(); it != v.end(); ++it){
    (*it)->show(out);
}

You could use a simple algorithm to copy the Account to the stream.

void show(std::ostream& out = std::cout ) const
{
    // for this to work Account must have operator<< defined.
    std::copy(v.begin(), v.end(), std::ostream_iterator(out));
}

}

This is correct BUT NOT ENOUGH for your original definition where v is a pointer. If you use objects you don't need to do anything.

~Bank(){
    delete v;
}

If you were using pointers then you also need to define a copy constructor and assignment operator to make sure you are not violating the rule of three. If you are using objects the compiler generated defaults work perfectly fine.


The main problem is that you are writing/appending to the file inside the spider's parse() method - this is not how this should be done in Scrapy - there is a special place - Item Pipelines. Check this answer to see how to include a custom pipeline when running Scrapy from a script.

Note that in the pipeline you should not be appending to a file, but instead collecting the data in the process_item() method and dumping it when the spider is finished in spider_closed() method. You may also do the writing in chunks to avoid potential memory problems on large output data sizes.

Other things to improve:

adjust/increase the number of concurrent requests
turn the logging off
enable HTTP cache
Scrapy running on PyPy?


An integer is even subset of another integer

I thought that this coding style looked familiar… and indeed it is.  As I previously remarked, flag variables suck.  You shouldn't need a variable like status.

You also don't need firstNumber and secondNumber.  They are just the same as i and j, respectively.

In fact, the whole algorithm can be implemented more simply, just translating the problem description directly into code.  Iterate through the possible even factors of m.  If you find a candidate that is a factor of m but isn't a factor of n, then you can conclude that m is not an even subset of n.

public static boolean isEvenSubset(int m, int n) {
    for (int evenFactor = 2; evenFactor < m; evenFactor += 2) {
        if ((m % evenFactor == 0) && (n % evenFactor != 0)) {
            return false;
        }
    }
    return true;
}

However, there is an optimization that we can do, since factors always occur in pairs.  There is also a quick test we can do to immediately detect an obvious result, if m is odd.

public static boolean isEvenSubset(int m, int n) {
    // Optional optimization: m has no even factors
    if (m % 2 != 0) return true;

    int sqrtM = (int)(Math.sqrt(m) + 1);
    for (int evenFactor = 2; evenFactor <= sqrtM; evenFactor += 2) {
        if (m % evenFactor == 0) {
            if (n % evenFactor != 0) {
                return false;
            }
            int otherFactor = m / evenFactor;
            if ((otherFactor % 2 == 0) && (n % otherFactor != 0)) {
                return false;
            }
        }
    }
    return true;
}


How to optimize the for loop for finding a matching 2 string using fuzzywuzzy

This will not be much faster, but more readable (IMO) and extendable. You are looking for the maximum (in similarity). So, use the built-in max function. You can also define a function that does the file reading (so you can swap it out for a list of dictionaries, or whatever, for testing) and a function to be use as key. I made it slightly more complicated than needed here to give some customizability. The word it is compared to is fixed, so it is passed to the outer function, but so is the column name (you could also hard-code that).

import csv
from fuzzywuzzy.fuzz import ratio as fuzz_ratio

def get_rows(file_name):
    with open(file_name, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        yield from reader

def similarity_to(x, column_name):
    x = x.lower()
    def similarity(row):
        return fuzz_ratio(row[column_name].lower(), x)
    return similarity

if __name__ == "__main__":
    items = get_rows('all_nut_data.csv')
    name = "Hayelnut"
    best_match = max(items, key=similarity_to(name, "Food Item"))
    match_quality = similarity_to(name, "Food Item")(best_match)

max ensures that the key function is only called once per element (so no unnecessary calculations). However, since the similarity is not part of the row, you have to calculate it again at the end. On the other hand, I don't call name.lower() every loop iteration.
 Note that get_rows is a generator. This is very nice because you don't need to load the whole file into memory (just like in your code), but if you want to run it multiple times, you need to recreate the generator each time.

In the end the code as currently written can not avoid having to call the function on each row, one at a time. With max at least the iteration is partially done in C and therefore potentially faster, but not by much. For some naive tests, the built-in max is about 30% faster than a simple for loop, like you have.

The only way to get a significant speed increase would be to use a vectorized version of that function. After some digging I found out that internally the fuzzywuzzy just returns the Levenshtein ratio for the two words (after type and bound checking, and then applies some casting and rounding) from the Levenshtein module. So you could look for different modules that implemented this or try if directly using the underlying method is faster. Unfortunately I have not managed to find a vectorized version of the Levenshtein ratio (or distance) where one word is fixed and the other is not.

However, there is fuzzywuzzy.process.extractOne, which lets you customize the scoring and processing. It might be even faster than the loop run by max:

from fuzzywuzzy import process, fuzz

def processor(x):
    return x["Food Item"].lower()

def get_best_match(name, rows):
    name = {"Food Item": name}
    return process.extractOne(name, rows,
                              scorer=fuzz.ratio, processor=processor)

if __name__ == "__main__":
    rows = get_rows('all_nut_data.csv')
    name = "Hayelnut"
    best_match, match_quality = get_best_match(name, rows)
    print(best_match, match_quality)

The packing of the name in the dictionary is necessary, because the processor is called also on the query.

Using a local dictionary (from the hunspell package), which contains 65867 words, I get the following timings for finding the closest match for "Hayelnut":

OP:             207 ms ± 4.05 ms
max:            206 ms ± 8.33 ms
get_best_match: 221 ms ± 3.77 ms

So no real improvement, in fact the last function is even slightly slower! But at least all three determine that "hazelnut" is the correct choice in this case.


Unless you're very sure you can outperform CPython's list.sort() here I would recommend using it instead of custom algorithm whose implementation is hard to read.

And most likely CPython based implementation is going to be fast because we are removing pure Python loops. I can't say the same thing about other implementations, for example PyPy, you may have to time and compare them yourself.

Now to do this using list.sort() we will have to use its key argument, key argument is used for specifying custom comparison values.

In this we can map 'low', 'medium' and 'high' to some numbers and use those numbers for comparison. If possible you can also numbers such numbers from get_category itself to reduce one step.

def get_category(value):
    if 1 <= value <= 3:
        return 'low'
    elif 4 <= value <= 10:
        return 'medium'
    else:
        return 'high'

def partial_sort(numbers):
    category_weight = {'low': 1, 'medium': 2, 'high': 3}
    numbers.sort(key=lambda x: category_weight[get_category(x)])
    return None  # Can be omitted, but let's be explicit.

As you can see the resulting code is much short and easier to read.

Timing comparisons

>>> data = [5, 7, 2, 9, 1, 14, 12, 10, 5, 3] * 10**5
>>> %timeit partial_sort(data)
1 loops, best of 3: 347 ms per loop
>>> data = [5, 7, 2, 9, 1, 14, 12, 10, 5, 3] * 10**5
>>> %timeit partial_sort_op(data)
1 loops, best of 3: 435 ms per loop

>>> data = [5, 7, 2, 9, 1, 14, 12, 10, 5, 3] * 10**6
>>> %timeit partial_sort(data)
1 loops, best of 3: 3.58 s per loop
>>> data = [5, 7, 2, 9, 1, 14, 12, 10, 5, 3] * 10**6
>>> %timeit partial_sort_op(data)
1 loops, best of 3: 4.42 s per loop

Notes

Don't use camel-casing for function and variable names, in Python underscores are preferred.
Your code should be PEP-8 compliant to make it much more readable.
Read more about sorting in Python: Sorting Mini-HOW TO
If you're modifying the array in-place then it is recommended to return None instead of the array. It makes it consistent with other in-place operations we have in Python like list.append(), list.extend(), dict.update() etc. Else use sorted() with same key to get a new list and return it from your function, but creating a new list is expensive.


Counting occurrences of Char8s in a file

If you're using "Char8", then it would make a lot of sense to me to write a simple histogram type function using a mutable attay in the ST monad, and then calculate the minimum and maximum values at the end; there's no need to do it as you go.

import Data.Vector.Unboxed.Mutable as V
import Data.Vector.Unboxed as V
import Data.ByteString as B
import Control.Monad.ST
import Data.Char

histo :: B.ByteString -> (Int,Int,Int)
histo bs =
    let vec = create ( do
                mvec <- V.replicate 256 0
                forM [0 .. B.length bs - 1] $ \i -> do
                    let c = fromIntegral (B.index i bs) :: Int
                    n <- unsafeRead mvec c
                    unsafeWrite mvec c (n+1)
                return mvec
                )
        f :: (Int, Int, Int) -> Int -> Word8 -> (Int, Int, Int)
        f (mn,mx,cnt) i w =
            let mn'  = if w > 0 && w < unsafeIndex vec mn then i else mn
                mx'  = if          w > unsafeIndex vec mx then i else mx
                cnt' = if isPrint (chr . fromIntegral $ w) then cnt+1 else cnt
            in (mn', mx',cnt')

     in V.foldl' f (32, 32,0) vec -- 32 = index for ' '

This should calculate the result in constant memory (though the fold should probably be made more strict using a strict 3-tuple but all three values are forced each time f is called anyway). I haven't tested this code because I don't currently have access to a compiler so there are probably missing imports and some type errors but I hope the gist is clear.

I think this is a good demonstration of when some mutation is useful (counting lots of elements) and when functional algorithms are clearer (folding over all the data). The counting could have been done using a fold too but I think it's easier to see that here it is definitely using a constant amount of memory for the counts and should also perform quite well.


We need to be more defensive in these areas:

malloc() and family can return a null pointer.
scanf() and family can return fewer than requested conversions.

Additionally, there's no need to cast the result of malloc() - if you've correctly included <stdlib.h>, then it returns a void*, which is assignable to any pointer type.

Writing the unnecessary cast makes the code harder to review, because all casts indicate areas that need close attention by the reviewer.


Monitor Downloads folder and sort files as they are downloaded

There's a bunch of small items to consider, and then some larger items too. Starting small....

Sweating the small stuff....

cd ~/ can be shortened to just cd. Not a big deal one way, or the other, but still....
Try to quote string values, even when they do not have spaces. Your basepath variable may end up having a space in it at some point ("My Downloads" at some point?), and the quotes make it clear. Again, this is a minor item...
Having declared the basepath variable, why are you not using it? Here you have:

filename=$(inotifywait -e create --format "%f" Downloads/InternetDownloads)

which should be:

filename=$(inotifywait -e create --format "%f" "$basepath")

... note the quotes around the variable in case it ends up with spaces again.

File Extensions

You pull the extension off the file with: arr=(${filename//./ }). This replaces the dots in the filename, with spaces, then loads that space-separated list in to an array (which considers the spaces to be item-separators). Then, you pull the extension from the array with ${arr[1]}....

Ouch. This works only if there's only one . in the file name, and the file has no spaces in the name.

There's a much simpler pattern-match you can do to alleviate this problem:

extension=${filename##*.}

From the documentation:

  the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case)  or the  longest matching pattern (the ## case) deleted.

With that, there's no arrays, and the extension is the last part (or the whole filename if there are no '.' values in the file.... you need to check for that case too. There's also the possibility that a file may end with a '.', leaving an empty-value extension.... you need to check that too.

inotify

Currently you have a number of problems with inotify:

you are letting it dump messages to STDERR:

Setting up watches.
Watches established.

This is repeated for each file. It's unnecessary, and can be removed with the -q option to inotifywait.
You are using the create event to track. This is triggered when the file is created... but is that what you want? A download may take a while to complete, so moving the file part way through a download may not make sense. Many programs will continue based only on the filehandle, which does not depend on the file location, but not all programs will behave well if the file is moved part way through.

You should consider tracking the close_write event instead. This will only trigger when a file handle is clsed after a write to the file handle. I expect this will track the 'end of download' rather than the 'start of download'
inotifywait (the way you have it set up) will only notify when the first file is created. This leaves you open to race conditions where a download may happen when you are copying the file to a new location. This new download will not be triggered on the next inotifywait cycle because it started before the wait. As a result, you are at risk of losing events.

I believe the best strategy for your job would be to declare a function for the jobs you want to do with each file.... and then pipe a 'monitor' stream in to it. I have put together the following:

#!/bin/bash

function relocate {
    local filename=$1
    local extension=${filename##*.}
    # need -d to text for directories we ourselves create
    if [[ -d "$filename" || "$extension" = "" || "$extension" = "$filename" ]]
    then
        # Directory, No extension, or empty extension.
        echo "Skipping: $filename"
        return
    fi

    if [ ! -d "$extension" ]
    then
        echo "Creating directory: $extension"
        mkdir "$outdir/$extension"
    fi

    echo "Relocate: $filename -> $outdir/$extension"
    mv "$filename" "$outdir/$extension/"

}

path=${1:-.}
outdir=${2:-.}

cd $path
echo "Working in $PWD with relocate to $outdir"

inotifywait --quiet --monitor --event close_write --format "%f" .  | while read line
do
    relocate "$line"
done


Input validation

It would be good to validate user input.
If I enter "hello" as the key value,
The UI won't like it very much.

Shifting

An idea to simplify the shifting.
Instead of taking modulo for each character,
double the alphabet (concatenate the original alphabet twice), and normalize the key value.
The solution will use twice the space for the alphabet,
but the shifting will be much faster without the modulo.

Skipping unknown characters

The current algorithm checks if a character is in the alphabet, skipping without translation if it's not. So if you convert an English sentence with space characters, the word boundaries will be lost, which will be a problem when reversing the process.

Finding the index twice

The current algorithm checks is in the alphabet, if yes it calls another to perform the shift. That method finds the index again for the second time, to calculate the shifted index. This second lookup could be eliminated if you rename "shift" to "translate" and change its behavior to lookup the index once and reuse it.

Dummy data

Instead of hardcoding the dummy result it would be better to compute it using the cipher.

Naming constants

The convention is to use SHOUTCASE for constants like the alphabet.

Testing

A bunch of assertions in a main method are no substitute for proper unit testing.


Decoding and encoding JSON for a PHP service

If you are truly trying to decouple the request handling and response building from the service definition (i.e. build a template), you might want common classes which could accept some service configuration information containing things such as:

CORS configuration
Security configuration (is secure request required)
Support HTTP action verbs

And perform some of the basics around building the request and response objects

Imagine a template which looks like this:

// likely stored in configuration somewhere
$request_config = (object) [
    'https_required' => true,
    'https_forward_allowed' => true
    'http_accept' => [
        'application/json' => true,
        'xml/text' => false
    ],
    // other configurations you may need to validate a request or perhaps
    // determine its routing
];

$response_config = (object) [
    'cors_headers' => [
        'Access-Control-Allow-Origin: *',
        'Access-Control-Allow-Headers: origin, content-type, accept, authorization',
        'Access-Control-Allow-Methods: POST'
    ],
    'content-type' => 'application/json'
    // any other things you may want to configure in response
];

// instantiate response object based on configuration
try {
    // perhaps throw exception if configuration is bad
    $response = new Response($response_config);
} catch (Exception $e) {
    error_log(
        'Unable to build Response object. ' .
        'Exception message: "' . $e-getMessage . '"'
    );
    http_response_code(500);
    exit;
}

// try to build a valid request object
try {
    // instantiate request object
    // this instantiation should throw Exception (with reason) if you
    // get an unexpected request.
    // this request object constructor could check request headers
    // against expected values, try to to marshall (json_decode) the POSTed data
    // etc. and fail out with exception if request falls outside expected.
    $request = new Request($request_config);
} catch (Exception $e) {
    error_log(
        'Unable to build Request object. ' .
        'Exception message: "' . $e-getMessage . '"'
    );
    $response->set_error_code(400);
    $response->set_error_message('Bad Request');
    // call method which sends response, but would also be responsible
    // for sending appropriate method (like with internal class class to
    // (send_headers()) or similar method.
    $response->send();
    exit;
}

// now you have valid Request object you can work with and do things like:
$post_data = $request->get_post_data();

// maybe pass to the posted data to some class or otehr logic which builds
// a data structure for return.
$response->set_data(json_encode($some_data));
$response->send();
exit;

Note that the thought here is to define classes which can encapsulate the logic around validating the request against expected request headers.  You make this functionality more usable and extensable in this fashion.  For example, say you want to add an authentication/authorization component in your application.  You could ideally just have to modify the Request class to handle the extra logic around validating authentication information.

Outside of that, a few other thoughts:

$REQUEST_PROTOCOL = $isSecure ? 'https' : 'http'; What is this here for as it doesn't seem to be used anywhere else.
You have a few lines of code that are really long. Try to keep your lines under 80 characters.
You seem to start building your $response array out of order.  Where you define the empty array is several lines past the first time you try to set information into that array.


The main part of the code is converting the List<String> value into a String delimited by a comma. Instead of using an external i variable, you can use a StringBuilder and append the comma or not depending on whether it is empty or not.

Regarding your current code:

Try to avoid concatenating String with +. You should use a StringBuilder when necessary.
You don't need to make a separate code path for the case where the list is empty in the map value: the regular path handles it also.
You don't need to store the key and the value in local variables.
It is indeed a very good idea to return a new empty map instead of null when the incoming map is null.
If the value stored in the multimap is an empty list, then your code will throw an exception because it tries to access the element 0 when there is no such element.

This would be a proposed code for Java 7:

private Map<String, String> convertMultiToRegularMap(MultivaluedMap<String, String> m) {
    Map<String, String> map = new HashMap<String, String>();
    if (m == null) {
        return map;
    }
    for (Entry<String, List<String>> entry : m.entrySet()) {
        StringBuilder sb = new StringBuilder();
        for (String s : entry.getValue()) {
            if (sb.length() > 0) {
                sb.append(',');
            }
            sb.append(s);
        }
        map.put(entry.getKey(), sb.toString());
    }
    return map;
}

As a side-note, when you'll upgrade to Java 8, this code can be made simpler by using the new String.join(delimiter, elements) method.


Displaying markers for local attractions on a Google map

First off, I find it helpful to use arrays instead of multiple variables. So, how about this:

var map = [], infoWindow = [];

Then, lets rename id map to map0. This will allow us to be clever with how we reference it :)

Now we refactor initialize to use the array and reduce repetition:

function initialize(){
   initMap(0, 51.5069999695, -0.142489999533);
   initMap(1, 40.79445,-74.01558);
   initMap(2 , 48.858001709, 2.29460000992);
}

function initMap(ndx, lat, lng){
   var feed = new google.maps.LatLng(lat, lng);

   map[ndx] = new google.maps.Map(document.getElementById('map'+ndx), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: feed,
      zoom: 11
   });

   var request = {
      location: feed,
      radius: 5000
   };

   infoWindow[ndx] = new google.maps.InfoWindow();
   var service = new google.maps.places.PlacesService(map);
   service.search(request, callback);
}

Finally, lets refactor createMarker to use the arrays as well.

function callback(results, status) {
   if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
         createMarker(0, results[i]);
         createMarker(1, results[i]);
         createMarker(2, results[i]);
      }
   }
}

function createMarker(ndx, place) {
   var marker = new google.maps.Marker({
      animation: google.maps.Animation.DROP,
      map: map[ndx],
      position: place.geometry.location
   });

   google.maps.event.addListener(marker, 'click', function() {
      infowindow[ndx].setContent(place.name);
      infowindow[ndx].open(map[ndx], this);
   });
}

google.maps.event.addDomListener(window, 'load', initialize);

Finally, don't forget to rename map to map0


I don't think your considerations are a big problem.

However what I think is a bigger problem is the amount of verbosity and repetition in your code. While the code is readable as is, adding more elements in the future will make your __init__() method inflate and become unreadable.

This is because you are adding each Element individually. In large applications this is largely unfeasible when you have more than a dozen widgets, for reasons I am sure you can understand.

There are a couple of solutions to this:

Generate Layout using code

instead of doing this:

self.window.new_button = Gtk.Button(label="New")
self.window.new_button.connect("clicked", self.on_new_clicked)
self.window.hbox.pack_start(self.window.new_button, False, False, 0)

# ... repeat for all buttons

you can do this

buttons = [("New", self.on_new_clicked),
           ("Save", self.on_save_clicked),
           ("eMail", self.on_email_clicked),
           ("Pen", self.on_pen_clicked),
          ]

for name, callback in buttons:
    b = Gtk.Button(label=button)
    b.connect("clicked", callback)
    self.window.hbox.pack_start(b, False, False, 0)

Subclass standard widgets

Often you can also clean up your application by subclassing other widgets:

class myButtonBox(Gtk.ButtonBox):
    def __init__(self, *args, **kwargs):

        # add all buttons to self here

        super().__init__(*args, **kwargs)
        # note: super() without args works only in new versions of Python

Seperate Interface and logic by using GtkBuilder xml

I am mentioning this last since this is the best option, but not very frequently worth the effort.

The Gtk 3 Tutorial has a very nice page on GtkBuilder

  The Gtk.Builder class offers you the opportunity to design user
  interfaces without writing a single line of code. This is possible
  through describing the interface by a XML file and then loading the
  XML description at runtime and create the objects automatically, which
  the Builder class does for you. For the purpose of not needing to
  write the XML manually the Glade application lets you create the user
  interface in a WYSIWYG (what you see is what you get) manner

  This method has several advantages:

  Less code needs to be written.
  UI changes can be seen more quickly, so UIs are able to improve.
  Designers without programming skills can create and edit UIs.
  The description of the user interface is independent from the programming language being used.

  There is still code required for handling interface changes triggered by the user,
  but Gtk.Builder allows you to focus on implementing that
  functionality.


"Causes" Puzzle solution (network of words with Levenshtein distance 1)

Here is one idea: You could first put the words into a hashmap, the length of them being the key. O(n)

Then, since you are only interested in "causes", grab that word and make a node and remove it from the hashmap.

Then, a recursive function

adds all friends to the node that are in the hashmap (only looking at the relevant lengths)
removes those from the hashmap
calls itself on those new nodes

The end result is the social graph of "causes".

It really depends what you are interested in in improving though: For instance, one could assume the whole thing is only called once for a fixed string, or it could be called many many times for different inputs. Depending on that, one might precompute more.


Generalizing the Initialization of Singleton Derived Classes

Personally I've always preferred to have limited number of singletons in a project. Generally there's a good need for them, but how you implement them is another question. For instance I've seen people have a single singleton before with properties that were the objects it needed to have single instances of. Obviously any objects linked in a singleton will only have one if you access them through the singleton. this allows you to have ONE singleton object as a sort of container to hold any objects that need to be singletons. Mind you this is a personal preference, so I will digress.

I think the answer you're looking for is here https://stackoverflow.com/questions/16745629/how-to-abstract-a-singleton-class

It requires both the self-referencing generic typing and the use of the new() constraint.

This is the closest I've ever seen to what you're trying to do. It is not very strictly enforced though because of the need for the new() constraint.


Code runs Speed Test CLI using the python wrapper and then stores values within CSV

Don't use globals. E.g., you refer to df and df2 in csv_upload, why not make them parameters?
Use the standard if __name__ == '__main__': guard around the script's main body.
It's common to just accept a flat file path, and expect the calling code to perform any os.path.join in the creation of said path.
"upload" sounds like network activity, but you're saving the data to disk. This should probably follow a more typical naming scheme of to_csv or save or dump or something of that sort.
This seems like a prime candidate for being a class.

I'd suggest something like the following:

import speedtest
import pandas as pd
import os

class MySpeedtest:
    def __init__(servers, initial_data_path=None):
        # Initial Speedtest variables
        self.s = speedtest.Speedtest()
        self.servers = servers

        if initial_data_path is not None:
            self.df = pd.read_csv(initial_data_path)
        else:
            self.df = pd.DataFrame()

    def run_test(self):
        """Makes use of the speed-test-cli python wrapper
        to get speed test data and returns in a dictionary"""
        self.s.get_servers(self.servers)
        self.s.get_best_server()
        self.s.download()
        self.s.upload()
        self.s.results.share()
        results_dict = self.s.results.dict()
        self.df.append(pd.io.json.json_normalize(results_dict))

    @staticmethod
    def convert_mbps(arg):
        return arg / 1000000
        # Actually, this should probably be "arg / (2**20)"
        # 1 MB = 2**20 B

    def to_csv(self, path):
        """Attempts to append a csv file and, if none
        exists, creates one in a specified path"""
        self.df.to_csv(path, index=False)

if __name__ == '__main__':
    # TODO: populate a list of servers, define localpath/filepath/filename
    tester = MySpeedtest(servers, localpath)
    tester.run_test()
    tester.to_csv(os.path.join(filepath, filename))


Extracting opening and closing times for each day of the week

Your thinking is good: it's a small difference but... there is a difference. And you have to find a way to extract the difference out of the methods and try create a parameter from this. Small example:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Value { get; set; }
}

We could then group them by Id or Value for example:

public Item GetItemGroupedByName(List<Item> items)
{
    return items.GroupBy(x => x.Id).First().First();
}

public Item GetItemGroupedByValue(List<Item> items)
{
    return items.GroupBy(x => x.Value).First().First();
}

This gives the same kind of situation like yours. Luckily there's the Func<T, TResult> Delegate. The method can now look like this:

public Item GetItemGrouped(List<Item> items, Func<Item, int> rule)
{
    return items.GroupBy(rule).First().First();
}

And you call it like this:

GetItemGrouped(list, x => x.Value);
//or:
GetItemGrouped(list, x => x.Id);

Of course you can't group by Name in this case as it is a string property and the Func expects an integer. You might change the int to object, but please don't as that is hacky code. Since the purpose of your method is to group by a TimeSpan, you can implement this easily:

private static OpeningDay GetUsallyOpeningHour(List<OpeningDay> openingHoursDaily,
                                               DayOfWeek dayOfWeek,
                                               Func<OpeningDay, TimeSpan> groupByRule)
{
    var listOfSpecificDayOfWeek = openingHoursDaily.Where(x => x.DateTime.DayOfWeek == dayOfWeek);

    if(listOfSpecificDayOfWeek.Any())
        return listOfSpecificDayOfWeek.GroupBy(groupByRule)
                                      .OrderByDescending(x => x.Count())
                                      .ThenByDescending(x => x.Key)
                                      .First().First();

    return new OpeningDay { From = new TimeSpan(0, 0, 0), To = new TimeSpan(0, 0, 0), DateTime = DateTime.Now };
}

And now you can call the method like:

var openingDay = GetUsallyOpeningHour(openingHours, DayOfWeek.Thursday, x => x.From);
//or:
var openingDay = GetUsallyOpeningHour(openingHours, DayOfWeek.Thursday, x => x.To);


Construct list from a dataframe and a formula

Code Quality
Blank Lines
Generally, your code quality needs some improvement. For example, insert blank lines. So instead of
factors <- rownames(attr(tf, "factors"))
tvars <- attr(tf, "variables")
tlabs <- attr(tf, "term.labels")

I would suggest
factors <- rownames(attr(tf, "factors"))

tvars <- attr(tf, "variables")

tlabs <- attr(tf, "term.labels")

Order Within A Script or Source Code
Generally, one puts package import statements at the top of a file. Which you are not doing, and you also give no reason why you are doing it. So I would put library(lazyeval) at the top.
Further, you set variables before you use them. For example, factors <- rownames(attr(tf, "factors")).
These observations lead to the following script.
# to use 'as.lazy' and 'lazy_eval'
library(lazyeval)

dat <- data.frame(
  A = c("a", "b", "c"),
  B = c("x", "y", "z"),
  NotUsed = c(1, 2, 3))

frml <- ~ A + B + A:B
tf <- terms.formula(frml)

tvars <- attr(tf, "variables")
used <- lapply(eval(tvars, envir = dat), as.factor)
names(used) <- rownames(attr(tf, "factors"))

tlabs <- attr(tf, "term.labels")

lapply(tlabs, function(tlab){
  droplevels(lazy_eval(as.lazy(tlab), data = used))
})

Please pay attention to how a grouped the code lines.
A Better Way
Regarding a better way, for which you have asked, I would propose the following.
dat <- data.frame(A = c("a", "b", "c"),
                  B = c("x", "y", "z"),
                  NotUsed = c(1, 2, 3))

dat <- subset(x = dat, select = -NotUsed)

dat$c <- as.factor(paste(dat$A, dat$B, sep = ":"))

my.list <- lapply(dat,
                  FUN = function(column)
                  {
                      return(column)
                  })

In my view, this is a better way because it expresses your intention better. If you would have given me your code without any comments I would have a hard time explaining what it does or what it's purpose is. In addition, it does not require an additional package.
HTH!


Whenever you are passing arguments in C++, you must be a bit more careful. Since C++ is a default by-value language, passing in a std::vector the way you are doing it will create a full copy of the vector each time you call the function. This is expensive, and not needed. Instead, you should be passing by const &:

bool check_pass(const vector<string>& tomatch, const vector<string>& userlist)

The same thing applies when using a range-based for loop:

for (const string& uline : userlist)

Or you could simply let C++ deduce the type for you, using auto:

for (const auto& uline : userlist)

string has some methods that can help make your code a bit shorter and clearer; such as find:

auto place = uline.find(',');

As @janos has already mentioned, using a map (or unordered_map) would be a better fit here. This could look something like:

std::unordered_map<std::string, std::string> user_to_pwd;
while (getline(userfile, line)) {
    const auto index = line.find(',');
    user_to_pwd.insert(
        std::make_pair(line.substr(0, index), line.substr(index + 1));
}

Your check_pass function could then simply take three parameters: the map, and the username and password. This then becomes a (fast) lookup:

bool check_pass(
    const std::unordered_map<std::string, std::string>& user_pwds,
    const std::string& user,
    const std::string& password)
{
    auto it = user_pwds.find(user);
    if(it == user_pwds.end()) {
        return false;
    }
    return it->second == password;
}

Note also that you should not use using namespace std; up the top. This pulls everything from the std namespace into the global namespace, which can cause all sorts of issues. For small programs it probably won't, but it's best not to get into the habit of using it anyway.


#include <numeric>!

I see no reason why individual score is computed via std::accumulate, but the total uses a loop. I recommend std::inner_product there, at least for consistency.

Similarly, the

        for(int loop = 0;loop < 256;++loop) { data[loop] = loop;}

is

        std::iota(data, data + 256, 0);

Of course, a magic 256 shall be replaced by a symbolic name.

I don't feel comfortable with std::set used just to avoid sorting. It  obscures the intention. You seem to have the same feeling, and put the clarifying comment. I recommend to be explicit: read the names into a vector, and sort it. BTW, it would also reduce space requirements.


"Strone"?  What's a "strone"?  Oh… of course!

In seriousness, naming could be improved.  They are obviously arrays of strings; the Hungarian prefix is unnecessary.  Also, as constants, they should be declared static final and named with ALL_CAPS.

public class NumberToWords {
    private static final ONES = { "One", "Two", … };
    private static final TENS = { "Ten", "Twenty", … };
    …
}

Helper functions should be private.

It is customary to put the static keyword after the access modifier, as in public static void main(…).  It is unconventional to say static public boolean ConvertNumberToText(…).  Also, functions should be namedStartingWithLowerCase().

Using a single-element array as a parameter so that you can pass back the result as an out-parameter is very weird.  Using a StringBuilder would be a bit more obvious, but still very odd.  The right approach should be to return a String, and throw an exception if necessary — perhaps NumberFormatException.  Ideally, your code should be able to handle every possible int input, making errors impossible.


Allowing users to subscribe to categories

When you load the user, you can include the categories using eager loading.

@user = User.includes(:categories).find(params[:id])

or

@user = User.find(params[:id])
@categories = @user.categories.all


What I see here:

1.

You use autos, whose bit length is unknown in compile time. Despite that, the code uses them as 64-bit values. Afaik you should have some structural guarantee that they are really 64-bit (f.e. instead of "auto" use simply uint64_t).

2.

This code:

uint32_t version = 0;
version = ((eid >> 32) & 0xFFFFFFFF) + 1;

could be simplified to

uint32_t version = ((eid >> 32) & 0xFFFFFFFF) + 1;


I've never tackled such a problem before, so I'll proceed with this cautiously.

You don't need to declare those three variables and then assign to them.  Instead, initialize them right away where they're first used.

You can also move number right above the cin for slightly closer scope.

std::cout << "Enter the number: ";
int number;
std::cin >> number;
int first_digit = number/10;
int second_digit = number%10;

I suppose switch is an okay choice for this program.  Either way, the switch can still be condensed while making the program more modular (with functions).

Here's what 11-20 could look like within its own function:

std::string elevenThroughTwenty(unsigned int number)
{
    switch (number)
    {
        case 11: return "eleven";
        // ...
        case 20: return "twenty"; // you forgot the 20 in your code

        // throw an exception if number not in the switch
        // include <stdexcept> to use this
        default: throw std::logic_error("Not 11 through 20");
    }
}

Separating them as such helps with readability, organization, and conciseness.  You will also need proper defaults so that invalid numbers don't cause crippling errors.