Go function to generate permutations of a given integer array

To make it nicer for your reviewers you could post as a complete and
runnable example:

package main

import "fmt"

...

func main() {
    input := []int{1, 2, 3}
    output := permute(input)
    fmt.Printf("Input: %v\nOutput:\n", input)
    for _, x := range output {
        fmt.Printf("  %v\n", x)
    }
}

With that out of the way, I'd simplify permute a bit:

func permute(nums []int) [][]int {
    return backtrack(nums, []int{}, make([]bool, len(nums)), [][]int{})
}

In backtrack I'd consider returning early for the first case, that
lets you remove one level of indentation for the rest:

func backtrack(nums []int, tmp []int, invalid_pos []bool, res [][]int) [][]int {
    if len(tmp) == len(nums) {
        tmp2 := make([]int, len(tmp))
        copy(tmp2, tmp)
        return append(res, tmp2)
    }
    ...
}

Regarding your question:  Well, what happens if you remove the copy
call?

0 go % go run perm.go
Input: [1 2 3]
Output:
  [0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]

Clearly it does something and you cannot remove it just like that.  It
also has nothing to do with capturing iteration variables, the only ones
you have here are i and num - both aren't even part of the copy
call, plus, you're not capturing anything, there's no func() {...}
declaration anywhere that even could capture variables.

Variable capturing and the (most common?) problem with it comes only if you have a construction like this:

for i := ... {
    x := func() {
        foo(i)
    }
}

The i in the anonymous function is the one from the loop - and since it's always the same variable, all the created functions reference ... the same variable!  That can be confusing since people might expect that on each iteration of the loop we're capturing that one value that i currently has.  Go could've done that, but I'm guessing mostly for performance reasons that's not being done and you've to explicitly make it happen yourself:

for i := ... {
    j := i
    x := func() {
        foo(j)
    }
}

Now foo gets called with all the different values of i.

Okay so that's that, now I'd just recommend simplifying this algorithm
to get rid of invalid_pos, tmp and the res parameter and do it all
functionally and recursively.  I'm saying that because the code right
now is pretty complex for the problem and yet it doesn't do everything
upfront that it could, like preallocating the res array to the final
length, so it seems this is more of a learning exercise.

Start with the base cases, empty list and one element, then consider the
one element longer list:

func permute2(nums []int) [][]int {
    if len(nums) <= 1 {
        return [][]int{nums}
    }
    result := [][]int{}
    for i, x := range nums {
        ...
    }
    return result
}

Don't optimise to early for reusing things, that can also follow once
the algorithm is in its most simple form; clarity comes first.

Hint:  You can do it without copy or manually instantiating any
more slices via []int{}, just check out
append and how to do
subslices.  Take particular care to not simply append slices together without considering how the underlying data is going to be shared (that's why append([]int{}, <slice here>) might be necessary to prevent the slice from being modified).

As a spoiler:

   func permute2(nums []int) [][]int {
     if len(nums) <= 1 {
         return [][]int{nums}
     }
     result := [][]int{}
     for i, x := range nums {
         without := append(append([]int{}, nums[:i]...), nums[i+1:]...)
         for _, y := range permute2(without) {
             result = append(result, append([]int{x}, y...))
         }
     }
     return result
 }


I would say you're not using AES correctly - don't hold on to an instance of it in your class (guessing by the underscore in the name) but rather create it as needed, while holding AES's parameters (the key and IV) in your class:

using (var aes = new AesManaged() { IV = _IV, Key = _Key })
using (var decryptor = aes.CreateDecryptor())
using (var encryptedStream = new MemoryStream(encryptedTextBlob))
using (var decrypedStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read))
using (var textReader = new StreamReader(decrypedStream))
{
    return textReader.ReadToEnd();
}


The locking looks fine, but there are a couple of things which look fishy in the code.

Firstly,

            if (index < 0)
                index = -index;

This should surely be present in both methods or in neither? But it's only in the second one.

Secondly,

            int offset = (i - 1) * filterParams.bucketLength;

It seems that each derived hash is stored in a non-overlapping bucket. By my understanding of Bloom filters, what you have here isn't a Bloom filter.

Finally, I suggest for your consideration unrolling the multiplications:

        long hash = hash1;
        for (int i = 1, offset = 0; i <= filterParams.k; i++) {
            hash += hash2;

            int mod = ( int ) ( hash % filterParams.bucketLength );
            int index = offset + mod;

            bitSet.set(index);

            offset += filterParams.bucketLength;
        }

This saves a bit of thought as to "why does it multiply by i to calculate hash but by i-1 to calculate offset?".


Raising an error if a variable is not created during class initalization

You got the arrow anti-pattern:

    try:
        with open(self.filepath, 'rU') as c:
            rows = csv.reader(c)
            for row in rows:
                row[:] = [r.lower().strip() for r in row]

                if row[0].startswith('name'):
                    self._header = row     # Create Header Variable

                self._data.append(row)

    except IOError:
        raise IOError(
            '"{}" not found in "{}"'.format(self.filename, self.localdir))

4 levels of nesting..., instead, perform exception handling before:

try:
    with open(self.filepath, 'rU') as c:
        rows = csv.reader(c)
except IOError:
    raise IOError(
       '"{}" not found in "{}"'.format(self.filename, self.localdir))

Data processing comes later, so now you have 2 levels of nesting before and 2 levels of nesting after, that is much better than 4 levels of nesting in one place.


Repository pattern with plain old PHP object

You are already using the repository of Kohana. They hide their repository behind static factory methods though (copied from the documentation):

// Find user with ID 20
$user = ORM::factory('User')
    ->where('id', '=', 20)
    ->find();
// Or
$user = ORM::factory('User', 20);

Yet they fail to achieve the important thing about ORM and repositories: decoupling the application from the database. This is actually two-fold: the SQL-syntax leaks into the application space (the querybuilder) and the database-structure is mapped 1:1 on the model. Changing the model or database requires to change the other respectively. Comparing this to the great explanation at MSDN: the mapper is missing and the client business logic has access to the query object (and therefore to the datasource). A major (not related) issue is the all-presence of static method calls.

What you try is to fix this (thumbs up ;)). You have your business entities (MemberModel and ContactModel) and a repository MemberRepository. But instead of delegating the the ORMs repository you should use the query builder directly:

class MemberRepository implements MemberRepositoryInterface {
    public function find($id)
    {
        $record =  DB::select(...);
    }
}

The second important task is the mapping of database fields to entity fields (and vice versa). This should not be done in your business entity! The business entity does not know anything about how it is saved:

class MemberRepository implements MemberRepositoryInterface {
    public function find($id)
    {
        $record =  DB::select(...);
        // map $record to $entity;
        return $entity;
    }
}

Other means to manage your model in the repository as well (e.g. delete, update, create), not in your business entity!

Last your model. For now it is fine. But soon it should contain your business logic (no, not in your services or controllers ;)). You'll probably start with some data validation when setting properties. I'd suggest to use setters/getters right away, saves you refactoring later on.

Two final remarks about ORM at the end:

Repositories tend to be very repetitive. Especially when they only provide only the basic CRUD methods. Pretty much every ORM Framework provides a general repository for these methods (as Kohana does and what you used).
Some explanations on ORM pass query objects to the repository. Those are not to be confused with the query builder from your dbal. The query passed to the repository is written in the business language (e.g. the fields of your model) and mapped to a query of the querybuilder by the repository. This avoids leaking of database details into the business logic.


You can add both classes at once with attr, since all you need to do is pass a string with the classes you want separated by spaces:

$('DIV.content DIV.nav ul li.home').click(function(){
    $('DIV.content DIV.nav').attr('class', 'nav home');
});


Searching a Word Document from Excel - v2.0

Answers

Question 1: No, this is now Hungarian-free™. The article that was referred to in your prior post differentiated between "Apps Hungarian" and "Systems Hungarian", and your previous code was using the latter (i.e. strName). You were basically indicating that yourFunction SearchWordDoc(strPath, strName)was expecting String's as parameters. The current code is both more explicit and will in fact not even compile if you try to pass it anything but a String. This is a Good Thing™.

Question 2: This one is harder to answer without some information about the layout of the spreadsheet. From the code, I would gather that row 1 consists of column headings that correspond to your Word document names and that column "C" is the last names that you are looking up. If this is the case, your first loop (the "c" loop) counter is off - instead of starting at 1, it should start at the first column that is expected to have a value. I'm not sure exactly what the inner-most loop (the "k" loop) is doing - it seems to rely on the Word document being in the same sort order as the rows in the spreadsheet.  The Dictionary key is an integer, and you're using the row as the key when you index it instead of the last name. Take a another look at my answer to your last post, you should be parsing a name out of the Word file for the Dictionary keys.

Other Observations

Finding Worksheet Size: The following code will likely return inconsistent results in many cases (at least it does for me):

'Finds last row and column with valid data
With ActiveSheet
    lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
    lastColumn = ActiveSheet.Cells(ONE, Columns.Count).End(xlToLeft).Column
End With

Excel's Worksheet object has a property that is much easier to use and much more reliable and readable in your code:

With sheet.UsedRange
    lastColumn = .Columns.Count
    lastRow = .Rows.Count
End With

Using ActiveSheet: Don't do it. After you get your reference to sheet at the start of Sub LoadWordFromExcel(), don't use ActiveSheet again. If you need a reference in another function, pass it as an argument. Within the same function, always use your captured reference. To expand on my answer to your previous question, every time you call ActiveSheet, you get a reference to whatever Worksheet Excel has active.  If you are half way through your routine and the user opens another workbook, your reference can change.  This can (and will) result in read garbage cells and writing into the wrong spreadsheet.

Global Variables (other than constants): Avoid them in any way that you can, as they can lead to unexpected and hard to locate bugs. Variables should always have the minimum required scope.  In your case, you are using lineCount to track how many items you add to the Dictionary object you return, but there isn't a reason to do this.  You can just get a count directly from the object:

'instead of 1 To lineCount ...
For k = 1 To entries.Count
    ...
Next

