Iterating over an Array and an Iterable (List)

I would be happy with:

@Override
public boolean match(final InetAddress inetAddress)
{
    final byte[] bytes = inetAddress.getAddress();
    int end = Math.min(this.rules.size(), bytes.length);
    for(int i = 0; i < end; i++)
    {
        final int adressPart = bytes[i] & 0xFF; //byte range from -128 to 127, &0xFF makes it unsigned, therefore positive
        if(!this.rules.get(i).match(adressPart))
            return false;
    }
    return true;
}

If you think, the this.rules.get(i), then test it with a profiler. I would be surprised if this line is the reason for any slowdown, because the length of a InetAddress is probably quite limited and most likely implemented as an ArrayList annyway. If it really matters, you can change it to:

@Override
public boolean match(final InetAddress inetAddress)
{
    final byte[] bytes = inetAddress.getAddress();
    ByteRule[] byteRulesArray = rules.toArray(new String[rules.size()]);
    int end = Math.min(this.rules.size(), bytes.length);
    for(int i = 0; i < end; i++)
    {
        final int adressPart = bytes[i] & 0xFF; //byte range from -128 to 127, &0xFF makes it unsigned, therefore positive
        if(!byteRulesArray[i].match(adressPart))
            return false;
    }
    return true;
}

or if you even fear the array creation, you can use an iterator:

@Override
public boolean match(final InetAddress inetAddress)
{
    final byte[] bytes = inetAddress.getAddress();
    Iterator<ByteRule> rulesIterator = rules.iterator();
    int end = Math.min(this.rules.size(), bytes.length);
    for(int i = 0; i < end; i++)
    {
        final int adressPart = bytes[i] & 0xFF; //byte range from -128 to 127, &0xFF makes it unsigned, therefore positive
        if(!rulesIterator.next.match(adressPart))
            return false;
    }
    return true;
}

Hint: In theory, the iterator solution would be faster than the array creation. However in the real world, because of hardware reasons, the array creation will, most likely, be faster.


I'm not a C-guru at all but I believe I can give you a few advices to improve your code:

Review your included libraries. Do you really need all those ones? Nope. Chuck Testa You only use stdio.h and stdlib.h.
main() should return int and you specify it actually returns NODE... but it isn't returning nothing at all! Double fail x( So... int main() { return 0; } FTW
Naming consistency. You have written getnode() and insert_front(). You can name your members whatever you want (getnode(), getNode(), get_node()) but keep the patter for all of them (insertfront(), insertFront(), insert_front()). IMO, underscores are much C-style.
Blank lines. Avoid inserting blank lines. They don't clarify the reading of your code, instead of that they expand your code unnecessarily. You can insert blank lines between your function definitions. This helps to delimit and group your functions and eases their location.
What if I type 4 in your menu? The golden rule in programming is: Users provide bad inputs. So you always must to validate inputs. Don't matter if it seems trivial. Always.
And for last and getting a bit cranky, you can get a temp node in one step within insert_front():

NODE temp = get_node(); // I've changed `getnode()` name for you. You are welcome.


I see three main issues: the improper usage of primitive constants, the bad naming of everything, and too long and complex methods. Case study: private boolean checkRook(Board b, List<Point> rooks, List<Point> castlingMove, int owner, int moveType).

The method name checkRook. If I call checkRook(...) and get "true" or "false", I have no idea what that actually means. Name the method so that "true" and "false" can be answers to the question. "checkRook"? "true." doesn't sound like a conversation. "rookCanMove?" "true." works much better (if that's what the method is doing, I'm still not sure...). In the context of a chess game the word "check" also has a special meaning, so you should be really, really careful to only use it correctly. "checkRook" makes no sense in that respect, either (unless it means "a rook giving a check to the opposing king").
The variable should be Board board, not Board b. It's not 1970s, you don't need to save bytes. "board" is much more readable than "b", and readability should be the king.
int owner and int moveType. These should be enums: Owner owner and MoveType moveType. For an integer owner, one has no idea what value is white and what value is black, but Owner.WHITE and Owner.BLACK are self-explanatory. Similarly, "moveType 5" says nothing to anyone -- compare with MoveType.CHECK and MoveType.EN_PASSANT.
Rather than giving the method both the Board and a list of rooks, consider implementing a new method into the Board class, something like Point[] getPiecesByType(PieceType.WHITE_ROOK). The board should hold references to its pieces, so you should be able to get their positions from it. This helps you remove one of those method parameters. Anything more than three is usually too much anyway.

Point[] t = {(Point) super.getPosition().clone(), (Point) r.getPosition().clone()};
int[] s = {5, 9};
// ...
if (b.checkPosition(m) && m.x < s[moveType])

Again, horrible naming. These cannot be read out of context, nor without scrolling back and forth, looking for the variable initializations. Actually, many of those are incomprehensible even when you see the definition. s, seriously? The t is a list of two points, so apparently a move from Point A to Point B: this should be encapsulated into a new class, called, for example, Move.

Furthermore, assuming the method checkRook checks something about the rooks in relation to the castling, I don't know how you managed to make the method so long. The only thing you need to check about rooks is that they haven't moved. Then you should have other methods for checking that your king is not in check and that it's not going to move over or onto a square that is in check.

Overly long methods like checkRook violate the well known principle that is formalized in Clean Code as follows:

  FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. THEY SHOULD DO IT ONLY.

Uncle Bob continues:

  We should also be able to write a brief description of the class in about 25 words, without using the words “if,” “and,” “or,” or “but.”

and that's obviously true for methods too. So break your methods into smaller ones that have descriptive names.


Sorting Exclusive of Specified Indexes in List

Limitations

The implementation will not work well for certain inputs with duplicate values. The spec doesn't say that there won't be duplicate values, so you should not assume that.

This limitation can be fixed by excluding items to sort by index instead of value.

Performance

element not in non_sort_subjects and whole_index in static_index_list will be linear searches, since non_sort_subjects and static_index_list are lists. A simple improvement would be to search in sets.


NodeJS module to calculate linear motion

Nice documentation. This code is clear and easy to read. Here are some basic nits:

You should probably follow standard JSDoc conventions. Don't do this:

/**
*
*/

Do this instead:

/**
 *
 */

If you're nitpicky about the @param, Float technically doesn't exist since all JavaScript numbers are floats. Use Number instead.
See this SO post about rounding to 2 decimal places. Using it is completely up to you, there's nothing wrong with the way you're doing it. (This suggestion is slower, but looks cool I guess)

const round = val => {
    return +val.toFixed(2);
};

You know the constraints of your areValuesValid() function, there's no need to === false.

const calculateTime = (velocity, distance) => {
    if (areValuesValid(velocity, distance) && parseFloat(velocity) !== 0) {
        return round(distance / velocity);
    }
    return 0;
}

Also, why the need to do parseFloat(velocity)? If you know all your arguments will be numbers, this is unnecessary. If you don't know the data type of your arguments, you should probably enforce that they are numbers using typeof.

Happy coding!


To improve readability you should use proper naming conversions.
From the given code what i can understand that the input parameter user is for constructing the table name, that means all your table looks like someName_table(i'm not sure), if so user is not a good name for that variable, let me rename them as queryOnTable.
Another thing i have noticed is that Timestamp will be a common column for all your tables.(me too assume so or else we have to consider that too).
Here in your case you are specifying the database name as well as the
current user of the database in the connection using var MySql =
Query.Connection(Session.Current.Username, Session.Current.Database)
so you need not be specified them in the executable query. Or else
you can use the input parameters db and user(if the above point is false) can be used to create the connection(if connection string change dynamically). This may help you to reduce the complex formatting of the select statement.
Here the given snippet will always select the whole data ( select *
) from the given table, This will not be a good choice, always
collect the data which you want. I i prefer you to use another input
array to the function that specifies the required fields.
This article says that .Parameters.Add() is better choice that .Parameters.AddWithValue() So we can prefer that here by changing the last parameter List<string[]> column to something like List<myQueryParameter>.

where myQueryParameter is defined as:

public class myQueryParameter
    {
        public MySqlDbType  paramType { get; set; }
        public string paramValue { get; set; }
    }

I suggest you to include an additional parameter called additionalClause which can be used for specifying clauses like Group by, order by etc.
Now the query building; Many article available in the various sites stated that StringBuilder is the best option for concatenating the string when the concatenations are more than 1000, where as String.Join() is even more efficient than StringBuilder if concatenations are less than 1000. + and String.Concat() are less efficient than these two.

Now consider the modified method:

public static DataTable GetDataTable(string queryOnTable,
                                    string dtStart,
                                    string dtEnd = "yyyy-MM-dd HH:mm:ss",
                                    List<string> reqColumns = null,
                                    List<myQueryParameter> conditionalParams = null),
                                    string additionalClause="")
    {
        if (reqColumns == null) { reqColumns = new List<string>() { "*" }; } // select all columns if not specified

        string mysqlTimestamp = "yyyy-MM-dd HH:mm:ss";

        StringBuilder sqlQueryBuilder = new StringBuilder();
        sqlQueryBuilder.Append("SELECT ");
        sqlQueryBuilder.Append(String.Join(",", reqColumns));
        sqlQueryBuilder.Append(String.Format(" FROM {0} WHERE ", queryOnTable));

        if (dtEnd != mysqlTimestamp)
        {
            sqlQueryBuilder.Append("`Timestamp` >= @dtStart AND `Timestamp` <= @dtEnd");
        }
        else
        {
            sqlQueryBuilder.Append("`Timestamp` = @dtStart");
        }

        if (conditionalParams != null)
        {
            foreach (myQueryParameter param in conditionalParams)
            {
                sqlQueryBuilder.Append(String.Format(" AND `{0}` = @{0}", param.param));
            }
        }

        if (additionalClause != "")
            sqlQueryBuilder.Append(additionalClause);

        var data = new DataSet();
        using (var MySql = new MySqlConnection("Query.Connection(Session.Current.Username, Session.Current.Database)"))
        {
            MySql.Open();
            using (var MySqlCmd = new MySqlCommand(sqlQueryBuilder.ToString(), MySql))
            {
                MySqlCmd.Parameters.AddWithValue("@dtstart", dtStart);
                MySqlCmd.Parameters.AddWithValue("@dtEnd", dtEnd);
                if (conditionalParams != null)
                {
                    foreach (myQueryParameter condition in conditionalParams)
                    {
                        MySqlCmd.Parameters.Add(String.Format("@{0}",condition.param),condition.paramType).Value = condition.paramValue;
                    }
                }
                using (var Adapter = new MySqlDataAdapter(MySqlCmd))
                {
                    Adapter.Fill(data);
                }
            }
        }
        return data.Tables[0];
    }

