parsing a flat file and removing duplicates

You should probably close the file as soon as you are finished.
Divorcing the open() and close() makes it harder to see maintain.
Move close() to here (just after you finish using the file).
open (YYY, "/home/access_log");
#assigning flat file to an array
my @incomingarray=<YYY>;
close (YYY);

In the main loop you add overwriten the current values with just the IP address I would not consider this good practice (though it works here because of the simplicity of the program). And since your next step is to convert the array into a hash why not do so directly in the loop.
  $incomingarray[$value] = $ip;

Why not just do:
  $IPlist{$ip} ++; // Increment the count that way you can count each IP.

There is no need to create a new array just to loop over them. You can use the keys directly in the foreach statement to loop over the hash.
my @distinctIP = keys %IPlist;
foreach (@distinctIP) {
  print "$_\n";
}

Just as easy to write:
foreach (keys %IPlist) {
  print "$_\n";
}

Two things no note about variables.
Using the automatic variables $_ and @_ make writing the code easier but (in my opinion) also can make the code harder to read and maintain (if overused). This is why perl has got the reputation of being a write once never read or understand again language. So please try and be explicit.
Also all the variables you declare are global scope (you seem to have fixed this). I know for this short program it does not make any difference but a habit you should get into is declaring variables with my. This scopes the variable to the current block (thus making them behave like variables in most other modern languages). By doing this you reduce problems associated with modifying global state accidentally and when you do drop my you know it is on purpose and thus affecting the global version.
Loading the whole array.
Personally I would not have loaded the file into the array and parse it. I would have just read the file line by line and done the appropriate parsing:
#!/usr/bin/perl

use strict;
use warnings;

my %IPList ;
open(YYY, "access_log");
while(my $line = <YYY>)
{
    chomp $line;
    (my $ip, my $junk) = split(/ - - /, $line);

    $IPList{$ip}++;
}
close(YYY);


Sample table-driven finite-state machine

If I were a candidate, I'd judge what I think the quality of your code looks like based on this simple, and I'd have some concerns:

Your transition table depends on the values of the Lexeme enum not changing (say by inserting additional values). If this is the case I'd like there to be a comment on enum saying order is significant or having the values explicitly given orders. Otherwise I'd expect the actual numbers to not matter.
Your code contains a transition table. That's hard to read and hard to modify. Why would you do that?
You've two extra sets of parens here:

while ((currentState >= 0) && (currentState != 7))

Your states and done via magic numbers and not an enum.
The check for -1 feels like it's in the wrong place. It is handling an error condition. But the other element of the switch isn't an error condition.


Is this code a good solution for this task?

You have not implemented exception handling (the last requirement). Eg. if calling code passes null to AddToJuices or AddToSlices, it won't crash straight away, but as soon as you call MakeFreshes, it will result in an unhandled NullReferenceException once it gets to this null "fruit".

Also note that we don't know what calling code may pass in as an argument - could be some object that implements one of the interfaces, but actually explodes once our code calls its MakeJuice or MakeSlices... The requirement states that it's the responsibility of this code to handle exceptions, so if this was my homework, I'd prefer to be on the safe side here.

Less importantly, you implemented Name as a property of Fruit rather than a field (which is what the description asks for), although public
fields actually are considered a bit of a code smell, and a backing field is automatically created for properties, so I would leave it.
Aiming at good code style you could make it immutable though (as a readonly field, or a property with a private setter), and set it in the constructor - it stands to reason that name of a given fruit isn't subject to change. juices and slices could be readonly too, but that's nitpicking already.

Apart from the lack of exception handling, it seems okay to me. I like that you used some modern C# features to cut down on verbosity.


You can use the same options object for all three animations.

var opts = {
    useTranslate3d: true,
}
$(".loading").delay(2600).fadeOut(opts);
$(".zip").delay(1900).slideDown(opts);
$("#zip").delay(2800).slideDown(opts);

Having .zip and #zip pointing to different elements might also be a bit confusing - but that depends on your DOM structure.


It's not init that causes you to have to be responsible for releasing the memory its alloc. If you call alloc, retain or new (this is rarely used these days) then you are responsible for releasing the memory yourself.

So in the case where you had an autoreleased object and you retained it. Then yes you would then be responsible for subsequently releasing it.

The most common side affect where you can be responsible for releasing an object you didn't explicitly call alloc or retain on is with a property that has the retain attribute.

@property (retain) NSString *string;

if you then have the following code somewhere

self.string = [NSString stringWithString:@"This is an autoreleased string typically"];

calling the self.string piece will cause it to retain the value you are setting it with. So you would want to make sure and have the following to clean it up, probably in your dealloc.

self.string = nil;


Use optional to check Null pointer exception

Optional.map produces a cleaner code. It's similar to flatMap except the function inside doesn't need to know about Optional. Also passing method references makes things a little bit shorter.

Optional.of(price)
        .map(Price::getPreviousPrice)
        .map(Price::getRegion)
        .map(Region::getValue)
        .ifPresent(ActualValue::setValue);


How should I format my code to make it easier to read and understand in the future

I prefer using JOIN...ON, clarifying an intention of priority of OR and AND phrase.

SELECT
  events.event_time,
  messages . *
FROM
  events
  JOIN messages ON events.global_id = messages.global_ref_id
WHERE
    ((messages.to =184 AND messages.from =192)
      OR (messages.to =192 AND messages.from =184))
    AND messages.global_ref_id < 495
ORDER BY
  messages.global_ref_id ASC


String cut by a separator with the separator in the respective list element in python

You can exploit zip and iterators to allow you to pair things together:

data = [a + b for a, b in zip(*[iter(data)]*2)]

You could use just re, and change the separator with a look ahead assertion.

data = re.split(" (?=my_separator)", s)

You can use str.split, and just add the separator back:

sep = 'my_separator '
data = s.split(sep)[1:]
data = [sep + i for i in data]

data = [sep + i for i in s.split(sep)]


Some thoughts on speed:

Start caching results in isPrime.
Print things as soon as you calculate them, no need to store them back into an array. (This makes debugging easier, too.)

As Leonid pointed out, storing things may be a good idea.  I would keep it an array in that case, not a linked list, as that costs less time.
However, I would simply disable output when profiling, and keep my suggestion for debugging.
On a similar note, consider splitting both the main algorithm and the output into separate functions so that you can easily disable both.  That makes it much easier to check how much each stage of the algorithm (parsing, processing, printing) is taking.