Constants: Definately well intentioned, but there are a couple of things to mention here.  First, these should typically be placed in your module's header (after the missing Option Explicit). The primary reason to do so is so that they get a wider scope. Remember, the goal of having a constant is not just to have an easily identifiable name - it make changes a lot easier. For example, if your layout changes, you can change Const LAST_NAME As Integer = 3 to whatever value you need exactly once instead of searching all over for the number 3 and trying to figure out if it is being used as a column index. That said, Const ONE As Integer = 1 is never going to change. Use 1 instead. The other goal, easily identifiable names, is the other place I would make a couple minor changes to make them more explicit and readable.  I'd likely do something like this:

Option Explicit

Private Const FIRST_DATA_ROW As Integer = 2
Private Const WORD_DOCUMENT_PATH As String = "C:\Users\<user>\Desktop\Macro folder\"
Private Const LAST_NAME_COL As Integer = 3
Private Const PARSE_START_INDEX As Integer = 21
Private Const PARSE_LENGTH As Integer = 11

Variable Names: While you can occasionally use one letter loop counters like i when it is obvious that you are indexing something, in this case it would be better to be more descriptive in what you are looping through and how you are using the loop counters to index.  This is much more important in nested loops than in a simple array traversal.  I'd suggest something more like this:

Dim row As Integer
Dim key As Integer
Dim col As Integer

For col = 1 To lastColumn
    ...
    For row = FIRST_DATA_ROW To lastRow
        For key = 1 To entries.Count
            ...
        Next key
    Next row
Next col

I'm also a fan of the Next [Variable] syntax for readability, especially with nested loops.

Odds and Ends: The following If test will never return False:

file = Dir$(PATH_TO_FOLDER & sheet.Cells(ONE, c).Value & ".docx")
If (Len(file) > 0) Then

The length of the file variable will always be at least 5 + Len(PATH_TO_FOLDER) - it can never be zero. You should also make a habit of using Trim$() before you test a string length (unless you care about white-space).

Also, if you are going to return a the value of Left() or Right() into a String, use the string specific functions Left$() and Right$() to prevent casting back and forth from a Variant. Better than Left$(Right$(var, start), length) would be to use the Mid$() function.

This test is wildly inefficient:

If InStr(entries(k), sheet.Cells(r, LAST_NAME).Value) <> 0 Then

It takes the returned Item from the Dictionary and then uses a string comparision to see if it matches the cell contents. The Dictionary object has a method to determine if a given key exists - .Exists(). Restructuring this one If statement can likely eliminate the inner-most loop entirely (assuming you key by name).

Dim key As String
...
key = Trim$(sheet.Cells(row, LAST_NAME).Value)
If entries.Exists(key) Then
    sheet.Cells(row, col).Value = Mid$(entries(key), PARSE_START_INDEX, PARSE_LENGTH)
Else
    sheet.Cells(row, col).Value = vbNullString
End If

Finally (and this is more of a pet-peeve of mine), use the built-in constants when they exist to improve readability. "" is much harder to comprehend at a glance than vbNullString in much the same way that vbCr is easier to read than Chr$(13).


CommandBinding refresh on parameter changed

I'm having to break MVVM by having the view tell the VM command that its execution has changed because the command binding doesn't seem to refresh on the parameter changing.

The fundamental problem here seems to be that MenuItem tests whether (in effect) Command.CanExecute(CommandParameter) to update its own Enabled property when Command changes, but not when CommandParameter changes.

It seems to me that the least inelegant way of working around this (IMO) bug in WPF is to subclass MenuItem and use DependencyProperty.OverrideMetadata to register a callback on CommandParameterProperty which updates an overridden IsEnabledCore property. To really do it properly you'd want to also override metadata for CommandTargetProperty and handle RoutedCommand specially, as in CommandHelpers.CanExecuteCommandSource.

An alternative approach, which would be hackier and require more XAML but wouldn't get quite so deep into the inner workings of WPF, would be an IMultiValueConverter which takes two parameters (the command and the parameter) and returns a parameterless command. Then you could set up multibindings such that a change in the parameter causes the MenuItem's Command to change, triggering its CanExecute test.

Both of these approaches would require changes in the XAML of all the grids, but no per-grid codebehind. They would also eliminate the assumption, which IMO is one of the nastiest problems of the codebehind in the question, that all commands are instances of DelegateCommand<object>.

(The other nasty problem is that if the while loop is broken because current == null, the body of the second loop will throw a NullReferenceException).


One of the ways to structure your objects is to describe your problem in a sentence or two, then turn the nouns into classes, and the verb phrases into methods.

In this case, you may end up with Hangman (the game), Player, and not really much else. You can choose to put the user interaction in Hangman or you can create a separate class for it, as you did with GamePlay.

There are a couple of things to keep in mind:

Make sure the interface makes sense. For example Hangman.new; GamePlay.new to start a game is a bit awkward. Whenever the interface is awkward it usually means there's a problem with the design. In this case, you have to manage two classes independently and you may have noticed that there's not much more you can do with your Hangman class as it is without managing it with logic external to either class.
Apply the right behavior to the right object. Assuming Hangman represents the game, then it should do all the game stuff: new (begin), save, load, guess, show_word, etc. Then GamePlay would just be user interaction, calling the Hangman game's methods as needed.

So let's think about the interface a bit: instead of

Hangman.new
Gameplay.new

perhaps you want something more like GamePlay.begin, or if you want to specify what game it is, maybe Hangman::GamePlay.begin which means you'd put the classes in an organizing module.

This exercise structures everything around a mental model. Then it's up to you to keep the model clean. Every time you need to add functionality, ask yourself: should this go into Hangman or GamePlay? Make sure that you have the separation of concerns clear.

In your case you have user prompts in two classes which is not a clean separation of concerns and may cause problems (e.g. GamePlay doesn't know the player's name).

Hopefully this makes sense. It tackles just the organizing step, let me know if you want assistance refactoring to a different model.


It seems that you are looping through seeds to find the one that causes a randomized procedure's output to match the output from a previous run.

If you had set the random seed immediately before running the randomized procedure and have simply forgotten the seed you used, then this in theory would work; all you need to do is loop through the billion or so possible input seeds until one matches. There's no real way to speed up the process (beyond parallelizing, which would be easy because the problem is embarrassingly parallel). apply is just a wrapper on a loop, so that would not speed up the process.

Unfortunately, more likely than not you did not set the random seed immediately before running the code. Therefore you would really need to test all the internal states of the pseudorandom number generator (PRNG) that you used to find the one that matches the results. Unfortunately there are intractably many internal states; for instance, the most popular implementation of the Mersenne Twister, which you are likely using, has a period of 2^19937 - 1, meaning it has at least that many possible internal states. Clearly it's impractical to test this many states, so it's probably hopeless to try to match an exact PRNG state if you hadn't set the seed immediately prior to running your randomized procedure.


Find the second largest number in an array with at most n + log2 n - 2 comparisons

Algorithm and implementation

The algorithm is correct. Essentially it compares the elements pairwise, recursively until all pairs are eliminated, while at each comparison, tracking the compared elements in a list. At the end, the algorithm finds the maximum value, and a list of \$\log_2(n)-1\$ elements, which must contain the 2nd maximum value.

The implementation looks more complicated than it needs to be, and I find it hard to read. I suggest to organize and implement differently:

Create a function find_max_with_tracking that takes a list of values and returns a tuple of the maximum value and the list of values the maximum was compared to:

Map the input list of values to a list of tuples: [(x, []) for x in input]
Recursively reduce the list of tuples, comparing then pairwise, keeping the tuple with the higher value, and adding to its list the value of the other tuple. This could be implemented either with a recursive function, or with a loop.
Return the single tuple that remains, containing the maximum element, and a list of \$\log_2(n)-1\$ values that must contain the second largest value.

This point is reached by n - 1 comparisons, and we have \$\log_2(n)\$ values to scan to find the second largest value. You can use a simple linear scan for this step.

This implementation should be simpler and easier to read.

Programming in general

Avoid global variables as much as possible. If you need to track something, such as the count in this example, then you can wrap the operation in an abstract data type that manages the state and operations (functions) on the state.

Excessive array creation in a loop or recursive function as in get_second is usually a bad sign, to investigate closely and try to eliminate. In this example this was an important hint that the implementation is probably inefficient.

Programming in Python

The implementation uses Python 2 features that are obsolete today, such as print without parentheses (the old keyword instead of the modern function) and xrange instead of range. I suggest to test your scripts using Python 3.


The posted code does the following:

Read all lines, just for counting
Create an array with the right size
Read all lines again, this time for storing
Print all lines in reverse order

It's wasteful to read a file completely just to find the number of lines, and then need to read the file again to store the content.
It would be better to store the lines in a data structure that can grow its capacity as needed, to eliminate the need to know the number of lines in advance. That is, use any List implementation.

Possible bug

The description doesn't mention that there is precisely one integer per line in the input.
It must be the case, otherwise this code may not work well:

for(int i=0; i<buffer.length; i++) {
    buffer[i] = Scan.nextInt();
}

That is, if there are multiple numbers per line, then you will not read the entire file,
only the first \$N\$ numbers.
Similarly, if there are empty lines, then there may not be enough numbers,
and then the .nextInt call will throw a NoSuchElementException.

The thing is, since there program doesn't use any integer operation,
only read and print,
there's no point reading integers.
Keep in mind that when you read integers,
you also incur a parsing step.
It would make more sense to read the lines as strings,
it would be simpler, and it seems that's all you really need anyway.

Suggested implementation

Here's an alternative, more efficient solution,
that also simplifies the reversing logic using a LinkedList, with a descendingIterator:

LinkedList<String> lines = new LinkedList<>();
while (scanner.hasNextLine()) {
    lines.add(scanner.nextLine());
}
scanner.close();

Iterator<String> iterator = lines.descendingIterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}


Yield statement in a using block from a clarity point of view

public IEnumerable<string> GetUsers()
{
    using (SqlDataAdapter adapter = new SqlDataAdapter())
    {
        DataSet ds = new DataSet();
        string sql = @"SELECT lead  FROM teams";

        using (var sqlCnn = new SqlConnection(connetionString))
        {
            sqlCnn.Open();

            using (var sqlCmd = new SqlCommand(sql, sqlCnn))
            {
                adapter.SelectCommand = sqlCmd;
                adapter.Fill(ds);

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var login = row[0].ToString();
                    yield return login;
                }
            }
        }
    }
}

Usually you shouldn't worry about having a yield return inside a using block but this isn't needed here at all. This is because the DataSet is disconnected from the database. The only thing you would buy would be that for an exception the SqlDataAdapter, SqlConnection and SqlCommand will be properly disposed if for instance the row[0] contains DBNull.