Before going to the usage example let me define a table; Let user_data is the table having columns as follows:

Column Name  | DataType
user_id          VarChar
user_name        VarChar
int_field        Int32
text_field1       Text
text_field2       Text
text_field3       Text
Timestamp         DateTime

We can call the GetDataTable() method as like the following:

// Creating input parameters
List<string> reqcolumns = new List<string>() { "user_name", "int_field", "text_field1", "text_field2","text_field3" };
List<myQueryParameter> parameters = new List<myQueryParameter>();
parameters.Add(new myQueryParameter() { param = "user_id", paramType = MySqlDbType.VarChar, paramValue = "USR001" });
parameters.Add(new myQueryParameter() { param = "int_field", paramType = MySqlDbType.Int32, paramValue = "12" });
parameters.Add(new myQueryParameter() { param = "user_name", paramType = MySqlDbType.VarChar, paramValue = "un-luckey" });

//Calling the method
var dt = GetDataTable("user_data",
                      "2014-02-15 00:00:00",
                      "yyyy-MM-dd HH:mm:ss",
                      reqcolumns, parameters,
                      " Order by Timestamp");

Which will creates the query as like the following:

  SELECT user_name,int_field,text_field1,text_field2,text_field3 FROM
  user_data WHERE Timestamp = @dtStart AND user_id = @user_id AND
  int_field = @int_field AND user_name = @user_name Order by Timestamp


Delete the node at index i from its current position and insert it after node at index j

This looks quite sane, is there a reason you do not work with iterators?

your assert doesnt use the reference but a copy, so you should use const std::initializer_list<int> &indices
In the equal case, i would make it actually explicit and do std::swap(nodes[i], nodes[i + 1]), which is the same pattern you used all over the code.
It might be ok if your assert is used multiple times, but it is rather confusing, that you pass it i and j and i read only i in the code. Maybe use better names like index1 index2
Any reason you declare x outside of the loops?


Check if an element is present within a linked list