You could try caching rem*rem, as you know there's only ten possibilities.  May be faster, may be slower.
You should take a look at the input you'll be dealing with and figure out what values your program needs to have that could be given beforehand.  What values can the numbers you're checking for primality be?  (I would guess you need up to around 2000, but I'm not sure.)

Some general thoughts:

Add some comments.  What is a lucky number?
Add some blank lines.
Rename getLucky to isLucky or checkIsLucky.  I'd go for the first, but some people will tell you that functions need a verb other than "is".  If Java supports it, you could make it an extension method and then do arr[i].isLucky().
Don't make variables static unless they have to be.  Both T and ans can be local to main.
Make your variable names more meaningful.  In particular, replacing T with numberOfInputPairs (or numInputPairs, at least) would improve matters.
Don't use the same name for two variables, with one letter difference.  Why do you have sum and sum1?  What's the difference between them?
Use the += operator when possible.  sum1 += rem*rem is easier to read than what you have.

To address the question of numberOfInputPairs being too long: let's reformat the code a little and change the name appropriately:

public static void main(String ar[]){
    Scanner scan = new Scanner(System.in);
    int numberOfInputPairs = scan.nextInt();
    int ans[] = new int[numberOfInputPairs];

    for (int i = 0; i < numberOfInputPairs; i++){
        A = scan.nextLong();
        B = scan.nextLong();
        for (long j = A; j <= B; j++) {
            if (getLucky(j)) {
                ans[i]++;
            }
        }
    }

    for (int i = 0; i < numberOfInputPairs; i++) {
        System.out.println(ans[i]);
    }
}

Yes, if no whitespace is added, the longer variable names make a wall of text a bigger wall of text, and convey very little meaning.  However, with just a slight increase in the amount of whitespace, I find that the longer variable name is no less clear and makes it clear what is being done.

(By the way, I think this is partially a language problem: as things are, it is used three times, while a proper for-each loop would mean it would only need to be used once.)

I do not agree with n or T offering that clarity; numPairs would do, too, and is down to personal preference.


Determining if there is a route between two nodes in a directed graph

You don't reset the src.state when you return the result.

This means that between isThereAPath calls you need to reset the state manually. Instead you should reset the state:

public static boolean isThereAPath(Node src, Node dst){
    //Assumption: Nodes are initialized with State.White
    if(src.state == State.White){
        src.state = State.Grey; //Means visiting this node right now
        for(Node node : src.getAdjacent()){
            if(node == dst){
                src.state = State.White;
                return true; //Hit - path found!
            }
            if(isThereAPath(node, dst)){
                src.state = State.White;
                return true;
            }

        }
    }
    return false; //NO path found
}


Algorithm that checks if a tree is full and complete

On the whole I like your implementation. It is elegant and correct. I also like your use of a TreeInfo object.

Your calculation of valid is a little unnecessarily complex - you can make it much simpler and clearer as a single statement.

You may find (and this is only my opinion) adding some comments helps you think more clearly about the code.

Once I had finished tinkering my version looks like:

public boolean isFullCompleteTree(Tree<Integer> t) {
    TreeInfo rootInfo = isFullCompleteTree(t.getRoot());
    return rootInfo.valid;
}

public TreeInfo isFullCompleteTree(Node<Integer> node) {

    if (node == null) {
        // A null node is valid with a size of 0.
        return new TreeInfo(true, 0);
    }

    // Inspect both branches.
    TreeInfo rightInfo = isFullCompleteTree(node.goRight());
    TreeInfo leftInfo = isFullCompleteTree(node.goLeft());

    // Valid when both branches are valid and have the same child count.
    boolean valid = rightInfo.valid && leftInfo.valid
            && rightInfo.numChildern == leftInfo.numChildern;
    return new TreeInfo(valid,
            // My size is the total size of my children + 1
            rightInfo.numChildern + leftInfo.numChildern + 1);
}

Notice how the valid calculation matches your spec of its left son has number of children that is equal to its right son's number of children along with the obvious both children are valid.


Triggering based on words or phrases entered in a text box

Performance

  I have my code working as needed but am looking for way to improve / optimize it.

If you want to improve the performances there are a few things you can do.

Testing

The first thing is that you can run tests and see how code style and logic can effect performance. Javascript testing is a little tricky. You can not just run the functions. You need to make sure you are not being tricked by the optimiser

I have added a basic Javascript performance tester to the bottom to highlight the following points.

Slow iterators

The Array iteration functions such as Array.some are generally slower than writing a standard for, for of or while loop. The reason is because functions incur a lot of additional overhead each time they are call.  They need their own memory, special structures to hold the current scope, and closure values. All this is added to the JavaScript heap and called the function's "context".

On top of that the actual function Array.some has to do some checks to make sure that the arguments you pass are correct and can be used. This all adds to the time to run the function.

For of loops are faster

Using a for...of loop avoids all that overhead and for this example is about 60% faster (on Chrome)

var triggerWords = ['hello there','world', 'hello world', 'how do I turn this on', 'general kenobi'];
for(const  word of triggerWords ){
     if(inputVal.indexOf(word) {
         $("#showme).show(300);
         return;  // all done exit the key up event
     }
}
$("#showme).hide(300);

Native power!

But the problem is still the iteration. Using JavaScript to check each string in turn is never going to utilize a modern CPU's true power. But there is a way to have the search done using pure native code.

RegExp will do the test in a fraction of the time.

Building the regular expression from array of string is expensive, so you would not use this method if the search string (triggerWords) changes each test. But if the the search is the same each time, you can build the regExp at the start and you get around a 1000% performance boost.

// create at start;
var triggerWords = ['hello there','world', 'hello world', 'how do I turn this on', 'general kenobi'];
const reg = new RegExp(triggerWords.join("|"),"gi")

// inside the key event
if(reg.test(inputVal)){
    $("#showme).show(300);
} else {
    $("#showme).hide(300);
}

The cost of libraries

The easiest way to get a performance boost is to drop the libraries.

Without jQuery the code looks like.

const wordSearch = /hello there|world|hello world|how do I turn this on|general kenobi/gi;
inputTest.addEventListener("keyup", (event) => {
    if( wordSearch.test(inputTest.value.replace(/[^a-z ]/gi,"")) ) {
         showme.classList.remove('hide');
    }else {
         showme.classList.add('hide');
    }
 });

And add a hide class to the CSS.

 .hide { display : none; }

The next snippet shows it all put together, copied from your fiddle (a page needing well over 1Mbyte of javascript to run) to a total of less than 1000bytes for all the code, css, and markup

const wordSearch = /hello there|world|hello world|how do I turn this on|general kenobi/gi;
inputTest.addEventListener("keyup", (event) => {
    if( wordSearch.test(inputTest.value.replace(/[^a-z ]/gi,"")) ) {
         showme.classList.remove('hide');
    }else {
         showme.classList.add('hide');
    }
 });
#showme{
  padding-top:15px;
}
.muted{
 padding-top:15px;
 font-size:12px;
 color:#ccc;
}
.hide {
 display : none;
}

Enter a word or phrase to search:

Search: <input id ="inputTest"  type="text" placeholder="Word / Phrase">

Indexed words / phrases:

hello there

world

hello

hello world

how do I turn this on

general kenobi

Example performance comparisons.

The snipped tests the 3 search methods Array.some, for..of and regExp

It uses the worst case scenario and runs the tests many 1000's of times. The test order is random to stop the optimizer slewing one method over another, and the result of each search are socked up by a global variable to stop the optimizer from just removing the inner loops completely

Let the test run until the mean times start to stabilize then click the page to compare the performance results.

/*===========================================================================
  Set up test data.
  One big array with

  ===========================================================================*/
const rand = (max) => Math.random() * max | 0;
const innerLoopCount = 1000;
var c = "aabbaa";
var b = "skjht kjhlvuh svrtgkj abcdef ghijklmn opqrst uvwxyz1 234567890 ";
var a = [];
for(i = 0; i < 10; i ++){ a.push(b.substr(rand(b.length -10), rand(8) + 2)) };
var reg = new RegExp(a.join("|"),"gi");
document.addEventListener("click",() => stop = true )
var stop = false;

var soak = 0; // this is to prevent optimiser removing test code. It soaks up entropy generated by the functions :P
function testA(){
    var i = 0, found;
    const now = performance.now()
    while(i++ < innerLoopCount){
      var found = a.some(function(word) {
          return c.indexOf(word) > -1;
      })

      soak += found ? 1:0;
    }
    return performance.now() - now
}
function testB(){
    const now = performance.now()
    var i = 0, found;
    while(i++ < innerLoopCount){
      found = false;
      for(const word of a){
          if(c.indexOf(word) > -1) {
              found = true;
              break;
          }
      }
      soak += found ? 1:0;
    }
    return performance.now() - now;
}
function testC(){
    const now = performance.now()
    var i = 0, found;
    while(i++ < innerLoopCount){

      found = reg.test(c);
      //for(const word of a){
      //    if(c.indexOf(word) > -1) {
      //        found = true;
      //        break;
      //    }
     // }
      soak += found ? 1:0;
    }
    return performance.now() - now;
}

const tests = [
    { count : 0, time : 0, run : testA, status : statusElementA, name : " 'Array.some' : "},
    { count : 0, time : 0, run : testB, status : statusElementB, name : " 'for...of' : "},
    { count : 0, time : 0, run : testC, status : statusElementC, name : " 'regExp' : "},
];
function testing() {
    var testsCount = tests.length;

    for(var i = 0;i < 100; i ++){
        var selTest = tests[Math.random() * testsCount | 0];
        selTest.time += selTest.run();
        selTest.count += 1;
    }
    for(const test of tests){
        test.mean = test.time / test.count;
        test.status.textContent = `${test.name} mean ${test.mean.toFixed(3)}ms over ${test.count} cycles.`;
    }
    if(!stop){

        setTimeout(testing,100);
    }else{
      tests.sort((a,b) => a.mean - b.mean);
      const slowest = tests[tests.length -1].mean;
      var win = "  Fastest";
      let test;
      for(test of tests){
          test.status.textContent += (test.mean / slowest * 100).toFixed(1) + "%"
          if( win ) {
              test.status.innerHTML += win;
              test.status.className = "champ";
              win = undefined;
          }
      }
      test.status.innerHTML += "  Slowest"
      test.status.className = "lost";
    }
}
setTimeout(testing,100);
body {
    font-family : arial;
    font size : large;
    text-align : center;
}
h4 {
   font-size : small;
}
.winner {
   color : green;

}
.looser {
   color : red;
}
.champ {
   background : #CFC;
   font-weight : 700;

   transition: all 0.5s ease-out;
}
.lost {
   background : #FCC;
   transition: all 0.5s ease-out;
}

Javascript Array.some V for...of V regExp

Click on the page to stop testing.


FFmpeg command line for showing two videos side by side

Partial result

ffmpeg -v warning -i video1.mkv -i video2.mkv -filter_complex '[0:v]scale=400:400,pad=800:400 [0:q]; [1:v]scale=400:400[1:q]; [0:q][1:q]overlay=400:0' -f nut -c:v rawvideo -c:a copy - | mplayer -noconsolecontrols -cache-min 1 -cache 1024000 -

Dummy video input removed
Filenames now separate command line aguments, not parts of a longer string
Still manual geometry
Still not automatically extendible to more videos
Preparing and playing video decoupled, now can use other player instead of mplayer (unfortunately mpv or vlc fails to provide seeking in this scenario)
Audio is preserved


Some notes:

@session: A method called find_or_create_session should not change the state of instance variables.
@sessions.find_by facebook_id: fbid is written twice. Use variables to avoid repetition. Also, the consensus in the Ruby community is to always write parens (except for DSL-like code).
Time.now - @session.last_exchange: You can perform that check in the  SQL query.
Your method is basically doing find_or_create_session = existing_session || new_session, let the code mimic it.

I'd write:

def find_or_create_session(fbid, max_age: 5.minutes)
  Session.find_by(["facebook_id = ? AND last_exchange >= ?", fbid, max_age.ago]) ||
    Session.create(facebook_id: fbid, context: {})
end


Naming

In order for code to be useful, it has to be understood. This applies equally to you now, you in 6 months and anybody else who eventually has to work with it. As such, code should be written for other people to read and understand.

Documentation helps with this. Writing down what your program is doing/why. But the easiest way is just to name things descriptively and unambiguously.

Dim service As String
Dim supplier As String
Dim priceRange As String
Dim price As String

These are good names. Somewhat ambiguous, I'd prefer something like serviceName, supplierName, priceText etc. to be completely unambiguous, but I can look anywhere in your code, see those variables and know precisely what they are.

Dim wsText As Variant
Dim wSum As Worksheet
Dim Lrow As Long
Dim a As Long, b As Long

These are not good names.

If I see something called wsText I'm going to parse that as Worksheet Text which means... some kind of text, in a worksheet? A worksheet called text? Oh, it's a list of worksheet names.

Yeah, that was completely non-obvious.
Just call it worksheetNames or maybe targetWorksheetNames.

wSum is similarly ambiguous and not-obvious about what it is. Just call it summarySheet.

a, b are generic, and hence useless. Here, they refer to Row and Column indexes, so why not call them currentRow, currentcolumn?

Good naming just makes code a hell of a lot easier to work with. Like so:

Sub AggregateSheetData()

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

    Dim sheetNames As Variant
    sheetNames = Array("<25K", "25K <100K", "100K <250K", "250K <500K", "500K <1M", "1M <5M", "5M <15M", "15M <30M", "30M <50M")

    Dim summarySheet As Worksheet
    Set summarySheet = ThisWorkbook.Worksheets("Summary")

    Dim currentSummaryRow As Long
    currentSummaryRow = summarySheet.Cells(summarySheet.Cells.Count, 1).End(xlUp).Row

    Dim service As String
    Dim supplier As String
    Dim priceRange As String
    Dim price As String

    Dim currentSheet As Worksheet
    Dim currentSheetName As String
    Dim currentRow As Long, currentColumn As Long
    Dim lastRow As Long

    Dim sheetCounter As Long
    For sheetCounter = LBound(sheetNames) To UBound(sheetNames)

        currentSheetName = sheetNames(sheetCounter)
        Set currentSheet = ThisWorkbook.Worksheets(currentSheetName)

        lastRow = currentSheet.Cells(currentSheet.Rows.Count, 1).End(xlUp).Row

        For currentRow = 5 To lastRow
            currentSummaryRow = currentSummaryRow + 1

            For currentColumn = 12 To 47

                priceRange = currentSheet.Cells(2, 1).Text
                service = currentSheet.Cells(currentRow, 1).Text
                supplier = currentSheet.Cells(4, currentColumn).Text
                price = currentSheet.Cells(currentRow, currentColumn).Text

                summarySheet.Cells(currentSummaryRow, 1) = service
                summarySheet.Cells(currentSummaryRow, 2) = supplier
                summarySheet.Cells(currentSummaryRow, 3) = priceRange
                summarySheet.Cells(currentSummaryRow, 4) = price

            Next currentColumn
        Next currentRow
    Next sheetCounter

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True

    MsgBox ("Complete")

End Sub

Now things are becoming a lot clearer, and we can move on to the next stage of making this code useful. Namely, explaining and documenting important information.

Magic Numbers

A magic number is any hard-coded value which appears in your code.

Why does a start at 5?

Why does b only go from 12 to 47?

Why is supplier always pulled from row 5?

Why is service always pulled from column 1?

Why are they laid out in columns 1-4 of the summary sheet, and in that order?

How do we know that our worksheets haven't been renamed?

For each of these questions, you should either re-structure your code so they don't have to be hard-coded, or you leave a note explaining why they have the values they have and put them in appropriate variables.

In this case, I recommend constants. Like so:

'/ Each sheet is laid out with Suppliers on row 4, Service in column 1, and then price values in a grid.
Const SUPPLIER_ROW As Long = 4
Const SERVICE_COLUMN As Long = 1

...

...

For currentRow = SUPPLIER_ROW + 1 to finalRow
    For currentColumn = SERVICE_COLUMN + 1 to finalColumn

    ...

    ...

And now, if your data ever moves around, you only have to go and change that value in one place. And everywhere else in your code, you can refer to your constant by name, rather than trusting that you'll remember why the numbers are what they are.

Arrays

This is where we're going to give you a serious performance tune-up. I expect it will solve all of your speed and memory problems.

Doing anything to a Worksheet is a huge operation. If you write

priceRange = currentSheet.Cells(2, 1).Text

it doesn't feel like a big operation, but you have to query the Worksheet Object, which queries the Cells object, which searches through a couple billion range objects to find the one you're after, which then gets queried to determine the text value it's currently displaying. This also triggers Worksheet Events (query handlers, events, calculations, screenUpdating, validation, etc.) which fire off their own chains of cascading events and so on and so forth.

And you're doing this roughly 2 Million times.

(N.B. the above is for illustration only. The actual chain of events is much more complex and convoluted).

When working with data, what you want is an Array. An Array is just a grid of values laid out in memory, so querying a value from an Array is literally a trillion times faster than querying it from a Worksheet object.

VBA makes this incredibly easy. Just create a Range that encompasses all your data, and do the following:

Dim dataArray As Variant
dataArray = dataRange

And now, whatever was in the topLeft Cell of your Range is in dataArray(1, 1). Next row down dataArray(2, 1) and so forth. you can then read this data back to a worksheet by doing the same in reverse:

pasteRange = dataArray

The following is your code, re-written to use Arrays, and it will be quite literally a thousand times faster:

Sub AggregateSheetData()

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

    '/ row/column positions on data sheets
    Const SUPPLIER_ROW As Long = 4
    Const SERVICE_COLUMN As Long = 1
    Const START_COLUMN As Long = 12

    Const SUMMARY_SHEET_NAME As String = "Summary"

    Dim sheetNames As Variant
    sheetNames = Array("<25K", "25K <100K", "100K <250K", "250K <500K", "500K <1M", "1M <5M", "5M <15M", "15M <30M", "30M <50M")

    Dim summaryData As Variant
    ReDim summaryData(1 To 4, 1 To 1)
    Dim summaryCounter As Long

    Dim service As String
    Dim supplier As String
    Dim priceRange As String
    Dim price As String

    Dim dataRange As Range
    Dim sheetData As Variant
    Dim finalRow As Long, finalColumn As Long
    Dim iRow As Long, iColumn As Long

    Dim currentSheet As Worksheet
    Dim currentSheetName As String

    Dim sheetCounter As Long
    For sheetCounter = LBound(sheetNames) To UBound(sheetNames)

        currentSheetName = sheetNames(sheetCounter)
        Set currentSheet = ThisWorkbook.Worksheets(currentSheetName)

        With currentSheet

            priceRange = .Cells(2, 1).Text

            finalRow = .Cells(.Rows.Count, SERVICE_COLUMN).End(xlUp).Row
            finalColumn = .Cells(SUPPLIER_ROW, .Columns.Count).End(xlToLeft).Column

            Set dataRange = .Range(.Cells(SUPPLIER_ROW, SERVICE_COLUMN), .Cells(finalRow, finalColumn))

        End With

        sheetData = dataRange

        Dim LB1 As Long, UB1 As Long
        Dim LB2 As Long, UB2 As Long
        LB1 = LBound(sheetData, 1)
        UB1 = UBound(sheetData, 1)
        LB2 = LBound(sheetData, 2)
        UB2 = UBound(sheetData, 2)

        For iRow = LB1 To UB1
            service = sheetData(iRow, LB2)

            For iColumn = (START_COLUMN - SERVICE_COLUMN + 1) To UB2

                supplier = sheetData(LB1, iColumn)
                price = sheetData(iRow, iColumn)

                summaryCounter = summaryCounter + 1
                ReDim Preserve summaryData(1 To 4, 1 To summaryCounter)

                summaryData(1, summaryCounter) = service
                summaryData(2, summaryCounter) = supplier
                summaryData(3, summaryCounter) = priceRange
                summaryData(4, summaryCounter) = price

            Next iColumn
        Next iRow
    Next sheetCounter

    Dim summarySheet As Workbook
    Set summarySheet = ThisWorkbook.Worksheets(SUMMARY_SHEET_NAME)

    Dim pasteRange As Range
    With summarySheet

        finalRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        Set pasteRange = .Range(.Cells(finalRow + 1, 1), .Cells(finalRow + summaryCounter, 4))
        pasteRange = summaryData

    End With

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True

    MsgBox ("Complete")

End Sub


You can just parse the number right out of the location like this:

setTimeout(function() {
    var matches = window.location.hash.match(/^#page(\d+)$/);
    if (matches) {
        scroll(+matches[1] - 1);
    }
}, 500);

OK, now that you've changed to random strings, you could use a table lookup like this:

setTimeout(function() {
    var values = {
        "#somename": 1,
        "#somethingelse": 2,
        "#someotherword": 3,
        "#sometext": 4
    };
    var val = values[window.location.hash];
    if (val) {
        scroll(val - 1);
    }
}, 500 );

P.S. Note, there is no reason to return anything from the setTimeout() callback as the return value is not processed by anything which is why I removed the return statement.


Navigating around ul li and looking for the active state on the current slide

It looks like you're looking for the index of the first child of $imageContainer with the active class. (Incidentally, your code will also trigger on stuff like inactive, which might be a false positive. Be careful about your classes!)

Native selectors work fine here. Furthermore, your initial assignment doesn't do things the jQuery way -- there's no reason to initialise two separate jQuery objects. Try replacing your block with something like:

$imageContainer = $(this).parent().children().first().children()
currentIdx = $imageContainer.index($imageContainer.filter(".active"))

Better yet, instead of that monstrous .parent().children().first().children(), give it a meaningful ID or class, so you can just do $imageContainer = $(".image-container", this).

If you can guarantee that the ul will contain only lis, then you can simplify further to currentIdx = $imageContainer.filter(".active").index().

Depending on your exact situation, you may even be able to replace everything with the one liner:

currentIdx = $(this).parent().find(".active").index()


I suggest to use following method name: isEmpty() instead of empty()
If your Java version > 1.5 you should use @Override for your toString() method.
Do you really need the the article in class field name like theData?
You don't need both size and topOfStack variables. theData.size is enough.


Passing a value from my Gruntfile to an external Grunt task

Since file is an object, and it has a constructor, that can be use to store the file path:

grunt.event.on('watch', function (action, filepath, target) {
    if (target === 'releases') {
        grunt.file.constructor.filepath = filepath;
    }
});

References

Why Composition is Harder with Classes – JavaScript Scene – Medium
grunt/file.js at master · gruntjs/grunt


The first snippet runs on any type returned by result.get, the second snippet needs the method to return a String. So it makes only sense to compare the snippets if result.get returns  a String. I assume so.

The type cast is a noOp in byte code. So the real difference is that the first snippet calls name.toString(), but the second uses name directly. The result is the same but the method call may be slower than the direct access to name.

If the first is really slower depends on the optimizing that will be done by the compiler and runtime environment. You should benchmark it with the version of java currently in use, if you are interested in the result.


Given a string S and Q query strings(q1,q2,...), check for each query string whether or not it is sub-sequence of S

Formatting

Everything inside your class body should be indented by one step further than it currently is.
Binary operators (+,-, ...) are usually surrounded by one space to make reading them easier

Outputting results
Your if-else statement can be easily replaced by a ternary statement because it IMO is too trivial to actually be worth the effort of reading 5 lines for it.
In other cases I'd advocate against using the ternary, but here it's just so crudely obvious I can't help but recommend using it.
Immutability
It's significantly cleaner to not allow changing your reference string after you read it in. Mark effectively final variables as final explicitly to ease reading.
After applying this handful of changes your code looks as follows:
public class Query {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(new InputStreamReader(System.in));
        final String str = scanner.next();
        int n = scanner.nextInt();
        while (n-- > 0) {
            String sub = scanner.next();
            System.out.println(isSub(str,sub) ? "Yes" : "No");
        }
    }
}


Generate a Bitcoin Address and the Wif from a phrase

If you're planning on running this repeatedly, you could try running this on PyPy, and see if the JIT starts to speed up some of the regions being run repeatedly.  That would be a low-effort way to try to get a performance improvement on long-running code.

Before doing any code changes, profile your current code.  That should tell you where the most gains are to be had.  Then you could move forward with optimizing with a lot more information.

And, it's possible that doing this in a language with a really good compiler for native machine code would get you faster results.  I would tend to think of OCaML in that context, but your milage may vary.


Restructuring and optimization

The initial approach introduces inefficient file processing as get_content function reads all lines from the input file into a list at once and holds that list in memory throughout the entire processing. The traversal of the lines that were read is then redundantly repeated in run_code function.The more efficient way is to convert get_content into a generator function and consume one line from file at a time on demand.

The optimized get_content function:

def get_content(file: str) -> List[str]:
    """
    Yields lines from the passed file path
    :param file -> str: File to read content
    :return List[str]: Content in file
    """
    with open(file, "r") as file:
        for line in file:
            yield line.rstrip()

run_code function is renamed to parse_code

Inefficiency of validating and traversing commands

In parse_code (formerly run_code) function the commands sequence is potentially being traversed twice:
once on correct_syntax(commands) call and then - on getting numbers chr(get_number(fish)) for fish in commands.Moreover, consequent validations in this case may lead to redundant calculations.Consider the following situation: commands contains 10 items, all of them passed correct_syntax check but then, the 9th item fails on get_number check. That causes 10 redundant operations/checks.

To optimize validations we notice that is_fish and get_number are conceptually dependent on the same context - "fish" and are intended to validate the same "fish" object.Thus, those 2 validations are reasonably combined/consolidated into one validation function is_fish:

def is_fish(fish: str) -> bool:
    """
    Validates "fish" item
    Fish: Starts with >< ends with > and has number inside
    A fish like so ><98g> will fail the check

    """
    return fish.startswith("><") and fish.endswith(">") and fish[2:-1].isdigit()

get_number function is now removed. The correct_syntax function is renamed to get_fish_numbers and its responsibility now is "Collect fish numbers from valid fishes":

def get_fish_numbers(pond: List[str]) -> bool:
    """
    Collects fish numbers with checking the syntax of the passed list of commands on the following criteria:

    Is a fish ><..>

    Correct Example:
    ><98> ><108> ><56>

    Incorrect Example:
    ><98> >><<76>> ><[108>

    """
    fish_numbers = []
    for fish in pond:
        if not is_fish(fish):
            sys.exit(f"Incorrect Syntax: {fish}")
        fish_numbers.append(int(fish[2:-1]))

    return fish_numbers

And finally the optimized parse_code function:

def parse_code(code: List[str]):
    """
    Parse and output the passed Fishy Code
    """
    for line in code:
        # Clean up code and separate commands#
        commands = line.split(" ")

        # Check if line has multiple statements in it
        fish_numbers = get_fish_numbers(commands)
        if len(fish_numbers) > 1:
            output = "".join(chr(num) for num in fish_numbers)
            print(output)
        else:
            print(chr(fish_numbers[0]))


Algorithmically speaking, there is no better way to find a matching password without considering characteristics of the password itself.  For instance, if you take into account the length, you could restrict the generated passwords to be only of that length.  If you consider the actual characters, then well, you already have the password, so you're done.  But neither of these seem to be true to the exercise, do they?

But what about parallelization?  After all, this task is trivial to parallelize.  Surely if we harness the processing power of all our cores, we will be able to chew through those passwords in lightning speed, right?

Ok, let's talk about that.  Suppose you have a machine with 24 cores.  If we parellelize, should get a speedup of 24, right?  Well, not quite, because there's always some overhead when you parallelize something, due to things like task coordination and so on.  So the actual speedup will be something less than 24.  But, for the sake of argument, let's assume we have an ideal system and we actually do see a speedup of 24.

Now, you said it took 2 days to find the password "password", right?  So with 24 cores, it now takes 2 hours.  "password" is 8 charaters.  So let's just say that we can find any 8 character password in 2 hours.  That's pretty good compared to 2 days!

But what about 9 character passwords.  If I counted correctly, there are 68 characters you use to generate passwords.  So the set of all 9 character passwords will be 68 times larger than the set of all 8 character passwords.  So generating all 9 character passwords will take 68*2 hours = 136 hours = 5 days + 16 hours.  Ouch!

So what now, purchase more machines?

By the way, the maximum password length you examine is 15.  There are 68^15 passwords of that length.  8^15 is 3,073,503,348,387,795,563,479,826,432.  To examine this number of passwords will take 6,722,988,818,432 times longer than it takes to examine all 8 character passwords.  And yes, that's 6.7 Trillion.  It would about 1.5 Billion years to examine all those passwords on our 24-core machine.  I don't know how old you are, but suffice it to say that if you plan on obtaining the results before you expire, you're going to need a lot more machines.  If you do plan on doing this, please let me know what server provider you'll be using ... I'd love to invest in them!

So, the bottom line is, the only way to brute force something is through brute force.  Parallelization can help, but only if the problem is tractable to begin with.  The power of exponentiation will win every time.


How to make this code fit into the base class

You can create an abstract method that will wrap the GetXXXAsync() method:

public class BaseClass<T>
{
    protected void Getitems()
    {
        // some preparation code here which is the same for all sublcasses

        GetItemsInternal(a =>
        {
            // same code here for all sublclasses
        });
    }

    // probably needs a better name
    protected abstract void GetItemsInternal(Action<EntityResultArgs<T>> operationComplete);
}

public class DerivedClass : BaseClass<SomeType>
{
    protected override void GetItemsInternal(Action<EntityResultArgs<SomeType>> operationComplete)
    {
        _model.GetXXXAsync(operationComplete);
    }
}


This design pattern is known as a Singleton, and you can read more about them here.

It's super easy to set up a singleton in Swift, and when I use this pattern I forward all method calls to the shared instance of the class.

class Singleton {
    static let sharedInstance = Singleton()

    // type method (aka class method), allows for easy-access code
    class func doSomething() {
        // forward the method and any parameters to the shared instance
        sharedInstance.doSomething()
    }

    // instance method, visible through Singleton.sharedInstance
    func doSomething() {
        println("Did something.")
    }
}

And the usage would be like so:

Singleton.doSomething()
Singleton.sharedInstance.doSomething()

(Both call the same method, just the first one is more concise)

Notes:

Apple is calling class methods in swift type methods
I use camelCaseForMethodNames because it is a convention (instead of CapitalizingEveryWord like class names)
People tend to have mixed opinions about Singletons (read more about that here, if you desire).


First off, this is buggy. If one of the input arrays is empty, you'll get an ArrayIndexOutOfBoundsException - and even if you correct that error, the iterator will stop if it encounters an empty array.

Consider using proper tests with multiple scenarios, especially with edge cases, in order to catch errors like that.

Then I get two warnings from Eclipse (other compilers and their settings may differ, but I believe these are "common" warnings, that normally would be raised). You should never have warnings. Code should preferably be adjusted or rewritten to avoid them, or at the very least (if you have a good reason to keep the warning) annotated with @SuppressWarnings and commented on with those reasons.

1) Due to the use of generics together with variable arguments the GlueArrays constructor should have the annotation @SafeVarArgs.

2) The instantiation of the iterator in iterate() is lacking its type parameters. It should be

return new GlueArrayIterator<T>(arrays);

or, if you are at least using Java 1.7, just

return new GlueArrayIterator<>(arrays);


As a general rule, I'd tend to prefer the built in C++ bool over the Windows-specific BOOL.

Your sanitizePath seems less than ideal, at least to me. Passing them parameter by reference, then creating a local copy from the reference seems like kind of a waste. If you want a local copy, just pass by value. Regardless of that, std::string already provides a function to search for the position you want, so I'd probably use that.
 std::string sanitizePath(std::string const &input) {
     auto pos = input.find_last_not_of("/\\");
     return input.substr(0, pos+1);
 }

After a few decades of using C++, I've gotten to the point that almost any time I see an open and matching close operation, my immediate reaction is to use RAII--define a class that does the open in its ctor, and the matching close in its dtor. It looks to me like file searching fits this pattern, and probably benefits from the RAII treatment.

Likewise, if I'm going to iterate through a collection of objects, my reaction is to think about whether I can define an actual iterator, so I can off-load as much work as possible onto standard algorithms (and such).

I'd avoid using std::endl. In this case, it probably doesn't make a huge difference, but I'd still form the habit of using '\n' when you want a new-line.

You might want to consider using a std::filesystem::recursive_directory_iterator, which already implements an iterator interface for file searching. Using it, the code for findFiles would reduce down to something like this:
 int findFiles(std::filesystem::path const& fspath, const std::string& fs)
 {
     std::filesystem::recursive_directory_iterator di { fspath };
     int count = 0;

     for (auto const& file : di) {
         if (file.path().filename() == fs) {
             std::cout << file.path().string() << "\n";
             ++count;
         }
     }
     return count;
 }


using the TaskObservableExtensions from System.Reactive.Threading.Tasks (in the Rx Linq DLL) it is easy:

IObservable<List<SearchResult>> observable = Search(queryString).ToObservable()

I'd consider the code there to be "correctly written" (I'm in no way linked to the code nor its authors.)

If you want to rewrite your Search method to work directly with Observables I'd recommend using their full power:

private IObservable<SearchResult> Search(string query)
    {
        return Observable.Create<SearchResult>(
            (observer, cancellationToken) => Task.Factory.StartNew(
                () =>
                {
                    foreach (TestsGroupMeta group in Engine.Groups)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        string name = group.ToString();
                        if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
                        {
                            observer.OnNext(new SearchResult { Name = name, Type = "Group" });
                        }

                        foreach (TestMethodMeta method in group.Methods)
                        {
                            name = method.ToString();
                            if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
                            {
                                observer.OnNext(new SearchResult { Name = name, Type = "Method" });
                            }
                        }
                    }

                    observer.OnCompleted();
                },
                cancellationToken,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default));
    }

An observer is now able to process SearchResults as soon as they are found (as opposed to wait for the completion of the computation yielding all results at once) and can unsubscribe anytime which in turn will cause a cancellation of the result computation. If some function still needs all SearchResultsat once there's always Observable.ToEnumerable and friends. In addition, possible parallelization is now obvious (e.g. using Parallel.ForEach) but still not trivial (hinted at by the inclusion of TaskCreationOptions and TaskScheduler, sensible options for Parallel.ForEach not included). Also clients must then be prepared to consume 'out-of-order' search results.

Potential further improvements:

check for cancellation at more / more appropriate places
split Task/Observable logic and searching
handle (now asynchronous) errors (e.g. by trying the foreach and calling observer.OnError)
specify culture forToString
employ a more 'functional' style by leveraging SelectMany (suits my personal taste)

Otherwise you could at least use Observable.Start which gets rid of the otherwise unused observer:

private IObservable<SearchResult[]> Search(string query)
{
    return Observable.Start(() =>
    {
        List<SearchResult> result = new List<SearchResult>();
        foreach (TestsGroupMeta group in Engine.Groups)
        {
            string name = group.ToString();
            if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                result.Add(new SearchResult { Name = name, Type = "Group" });
            }

            foreach (TestMethodMeta method in group.Methods)
            {
                name = method.ToString();
                if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
                {
                    result.Add(new SearchResult { Name = name, Type = "Method" });
                }
            }
        }
        return result;
    });
}