I would extract the foreach loop over the Rows out of the using blocks which I would also use different. The most outer one should enclose the SqlConnection followed by the SqlCommand and the last should be the SqlDataAdapter.

By stacking the using blocks you reduce the horizontal spacing which makes it easier to read.

Because you are only interested in one DataTable you should use the overloaded adapter.Fill(DataTable) method.

Next to mention is that you should declare your variables as near to their usage as possible.

Applying this points will lead to

public IEnumerable<string> GetUsers()
{
    DataTable dataTable = new DataTable();
    string sql = "SELECT lead FROM teams";

    using (var sqlCnn = new SqlConnection(connetionString))
    using (var sqlCmd = new SqlCommand(sql, sqlCnn))
    using (SqlDataAdapter adapter = new SqlDataAdapter())
    {

        sqlCnn.Open();

        adapter.SelectCommand = sqlCmd;
        adapter.Fill(dataTable);

    }

    using (dataTable)
    {
        foreach (DataRow row in dataTable.Rows)
        {
            var login = row[0].ToString();
            yield return login;
        }
    }
}

Edit based on @t3chb0t comment

  The data table is being created before the sql connection, if something goes wrong there, using(dataTable) will not be executed

nevertheless I am not sure it is needed.

public IEnumerable<string> GetUsers()
{

    string sql = "SELECT lead FROM teams";

    using (var sqlCnn = new SqlConnection(connetionString))
    using (var sqlCmd = new SqlCommand(sql, sqlCnn))
    using (SqlDataAdapter adapter = new SqlDataAdapter())
    using (DataTable dataTable = new DataTable())
    {

        sqlCnn.Open();

        adapter.SelectCommand = sqlCmd;
        adapter.Fill(dataTable);

        sqlCnn.Close();

        foreach (DataRow row in dataTable.Rows)
        {
            var login = row[0].ToString();
            yield return login;
        }
    }
}


Well, Regex is going to be slow, by virtue of it being a very powerful, flexible engine that can't assume you'll never want to do something that a regex can achieve. This particular regex pattern is pretty simple (no lookbehinds, etc) but there will be some overhead inherent in Regex use which you can trim. You can iterate through the string and count occurrences of groups of vowels in linear time with very little overhead.

private static int SyllableCount(string word)
{
    word = word.ToLower().Trim();
    bool lastWasVowel;
    var vowels = new []{'a','e','i','o','u','y'};
    int count;

    //a string is an IEnumerable<char>; convenient.
    foreach(var c in word)
    {
       if(vowels.Contains(c))
       {
          if(!lastWasVowel)
             count++;
          lastWasVowel = true;
       }
       else
          lastWasVowel = false;
    }

    if ((word.EndsWith("e") || (word.EndsWith("es") || word.EndsWith("ed")))
          && !word.EndsWith("le"))
        count--;

    return count;
}

I'd A/B the above algorithm against the one you already have; you should see at least some performance increase. Notice that although this may well be faster as it does exactly what you want and doesn't see if you want to do anything else, it uses more LOC to achieve the same result. This is Regex's real power; powerful string analysis with very concise code.


First of all, I would architecture the data in a more readable and flexible way:

[
  {
    infinitive: "be",
    past: "was",
    participle: "been",
    russian: "быть"
  },
 {
   ...
 },
...
]

That tells me as reader a lot and leaves vast room for future changes without breaking the rest of your code.

Further, if you want to make your code readable for others (or even for yourself after a while), I would recommend to use descriptive names for your functions and variables. When I read

<tr ng-show="isStage('input')">

I get no clue what the function isStage does from its name.
So I am forced to scan the rest of your code for its definition, which costs time. You could help me by giving it a name that would give me a rough idea without the need to go elsewhere.

Another thing I see is the use of $http inside controller, which is an anti-pattern. It sadly appears in many tutorials, yet it breaks one of the most fundamental principles of clean code - the single responsiblity principle. Your controller is responsible for gluing your scope (ViewModel layer) with your View, but not for pulling data from your Model layer. That is the job of a dedicated Service.


Consider working with SPL's fileinfo and iterator classes  (i.e. SplFileInfo, DirectoryIterator and FilterIterator, CallbackFilterIterator, etc) to build something a little more resilient.

Example:

// your filter logic
$imageFilter = function (SplFileInfo $splFileInfo) {
    return preg_match(
        '/^screenshot[0-9]{1,3}\.png$/',
        $splFileInfo->getFilename()
    ) ? true : false;
}

// get files in directory based on filter function
try {
    $directoryIterator = new DirectoryIterator($directoryPath);
    $filteredImageIterator = new CallbackFilterIterator(
         $directoryIterator,
         $imageFilter
    );
} catch (Exception $e) {
     // do something here, or don't wrap in try-catch at all if you want to bubble up exception.
}

foreach($filteredImageIterator as $image) { /* your code */ }

Note that you can build upon the filter shown here by adding things like verifying file is readable/writable, get file modification timestamps, or other such functionality exposed by SplFileInfo, which could include ability to easily create SplFileObject for working with file contents.


Monoalphatic and Polialphabetic cipher in Ruby

Extract constant expression to outside of loop

In this code, (decode ? 26 - key : key) is evaluated for each character in text:

  text
      .chars
      .select { |char| ALPHABET.include?(char) }
      .map {|char| shift(char, (decode ? 26 - key : key) )}
      .join

It would be better to move it outside the expression so that it's only evaluated once:

  shift_key = decode ? 26 - key : key

  text
      .chars
      .select { |char| ALPHABET.include?(char) }
      .map {|char| shift(char, shift_key)}
      .join

Minor formatting issues

The code formatting style is not consistent, for example compare these two lines:

      .select { |char| ALPHABET.include?(char) }
      .map {|char| shift(char, shift_key)}

In the first one, there's a space after { and before },
but in the second there isn't.
Both ways seem fine to me,
but it would be better to use one of these ways, consistently everywhere.

Similarly here,
there's a space after [ but not before ].
For the sake of consistency,
it would be better to remove the space after [ or add one before ].

  ALPHABET[ (ALPHABET.index(letter) + key) % ALPHABET.length]

Overall

This looks nice, a pleasure to read, and I don't even know Ruby ;-)


General

Your model should not return an ObservableCollection because that collection should be used only if its change notification ability is needed (e.g. with data binding). The method GetDocuments should return an Array or an IEnumerable.
The method InitializeColumns also seems to be GUI related. Consider moving it to the view model.

Background Processing

If you have to load documents in the background, I would suggest using BackgroundWorker (for .Net Framework 3.5 and below). But you should use it more like:

Pass the model to the RunWorkerAsyncmethod and use the Argument property to access it.
Do not access view model properties from within the DoWork delegate because that is the code that will be executed in the background. Assign the calculated result to the Result property instead.
Use the RunWorkCompleted method to process the calculated result on the GUI thread.

e.g:

var bw = new BackgroundWorker();
bw.DoWork += (o, e) => e.Result = (e.Argument as Model).GetDocuments();
bw.RunWorkerCompleted += (s, e) => ShippingDocuments = new ObservableCollection((ShippingDocument[])e.Result);
bw.RunWorkerAsync(model);


Embrace lambda expressions!
Your Operations is a lot more complicated that it needs to be. First of all, I would rename it Operation instead of Operations: the class does not represent multiple operations but a single one.
An Operation has 2 members: the symbol and the concrete operation it is performing. As such, consider adding 2 fields to your class symbol and operation. They will be initialized using a custom constructor. For the operation, all of them will be taking as input 2 double values, and returning a double that is the result of the calculation. This can be represented with the DoubleBinaryOperator class. Consider this:
enum Operation {

    ADD("+", (d1, d2) -> d1 + d2), // or Double::sum
    SUB("-", (d1, d2) -> d1 - d2),
    MUL("*", (d1, d2) -> d1 * d2),
    DIV("/", (d1, d2) -> d1 / d2);

    private final String symbol;
    private final DoubleBinaryOperator operator;

    private Operation(String symbol, DoubleBinaryOperator operator) {
        this.symbol = symbol;
        this.operator = operator;
    }

    public double getResult(double d1, double d2) {
        return operator.applyAsDouble(d1, d2);
    }

    public String getSymbol() {
        return symbol;
    }

}

The great advantage is that the code is now a lot shorter, and more readable. Instances of the concrete operations are created using a lambda expression.
Prefer primitives when possible
Your code is working on Double objects. In fact, you could just work with the primitive type double: simpler, no auto-boxing that may impact performance is performed. You should avoid to create unnecessary objects when possible.
Careful with Optional.get()
To retrieve the operation from its symbol, the code is looping over all the possible operations, filtering the one having the correct symbol and returning it. However, if there are no operations with this symbol, it will fail with a NoSuchElementException from Optional#get().
The issue is that it is "hidden" in the code. When reading it, you can easily not spot this fact. Instead of relying on this behaviour, you should express in your code what you want to happen when no operations were found. You could default to another operation with orElse, but most likely you will want to fail with an exception. And for that you can use orElseThrow. The advantage is that it documents clearly in the code what is expected to happen when no operations are found.
Operation correctOp =
    Arrays.stream(Operation.values())
          .filter(op -> op.getSymbol().equals(operator))
          .findFirst()
          .orElseThrow(() -> new IllegalArgumentException("No operation found for operator " + operator));

The end result is the same: an exception will be thrown. But in this example, the reader and the maintainer of the code clearly sees that this case was thought of. Also, it provides a more meaningful exception message for the user.
Note that I replaced the creation of the Stream with Arrays.stream(array): there is no need to first convert to a list to create a Stream, you can do it directly on an array.
Clear parameters to functions
The method calculateAnswer currently takes as parameter a List<Double> inputs for the inputs by the user. Why? This is awkward: it would imply the function could be called with an empty list, or a list with 1 element... and the code will fail trying to access an out of bounds index since it expects at least 2 elements in the list.
In fact, the method only takes 2 inputs, so instead of wrapping them in a list, pass them as 2 parameters:
double calculateAnswer(double firstInput, double secondInput, String operator)

This also means you need to refactor a bit the main code: don't use a List<Double> but store each number given by the user in 2 separate local variables.
Boolean arithmetic
Don't do
runAgain = scanner.next().equals("Y")?true : false;