First, you need to realize that Python is not Java. Python is a "consenting adult language." (Watch Raymond Hettinger's talk for more.)

What that means is the bizarre fetish for mutators/accessors/getters and setters that permeates Java and C# doesn't exist in Python. You don't need to write:

class Node:
    def getData(self):
    def getNext(self):
    def setData(self,newdata):
    def setNext(self, newnext):

Instead, you can just write this:

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

And let people access node.data and node.next directly. (Python provides a mechanism, @property, for dealing with the case where you want to turn a member access into a function call. But it's not the first thing to do.)
The next thing that struck me about your code was this:

llist = Linkedlist()
llist.add_member(23)
llist.add_member(98)
llist.add_member(415)
llist.add_member(123)

That's a lot of letters to get 4 numbers into a list. You can, and should, do better!

"How can I do this better," you ask? Well, post it on CodeReview of course! But also, consider how the Python list class (and set, and dict, and tuple, and ...) is initialized. And how the Mutable Sequence Types are expected to work.

Because your code is implementing a "mutable sequence type." So there's no reason that your code shouldn't work the same way. In fact, if you want other people to use your code, you should try to produce as few surprises as possible. Conforming to an existing interface is a good way to do that!
Create an initializer that takes a sequence.

class LinkedList:
    def __init__(self, seq=None):
        ...
        if seq is not None:
            self.extend(sequence)

Implement as many of the mutable sequence operations as possible.
Use the standard method names where possible: clear, extend, append, remove, etc.
Implement special dundermethods (method names with "double-underscores" in them: double-under-methods, or "dundermethods") as needed to make standard Python idioms work:

def __contains__(self, item):
    for i in self:
        ...

def __iter__(self):
    node = self.head

    while node:
        yield node.value
        node = node.next

Implement your test code using standard Python idioms, to prove it's working:

llist = LinkedList([23, 98, 415, 123, 981, 454, 213, 198, ...])

while True:
    item = int(raw_input("Enter a number to search for: "))

    if item in llist:
        print "It's in there!"
    else:
        print "Sorry, don't have that one."


Counting the proportion of vowels in substrings

Style

You probably don't care much about this but your style (spacing for instance) is not very consistent.

Making things easier to improve

You'll make your code much easier to improve if :

you have a way to measure performances
you have a way to ensure you don't screw it up.

You can do so by writing a few tests.

#include <assert.h>
#include <bits/stdc++.h>
using namespace std;

long double prettyness(const string & s)
{
    long double sum = 0.0;
    long double len_s = s.length();
    for (int i = 0; i < len_s; i++)
    {
        for (int j = i+1; j <= len_s; j++)
        {
            string ss = s.substr(i,j-i);
            long double len = 0.0;
            long double len_ss = ss.length();
            for (int r = 0; r < len_ss; r++)
            {
                if(ss[r]=='I' || ss[r]=='E' || ss[r]=='A' || ss[r]=='O' || ss[r]=='U' || ss[r]=='Y' )
                    len++;
            }
            sum += len/len_ss;
        }
    }
    return sum;
}

void stdio_tests()
{
    string s;
    while (cin>>s)
    {
        cout << fixed << std::setprecision(6) << prettyness(s) << endl;
    }
}

void unit_tests()
{
    long double res;
    res = prettyness("IEAIAIO");
    assert(res == 28);
    res = prettyness("BYOB");
    assert(5.83333 < res && res < 5.83334);
    res = prettyness("YISVOWEL");
    assert(17.04 < res && res < 17.06);
    res = prettyness("QWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKLZXCVBNM");
    assert(79984 < res && res < 79985);
}

int main()
{
    unit_tests();
    return 0;
}

Improvements

I already got rid of the multiples calls to length() above. Let's try to make other improvements.

For a start, you don't need to use substr at all. You can simply try to be smart with string indices :

long double prettyness(const string & s)
{
    long double sum = 0.0;
    long double len_s = s.length();
    for (int i = 0; i < len_s; i++)
    {
        for (int j = i+1; j <= len_s; j++)
        {
            long double len = 0.0;
            for (int r = i; r < j; r++)
            {
                if(s[r]=='I' || s[r]=='E' || s[r]=='A' || s[r]=='O' || s[r]=='U' || s[r]=='Y' )
                    len++;
            }
            sum += len/(j-i);
        }
    }
    return sum;
}

Then, you can get rid of the multiple checks of the char value by storing the result in an array.

Also, you could make things much faster by storing cumulative sums of vowels so that you can get number of vowels in substring i..j by computing something like cum[j]-cum[i].

The code would be something like :

long double prettyness(const string & s)
{
    long double sum = 0.0;
    size_t len_s = s.length();
    long double cum[len_s + 1];
    cum[0] = 0;
    for (int i = 0; i < len_s; i++)
        cum[i + 1] = cum[i] + (s[i]=='I' || s[i]=='E' || s[i]=='A' || s[i]=='O' || s[i]=='U' || s[i]=='Y');
    for (int i = 0; i < len_s; i++)
        for (int j = i+1; j <= len_s; j++)
            sum += (cum[j]-cum[i])/(j-i);
    return sum;
}

This is much faster but I'm pretty sure there is a way to do better. For instance, substrings of same lengths could be considered together to perform a smaller number of divisions.

long double prettyness(const string & s)
{
    size_t len_s = s.length();
    double cum[len_s + 1];
    cum[0] = 0;
    for (int i = 0; i < len_s; i++)
        cum[i + 1] = cum[i] + (s[i]=='I' || s[i]=='E' || s[i]=='A' || s[i]=='O' || s[i]=='U' || s[i]=='Y');
    long double sum = 0.0;
    for (int l = 1; l <= len_s; l++)
    {
        long double tmp_sum = 0.0;
        for (int end = l; end <= len_s; end++)
        {
            tmp_sum += cum[end] - cum[end-l];
        }
        sum += tmp_sum/l;
    }
    return sum;
}

Then, some trick to compute the inside of the loop faster. Indeed, many indices cancel each other. At the end, you are down to some value that can be precomputed with another cumulative array :

long double prettyness(const string & s)
{
    size_t len_s = s.length();
    double cum[len_s + 1];
    cum[0] = 0;
    for (int i = 0; i < len_s; i++)
        cum[i + 1] = cum[i] + (s[i]=='I' || s[i]=='E' || s[i]=='A' || s[i]=='O' || s[i]=='U' || s[i]=='Y');

    double cum_cum[len_s + 2];
    cum_cum[0] = 0;
    for (int i = 0; i <= len_s; i++)
        cum_cum[i + 1] = cum_cum[i] + cum[i];

    long double sum = 0.0;
    for (int l = 1; l <= len_s; l++)
        sum += (cum_cum[len_s + 1] - cum_cum[l] - cum_cum[len_s - l + 1])/l;
    return sum;
}

You have a O(n) algorithm, that should be fast enough (and it is easy to see that better complexity cannot be achieved).


The missing part is a JsonConverter:

[JsonConverter(typeof(JsonTConverter))]
public struct Json<T>
{

And:

public class JsonTConverter : JsonConverter
{
    public override bool CanConvert(Type objectType) =>
        objectType.IsConstructedGenericType &&
        objectType.GetGenericTypeDefinition() == typeof(Json<>);

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) =>
        Activator.CreateInstance(objectType, reader.Value);

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =>
        writer.WriteValue(value.ToString());
}


The part of the code that makes it really slow is this:

string concattedUnitPart = "";
foreach (var line in tempCP4List)
{
  concattedUnitPart = concattedUnitPart + line;
  line1CP4PartLines++;
}

You should not concatenate large strings like that. The string gets longer and longer for each iteration, and it's copied into a new string each time.

If you Read a file that is 1.8 MB, that consists of lines which varies between 50 and 100 characters, you will have been copying about 10 000 MB of data before you have the result.

Also, it scales very badly, so when the files grow it will grow slower at an exponential rate. To handle a file that is 5 MB you will be copying about 80 000 MB of data.

James suggestion to do a replace seems to be a good option. If you want to split and join, you can use the String.Join method:

string[] splitCP4DataBaseLines = CP4DataBaseRTB.Text.Split('\n');
string concattedUnitPart = String.Join(Environment.NewLine, splitCP4DataBaseLines) + Environment.NewLine;


Reading many kinds of numbers from a byte buffer

There is only ONE problem that will be hard to eliminate because I assert that "ByteBuffer" is not within your domain. And this problem is not related to redundancy in the manner of duplicate code. The bytes read can be derived from the method called:

read(address, 4).getInt();

So if you have any possibility to use "4" within "getInt()" then your code improves a little bit. Maybe extract the magic numbers as constants.

Everything else you assume is of an error type 2. Assuming redundancy where there is not redundancy and acting unnecessarily. So everything you do to the code trying to eliminate redundancy will introduce problems.

For example:

Your generic suggestion will divide responsibility into half. The caller has to synchronize the expected return type with the called method. In the original solution there is no necessity to care.

Leave the code presented as it is. There is no possibility to improve it in the way you expect it.


Cut float numbers in a stream (putchar, getchar) and in a string

For input/output, it's generally better to work with strings rather than one character at a time with getchar() and putchar() — that is, if you can manage to write the code elegantly.  String-processing code would be more reusable, and it would likely avoid the overhead of repeatedly calling getchar() and putchar().

Note, however, that gets() is a deprecated function that you should never use because it offers no way to protect against buffer overflow.  Instead, use fgets() (which lets you specify a buffer size) or getline() (which automatically resizes the buffer).

Neither implementation is easy to follow.

The first version has calls to getchar(), putchar(), and isdigit() all over the place, as well as nested loops and mysterious flag variable.  Only the outer loop test for the '&' terminator character, which seems wrong.

The second version increments i and j all over the place, and has nested loops (of which only the outer one tests for '&').  It's clear that the output string will be no longer than the input, so it should be possible to reuse the original s buffer.

A better approach would be to have one loop that looks at each input character in turn.  The loop copies one character of input to the output per iteration, except when excess decimal precision is seen.  Instead of s[i] and s1[j], it would be easier to use char pointers named in and out.

/**
 * Overwrites string s with a string in which numbers are truncated after
 * some number of decimal places.  The input s may be terminated by a NUL
 * or an ampersand character.
 */
char *truncate_decimals(char *s, int max_places)
{
    int places = -1;
    char *out = s;
    for (char *in = s; *in != '\0' && *in != '&'; in++)
    {
        if (*in == '.')
        {
            places = 0;   // Decimal point encountered. Start counting places
        }
        else if (!isdigit(*in))
        {
            places = -1;  // Non-digit encountered. Resume normal copying
        }
        else if (places >= 0 && ++places > max_places)
        {
            continue;     // Excess precision; don't copy
        }
        *out++ = *in;
    }
    *out = '\0';
    return s;
}


Two approaches to Logging when Unit Testing with Python

According to the logging docs:

  The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction logging.getLogger(__name__). That’s because in a module, __name__ is the module’s name in the Python package namespace.

Based on my experience, I would say that you should always use logging.getLogger(__name__) for bigger projects, as it'll make logging modularization easier.

As your question is broad, I recommend you to read the Logging Cookbook, in this link, as it holds many important use cases in which you could optimize the way you use logging.

It's also possible to mix both cases in order to add a timestamp, in example, which is an improved way of using this module:

#!/usr/bin/env python
import logging
import unittest

class GetLoggerTest(unittest.TestCase):
    logger = logging.getLogger(__name__)
    logging.basicConfig(format = '%(asctime)s %(module)s %(levelname)s: %(message)s',
                    datefmt = '%m/%d/%Y %I:%M:%S %p', level = logging.INFO)

    def test_logger(self):
        self.logger.info("self.logger.info test_logger")
        pass


Find most significant bit without bitshifts

use std::uint8_t, to avoid relying on something that may or may not exist in the global namespace.
An unsigned type will always be >= 0. So if a_variable is 0, this will result in undefined behaviour by accessing something out of bounds of the bitset (and either crash or loop forever).
If we're finding the "most significant bit", I don't think avoiding bitshifts makes it more readable. (This requires understanding of both numeric_limits::digits, and std::bitset instead).


First, I will start with the good:

Photo 1

It is excellent that you use the HTML5 tag figure instead of a plain old div.

You may just have removed this for brevity (many people do), but when you write HTML, you should build your page like this:

<!doctype html>

    <title>Your Title Here</title>

Photo 1

Photo 2

You can validate your HTML at the W3C validator (it validates once you provide the framework).

It does look clumsy the way you write out each figure.  If I were you, I would probably load the images and figcaptions in a separate file (maybe a JSON file?) and use JS to add them to the page.  This way, you just have to enter the new data in this file, and the webpage will load them right in the next it is loaded.


Great that you provided a docstring! You made one minor formatting mistake though, there should be a blank line between your brief single line summary and the rest of the docstring. It's recommended in the style guide partially for readability and partially for script parsers.

class MongoDB(object):
    """Provides a RAII wrapper for PyMongo db connections.

    Available collection functions limited to those in
    attributes_to_pass. Number of simultaneous connection
    users also tracked. """

It seems like attributes_to_pass is actually a constant. If that is the case it should be UPPER_SNAKE_CASE to be clear that it is, especially when mixed with attributes that often change like client and num_users. It should also be a tuple, as tuples are immutable so will not change unless updated in the source code.

ATTRIBUTES_TO_PASS = ("update", "insert", "count")

Also, when you call on these constants you refer to the class name. While that's possible I'd personally say it's less readable. I had thought you were calling on a class you imported for a second. You can just pass self instead of the classname.

def __getattr__(self, attr):
    if attr in self.ATTRIBUTES_TO_PASS:
        return getattr(self.collection, attr)
    else:
        return getattr(self, attr)


I would just like to hi-light a few points of difference in the two and how I think they are reflected in what you are seeing.

When making a comparison between arr[target] and ele, if they are not the same then you do not need to include target within the bounds of the next iteration (hence the +/- 1). This can reduce the number of comparisons though the effect is more significant on smaller datasets.
When following the above point, it becomes sufficient terminate as "not found" when beginning > end rather then check that you are looking at the beginning or end value. Also your approach may provide a false negative when looking for "B" in the following situation.

    target
    |
    v
... A B
    ^ ^
    | |
    | end
    beginning

In this situation, because target === beginning and arr[target] !== B, it returns -1.
The googled code uses parseInt, I'm not sure how this affects correctness but I suspect this has an adverse effect on the performance.

I think what you are seeing in the scalability is because the googled code does fewer comparisons but the parseInt makes the comparisons more expensive. The reduced number of comparisons is more significant for small data sets, but for larger data sets cost of the comparison becomes more significant.

I would suggest some experimentation/investigation to see if this is accurate.


In the following, I am omitting checking for the correctness of the outputs as you have not provided a specification for what that should be. Nevertheless, consider the following points.

I think the signatures of your encoding and decoding functions are a bit unexpected: I would expect an encoding function to take a single string and not a vector of strings. This gives me the feeling that the function is doing too much (i.e., violating the guideline of one function, one responsibility). So I would break the logic into smaller pieces:

std::string encode(const std::string& str, int shift)
{
    std::string str_enc;
    std::transform(str.cbegin(), str.cend(), std::back_inserter(str_enc), [&](char ch) -> char
    {
        if (ch == 'z' || ch == 'Z')
        {
            return ch - 25;
        }
        else if (isspace(ch))
        {
            return ' ';
        }
        else
        {
            return ch + shift;
        }
    });

    return str_enc;
}

std::vector<std::string> encode(const std::vector<std::string>& str, int shift)
{
    std::vector<std::string> tempMsg;
    std::transform(str.cbegin(), str.cend(), std::back_inserter(tempMsg),
        [&](const std::string& s) { return encode(s, shift); });

    return tempMsg;
}

In the main loop logic, before getting into any file reading, check whether the choice made by the user is sensible (either 1 or 2). This allows you to make finalResult const and to initialize it in a nicer way. This is a good modern practice as given by e.g., ES.28 of the C++ Core Guidelines:

assert(choice == 1 || choice == 2);
const std::vector<std::string> finalResult = [&]()
{
    return choice == 1 ? encode(lines, key) : decode(lines, key);
}();

You don't have to explicitly close file streams. They close upon destruction.
To check if the file is good to go, you can do if(inFile) { ... } invoking its operator bool() which tells you if the stream has no errors and is ready for I/O operations (specifically, it returns !fail()).
When writing to file, you can use standard algorithms (like std::copy) since your logic is very simple:

std::ofstream outFile("outfile.txt");
std::copy(finalResult.cbegin(), finalResult.cend(),
    std::ostream_iterator<std::string>(outFile, "\n"));

Everywhere in your code, avoid using std::exit (for reasons and more discussion, see here). Instead, just do return EXIT_FAILURE or return EXIT_SUCCESS as appropriate.


Bad things will happen if any part of any circle strays outside the 0-to-1005 bounds.  It's up to you to decide whether error handling for straying out of bounds is essential.

Mild rewrite

Representing each circle as a list is not quite appropriate.  Using indexes circle[0], circle[1], and circle.[2] to mean x, y, and r, respectively, is awkward.  As a remedy, I strongly recommend namedtuple.

from collections import namedtuple

Circle = namedtuple('Circle', ['x', 'y', 'r'])
n = int(raw_input())
circles = []
for i in range(n):
    circles.append(Circle(*map(int, raw_input().split())))

Initialization of a 1005 × 1005 grid is better written as:

mat = [[0] * 1005] * 1005

The rest of the program is straightforward.  You should avoid switching nomenclature from x, y to i, j.  To reduce nesting, you can eliminate one nested if by using and.

ans = 0
for circle in circles:
    minx, maxx = circle.x - circle.r, circle.x + circle.r
    miny, maxy = circle.y - circle.r, circle.y + circle.r
    for x in range(minx, maxx+1):
        for y in range(miny, maxy+1):
            if mat[x][y] <= 1 and (x-circle.x)**2 + (y-circle.y)**2 <= circle.r**2:
                mat[x][y] += 1
                if mat[x][y] == 2:
                    ans += 1
print ans

Going further

The nesting of for: for: for: if: if is still rather overwhelming.  I think it would be beneficial to split out some of that complexity.

class Circle (namedtuple('Circle', ['x', 'y', 'r'])):
    def contains(self, x, y):
        return (x - self.x)**2 + (y - self.y)**2 <= self.r**2

    def grid_points(self):
        for x in xrange(self.x - self.r, self.x + self.r + 1):
            for y in xrange(self.y - self.r, self.y + self.r + 1):
                if self.contains(x, y):
                    yield x, y

def read_ints():
    return map(int, raw_input().split())

n = int(raw_input())
circles = [Circle(*read_ints()) for _ in xrange(n)]

mat = [[0] * 1005] * 1005
ans = 0
for circle in circles:
    for x, y in circle.grid_points():
        mat[x][y] += 1
        if mat[x][y] == 2:
            ans += 1
print ans

The way I've written it, I've removed the optimization of skipping grid points that are already known to be in the intersection of previously analyzed circles.  I think it's probably a worthwhile tradeoff in favour of readability.


NodeJS conditional request before the real request

Promises would make sense to me, but first step would be to extract stuff into functions.

You don't really need promises for this, though. Here's one way to just do it with plain callbacks:

exports.auth = (request, response, next) ->
  getUsername = (request, cb) ->
    email = request.body.email
    return cb null, request.body.username unless email

    users.findByEmail email, (error, result) ->
      return cb new InternalServerError(error) if error
      cb null, result[0].username

  getUsername (err, username) ->
    return next err if err
    auth.auth username, request.body.password, (err, json) ->
      return next err if err
      response.json json


How about:

NS.CheckType = function (o,test) {
    // implements both
    return test ? o.constructor.name === test : o.constructor.name;
};
// usage
NS.CheckType(false);       //=> 'Boolean'
NS.CheckType(false,Array); //=> false
NS.CheckType({},Object);   //=> true
NS.CheckType({},Array);    //=> false
NS.CheckType([],Object);   //=> false
NS.CheckType([],Array);    //=> true
NS.CheckType(/[a-z]/);     //=> 'RegExp'
NS.CheckType(0);           //=> 'Number'
// etc...

Because most js-things 'inherit' from Object you can also use:

Object.prototype.is = function (test) {
    return test ? this.constructor === test : this.constructor.name;
};
// usage
'string'.is();        //=> 'String'
'string'.is(Object);  //=> false
 (function(){}).is(); //=> Function
 var f = function(){};
 f.is(Function);      //=> true
 // also
 function Animal(name){this.name = name || 'some animal';}
 var dog = new Animal('Bello');
 dog.is(Animal); //=> true
 // etc...

[Edit] tested this in IE7-10:

Object.prototype.is = function (test) {
    return test
      ? this.constructor === test
      : (this.constructor.name ||
         String(this.constructor)
             .match ( /^function\s*([^\s(]+)/im)[1] );
};

for completeness: if the constructor function is anonymous the method will fail. Here's a solution for that:

Object.prototype.is = function (test) {
        return test
          ? this.constructor === test
          : (this.constructor.name ||
              ( String(this.constructor).match ( /^function\s*([^\s(]+)/im)
               || ['','ANONYMOUS_CONSTRUCTOR'] ) [1] );
};
// usage
var Some = function(){ /* ... */}
    some = new Some;
some.is(); //=> 'ANONYMOUS_CONSTRUCTOR'

And as bonus:

Object.prototype.is = function() {
        var test = arguments.length ? [].slice.call(arguments) : null
           ,self = this.constructor;
        return test ? !!(test.filter(function(a){return a === self}).length)
               : (this.constructor.name ||
                  (String(self).match ( /^function\s*([^\s(]+)/im)
                    || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Some = function(){ /* ... */}
   ,Other = function(){ /* ... */}
   ,some = new Some;
2..is(String,Function,RegExp);        //=> false
2..is(String,Function,Number,RegExp); //=> true
some.is();                            //=> 'ANONYMOUS_CONSTRUCTOR'
some.is(Other);                       //=> false
some.is(Some);                        //=> true
// note: you can't use this for NaN (NaN === Number)
(+'ab2').is(Number);                 //=> true


strReadLine function (read line by line from a string)

Code format

Your use of spaces, braces and parantheses is unconventional in some places.

For example:

while( (line = strReadLine(input)) ){
    x++;
    printf("%s\n",line);
    if(x == 300){printf("emergency break\n");break;}
}

Conventionally this would look more like this:

while (line = strReadLine(input)) {
    x++;
    printf("%s\n", line);
    if (x == 300) {
        printf("emergency break\n");
        break;
    }
}

You could try using your IDE's auto-format feature and see how it arranges the code. Also you might want to have a look at some C coding conventions that can be found online, to see how people commonly format their C code in a readable way.

Thread safety

It seems like you are trying to guard the function against multiple threads executing it at the same time. However, the function's purpose is to read a string line by line, not to write to it. So as long as the function is only reading from its input, there should be no need to prevent multiple concurrent executions.

If multiple threads really did execute it at the same time, you could still get a race condition between checking the variables and overwriting it, and thus not get the error message when you would expect it.

Abusing booleanness

When checking whether an integer has the value 0, it is more readable if you compare it to 0, as you do in the first of the following two lines. It reads more intuitively, because a length cannot be true or false, as the second line implies, even though the compiler can handle both. Then you also wouldn't need the comment explaining what !length is supposed to mean. if (length == 0) says it explicitly.

if(length == 0 || start == 0) length = strlen(text);
if(!length) return (char*) 0;//the string is 0 length


Java cycle detection using DFS in an undirected graph

There are a couple of suggestions I have here.

The first is a major performance one... you have the code:

boolean isCycle = false;
for(Node node : nodes){
    isCycle = isCycle || isCycled(node, getEdgeNum(n,node));
}
return isCycle;

This should be 'short-circuited' for true conditions, and should simply be:

for(Node node : nodes){
    if (isCycled(node, getEdgeNum(n,node))) {
        return true;
    }
}
return false;

There is no need to continue to walk the entire tree and find every cycle after yu have found one already!

The second item is more minor, and just something I would 'try'....

Instead of using the edge management, and visited tate on the nodes, I would consider using an IdentityHashMap to track what has been seen or not. Treat it like a 'stack' using put() and remove() like push and pop. That way yon can do something like:

//base case: if an unexplored edge that lead to a node that is visited.
// if(edgeNum>=0){//make sure it is not the first node
    if(seenmap.contains(node)) {
        return true; //found cycle
    }
// }

for(Node node : nodes){
    seenmap.put(node, null);
    isCycle = isCycle || isCycled(node, getEdgeNum(n,node));
    seenmap.remove(node);
}

If your comment about the A-->B-->A not being a cycle means that if a node points back to where it came from , it's not a cycle, then I recommend passing in the 'source' when you walk the graph... for example:

boolean isCycled(Node n, Node from, int edgeNum){

and then, your logic will look like:

for(Node node : nodes){
    if (node == from) {
        // this is a point-back to where we just came from in the graph)
        return false;
    }
    seenmap.put(node, null);
    isCycle = isCycle || isCycled(node, n, getEdgeNum(n,node));
    seenmap.remove(node);
}


Find the longest common subsequence algorithm - low speed

Firstly, your algorithm is incorrect try:

lcs("AAAABCC","AAAACCB"), the LCS should be "AAAACC", but your algorithm finds "AAAAB".

Secondly your algorithm is O(n^2*m) not O(n*m). Since you don't elaborate as to why you think your algorithm is theta(n*m) I can't really guess where your analysis has gone wrong.

Your second version attempts to optimize the process of searching through the string by using a list of pre-calculated positions. This means you don't have to scan through all the positions in the string with different characters. However, you lose the ability to skip all the position before your starting index. For long strings with few distinct characters, you end up losing out.


A review of the JavaScript part:

ajaxCon is a class/constructor, so you should call it AjaxCon, though really I would think about finding an even better name :)
ajaxFailure -> You have a number of functions that have ajax in their name, since these functions are in the Ajax constructor you can drop the ajax part
this.callback = false; -> Don't declare callback at all and then use if(this.callback) this.callback(responseArray);
This could use some newlines:
$.ajax( $.extend(true, {}, this.ajaxSettings, {data:{'ajaxFunction':functionName, 'arguments':argumentArray}} ) );

and also

this.ajaxSettings = { url: window.location.href, type: 'POST', cache: false, data: {ajaxRequest: true}, success: function (returnData) {
    ajaxCon.ajaxReturn(returnData)
}};

Also the location of this.ajaxSettings is odd, this belongs on top of that function


Animation that gets triggered by two buttons

Depends on application design. What is "more important" - image, or button?

It could be something like move(Image image) method in the buttons (decalred in interface of the buttons), or it may be reactOn(Button button) in Image.

It is hard to recommend something with the presented information. Generally, code reuse is always a good move.


Calculate quote volumes (for a financial instrument) within numeric constraints

Bug

adjust_volume(0) presently results in:

  UnboundLocalError: local variable 'bid_volume' referenced before assignment

since if position_size == 0: is currently indented inside the elif position_size < 0: statement, so is unreachable.  (This could be a result of poor formatting when copying the code into the question post.)

Possible Bug

Some volume calculations result in negative volumes.  (adjust_volume(99) gives bid_volume == -8, and adjust_volume(-99) gives ask_volume == -14, which seem like invalid results.)

Possible Bug

If adjust_volume() is given an argument >= 100 or <= -100, it also fails with an UnboundLocalError.  Limits should be checked and a ValueError be raised instead.

  This trading system strictly cannot exceed a position limit of 100 in either direction, so our order volumes need to never exceed 100 when combined with the absolute value of current position.

100 does not exceed 100, so it is likely the original implementation should have allowed +100 and -100 as well.  But these currently result in UnboundLocalError.

Chained comparisons

I have to say, this condition makes my brain hurt:

    elif position_size <= -65 and position_size > -82:

It took me several moments to unwind what the range was, and I had to triple check that I got it right.  It would be much clearer to express as:

    elif -82 < position_size and position_size <= -65:

or using the chaining comparison operations:

    elif -82 < position_size <= -65:

Bisect

You have 9 ranges:

-100 < position_size <= -82
-82 < position_size <= -65
-65 < position_size <= -45
-45 < position_size < 0
0 <= position_size <= 0
0 < position_size < 45
45 <= position_size < 65
65 <= position_size < 82
82 <= position_size < 100

Instead of using a tree of if-elif-else statements to locate the correct range, you could bisect the list -81, -64, -44, 0, 1, 45, 65, 82 to determine the correct range bucket.

Note: Negative bucket limits have been increased by 1 to account for the difference in whether the lower limit or the upper limit is included as position_size goes from negative values to positive values.

from bisect import bisect

POSITION = (-81, -64, -44, 0, 1, 45, 65, 82,)
BID_ASK = (
    (75, 85), # -100 < pos <= -82
    (50, 82), # -82 < pos <= -65
    (50, 65), # -65 < pos <= -45
    (10, 45), # -45 < pos < 0
    (30, 30), # 0 <= pos <= 0
    (45, 50), # 0 < pos < 45
    (65, 50), # 45 <= pos < 65
    (82, 50), # 65 <= pos < 82
    (91, 85), # 82 <= pos < 100
)

def adjust_volume(position_size):

    if not(-100 < position_size < 100):
        raise ValueError("position size out of range")

    bucket = bisect(POSITION, position_size)

    bid_volume, ask_volume = BID_ASK[bucket]
    if position >= 0:
        bid_volume -= position_size
    else:
        ask_volume -= abs(position_size)

    return position_size, bid_volume, ask_volume


Regular expression matching with string slice in Go

You're not making good use of regular expressions. A single regex can do the job:

pattern := regexp.MustCompile(`([a-zA-Z]+)=`)

The parentheses (...) are the capture the interesting part for you.

You can use result = pattern.FindAllStringSubmatch(s) to match a string against the regex pattern. The return value is a [][]string, where in each []string slice, the 1st element is the entire matched string, and the 2nd, 3rd, ... elements have the content of the capture groups. In this example we have one capture group (...), so the value of the key will be in item[1] of each []string slice.

Instead of a map[string]string map for seen, a map[string]boolean would be more efficient.

Putting it together:

func GetKeys(logs []string) []string {
    var keys []string
    pattern := regexp.MustCompile(`([a-zA-Z]+)=`)

    seen := make(map[string]bool)
    for _, log := range(logs) {
        result := pattern.FindAllStringSubmatch(log, -1)
        for _, item := range result {
            key := item[1]
            if _, ok := seen[key]; !ok {
                keys = append(keys, key)
                seen[key] = true
            }
        }
    }

    return keys
}

If the input strings are not guaranteed to be in the right format matching the pattern, then you might want to add a guard statement inside the main for loop, for example:

    if len(result) != 2 {
        continue
    }


If n is zero then the loop

while (startCol <= endCol && startRow <= endRow)

does nothing, which means that the test

if (n == 0)

is not necessary.

Here

for (int i = endCol; i >= startCol; i--)
{
    //keep in mind this is a spiral we can be in a line we are not suppose to touch the values
    //only in the upper half of the matrix we need
    if (startRow <= endRow)
    {
        res[endRow][i] = num++;
    }
}

the condition of the if-statement is a loop invariant, so that it can be done outside of the loop:

if (startRow <= endRow)
{
    for (int i = endCol; i >= startCol; i--)
    {
        res[endRow][i] = num++;
    }
}

Even if the C# compiler is smart enough to recognize the loop invariant and reorders the statements, the latter variant would be clearer to the reader of your code. The same applies to the next loop in your function.

Then note that startRow/startCol and endRow/endCol have the same value at the start of the loop body, and the tests

if (startRow <= endRow) ...
if (startCol <= endCol) ...

can fail only in the last iteration. Therefore one can move that case out of the main loop, use only two variables for the first and last row/column, and write the inner loops in a symmetric fashion:

int start = 0;
int end = n - 1;

while (start < end)
{
    for (int i = start; i < end; i++)
    {
        res[start][i] = num++;
    }
    for (int i = start; i < end; i++)
    {
        res[i][end] = num++;
    }
    for (int i = end; i > start; i--)
    {
        res[end][i] = num++;
    }
    for (int i = end; i > start; i--)
    {
        res[i][start] = num++;
    }

    start++;
    end--;
}

if (start <= end)
{
    res[start][start] = num;
}


Find existing player to update or create new one

A very quick review for the code, and assuming Java < 8:

public void handleNewPlayer(Player newPlayer, Player[] otherPlayers) {
    for (Player otherPlayer : otherPlayers) {
        if (newPlayer.id == otherPlayer.id) {
            updatePlayer(otherPlayer);
            return;
        }
    }

    createPlayer(newPlayer);
}

Some code styles prohibit this because you typically only want to have one return in a function (there's two here), but I typically overlook this for simple methods where the logic ends up clearer in my opinion.

And here's a Java 8 way (might not be optimal)

public void handleNewPlayer(Player newPlayer, Player[] otherPlayers) {
    final Optional<Player> otherPlayer = Arrays.stream(otherPlayers)
        .filter((Player p) -> newPlayer.id == p.id)
        .findFirst();

    if (otherPlayer.isPresent()) {
      updatePlayer(otherPlayer.get());
    }
    else {
      createPlayer(newPlayer);
    }
}

It doesn't do much on the LOC metric, but it has a much clearer semantic meaning.

A comment from Vogel612 brings up the Optional#orElse method. This sounds like a great method, but the only way I can see it used here is as follows:

public void handleNewPlayer(Player newPlayer, Player[] otherPlayers) {
    final Optional<Player> player = Arrays.stream(otherPlayers)
        .filter((Player p) -> newPlayer.id == p.id)
        .findFirst()
        .orElse(newPlayer);

    if (newPlayer == player) {
      createPlayer(newPlayer);
    }
    else {
      updatePlayer(player);
    }
}

I think this has even greater semantic meaning, but your mileage my vary. Additionally, I still feel like we're lacking the conciseness of the final version below.

Finally, you can now use Groovy for Android development. Here's how this can be done in Groovy:

def handleNewPlayer(Player newPlayer, Player[] otherPlayers) {
  def otherPlayer = otherPlayers.find() { newPlayer.id == otherPlayer.id }
  if (otherPlayer) {
    updatePlayer otherPlayer
  }
  else {
    createPlayer newPlayer
  }
}


if (this.ValueTextBox.Text.Length > 0)
{
    value = Convert.ToInt32(this.ValueTextBox.Text);
}

This will throw a nullpointerexception if Text is null, use TryParse instead

int value;
bool result = Int32.TryParse(ValueTextBox.Text, out value);
if(result){
 // use value
}

I don't recommend you using SelectedIndex, because it breaks your code if the ordering get changed in the future, I would use SelectedItem instead.

Notice that you are repeating code, which is not a brilliant idea.

TheTypeForThis gr01 = null;
TheTypeForThis adapter = null;
switch (this.ServerComboBox.SelectedIndex)
{
    case 0:
        gr01 = new GR01.TargetVDNDataTable();
        adapter = new ICMQuery.Models.GR01TableAdapters.TargetVDNTableAdapter();
        break;
    case 1:
        var ds01 = new DS01.TargetVDNDataTable();
        var adapterNew = new ICMQuery.Models.DS01TableAdapters.TargetVDNTableAdapter();
       break;
}

 if (value == 0)
 {
    adapter.Fill(gr01);
 }
 else
 {
    adapter.FillByPeripheralNumber(gr01, value);
 }
 this.FindScriptsDataGrid.DataSource = gr01;


Understanding the differences: A direct comparison between Cython and C++

Translating python to C++ (just a direct line for line translation).

Headers

import cython                                       #include <iostream>
import numpy as np                                  #include <vector>
                                                    #include "Range.h"
@cython.boundscheck(False)
@cython.wraparound(False)

MathObject

cdef class MathObject:                              struct MathObject {
    cdef double a                                       double a;

    def __init__(self, a):                              MathObject(double a)
        self.a = a                                          : a(a)
                                                        {}
    cpdef double logMap(self):                          double logMap() {
        self.a = 4.0 * self.a * (1.0 - self.a)              a = 4.0 * a * (1.0 - a);
        return 0                                            return 0;
                                                        }
    def get_value(self):                                double get_value() {
        return self.a                                       return a;
                                                        }
                                                    };

run

def run():                                          void run() {
    cdef int i, ii, iii
    cdef int one_thousand = 1000                        int one_thousand = 1000;
    cdef double x = 0.2                                 double x = 0.2;

    cdef MathObject objInstance

    objArray = np.empty(one_thousand, dtype=MathObject) std::vector<MathObject> objArray(one_thousand, x);
    for i in range(len(objArray)):
        objArray[i] = MathObject(x)

    cdef MathObject[:] objArrayiew = objArray

    for i in range(one_thousand):                       for(int i: Range(one_thousand)) {
        for ii in range(one_thousand):                      for(int ii: Range(one_thousand)) {
            for iii in range(one_thousand):                     for(int iii: Range(one_thousand)) {
                objInstance = objArrayiew[iii]                      MathObject& objInstance = objArray[iii];
                objInstance.logMap()                                objInstance.logMap();
                                                                }
                                                            }
        print objArray[i].get_value()                       std::cout << objArray[i].get_value() << "\n";
                                                        }

    return None
                                                    }

main

if __name__ == "__main__":                          int main() {
    run()                                               run();
                                                    }

In C++ there is no built in Range type. But it is easy to write:

class Range
{
    int beginValue;
    int endValue;

    struct RangeIterator
    {
        int value;
        RangeIterator(int v) : value(v) {}
        RangeIterator& operator++()     {++value;return *this;}
        int            operator*()      {return value;}
        bool           operator!=(RangeIterator const& rhs) const {return value != rhs.value;}
    };

    public:
        typedef RangeIterator           iterator;
        Range(int e)
            : Range(0, e)
        {}
        Range(int b, int e)
            : beginValue(b), endValue(e)
        {}

        iterator begin() { return RangeIterator(beginValue);}
        iterator end()   { return RangeIterator(endValue);}
};

A couple of notes on the direct translation that I would change:

If you are not going to return a meaningful value (and we notice from usage that the return value is ignored).

double logMap() {
    a = 4.0 * a * (1.0 - a);
    return 0;
}

Then I would make this a void function so you know its not supposed to return anything.

void logMap() {
    a = 4.0 * a * (1.0 - a);
}

I don't like geters they break encapsulation:

double get_value() {
    return a;
}

You usually find that if you are getting values from an object doing stuff with it there is usally a member function (or member of the public API) that can do that. In this case you are only using the value to print. So why not just create a function that knows how to print the value.

friend std::ostream& operator<<(std::ostream& stream, MathObject const& data)
{
    return stream << data.a;
}

If values don't change then mark them as const.

int    const one_thousand = 1000;
double const x            = 0.2;


Formatting

The obvious wrong thing with your code is the indentation (I don't know if it is because of the copy on CodeReview.SE).

Also, the lines breaks seem to be used randomly. They should be used to divide the different logical parts of your function/program.

You could use more spaces to make your code easier to go through.

Finally (but this is a tiny detail), you have loads of trailing whitespace making things a bit more painful to edit. You can easily remove them automatically.

Activate warnings in your compiler

It is usually a good idea to enable all warnings in your compiler and to take them into account. In your case, gcc complains about the return value for main.

Once this is fixed, your code looks like :

#include <stdio.h>
#include <string.h>

int main()
{
        char str[20];
        printf("\n Enter a string");
        scanf("%s",str);
        int len = strlen(str);
        int i,flag = 1;
        for(i=0; i < len - 1; i++)
        {
                if (str[i+1] >= str[i])
                        continue;
                else
                {
                        flag = 0 ;
                        break;
                }
        }

        if(flag == 0)
                printf("\n String is not Abecedarian ");
        else
                printf("\n Is abecedarian");
        return 0;
}

Logic

Your code seems OK but there is a way to improve how the logic is written. For instance, you could get rid of the continue by rewriting the condition. The inside of the loop becomes :

            if (str[i+1] < str[i])
            {
                    flag = 0 ;
                    break;
            }

In the same kind of spirit, I'd inverse the conditions for the printing as I find it easier to read something like :

    if(abcdarian)
            printf("\n Is abecedarian");
    else
            printf("\n String is not Abecedarian ");

More style

It is usually a good idea to try to move your variables in the smallest possible scope. In your case, using c99, you can move i into the for loop : for(int i=0; i < len - 1; i++).

In the same kind of spirit, it could be a good idea to create a function to handle the logic currently in the loop. Then you'd be able to just call if (isAbecedarian(str)).

About scanf

You'll find online a few problems with scanf and details about what you should be doing like using fgets.


Your IsElementVisible method can be condensed to:
public bool IsElementVisible(IWebDriver driver, By element)
{
    return driver.FindElements(element).Count > 0
        && driver.FindElement(element).Displayed;
}

I guess the method IsElementNotVisible should return boolean negation of result of the IsElementVisible method:
public bool IsElementNotVisible(IWebDriver driver, By element)
{
    return !IsElementVisible(driver, element);
}

Boolean comparisons
Expressions x == true and just x are eqivalent.
Expressions x == false and just !x are also eqivalent.
For example, you don't need to write:
if (productIssue == false || productIssueB == false)

you could write instead:
if (!productIssue || !productIssueB)


I have only a couple of points:

1

You implementation will be able to store only one list throughout your Java program:

SinglyCircularList list1 = new SinglyCircularList();
SinglyCircularList list2 = new SinglyCircularList();

list1.insert(1); // Here list1 = [1], and list2 = [1];
list2.insert(2); // Now  list1 = [1, 2], and list2 = [1, 2]

So, basically, you should remove the keyword static from everywhere except the main(String[] args).

2

It would be nicer if your delete method would throw an exception on deleting from an empty list.

3

Instead of printList() you could override the public String toString().

4

private static NodeS head = null;
private static NodeS tail = null;
private static int size = 0;

Whenever declaring class or object fields, references are initialized by default with null, and numeric fields to zero. You can write simply:

private NodeS head;
private NodeS tail;
private int size;

Summa summarum

I had something like that in mind:

import java.util.NoSuchElementException;

public class SinglyCircularList<E> {

    private static final class Node<E> {

        private final E datum;
        private Node<E> next;

        Node(final E datum) {
            this.datum = datum;
        }

        E getDatum() {
            return datum;
        }

        Node<E> getNext() {
            return next;
        }

        void setNext(final Node<E> next) {
            this.next = next;
        }
    }

    private Node<E> head;
    private Node<E> tail;
    private int size;

    public int size() {
        return size;
    }

    public void insert(final E datum) {
        final Node<E> newnode = new Node<>(datum);

        if (head == null) {
            head = newnode;
            tail = newnode;
            size = 1;
            return;
        }

        tail.setNext(newnode);
        tail = newnode;
        size++;
    }

    public E delete() {
        if (isEmpty()) {
            throw new NoSuchElementException("Deleting from an empty list.");
        }

        final E ret = head.getDatum();

        if (size == 1) {
            head = null;
            tail = null;
        } else {
            head = head.getNext();
            tail.setNext(head);
        }

        size--;
        return ret;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("[");

        if (size > 0) {
            sb.append(head.getDatum());
        } else {
            return "[]";
        }

        Node<E> currentNode = head.getNext();

        for (int i = 1; i < size; ++i, currentNode = currentNode.getNext()) {
            sb.append(", ").append(currentNode.getDatum());
        }

        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        SinglyCircularList<Integer> scl = new SinglyCircularList<>();

        System.out.println("Creating the list:");

        for (int i = 1; i <= 8; ++i) {
            System.out.println(scl);
            scl.insert(i);
        }

        System.out.println(scl);

        System.out.println("Removing from the list:");

        while (!scl.isEmpty()) {
            scl.delete();
            System.out.println(scl);
        }
    }
}

Hope that helps.


Avoid using "special return values" in code for when errors occur. It should be up to the calling code how to handle the situation.

I would let the getNumberDialog utility function re-throw the exception:

private int getNumberDialog(String message) throws NumberFormatException {
    String resultInString = JOptionPane.showInputDialog(message);
    int result = Integer.parseInt(resultInString);
    return result;
}

And in your usage code, you catch the exception:

try {
    int times = getNumberDialog("How many times?");
    game.playForMeNrTimes(times);
} catch (NumberFormatException ex) {
    JOptionPane.showMessageDialog(null, "You didn't gave a number");
}

The key here is that the utility-function getNumberDialog doesn't know about any context. It doesn't know how the returned value will be used, so how can it possibly decide on a default value to use in the case of an error?


Using RouteValueDictionary to convert anonymous type to query string

Instead of catching an exception if the url is relative, use the System.Uri class to see if it is an absolute Uri.


Program that generates brainfuck code that outputs given text

I opened your code in CLion. The first thing it marked was:

#define ALLOCATION_ERROR 1

It's unused.

Other than that, there were no warnings, which is already quite good.

Next I compiled your code using both GCC and CLang:

$ gcc -Wall -Wextra -Os -c bfgen.c
$ clang -Wall -Weverything -Os -c bfgen.c
bfgen.c:5:9: warning: macro is not used [-Wunused-macros]
#define ALLOCATION_ERROR 1
        ^
1 warning generated.

That's also good. You prepared your code quite well for this code review by fixing the compiler warnings (if there had been any).

Now to the human part of the code review.

I would remove the inline from the function definitions. Trust the compiler to do the right thing here.

The word get in the function name get_file_pointer makes it sound as if this function had no side effects. This assumption is wrong. The function should have a better name. It is typical for these error-checking wrapper functions to be prefixed with x. You will find many implementations of xmalloc, xrealloc, xopen, and so on in other projects.

In the get_file_pointer function, you should include the kind of error in the fprintf output:

fprintf(stderr, "Error: failed to open file '%s': %s\n", filename, strerror(errno));

The function int_to_brainfuck has a bad name. It's clear from the function signature that it takes an int, therefore the function name should rather describe what that int means. It's a difference, but there is no documentation about what differs. After reading the whole code of the function I know that it's the difference between the previous character and the next character. This information should be encoded in the function name.

Calling strlen repeatedly is a waste of time. At each point in the code you know exactly how long the string is, therefore it is more efficient to just store the current end of the brainfuck_code in a pointer and always strcpy to that pointer:

size_t code_len = number_of_tens + loop_body_length + number_of_ones + 2;
char *brainfuck_code = calloc(code_len, sizeof *brainfuck_code);
char *code = brainfuck_code;

if (number_of_tens > 0) {
    *code++ = '>';
    memset(code, '+', number_of_tens);
    code += number_of_tens;
    strcpy(code, "[<");
    code += 3;
    memset(code, character_in_loop, 10);
    code += 10;
    strcpy(code, ">-]<");
    code += 4;
}

memset(code, character_in_loop, number_of_ones);
code += number_of_ones;
*code++ = '.';

assert(brainfuck_code + code_len == code);

return brainfuck_code;

I added the assert at the end because these explicit length calculations can always go wrong. If the compiler is smart enough, it will find out that this assertion always succeeds and may even eliminate it. And in case you forgot a character to change the code later, you will quickly get a crash dump instead of undefined behavior because of a buffer overflow.

I suspected you had already calculated the length wrong because I couldn't find the first character in the formula. Instead, there's a magic number 2 in that formula. You should make the formula correspond to the actual code by writing it like this:

size_t code_len = 1 + number_of_tens + 3 + 10 + 4 number_of_ones + 1;

This allows you to quickly compare it to the code.

Even better would be if you would not need this whole calculation at all. Since you are writing the output to a file anyway, you don't need to allocate the memory yourself. I'm thinking of two functions like these:

typedef struct {
    FILE *out;
} bfgen;

static void bfgen_emit_str(bfgen *gen, const char *code) {
    ...
}

static void bfgen_emit_repeat(bfgen *gen, char code, size_t n) {
    ...
}

Then you can simply write:

static void
bfgen_emit_difference(bfgen *gen, int difference) {
    if (difference == 0) {
        bfgen_emit_str(".");
        return;
    }

    char character_in_loop = difference > 0 ? '+' : '-';
    unsigned int abs_diff = difference > 0 ? difference : -difference;
    unsigned int number_of_tens = abs_diff / 10;

    if (number_of_tens > 0) {
        bfgen_emit_str(gen, ">");
        bfgen_emit_repeat(gen, '+', number_of_tens);
        bfgen_emit_str(gen, "[<");
        bfgen_emit_repeat(gen, character_in_loop, 10);
        bfgen_emit_str(gen, ">-]<");
    }

    bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);
    bfgen_emit_str(gen, ".");
}

This code looks much clearer. Now that you don't have to think about all this annoying buffer size calculation anymore, it becomes much easier to add new optimizations, such as avoiding the loop when number_of_tens is exactly 1. In the previous version of the code I wouldn't have added this feature out of laziness and fear of breaking things.

Based on this example, you can see that the functions bfgen_emit_str and bfgen_emit_repeat are really useful, and implementing them is easy.

static void bfgen_emit_str(bfgen *gen, const char *code) {
    fputs(code, gen->out);
}

static void bfgen_emit_repeat(bfgen *gen, char code, size_t n) {
    for (size_t i = 0; i < n; i++) {
        fputc(code, gen->out);
    }
}

Looking at bfgen_emit_difference again, that function doesn't do what its name says. It doesn't only emit code to calculate the difference, it also emits code to print the resulting character. It shouldn't do that. The call to bfgen_emit_str(gen, ".") belongs in bfgen_generate_code instead.

It doesn't matter anymore, but your original version of int_to_brainfuck was essentially:

static char *
int_to_brainfuck(...) {
    if (condition) {
        return ".";
    } else {
        return allocated_string;
    }
}

You must never write such a function since the caller cannot know whether they should free the string or not. This leads either to memory leaks or to undefined behavior. You don't want either of these.

In the main function, you should open the input file in binary mode and the output file in text mode. Currently it's the other way round.

The main takeaway from this code review is that it makes sense to define your own data structures and the corresponding functions. Make these functions as easy as possible to use. Free the caller from any unnecessary tasks such as calculating buffer sizes or managing memory, which are really boring and error-prone.

An idea for further work is to make the generated code more efficient by keeping track of the actual memory contents. This can now be easily done in the struct bfgen. Then you can look which memory cell has currently the closest value and use that instead of just using a single memory cell.

The rewritten and restructured code is:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FILE_ERROR 2
#define OTHER_ERROR 3

static FILE *
xfopen(const char *filename, const char *mode) {
    FILE *file_pointer = fopen(filename, mode);
    if (file_pointer == NULL) {
        fprintf(stderr, "Error: failed to open file '%s': %s\n",
                filename, strerror(errno));
        exit(FILE_ERROR);
    }
    return file_pointer;
}

typedef struct {
    FILE *out;
} bfgen;

static void
bfgen_emit_str(bfgen *gen, const char *code) {
    fputs(code, gen->out);
}

static void
bfgen_emit_repeat(bfgen *gen, char code, size_t n) {
    for (size_t i = 0; i < n; i++) {
        fputc(code, gen->out);
    }
}

static void
bfgen_emit_difference(bfgen *gen, int difference) {
    if (difference == 0) {
        return;
    }

    char character_in_loop = difference > 0 ? '+' : '-';
    unsigned int abs_diff = difference > 0 ? difference : -difference;
    unsigned int number_of_tens = abs_diff / 10;

    if (number_of_tens > 0) {
        bfgen_emit_str(gen, ">");
        bfgen_emit_repeat(gen, '+', number_of_tens);
        bfgen_emit_str(gen, "[<");
        bfgen_emit_repeat(gen, character_in_loop, 10);
        bfgen_emit_str(gen, ">-]<");
    }

    bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);
}

static void
bfgen_generate_code(bfgen *gen, FILE *input_file) {
    int current_char, last_char = 0;
    while ((current_char = fgetc(input_file)) != EOF) {
        bfgen_emit_difference(gen, current_char - last_char);
        bfgen_emit_str(gen, ".\n");
        last_char = current_char;
    }
}

static void
parse_args(int argc) {
    if (argc != 3) {
        puts("Usage: bfgen <input> <output>");
        exit(OTHER_ERROR);
    }
}

int
main(int argc, char **argv) {
    parse_args(argc);
    FILE *input_file = xfopen(argv[1], "rb");
    FILE *output_file = xfopen(argv[2], "w");
    bfgen gen = {output_file};
    bfgen_generate_code(&gen, input_file);
    fclose(output_file);
    fclose(input_file);
    return 0;
}


This code is not portable.  The order of bit-fields within a word is completely compiler-dependent, so the test that appears to work on one platform may give completely different results on another.
You have avoided a common trap of using signed 1-bit fields (which can hold values 0 and -1) - these unsigned ones are much better.
I don't think there's any need for the bits member to be named - I would use an anonymous member there.
The numbering of bits is unconventional - most programmers would expect b0 to be the least-significant bit, and b7 the most significant (corresponding to 2⁰ and 2⁷ value of those bits in integers).
The test would be better if it were self-checking - return with non-zero status if any of the expectations are not met.  For example:
int main(void)
{
    int failures = 0;

    {
        /* First test */
        union bit_array test = { {1, 1, 1, 1, 1, 1, 1, 1} };
        if (test.value != 0xFF) {
            fprintf(stderr, "Test 1 expected 0xff, got %#04hhx\n", test.value);
            ++failures;
        }
    }

    {
        /* Second test */
        union bit_array test = { {1, 1, 1, 1, 1, 1, 1, 1} };
        test.bits.b8 = 0;
        if (test.value != 0xFE) {
            fprintf(stderr, "Test 2 expected 0xfe, got %#04hhx\n", test.value);
            ++failures;
        }
    }

    return failures != 0;
}

We need tests of the most-significant bit, and setting as well as resetting bits.  I'll leave that as an exercise.


Helper for DropDownLists with extension method

The native MVC solution is to pass your collection into the SelectList class.

@Html.DropDownListFor(m => m.Item, new SelectList(Model.MyList, "ValueProperty", "TextProperty"))

This would make your helper method unnecessary.

However, the downside to the native approach is that there is no compile-time safety on the Text/Value properties, so you may still want to have a helper method similar to what you've written for this added benefit.

The DropDownListFor methods handle which item is selected for you, so you don't need to concern yourself with populating the Selected property for your SelectListItems.

Your extension method is not idiomatic to DropDownListFor<TModel, TProperty> because you're not using a generic type for the given property. You would at least want to keep TProperty as a generic type, and add a third generic type to your extension method for the collection type. This would change your method signature to DropDownListFor<TModel, TProperty, TElem> and your second parameter to Expression<Func<TModel, TProperty>> expression.

However, your approach has one major design issue: you lose out on all the overloads that exist for DropDownListFor. While you could reimplement all of them, it would be tackling the wrong problem.

You essentially want an elegant way to create a SelectList, so that's what your extension method should do. A Linq extension that works similarly to the ToDictionary extension method would look like the following:

public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> source, Func<T, string> valueFunc, Func<T, string> textFunc)
{
    return source.Select(x => new SelectListItem
    {
        Value = valueFunc(x),
        Text = textFunc(x)
    });
}

Then you can use the native MVC DropDownListFor on any collection easily:

@Html.DropDownListFor(m => m.Item, Model.MyList.ToSelectList(x => x.ValueProperty, x => x.TextProperty))
@Html.DropDownListFor(m => m.Item, Model.MyList.ToSelectList(x => x.ValueProperty, x => x.TextProperty), "Choose...", new { @class = "form-control dropdown" })


Laravel coupling

What a shame that you decided to tie this to laravel. You can decouple the entire library from laravel framework and only provide a bundle for laravel.

routeFromModel accepts Model, but it can actually work for any object.

$route = $router->getRoutes()->getByName($routeName);
if (!$route) {
  throw new RouteNotFoundException("Route $routeName not found");
}
$params = $route->parameterNames();

This means you really don't need the router, you just need something that gives you an "array of prameter names" based on a "name".

return rtrim($urlGen->route($routeName, $data), '?');

Returning just the data here would make it more flexible.

IoC

You are pulling the RouteBuilder from DI container, why not have the container inject those deps. The way it is now, it could just be a static class with only static methods...


Least suprising extension methods for DateTime to NATO date-time group

Firstly, I don't like the acronyms. With intellisense you can hit tab pretty early on to finish your names for you, so there's no sense adding an extra cognitive leap to work out what these functions do (even with your fairly comprehensive commenting). Call them ToDateTimeGroup and ToZuluDateTimeGroup or, even better, ToNatoDateTimeGroup and ToNatoZuluDateTimeGroup.

Speaking of commenting, your meta comments for the second method are unfinished. Additionally your commenting in-method is only commenting obvious code, which is unhelpful. Comments should explain why, not what or how, unless it's really hard to work it out (in which case, it probably needs refactoring). Additionally, comments on a new line above the code in question are generally more readable.

Your parameter names would also be better written out fully, e.g. dateTime instead of dt.

Your "Z" code is a magic string and should be a constant somewhere. It is arguable that your format strings are too.

I seem to say this a lot, but prefer to use var when the right hand side of a declaration makes the type obvious. Doing so means that should you need to change a variable's type, you only have to edit the declaration once.

I like to extend this rule to also include when the variable name makes the type obvious too, but many disagree, so your mileage may vary.

Resulting code looks like this:

/// <summary>
/// Extension methods to create NATO date-time groups from DateTime instances.
/// </summary>
static class NatoDtg
{

    private const char ZuluTimeZoneCode = `Z`;

    /// <summary>
    /// Get NATO date-time group for UTC/Zulu timezone
    /// </summary>
    /// <param name="dt">this</param>
    /// <returns>NATO date-time group</returns>
    public static string ToNatoZuluDateTimeGroup(this DateTime dateTime)
    {
        var utcTime = dateTime.ToUniversalTime();
        var culture = new CultureInfo("en-GB");

        var builder = new StringBuilder();
        builder.Append(utcTime.ToString("ddHHmm", culture));
        builder.Append(ZuluTimeZoneCode);
        builder.Append(utcTime.ToString("MMMyy", culture).ToLower());
        return builder.ToString();
    }

    /// <summary>
    /// Get NATO date-time group for a time zone
    /// </summary>
    /// <param name="dateTime">this</param>
    /// <param name="timeZone">Time zone for the date-time group </param>
    /// <returns></returns>
    public static string ToDtg(this DateTime dateTime, TimeZoneInfo timeZone)
    {
        if (timeZone == null) throw new ArgumentNullException("TimeZoneInfo is null");
        var culture = new CultureInfo("en-GB");
        var builder = new StringBuilder();
        builder.Append(dt.ToString("ddHHmm", culture));

        TimeSpan time = timeZone.GetUtcOffset(dateTime);

        char letter = '#';
        if(ts.Hours == 0)
        {
            letter = ZuluTimeZoneCode;
        }
        else if(ts.Hours >= 1 && ts.Hours <= 9)
        {
            //Letters A-I are based on hours
            letter = 'A';
            letter += (char)(ts.Hours-1);
        }
        else if(ts.Hours >= 10 && ts.Hours <= 12)
        {
            //Letters K-M are based on hours, offset because we skip J
            letter = 'A';
            letter += (char)ts.Hours;
        }
        else if(ts.Hours >= -12 && ts.Hours <= -1) // N-Y
        {
            //Letters N-Y are based on hours backwards.
            letter = 'Z';
            letter += (char)ts.Hours;
        }
        else
        {
            throw new InvalidOperationException("Unknown UTC offset for timezone");
        }

        builder.Append(letter);
        builder.Append(dt.ToString("MMMyy", culture).ToLower());
        return builder.ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {

        var now = DateTime.Now;

        Console.WriteLine("Zulu   DTG {0}", now.ToZuluDtg());
        Console.WriteLine("Berlin DTG {0}", now.ToDtg(TimeZoneInfo.GetSystemTimeZones().Where(i => i.DisplayName.Contains("Berlin")).FirstOrDefault()));
        Console.WriteLine("Local  DTG {0}", now.ToDtg(TimeZoneInfo.Local));
        Console.ReadLine();
    }
}


Good job on your first program!

Before moving on to the review, a quick note on using namespace std

As long as you do it in a cpp file (and not a header), bringing in symbols from a namespace one at a time is absolutely fine, since you are in control:

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

Errors

main's return value

The main()'s return value is for program status, not program output. I suspect you meant to do:

cout << "the sum is: " << addTwoNumbers() << endl;
return 0;

Good practice improvements

Avoid globals

int x;
int sum = 0;
int i = 0;

These have no business being global variables, they belong inside of your functions, as close to their first use as possible:

for(int i=0; i<2;)
{
    int x;
    cin >> x;

istream::fail() vs operator bool()

Edit Disregard this recommendation. See the comment below.

instead of if(std::cin.fail()) you should simply do if(std::cin), it actually covers more scenarios as well.

istream::ignore()

Whenever you use an arbitrary number like 256, it's a sign that something is not how it should be. In this specific case, you want to do cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

From a higher level:

addTwoNumbers() does too many things

Try to keep your functions short, single-purpose and reusable.

As guidance, look at this version of your main().

int main() {
  cout << "Enter two integers" << endl;

  int first = getNumber();
  int second = getNumber();

  cout << "the sum is: " << (first + second) << endl;

  return 0;
}

getNumber() would now be be a usefull and reusable piece of code, which is what functions should be.


spyOn click events and check call function

From a once over:

I would drop this test, you are testing Jasmine and/or the test, but not the results of calling app.navigation.init()

it ('spy on behavior', function () {
    var spy = spyOn(app.navigation, 'init');
    app.navigation.init();
    expect(spy).toHaveBeenCalled();
});

Be aware that Function.bind() which you use in navigation.init() creates a brand new function, so this.routeHandler never calls this.hanldeRouteTo
Also be aware that you are not calling app.navigation.bind() as far as I can tell, so the binding of the event is not happening
Perhaps you are not a native English native speaker, but your describe calls are not up to snuff. It hampers my reading flow of the code. Example: 'initiation the navigation module'


Pretty printing degrees input to radians

Your code looks more complicated than necessary and some of your special cases are really not needed.

I will use an incremental development to avoid unnecessary code:

The first version is just based on the formula, with no additional prettiness:

function printRadians(angle) {
  return angle + "π" + "/" + 180;
}

document.write([45, 90, 180, 270, 360, -45, -18].map(printRadians).join('  '));

Then we want to simplify the fraction, using, as you did, the gcd function:

function gcd(a, b) {
  return (b == 0)?a:gcd(b, a%b);
}

function printRadians(angle) {
  var _gcd = gcd(angle, 180)
  return angle / _gcd + "π" + "/" + 180 / _gcd;
}

document.write([45, 90, 180, 270, 360, -45, -18].map(printRadians).join('  '));

We are getting nearer, now we should take care of removing unnecessary ones:

function gcd(a, b) {
  return (b == 0)?a:gcd(b, a%b);
}

function printRadians(angle) {
  var _gcd = gcd(angle, 180)
  var numerator = angle / _gcd == 1 ? "" : angle / _gcd;
  var denominator = 180 / _gcd == 1 ? "" : "/" + (180 / _gcd);
  return numerator + "π" + denominator;
}

document.write([45, 90, 180, 270, 360, -45, -18].map(printRadians).join('  '));

And now let's put the minus in front of the numerator, not denominator:

function gcd(a, b) {
  return (b == 0)?a:gcd(b, a%b);
}

function printRadians(angle) {
  var _gcd = gcd(angle, 180);
  var numerator = angle / _gcd == 1 ? "" : angle / _gcd;
  var denominator = 180 / _gcd == 1 ? "" : "/" + Math.abs(180 / _gcd);
  return ((angle < 0 ? "-" : "") + numerator) + "π" + denominator;
}

document.write([45, 90, 180, 270, 360, -45, -18].map(printRadians).join('  '));

And we are done, just \$4\$ lines, with no lengthy ifs for special cases.


The code is not bad;

Quite configurable
Helper functions

However,

There is quite a bit of copy paste code
Placing the style classes in self.A. makes for verbose code
The css classes themselves are lengthy as well
onBlur keeps making the font larger, but focus does not make the font smaller, which could cause comically large labels
applyEL -> applyEventListeners reads/parses better

This could be done instead:

/*****************************************************************************************
 **SDynInput - provides dynamic input for labels and borders
 */
var SDynInput = $A.Class.create({
    Name: 'SDynInput',
    // elements are passed in as input/label pairs
    set: function (inputLabelPairs) {
        var index;
        for (index = 0; index < inputLabelPairs.length; index += 2) {
            this.applyEventListeners(inputLabelPairs[index], inputLabelPairs[index + 1]);
        }
    },
    // apply event listeners to the input elements
    applyEventListeners: function (input, label) {
        var self = this,
            labelSpeed = 200,
            // CSS classes used to toggle the label
            hideLabel = 'toggle_label_hide',
            obscureLabel = 'toggle_label_obscure',
            showLabel = 'toggle_label_show',
            // CSS classes used to toggle the input border
            hideBorder = 'toggle_border_hide',
            obscureBorder = 'toggle_border_obscure',
            showBorder = 'toggle_border_show',
            applyClasses = function (inputClass, labelClass) {
                $A.addClass(input, inputClass);
                $A.addClass(label, labelClass);
            },
            applyHidingClasses = function () {
                applyClasses(hideBorder, hideLabel);
            };
        input.addEventListener("blur", function () {
            if (input.value === '') {
                applyClasses(borderShow, labelShow);
                $A.expandFont(label, 'up', labelSpeed);
            }
        }, false);
        input.addEventListener("focus", function () {
            if (input.value === '') {
                applyClasses(borderObscure, labelObscure);
            }
        }, false);
        input.addEventListener("paste", applyHidingClasses false);
        input.addEventListener("keypress", applyHidingClasses, false);
        input.addEventListener("drop", function () {
            $A.setTimeout(applyHidingClasses, 0);
        }, false);
    }
}, true);


Convert a custom object to a query string

I wouldn't go the StringBuilder route, simply because you need to handle the "what if I'm at the start/end" problem. Instead, simply collect the "URL_translated" key-value pairs into an IEnumerable<string> and then apply string.join().

If you're working in .NET Core, Microsoft does all the lifting for you. Here's how they do it.


A PHP Controller, which feels to 'array-like', in Laravel

You could use route model binding to remove some lines from your code, but that would require changing the route so it passes the MenuItem's id.

public function update(UpdateMenuItemRequest $request)
public function update(MenuItem $item, UpdateMenuItemRequest $request)
{
    $validated = $request->validated();

    $item = MenuItem::findOrFail($validated['id']);

    foreach($validated['translations'] as $validatedTranslation) {
        $item->translations()->updateOrCreate(['locale' => $validatedTranslation['locale']], $validatedTranslation);
    }

    return $item;
}

Also, if you want legibility and go all out with functional programming, you could replace your loop with a collection method.

# Assuming the request object only has a translation array since you don't need the id anymore
public function update(MenuItem $item, UpdateMenuItemRequest $request)
{
    collect($request->validated()['translations'])->each(function ($translation) use ($item) {
        $item->translations()->updateOrCreate($translation);
    });
}

Depending on what kind of relationship we're dealing with there could be other ways as well.


But what differences would there be if I had the above classes as
  nested classes in the Wrapper.java class? Or is creating them
  separately and then putting them in a package more preferable?

It depends on your information hiding principles.
In general, it's good to hide as much information as possible.
The fewer classes you expose,
the fewer classes you have to support,
and therefore the more freedom you have to make changes later.

So, if these classes don't need be visible by users of your library,
then they can be nested inside Wrapper.
Wrapper too, looks like something that shouldn't be exposed.

On the other hand: (from Effective Java by Joshua Bloch)

  A nested class should exist only to serve its enclosing class. If a nested class would be useful in some other context, then it should be a top-level class.

  What are the differences in terms of speed, efficiency, design, or
  anything else anyone could advise on?

Speed, nothing. Efficiency, nothing.
The difference is in API design.
Everything that's public is a liability for you.
Once other developers start using it,
you'll have to pay attention to the changes you make,
in case you might break compatibility.


Authorization - Create and unlock a User

Some quick remarks:

Don't name things "class", e.g. HelperClass.
Don't use Hungarian notation and give your variables meaningful names: u_gvid is a complete mystery to me.
I don't get why CheckIfUserExists and CheckIfUnblocked are public, and even less why they'd use RedirectToAction. I expect these methods to return a boolean, not to execute redirects etc.
NpgsqlConnection and NpgsqlCommand don't follow the Microsoft naming guidelines: they are compound words, so the "s" in "sql" should be capitalized.
Don't write ADO.NET code. You're using 15+ lines to write something that could be expressed much simpler by using Dapper. The var result = cmd.ExecuteScalar().ToString().ToLower(); and if (result == "false") bit is even worse. You don't provide us with the relevant SQL, so perhaps there is a good reason to return a boolean-like string, but I wouldn't be surprised if the query logic could be much simplified.
CheckIfUserExists and CheckIfUnblocked are IMHO bad method names. To me they should be something like DoesUserExist and IsUserUnblocked, which are the kind of methods I'd expect to return a boolean.
CheckIfUserExists should not execute CreateUser, unless you rename the method. And I wouldn't expect a method called CreateUser to return a boolean. Avoid this temptation by moving these methods to a service etc. instead of them being part of the controller. Keep your controllers as light as possible, things like data processing etc. should be handled by dedicated classes.
In CheckIfUnblocked you have a boolean: var result = (bool)cmd.ExecuteScalar();. Why then not simply return this instead of doing the whole if (result) return true; / else return false; dance? You spend six lines on something that could be expressed by a single one.


I’m afraid your approach to matching multiple characters looks fundamentally misguided to me. Consider cases like:

abcbcd    ab*cd

One approach that works is a recursive matcher, i.e. when encountering *, try wildcard(value+1, wcard) and if that fails, wildcard(value, wcard+1). This will give you the standard semantics of an * matching as much as possible. For a minimal match, reverse the order of the two recursive calls. This is very easy to implement (much easier than your approach, in fact), but tends to need a lot of stack space for large strings.

The alternative is to build an explicit backtracking stack, which is considerably harder to get right, but uses less memory, and usually uses it on the heap rather than the stack.