A program that expands a list of maps and chooses a random element

You actually already fixed up the main thing that I was going to comment on: your previous use of def over let. Just to emphasize on why it's important to choose one over the other though:

(defn f []
  (def my-var 5))

(f)

(println my-var)
5  ; It leaked the state of the function and polluted the namespace

Beyond that, this isn't bad code. As I mentioned on SO, I'm a little rusty, so hopefully someone else will go a little more in-depth. I'll mention what I see here though:

This might be a little over-engineering, but I don't like how the asym-hobbit-body-parts definition is repeating the keys :name and :size over and over. This allows typos to slip in, and makes more work for you if you want to add more parts. I'd make a "constructor" that automatically creates the maps from the data:

(defn new-part [part-name part-size]
  {:name part-name, :size part-size})

(def asym-hobbit-body-parts [(new-part "head" 3)
                             (new-part "left-eye" 1)
                             (new-part "left-ear" 1)])

I like this because now there's a function that definitively says what a "part" is defined as, and if you ever want to change what keywords you use, you only need to change new-part now.

This still has duplication though, and could be reduced down with a helper that auto-wraps vector "tuples":

(defn new-parts [& name-size-pairs]
  (mapv #(apply new-part %) name-size-pairs))
  ; or (mapv (partial apply new-part) name-size-pairs))  ; Partially apply "apply"

(def asym-hobbit-body-parts3 (new-parts
                               ["head" 3]
                               ["left-eye" 1]
                               ["left-ear" 1]))

Or, if you want to get rid of the need for the wrapping vectors, you can use partition to cut a list of attributes into 2s:

(defn new-parts [& name-size-pairs]
  (->> name-size-pairs
       (partition 2)  ; Cut the list into pairs of 2
       (mapv #(apply new-part %))))

(def asym-hobbit-body-parts3 (new-parts
                               "head" 3,
                               "left-eye" 1,
                               "left-ear" 1))

It really depends on how you want it to read.

In case you aren't familiar with them, I highly recommend practicing use of -> and ->>. They seem a little complicated at first, but once you understand them, they have the potential to make your code much neater. They allow your code to read more easily as a series of transformations.

I think the reduction in make-sym-parts is too big. When I have a call to reduce with a large reducing function like that, I try to move it out into its own standalone function. That gives that code a name to make it clearer what it's doing, and makes the call to reduce easier to understand. I decided just to make it a local function using letfn. You could also make it a global function using defn; but I don't think that's necessary.

(defn make-sym-parts [asym-set num]
  (letfn [(transform-lefts [sink {:keys [name] :as body-part}]
            (if (str/starts-with? name "left-")
              (into sink (apply vector body-part
                                (for [i (range num)]
                                  (update body-part :name
                                          #(str/replace % #"^left" (str i))))))

              (conj sink body-part)))]

    (reduce transform-lefts [] asym-set)))

I also altered what you're doing in the for comprehension. You had a literal {:name ..., :size size} in there. This isn't good practice though. Pretend in the future you decide to add a new attribute to body parts. Maybe :quality or something. What happens if you forget to update make-sym-parts? Because you're reconstructing the map from scratch, the new body part will be discarded! update is like assoc, but it "updates" a previous value using a function instead of overwriting it like assoc does. The previous value is passed into the function, and the new value becomes whatever the function returns.

This could still be improved a bit by making use of mapcat. Right now, you're using reduce instead of map because in some cases, you need to add multiple entries per existing element. mapcat (basically short for "map then concatenate") can help here. It will automatically flatten the resulting list. This means you can get rid of the sink accumulator:

(defn make-sym-parts [asym-set num]
  (letfn [(transform-lefts [{:keys [name] :as body-part}]
            (if (str/starts-with? name "left-")
              [body-part
               (for [i (range num)]
                 (update body-part :name
                         #(str/replace % #"^left" (str i))))]

              [body-part]))]  ; Note how this requires a wrapping so it can be flattened

    (mapcat transform-lefts asym-set)))  ; Lazy!

The major drawback here is I wouldn't be surprised if this is slower. That likely isn't an issue though.

I was going to suggest you change rand-part to use reduce (I had a whole thing written up and everything!), then I realized that it requires knowledge of the next part in the list. It is still possible to use reduce, but it would require doing something messy like partitioning the list of parts into pairs, then reducing over the pairs. I think what you have here is likely neater.

I will mention though, just in case you didn't know, reduce allows for an early exit using reduced. If you didn't need to use remaining in the loop, that would allow your loop here to be written using reduce.

The only real two noteworthy things in rand-part are

I would use :keys here to deconstruct current. You're using explicit key-access a lot which adds some bulk.
(reduce + can also be written as (apply +. If you look at the definition of +, it and most other binary operators have a var-arg overload to delegates to a reduction. It's not a big deal either way. From what I've seen, (apply + is generally regarded as more idiomatic, but not by much.

Something like:

(defn rand-part [parts]
  (let [size-sum (apply + (map :size parts))
        thresh (rand size-sum)]
    (loop [[{:keys [name size]} & remaining] parts
           sum size]
      (if (> sum thresh)
        name
        (recur remaining
               (+ sum (:size (first remaining))))))))

Good luck and welcome to Clojure!


The answer to this question suggests the following:

''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))

It's close to your solution, but avoids having to type out the whole alphabet by using predefined values and avoids the use of map() and lambda.


Decompose any number to its prime factors raised to their respective powers

The problem with your prime generator is that you don't use the previously generated primes to check if a number is prime. The idea is that every non-prime number can be "prime factorized". Which also means that if a number can't be divided by the primes smaller than it, it's a prime number. For example, if you want to see if 13 is prime, you can check if it can be divided by 2,3,5,7,11 and since it can't be divided by any of those, it's prime. That's not a big improvement for small numbers, but for big numbers, it becomes a really good improvement since you already have those primes at hand. But for this to work, you need to generate primes from 2, not from i. It's also pretty standard that limits are exclusive when you pass integer intervals, so I've changed n+1 to n in the range, but feel free to undo this.

def gen_primes(n):
    #Let's give us an head start.
    primes = [2]

    for possiblePrime in range(3,n):
        for p in primes:
            if possiblePrime % p == 0:
                primes.append(possiblePrime)

    return primes

Now, you could modify this algorithm to check for [p for p in primes if p < n ** 0.5], but you'd need to check that this list isn't empty (for example if n = 3 when primes = [2]) and add the prime to your list. If you decide to implement this, you could use a more suited algorithm to filter the primes because your array is always sorted, which opens nice possibilities. Finally, to make this algorithm even smarter, we could transform it into a generator using the yield keyword. This way, you maybe wouldn't need to generate all primes to n if it's not necessary.

def gen_primes(n):
    #Let's give us an head start.
    primes = [2]
    yield 2

    for possiblePrime in range(3,n):
        for p in primes:
            if possiblePrime % p == 0:
                primes.append(possiblePrime)
                yield possiblePrime

This way, for example, if you use gen_primes(512) to find the prime factorization of the number 512, you would only yield 2 and not all other primes between 2 and 514 (because \$512 = 2^9\$ That's a great improvement!

The rest of your algorithm would change to something like this :

n  = int(x ** 0.5)
prime_factors = []
prime_exponants = []

for prime in gen_primes(n):
    if x == 1:
        return

    e = 0
    while x % prime == 0:
        e += 1
        x /= prime

    if e > 0:
        prime_factors.append(prime)
        prime_exponants.append(e)

The main advantage of this is that you only generated the primes you need, no more, no less.

Now let's talk coding style : The python standard is snake_case, you used camelCase. It's not the end of the world, but standards are important. At least you're consistent (you didn't mix styles), which in my opinion makes it okay.

You use a lot of single letter variable names in your algorithm, it makes it harder to read. You shouldn't be shy to use meaningful names it's much easier for everyone (including yourself) to understand and debug the code.

Last thing it that I think the order in which your code is is confusing. You have code -> functions -> code, I think it'd be clearer if you defined your functions at the top of your file (obviously, after import).


You have a couple of options here depending on how explicitly you want to couple this view to the "push" action.

One option which I like is to rely on the existing responder chain. This gives you a lot of flexibility to allow views to emit events from anywhere in the view hierarchy and handle those events in a parent view, view controller, or the app delegate. I like that it avoids the overhead of connecting cells to view controllers (either through target action patterns as you have now or through a delegate protocol) but with the tradeoff that it becomes less obvious which class will respond to an event and requires more integration testing.

// Traverse the responder chain looking for the first responder who conforms to a provided generic type
extension UIResponder {
    func handoffEvent<T>(@noescape eventHandler: (T) -> Void) {
        var nextResponder: UIResponder?
        nextResponder = self
        while((nextResponder) != nil) {
            if let responder = nextResponder as? T {
                eventHandler(responder)
                return
            }
            nextResponder = nextResponder?.nextResponder()
        }
        // FIXME: you probably want some warning if you fail to find a responder of the expected type
    }
}

// Define a protocol for our responder
protocol ControllerRouter {
    func pushUserProfileViewController(user: User)
}

// Views can then send events up the responder chain to be handled by some responder who adopts our protocol but the view doesn't need to know anything about who that responder is
class SomeCustomView: UIView {
    @IBAction func didPressProfileButton() {
        self.handoffEvent { (handler: ControllerRouter) in
            handler.pushCurrentUserProfileViewController(self.user)
        }
    }
}

// Some class in the responder chain needs to implement our protocol to handle the event
class ViewControllerOrAppDelegateOrWhatever: ControllerRouter {
    func pushCurrentUserProfileViewController(user: User) {
        guard
            let navigationController = self.navigationController,
            let profileViewController = self.storyboard.instantiateViewControllerWithIdentifier("profileView") as? ProfileViewController
        else {
            // FIXME: do not ignore unexpected nils
            return
        }
        profileViewController.user = user
        navigationController.pushViewController(profileViewController, animated: true)
    }
}


Use immutable sequences
Turn
NAMES = ['Jimmy', 'Samie', 'Elani', 'Aron', 'Emir', 'Sven', 'Nelson',
         'Antonio', 'Isabel', 'Wally', 'Li', 'Noam', 'Francis', 'Danya',
         'Danny', 'Engine']

RATINGS = [600, 900, 400, 700, 1000, 1100,
           1300, 1500, 1600, 1800, 2000,
           2200, 2300, 2650, 2500, 1000]

into tuples instead of lists, because they're constants.
Use data classes
class Player:
    """This class holds the player information"""

    def __init__(self, name, rating):
        self.name = name
        self.rating = rating
        self.opponent = None

    def __repr__(self):
        return 'Player({}, {})'.format(self.name, self.rating)

does not need an explicit __init__ if you make it a @dataclass:
@dataclass
class Player:
    """This class holds the player information"""
    name: str
    rating: int
    opponent: Optional['Player']

though I don't think that it's appropriate to represent opponent as an attribute of a player. That belongs to the game state.
Sequence representation
Consider changing
    self.tournament_rounds = {1: 'Round 1', 2: 'Round 2', 3: 'Semi-final', 4: 'Final'}

into a global (or class-static) tuple of strings:
TOURNAMENT_ROUNDS = ('Round 1', 'Round 2', 'Semi-final', 'Final')

The indices as keys are redundant.
Iterators and responsibilities
def next_round(self):
    """Go the next round of the tournament"""

    self.game_round += 1

    try:
        print(self.tournament_rounds[self.game_round])
    except KeyError:
        return

and
            print(f'{player.name} wins this round by checkmate')
            player.rating += self.game_round * 200

seem dicey to me in terms of OOP representation. You'd be better-off having the game class yield a generator of rounds. This will make the game instance reusable.
Your score_game has the following responsibilities baked in - game simulation, and game presentation. These need to be separated - your score_game should not be printing. Also, score_game is itself not a great name, since it's not just scoring the game - it's actually running the game simulation.
Random selection
        maximum_range = 1000
        player_range = [i for i in range(0, int(player_chance * maximum_range))]
        choice = random.randint(0, maximum_range)
        if choice in player_range:

needs to be re-thought. Currently you're constructing a list, in memory, of every single number from 0 through (up to) 1000 only to do a membership test and then throw the whole thing away. Instead, just generate a random number and compare it to an upper bound.
Sleepy code
Don't arbitrarily add sleep. If you want to space out your console interface between logical operations, wait for a keypress.
Suggested
"""Chess Game simulator"""

from dataclasses import dataclass
from random import shuffle, randrange
from typing import ClassVar, Tuple, Iterable, Dict

@dataclass
class Player:
    name: str
    rating: int

    def __str__(self):
        return f'{self.name}({self.rating})'

CHESS_PLAYERS = [
    Player(name, rating)
    for rating, name in (
        ( 600, 'Jimmy'),
        ( 900, 'Samie'),
        ( 400, 'Elani'),
        ( 700, 'Aron'),
        (1000, 'Emir'),
        (1100, 'Sven'),
        (1300, 'Nelson'),
        (1500, 'Antonio'),
        (1600, 'Isabel'),
        (1800, 'Wally'),
        (2000, 'Li'),
        (2200, 'Noam'),
        (2300, 'Francis'),
        (2650, 'Danya'),
        (2500, 'Danny'),
        (1000, 'Engine'),
    )
]

class Match:
    def __init__(self, p1: Player, p2: Player):
        self.p1, self.p2 = p1, p2
        total = self.p1.rating + self.p2.rating
        if randrange(total) < self.p1.rating:
            self.winner = self.p1
        else:
            self.winner = self.p2

    def __str__(self):
        return f'{self.p1} vs {self.p2}'

    @property
    def outcome(self) -> str:
        return f'{self.winner} wins this round by checkmate'

class Round:
    def __init__(self, name: str, matches: Iterable[Match]):
        self.name = name
        self.matches = tuple(matches)

    def print(self):
        print(self.name)
        print('-'*45)
        print('\n'.join(str(match) for match in self.matches))
        print('-'*45)
        print('\n'.join(match.outcome for match in self.matches))

class ChessGame:
    ROUND_NAMES: ClassVar[Tuple[str]] = ('Round 1', 'Round 2', 'Semi-final', 'Final')

    def __init__(self, players: Iterable[Player]):
        self.players: Tuple[Player] = tuple(players)

    def __iter__(self) -> Iterable[Round]:
        players = list(self.players)

        for i_round, name in enumerate(self.ROUND_NAMES):
            shuffle(players)
            half = len(players)//2
            round = Round(
                name,
                (
                    Match(p1, p2)
                    for p1, p2 in zip(players[:half], players[half:])
                )
            )
            yield round

            for match in round.matches:
                match.winner.rating += (i_round + 1) * 200

            players = [match.winner for match in round.matches]

    def print_run(self):
        for round in self:
            round.print()
            print()

def main():
    sim = ChessGame(CHESS_PLAYERS)
    sim.print_run()

if __name__ == '__main__':
    main()

The biggest 'gotcha' here is that, whereas the ChessGame is now reusable, player instances (just as in your original code) are mutated, so if you want to do repeated simulations you have to make copies of your player instances.


Ignore nil values and unwrap optionals returning the value as the wrapped type

There is already a function in reactiveSwift that you can use:

 .skipNil()


Creating a grid to the specified size using lists

Grid creation

You know about list-comprehensions, but you use a default value before filling your rows with zeroes. You could do it in one go:

grids = [[0 for _ in range(gridSize)] for _ in range(gridSize)]

which can be simplified to

grids = [[0] * gridSize for _ in range(gridSize)]

Grid printing

The for loop in Python is meant to be used to iterate directly over elements rather than indices:

for row in grids:
    print(row)

Function parameters

It is bad practice to rely on global to share data accros functions. You should define those function to accept parameters instead.

This let you also extract input handling from your grid creation function which is also better as let you have a single responsibility per function:

def ask_size():
    while True:
        try:
            grid_size = int(input("input grid length and width\n"))
            if grid_size < 2:
                print ("invalid int")
            else:
                return grid_size
        except ValueError:
            print ("invalid input")

def make_grid(size):
    return [[0] * size for _ in range(size)]

def print_grid(grid):
    for row in grid:
        print(row)

grids = make_grid(ask_size())
print_grid(grids)

Exception handling

Python have else clauses that are executed when the try part succeeded. The aim is to reduce the amount of code protected by the try to avoid catching unexpected exceptions. In your case, you could change that part to:

def ask_size():
    while True:
        try:
            grid_size = int(input("input grid length and width\n"))
        except ValueError:
            print ("invalid input")
        else:
            if grid_size > 1:
                return grid_size
            print ("invalid int")


Working with forms in Meteor, using selectors for every input

As far as I know, Meteor's reactivity is one-way: changes in data are reflected in the DOM. To go the other way (DOM to data) there's two common methods: 1) grabbing data directly from the DOM when it's needed (i.e. to save it) as you've done above and 2) binding DOM elements to data models, and using the data models for CRUD operations.

1 is simpler to implement, but 2 gives you more control over data-flow, subscriptions, and life-cycles. 2 has plenty of great libraries you can use, so you don't have to reinvent the wheel just to leverage these benefits. Backbone.js is probably the most well known plain-JavaScript library for this sort of thing (also check out Lo-Dash and Exoskeleton if you haven't), but the Meteor ecosystem may have a preferred library for this.


Simple factorial program using recursion

Recursion

It's good that you are trying to grasp recursion, the more programming patterns you understand, the better.

But I would disagree that you need to use recursion more often. Generally, it consumes more memory and iterative solutions tend to be faster as well.

As for your solution, I think that if (n == 1) would be clearer than if (n < 2) (also, n < 2 returns 1 for input 0, which is wrong), and I wouldn't save the return value in result, but return it directly.

Exceptions

In recur throwing an IllegalArgumentException makes sense (it is an illegal argument), but showing the dialog here doesn't make that much sense, I would move that to main.

Also, don't throw an exception you just caught without a reason. If you don't want to execute the following function, just put all code in the try and catch the different exceptions.

Other

recur isn't a good name. I would call it factorial or factorialRecursive.
I would wrap the show message code into a function, that way you could also easily exchange it for something else (like a print). If you then further wrap this up in an object, unit testing would also be easier.

Code

If you do all of this, the code would look something like this:

public static void main(String[] args) {
    int factorialNumber = 0;
    try {
        factorialNumber = Integer.parseInt(input("Which number should we compute the factorial of?"));
        print(factorialNumber + " factorial is " + factorialRecursive(factorialNumber) + ".",
                "Result");
    } catch (NumberFormatException nfe) {
        error("Input must be an integer!", "Error");
    } catch (IllegalArgumentException iae) {
        error(iae.getMessage(), "Error");
    }
}

public static int factorialRecursive(int n) {
    if (n < 0) {
        throw new IllegalArgumentException("n must be >= 0 but was " + n);
    }
    if (n < 2) {
        return 1;
    }

    return factorialRecursive(n - 1) * n;
}

public static String input(String message) {
    return JOptionPane.showInputDialog(null, message);
}

public static void print(String message, String title) {
    JOptionPane.showMessageDialog(null,
            message,
            title, JOptionPane.PLAIN_MESSAGE);
}

public static void error(String message, String title) {
    JOptionPane.showMessageDialog(null, message,
            title, JOptionPane.ERROR_MESSAGE);
}


Concatenate strings (originally binary) in 8-character chunks, 2 per row

You need to separate splitting the string into bytes from creating lines.

By following the Single Responsibility Principle it's much easier to optmize your code because you can focus on one unit at a time. Other benefits are: easier maintenance and easier testing.

(I call it just byte because it's 8 elements long)

Ok, so here you'll need two methods. The first one just creates a list of strings and can be greatly simplified because we can add each substring directly to the list.

public static IEnumerable<string> Bytify(this string value)
{
    var byteLength = 8;
    for (var i = 0; i < value.Length; i += byteLength)
    {
        yield return value.Substring(i, byteLength);
    }
}

There are many other methods for splitting the string into batches but that's not the point. It's about the SRP. If you have separate methods you can exchange the algorithm for another one without breaking or adjusting everything else. The method creating the lines will still work because it doesn't need to know how you create the list, it just requires one.

Done. Now you can work with the bytes.

The other method can build the lines. With some LINQ it's very easy to create each one. Notice that I also flipped the condition to be values.Count % 2 == 0 that I find is easier to understand.

public static string ToBytePairs(this IList<string> values)
{
    var text = new StringBuilder();
    var lineWidth = 2;
    var byteSeparator = " ";

    for (var i = 0; i < values.Count; i += lineWidth)
    {
        text.AppendLine(string.Join(byteSeparator, values.SkipFast(i).Take(lineWidth)));
    }

    if (values.Count % 2 == 0)
    {
        text.AppendLine(string.Join(byteSeparator, new[] { "60000000", "00000000" }));
    }
    else
    {
        // There is line break at the and already so we need to insert this one before it.
        text.Insert(text.Length - 1, $"{byteSeparator}00000000");
    }

    return text.ToString();
}

As a bonus a faster skip extension so that the entire list doesn't have to be enumerated.

private static IEnumerable<T> SkipFast<T>(this IList<T> values, int index)
{
    for (var i = index; i < values.Count; i++)
    {
        yield return values[i];
    }
}

The default Skip is not a super fast solution but it's enough for short lists. You can easily find Skip optimized for IList that uses indexes if your strings a very big and every second matters. Just don't optimize too much if you don't need to. Premature optimization is the root of all evil.

Example:

var input = "8111111182222222833333338444444499999999";
var bytes = input.Bytify().ToList();
bytes.ToBytePairs().Dump(); // Dump() is LINQPad's method.

Result

// 8111111182222222833333338444444499999999

81111111 82222222
83333333 84444444
99999999 00000000

or

// 81111111822222228333333384444444

81111111 82222222
83333333 84444444
60000000 00000000


Dont't use using namespace std;

Use consistent formatting:

Your vertical whitespace and indentation are inconsistent. That makes your code a little difficult to read.

Use of access modifiers

It is unnecessary to specify private as an access modifier at the top of your class as they are private by default. However it is common to list public members and functions first because anyone (including you) reading your code is going to be more interested in the interface for the class.

Omit return 0;

main() will return on its own at the end of its execution. It is considered standard practice not to return at the end of main() and the compiler will generate the appropriate return as needed.

Let RAII do its job

{
ofstream myfile;

// Definition on File Name: "MeinTest.wav"
myfile.open (FileName.c_str(), ios::out | ios::binary);

… // other code
//  File is writen so close
myfile.close();
}

The very next line after you close your file explicitly the scope ends. Your file will close itself on going out of scope and perform all necessary operations (like flushing and memory cleanup) A huge part of writing quality C++ classes is proper RAII cleanup so that you and I don't need to clean up after ourselves. Let your objects go out of scope instead of doing it explicity.

Only write meaningful comments

Most of your comments (like those in the previous example) only serve to state what is already clearly stated by the code itself. As a rule of thumb you should always assume that anyone reading your code is capable of reading code. myFile.close() should be readily apparent as to what it does. Only comment when something isn't easy to understand. (also consider refactoring or renaming when you find the need for a comment.)

Don't use All-cap variable names

char RIFF[] = "RIFF";
char WAVE[] = "WAVE";

All cap variables are conventionally reserved for macros. prefer instead:

char Riff[] = "RIFF";
char Wave[] = "WAVE";

or

char riff[] = "RIFF";
char wave[] = "WAVE";

Incidentally I am a bit uncertain about the current use case but I am unsure why you are using C-style char array[] (and not char* array[]) or a C++ string? is there a reason you can't use an std::string?

Use C++ casts

unsigned char a = (unsigned char)i1;
unsigned char b = (unsigned char)i2;
unsigned char c = (unsigned char)i3;
unsigned char d = (unsigned char)i4;

C++ static_cast<> is safer than C-style casts as it is checked at compile time. Also you should use C++ conventions when writing C++ code.

Concatenate your operations

long i = x;
int i1 = i % 256;
i = i - i1;
i = i / 256;
int i2 = i % 256;
i = i - i2;
i = i / 256;
int i3 = i % 256;
i = i - i1;
i = i / 256;
int i4 = i;

unsigned char a = (unsigned char)i1;
unsigned char b = (unsigned char)i2;
unsigned char c = (unsigned char)i3;
unsigned char d = (unsigned char)i4;

can be re-written:

int x1 = x % 256;
x = (x - x1) / 256;
int x2 = x % 256;
x = (x - x2) / 256;
int x3 = x % 256;
x = (x - x1) / 256; // did you mean to use x3 here? (well i3 in your code)
int x4 = x;

unsigned char a = static_cast<unsigned char>(x1);
unsigned char b = static_cast<unsigned char>(x2);
unsigned char c = static_cast<unsigned char>(x3);
unsigned char d = static_cast<unsigned char>(x4);

notice it was also unnecessary to copy x into a second variable. you can use it directly (it's already a copy)

Omit unused headers

You aren't using <iostream>. to that end you can omit it.

Compare values of the same type

for(float m = 0; m <= DataLeng; m++)

That line threw me off for a moment. I've never seen a float as a comparison within a for loop. Especially since DataLeng is an int. Your compiler should have warned you about this. To that end. . . :

Use max compiler warnings

Make sure you have max compiler warnings on. Consider warnings as error too. This will catch a lot of issues for you and help you clean your code before you even get to us. use -W4 on VS or -Wall on gcc/clang and -Werror. (If you use a different compiler you will have to look up how to better utilize warnings.)

Prefer prefix over postfix


This is a good unit test. It may seem like a trivial case to test a boolean response, but wrapping this in a test ensures that you always get the correct response. What if you decide to refactor the internals of BooleanToVisibilityConverter down the road? With this test, you can always be confident that it's behaving correctly.

To me, the two assertions look like they belong together. As a matter of style, you could split the test up so that you have two tests with a straight AAA (Arrange, Act, Assert) pattern - one for true, one for false. In my opinion, that would be a little excessive. I like a test that looks like this because it is clear and quick.

If you were writing a test of a converter that had many possible outputs and multiple input conditions (for example), then you definitely should consider splitting it up and testing each condition separately. For now, you're on the right track.


JobTypeLogic and JobType classes in MVC business logic

This feels bad to me:

private UnitOfWork unitOfWork = new UnitOfWork();

public JobTypeLogic()
{
    JobTypeEngine = unitOfWork.Repository<JobType>();
}

This begs for IoC/DI, otherwise I cannot see how you'd test your code.

JobTypeEngine.List.ToList();: I don't know what's worse, that you've got a property named List, or that it apparently isn't a List at all.

public IEnumerable<SelectListItem> JobTypeList { get; set; }: Does a SelectListItem belong in the BLL? Why isn't that a JobType instead, and why aren't you calling it JobTypes (especially since it is an IEnumerable and not a List)?

GetJobTypeList() doesn't seem to be used. It also again assigns JobTypeEngine even though this already happened in the JobLogic constructor.


If you want to make the code "easier to read and look neater", the first thing that I would do is to run it through an indenter. This is currently haphazard at best, and makes it difficult to follow.

The second thing I would do for ease of readabilty and maintenance is to extract the top portion of the Sub where you build the Headers array and calculate the column indexes into a function. This Sub is doing 2 things, and everything above 'retrieving information using Index Match can be treated as an atomic procedure.

I'd replace the string literals "" with the constant vbNullString - it's more readable and doesn't require a memory allocation. While you're at it, I'd get rid of all of the other magic numbers that you're using.  For example, FundingSheet.Rows(3) would be much more readable as FundingSheet.Rows(HEADER_ROW).

I'm not sure I understand why you declare AccountNumber As Variant, and then repeatedly cast it to a String with CStr(AccountNumber). If you're using it as a String, declare it as a String. Declare it as a String and then just cast it once when you assign it:

AccountNumber = CStr(Cell.Value)

Avoid 1 based indexing like Dim Headers(1 To 21, 1 To 2) unless there is a good reason to do so. The default array base is zero, you aren't setting the Option Base, and there is nothing in the procedure where having a base of 1 is relevant. All it does is add cognative load when you've scrolled down to the bottom of the Sub and trying to process the indexing.

Regarding the comment 'B/c there is no naming convention, many different static data names, you should consider passing the sheet name to the Sub as a parameter instead of hard coding it (presumably in a copied and pasted version of the procedure).  It isn't clear from your description if the same applies to the hard coded column headers, but those can also be passed as a parameter if they are not fixed (and would be another reason to extract the top portion as a function).

Performance

This code is slow because you are writing VBA code as if it were intended to be a function on a worksheet. If you need it to function independently (for example, in a UDF), that might be appropriate, but it is never going to be performant. Take a look at the top of the Sub. You're basically trying to build a lookup table, but then promptly discarding (or ignoring) the captured information later in the code and relying on Application.Index and Application.Match to get your column definitions in the correct order. This section (line break added for clarity)...

For i = LBound(Headers) To UBound(Headers)

    If Headers(x, 2) = "" Then
        x = x + 1
    Else
        Cell.Offset(0, x).Value = Application.Index(FundingSheet.Columns(Headers(x, 2)), _
            Application.Match(CStr(AccountNumber), FundingSheet.Columns(Headers(1, 2)), 0))
        x = x + 1
    End If

    If x = 22 Then Exit For
Next i

...is repeating the row lookup for every single column. That is incredibly inefficient. It might make sense if this was a UDF (and would be inefficient as a user function too), because each cell in a column would need to find the appropriate row. It's silly in this context though, because the Application.Match is going to return exactly the same thing for each of the 22 times that you call it.

For each account, you need to do two things; First, find the row that contains the account data, Second, copy the data based on the column lookup. I'd consider using a Scripting.Dictionary for the column lookup - you're doing a fairly simply column mapping between source column and destination column, so once you have the mapping built you can do lookups on that instead of repeatedly using Application.Index. Find the row target row once before you loop through the Headers array, and then just map the columns to the correct destinations. That would be a huge first step in improving the performance.

That said...

You're using Excel as if it was database. The real solution would be to use an actual database as a back-end and use Excel to simply present the data. If you can't do that for some logistical reason (IT resistance, for example), then stop treating Excel as a spreadsheet when you retrieve data from it. Open an ADO connection, and just query for your lookup results. ADO doesn't care about the column order, and you can just request columns by name and write them where they need to go. This is going to be way faster than using the Excel lookups (the driver is optimized for this), and you can request multiple results in one operation.

If Excel is your "database", then take advantage of the database tools that are available.


Returning a different but similar "increasing" string depending on instance argument

The easiest way is to add a method to the ScreenViewer class which returns the page value, eg:

public abstract class ScreenViewer {
    public abstract int getPageCount();
}

public class ScreenViewerPage1 {
    @Override
    public getPageCount() {
        return 1;
    }
}

private getDescription(ScreenViewer o) {
    if(Utils.isTotalPagesVisible()) {
        int total = 5;
    } else {
        int total = 3;
    }
    return "Description:" + o.getPageCount() + " out of " + total ;
}

But I would rethink your whole approach. What if you want to add ScreenViewerPage6? It's hard to say how exactly your code could be rewritten without knowing how the classes look, but I would assume that it should be possible with lists, etc.

Misc

Your indentation is off.
o is not a good variable name.
use else if when appropriate.
I would not hardcode magic numbers such as 5 and 3.


Show image when in viewpoint of browser window

Correctness

You need to handle resize events also. Yes, you can add it like : $(window).on('scroll load resize', ...
You are only checking for the visibility of the top/left corner, if you load a large image, scroll right, and then scroll down, you will see the right edges of the ALT text of the images, but because their top/left corner is not in viewport, those images will not load. You might want to check if any point of the img box is visible.

Browser Behavior

Make sure you have <!DOCTYPE HTML> on your document, this will load all images if you miss doctype declaration. (for Firefox, Chrome, don't know about others)
You might want to mark images processed, by adding a class or another data; and do not fiddle with the src attributes of the images once they are loaded.

Javascript related

Because you miss a var before $eleImage and elementOffset, they pollute global namespace.
You copy the value of $(this) here : $eleImage = $(this), but you keep using $(this) below.


MVC OnActionExecuted - session cookie - expire after x minutes of inactivity

The ideal and correct way is to create a class that inherits ActionFlterAttribute and override OnActionExecuting method. Then register it in the GlobalFilters in Global.asax.cs.

Finally do not use Add but use Set method. Why? Below is from MSDN and explains what the difference is:

  The Set method first checks to see if a cookie already exists in the collection and if so updates it. The Set method does not allow duplicate cookies in the cookie collection. To add duplicate cookies in the cookie collection, use the Add method.


Bash script to create directories and files with a numbered prefix

tail must to read the whole file. Calling sort with a -r (aka --reverse option) you can use head instead.
touch takes multiple arguments. You may

touch $DIRNAME/first.txt $DIRNAME/second.txt $DIRNAME/third.json

and further use brace expansion:

touch $DIRNAME/{first.txt,second.txt,third.json}

I would consider here-documenting the json files instead of echoing them, along the lines of:

cat << EOF >> $DIRNAME/test.json
{
     "enabled": true
}
EOF


Correctness. It is possible that Vitaly on his way picks up multiple keys of the same kind. Your code implies that there is no more than one of each kind.
Performance. As suggested in comments, conversions back and forth from lists to sets are expensive. A dictionary key_type: key_count is most likely what you need.


Speed up a while loop that conditionally creates a new variable in R

Do not use explicit loops unless you absolutely have to

Many functions in R are vectorized and your code will be much faster if you leverage this instead of writing your own loops.

For example, you can compute the first part of your newID with a single paste() call:

dat$newID <- paste("Ind", dat$ID)

    x ID change newID
1   1  0      0 Ind 0
2   2  0      0 Ind 0
3   3  0      0 Ind 0
4   4  0      0 Ind 0
5   5  0      1 Ind 0
6   6  0      0 Ind 0
7   7  0      1 Ind 0
8   8  0      0 Ind 0
9   9  0      0 Ind 0
10 10  0      0 Ind 0
11  1  1      1 Ind 1
12  2  1      0 Ind 1
13  3  1      0 Ind 1
14  4  1      0 Ind 1
15  5  1      1 Ind 1
16  6  1      0 Ind 1
17  7  1      1 Ind 1
18  8  1      0 Ind 1
19  9  1      0 Ind 1
...

The second part of your newID is simply the cumulative sum of change

The most tricky part here is to reset the counter each time the ID changes. A way to do this is to use the function by, which will execute a given function on a group of rows depending on the values of a grouping variable (here ID):

by(dat, dat$ID, function(x) {
  cumsum(x$change)
})

dat$ID: 0
 [1] 0 0 0 0 1 1 2 2 2 2
---------------------------------------------------------------------------------------------
dat$ID: 1
 [1] 1 1 1 1 2 2 3 3 3 3
---------------------------------------------------------------------------------------------
dat$ID: 2
 [1] 1 1 1 1 2 2 3 3 3 3

The two issues here are:

by returns a list so we have to use unlist() before trying to put the result in a data.frame column

dat$newID <- unlist(by(dat, dat$ID, function(x) {
  cumsum(x$change)
}))

because change doesn't start with 1, the values for the first ID are shifted by one. We can fix this by changing the first value manually.

Put everything together

dat$change[1] <- 1

dat$newID <- unlist(by(dat, dat$ID, function(x) {
  cumsum(x$change)
}))

dat$newID <- paste0("Ind ", dat$ID, "|", dat$newID)

And you get exactly the output you were asking for, without any explicit for loops!


Listing skills for role-playing characters

It might be a bit cleaner if you introduce a new class (or struct) containing both AttackSkillData and SkillAttackType.

Consider something like this;

public class AttackSkill
{
    public AttackSkillData data;
    public SkillAttackType type;
}

And consider adding a List<AttackSkill>() instead of five different lists.

Your code should then look like this;

public class SkillsComponent
{
    private List<AttackSkill> skills = new List<AttackSkill>();

    public SkillsComponent(List<AttackSkill> listOfAllSkills)
    {
        this.skills = listOfAllSkills;
    }

    public void AddNewSkill(SkillAttackType skillAttackType, AttackSkillData data)
    {
        skills.Add(new AttackSkill{ type = skillAttackType, data = data});
    }

    public List<AttackSkill> GetListOfLearnedSkills(SkillAttackType skillAttackType)
    {
        return skills.Where(s => s.type == skillAttackType).ToList();
    }
}

You can then acces any type of skill using a Where() where needed. For example, to get all skills having SkillAttackType.Strike;

List<AttackSkill> strikeSkills = skills.Where(s => s.type == SkillAttackType.Strike).ToList();

It will make your code less noisy and you will be rid of the switch. Double score!


It looks to me, that your problem could do with a bit more LINQ and the string concatenation operator.  Specifically the group clause.  Here's one way it could be done:

public static string Method2()
{
    List<int> sample = new List<int> { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };

    var data = String.Join(", ", (from int i in sample
                                 group i by i into g
                                 select $"({g.Count()}) {Cache[g.Key.ToString()]}"));

    return data;
}

The efficiency, I think would be better than what you have so far,the Distinct and each Count are extra iterations over the data, but, it would have to be tested to be sure.

It definitely has the advantage of being more concise.

Having the string format in one place makes it easier to see what's happening.

If you need the data parsed, instead of one long string, at some point, removing the String.Join part will leave an IEnumerable<string>.


Levenshtein Distance of transitively similar words

First of all, this is not a Python issue. Rather this is an issue of the implementation itself.

I agree with @Gareth Rees . You should always provide a minimally working example of the code. This is true for StackOverflow and especially true for CodeReview. In that respect all we can review is the little snipped you provide under the assumption that the functions you don't provide do certain things.

The first thing that you can cut is the else: block. It enters iff the last element of neighbors is in already_in_set and what it does is it adds the last element of neighbors to already_in_set; in other words: nothing. As a side effect you do pop the last element and since you do it in both cases it is better allocated above the if.

It looks like search(tree, temp) will return an iterable thing containing all rank 1 neighbors of temp. If you don't do any caching, search is incredibly slow! Loosely speaking that's O(len(dictionary.txt) * max([len(word) for word in dictionary.txt])^2) for the naive implementation and O(max([len(word) for word in dictionary.txt]) * depth(tree)) for the one given in the blog post you mention.

To make matters worse, you do this for every friend of a word exactly one (since you prune duplicates). So what your running is O(len(dictionary.txt)*max([friends(word) for word in dictionary.txt])*O(search)) which in the very crudest worst case can be O(len(dictionary.txt)^4) (!); although this case is only relevant for theoretical considerations.

Here is a list of things you can do:

Cache the Levenshtein distance of two words; also you don't need the actual value, rather the result of the expression distance <= 1 so there is room for more optimization. Also this is symmetric: distance(a,b) = distance(b,a) so you can cache two values for every computation
Cache the result of search(tree, temp). Again this is symmetric: if b in search(tree,a) then a in search(tree,b) so you can cache this result for every element of search(tree,a) without ever computing them [note that this is reflexive too: a in search(tree,a)]
Cache the result of find(keyword). find defines a group relation on dictionary.txt; hence if b in find(a) and c in find(a) then also: a in find(b), a in find(c), c in find(b), b in find(c). You can simply cache this number for every element in the network of a.

Doing all these things will reduce worst case performance to
O(O(find)+O(search)+O(distance)) = O(len(dictionary.txt)^2) and should make it substantially faster. You could think of ways to reduce the number of computations needed for search and distance potentially reducing the overall complexity, but I didn't think into this further.


You ask:

Should I assign each string to a variable? Many strings are not shared and will only be used once.

Obviously, in the other case, where the string is reused/shared, then of course one would (and should) define the constant/pointer once rather than ever repeating the same string literal in multiple places. This makes code easier to maintain.
You might also use constants/pointer to centralize the definition of all the possible keys in one place. E.g. if the string literals define possible key names used in some web interface, we might want to put all these key names in one place, making it easier to keep track of the API.
But if the strings are not shared and there is no organizational benefit to centralizing these definitions, then no, one would not assign each string its own variable.

Is it worth modifying like this?

If you are asking whether you should convert this ...
- (UIImage *)appleImage {
    UIImage *image = [UIImage imageNamed:@"apple.png"];
    return image;
}

... to the following ...
- (UIImage *)appleImage {
    static NSString *name = @"apple.png";
    UIImage *image = [UIImage imageNamed:name];
    return image;
}

... then the answer is, no, there is little benefit in doing do.
I would advise against pulling the string literal into its own local NSString pointer just for the sake of it. It just adds syntactic noise in this case. Yes, there are cases where one might pull the literal into its own line for the sake of clarity, but that not is not the case here.
The governing principles are code maintainability and readability.