It is both clearer and shorter to just have
runAgain = scanner.next().equals("Y");


First of all, it's considered better practice to implement isCorrectAmount as follows:

private boolean isCorrectAmt(int amt){
    return amt%10 == 0;
}

Next, if you want to update the value of an existing key in a Map, it's not necessary to remove the mapping for the key and then reinsert it. You can just call put, and if the map already contains a mapping for the key it will simply update the key's value. So with that in mind, I would suggest changing the body of reduceBalance as follows:

private synchronized void reduceBalance(int denomination, int noToReduce){
    int amt = notes.get(denomination);
    notes.put(denomination, amt-noToReduce);
}

The next thing I thought about questioning was your choice of a TreeSet for maintaining an order collection of denominations. Normally you should collect items in a List if you are interested in keeping them in order, and use a Set if you want to stop your collection from containing duplicates. TreeSet just happens to be a collection implementation that offers both features. Overall however I think using TreeSet here allows you to achieve your goal in as little code as possible, so in the end this is fine by me.

By using a TreeSet, one thing you could do is use the advanced methods on its API to fast-forward through the denominations that are greater than your amount. This is probably not really worth doing as the gains are minimal, and I must stress that I haven't tested this out, but you could conceivably do this:

//get sorted denominations
TreeSet<Integer> denominations = new TreeSet<Integer>(notes.keySet());
Integer start = denominations.floor(amt);
denominations = denominations.headSet(start, true);
Iterator<Integer> iter = denominations.descendingIterator();

Your main issues in terms of the functional correctness of your code are:

withdrawAmt needs to perform more validation on its input. As well as checking that the input is a multiple of 10, it needs to check that it is non-negative and also less than or equal to the total amount in the machine.
Your while loop in withdrawAmt needs to account for the situation where there are not enough notes in the machine to pay out the requested amount. What if somebody wants to withdraw $30 but there are only 2 $10 notes left? Think about what your code currently does in this situation.

Finally, by making the main entry point into the ATMMachine class synchronized (as well as most of the other methods), concurrent requests to withdraw money will pretty much proceed in series, one after the other. In all fairness this may have to be the case. One of the first things that the machine needs to check is that it has enough cash to service the current user, and it can't establish this for sure if there's another user currently in the middle of a withdrawal.

Nevertheless, given that your focus is on Java's collections, it may be worth looking at the concurrent collection classes and seeing if making notes a ConcurrentHashMap might allow you to perform some actions in parallel. I'll have a look myself and update this answer if I can propose some code that would result in less blocking.


Create a view vw_HousesAccess  which will contain following query and then

        Create View vw_HousesAccess
        as
        Select * --TODO specify columns where
        FROM Houses
            INNER JOIN Houses_Access ON Houses.ID = Houses_Access.DoorKey
            FULL OUTER Join UserAccess ON  Houses_Access.GroupKey  = UserAccess.GroupKey

        ---then in main query you can use like this.
        IF Exists(Select 1 from vw_HousesAccess  where  WHERE ID IS NOT NULL AND ID = @DoorKey AND UserKey = @UserKey)
         ---your logic


No, that code is not enough to handle any valid JSON.

Here are two examples where the result is not only different from the expected, but also unparsable:

The string:

{"hello":"wor\":ld"}

will be converted to:

