C++: Generating similar methods with macros

Do you consider this a good solution?

No.

  Would you have done it another way?

Yes.

Macros are never the solution. There is always a better tool. Macros are designed to deal with Hardware/OS/Compiler variations. You should limit their use to this situaation.

It looks like your macros are used to manually insert functions for specific situations. It seems like these could be deduced using template specializations. It is hard to provide a better solution without more code. But let my give it a go (this will probably be wrong as I don't have enough information).

template<typename Type>
TypeOfLuaObject LuaState::lua;

template<typename Type>
struct DoCheck;
template<typename Type>
struct DoConversion;

// Provide a specialization of these two macros for each
// type you are using.
template<>
struct DoCheck<int>
{
    bool operator()(TypeOfLuaObject& lauObjec, int val) const {return lua_isnumber(lauObjec, val);}
};
template<>
struct DoConversion<int>
{
    int operator()(TypeOfLuaObject& lauObjec, int val) const {return lua_tonumber(lauObjec, val);}
};

// The main function can then be left in its generalized form
// It will pick up the specialization of the above macros.
// Type will be deduced automatically from `def` parameter and the other two
// template parameters will be deduced from `Type` so you do not need to manually
// specify the type when calling.
template<typename Type, typename Check=DoCheck<Type>, Conversion=DoConversion<T>>
Type LuaState::getTableField(const char* table, const char* key, Type def)
{
    lua_getglobal(lua, table);
    if (!lua_istable(lua, -1))
    {
        return def;
    }
    Type result;
    lua_pushstring(lua, key);
    lua_gettable(lua, -2);
    Check doCheckObj;
    if (!checkObj(lua, -1))
    {
        result = def;
    }
    else
    {
        Conversion doConversionObj;
        result = doConversionObj(lua, -1);
    }
    lua_pop(lua, 1);
    return result;
}

Other comments:

When you use macros. Make sure they are all uppercase.

Macros do not obey scope boundaries. So we reserve all uppercase letters for macros to prevent accidental smashing of normal variables.

Don't use '_' as a prefix for identifiers.
Most people don't know the actual rules for this. So even if you do it will confuse them.

But you are breaking the rule with your macros _getGlobal and _getTableField. As they are macros they are not bound by the scope of your namespace and thus could potentially be trampling on some system macro.

See the artile I wrote on SO: https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797


Implementing a temporary data context manager

I just realized, that I can simplify mktemp by directly returning the tempfile._TemporaryFileWrapper's buffer, which can be used in a file context for open and closing without deleting the superordinate _TemporaryFileWrapper:

def mktemp(self, mode='w+b', encoding=None, suffix=''):
    """Creates and registers a named temporary
    file and returns the file object.
    """
    return self.enter_context(NamedTemporaryFile(
        mode=mode, encoding=encoding, suffix=suffix, prefix=self.prefix,
        dir=self.root)).file

Update
With the change above, the returned buffer does not behave as expected regarding its attribute name.
To fix that, I introduced a wrapper class:

class NamedFile:
    """Wraps a file buffer and its associated name."""

    def __init__(self, file, name):
        """Sets buffer and name."""
        self.file = file
        self.name = name

    def __enter__(self):
        self.file.__enter__()
        return self

    def __exit__(self, typ, value, traceback):
        return self.file.__exit__(typ, value, traceback)

    def __getattr__(self, attr):
        return getattr(self.file, attr)

    @classmethod
    def from_ntf(cls, named_temporary_file):
        """Creates a named file from the specified NamedTemporaryFile."""
        return cls(named_temporary_file.file, named_temporary_file.name)

And return it instead of the raw buffer accordingly:

def mktemp(self, mode='w+b', encoding=None, suffix=''):
    """Creates and registers a named temporary
    file and returns the file object.
    """
    return NamedFile.from_ntf(self.enter_context(NamedTemporaryFile(
        mode=mode, encoding=encoding, suffix=suffix, prefix=self.prefix,
        dir=self.root)))


Repeated sequential subsetting of data.table

I am not a data.table expert so I can't tell if there is a faster approach, though https://stackoverflow.com/q/16573995/1201032 suggests you are already using something efficient at each step.

The changes I have to suggest would however make your code a lot easier to read and maintain. First, define a function that can be applied at each step:

max_subset <- function(dt, var, by)
  dt[dt[, .I[which.max(get(var))], by = by][,V1]]

Then, you can make your successive calls as follows:

step <- payoff_mat
step <- max_subset(step, "V3", c("V4", "V5"))
step <- max_subset(step, "V2", c("V4"))
step <- max_subset(step, "V1", c())

Or using the magrittr package:

library(magrittr)
payoff_mat %>% max_subset("V3", c("V4", "V5")) %>%
               max_subset("V2", c("V4")) %>%
               max_subset("V1", c()) -> step3

Note that assigning intermediate outputs to a variable in the first approach (step <- ...) should not carry any significant time (feel free to test). And your code will be a lot more readable than using nested calls: max_subset(max_subset(max_subset(...), ..., ...).


From a string of 3 numbers to 3 integers

I'd write the code as

fn main() {
    let input = "   455   123   42  ";

    let numbers: Result<Vec<i32>, _> = input
        .split_whitespace()
        .map(str::parse)
        .collect();

    println!("{:?}", numbers);
}

As mentioned in a comment, iterators are very idiomatic in Rust. The Iterator trait is the main documentation to check out. Once you have an iterator, such as by calling split_whitespace, you can do powerful things.

In this case, we can map a closure or a function across each element in the iterator, converting it from one type to another. Although we could have used map(|the_string| the_string.parse()), I prefer the shorter form of syntax when I can use it.

We converted each element using str::parse, which returns a Result, one of Rust's main error handling types. At this point, each element from the iterator will be a Result, but we don't know what type it is yet! parse is powerful in that you can parse to many types, but that power comes at a cost — you have to specify what type you want to parse to. In the original code, the turbofish operator was used (::<>), but I'm not the biggest fan of the fish.

After all this code, we haven't really done anything yet. Rust iterators don't do anything until you pull values from them via next. We could call next over and over ourselves, but in this case I'd like a collection of all the values. That's where collect comes into play.

Similar to str::parse, collect allows the caller to specify what type should be collected into. This allows us to collect into a Vec or a HashSet or many other types. In this case, we can collect into Result. If any of the iterator values were invalid, the entire collection will be invalid with the first found error. Otherwise, we will construct a Vec. Here is where we finally specify what type to parse into as well: an i32. We leave the error type up to the compiler by using the underscore _; once we have specified what kind of type to parse to, we also specify the error type.

To wrap it all up, we print the value to the user using the Debug formatter. This will show us if the Result was an Ok with the entire vector of values or an Err along with the error itself.

  bad error handling

I'd point out that your original code has more error handling compared to many other languages, just because of Rust. For example, each call to unwrap or panic is error handling that other languages might have deferred to runtime (or never!). You handled the cases of the iterator being too short (although see below) as well as when the number failed to parse.

Your error reporting mechanism is fairly basic: the program ends when an error is encountered. There's nothing wrong with that though. It's far better than continuing on when you don't know how to!

As a side note, it's undefined behavior what the result of calling Iterator::next after it returns None the first time. The iterator is free to return nonsense values. If you need to call an next multiple times without checking the value in between each call, you should fuse the iterator, ensuring it will always return None after the first None.


PHP MVC implementation without a framework

Before you consider any answer, always consider the rule that you should not write code which is not helpful and avoid code which is unused. When you are using an external framework there is a community which maintains it for you. Here its only you who is the expert.

Less code you write, less maintenance & faster development time.
More readable and maintainable code, easier it is.

Feedback on your code.

Routes.php is quite simplistic. It is not necessarily bad but you havent considered how you would pass on different types of values.
The framework considers only routing as the primary goal of the framework. But you havent considered other things like DB query, Caching, Templating, Security. etc
You are loosing a lot of flexibility in file management when with the current routes framework.

In addition to the above I suggest including two more pieces of code.

A general file (include_top.php) which gets included in top of all files. It might look something like the following

<?
session_start();
//do some global configurations
function __autoload($className) {
    // Put your own directory structure here //
    if(file_exists("../classes/$className.php"))
    include_once "../classes/$className.php";
}
?>

This helps you to easily structure your code into different folders without worry about certain import statements having right path and doing additional global configurations.
An ORM (Object-relational mapping) is a must for any scalable
framework. You can checkout existing frameworks already. I will put a plug for my own light weight ORM.


Return the repeated number and the missing number

There is a shortcut you can take to find the missing number after you've found the duplicated number.  You may have come across this fact before, where the sum of the numbers 1 to n is n*(n+1)/2.  We can leverage this along with the duplicated number to find the missing number.  If you add up every number in your list and subtract that from what the expected sum would be from 1 to n, most of the terms will cancel, leaving you with missing - duplicate.  You can visualize that with an example:

 (1+2+3+4+5+6+7)
-(1+2+3+4+5+1+7)
=(6)-(1)

In that example, n is 7, the duplicated number is 1, and the missing number is 6.  So you get the formula expected_sum - actual_sum = missing - duplicate.  We can solve for missing by adding duplicate to both sides, leaving us with missing = expected_sum - actual_sum + duplicate!  Let's do that.

First, you can calculate the expected sum from that formula, n*(n+1)/2.  In your loop searching for the duplicate, you will need to keep a running total (and don't break early).  After you find the sum of your list and identify the duplicate number, you can calculate the missing number using the formula we talked about in the above example, missing = expected_sum - actual_sum + duplicate.

Also, you don't need to record the frequency as an integer, you can just keep a list of booleans for numbers already seen.  I've also taken the liberty of cleaning up the indentation issues and renaming some of the variables for the purpose of readability.  Here is the solution:

public class Solution {
    // DO NOT MODIFY THE LIST. IT IS READ ONLY
    public ArrayList<Integer> repeatedNumber(final List<Integer> A) {
        //O(n) solution
        //Keep a record of all the numbers appearing in the list
        boolean [] seen = new boolean[A.size()];

        int rep_num = 0, miss_num = 0;
        int expected_sum = A.size() * (A.size() + 1) / 2;
        int actual_sum = 0;

        //Find sum of list and identify duplicate number
        for( int i = 0; i < A.size(); i++ )
        {
            int num = A.get(i);
            if(seen[num - 1])
                rep_num = num;

            seen[num - 1] = true;
            actual_sum += num;
        }

        miss_num = expected_sum - actual_sum + rep_num;

        ArrayList<Integer> results = new ArrayList<Integer>();
        results.add(rep_num);
        results.add(miss_num);

        return results;
    }
}


Use Python to determine the repeating pattern in a string (no leftovers)

length = (len(s))

Unnecessary ( )’s.

 range_list = (range(1, len(s)+1))

Again, unnecessary ( )’s.  Does not actually create a list, just a range object, so a better name is in order.   And you can remove this entire statement (see below).

 list_char = list(s)

You don’t need to create a list of characters to solve this problem.  (More later.)

 divisors = []

Unnecessary statement.  Made obsolete by very next statement:

 divisors = [x for x in range_list if (length)% (x) == 0]

Unnecessary ( )’s ... twice.  Could replace range_list with range(1, len(s)+1), and remove above range_list = .....

 max_pieces = []

Misleading and useless.  You store a single integer in this variable later, not a list.

 for i in range (len(divisors)):
     size = divisors[i]

A more pythonic way would be:

 for size in divisors:

I might use divisor instead of size, when looping over a list of divisors.

     split = [list_char[i:i+size] for i in range(0, length, size)]

Confusing.   i is already used in outer loop.  List comprehension’s i is (fortunately) a separate variable ... but give it a different name ... maybe j.

Instead of list_char[i:i+size], you could simply use s[i:i+size].  This would return a substring instead of a sublist of characters, which would be just as effective.

     if(all(x == split[0] for x in split)):

The if statement does not need the outer ( )’s.

         max_pieces = int(length/size)

More pythonic would be max_pieces = length // size

         break
 return max_pieces

break could be replaced with just return max_pieces.  And the current return statement replaced with an error message or return 1 catch-all.


Determining a value given the coordinates for numbers arranged in a triangular fashion

I don't see why you should return the answer as a string.  That makes your mathematical function weird.

You shouldn't use flag variables like not_finished = True; they are almost never necessary, and in this case not_finished is totally superfluous, since it is always True.  Actually, this loop would be better written as

for counter in itertools.count(1):
    x_cord = 0
    …

Your solution is brute force.  I would characterize it as \$O(\max(x^2, y^2))\$.  Of course, performance is going to be a problem with large coordinates.  The solution is not to use memoization, but to work out a formula for the answer.

First, note that the numbers along the bottom (\$\mathit{fn}(x, 1)\$) are recognizable as the triangular numbers, and even if you didn't recognize them, you could easily figure out the formula.  Then, you can count backwards along the \$\nwarrow\$ diagonal.

$$\begin{align}
\mathit{fn}(x, 1) =&\ 1 + 2 + 3 + \ldots + x = \frac{x\ (x+1)}{2} \\
\mathit{fn}(x - 1, 2) =&\ \mathit{fn}(x, 1) - 1 \\
\mathit{fn}(a - 2, 3) =&\ \mathit{fn}(a, 1) - 2 \\
 \vdots& \\
\mathit{fn}(a - (y-1), y) =&\ \mathit{fn}(a, 1) - (y-1) \\
 \vdots& \ \scriptstyle{a\ =\ x+y - 1} \\
\mathit{fn}(x, y) =&\ \mathit{fn}(x + y - 1, 1) - (y - 1) = \frac{(x + y)(x + y - 1)}{2} - (y - 1)
\end{align}$$


Programmatically getting the GUID of an application

Well, there isn't much to say here. But I still see some stuff I don't really like.

The implementations of Lazy<Guid> _MyGuid and Guid GetMyGuid() are quite simple and easy to read and understand. What bothers me here is that for the variable, and both methods the documentation is almost the same. But, at least for me, more critical is the documentation of Guid GetMyGuid() which states "Lazily gets ..." which is clearly an implementation detail which I wouldn't show.

The method Guid GetGuid() is another thing. IMO its very hard to read and understand by sprawling the Guid.TryParse() over 3 lines.

The change I will suggest is a little bit longer but its more readable, at least for me

public static Guid GetGuid(this Assembly assembly)
{
    var guidAttribute = (GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault();
    if(Guid.TryParse(guidAttribute?.Value, out Guid guid)) { return guid; }
    return Guid.Empty;
}

which could also be written like so

public static Guid GetGuid(this Assembly assembly)
{
    var guidAttribute = (GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault();
    Guid.TryParse(guidAttribute?.Value, out Guid guid); // If Guid.TryParse returns false the out Guid is Guid.Empty
    return guid;
}


Three Cards Trick - Assigning random number to the cards

Style

The name CreateCard is pretty bad. One would expect it to create a card and return it.

Making things easier to change

At the moment, if you ever want to use 4 or 5 cards instead of 3, you have to update code in multiple places : Q = random.randint(1,HERE), cards = HERE (3 times) and add tests like elif Q == VALUE:. This is just too easy to get wrong.

Even assuming you can only use randint, you have various ways to achieve what you are doing in a less repetitive way.
First idea would be to tell that once you've generated the position for Q with q_pos = random.randint(1,nb_cards), you know you have q_pos -1 'A' cards before it and nb_cards - q_pos after.

This becomes :

def shuffle(nb_cards):
    q_pos = randint(1,nb_cards)
    return ['A'] *  (q_pos -1) + ['Q'] + ['A'] * (nb_cards - q_pos)

A different strategy would be to create a list of 'A's and just put Q somewhere.

def shuffle(nb_cards):
    cards = ['A'] * nb_cards
    q_pos = randint(0,nb_cards-1)
    cards[q_pos] = 'Q'
    return cards


Is there something particular wrong with the following implementation which could lead to major issues?

Yes; the union seems to be used in a way that is actually Undefined Behavior.  Let’s see…

    f32.IEEE.Sign = bits.IEEE.Sign;
    f32.IEEE.Exp  = bits.IEEE.Exp + 112;
    f32.IEEE.Man  = bits.IEEE.Man << 13;

    return f32.Float;

Yes, you are reading from the Float member that is never written to, the optimizer can know that it is not the active member, and act as if the program never reaches this point.  Anything is possible, including crashing.

We have seen the optimizers get more and more aggressive, taking advantage of U.B., breaking “bad” code that worked historically.  So, it is a real concern.  In any case, the layout of the bit fields is up to the implementation; that is only an issue if you plan on saving these 16-bit values to files.

See Scott Schurr’s presentation on this.  Your specific case is handled toward the end, and he shows that of all the work-arounds, using intrinsic memcpy with the items known to be properly aligned will be completely optimized out by the compiler, generating the code you really intended with the union!

See also ⧺ES.9.

float   f32 = (float)f16;

Don’t use C-style casts.  Any appearance of such a cast is a flag for code review; casts that are actually needed should be function style, specialized, or use clearly named helper functions.

You supplied an implicit conversion, so you don’t need this cast at all.


Look here:

for (int i = 0; i < strlen(input); i++) {

Note that strlen(input) is O(n), proportional to the length of the input.  That makes your algorithm O(n2), which is slower than it should be.  If you need to call strlen(), make sure to call it just once.  However, this problem is easily solvable without using strlen() at all.

Others have pointed out your memory leak.  What should be done about it?  The output is never longer than the input, right?  Therefore, I would say that your best option is to overwrite the input with the sanitized output.  There is no need to allocate any additional memory, and no need to worry about the buffer size.  (If the caller wants to keep the original string, then the caller can duplicate it first.)

There is no need to write a to_lowercase() function that calls tolower() on each character in the string.  Just call tolower() as part of the loop.

The character_value comparisons could be simplified to isalpha(character_value).  Your naming style is inconsistent between character_value and wordMatched.  I would change int character_value to char c.

With this code…

} else if (wordMatched) {
    wordMatched = false;
    sanitized[iterator++] = ' ';
}

… you output a space when transitioning from a letter to a non-letter.  However, that would output a space corresponding to the 7 at the end of 13What213are;11you-123+138doing7.  In my opinion, it would be better if it didn't output a space at the end.

Suggested solution

I've put some miscellaneous remarks in comments.

#include <assert.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>              // You missed this for printf(3)
#include <stdlib.h>

/**
 * Replaces consecutive non-alphabetic characters in the input
 * string with a single space.  Non-alphabetic characters at the
 * beginning and end are trimmed off as well.  The remaining ASCII
 * letters are replaced with their lowercase counterparts.
 *
 * The input string will be overwritten.
 *
 * Returns the length of the sanitized output.
 */
size_t sanitize(char *s) {
    bool needSpace = false;
    char *out = s;
    for (char *in = s; *in != '\0'; in++) {
        assert(out <= in);
        if (isalpha(*in)) {
            if (needSpace) *out++ = ' ';
            needSpace = false;
            *out++ = tolower(*in);
        } else if (out > s) {
            needSpace = true;
        }
    }
    *out = '\0';
    return out - s;
}

int main(int argc, const char *argv[]) {
    char line[1024];
    FILE *file = stdin;        // Read from stdin if no filename given
    if (argc > 1 && !(file = fopen(argv[1], "r"))) {
        perror(argv[1]);       // Some error handling that you didn't have
        return EXIT_FAILURE;
    }
    while (fgets(line, sizeof(line), file)) {
        sanitize(line);
        puts(line);            // Don't need printf() when puts() will do
    }
}


Some quick remarks

variables should be named using camelCase casing
avoid declaring multiple variables on the same line to improve readability.
don't trust the users of your app! Never trust them! If you think, hey they can read and follow instructions you will get into great pain. Always check that inputs are valid. That beeing said you should use int.TryParse() instead of Convert.ToInt32()
method arguments should be named using camelCase casing as well.
let your variables have some room to breathe (see the % operator)
don't use abbreviations for naming stuff. In a few months you won't know what they are about.
comments should explain why something is done in the way it is. Let the code speak for itself what is done by using names as descriptive as possible.


Two remarks on your code:

There seems to be an indentation error in your code, everything before your first for loop has too much indentation.

In general, it is a good idea to use telling names for variables. For example, column and row instead of a and b.

Following is my version of the code. It is not an exact reproduction of your plot, but the way I would approach an analysis like this:
from sklearn.datasets import load_iris
import pandas as pd
import seaborn as sns

iris = load_iris()

# convert dataset to pandas DataFrame
iris_df = pd.DataFrame(iris['data'])
iris_df.columns = iris['feature_names']
iris_df['species'] = iris['target']
iris_df['species'] = iris_df['species'].replace([0, 1, 2],  iris['target_names'])

# alternative: load dataset from seaborn library (they use slightly different column names)
# iris_df = sns.load_dataset('iris')

sns.pairplot(data=iris_df, corner=True, hue='species')

This produces the following plot:

As you can see, the code has become much shorter and the resulting figure still contains all the plots you wanted (plus a few extra ones). Great thing about using pandas and other related libraries (e.g., seaborn) is that you can often write very compact code (e.g., by getting rid of many for loops).
First, I converted the iris dataset to a pandas DataFrame (documentation). A DataFrame is the main data type in pandas and makes analysis and processing of your data much easier. As shown in the code, there is an alternative way of loading the iris dataset into python using the seaborn library (sns.load_dataset('iris')) This will give you the dataset directly as a DataFrame, no more need to convert it.
Then, I call pairplot from the seaborn library. seaborn is a plotting library based on matplotlib that works with DataFrame objects. It has a high-level interface, meaning you can produce complex plots such as the one you see with often a few lines of code.

I just found out that pandas already has a very similar plot function, check out  scatter_matrix. So you don't necessarily need to use seaborn (even though it's a great library and I recommend it).


Scrape data from a webpage and store them in a database

The database setup mydb should be in it's own function, or even just
a global since this script is rather minimal.  There's no reason to
duplicate this code.
If mysql.connector doesn't, I'd look for a database connector that
supports the with ... statement for connections and transactions
(relatively sure e.g. sqlalchemy supports that).  Because you can
always forget to call commit (or rollback), but with with you
have a little bit less mental overhead.
It's a simple script ... long term I'd worry about losing data that
way.  Also why is it dropping the whole table instead of, say,
DELETE FROM webdata; and only recreating the table if it doesn't
exist?
The bs4 part looks okay and the insert too; I'd perhaps have some
checks in there that you don't overflow on the 255 limit with the
review (or the name I suppose).  Also some warnings around empty
values might be good for you to debug / notice that something's off.
AFAIK requests is a good choice, you might also want to check the
status code though.

Okay, so long-term:

To be more flexible, look at argparse or any of the command line
parsing libraries so that you never have to edit the script in case
one of the parameters changes (database connection, URL).  I'd keep
the HTML querying like it is, that's usually not wise to put into a
configuration unless it changes frequently.


Is there a more efficient way to simulate in R, by exposition factor, gender and disease profile?

There are a few improvements to your (I'm assuming that genero and gender are the same variable).

Very important. Use a space around the assignment operator! x<-5 Does this mean assign 5 to x to is x less than -5
Rather then rep(0,n) just use numeric(n)
Your loops should be rewritten. For example:

##I presume that exposicao is exposition.
for(i in 1:n){if(u[i]>0.15)exposicao[i]<-1}

can be written as:

exposition[runif(n) > 0.15] = 1

and

for(j in 1:n){{if(exposicao[j]==1 & b[j]>0.5)genero[j]<-1}
{if(exposicao[j]==0 & b[j]<0.2)genero[j]<-1}}

can be written as:

genero[exposicao==1 & b>0.5] = 1
genero[exposicao==0 & b>0.2] = 1


I would change memoized to work with a functor type and use a traits approach to deduce the return type and the argument type.

template <typename Functor>
typename Functor::R memoized(typename Functor::T in) {
   using T = typename Functor::T;
   using R = typename Functor::R;

   static std::map<T,R> memo;
   typename std::map<T,R>::iterator found = memo.find(in);
   if (found != memo.end()) { return found->second; }
   std::cout << "not found" << std::endl; // only for demo
   R res = Functor()(in);
   memo[in] = res;
   return res;
}

struct Test1
{
   using T = double;
   using R = double;
   R operator()(T x) { return x*x; }
};

struct Test2
{
   using T = double;
   using R = double;
   R operator()(T x) { return x; }
};

My rationale for using a functor is that it simplifies user code.

int main() {
    std::cout << memoized<Test1>(1) << std::endl;
    std::cout << memoized<Test1>(1) << std::endl;
    std::cout << memoized<Test1>(1) << std::endl;
    std::cout << std::endl;
    std::cout << memoized<Test2>(1) << std::endl;
    std::cout << memoized<Test2>(1) << std::endl;
    std::cout << memoized<Test2>(1) << std::endl;

    return 0;
}


3) Yes, you can shorten the function:

def decide(mess, indexes):
    return ''.join(mess[int(i)-1] for i in indexes)

I just removed the unnecessary conversion to list and replaced the append loop with a generator expression.

Tuple unpacking allows more documenting names:

mess, indexes = lunedì.split('|')
print(decoder(mess, indexes.split()))

I do not think you need so much stripping at the file parsing step.


Feedback

The code seems fairly concise, though I do have suggestions below that can simplify it even more. I was hoping there was some class name applied to the element with class carousel during the slide transition but apparently the bootstrap code does not do that, though you could use the event callback functions to apply a class name yourself. That way the CSS style for pointer-events can be moved into the CSS.

Because the .on() method accepts multiple events separated by a space, you can use one call for both events, and a single Partially applied function to call the .toggleClass() method, which will add and then remove a class to the carousel element:

var carouselCollection = $('#myCarousel');
carouselCollection.on('slide.bs.carousel slid.bs.carousel',
    carouselCollection.toggleClass.bind(carouselCollection, 'sliding'));

Then the CSS can contain the style:

.carousel.vertical.sliding .carousel-indicators li {
  pointer-events: none;
}

See that working in the rewritten code below.

I don't see much point in creating the function carouselDuration() and calling it immediately afterwards but then never again. Why not just move that single line out where it is called? I could see a point in doing that after some condition is met (e.g. DOM ready, jQuery/carousel ready, etc).

Some of the CSS rulesets are a bit redundant. For instance, some of the top: 0 rulesets should be cascadable from .carousel.vertical .carousel-inner>.item and apply to the next three subsequent selectors.

Also, I believe I was able to remove this block without any adverse affects. Are there really elements with class .right and .left or are those for the left/right controls that aren't being used?

.carousel.vertical .carousel-inner>.next,
.carousel.vertical .carousel-inner>.prev,
.carousel.vertical .carousel-inner>.right {
  transform: translate3d(0, 100%, 0);
  top: 0;
}

Suggestions

It would likely help to define that value for the duration as a constant (and if you are using ecmascript-6 then use const) at the top of the code, so it can be easily modified in the future if necessary.

While there are only a couple redundant DOM queries (e.g. $(#myCarousel)) it would be wise to cache those in a variable.

The event handler functions are very redundant, and violate the Don't Repeat Yourself principle.  The only thing that appears to change is the value assigned to the CSS style pointer-events. If the approach mentioned above with the .toggleClass() method doesn't work, the common code in the two callback functions could be abstracted into a single function that accepts the value for that CSS style, and then Partially applied functions could be created with Function.bind() to fix the value to apply to the style.

var carouselCollection = $('#myCarousel');

function setPointerEventsOnListItems(value, e) {
  var $indicator = carouselCollection.find('.carousel-indicators>li');
  $indicator.css('pointer-events', value);
}
// While a transition is in progress (slide event), do this
carouselCollection.on('slide.bs.carousel', setPointerEventsOnListItems.bind(null, 'none'));

// While a transition has finished (slid event), do this
carouselCollection.on('slid.bs.carousel', setPointerEventsOnListItems.bind(null, 'auto'));

As you likely know, the jQuery DOM ready function would be good to use so as to avoid accidentally accessing the DOM before it is ready (though that isn't a problem as much nowdays with modern browsers and adding the script tags to the end of the ). An IIFE could also be used instead of that jQuery DOM ready callback.

Rewritten code

The code below utilizes the advice above, though utilizes the .toggleClass() method.

var DURATION = 1000; //could use const instead of var if supporting es-6
$(function() { //DOM ready callback
  $.fn.carousel.Constructor.TRANSITION_DURATION = DURATION;
  var carouselCollection = $('#myCarousel');
  // While a transition is in progress (slide event), do this
  carouselCollection.on('slide.bs.carousel slid.bs.carousel', carouselCollection.toggleClass.bind(carouselCollection, 'sliding'));
});
.carousel.vertical {
  position: relative;
}

.carousel.vertical .carousel-inner {
  height: 100%;
  width: auto;
}

.carousel.vertical .carousel-inner>.item {
  width: auto;
  transition: 1s ease-in-out;
  transform: translate3d(0, 100%, 0);
  top: 0;
}

.carousel.vertical .carousel-inner>.left,
.carousel.vertical .carousel-inner>.prev.right,
.carousel.vertical .carousel-inner>.next.left,
.carousel.vertical .carousel-inner>.active {
  transform: translate3d(0, 0, 0);
}

.carousel.vertical .carousel-inner>.active.right,
.carousel.vertical .carousel-inner>.active.left {
  transform: translate3d(0, -100%, 0);
}

.carousel.vertical .carousel-indicators {
  display: inline-block;
  width: auto;
  padding: 0;
  margin: 0;
  left: auto;
  right: 10px;
  bottom: 2px;
  z-index: 9;
  font-size: 0;
}

.carousel.vertical .carousel-indicators li {
  border: none;
  cursor: pointer;
  display: inline-block;
  width: 18px;
  height: 18px;
  text-indent: -9999px;
  background: url("https://grgs.ro/1/i/sprite.png") no-repeat -528px -502px;
}

.carousel.vertical.sliding .carousel-indicators li {
  pointer-events: none;
}
.carousel.vertical .carousel-indicators li.active {
  background-position: -528px -524px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">


Global variables in the best of cases are questionable, but in this case especially you have buff_size as a global variable. buff_size is only used in main() so should be a local variable there.

You can also take advantage of the fact that std::condition_variable::wait() has another overload that takes a predicate to replace:

while (count == 0) {
    cv.wait(lck);
}

with:

cv.wait(lck, []{ return count > 0; });

Although, did you really want every consumer to print out every letter every time? If buff_size were 10, you'd end up logging 55 letters. Was that intentional? If it wasn't, you could drop count entirely, switch data to be a std::queue and have your consumer be:

std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{return !data.empty(); });
std::cout << data.front() << std::endl;
data.pop();

On the producer front, did you really mean notify_one() and not notify_all()? Let all the consumers fight for the lock!

Lastly, this:

if (buff_size < 0) {
    buff_size = 0;
}
else if (buff_size > 26) {
    buff_size = 26;
}

is a clamp. It might be worth writing something like:

template <typename T>
T clamp(T const& val, T const& lo, T const& hi)
{
    return std::min(std::max(val, lo), hi);
}

buff_size = clamp(buff_size, 0, 26);


Which approach is preferable string parsing?

Let's analyze each approach:

public static int Wordcount1(string strName)
{
    string temp = null;
    int ctr = 0;

    for (int i = 0; i < strName.Length; i++)
    {
        if (strName[i] != ' ')
        {
            if (temp == null)
                ctr++;

            temp += strName[i];
        }
        else if (strName[i] == ' ')
            temp = null;
    }

    return ctr;
}

You are using temp string only as boolean flag (whether its null or not). So, you don't need to store current word in this variable. Actually temp += strName[i] creates many strings in memory, because strings are immutable. So, its performance and memory consuming. Remove it.

Also you don't need second if. If char is not white space, then it is white space. There is no third option. And improve naming - don't use prefixes for variable names.

public static int Wordcount(string text)
{
    bool wordFound = false
    int count = 0;

    for (int i = 0; i < text.Length; i++)
    {
        if (text[i] != ' ' && !wordFound)
        {
            wordFound = true;
            count++
            continue;
        }

        if (wordFound)
            wordFound = false;
    }

    return count;
}

Another approach:

public static int GetWordsCount(string strName)
{
    bool wordfound;
    int ctr = 0;

    for (int i = 0; i < strName.Length; )
    {
        wordfound = false;

        while ((i < strName.Length) && (strName[i] == ' '))
            i++;

        while ((i < strName.Length) && (strName[i] != ' '))
        {
            if (!wordfound)
            {
                ctr++;
                wordfound = true;
            }
            i++;
        }
    }

    return ctr;
}

For me its a little harder to understand, because you are incrementing loop variable in loop body on some conditions inside other loops. But you are not creating strings here as you do in your second approach. So it's definitely better in terms of performance and memory usage, than you original second approach.

In second approach you can eliminate usage of boolean flag, and condition check in second while loop. Also with some comments this code becomes easier to understand:

public static int GetWordsCount(string text)
{
    int count = 0;

    for (int i = 0; i < text.Length; )
    {
        // process to next word
        while ((i < text.Length) && (text[i] == ' '))
            i++;

        if (i < text.Length)
            count++;

        // loop till the word end
        while ((i < text.Length) && (text[i] != ' '))
            i++;
    }

    return count;
}

But of course its better to use already existing functionality:

return text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length;

Its not that fast, and it creates array of words which uses memory. But it's easy to understand for other developers. So, instead of doing premature optimization, I'd go with this approach and modified it only in case of performance problems.


Speeding up an algorithm for finding the number of distinct lines

You can improve your divisors function:

Version 1: (not includes n)

def divisors(n):
    """Return the divisors of n (including 1)"""
    if(n == 1):
        return (0)

    divs = set([1])
    r = floor(sqrt(n))
    if(r**2 == n):
        divs.add(r)

    f = 2
    step = 1
    if(n & 1 == 1):
        f = 3
        step = 2

    while(f <= r):
        if(n % f == 0):
            divs.add(n/f)
            divs.add(f)
        f = f + step

    return sorted(divs)

Version 2: (includes n) from here

def divisors2(n) :
    """
    Generates all divisors, unordered, from the prime factorization.
    """
    factors = factorI(n)
    ps = sorted(set(factors))
    omega = len(ps)

    def rec_gen(n = 0) :
        if n == omega :
            yield 1
        else :
            pows = [1]
            for j in xrange(factors.count(ps[n])) :
                pows += [pows[-1] * ps[n]]
            for q in rec_gen(n + 1) :
                for p in pows :
                    yield p * q

    for p in rec_gen() :
        yield p

where factorI is:

def factorI(n):
    """Returns the factors of n."""
    lst = []
    num = int(n)
    if(num & 1 == 0):
        lst.append(2)
        num /= 2
        while(num & 1 == 0):
            lst.append(2)
            num /= 2

    factor = 3
    maxFactor = sqrt(num)
    while num>1 and factor <= maxFactor:
        if(num % factor == 0):
            num /= factor
            lst.append(factor)
            while(num % factor == 0):
                lst.append(factor)
                num /= factor
            maxFactor = sqrt(num)
        factor += 2

    if(num > 1):
        lst.append(num)
    return lst

For efficiency reasons you could also make generator functions.


Using the * operator to repeat strings is smart, but there are still a lot of nested ifs and and fors.  In Python, excessive looping can often be remedied using list comprehensions and itertools.

It would definitely be a good idea to split the work into functions.  The input validation code is unrelated to the output routine.  The output routine, in turn, can be decomposed into smaller reusable units.  In particular, it is helpful to observe that the odd rows are like the even rows, but upside-down and colour-inverted.

from itertools import chain, cycle, islice

def tesselated_triangles(height, cols, rows):
    def triangle_row(height, cols, space=' ', fill='*'):
        return [
            (
                space * (height - i) +
                fill * (2 * i + 1) +
                space * (height - i - 1)
            ) * cols
            for i in range(height)
        ]

    def alt_triangle_row(height, cols, space=' ', fill='*'):
        return reversed(triangle_row(height, cols, space=fill, fill=space))

    return '\n'.join(chain.from_iterable(
        row(height, cols)
        for row in islice(cycle([triangle_row, alt_triangle_row]), rows)
    ))

print(tesselated_triangles(6, 6, 4))

Additional remarks:

Since strings in Python are immutable, repeated string concatenation should be avoided.  Appending just a single character using += involves allocating and copying the entire string.  For this application, you should use '\n'.join(…).  (Doing '\n'.join(…) would also avoid printing two newlines at the end of the output, which is wrong in my opinion.)
If the program failed, it would be a good idea to call sys.exit() with a non-zero status code.
It is uncommon in Python to write if(…): using parentheses.
Using extra spaces to align equals signs is discouraged in PEP 8, the official Python style guide.  In this case, I really think you have overdone it.

half_space      -= 1
stars           += 2
triangle        += "\n"

get_even_number() is poorly named.  You're not retrieving anything; you're testing something.  An appropriate name would be is_even_number() or simply is_even().  You could just eliminate the function, though, since it's so simple.


Text menu and validation of the chosen item

Let’s suppose that perfectness is our goal :)

    static void Main(string[] args)
    {
        new Menu("Please select one of the following options to run:")
            .Option("Run Initial Data Import", () => Console.WriteLine("Importing..."))
            .Option("Nightly Maintenance", () => Console.WriteLine("I am the terror (that flaps in the night)!"))
            .Option("Exit")
            .Execute();
    }

Where:

public class Menu
{
    public Menu(string prompt = "Please choose:")
        : this(prompt, Enumerable.Empty<Option>())
    {
    }

    Menu(string prompt, IEnumerable<Option> options)
    {
        Prompt = prompt;
        Options = options;
    }

    string Prompt { get; }
    IEnumerable<Option> Options { get; }

    public Menu Option(string name, Action action = null) =>
        new Menu(Prompt, Options.Concat(new[] { new Option(name, action ?? (() => {})) }));

    public override string ToString() =>
        Prompt + "\n\r" +
        string.Join("\n\r", Options.Select((o, i) => $"{i+1}. {o.Name}"));

    public void Execute() => Execute(Console.Out, Console.In);

    public void Execute(TextWriter writer, TextReader reader)
    {
        writer.WriteLine(this);
        int i;
        if (int.TryParse(reader.ReadLine(), out i) && --i >= 0 && i < Options.Count())
            Options.ElementAt(i).Execute();
        else
            Execute(writer, reader);
    }
}

And

class Option
{
    public Option(string name, Action action)
    {
        Name = name;
        Execute = action;
    }

    public string Name { get; }
    public Action Execute { get; }
}


You should take advantage of the key argument to max():

  The key argument specifies a one-argument ordering function like that used for list.sort().

best_match = max(names, key=lambda name: fuzz.ratio(name_to_match, name))


public IEnumerable<ProductCardRowViewModel> Search()
{
    GenericRepository<Rows> repo = new GenericRepository<Rows>();
    var temp = repo.GetAll();

    if (this.Warehouse != 0)
        temp = temp.Where(x => x.Head.Warehouse == this.Warehouse );
    if (ProductCode > 0)
        temp = temp.Where(x => x.ProductCode == this.ProductCode );
    if (!string.IsNullOrEmpty(this.UnitCode))
        temp = temp.Where(x => x.UnitCode .Equals(this.UnitCode));

    List<ProductCardRowViewModel> data = new List<ProductCardRowViewModel>();

    foreach (Rows row in temp)
        data.Add(new ProductCardRowViewModel(row));

    return data;
}

omitting braces {} in places where they are optional is bad practice and leads to error prone code.
in its current state this method is returning for Warehouse == 0, ProductCode == 0 and for instance UnitCode == string.Empty all items. If this is what you want then IMO a comment should describe this behaviour.
you are sometimes using this and sometimes you don't. Choose one style and stick to it.
I would add a ToList() to temp in the loop. And by the way temp is a really bad name.
instead of building the returned value as a List<T> you could simply use yield return. If you want to keep the List you should at least use var.

Applying the mentioned points would lead to

public IEnumerable<ProductCardRowViewModel> Search()
{
    GenericRepository<Rows> repo = new GenericRepository<Rows>();
    var rows = repo.GetAll();

    if (this.Warehouse != 0)
    {
        rows = rows.Where(x => x.Head.Warehouse == this.Warehouse );
    }

    if (this.ProductCode > 0)
    {
        rows = rows.Where(x => x.ProductCode == this.ProductCode );
    }

    if (!string.IsNullOrEmpty(this.UnitCode))
    {
        rows = rows.Where(x => x.UnitCode.Equals(this.UnitCode));
    }

    foreach (Rows row in rows.ToList())
    {
        yield return new ProductCardRowViewModel(row);
    }
}


Modifying __getattr__ to return a nested attribute instead of the named object

Do not write trivial getters/setters; this is not Java/C++/etc. It's more Pythonic to simply have everything public under most circumstances. Private-ness is not enforced anyway and is more of a suggestion.
Consider using @dataclass
You can drop empty parens after your class definition
Under what circumstances would it be possible for properties to be missing from DocumentObject? I'm not sure why you check for this. Won't it always be in vars?
Use type hints.
Use snake_case, not camelCase for variables
Do not allow arbitrary __setattr__ on your DocumentObject other than to registered properties
Do not accept a dict with redundant keys; just accept an iterable of properties
IMO it's less surprising to have the document's actual properties dict override any request to a property named "properties" than the other way around

Suggested:
from dataclasses import dataclass
from typing import Dict, Iterable, Union

@dataclass
class Property:
    name: str
    value: float  # ?? or maybe Any
    unit: str = 'mm'
    is_visible: bool = True

PropDict = Dict[str, Property]

class DocumentObject:
    def __init__(self, properties: Iterable[Property]):
        self.properties: PropDict = {p.name: p for p in properties}
        self.__setattr__ = self._setattr

    def __getattr__(self, name: str) -> Union[PropDict, float]:
        if name == 'properties':
            return self.properties
        return self.properties[name].value

    def _setattr(self, key: str, value: float):
        self.properties[key].value = value

brick = DocumentObject((
    Property('length', 10),
    Property('width', 5),
))
print(brick.properties['length'].name)
print(brick.length)
brick.width = 7
print(brick.width)


I wouldn't even use a switch here:

wait_sem(semaphore[me*2+1]);
wait_sem(semaphore[me*2+2]);
if (me==0) {
    signal_sem(semaphore[0]);
}

Edit: I see the sequence is not quite linear. If you can come up with an easy mapping between me and the indices, this will work (but with a different formula). Otherwise, a switch statement may be the easiest way.

You can also bury the switch inside a map by mapping the input ints to the two indices (std::map<int, std::pair<int, int> >). It essentially does the same thing, but you can hide the ugly in a header file.


Onclick radio buttons to change background color

The code looks pretty good. I only see a couple CSS rules that appear to be useless - for instance:

background: #eeeeee;

under the ruleset:

.button span {

But that style is overridden by the background styles under the <label> tags (i.e. .orange .button span and .amber .button span). The only reason I could think that would be needed is if you have other HTML not included in the example above that would have other colors...

What is the goal of the styles for html? I read the answers to Styling the <html> element in CSS? and it leads me to believe it is an attempt to avoid scrollbars, but maybe that is incorrect.

And is it really necessary to specify

background: #ffffff;

for the body tag? Maybe there are browser settings I am unaware of that allow a user to have a default background color other than that??


Is there any flaws in my code which let me to save settings to a file?

LastUsed is an awful name for a class.  The name of a class should always be a noun.  No exceptions.

Read-only fields should be marked as read-only using the readonly keyword.

CheckFileStatus is an awful name for a function. It does not give any hints as to what it means by 'File Status', nor any hints as to what it means by 'Checking' it.  Looking inside, I see that it performs operations that change the state of the system, so 'Check' is an awful choice of a name for what it does.  When a function begins with 'Check' it is supposed to return bool and to perform absolutely nothing that would change any state anywhere at all. No exceptions.

EmptyFile is not a good name for a function that checks whether a file is empty, because it may be confused with a function that actually empties the file.  Call it IsEmpty instead, and make it a property, not a function.

This is lame:

if (fileInfo.Length == 0) return true;
else return false;

Replace it with this:

return fileInfo.Length == 0;

In the SetFileText/GetFileText functions, streamWriter.Write() is not symmetrical to streamReader.ReadLine(). Consider either using streamReader.ReadToEnd(), (the preferred solution,) or using streamWriter.WriteLine() and also asserting that the text to be written does not already contain any Eolns, because if it does, then GetFileText() will not return the same string that was given on SetFileText().

The functions CheckFileStatus() and EmptyFile() expose implementation details of the class. These implementation details should not have to be exposed for a class which simply acts as a repository for a single string. It should be possible to rewrite the class to read/write the string from the Windows Registry, or from application.config, without having to change the interface of the class. So, replace those methods with some method which abstracts their usage.

And, by the way, why are you doing all this instead of just using the Windows Registry or application.config ?


Unicode is hard to get right, especially in Java as it has a more or less broken concept of a “character”. An Unicode code point is a 21-bit number. These code points are encoded to bytes with the UTF-8 or UTF-16 encodings (well, there are a couple more…). But when Java was created, Unicode only had characters in a 16-bit range, and code points were encoded with the (now deprecated) UCS-2 encoding.

There's a lot of pain from the fact that the 21-bit Unicode code points don't fit into a single 16-bit char or Character in Java. Two consecutive chars might actually be surrogate pairs. When reversing a string, we have to special-case these. We can use the Character.isHighSurrogate(char) function to test whether a given char starts a surrogate pair. If we encounter such a code point, we advance to the next char in the string, and push it onto the stack first:

for (int i = 0; i < originalString.length(); i++) {
    char ch = originalString.charAt(i);
    if (Character.isHighSurrogate(ch)) {
        i++;
        if (i < originalString.length()) {
            stack.push(originalString.charAt(i));
        }
    }
    stack.push(ch);
}

As a test case, you can reverse a string with the smiley character : "hi \ud83d\ude03". Reversed, it should be "\ud83d\ude03 ih".

It is best to think of Java's char as “an UTF-16 code unit” (see Wikipedia for all the details about UTF-16 you didn't want to know, but should). To learn about what Unicode is, and how to tame it, start with Joel Spolsky's Unicode blog post.


I had to adapt the test program to get meaningful results using /usr/bin/time:

#include <iostream>
int main()
{
    static const int codeSize = 4096;
    cv::Mat1f mat1(1, codeSize);
    cv::Mat1f mat2(1, codeSize);
    float low = 0;
    float high = 2.0;
    srand(0);
    cv::theRNG().state = cv::getTickCount() ;

    randu(mat1, cv::Scalar(low), cv::Scalar(high));
    randu(mat2, cv::Scalar(low), cv::Scalar(high));

    double d = 0;
    for (auto i = 0;  i < 1000000;  ++i) {
        d += euclDist(mat1, mat2);
    }

    std::cout << d << std::endl;
}

(I used two different inputs to avoid a predictable result of 0, made sure I used the result to prevent optimising out, and executed a million iterations to get the run time over a second).

Here's my compilation flags (used with my standard Makefile):

167501: PKGS += opencv
167501: CXXFLAGS += -O3 -march=native
167501: CXXFLAGS += -fopenmp

Having done that, I tried a couple of variations, all compiled with GCC version 7.1.0, and executed them on an Intel i7-6700K with 128KiB/1MiB/8MiB L1d/2/3 caches.

The original clocks in at 14.6 seconds user time without the OpenMP directive and 4.5 seconds with it.

Changing the std::pow() call to a plain multiply improved those times to 4.2 and 0.6 seconds respectively.

I got another factor of three improvement in wall-clock time, at the expense of much more processor time, by distributing across 8 cores with

#pragma omp parallel for simd reduction(+:dist)

For this code, the loop is a bit small for parallelization, it seems.

float euclDist(const cv::Mat1f& first, const cv::Mat1f& second)
{
    float dist = 0;
    const float *const firstp = first.ptr<float>(0);
    const float *const secondp = second.ptr<float>(0);
#pragma omp simd reduction(+:dist)
    for(auto i = 0;  i < first.cols;  ++i) {
        auto const d = firstp[i] - secondp[i];
        dist += d * d;
    }
    return std::sqrt(dist);
}


Positioning a container next to its menu

I have trouble to realize what were your initial whishes, since the current choices lead to some inconveniences (as it already appears in the reduced "snippet box").

Here is what I can|can't understand:

You want to keep menu always visible and located at the same place regardless how user scrolls.
So using container_menu {position: fixed;} is ok.
You want to have main container occuping the rightmost place, in front of container_menu and starting at the top of the window.
So using container_main {float: right;} is ok.
But why did you also set its postion to relative? Without adding some of top|left|right|bottom properties it changes nothing to its own location. In the other hand, it might be useful to constraint its
 childs if they had for example fixed position but they don't.
So using container_main {position: relative;} is useless.
Since you set fixed width values for container_main and its
 children, depending on the window width it may result in a (likely) unwanted layout: as soon as the window is small enough, container_main partially or totall overwrites container_menu.
So regarding only this point (but see also below) you should add container_menu {z-index: 1;} (or any other
convenient value, depending on other elements not currently showed).
For the same reason, if the window width is smaller than the fixed
 children, their content becomes cropped.
So you had better using a totally different technique, such as setting container_menu postion to fixed, with a left margin equal to container_menuwidth, and using percentage for container_main width

Here is an example using the above technique:

body {
  font-size: 16px;
  font-family: 'Open Sans', sans-serif;
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

/*Contenedor de la barra de navegacion: Columna*/
.container_menu {
  height: 100%;
  width: 18rem;
  /*display: inline-block;*/
  position: fixed;
  background-color: gray;
}

/*Barra de navelación: Elemento
*/
.container_menu .menu {
  width: 100%;
  padding: 0;
}

.container_menu ul {
  list-style-type: none;
}

.container_menu .menu li a{
  color: white;
  display: block;
  padding: 1rem 1.5rem;
  background-color: gray;
}

.container_menu .menu li a:hover {
  color: white;
  background-color: black;
}

.container_main {
  height: 100%;
  margin-left: 18rem;
  background-color: black;
  position: fixed;
  overflow-y: scroll;
}

p {
  color: white;
  background-color: blue;
  width: 60%;
  border: .7rem solid white;;
  padding: 5rem;
  margin: 10rem auto;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="css/style.css" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300i,400" rel="stylesheet">
  <title>MDN - Mockup</title>

Teaching Activities

Web Literacy

Leadership Opportunities

Tools

Comunity

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
      ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
      laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
      voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
      non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
       ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
       laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
       voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
       non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
       ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
       laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
       voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
       non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  <


Idiomatic F# unit test using xunit and unquote

I guess I mostly needed to figure out how to replace LINQ with F# equivalents and then refactor a bit. Now I have this:

let ToArrays schedules =
    schedules
    |> Seq.map (fun schedule -> schedule |> Seq.toArray)
    |> Seq.toArray

[<Fact>]
let ``Two courses, one with one time and one with two times that all differ, returns two unique schedules with two entries each``() =
    // arrange
    let course1 = getCourse1()
    let course2 = getCourse2()
    let time1 = getTime1()
    let time2 = getTime2()
    let time2a = getTime2a()
    time1 |> course1.AddTime
    time2 |> course2.AddTime
    time2a |> course2.AddTime

    let schedulesExpected =
        [|
            [| ScheduleEntry(course1, time1); ScheduleEntry(course2, time2) |]
            [| ScheduleEntry(course1, time1); ScheduleEntry(course2, time2a) |]
        |]

    // act
    let schedulesActual = [| course1; course2 |] |> ScheduleGenerator.Schedulyze

    // assert
    test <@ schedulesActual |> ToArrays = schedulesExpected @>


Comments on the code as it is

This:

  __attribute__((fastcall))

will not improve your performance, as the culprit is the algorithm not the compiler. If you really want to tell the compiler to optimize your code harder, you can try inline instead.

This forward declaration:

  extern bool isPal(const int &number) __attribute__((fastcall));

is unnecessary as the function body directly follows the forward declaration.

Looking at the isPal function the name could have been better. I would suggest isPalindrome.

bool isPal(const int &number)
{
    char buffer[6];
    sprintf(buffer,"%i",number);
    const string x = buffer;
    for(int i=0, end = x.size()-1;i<end;i++,end--)
        if(x[i]!=x[end])
        return false;
    return true;
}

Unless you need to modify the argument, always take simple types by value; so const int& number should be int number.
The input range is \$[0,1000000]\$ so your buffer is too small it needs to be at least 7 + 1 (for the null terminator).
The use of sprintf is discouraged, please prefer snprintf instead. You might want to consider stringstream for type conversion but I'll leave that up to you.
The variable const string x is unnecessary, simply use strlen from <cstring> instead.
You really should put some white spaces in there as the code is hard to read as it is.
Always prefer to use curly braces ({}) on control statements. Your missing indentation on the return false statement is confusing.
Also you can do without the end variable, but that's up to taste. But I will leave it there.

Fixing the above, your function should look like:

bool isPalindrome(int number)
{
    char buffer[8];
    snprintf(buffer, 8, "%i", number);
    int len = strlen(buffer);
    for(int i = 0, end = len - 1; i < end; i++, end--){
        if(buffer[i] != buffer[end]){
            return false;
        }
    }
    return true;
}

Now looking at your main() function.

Always prefer to declare your variables in the smallest possible scope. This makes the code easier to read. This means that counter, number and t should be declared inside of the loop body.
You're using C-style IO in a C++ program, this is not recommended. Instead you should use C++ streams cin and cout.
Again you could use some more white spaces.

The fixed code:

int main()
{
    int n;
    cin >> n;;
    while(n--)
    {
        int counter = 0;
        int number;
        cin >> number;
        int t = number + counter;
        while(!isPal(t))
        {
            ++counter;
            t = number + counter;
        }
        cout << counter << endl;
    }
    return 0;
}

Data handling improvements

You are formatting the input to a string to check if it is a palindrome. This is quite  unnecessary. To test if an integer is a numeric palindrome, you need to count the number of digits in the number, then extract and flip the digits in the top half and compare them to the bottom half. Like this:

int64_t ipow(int64_t base, int exp, int64_t result = 1) {
  return exp < 1 ? result : ipow(base*base, exp/2, (exp % 2) ? result*base : result);
}

int countDigits(int value){
  int digits = 0;
  while(value != 0){
    value /= 10;
    digits++;
  }
  return digits;
}

int flipDigits(int value){
  int ans = 0;
  while(value){
    ans *= 10;
    ans += value % 10;
    value /= 10;
  }
  return ans;
}

int isPalindrome(int value){
  int digits = countDigits(value);
  int ten_pow_digits_2 = ipow(10, digits/2);
  int high_digits = value / ten_pow_digits_2;
  if(digits%2){
    high_digits /= 10;
  }
  int low_digits = value % ten_pow_digits_2;

  return flipDigits(high_digits) == low_digits;
}

This will check if the number is a palindrome without formatting to a string and will be faster. However we can do better by improving the algorithm.

Algorithmic improvements

I'm not going to describe the correct algorithm here as @outoftime has already done so in his answer. Instead I'm going to provide a different implementation of the same algorithm with less code that doesn't abuse inheritance of the standard containers. You can find such improvements as predefined values and so on.

#include <iostream>

constexpr int64_t ipow(int64_t base, int exp, int64_t result = 1) {
  return exp < 1 ? result : ipow(base*base, exp/2, (exp % 2) ? result*base : result);
}

// This covers the range of int.
const int pow10[]{ipow(10,0), ipow(10,1), ipow(10,2), ipow(10,3),
    ipow(10,4), ipow(10,5), ipow(10,6), ipow(10,7), ipow(10,8), ipow(10,9) };

int countDigits(int value){
  int digits = 0;
  while(value != 0){
    value /= 10;
    digits++;
  }
  return digits;
}

int getDigit(int value, int digit){
  int place = pow10[digit];
  return (value/place) % 10;
}

int calcPalindromeDeficiency(int value){
  const int digits = countDigits(value);
  int digit = 0;
  int ans = 0;
  while(digit != (digits+1)/2){
    int top_digit = getDigit(value, digits - digit - 1);
    int bottom_digit = getDigit(value, digit);
    int to_add = ((10 + top_digit - bottom_digit)%10)*pow10[digit];
    ans += to_add;
    value += to_add;
    if(getDigit(value, digits - digit - 1) == getDigit(value, digit)){
      digit++;
    }
  }
  return ans;
}

int main(){
  int n;
  std::cin >> n;

  while(n--){
    int input;
    std::cin >> input;
    std::cout << calcPalindromeDeficiency(input) << std::endl;
  }
  return 0;
}

I find it more elegant to not convert to string when handling numbers.


I'm not too familiar with GUIs nor MVC, but I guess your model contains at least a string (which is displayed in the responseArea). You might put that into a separate model class.

Another thing is a websocket service which I try to hide behind the model and separate it from the controller class. Wikipedia says the following about MVC's model:

  A model notifies its associated views and controllers when there has been a change in its state.

So, the websocket service could notify the model, then the model would notify the view about the change.
I'd rename IController to Controller.

Clean Code by Robert C. Martin, Chapter 2: Meaningful Names, p24:

  Interfaces and Implementations

  These are sometimes a special case for encodings. For example, say you are building an
  ABSTRACT FACTORY for the creation of shapes. This factory will be an interface and will
  be implemented by a concrete class. What should you name them? IShapeFactory and
  ShapeFactory? I prefer to leave interfaces unadorned. The preceding I, so common in
  today’s legacy wads, is a distraction at best and too much information at worst. I don’t
  want my users knowing that I’m handing them an interface. I just want them to know that
  it’s a ShapeFactory. So if I must encode either the interface or the implementation, I choose
  the implementation. Calling it ShapeFactoryImp, or even the hideous CShapeFactory, is
  preferable to encoding the interface.

I think WebsocketService should not know anything about Controller.connectAs. Currently it violates the interface-segregation principle. You could create a WebsocketCallback interface which your controller implementation class could implement:

public interface WebsocketCallback {
    void updateMessage(String message);
}

public class DefaultController implements Controller, WebsocketCallback {
    ...
}

I guess implementing it by the model class could be even better (see #1).
I would rename the parameter here to message to express its purpose and make the code easier to understand:

public void updateMessage(String string) {

I would throw here an exception instead of hiding the error:

@Override
public void updateMessage(String message) {
    if (display != null) {
        display.addMessage(message);
    }
}

Crash early. It is rather a bug in the code when it is called without setting the display before which you shouldn't hide. It would help debugging: having a stacktrace usually better than just an one-line bugreport: "the button does not do anything" or something similar. See also: The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas: Dead Programs Tell No Lies.
If responseArea if a JTextArea instance, you could use append instead of setText(getText() ...) here:

responseArea.setText( responseArea.getText() + line );


Efficiently calculate the value of an arithmetic sequence

Seems trivial. Pair them, each pair is worth -1.
f(1000) =  1 - 2  +  3 - 4  + ... +  999 - 1000
        = (1 - 2) + (3 - 4) + ... + (999 - 1000)
        =   -1        -1    + ... +     -1
        = -500

Odd n left as exercise for the reader.
(I wrote this when the question title still said "1 − 2 + 3 − 4 + · · ·", can't be bothered to switch all signs now.)


Firstly, the algorithm is poor.  Repeated trial division is one of the worst ways to generate primes.  Prefer a sieve of some sort (you can use an array to store the primes).

Instead of true; return we can return 0; similarly, return 1 can replace false; return.

Testing $? is usually a sign that you simply need to move the tested command:

if ! hasFactor $n
then
    echo $n
fi

Or simply:

hasFactor $n || echo $n


Input validation?

At first glance, this looks like some sort of input validation:

if (number < 0) {
    System.out.println("Error: Not a positive integer");
} else {
    // ...
}

// ...
System.out.println("The binary representation of your integer has: " + oneCount + " ones.");
System.out.println("The binary representation of your integer has: " + zeroCount + " zeros.");

But it's not... If the input is negative,
processing will happily continue and print that the number has 0 zeros and 0 ones, which is not true.

Lastly, errors should be printed on System.err instead of System.out.

Variable scope

Declare variables where you really need them, not sooner.
number, zeroCount, oneCount can all be declared later.

Decompose to smaller units

Instead of dumping the code in a single main method,
it would be better to decompose the multiple small methods,
each responsible for one thing.
For example, you could have these methods:

read an int from standard input
convert an int to a binary string
count the number of ones in a binary string

the number of zeros is length minus the number of ones

Simplify

Instead of this:

binary = Integer.toString(mod) + binary;

You could simplify as:

binary = mod + binary;

Reinventing the wheel

Integer.toBinaryString(...) does the same thing as your main loop.


You can simplify the javascript to be something as given below by adding some properties to the markup.

jQuery(function () {

    jQuery('input:radio[name^="question"]').change(function(){
        var $this = $(this);

        $this.closest('.question-container').hide();
        $('#' + $this.data('target')).show();
    });
});

Required changes in the markup

add a class question-container to the question container ie the element with the question id like q1, question1A, etc
For all radio boxes add an additional attribute data-target which will have the id of the question to be displayed if it was checked. ex Yes button in question question1A will have data-target="question1B" and No button will have data-target="question2-1A"

demo: Fiddle


Luhn Algoritm for social security numbers

Some quick remarks:

Use clear variable names: f doesn't tell me anything.
Why do you call Directory.CreateDirectory before you do the actual validity check?
Do you even need to call Directory.CreateDirectory? I'm not sure, but I wouldn't be surprised if new StreamWriter("C:\\Log\\log.txt", true) creates any missing directories etc.
"C:\\Log\\log.txt" is used in two places, so it should be at least centralized. Assign it to a variable or perhaps even a constant.
You wrote a whole method -- ValidityCheckIsNotNull -- to encapsulate string.IsNullOrEmpty? WHY? What do you gain from this? What's the point?
Your lines are waaay too long. 170 characters which contain multiple LINQ methods are simply unclear. At least split it up into multiple lines.

Here is that same code, split over multiple lines:

socialSecurityNumber
   .Where((e) => e >= '0' && e <= '9')
   .Reverse()
   .Select((e, i) => (e - 48) * (i % 2 == 0 ? 1 : 2))
   .Sum((e) => e / 10 + e % 10);

Already it's a lot clearer. However, you need to comment this: .Select((e, i) => (e - 48) * (i % 2 == 0 ? 1 : 2)) because I cannot figure out easily what this logic is supposed to do. Properly naming e and i would help, I guess. Or even better: move it to a properly named method of its own.

Comments like //If the string is not null/empty and if the Social Security Number is valid, then return true. don't tell me anything your code doesn't tell me.
ValidityChecker isn't a proper method name: "Use verbs or verb phrases to name methods."
All of your logging logic should be in a separate method. It should not be part of ValidityChecker.
Logic as the name of your class? Far too generic.


Route factory which creates instances based on database context and model

Any particular reason you have all those using statements in the namespace itself?

This line:

DbContextTypeWrapper<SapphireDbContext<SiteTree>, SiteTree> dbContextTypeWrapper = new DbContextTypeWrapper<SapphireDbContext<SiteTree>, SiteTree>();

throws a gray-flag for me. Perhaps you should consider injecting the DbContextTypeWrapper into the RouteFactory? It seems to have an awful dependence on certain specifics, that can be abstracted away.

Another suggestion, would be to consider generics for it, considering you also depend on SiteTree as well.

The ideal solution would be an interface ISiteTree that you depend on, regardless of the SiteTree implementation. You could provide a default SiteTree implementation, or allow the additional assemblies to provide their own.

Likewise, the use of internal tends to lend way to some particular properties, for example, the behavior between assemblies can be different. This is particularly foul. You should consider either marking the internal methods public, or marking them private.

Depending on what you have access to, you should consider interfaces/generics again to allow for the DbContextTypeWrapper to vary a little between assemblies. By restricting the public implementation to SapphireDbContext, you also restrict it to only those DB types that SapphireDbContext supports. (If it only supports MSSQL, then you'll need an MSSQL server for each-and-every other project you use this in.)

Though I do not generally advocate the use of var, you could shorten some of your lines with it. (Especially the obscenely long ones.)


Doubly linked list implementation in C++

Unusual API

Some method names are a bit unusual in a linked list, here are some more common alternatives:

addToHead -> addFirst, unshift, prepend
addToTail -> add, addLast, append
removeFromHead -> removeFirst, shift
removeFromTail -> removeLast, pop
isInList -> contains

Information hiding

Users of DoublyLinkedList don't need to be aware of DoublyLinkedNode.
This implementation detail can be hidden.
I suggest to make it private by moving it out of the header file.

Naming

The naming is quite terrible at places. Here's the worst part:

DoublyLinkedNode(int nu, DoublyLinkedNode *ne = 0, DoublyLinkedNode *pre = 0) {
    info = nu;
    next = ne;
    prev = pre;
}

It would be better to call "ne" -> "next" and "pre" -> "prev", and "nu" -> "info" and use this-> on the left hand sides:

DoublyLinkedNode(int info, DoublyLinkedNode *next = 0, DoublyLinkedNode *prev = 0) {
    this->info = info;
    this->next = next;
    this->prev = prep;
}

"info" is an unusual name for the payload in a linked list node.
"value" or "data" would be better.

Instead of DoublyLinkedNode, I'd call it simply Node.
As it can be private, and it's unlikely to need any other kind of node in the linked list implementation.

Constructor initialization

There's a simpler way of initializing variables in the constructor:

DoublyLinkedNode(int info, DoublyLinkedNode *next = 0, DoublyLinkedNode *prev = 0) : info(info), next(next), prev(prev) {}

Use nullptr

Instead of setting pointers to 0 to null them out,
it's recommended to use nullptr.
You might need to enable this in your compiler,
for example with g++ you can pass the --std=c++0x flag.

Avoid external references when you don't really need them

This loop in the destructor makes references to head and isEmpty defined elsewhere:

for (DoublyLinkedNode *p; !isEmpty();) {
    p = head->next;
    delete head;
    head = p;
}

It would be more clear and simple to avoid such external references:

for (DoublyLinkedNode * node = head; node != nullptr;) {
    DoublyLinkedNode * toDelete = node;
    node = node->next;
    std::cout << "deleting: " << toDelete->info << "\n";
    delete toDelete;
}

For loop without body

The for loop in this method doesn't have a body.
This is not recommended.

bool DoublyLinkedList::isInList(int el) const {
    DoublyLinkedNode *tmp;
    for (tmp = head; tmp != 0 && !(tmp->info == el); tmp = tmp->next);
    return tmp != 0;
}

The reason the loop doesn't have a body is because of the !(tmp->info == el) in the loop condition.
That condition doesn't belong there.
It's recommended to put in the loop condition only what concerns the iteration process, in this example checking if the loop variable tmp has reached the end of the list or not.

The condition !(tmp->info == el) is about something else,
it's about evaluating the return value of the function.
That condition would be much better in the loop body, like this:

bool DoublyLinkedList::isInList(int el) const {
    for (DoublyLinkedNode * node = head; node != nullptr; node = node->next) {
        if (node->info == el) {
            return true;
        }
    }
    return false;
}

Also note that this alternative also saves an extra boolean check.


I'm not particularly familiar with C, but I have a few observations that may be helpful.

I like the attention to zeroing out your digest before you start. Using uninitialised memory is the sort of bug that can go unnoticed for a while, and it's good that you've caught it.

At the same time, I'm slightly alarmed that you're doing everything with raw loops, instead of using standard library functionality that does the same job. For example your loop to find inputLen could be replaced by a call to something like strlen and your loop to zero the array with a call to memset. As well as generally being more confident that you're using a tested and optimised routine, using library functions makes it easier to read and reason about your code.

I also quite like your use of comments. They're well placed, complementing the code and explaining some of the whys where the code explains the hows.

As for the hashing itself, I'm sure that the output looks fairly random, but it's actually doing a lot of work for the level of hashing that it supplies.

My top concerns:

If the input is longer than HASH_LENGTH, the latter part of the input is completely ignored.
XOR is a standard building block for this sort of low level stuff, but one of the key properties of XOR is that it undoes its own work. That is to say, because your for loop with j is only doing XOR it will confuse rather less than you'd expect for the work that goes into a nested loop.
The space allocated to digest at the end is underused. For example, because it's restricted to that alphabet, the first three bits of every byte will be "011". That has implications for use with, say, hash maps because the hash map will allocate 87.5% of its slots to values this hash function can never fill for any possible input.


Finding legal knight moves in a chessboard in APL (follow-up)

On your previous version you commented, "This works and gives the expected result for a series of test cases." But you never provided those test cases, right? I think the biggest thing missing here is test cases. Especially since test cases would quickly clarify the expected behavior of the function on weird inputs, and then you could maybe even get rid of some of the vague comments like

expects a vector with 2 integers, e.g. (1 1)

I infer that the two integers are supposed to be in the range 1..8 (not 0..7 as one might expect if one'd been doing too much programming lately and not enough chess). What happens when they're not in the range 1..8?
What happens when there are three integers in the vector, or one, or none?
What happens when there's something other than integers in the vector?

I know you split out isInsideBoard into its own named function thanks to a comment on the earlier question; but if it's only ever used once, is that buying you anything? Honestly, as not-really-an-APLer-myself, ∧/(1∘≤∧≤∘8) is pretty much the only part of that code that I could instantly understand!

If I understand correctly, the output of KnightMovesRevised is a vector each of whose elements is suitable for feeding back into KnightMovesRevised; is that right? If so, that's good! You could even write a test case demonstrating how to find the number of cells that are exactly 2 knight-moves away from (1,1).


bash script to organize files and cleanup files

errors

typo: function named movieMovie, invoked as moveMovie

potential errors

use of $dest_Dir"$line"

you expect dest_Dir to end with a slash, but that's not validated anywhere
use "$dest_Dir/$line" instead (it's OK to have multiple slashes)

don't use ls to verify the presence/absence of files:

removeEmptyDirectory() {
    dir="$1"
    shopt -s globstar nullglob dotglob
    files=("$dir"/*)  # an array holding all the filenames
    if (( ${#files[@]} == 0 )); then
        # the directory is empty
        rmdir "$dir"
    else
        echo "warning: directory not empty: $dir" >&2
    fi
}

Even better, use find:

removeEmptyDirectories() {
    while read -r line; do
        find "$dest_Dir/$line" -depth 0 -empty -exec rmdir '{}' \;
    done < "$DirList"
}

Double quote all your variables, everywhere, unless you have a specific reason not to.

style

clean up your indentation.  It is idiomatic to put then and do at the end of the same line as if and while (see removeEmptyDirectories() example above).
use a consistent naming convention

variables DirList, src_Dir -- use camelcase or underscores, but both?

don't need the else : branch
"line" is not a descriptive variable name.
use find -exec instead of piping to xargs.


Time delay indication bar for a text game

You can use bar.count rather than your sum
You can use ' ' * n, rather than your for loop.
You don't need [ in your bar.
You don't need to add whitespace, str.format can do that for you.

>>> '[{:<10}]'.format('XX')
'[XX        ]'

You don't need the bar variable.
I'd move the input out of the function, as it doesn't have much to do with the bar.
You could change the size of the bar with another argument.

def progress_bar(text, secs, size=10):
    for i in range(size + 1):
        print('{}\n\n[{:<{}}]'.format(text, 'X' * i, size))
        time.sleep(secs)
        os.system('cls' if os.name == 'nt' else 'clear')

You can also remove the need for os if your terminal support \r. This will mean that you can remove text from the function too, as IMO it shouldn't really be there either.

def progress_bar(secs, size=10):
    for i in range(size + 1):
        print('\r[{:<{}}]'.format('X' * i, size), end='', flush=True)
        time.sleep(secs)
    print()

print('Your text here!\n')
progress_bar(0.15)
input('>')

Alternately you can use \b, this is better if you want to allow text like bar: [].

def progress_bar(secs, size=10):
    for i in range(size + 1):
        print('[{:<{}}]{}'.format('X' * i, size, '\b' * (size + 2)), end='', flush=True)
        time.sleep(secs)
    print()

print('bar: ', end='', flush=True)
progress_bar(0.15)
input('>')


Two permutation iterators for classes in Python with and without a generator

Well Permutation has basically equivalent code to Permutation2, but is doing things the hard way.  Therefore, I'll just look at Permutation2, particularly __iter__().

 def __iter__(self):
     curr = self.start
     stahp = False
     while not stahp:
         yield curr
         curr = self.p[curr]
         stahp = curr == self.start
     else:
         raise StopIteration

You shouldn't need to explicitly raise StopIteration.  Iteration automatically stops when the flow of control reaches the end of the function.

I find the LoLcat spelling of "stop" amusing.  However, flag variables are generally a bad idea.  You would be better off writing if curr == self.start: break, for example.  However, I'd just choose to write it like this:

def __iter__(self):
    yield self.start
    curr = self.p[curr]
    while curr != self.start:
        yield curr
        curr = self.p[curr]

(Once again, the lack of a do-while loop in Python makes life difficult.)

Take care to indent your code very carefully in Python, as whitespace is significant.  Four spaces is a very strong norm, established in PEP 8.  You've used five spaces at the first level.


Function Visibility

In the code there's some functions that seem to be intended for internal use only. To hide these from external modules you should have a "proper" module declaration that exports those functions you want to make "public".

module MyTree ( Tree(ETree, Node), tInsert, tFromListL, tFromListR, ... ) where

this allows you to hide (and change) implementation details of your exposed function.

Balancing Your Tree

Your algorithm to balance that tree is something along the lines of \$\mathcal{O}(3 * n)\$. That's bad compared to an almost constant time-effort when balancing in tree form. Then again why are you even exposing this functionality?

If you allow a tree to be unbalanced, you shouldn't expose an operation to balance it and vice versa. You should strongly consider extracting balanced behaviour into either a separate type and using instance to expose a common "interface" or extract this into a completely separate module.

Something like this:

class (Ord a) => Tree a where
    tInsert, tDelete :: a -> Tree a -> Tree a
    tElem :: a -> Tree a -> Bool
    tIsBalanced :: Tree a -> Bool
    tSize, tDepth :: Tree a -> Int
    tMin, tMax :: Tree a -> a
    tToList :: Tree a -> [a]

data BalancedTree a = Empty | Node (BalancedTree a) (BalancedTree a) a deriving (Show)

instance NormalTree BalancedTree where
-- | because we are an instance of NormalTree we can access tInsert'
    tInsert = balance . tInsert'
-- and so on and so forth

data NormalTree a = Empty | Node (Tree a) (Tree a) a deriving (Show)

instance Tree NormalTree where
    tInsert = tInsert'

    -- | default implementation for insert without balancing
    tInsert' :: a -> Tree a -> Tree a

  Note that I haven't even used this myself and I'm not sure whether
  this works. The code should give you a gist as to how this could /
  should work and isn't even intended to be syntactically correct.

This defines the "interface" of Tree in a class and then uses data types to implement said "interface".

Errors In Expected Circumstances

When you call tMax or tMin respectively on an ETree (which would be better named as Empty) an error is raised. That's an IMO really ugly and declarative way of solving this. It'd be preferrable to have a pure function. This requires a small change to the type-signature:

tMin, tMax :: Ord o => Tree o -> Maybe o

Which in turn allows you to do the following:

tMin Empty = Nothing
tMin (Node lT _ a) = case lT of
    Empty -> a
    (Node lT' _ _) -> tMin lT'

This function is total and pure. As such it's much easier and cleaner to use.


Are these list-comprehensions written the fastest possible way?

def listexpression(n):  #LE
    return [x * x * (1 + x) for x in range(n)]

is over 3 times faster than your version with x**2+x**3 (from 8.47 ms to 2.31 ms with n = 10000).

Though, NumPy will also benefit from regrouping the expression this way.


Thread safety of this queue backed by ConcurrentHashMap

What if you have 2 threads that submit the same E. The first one runs untill the switch here in the code snippet below. Then the second thread runs up to that point. Both pass the check because it's not in the map yet, but then both will put in a new Future in the map.

@Override
public Future<E> submit(E e) {
    if (!itemsBeingWorkedOn.containsKey(e)) {
        //***switch here***
        itemsBeingWorkedOn.put(e, asyncWorker.executeWorkAsync(e, this));
    } else {
        LOGGER.debug("Rejected [{}] as it's already being worked on", e);
    }
    return itemsBeingWorkedOn.get(e);
}

Easiest way to make this thread safe would be to just make the entire method synchronised. If you're expecting to skip a lot that are already in you might consider this idea based on double checked locking:

@Override
public Future<E> submit(E e) {
    if (!itemsBeingWorkedOn.containsKey(e)) {
        synchronised(this){
            if (!itemsBeingWorkedOn.containsKey(e)) {
                itemsBeingWorkedOn.put(e, asyncWorker.executeWorkAsync(e, this));
           }
       }
    } else {
        LOGGER.debug("Rejected [{}] as it's already being worked on", e);
    }
    return itemsBeingWorkedOn.get(e);
}

This might have some really sublte unexpected results when one finishes (and is taken out of the map) just when another is submitted (this can return null). Depending on how you intend to use the class this may not be a problem though.


Configuring fields to be extracted by a data processor

This seems like a desperate attempt to find a use for closures, and I believe your problem would be solved much more simply by making $rec an object, perhaps even a tied object that lets you overload indexing

Some observations:

It makes the API much less useful when the calling code has to know which form of data it is dealing with anyway. ret_col_sub returns a closure that expects a simple string for its parameter, while ret_substr_sub returns a closure that requires an array reference. All of that should be hidden from the caller
I can see that ret_col_sub won't compile
Checking that a string doesn't match \D isn't sufficient to ensure that it is numeric, as an empty string will pass that test
It is correct to rebase the substring offset, but a length is a length and that should be left untouched
The postfixed ++ and -- operators have become popular because of the name of the C++ language, but unless you are using the value returned by tge operator you should be using tge prefixed version. It is wrong to rely on the compiler to optimise out the storage of the unused original value
As has been said, your style contravenes common standards, in particular those laid out in perlstyle which are the most universal


Moving files while preserving the folder structure

No, you do definitely need 3 parameters to do what you are trying to do

Although I would suggest a different 3.

public void Move(string sourceRoot, string targetRoot, string[] relative) {
    /* Precondition checks and try-catch removed for clarity */

    string source = Path.Combine(sourceRoot, relative);
    string target = Path.Combine(targetRoot, relative);
    string folderStructure = Path.GetDirectoryName(target);

    /* etc */
}

This makes clear that there is shared structure under source and target, and there isn't any direct string manipulation on file and folder names. I would even be tempted to factor this out into a seperate class, e.g.

class DirectoryMover {
    private string source;
    private string target;

    private void Move(string[] relative) { ... }
    public void MoveAll() { /* iterate over folders calling Move */ }
}


Check if two strings are permutations of one another

This question has used the word "permutation" for two strings, and in standard English what that's asking for is "is one the anagram of the other"? Using "anagram" as a search would help you find a lot of other information on this problem, especially on Code Review.

Your solution is significantly over-engineered. You have broken down the problem in to too many steps, and you've missed an opportunity to show how you would avoid code duplication.

Let's break down your code in to its stages:

Check each string is valid input
Check the strings are the same length
Extract the characters from each string
Sort each string's characters
Create a new String from each input's sorted characters.
Iterate over each of the sorted string's characters and compare to the other string.
Return the match status

Now, let's strip out the redundant parts... for example, you don't need to convert the sorted characters back to a string only to loop over each character again.... get rid of stage 5 and convert stage 6 to operate over the sorted array.

Also, stage 1, that's a bug. Two empty strings are anagrams of each other... agreed? Get rid of that check.

Now, what's left is two identical operations performed on two different inputs, which are then compared, so extract the common logic in to a function (Code reuse is a good thing):

private static final char[] sortedChars(String input) {
     char [] chars =  input.toCharArray();
     Arrays.sort(chars);
     return chars;
}

Then, your code looks like:

public static boolean containsPremutation(String firstString, String secondString){
    char[] firstChars = sortedChars(firstString);
    char[] secondChars = sortedChars(secondString);

    ....

}

Now what? Instead of converting them to strings, we can use the core library's Arrays class to do the comparisons for us:

return Arrays.equals(firstSorted, secondSorted);

The full code would be:

private static final char[] sortedChars(String input) {
     char [] chars =  input.toCharArray();
     Arrays.sort(chars);
     return chars;
}

public static boolean containsPremutation(String firstString, String secondString){
    char[] firstChars = sortedChars(firstString);
    char[] secondChars = sortedChars(secondString);

    return Arrays.equals(firstSorted, secondSorted);
}

Looking at the code that way, you can see other issues too...

generally, "Hungarian Notation" is frowned on in Java Code Style - don't have String appended to variable names like firstString and secondString ... we know that they are strings.
do we even need the variables in the contains... method? Could it just be:

public static boolean containsPremutation(String first, String second){
    return Arrays.equals(sortedChars(first), sortedChars(second));
}

As mentioned in a comment, it's Permutation and not Premutation.


You are attempting to use the AtomicBoolean to satisfy two requirements:

The first thread to access the data loads it while all others wait until it's been loaded the first time.
Another thread can update the data for future callers.

Neither of these is working perfectly.

While only one thread will load the data, all other threads will receive null without waiting until that first thread completes the loading process.
Because the list of objects is updated after the memory barrier, other threads are not guaranteed to see the new reference immediately.

Solving the first problem is simple enough: use a CountDownLatch to cause all incoming threads to block until the first list of objects is set. Ideally the system would start another thread to specifically load the data rather than letting the first random thread to come along and do it. This isn't necessary (see below), but it's much cleaner.

For the second problem, wrap the list of objects in an AtomicReference to supply a correct memory barrier. You might be thinking, "Oh no! Not two synchronizers for each access!" but Java's synchronization primitives have improved greatly over the years, and the atomic value holders are even cheaper than full synchronization.

public class HibernateDao extends SomeOtherClass implements Dao {
    private CountDownLatch dataLoaded = new CountDownLatch();
    private AtomicReference<List<SomeObject>> data = new AtomicReference<>();

    @Override
    public List<SomeObject> getAllSomeObjects() {
        dataLoaded.await();          // wait until first countDown call
        return data.get();
    }

    @Override
    public void updateAllSomeObjects(Collection<SomeObject> someObjects) {
        replaceAll(SomeObject.class, someObjects);
        data.set(someObjects);
        dataLoaded.countDown();      // release any waiting threads
    }
}

If you really must have the first thread perform the initial loading rather than a separate thread that calls updateAllSomeObjects on its own, you can add back your beloved AtomicBoolean. This would be my last choice, however.

  Note that while you can use if (!ab.getAndSet(true)) it's clearer to use compareAndSet as it indicates that you're performing a tested set rather than allowing any thread to set the new value.

    private AtomicBoolean firstCaller = new AtomicBoolean();

    @Override
    public List<SomeObject> getAllSomeObjects() {
        if (firstCaller.compareAndSet(false, true)) {
            updateAllSomeObjects((List<SomeObject>) getHibernateTemplate().loadAll(SomeObject.class));
        }
        else {
            dataLoaded.await();      // wait until first countDown call
        }
        return data.get();
    }


A few notes:

A tuple of two-tuples is an odd structure for values, if you used a dictionary {'M': 1000, ...} you could avoid the loop over values and just use boom.append(values[year[i]]);
There is no point including e.g. CM in values, as there is no way year[i] (a single character) would ever be equal to those letters;
values should be defined inside the function, perhaps as a default argument, as it's not needed in any other scope;
for i in range(len(year)): ... year[i] is generally unpythonic, use for letter in year: instead (where you need i and i+1, you can use zip(l, l[1:]) to get pairs);
boom is not a very good name for the list, as it doesn't really explain what should be in it (something like numbers might be better) and there's no need to limit yourself to year inputs; and
Per the style guide, the function should be called roman_to_int, and you should consider adding a docstring.

With the above fixes:

def roman_to_int(roman, values={'M': 1000, 'D': 500, 'C': 100, 'L': 50,
                                'X': 10, 'V': 5, 'I': 1}):
    """Convert from Roman numerals to an integer."""
    numbers = []
    for char in roman:
        numbers.append(values[char])
    total = 0
    for num1, num2 in zip(numbers, numbers[1:]):
        if num1 >= num2:
            total += num1
        else:
            total -= num1
    return total + num2

You could also consider simplifying with a list comprehension, and adding error handling for the following cases:

roman is an empty string ""; and
roman contains characters not in values.