{'hello':'wor':ld'}

The string:

{"hello":"w''orld"}

will be converted to:

{'hello':'w\''orld'}


Creating and finding posts using Parse.com

This depends on the scope in which you want the variable to have.

Is the variable the same between the two function calls? if so, you would tend to only define it once, as calling it twice may be expensive.

Interestingly however, you've defined an ES6 const which will complain if you redefine the same value (which is why I presume you've named the variable differently).

If you intended the variable to be different between the two calls, you would normally not use const.

Looking at your example, I would define this variable once, and use the const keyword in order to explicitly avoid is being redefined by accident elsewhere.

You also ask about conventions. Looking at the MDN page for const, they advise naming constants with uppercase characters. So I would probably go down that route unless it contravenes your coding style: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const


read an excel that contains population data of counties and compute summaries by state, county

There are two ways in which you can change your code. The easiest one is to use a more powerful library, that can do more than just reading excel worksheets. For this I would recommend pandas, in which this task is very few lines:

import pandas as pd

df = pd.read_excel("support files/censuspopdata.xlsx")
df.groupby("County").agg({"State": "last", "CensusTract": "count", "POP2010": "sum"})

#               State  CensusTract  POP2010
# County
# San Francisco    CA            7    31060

But you can also improve your use of vanilla Python, by using set comprehensions, the standard library module collections and following Python's official style-guide, PEP8:

from collections import Counter, defaultdict
import openpyxl

wb = xl.load_workbook("support files/censuspopdata.xlsx")
sheet = wb.active

#Create a unique list of all state names from the state column (which is 2nd column)
states = {cell.value for cell in list(sheet.columns)[1][2:]}

#Initiate the countie_in_state dict to hold a set for each state key as it would be populated when the Excel is read row-by-row
counties_in_state = defaultdict(set)

# counter counts the number of census tracts(rows) and counter_pop holds the cumulative population
counter = Counter()
counter_pop = Counter()

#Skip the first row as it contains column names
for row in range(2, sheet.max_row+1):
    #Each row represents a census tract
    state  = sheet.cell(row, 2).value
    county = sheet.cell(row, 3).value
    pop = sheet.cell(row, 4).value

    counties_in_state[state].add(county)
    counter[county] += 1
    counter_pop[county] += pop

print("State","County", "Count", "Pop", sep="\t")
for state,county_set in counties_in_state.items():
    # Sort the counties in each state
    for county in sorted(county_set):
        print(state, county, counter[county], counter_pop[county], sep="\t")

You could put this code under a if __name__ == "__main__": guard to allow importing from this script and generalize this code so it gains an interface similar to the pandas one:

from collections import Counter, defaultdict
import openpyxl

def update_sum(old, x):
    return old + x

def update_count(old, x):
    return old + 1

def update_last(old, x):
    return x

FUNCS = {"sum": update_sum, "count": update_count, "last": update_last}

def groupby(sheet, key, **agg):
    assert agg, "Must give an aggregation function"
    rows = sheet.rows
    headers = [cell.value for cell in next(rows)]
    funcs = {name: FUNCS[func_name] for name, func_name in agg.items()}
    counters =  defaultdict(lambda: defaultdict(int))
    key_index = headers.index(key)
    assert key_index >= 0, "Key not found in data"
    for row in rows:
        row_key = row[key_index].value
        for i, (name, cell) in enumerate(zip(headers, row)):
            if name in agg:
                counters[row_key][name] = funcs[name](counters[row_key][name], cell.value)
    return dict(counters)

if __name__ == "__main__":
    wb = xl.load_workbook("support files/censuspopdata.xlsx")
    sheet = wb.active

    agg = {"State": "last", "POP2010": "sum", "CensusTract": "count"}
    for county, data in groupby(sheet, "County", **agg).items():
        print(data["State"], county, data["CensusTract"], data["POP2010"], sep="\t")
    # CA    San Francisco   7   31060

This is not the most flexible code, extending it to support e.g. a "mean" is quite hard. For this you would probably have to read the table into a different data structure, sort by the key and then use itertools.groupby. This way you can use any function that acts on the whole group:

from itertools import groupby
from operator import itemgetter

def first(x):
    return next(x)

def last(x):
    return list(x)[-1]

def count(x):
    return len(list(x))

def groupby_agg(sheet, *key, **agg):
    rows = sheet.rows
    headers = [cell.value for cell in next(rows)]
    data = [{col: cell.value for col, cell in zip(headers, row)}
            for row in rows]
    data.sort(key=itemgetter(*key))
    d = {}
    for name, group in groupby(data, key=itemgetter(*key)):
        group = list(group)
        d[name] = {col_name: func(map(itemgetter(col_name), group))
                   for col_name, func in agg.items()}
    return d

...
groupby_agg(sheet, "County", State=first, CensusTract=count, POP2010=sum)
# {'San Francisco': {'CensusTract': 7, 'POP2010': 31060, 'State': 'CA'}}

This has the advantage that you can also use the built-in sum, min, max, statistics.mean, .... It also allows using multiple keys, although it does not give you a multiply nested dictionary in this case:

groupby_agg(sheet, "State", "County", CensusTract=count, POP2010=sum)
# {('CA', 'San Francisco'): {'CensusTract': 7, 'POP2010': 31060}}


Make some inputs inside functions instead of main

You are using classes wrong. With your class, you can never have two friend books, because each instance uses the classes mutable listOfFriends. (N.B.: A dictionary called listOf... is not very helpful).

Instead, have one FriendBook object, and let its methods take arguments:

class FriendBook:

    def __init__(self):
        self.friends = set()

    def add(self, firstname, lastname):
        self.friends.add((firstname, lastname))

    def remove(self, firstname, lastname):
        self.friends.remove((firstname, lastname))

    def __str__(self):
        return '\n'.join("{} {}".format(*name) for name in self.friends)

A few notes:

The friends are a set now (this assumes that no two friends share the same first and last name, already a better assumption than yours, which assumed that every friend had a unique last name). You could also make it a list, you would just have to change self.friends.add to self.friends.append.
The magic function __str__ allows simply calling print(fb), where fb is an instance of FriendBook, to print the full list of friends.
I made the names a bit easier. Note that Python has an official style-guide, PEP8, which recommends using PascalCase for classes and snake_case everywhere else.

For your main question, yes you can put these in a function:

def ask_name():
    first_name = input("Enter firstname\n")
    last_name = input("Enter lastname\n")
    return first_name, last_name

I would also slightly rewrite your main function, like this:

if __name__ == "__main__":
    fb = FriendBook()
    while True:
        print("1. Add Friend\n2. Show Friends\n3. Remove Friend\n9. Quit\n")
        try:
            option = int(input())
        except ValueError:
            print("Only integers allowed")
            continue
        if option == 1:
            fb.add(*ask_name())
        elif option == 2:
            print(fb)
        elif option == 3:
            fb.remove(*ask_name())
        elif option == 9:
            break
        else:
            print("Not a valid option")

Notes:

I wrapped it all in a if __name__ == "__main__" guard to allow importing this class from another script.
I use the defined function to ask for the names and use tuple unpacking to pass it to the methods.
I limited the scope of the try...except clause and made it more specific. Your current except covered everything, even, for example, the user pressing Ctrl+C. You should almost always avoid doing this.


Implementing the midpoint displacement algorithm in Java

.... Hrm...

import java.util.Random;

I'm assuming this is sufficient for your needs.  In the future, it may be preferable to create your own interface, that you can supply different implementations for.

public class MidPointGenerator {

    private static double[] heightmap;
    private static double randrange;
    private static int iterations;
    private static double roughness;
    private static int n;

What does n represent?  Most of the other variables are named okay (although randrange should probably be deviation, or similar).
Mutable class-level variables should (almost always) die.  Especially since:

public MidPointGenerator(double s, int i, double h){
    n = (int)(Math.pow(2, i) + 1); // size of the array
    heightmap = new double[(int)n];
    randrange = s;
    iterations = i;
    roughness = Math.pow(2,-h);
    midPoint(0, n-1, randrange,0,i);
}

You set them in the instance constructor!  So, they're really instance variables!  If I were attempting to use your class, I might end up mighty confused as to behavior, when attempting to use two different instances.  Also, your parameter names are terrible - they don't tell me at all what they're used for.  And don't use end-of-line comments.

public static void midPoint(int left, int right, double range, int i, int goal){

    if(i == goal){
        return;
    }

What does i represent?  The only time such short variables are ever really acceptable is as indices during iterators (maybe).  This method is static because it's operating on class-level variables (which should be instance-level), but there's no good reason for it to be flagged public as well.

    int mp = (left + right) / 2;
    double mpheight;

    if(heightmap[left] < heightmap[right]){
        mpheight = ((heightmap[right] - heightmap[left]) / 2.0) + heightmap[left];
        heightmap[mp] = mpheight + random(range);
    }
    if(heightmap[right] < heightmap[left]){
        mpheight = ((heightmap[left] - heightmap[right]) / 2.0) + heightmap[right];
        heightmap[mp] = mpheight + random(range);
    }
    if(heightmap[right] == heightmap[left]){
        heightmap[mp] += random(range);

    }  // <- Missing?

I'm assuming, given other indentation, that the brace (}) belongs here.  Compiler error otherwise.

    midPoint(left, mp, range * roughness, i+1, goal);
    midPoint(mp, right, range * roughness, i+1, goal);

}

public static double random(double range){
    //Returns a random number from -s to s.
    Random random = new Random();

You're creating a new Random object each time you enter this object (and not using the variable you created earlier...).  Depending on how your program runs, you may have multiple instances of Random with the same seed value, causing them to generate the same output; while occasionally random generators should return the same output, getting them in this fashion is undesirable.  Same comments about public and static.

    double randNum =  range - ((2*range) * random.nextDouble());
    return randNum;
}

random.nextDouble() returns an evenly distributed value in the range [0, 1).  The result of the math, though, is not evenly distributed along (-range, range); at least, I don't think so (anybody else know better?  help?).  You can generate double-ended integer ranges (with Random.nextInteger(upper)), which doesn't really help here.  You may need a new random generator, if you're going to get 'correct' results - what you have may be good enough for your current purposes.

public static void displayHeights(){
    for(int i = 0; i < heightmap.length; i++){
        System.out.println(heightmap[i]);
    }
}

Same comments about public and static.  Really, you should be using a for-each loop.  Oh, and not printing out to the console directly, but that's probably forgivable here.

public double getHeightValue(int index){
    if(index == n ){
        return 0;
    }
    return heightmap[index];
}

public int getIterations(){
    return n;
}

I'm assuming that these methods are for whatever needs to inspect the state of the map after you're done constructing it (hence the public), given it's not used anywhere in your code.  You really ought to be returning some sort of array/collection, though (probably a copy of heightmap), which should be easier to work with.

Ah, I think this is more along the lines of how I would have done it:

public class MidPoint {

    private static final Random RANDOM = new Random();

    private final double[] heightmap;

    private MidPoint(double[] heightmap) {
        this.heightmap = heightmap;
    }

    private double[] getHeightmap() {
        return Arrays.copyOf(heightmap, heightmap.length);
    }
}

This is the basic class definition (static creation methods in a second).  Because the class now represents the end state, I felt it was appropriate to change the name.  The constructor is private, because it doesn't make much sense for it to be manually created.  And the end heightmap should be accessed as a copy, so that the result can be safely shared.  It's also being output as the array, not as by-index, which you may find easier to work with.

private static double random(double range) {
    return range - ((2 * range) * RANDOM.nextDouble());
}

I just tightened this up a little, was all.  It might not be 'perfect', but I personally don't know of a better way to set this up, if the variation is an issue.  Actually, this method makes (temporary) testing really easy - just have it return a constant value!

private static double getMidpoint(double a, double b) {
    return ((a - b) / 2) + b;
}

Helper method, to remove code duplication.

private static double getOffset(double current, double left, double right) {
    final int comparison = Double.compare(left, right);

    if (comparison < 0) {
        return getMidpoint(left, right);
    } else if (comparison > 0) {
        return getMidpoint(right, left);
    } else {
        return current;
    }
}

... Mathematically speaking, the greater/less than shouldn't be necessary (because the midpoint calculation gives correct results either way).  The problem comes in that the way doubles (and limited-precision numbers of all types) are represented won't necessarily always give the same results.

private static void midPoint(double[] heightmap, int iteration, int limit, int left, int right, double range, double deviation) {
    if (iteration == limit) {
        return;
    }

    final int midpoint = ((right - left) / 2) + left;

    heightmap[midpoint] = (getOffset(heightmap[midpoint], heightmap[left], heightmap[right]) + random(range));

    final double adjusted = range * deviation;

    midPoint(heightmap, iteration + 1, limit, left, midpoint, adjusted, deviation);
    midPoint(heightmap, iteration + 1, limit, midpoint, right, adjusted, deviation);
}

Recursive method.  Things have mostly just been extracted to helper methods.  The only big difference is the way the midpoint is retrieved, which was changed so that with larger iterations (because of the squaring from iterations) they won't overflow.

private static double[] getMidPoints(final int iterations, final double range, final double roughness) {
    final double[] heightmap = new double[(int) Math.pow(2, iterations) + 1];
    final double deviation = Math.pow(2.0, roughness);

    midPoint(heightmap, 0, iterations, 0, heightmap.length - 1, range, deviation);

    return heightmap;
}

Setup for entire process, returning the finished array.

public static MidPoint generate(final int iterations, final double range, final double roughness) {

    if (iterations >= 31) {
        throw new IllegalArgumentException("Too many iterations, must be 30 or less");
    }

    if (Double.isNaN(range) || Double.isInfinite(range) || !(range > 0.0)) {
        throw new IllegalArgumentException("Range must be a positive value greater than 0");
    }

    if (Double.isNaN(roughness) || Double.isInfinite(roughness) || !(roughness > 0.0)) {
        throw new IllegalArgumentException("Roughness must be a positive value greater than 0");
    }

    return new MidPoint(getMidPoints(iterations, range, roughness));
}

And... The static generator method, returning the final value object.  The biggest thing here was the error checking.

Oh, the results always have 0.0 at the start and end of the set of midpoints, which makes me think something is up, but I have no idea what.  Unfortunately, I don't know what you're trying to implement, so I can't tell if something is wrong.  And no, it's not something I introduced - yours gets that too (constant values for the random get the same results).


Generic BinaryReader/Writer Read/Write methods

I'm guessing you defined more write methods than this? Otherwise the Write() would call itself recursively infinitely. You probably have overloads for every supported type, making the generic write method superfluous. This would also explain the weird casting you are doing. I'm guessing an overloaded function with a specific type has precedence over a generic method, which is why it could work. This however, doesn't make it a clean solution.

Your Read() method seems to be more useful. Instead of throwing a ArgumentException I would prefer throwing a NotSupportedException.

As a sidenote, are you sure you want to make these extension methods of Stream and not some more specific stream? Stream can be any type of stream.

In what way is this an improvement over using BinaryWriter/BinaryReader? For the purposes I gather from your code I would only create a Read<T> extension method for BinaryReader.

If you feel like experimenting a bit, there might be a more performant/cleaner solution, although you'll have to benchmark to be sure. You could create a Dictionary<Type, Func<object>> to hold a matching 'reader' for every type. Initializing the delegates to store in this dictionary is the tough part, on which information can be found in this article. Most likely this is not worth the effort, although it still is a very interesting article. :) Be sure to also check out the same solution implemented by using Expression Trees in the comments of the article. For a similar implementation example I did, check out this question I posted on Code Review.


C++ tuple implementation with get as a member

Your source is not very specific as to why/when my_tuple.template get<0>() is required.

If you have code like this:

Tuple<int, double, float> x(1,2,3);
int i = x.get<0>();

That is fine, because all template arguments to Tuple are known at the time of parsing and Tuple<int, double, float> is instantiated immediately, before the call to get is parsed. At that point the compiler already knows that in that specific instantiation of Tuple get is member function template rather than a non-template member and everything is ok.

This however

template<typename T>
auto foo(T t) {
    Tuple<T,int,double> x(t,2,3);
    return x.get<0>();
}

generates a compiler error, because when foo is parsed, the actual type of T is not known and instantiation of Tuple<T,int,double> needs to be delayed until instantiation of foo. This means that when x.get is parsed, the compiler does not yet know what kind of language construct get is in the instatiation of Tuple<T,int,double> and in fact it may very well vary for different T. Therefore it is assumed that get is a non-template member, which doesn't make sense considering the following template argument list.

Your code sadly does not solve this problem and I don't think it is solvable.

Additionally I noticed that your Tuple is an empty class if an empty type list is given. That is a bit inconsistent. I think at least get should be provided as empty function. Calling it should not be allowed, but referring to the member function should be fine.


Keep div fixed when it is inside it's container on scroll

This is not really a full answer yet, but after correcting my interpretation of your question (as reflected by comments under it) I keep having some incertainties, and a comment is not wide enough to clearly express them.

Anyway I can already notice some possible improvements, not depending on any further precision:

Cosmetic: the right: 0; property can be suppressed from span.bottom rule, since it doesn't change compared to span one.
Performance:

since their value never changes, declaration of span, div, and divHeight can be moved outside of the scroll() event.
we also can fix $(window) by declaring it as var win at the same level.

Operation: depending on the window size, the initial state may not follow your requirements, e.g.:

When running the code snippet and immediately switching to full page the yellow span should have the bottom class, while it doesn't.
The same happens when toggling between full page and reduced iframe: if the state should change when reaching the new window size, it doesn't till scrolling happens.

Then to avoid that, the computation for affecting/dropping bottom class should occur not only when document.scroll() but also window.resize() event happens.
Additionally, each of those events should be initially fired (although in practice only one is enough).

Here is the so modified snippet:

var span = $('span'),
    div = $('div'),
    win = $(window),
    divHeight = div.height();
$(document).scroll(compute).scroll();
$(window).resize(compute).resize();

function compute() {
  var spanHeight = span.outerHeight(),
      spanOffset = span.offset().top + spanHeight,
      divOffset = div.offset().top + divHeight;

  if (spanOffset >= divOffset) {
    span.addClass('bottom');
    var windowScroll = win.scrollTop() + win.height() - 50;
    if (spanOffset > windowScroll) {
      span.removeClass('bottom');
    }
  }
  console.log('spanOffset='+spanOffset, 'windowScroll='+($(window).scrollTop() + $(window).height() - 50));
}
*{margin:0;}
div {
  position: relative;
  background: pink;
  height: 800px;
  margin-bottom: 800px;
}
span {
  position: fixed;
  right: 0;
  bottom: 50px;
  width: 10%;
  height: calc(100vh - 100px);
  background: gold;
}
.bottom {
  position: absolute;
  bottom: 0;
}

  some content

Now let me explain what keeps puzzling me.
Both snippets (yours and mine) have the following wrong behaviour: as of a certain window height (couldn't precisely figure out yet), once switched to bottom the yellow span will never go back when scrolling up.

So before thinking further I'd want to be certain of what is precisely your need. Expressed independently from the current implementation, it seems to me that it is like follows:

as a fundamental requirement, the yellow span height must always be equal to window height minus a given height (say X, in this case 100px), and must not change
if not upset by the rule #3 below, the yellow span must be vertically centered in the window (its bottom is half the above given X)
taking over the rule #2, the yellow span must never cross the pink div (the bottom of the former can't move lower than the latter's one)

For now I remain pending. Thanks for confirming or correcting me.


Here are some things that may help you improve your program.

Use parentheses to clarify expressions

The code contains this line:

return (1 << num_of_bits)-1 << pos;

A programmer reading it might wonder which of the following is the correct interpretation:

return ((1 << num_of_bits)-1) << pos;
return (1 << num_of_bits)-(1 << pos);

To interpret correctly (the first one), one would have to remember that according to C operator precedence, the - operator has higher precedence than the << operator.  We can easily avoid this potential confusion by simply writing the code with parentheses, even though, technically, they're redunandant.

Eliminate unused variables

The load_to_cache function includes unused parameter offset.  If it's not used, it probably should be removed.

Be wary of plain char

Whether char is signed or unsigned is implementation defined.  I'd suggest instead using uint8_t from <stdint.h> to make sure that there aren't any surprises when doing right shifts.  A short example shows the difference:

#include <stdio.h>
int main() {
    signed char a = -1;
    unsigned char b = -1;
    printf("%x\n", a>>2);    // prints ffffffff
    printf("%x\n", b>>2);    // prints 3f
}

For similar reasons, most of the places the code is using int should probably be either unsigned or size_t.

Use a struct where appropriate

The cache is just memory, of course, but with a simulation, the bytes have structure and meaning.  The code has these three lines:

cache[set][0] = 1;
cache[set][1] = tag;
cache[set][2] = memory[memory_index][0];
cache[set][3] = memory[memory_index][1];

This suggests the following struct definition:

#define CACHESIZE 2
typedef struct cacheline_s {
    uint8_t valid;
    uint8_t tag;
    uint8_t mem[CACHESIZE];
} cacheline;

Now the lines above become this:

cache[set].valid = 1;
cache[set].tag = tag;
cache[set].mem[0] = memory[memory_index][0];
cache[set].mem[1] = memory[memory_index][1];

Reconsider the interfaces

Instead of this:

if (!is_valid(cache, set, tag)) {

I think it might make more sense to pass only a single cache line.  Using the struct defined above, the function now looks like this:

int is_valid(const cacheline *cache, int tag) {
    return cache->valid && (cache->tag == tag);
}

Note too that we're passing a const pointer, advertising the fact that the underlying cacheline will not be changed by this function.  A similar interface change could be made to load_to_cache.

Eliminate "magic numbers"

This code has a number of inscrutable "magic numbers," that is, unnamed constants such as 2, 4, 8, etc.  Generally it's better to avoid that and give such constants meaningful names.  That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "2" and then trying to determine if this particular 2 is relevant to the desired change or if it is some other constant that happens to have the same value.  This is especially beneficial in cases like this in which some numbers depend on others.  For example, we can use these to make sure that the two constants are easily changed and kept consistent.  Only the first variable needs to be touched.

#define CACHESIZE_BITS 1
#define CACHESIZE (1u << CACHESIZE_BITS)


Running async processes in node.js on multiple cores

Notice a pattern in the array of your async.parallel call? All the functions are the same except for a single number.

And, judging by the repeated comment for each function, you just copied the first version of the function and changed that one number.

You should create a loop that pushes functions into the array, changing that single number each time.

for(var i = 0; i < 4; i++) {
    array.push(function(callback) {
        console.log(i + 1);
        var k = cp.fork('./doOther.js',['0' + (i + 1)]);
        k.on('message',function(msg){
            console.log(msg);
            callback();
        });
    }
}

As another tip, if you aren't going to use k again, don't store cp.form(...,...); in a variable; just continue the .on stuff that you were doing to the k but to the cp.form(...,...).

That would look like this:

cp.fork('./doOther.js', ['0' + (i + 1)]).on('message', function(msg) {
    console.log(msg)
    callback();
});

Other than that, I'm not too familiar with node.js and what a core is, so I can't help you on that part.


This approach is not much good, but may be suit your required functionality. The method name is dbInsert and you
  are passing table and data in dictionary. you can make it much better by using better naming convention and parameter types.

On the place of this create a method with following parameter as:
GetIdentityOnInsert(string sqlQuery, CommandType commandType, SqlParameterCollection sqlParameters)

query will be: query = "Insert into tableName value(@param1,@param2);SELECT @@IDENTITY;"

Public Function GetIdentityOnInsert(ByVal sqlQuery as String, ByVal commandType as Commandtype, ByVal sqlParameters as SqlParameterCollection)
Try
Using connection As New SqlConnection(connectionString)

        ' Create the command and set its properties.
        Dim command As SqlCommand = New SqlCommand()
        command.Connection = connection
        command.CommandText = sqlQuery
        command.CommandType = commandType
        Dim parameter As New SqlParameter()

        For Each parameter In sqlParameters
            command.Parameters.Add(parameter);
        Next

        ' Open the connection and execute the reader.
        connection.Open()
        Dim newProdID As Int32 = 0
        ' try ExecuteScalar() if it gives error then replace it to ExecuteNonQuery()
        ' and replace the below code as in your question.
        newProdID = command.ExecuteScalar()

            'Dim cmd As New SqlCeCommand("SELECT @@IDENTITY", conn)
            'newProdID = Convert.ToInt32(cmd.ExecuteScalar())
            'Console.WriteLine("added: {0}", newProdID)
         Return newProdID

End Using
Catch e As Exception
    Console.WriteLine("Unable to insert: {0}", e.Message)
    Return 0
End Try
End Function

Hope this help you to create you Data Access Layer. you can extend ExecuteNonQuery with the above method.. just you have to customize little bit..


How to speed up this IP sweep, Port scanner python

IP range

for this its a single IP

It is? Then why do you ask for a range? Your 'end' is not used, so just delete it.
Fail-safe scanning
Consider rearranging this:
try:
    for port in range(startport,endport):

to:
for port in range(startport,endport):
    try:

In other words, some ports may fail and others may succeed.


Invert n bits beginning at position p of an unsigned integer

When you find it "unclear where to start counting" you have encountered one of the greatest problems in software development: extracting useful specifications from your stakeholders!  In these situations, when we can't just ask, then we need to choose an interpretation that seems most useful and reasonable, and (this is the important bit), be very clear that we had to make a choice, and what we chose.
In this case, I would probably make a somewhat more specific name, and also add an explanatory comment:
/*
 * Returns x with n bits inverted starting at bit p
 * (counting from the left)
 * E.g. invert_bits(0x0000, 4, 2) == 0x0c00 for 16-bit unsigned
 */
unsigned invert_bits(unsigned x, unsigned p, unsigned n)

That example in the comment would normally become one of the tests I use to verify the function.
I find it odd that we're working with unsigned yet we use sizeof (int) to calculate the width.  Although we know that int and unsigned int have the same size, it's clearer to be consistent.  Actually, I would just use sizeof x, which then makes it easier to re-use the code - e.g. if we write a version for unsigned long.
I think the arithmetic could be simplified if we consider that a mask with the leftmost p bits unset is ~0u >> p.  Using invert_bits(0x0000, 4, 2) again, as in the comment, we can visualise what we're doing:
      0000111111111111   mask_p = ~0u >> p;
      0000001111111111   mask_n = mask_p >> n;
      0000110000000000   mask_p ^ mask_n

As a completed function, we can reuse a single mask variable for this:
unsigned invert_bits(unsigned x, unsigned p, unsigned n)
{
    unsigned mask = ~0u >> p;
    mask ^= mask >> n;
    return x ^ mask;
}

The nice thing about this is that it adapts automatically to the type's size, without needing any sizeof at all in the computation.

In case I've provided too much spoiler here, I provide some follow-up exercises:

Write the same function, but with the assumption that you count bits from the rightmost (least significant) bit.
Write a version for unsigned long.
Write versions that unconditionally set and reset the specified group of bits.
Write a main() that tests whether the above functions work as advertise.  Remember to return EXIT_SUCCESS or EXIT_FAILURE as appropriate.

Which code can be shared in the answers to these questions?


Working with a new form instance every time

Public Sub ShowMainForm()
    With frmMain
        .Show vbModeless
    End With
End Sub

You don't want that With block, it's redundant.

Public Sub ShowMainForm()
    With New frmMain
        .Show vbModeless
    End With
End Sub

You don't want to do that with a vbModeless form either - the instance will be destroyed quite immediately after being created.

For an object-oriented approach that uses a modeless form, I'd suggest you make the form a member of a dedicated "presenter" class:

Option Explicit
Private WithEvents summaryForm As frmMain ' <~ notice WithEvents ..I'll get to it.

Private Sub Class_Initialize()
    Set summaryForm = New frmMain
End Sub

Private Sub Class_Terminate()
    Set summaryForm = Nothing
End Sub

Public Sub Show()
    If Not summaryForm.Visible Then summaryForm.Show vbModeless
End Sub

Public Sub Hide()
    If summaryForm.Visible Then summaryForm.Hide
End Sub

Now, this "presenter" class shall be responsible for accessing the form; notice how it already hides the implementation detail of the modeless-ness to the outside world.

When the user clicks the btnRun button, the form itself shouldn't be responsible for anything - so instead of calling MainGenerateReport directly, we'll fire an event to tell the presenter class that it needs to do something about it:

Option Explicit
Public Event OnRunReport()
Public Event OnExit()

Private Sub btnRun_Click()
    RaiseEvent OnRunReport
End Sub

Private Sub btnExit_Click()
    RaiseEvent OnExit
End Sub

That way the form has no dependencies to other modules, and pretty much zero responsibilities.

Back to the presenter, we can handle these events:

Private Sub summaryForm_OnRunReport()
    MainGenerateReport
    Refresh
End Sub

Private Sub summaryForm_OnExit()
    Hide
End Sub

Public Sub Refresh()
    'todo
End Sub

This leaves the problem of MakeLabel/Refresh. I don't know what tblInfo is, but I'm pretty sure it's not the form's concern. Really all it needs is some Range or ListObject that contains whatever information needs to go into that list - and instead of looping to .AddItem and explicitly set each .ListItem, you could use the control's .RowSource property and avoid looping altogether; this CR Q&A shows how.

Once the presenter class is capable of providing a data source for the form's ListBox (you'll have to verify it it actually binds to the source; if that's the case then you won't even need a refresh button, the list would just update itself).

That would be the Refresh implementation.

The last step is to instantiate the presenter; as long as the presenter instance is alive, the encapsulated form instance lives - there's no need to explicitly Unload Me anywhere.

Say you named the class SummaryPresenter, then you could have it exist in global scope:

Option Explicit
Private presenter As SummaryPresenter

Public Sub ShowMainForm() ' macro attached to shortcut key
    If presenter Is Nothing Then Set presenter = New SummaryPresenter
    presenter.Show
End Sub

Since we made the OnRunReport handler call Refresh after MainGenerateReport runs, the procedure no longer needs to call it explicitly. Or, if it does need to (hard to tell with just a little 'other code; comment to work with), then it can do so by calling the Presenter object's Refresh method:

Public Sub MainGenerateReport()
    ' other code;
    presenter.Refresh
    ' other code;
End Sub

This makes your code use the same instance of frmMain all the time, while separating responsibilities into different [class] modules... which isn't much different from working against the default instance in the first place.

But then, everything boils down to why you would want a new instance every time - IMO if the form is a modeless "toolwindow" that you can show/hide while working in Excel, then it's objectively better (more efficient) to avoid initializing it everytime you want to show it... just like it's more efficient to avoid initializing the listbox columns everytime you refresh it ;-)


Efficiency of Project Euler 28 - number spiral diagonals

An ultimate efficiency is in math. It can be shown that the result for \$2n+1\$ by \$2n+1\$ spiral is

$$(\frac{2n}{3}) (8n^2 + 15n + 13) + 1$$

The formula can be derived by induction. Another method is to realize that it must be a cubic dependency and fit the coefficients. And you can see that it is cubic, because numbers along the diagonals grow quadratically.


That's a pretty clever implementation. To improve this, I would take some of the cleverness out of it. In particular:

while (true)
{
    BigInteger next = a + b;
    a = b;
    b = next;
    yield return next;
}

2 lines longer, but no unnecessary cleverness. Perfectly clear, nice and simple, and should be just as efficient. It's good general rule to not try to be too clever. Keep it simple.

Also, FibonacciSequence would be a better name than Fibs.

Finally, as a tiny remark, put a space before opening parenthese of the while condition (like I did above, different from the original code).


Optimize query containing too many inner join and rows

Code Review Stack Exchange advice
It really helps if you explain, in plain English, what your code does or is supposed to do. As it stands, nobody has any idea what your code is supposed to do, and the best we can do is guess. With that in mind...

Nitpicks
Your aliases make no sense. Your table names are cryptic enough (you probably can't change that) but to alias WTFAC as F certainly doesn't help. WTFACINFO as BS to me only suggests this: WTF BS.

Your capitalization of SQL keywords is all over the place. Make it all caps, or all lower case, or whatever. Just stick to one style and be consistent.

Your indentations are not very helpful; in fact I find them confusing at best. Use indentations that are meaningful to make the code easier to sift through. For example, this:
inner JOIN dbo.WTVTAT TAT ON BS.TIE_ID = TAT.TIE_ID AND BS.RFAN_ID = TAT.RFAN_ID AND BS.PER_ID = TAT.PER_ID AND BS.CNT_ID = TAT.CNT_ID

Why not instead write:
INNER JOIN dbo.WTVTAT TAT
    ON BS.TIE_ID = TAT.TIE_ID
    AND BS.RFAN_ID = TAT.RFAN_ID
    AND BS.PER_ID = TAT.PER_ID
    AND BS.CNT_ID = TAT.CNT_ID

END YOUR SQL STATEMENTS PLEASE
Not using the delimiter ; throughout your query makes it much more difficult to understand the logic of your code. Use ; and even GO if need be. MS SQL Server is forgiving on syntax errors (try PostgreSQL for fun), that doesn't mean you shouldn't follow good practices of ending statements properly.

SELECT *
SELECT *
INTO ##TempStaffT
FROM Staff HF

Do you really need every column from this table? Perhaps you do, but more likely not. This could improve performance if you are more verbose about selecting exactly the columns you want and no more.
SELECT * makes the SQL engine query the information schema to get all the information about every column in the table, it can slow things down.
CROSS JOIN!?
This:
CROSS JOIN [dbo].[CustBusinessTable] CB

My view is that, unless you know you need a CROSS JOIN, you don't need a cross join. They are insanely slow and that is likely why your query takes so long. If you indeed know you need the cartesian product of [dbo].[CustBusinessTable] and ##TempB then I guess you're out of luck. But I have a feeling there is a better way to do this.


Suspend and resume a thread using signals

This is a useful question because it illustrates how a seemingly working program using pthreads can be loaded with pitfalls.  I hope that you take this answer in the spirit in which it is intended, which is to help you improve your programming.  I didn't see any major problems with the way you're using signals.

Consider using standard threads

You may already know this, but since C11, threads are now part of the standard.  Using them instead of POSIX threads (pthreads) could make the program, in theory anyway, somewhat more portable.  I'll make no further mention of that, however, and the rest will deal with pthreads, although most of the suggestions still apply.

Think carefully about using non-standard calls

The sigemptyset() call is neither a C nor a POSIX standard.  While it's widely supported, it isn't really portable, strictly speaking.  That may be fine for your purposes, but it's important to know which calls are standard and which are not to improve the portability of your program. (I was actually thinking of sigisemptyset here — my mistake!)

Use a mutex to access shared resources

Both threads are attempting to use printf but that's a problem because that requires access to a shared resource, namely stdout.  Access printf within POSIX threads are guaranteed to be thread safe, but the output could be scrambled (that is, the letters from two different threads could be intermixed).  One could use a mutex to assure that only one thread at a time is using that resource.  Here's one way to do that:

#include <stdarg.h>

static pthread_mutex_t stdout_mutex = PTHREAD_MUTEX_INITIALIZER;

static int locking_printf(const char *format, ...) {
    va_list args;
    va_start(args, format);
    pthread_mutex_lock(&stdout_mutex);
    int retval = vprintf(format, args);
    pthread_mutex_unlock(&stdout_mutex);
    va_end(args);
    return retval;
}

Then replace every instance of printf with locking_printf, including the ones in main since that's a thread, too.

Match return types with function

There's no need to write return NULL; at the end of thread_job because it's a void function.  Also, it's my view that one should omit return 0; from the end of main.  It's always contentious because others disagree (often very passionately!), but here's the rationale.

Use bool types where appropriate

The is_th1_ready and is_th2_ready variables are more appropriately described as bool rather than int variables.  For that reason, I'd recommend using <stdbool.h> and writing their declaration and initialization like this:

static bool is_th1_ready = false;
static bool is_th2_ready = false;

Think about casting

Creating the threads uses this kind of call:

pthread_create(&thread2, NULL, thread_job, (void *)2);

That's fine and appropriate.  However, the later use of that data within the thread is a bit unusual:

if (t_id == (void *)1)
    is_th1_ready = 1;

It's perfectly technically valid, but the more conventional approach is to cast the passed void * into something intelligible to the local thread -- often this is a pointer to a struct containing multiple values.  In this case, I'd probably write it like this instead:

if ((int)t_id == 1)
    is_th1_ready = true;

On my machine this causes a compiler warning because int and void * are not the same size (on this machine, with this compiler), but that's not a problem because we know with certainty that this is, in fact, an int.  Another approach would be to do the cast once in the creation of a local int variable.

Rethink the use of scanf

If the user enters a letter or some other non-numeric input, the scanf input fails and the user loses control of the application.  It's well known that scanf has problems.  For that reason, I'd recommend instead using fgets and then strtod.

char buf[5];  // we don't need a big buffer
fgets(buf, sizeof buf, stdin);
switch(strtol(buf, NULL, 10)) {

This will interpret any "garbage" input as 0, but that's probably OK for this program.  Note also that for POSIX systems, non-numeric input can be detected by looking at the errno value.

Prefer for to while where appropriate

The only use of terminate is within the loop, so I'd suggest changing from while to for like this:

for (bool running = true; running; ) {

Note that I've inverted the sense to eliminate the need to negate.  The compiler would probably have done something like that anyway, but I think it's more clear for human readers this way.

Don't bother killing threads at exit

The return from main or a call to exit() will both cause the threads to be cleaned up and resources returned, so I would probably omit the two pthread_kill calls at the end of main.

Consider more robust error handling

It's nice that the code is checking the return value of sigaction, but should the thread even launch if we can't handle the signals?  It's a design choice, but one worth considering, in my opinion.


My solution with a @tail pointer, althought it added complexity it made adding to tail O(1), also having a variable size @size made it easier to counter edge cases.

Having a tail pointer and a size variable makes totally sense.

  Could the Linked List be optimize?

I don't think you can improve performance much here, you already cover most / all of the corner cases. Well done to implement add_at_index with one iteration.

  Are you able to understand how is design when reading the code?

Here are some suggestions to make the code more readable

Extract helper methods

In your code you do several times if @head == nil to check if the list is empty. What about extracting an empty? method?

def empty?
  head.nil?
end

Same goes for instance with increasing the size.

  def increase_size
    @size += 1
  end

Use getter / setter methods

You already define getter and setter methods in your class but then fail to use them.

attr_accessor :head, :size, :tail

Instead of doing @head you should use head etc. Another problem is that the getter / setter are public, move them to the private section of the class. There is no need that consumer of this class know about these implementation details.

Implement the Enumerable interface

At several places in your code you need to iterate over your list with a while loop. If you implement the Enumerable interface of Ruby, you only need to do this once.

class MyLinkedList
  include Enumerable

  def initialize
    @head = nil
    @size = 0
    @tail = nil
  end

  def each
    current = head
    until current.nil?
      yield current
      current = current.next
    end
  end

  def [](index)
    each_with_index do |item, i|
      return item.val if i == index
    end
  end

https://ruby-doc.org/core-2.7.1/Enumerable.html

Use Ruby method names

You probably use the method stubs provided from LeetCode but I think it's still worth mentioning. Whenever possible you should use similar methods as already in the Ruby standard library. If we look at the Array class, we see for instance these methods.

def [](index) # get(index)
def unshift(value) # add_at_head(val)
def <<(value) # add_at_tail(val)
def append(value) # add_at_tail(val)
def [](index, value) # def add_at_index(index, val)
def shift # delete_at_head
def pop # delete_at_tail

Summary

Here are some of my suggestions applied

class MyLinkedList
  include Enumerable

  def initialize
    @head = nil
    @size = 0
    @tail = nil
  end

  def [](index)
    return if empty?
    return if index > size - 1
    return head.val if index.zero?
    return tail.val if index == size - 1

    each_with_index do |item, i|
      return item.val if i == index
    end
  end

  def unshift(value)
    node = Node.new(value)
    node.next = head

    @tail = node if empty?
    @head = node
    increase_size

    value
  end

  def <<(value)
    return unshift(value) if empty?

    node = Node.new(value)
    tail.next = node
    @tail = node
    increase_size

    value
  end

  def []=(index, value)
    return add_at_head(value) if index == 0
    return add_at_tail(value) if head == tail
    return add_at_tail(value) if size == index
    return if index > size

    each_with_index do |item, i|
      insert_node(item, value) if i == index - 1
    end
  end

  def each
    current = head
    until current.nil?
      yield current
      current = current.next
    end
  end

  private

  attr_accessor :head, :size, :tail

  def insert_node(item, value)
    tmp = item.next
    node = Node.new(value)
    item.next = node
    node.next = tmp
    increase_size
  end

  def empty?
    @head.nil?
  end

  def increase_size
    @size += 1
  end

  class Node
    attr_accessor :val, :next

    def initialize(val)
      @val = val
      @next = nil
    end
  end
end


C# Parser of strings with list of assignments

I'm not sure exactly where to start with reviewing this code. There are many things that jump out as unsafe or awkwardly approached.

If my source string contained:

foo1=bar1 foo=bar

Then querying for 'foo'

int startPos = s.IndexOf("=", s.IndexOf(varName)) + 1;

Will incorrectly return the index of 'bar1' not 'bar'.

Use positional data to locate the keys within the string. All keys begin immediately after a space, and end immediately before an equals sign, and contain no spaces or equal signs.

Start by splitting the string on the '='. Your first key will be result[0]. Find the last index of a ' ' character in result[1]. Everything before that is your first value. Iterate your split results to build a Dictionary<string, string> and a Dictionary<string, string[]>, processing the value of key as appropriate based on the assignment type. You can then check if a particular key is defined by looking for it in the dictionaries, and get the value directly.

Is there a purpose to specifying the number of array elements in the key, when you already know the number from the value? How do you propose resolving the difference in the case of an incorrectly constructed string?

"a[1]= x y z"

Should either be a[3]= x y z or a[1]= x, but which takes precedence. If you can control the incoming format, and are not dealing with something beyond your control, use a[]= x y z and don't rely on the count being placed in the key.


Shortening if-statements of displaying errors

You are repeating the same code:

echo str_repeat(' ', 20), '
↳ You did not enter your name.
', "\n";

Replace it with a function which will do the job:

function message($content, $class = ''){
    return str_repeat(' ', 20) . '
$content
\n";
}

You are using construction:

if () {} else if() {}

This is the same as:

if () {} else { if() {} }

I guess, that it is not what you want to use, the correct construction should be:

if () {} elseif() {}

The code itself can be rewritten like this:

function message($content, $class = ''){
    return str_repeat(' ', 20) . '
$content
\n";
}

if (!Input::exists()){
    echo message('We will address you by this name.', 'addition');
    echo message('Re-enter your email to make sure it\'s correct.', 'addition');
} elseif (Input::exists() && $token) {
    if($validation->error('firstname') && $validation->error('lastname')) {
        echo message('You did not enter your name.', 'addition error');
    } elseif($validation->error('firstname')) {
        echo message('You did not enter your first name', 'addition error');
    } else {
        echo message('You did not enter your last name.', 'addition error');
    }

    if($validation->error('emailConfirm') == 'match') {
        echo message('The email address you entered does not match.', 'addition error');
    } elseif($validation->error('emailConfirm') == 'type') {
        echo message('You did not re-enter a valid email address.', 'addition error');
    } else {
        echo message('You did not re-enter your email to confirm', 'addition error');
    }
}


Can you please look into my code and suggest me some performance improvement techniques.

No -- it doesn't work like that. While there are some obvious things you may catch visually (like observing string comparisons at each iteration) every time you optimize you should start by profiling your execution, then isolating the parts that take the most time, then optimizing, then profiling again.

For example, it's possible that optimizing in this case is not removing or changing something you "do wrong" but splitting your hard drive into chunks and parallelizing the effort.

Either way, first, profile the execution and identify the worst offenders.


Do not use an 'active' column as a way of joining a table.

  The other issue is that I have foreign keys on the auto_increment ids
  of both tables

I'm assuming you mean the invariant & variant tables both have PrimaryKeys which are auto_incremented. If so, this is fine. Most tables have an auto incremented primary key.

You could put all the columns onto the variant table (which is where they belong) and have an audit table. The audit table would contain the old value(s) & new value(s) along with the changed date.

If you wish to continue with your unique versioning system, I would still remove the active indicator on both tables, and instead sort by latest date to find the current. If no rows exist on invariant, either variant is 'inactive' or should be deleted.


Cleaner or better readability in URL composition

You could simplify to something such as:

$url = 'http://www.example.com/api/v1/all/limit/%d/offset/%d';

$newURL = sprintf($url, $limit, $offset);

We use sprintf() for this.

Update

  e (PREG_REPLACE_EVAL)

  Warning This feature has been DEPRECATED as of PHP 5.5.0. Relying on
  this feature is highly discouraged.

Docs

Now I really suggest you find an alternative.

According to your update, you say the number of variables might grow. Could you explain (example code?) this more? If it "grows", then the issue may not be this part of the function, it may be the surrounding code that needs fixing.


Frontmost window of the current application that passes a predicate check

There is a way of improving the code as desired in that it is possible to constrain the type T to T: NSWindow. Upon introducing this change, however, the function will indeed return the first NSWindow in the current ordering, whether or not it is of subtype T (too check this you must construct a test that can actually fail, i.e. by having an NSWindow of a another type above the window you are looking for - e.g. by adding a status item to your app). There is a workaround, however, as described in Optional binding succeeds if it shouldn't. Apart from the solution I stumbled upon in the question (of not constraining T), there is a much preferable option discovered by @vacawama in the answer to the linked question. The workaround is to generalise the variable to Any before type checking, e.g. as follows:

public func frontmost <T: NSWindow> (windowOfType: T.Type) -> T? {
    return frontmostWindow { $0 as Any is T } as? T
}

This improves the api considerably.


Figured I would raise a few points:

Having read your responses/replies, we can gather you have the following specs (roughly):

Small memory footprint
Optimization

Before I go over those two points, Let's first step through the code:

I feel the name VolumeIssue is not very descriptive. In fact, it seems odd to have the struct name be the combination of both of its fields.

Next, I would keep the readonly members but make them private, also drop the uppercase. Instead, use publicly accessible properties in order to access these fields as follows:

private readonly string volume;
public string Volume { get { return this.volume; } }

At this stage, you are most likey asking "why?" and probably for good reason. I mean, you have the following case covered:

Immutability - You've exposed the fields but they are readonly

Why would you bother adding more code when the current solution gives you the same solution for less...or does it?

The code may be functionally equivalent, but we there are more things to be considered. The struct is public. This means that you are allowing other developers to interact/use/inspect and interface to your value type.

Jon Skeet states the following:

  For every type you write, you should consider its interface to the
  rest of the world

You see, by exposing your fields, you are exposing the implementation of your struct, and I would recommend against this.

Jon goes on to say:

  A property communicates the idea of "I will make a value available to
  you, or accept a value from you." It's not an implementation concept,
  it's an interface concept.

Currently, you are violating the design principle of hiding the implementation and for this reason I would also argue in favouring the property/field combo. I've linked the article quotes at the bottom, it's a good read and should give you some interesting points to consider.

Having looked at you use of the struct, it is important to note that you only use the fields within the struct itself. Now, as these fields will only be given once (during the constructor), I would build the contents of the ToString method there and then as @dreza pointed out.

Back to your use case

I would say you are right in choosing to use a struct. Your struct only contains two fields and is embedded inside another object. See more detail here.

Briefly back to the first two points:

Memory footprint

Yup, you've got this covered.

Optimisation

One key thing that should be pointed out is that your value type should implement IEquatable. I would always do this.
This way, you avoid the cost of boxing/unboxing your value type upon any equivalence comparison.