BFS implementation to find connected components taking too long

First of all, two things to read or search for: Cluster analysis (just a hint, I'm not an expert about that) and Linked: The New Science of Networks by Albert-László Barabási.

Barabási in his book shows that networks usually have some nodes which have a lot more connections than the others. The distribution is not the same in the real world as the sample shell script generates.
The code is quite good, I like your variable and method names and separated methods. I wonder why haven't anyone reviewed it yet.

Vector<Set<String>> friendBuckets = bucketizeEmployees(employees);

I'd use a simple List or ArrayList here. Vector is considered obsolete.
In the getConnectedFriends method the

Set<String> queuedFriends = new LinkedHashSet<String>();

could be a Queue. It has a poll method. As far as I tested it's faster than the currently used iterator-based remove.

public class Main {

Main isn't a good class name. Everyone can have a Main. What's it purpose? Try to find a more descriptive name.

static HashMap<String, Set<String>> friendShips;

HashMap<...> reference types should be simply Map<...>. See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces

Should I always use the private access modifier for class fields?; Item 13 of Effective Java 2nd Edition: Minimize the accessibility of classes and members.

 static HashMap<String, Set<String>> friendShips;

Instead of Map<String, Set<String>> you could use Guava's Multimap (doc, javadoc) which was designed exactly for that. It would reduce the size of the mapFriends method:

public static void mapFriends(final String friendA, final String friendB,
        final Multimap<String, String> friendsShipMap) {
    friendsShipMap.put(friendA, friendB);
}

So, it could be removed.

public static Vector<Set<String>> bucketizeEmployees(Set<String> employees) {
    ...
}

This method calls getConnectedFriends(employee), which is the following:

private static Set<String> getConnectedFriends(String friend) {
    ...
}

It's confusing: what is the difference between an employee and friend? Are they the same?

if (friendShips.get(friend) != null) {

The following is the same:

if (friendShips.containsKey(friend)) {

A guard clause would be even better.

if (!friendShips.containsKey(friend)) {
    return connectedFriends;
}

if (!connectedFriends.contains(directFriend) && !queuedFriends.contains(directFriend)) {
    queuedFriends.add(directFriend);
}

The !queuedFriends.contains(directFriend) condition is unnecessary, it's a set which can't contain elements twice and adding an already added element to a LinkedHashSet doesn't modify anything. From the javadoc:

  Note that insertion order is not affected if an element is re-inserted into the set.

The following pattern occurs more than once in the code:

if (map.containsKey(key)) {
    String value = map.get(key);
    ...
}
...

It might be a microoptimization, but if you profile the code and the results shows it as a bottleneck the following structure is the same:

String value = map.get(key);
if (value != null) {
    ...
}
...

A few guard clause would help to make getConnectedFriends more flatten:

while (!queuedFriends.isEmpty()) {
    final String poppedFriend = getHeadElement(queuedFriends);
    connectedFriends.add(poppedFriend);
    if (!friendShips.containsKey(poppedFriend)) {
        continue;
    }
    for (final String directFriend: friendShips.get(poppedFriend)) {
        if (connectedFriends.contains(directFriend)) {
            continue;
        }
        queuedFriends.add(directFriend);
    }
}


C binary number converter (Hex and Decimals)

First things first, props to you for learning good old C in the day of dynamically typed high level languages! Now on to the review...

Error checking

Right now, there's nothing to stop me from entering 512351 as the seventh digit, for example. As a rule of thumb, if something comes from user input, double-check it. Your user is the greatest threat to program integrity. For example, check the input in a loop and only save it once it is a valid bit (0 or 1), if it's not valid, simply ask your user again. But this takes me to the next issue...

Input

Right now, you ask for each bit separately. I'm lazy. I wouldn't want to have 16 keystrokes to enter 8 digits. So, instead of asking for each bit on its own, consider just asking your user to type the digits as a string. Instead of eight integer variables, you could store them (temporarily, that is) in an array of characters. See the following snippet:

char input[8 + 1 + 1]; // 8 characters + newline + null terminator

printf("Enter a binary number: ");
fgets(input, sizeof input, stdin);
input[8] = '\0'; // We don't want the newline

This reads a line from standard input and stores the first 9 characters - 8 bits and a newline - in the array input, as well as a '\0' to terminate the string.

Now this is way shorter!

Conversion to decimal

But now that you have your digits as characters in a array, the conversion has to change. You can even be fancy and make your conversion more generic, in case you want to handle arbitrarily long numbers one day.

A typical idiom to get the numeric value from a character is int number = char - '0'; This subtracts the ASCII value for the character 0 from the character you have, leaving for example '5' as the integer 5. This will get strange when you use non-digit characters, of course. But you've checked that beforehand, I hope!

What's left is looping over your characters and adding their digit values to the total value.

int decimal_value = 0;

for (int i = 0; i != 8; ++i) {
    int digit = input[i] - '0';
    int factor = pow(2, 7 - i);

    decimal_value += digit * factor;
}

But since your binary digits are always either 0 or 1, you could tweak this a bit to prevent adding 0 a bunch of times.

int decimal_value = 0;

for (int i = 0; i != 8; ++i) {
    if (input[i] - '0') {
        decimal_value += pow(2, 7 - i);
    }
}

If the current character processed is '0', input[i] - '0' will evaluate to 0, which is falsy - the body of the if will not be executed. Otherwise, it is non-zero, which leads to the if-body being executed. Nice!

Conversion to hex

Right now, you do two things which should not be done together. You store the hex-digits as integer value, but once they're larger than 10 you store a character instead. This... works, but it's unusual and not that great. Instead, convert both two characters! The actual conversion is left as an exercise for you, but once you have both digits stored as first_hexdigit and last_hexdigit for example, you could to this:

char hex[2]; // Since we have two digits, let's store those as an array.
             // Note that, in contrast to before with input, we do not
             // have to make the array one larger than it needs to be,
             // as we do not use fgets which appends an extra character.

hex[0] = first_hexdigit >= 10 ? first_hexdigit - 10 + 'A'
                              : first_hexdigit + '0';
hex[1] = last_hexdigit >= 10 ? last_hexdigit - 10 + 'A'
                             : last_hexdigit + '0';

If you have never used it before, the ? and : are the ternary operator. Basically, a ? b : c means: if a is a truthy value, then return b, else c. Or, in other words:

int result;
if (a) {
    result = b;
} else {
    result = c;
}

To convert from a numeric value to a character, we switch our previous idiom around a bit: instead of subtracting our lowes character, we add it as value. If last_hexdigit is 6, for example, this becomes 6 + '0' which is just '6'. But if it's 12, the computation is 12 - 10 + 'A', which is 2 + 'A' which is 'C'.

Output

Since you've stored your results a bit differently, your way of printing has to be changed as well!

Assume we have our decimal value stored, as integer, in decimal_value and our hexadecimal as array of two characters in hexadecimal_value.

int decimal_value; // Your decimal
char hexadecimal_value[2]; // Your hexadecimal

printf("Decimal: %d\n", decimal_value);
printf("Hexadecimal: %c%c\n", hexadecimal_value[0], hexadecimal_value[1]);

This could made better a bit if you do make the hexadecimal_value array one larger than it needs to be and set the last character to '\0'. Because then, hexadecimal_value would be a string (as strings need to be null-terminated), which you could easily print with printf:

printf("Hexadecimal: %s\n", hexadecimal_value);

Encapsulation

Now that the actual code is cleaned up a bit, what can we do to make it more beautiful on a higher level?

Exctract functionality into functions, of course!

Right now, all your code is in main. This is okay for small programs like this, but should still be avoided. So instead, let's make some smaller functions for simple tasks! Your control flow is much like the following:

int main() {
    get_input();
    process_input();
    print_output();
}

Since it makes sense to handle the input and output in main (for this scale at least), let's focus on making the process_input()!
I suggest you use three functions, which carry your main logic:

int   is_valid_binary(const char *string);
char *binary_to_decimal(const char *string);
char *binary_to_hexadecimal(const char*string);

is_valid_binary takes in a string and returns 0 if it is not a valid binary number (e.g. contains characters other than '1' and '0'), otherwise, it returns 1. binary_to_decimal takes in a string of binary digits and returns a string of the very same number, but with decimal digits. binary_to_hexadecimal works similar; it takes a string and returns a string of hexadecimal digits. I leave actually writing these functions to you.

Once you have those three functions, your main would thus become:

int main() {
    char input[8 + 1 + 1];
    printf("Enter a binary number: ");

    do {
        fgets(input, sizeof input, stdin);
        input[8] = '\0';
    } while (!is_valid_binary(input));

    char *decimal = binary_to_decimal(input);
    char *hexadecimal = binary_to_hexadecimal(input);

    printf("Decimal: %s\nHexadecimal: %s\n", decimal, hexadecimal);

    // Since you allocated the memory for decimal end hexadecimal yourself,
    // you have to free it yourself as well! At least, you should allocate
    // it yourself.
    free(decimal);
    free(hexadecimal);
}

Exercise to you

To recap, consider the final version of main I pasted above. Your task now is to write the functions is_valid_binary, binary_to_decimal and binary_to_hexadecimal. You could also expand those functions to handle arbitrarily long binary numbers (not necessarily eight digits, but also 2 digits or 24 digits!). And, as an extra, take the input from the commandline. Use argv for that one.

Addendum

As Toby Speight mentioned in the comments, it is not really a good idea to use pow() when calculating 2^n. First of all, pow() uses doubles, which adds some conversion overhead (and, worst case scenario, wrong results due to the way double works. But it's rather unlikely.), and second: it's slow. Let me introduce you to bitmagic!

Consider the number 4, or 0b0100. 4 times 2 is 8, or 0b1000. There is a pattern going on here which is everywhere: if you multiply any number by 2, its binary representation gets shifted by 1 to the left. Since exponention is just repeated multiplication, 2^7 is just 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2. That's seven left-shifts right there! In C, performing left-shifts is done by using the << operator.

So, instead of calculating 2^7 by using the slow pow(), you can use 1 << 7 instead!

Basically: pow(2,x) == 1 << x.


This is not a hack.

if( ( i % 3 == 0 ) || ( i % 5 == 0 )  ||
   ( ( i % 3 == 0 ) && ( i % 5 == 0 ) ) )

What you have here is essentially:

if( a || b || ( a && b ) )

The truth table for a || b is:

\begin{array} {|cc|c|}
\hline
a & b & a \lor b \\
\hline
0 & 0 & 0\\
0 & 1 & 1\\
1 & 0 & 1\\
1 & 1 & 1\\
\hline
\end{array}

Where \$0\$ indicates false and \$1\$ indicates true.

Therefore, the last part of your if is completely useless.

if( a || b || ( a && b ) )

is exactly the same as

if( a || b )

So your if statement can be:

if( ( i % 3 == 0 ) || ( i % 5 == 0 ) )

Arithmetic Sum

Project Euler 1 can be transformed into a Arithmetic sum problem.

Ask yourself these questions:

How many numbers that are multiples by 3 are there below 1000 ?
How many numbers that are multiples by 5 are there below 1000 ?
How many numbers that are multiples by both 3 and 5 (i.e. 15) are there below 1000 ?

Then use the values for these individual arithmetic sums to arrive at your final answer. This will give your code a complexity of \$O(1)\$ instead of \$O(n)\$

As this is Project Euler, I only want to give you a little push in the right direction, hope this helps.


I did something like this. You can also just use a Strings file. What I did was create a spreadsheet in the Google Drive with all the translations (one column for the identifier BUTTON_TITLE_OK and one each language the app supports). It's then very easy to make a little formula in Google Drive that takes all the identifiers, and turns it into an enum. Like so:

    enum LocalizedStringIdentifier: String {
        case BUTTON_TITLE_OK
    }

    func string(_ identifier: LocalizedStringIdentifier) -> String? {
        guard let value = plists[identifier.rawValue] else { return nil }
        return value
    }

The advantage of this that you get code completion in Xcode and thus less chance of mistakes. Usage:

LanguageManager.shared.string(.BUTTON_TITLE_OK)

The advantage of the spreadsheet approach is that you have all localizations combined so you have a better overview (and it is also easier to share with your client so that they can provide you with the right translations, unless this is your own project).

Side note: If you do use plists, you should try use the new Codable protocol to load Plists directly into your models.


Because you use the returned value of IndexOf() only to check if it is > -1 a more readable way would be to use Contains() instead of IndexOf().

Internally Contains() does mostly the same than your comparison of the returned value. In the reference source of Contains() you will find

[Pure]
public bool Contains( string value ) {
    return ( IndexOf(value, StringComparison.Ordinal) >=0 );
}

while the counterpart of IndexOf() will look like so

[Pure]
public int IndexOf(String value) {
    return IndexOf(value, StringComparison.CurrentCulture);
}

The difference between these two methods by the meaning of the internally called IndexOf() method is the passed StringComparison parameter.

By reading the documentation you will read in the remarks section

  When you call a string comparison method such as String.Compare,
  String.Equals, or String.IndexOf, you should always call an overload
  that includes a parameter of type StringComparison so that you can
  specify the type of comparison that the method performs. For more
  information, see Best Practices for Using Strings.

Let us check what that means by using the german word daß and compare the results from StringComparison.CurrentCulture, StringComparison.InvariantCulture and StringComparison.Ordinal

Console.WriteLine("daß".IndexOf("daß", StringComparison.Ordinal));
Console.WriteLine("daß".IndexOf("dass", StringComparison.Ordinal));
Console.WriteLine("daß".IndexOf("dass", StringComparison.CurrentCulture));
Console.WriteLine("daß".IndexOf("dass", StringComparison.InvariantCulture));

this will yield the results

  0
  -1
  0
  0

As you see you need to know what you want to get returned by calling IndexOf(). If you need to know if the exact string is contained inside another string you shouldn't use the default IndexOf() method.


I think you should keep CountMap as Map String (Map UTCTime Int). That is a better way of keeping counts. If you do that then you can use mysc function directly. I find mysc much more readable and clear.

import           Data.Time (UTCTime)
import qualified Data.Map as M

type CountMap = M.Map String [(UTCTime,Int)]

-- Data used for plotting data series 'foo' and 'bar'
test :: CountMap
test =
  M.fromList [ ("foo", [(read "2012-09-28 12:00:00", 3), (read "2012-09-29 12:00:00", 4)])
             , ("bar", [(read "2012-09-28 12:00:00", 3)])
             ]

susetCount :: CountMap -> CountMap
susetCount = M.map M.toList . mysc . M.map M.fromList
mysc m =  M.map (flip M.union allelems) m
 where
    -- Find all possible UTCTime that can exist.
    allelems = M.map (const 0) $ M.foldr' M.union M.empty m


Incorrect counting

For a text file that ends with a space or newline character,
the countWords function counts 1 more word than there really are.

Before giving away the fix, I would point out a few things about this implementation:

totalWords = 0
for b, a in enumerate(self.txtStream):
    if a != ' ' and a != '\n' and b != len(self.txtStream)-1 and (self.txtStream[b+1] == ' ' or self.txtStream[b+1] == '\n'):
        totalWords += 1
return totalWords+1

The names b and a make this a bit hard to read.
The value of a is a character,
the value of b is the position (or index) of the character.
Better names would have been c and i (or pos or index),
and the code would be a bit easier to read.

Processing the text character by character like this is a bit complicated,
and it will get even more complicated if you add the special treatment to fix the processing at the end of the content.

A simpler way would be to split the input, and use the length of the resulting list, for example:

return len(self.txtStream.split())

However, this is not exactly the same original code, and it has a drawback too.
It's not the same, because the split() function of strings splits the input by any whitespace,
including TAB,
while your code splits strictly on SPACE and NEWLINE.
If you really want to use the same logic and not split on TAB,
then you would have to use the split function from the re package:

import re

# ...

return len(re.split('[ \n]', self.txtStream))

This preserves the behavior of your original code,
and fixes the off-by-1 error,
because just like the split function of strings,
it ignores whitespace at the end of the content.

The splitting technique has an important drawback though:
it consumes more memory,
because it creates a list of words from the content,
effectively doubling the memory use.
Your solution is harder to implement correctly and to read,
but it's more memory-efficient.

Always close resources

There are several issues here:

def __init__(self, txtFile):
    self.txtContent = open(txtFile)
    self.txtStream = self.txtContent.read()

def __repr__(self):
    return self.txtStream

The biggest issue is that a filehandle is not properly closed.
When you open something, remember to close it!

Since it's so easy to forget closing filehandles,
Python has a syntax to do this automatically for you:

with open(txtFile) as fh:
    self.content = fh.read()

Class attributes vs local variables

In the with example in the previous section,
I renamed self.txtContent to fh,
for two reasons:

It's a more appropriate name: txtContent implies some text content, which is not true and misleading. Likewise, I renamed txtStream to content, because that's what it really is. A "stream" is usually something that doesn't occupy much memory, doesn't contain the full content, but a data structure from which you can stream the content gradually without consuming much memory.
Even more importantly, self.txtContent is not used anywhere outside the __init__ function,
so there's no need to make it an attribute of the class, it can be a local variable.

Avoid repeated operations

In this code, char.lower() is performed 3 times:

if char.lower() not in characters:
    characters[char.lower()] = 1
else:
    characters[char.lower()] += 1

Since all 3 times it will give the same result,
it would be better to do this once,
store the value in a variable and use that variable instead of repeating the call.

Avoid repeated operations -- the bigger picture

An even more important repeated operation could be performed by users of the TextAnalyzer class.
Once you create an instance of this class,
the text content it read from the file will normally not change,
but calling countChars and countWords will recompute the same values over and over again.

If the class is not designed to change the value of the text content after construction,
then it would be better to not compute the character and word counts only once.

Python conventions

There are common conventions for variable and function naming in Python,
explained in PEP8.
It's strongly recommended to follow that when coding in Python.

Simplifications

Instead of this:

if char != ' ' and char != '\n':

You can write like this:

if char not in ' \n':

Instead of this:

return [x for x in characters.items()]

You can write like this:

return characters.items()

Instead of this:

if char.lower() not in characters:
    characters[char.lower()] = 1
else:
    characters[char.lower()] += 1

You can write like this:

c = char.lower()
characters[c] = characters.get(c, 0) + 1


Magic numbers.

Try to avoid them. 65 is really ord('A'), 90 is ord('Z'); so say that explicitly. Along the same line,

if i == ' ':

looks better than

if ord(i) == 32:

Naming

Try to use descriptive names. I'd prefer caesar_decrypt(ciphertext, shift) to shift(S, n). Same goes for A, a, etc.
Streamlining

I was really stumbled upon an asymmetry of elif and else cases of shift:

     a = n-(90-ord(i))+64
     word += chr(a)

is quite counter-intuitive. I'd suggest

for i in S:
  if ord(i) == 32:
      word += ' '
      continue
  a = ord(i) + n
  if a > ord('Z'):
      a -= ord('Z') - ord('A')
  word +=chr(a)


Creating multiple lists of named tuples based on condition

You can make a separate method that decided which type the instruction is:

def get_parser(instruction):
    if len(instruction) < 2:
        return Timing
    if instruction[2] == 'MATCH':
        return Cars
    return Items

and then just use that:

def assign_tuple_lists2(instructions):
    """Creates named tuple lists from instructions"""
    result  = defaultdict(list)
    for instruction in instructions:
        parser = get_parser(instruction)
        result[parser.__name__].append(parser(*instruction))

    return result

this uses a collections.defaultdict instead of separate lists per type

defaultdict(list,
            {'Timing': [Timing(timestamp='1')],
             'Cars': [Cars(timestamp='2', user='bob', reserve='MATCH')],
             'Items': [Items(timestamp='3', user='alice', action='55')]})


Some general style points:

Indentation, it's important. Please indent one level for each set of braces moving forward.
Frivolous comments. You have one comment for each function. These comments simply repeat what the names of the functions already tell us. They're noise. Remove them. I find it's a good practice to write pseudocode comments and then "fill in the blanks", but they shouldn't stay once you've implemented it. Comments should always say why, rarely should they say what.

Now we can see what's really going on a little better.

function hideNav() {
    $('nav').hide();
}

hideNav();

function showNav() {
    $('nav').show();
}

$('button').click(function() {
    if($('nav').is(':hidden')){
        showNav();
        $(this).text('Close me');
    }
    else
        hideNav();

    if($('nav').is(':hidden')){
        $('button').text('Open me');
    }
});

Personally, I don't see a point to the showNav() and hideNav() functions. It seems they don't do much except save a few keystrokes, but you've already written them and they're not actually hurting anything. I guess they're ok.

This else statement really needs some braces.

    if($('nav').is(':hidden')){
        showNav();
        $(this).text('Close me');
    }
    else
        hideNav();

    if($('nav').is(':hidden')){
        $('button').text('Open me');
    }

It's really not clear when the second if($('nav').is(':hidden') is supposed to execute. I think it should look like this.

    if($('nav').is(':hidden')){
        showNav();
        $(this).text('Close me');
    } else {
        hideNav();
    }

    if($('nav').is(':hidden')){
        $.('button').text('Open me');
    }

Which brings to mind some code duplication. I would create a isNavHidden() function to simplify all this a bit.

function isNavHidden() {
    return $('nav').is(':hidden');
}

Then you could write the above snippet like this.

    if(isNavHidden()){
        showNav();
        $(this).text('Close me');
    } else {
        hideNav();
    }

    if(isNavHidden){
        $.('button').text('Open me');
    }


Using deftype to create a wrapper class for byte arrays

First, your calls to .ba aren't being resolved for other, so that's forcing use of reflection. If you run lein check, you'll see:

Reflection warning, thread_test.clj:22:22 - reference to field ba on java.lang.Object can't be resolved.

This has the potential to slow the method down, although it only happens once per call, so the effect wouldn't be huge.

Use explicit type hints to ensure it knows what types you're working with, just like you did below that:

(let [m (alength ^bytes (.ba ^Bytes this))
      n (alength ^bytes (.ba ^Bytes other))

I tried type hinting the parameters instead, and got an error I've never gotten before. I think it was looking for a compareTo with Object parameters, so saying the parameters were Bytes was throwing it.

Other than that, I don't see anything performance related. I'll just point out, in case you don't know, this' ba is actually in scope. You can use it directly which gets rid of some bulk, although makes some of the code less symmetrical:

(deftype Bytes [^bytes ba]
  Comparable
  (compareTo
    [_ other]
    (let [m (alength ba) ; Here
          n (alength ^bytes (.ba ^Bytes other))
          l (min m n)]
      (loop [i 0]
        (if (< i l)
          (let [a (aget ba i) ; And here
                b (aget ^bytes (.ba ^Bytes other) i)
                d (compare a b)]
            (if (zero? d)
              (recur (inc i))
              d))
          (compare m n))))))


Streaming my UPS metrics for graphical viewing in bash

Good things

Using $() over backticks (``) for command substitution is a current best practice and does make code like this more readable.
It is also good use variables for long unchanging items like your API_URL.
Thanks for including the link to the graph.  This doesn't make your code any better, but it does lead to happier reviewers.  I'm such a fan of graphs I'd have thrown it inline.

Suggestions

Since you're using the $() form of command substitution, it is pretty easy to add some extra spaces inside of the parenthesis.  I think this makes it even more readable.  $( /sbin/apcaccess -up ${UPS_PROPS[$index]} )
Using the variable as a printf format is a good way to do it, but that means the value of the variable isn't a valid URL.  If this were a bit longer than 10 lines it wouldn't hard to imagine a naive maintenance programmer coming along and doing curl $API_URL somewhere and wondering why it is giving him errors.  So I would prefer to name the variable API_URL_FORMAT or API_URL_PROTO to make it clear it isn't a usable URL yet.
#!/usr/bin/env bash is considered more portable because it works with folks who can't install bash in the OS-proper place.
Run your code through https://www.shellcheck.net/ for several hints about quoting your substitutions.
It would be a bit clearer what's happening with the curl if you split it into two lines.  The first would set a variable like ADDING_URL="$(printf $API_URL_FORMAT $(expr $index + 1) $value)" then the second line would just be curl $ADDING_URL.  This leaves a pretty boring curl line I admit, but by using the variable it is easier to see what is happening with the printf before thinking about sending it out to the web.  And you may want more curl options later so the curl line could get more complicated.
Please use consistent case for your variable names!  Some are upper case, which is pretty traditional for shell scripts, but other half are lower case.  Some people like upper case because it makes the variables stand out more.  I don't think that makes much difference with modern syntax highlighting editors.  But it should definitely be consistent, either way, in such a short script.  One convention is to use upper case for exported/in the env variables and lower case for local/not in the env variables.  In the case all of your variables would be lower case since none of them are exported into the env.
Why are you looping over an array with one item in it?  Will it ever contain anything other than LINEV?  If not the code can be significantly simplified by getting rid of the for and just putting the values into the two inner lines.
If the for loop has some value I would try to use it like a shell for loop and loop over the values instead of the indexes.  I see that you use the index inside of the curl, but I'm not sure what that is doing for you.


Please check for additional comments in the code,

use strict;
use warnings;

# no need to die() when open()
use autodie;

# this hash transforms a move to a different direction. By default each move points to itself.
my %rotate = (
  'u' => 'u',
  'r' => 'r',
  'd' => 'd',
  'l' => 'l'
);

if (!defined($ARGV[0]))
{
  die ("You need a command line argument (no spaces) to use rotations: R, L, H and V/U/D rotate right, left, horizontally and vertically.");
}

my @adjust = split(//, lc($ARGV[0]));
#/(fix stackexchange code coloring)

for my $dir (@adjust) {
  my @keys;

  # rotate right
  if ($dir eq 'r') { @keys = qw(r d l u); }
  # rotate left
  elsif ($dir eq 'l') { @keys = qw(l u r d); }
  # vertical flip
  elsif ($dir eq 'v' or $dir eq 'u' or $dir eq 'd') { @keys = qw(d r u l); }
  # horizontal flip
  elsif ($dir eq 'h')  { @keys = qw(u l d r); }
  else {
    die ("I didn't recognize $dir. RLHVUD (case insensitive) are the only directions I do.");
  }

  # check "hash slice"
  @rotate{@keys} = @rotate{qw(u r d l)};
}

my $anyDif; # checks for differences once we've parsed rotations
for my $dir (keys %rotate) {
  #print "$dir becomes $rotate{$dir}\n";
  $anyDif += ($dir ne $rotate{$dir});
}

#print "Rotation: URDL => $rotate{'u'}$rotate{'r'}$rotate{'d'}$rotate{'l'}\n";

if (!$anyDif) { die("The rotations you requested don't change the puzzle's orientation."); }

# check "three argument open"
open(my $A, "<", "sok.txt");

while (my $line = <$A>) {
  print "Orig: $line";
  print "NEW:: ";
  $line =~ s/\b([0-9\*]*)([URDL])\b/$1 . newdir($2)/gei; # I included * with numbers because it means "push to the end"
  chomp($line);
  print "$line\n"; #this is to avoid orig/new appearing on the same line at the end of a file.
}
close($A);

##################################subroutine

sub newdir {
  my ($v) = @_;
  my $lc = lc($v);

  # check "ternary operator"
  return ($v eq $lc) ? $rotate{$v} : uc($rotate{$lc});
}


Creating and manipulating a variant number of bufferedImages for vision algorithm

Skip the object wrapper. Generate the images list in a static function or a method and return it as is or return its iterator or stream if that is how you like it. Or return a custom iterator or stream that generates the images.

Consider re-factoring the looping code. Three loops is a bit too much in the same place. Extract the outer one to a function/method.

Several values are computed multiple times. '(k * pointYResolution)' and 'currentColor.getRGB()' for example. Store them in variables.

'ImageList' should be 'imageList' in java naming.

Add final to all variables that re not changing.

JavaDoc do you use it?

Make sure buffered image can hold the size of data you need. Some graphics buffers will scale up to a rectangle with a side power of 2 greater than what you ask and can potentially eat a lot of memory. I have no idea if this is applicable to this case here.


I finally solved the Birthday Problem using Java

Can be done without BigDecimals and factorials

You can compute the chance of shared birthdays using a simpler method, which avoids big numbers and factorials.  With one person, the chance of all people having different birthdays is 100% (obviously).  If you add a second person, that person has a 364/365 chance of also having a distinct birthday.  When you add a third person, that person has a 363/365 chance of having a birthday distinct from the previous two.  So as you keep adding more people, you keep track of the total chance of everyone having a distinct birthday by multiplying your current chance by (365-i)/365 for each new person.

Here is how you could do this in java:

import java.util.Scanner;

public class Testing {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Number of Students: ");
        int num = sc.nextInt();

        double notSameChance = 1.0;
        for (int i = 0; i < num; i++)
            notSameChance *= (365-i) / 365.0;

        System.out.printf("\nNot Same Birthday chance: %.0f%%\n",
                (notSameChance * 100) );
        System.out.printf("Same Birthday chance: %.0f%%\n",
                ((1 - notSameChance) * 100)  );
    }
}

Factorial function was strange

Looking at your factorial function, it does an addition and a multiplication on every loop.  Although it appears to work, you could make it simpler by doing just the multiplication, like this:

public static BigDecimal fact(int num)
{
    BigDecimal abd = new BigDecimal("1");

    for (int i=2; i<=num; i++) {
        abd = abd.multiply(BigDecimal.valueOf(i));
    }
    return abd;
}


Skip input to next line, for reading serialized objects

IgnoreUntilNewLine is too long in my opinion.  I'd simplify it to ignore_line.

It probably makes sense to provide the manipulator object in the library instead of letting the user declare one:

struct ignore_line_t {
    constexpr explicit ignore_until_newline_t() = default;
    // ...
};
inline constexpr ignore_line_t ignore_line{};

so the user can use it directly in a >> chain:

stream >> tmp.x >> tmp.y >> TU::ignore_line

Incidentally, we can go further and provide a similar helper for getline to fit in the chain:

class getline {
    std::string& dest;
public:
    explicit getline(std::string& s)
        : dest{s}
    {
    }
    friend std::istream& operator>>(std::istream& is, getline man)
    {
        return std::getline(is, man.dest);
    }
};

so your example can be written simply as

stream >> tmp.x >> tmp.y >> TU::ignore_line >> TU::getline(tmp.line)


Self Join Exercise. Have I over-complicated it?

You have a bug. Change the row ('u3', 100, 500, 125) to ('u3', 99, 500, 125), and try again. You will see that u3 row disappears.

You can fix it with the following minimal change:

rm.reading_time = (SELECT MAX(r2.reading_time)
  FROM Readings r2
  WHERE  r2.user_id=r.user_id -- you have to join on ids first
  and r2.reading_time < r.reading_time)

There is another bug here:
r.x-rm.y should have been r.y-rm.y.
user_id, reading_time is a unique key by problem definition. Having it declared will enable us to detect some invalid inputs. What is the average speed of an object that can be at more than one place?
I would go along with something like this for the intermediate script:

SELECT t.*, t2.*
FROM (SELECT r.user_id,r.reading_time,
         max(r.x) AS x1, max(r.y) AS y1,
         max(rm.reading_time) AS prev
FROM Readings r
JOIN Readings rm ON (r.user_id = rm.user_id AND rm.reading_time < r.reading_time)
GROUP BY r.user_id,r.reading_time) t
INNER JOIN Readings t2
ON t.user_id = t2.user_id AND t2.reading_time = t.prev;


Select data from csv and make associative array

Well, first of all this data must be stored in a database, not a file. Using PDO you'll get your array in a few lines (assuming a database connection is already established):

$sql = "SELECT city, district FROM zip WHERE zipcode=? ORDER BY city, district";
$stmt = $pdo->prepare($sql);
$stmt->execute([$zipcode]);
$data = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);

As of the code present, there are way too much loops to my taste. I believe everything could be done in one loop, like

$zipcode = '67401';
$data = [];
foreach (file("zip.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $row) {
    list($zip, $city, $district) = explode(",",$row);
    if ($zip == $zipcode) {
        if (!isset($data[$city])) {
            $data[$city] = [];
        }
        $data[$city][] = $district;
    }
}

well if you need to sort your arrays, a couple extra loops are still needed

ksort($data);
foreach ($data as $city => $array) {
    sort($data[$city]);
}


Given a word, find other words in an array with same length and same characters

Whitespace is very important for readability. For posting to Stack Exchange sites I recommend replacing tabs with spaces, because otherwise the site does that for you and the tabstops might not match. Here, though, the whitespace is so crazy that I think you need to look at configuring your IDE to pretty-print the code. Reformatting so that I can understand the structure:

public class d3 {
    public static void main(String[] args){
        String Search="loop";
        String[] letters = Search.split("") ;
        int counter;

        String[] words={"pole","pool","lopo","book","kobo"};

        for(int i=0;i<words.length;i++)
        {
            counter=0;
            String ssplit[] = words[i].split("");
            for(int j=0;j<words[i].length();j++)
            {
                if(letters.length==ssplit.length)
                {
                    for(int k=0;k<letters.length;k++)
                    {
                        if(letters[j].equals(ssplit[k]))
                        {
                            counter++;
                            ssplit[k]="*";
                            break;
                        }
                    }
                    if (counter == 4)
                    {
                        System.out.println(words[i]);
                    }
                }
            }
        }
    }
}

Names

Java convention is that camel-case names which start with a capital letter are types (classes, interfaces, etc), so Search as the name of a variable is unexpected.

counter is not entirely uninformative, but a better name would tell me what it counts. Similarly, it would be helpful to distinguish which variables relate to the search query and which to the items searched. The best convention I've seen there is PHP's needle and haystack, so I would suggest needleLetters and haystackWords.

foreach statement

Instead of for(int i=0;i<words.length;i++) ... words[i] you can use for (String word : words) ... word. This removes a variable and simplifies the naming, making it easier to see what the code does.

Decomposing strings

String has a method toCharArray(). I think it would make more sense to use that than split("").

Don't put something in a loop which can go outside it

            for(int j=0;j<words[i].length();j++)
            {
                if(letters.length==ssplit.length)
                {
                    ...
                }
            }

could be rewritten

            if(letters.length==ssplit.length)
            {
                for(int j=0;j<ssplit.length;j++)
                {
                    ...
                }
            }

Executing the test once is more efficient, and it's also easier to understand because the maintainer doesn't have to reason about loop invariants to work out what might have changed the second time the test is executed.

Since there's nothing after this test in the loop body, an alternative would be

            if(letters.length!=ssplit.length)
            {
                continue;
            }

            for(int j=0;j<ssplit.length;j++)
            {
                ...
            }

Beware hard-coded constants

Why

                    if (counter == 4)
                    {
                        System.out.println(words[i]);
                    }

? That's a bug. The comparison should be with letters.length. Also, it would make more sense to move the test outside the loop over j.

Use advanced data structures

            for(int j=0;j<words[i].length();j++)
            {
                for(int k=0;k<letters.length;k++)
                {
                    if(letters[j].equals(ssplit[k]))
                    {
                        counter++;
                        ssplit[k]="*";
                        break;
                    }
                }
            }

takes time proportional to words[i].length() * letters.length. If you use java.util.HashMap<Character, Integer> to store a per-character count, you can generate a representation for each word in time proportional to the length of the word, and you can compare the representations of two words in time proportional to the length of each word. In this toy example it doesn't matter, but for real applications the difference between \$O(n^2)\$ and \$O(n)\$ can be the difference between a project being feasible and not. The first place to look for optimisations is always the algorithm.


Protecting webpage text from being selected

That is an old skool question, the common wisdom is that you cannot prevent a user from getting to the text. There are a number of ways to get around your protection.

For example, in Chrome, open Developers Tools, open your site, check the web request, and then all the text will be perfectly copy pastable.

Other than that:

alert() has been a bad practice for 20 years now, please use something else
Indent your code, use jsbeautifier if you have trouble
In the keydown, I would check whether the control key is pressed before throwing an error, unless the user never needs to press PageUp or PageDown
I am not entire surely, but I think you will need event.preventDefault(); to really prevent right clicking etc.


Find all combinations of 4 elements whose sum equals a target in Python

Lists are pretty inefficient for this type of thing. The majority of the complexity is from iterating over the lists and comparing contents. Sets use a hash for their content, reducing complexity.

When using sets, most of the complexity comes from the combinations function.

Here are the results of a time test on your code

res1 = Solution().fourSum([-5,5,4,-3,0,0,4,-2],4)
print(time.time() - start)
# 0.0001342296600341797

The results of a method using only sets

res = Solution().fourSum([-5,5,4,-3,0,0,4,-2],4)
print(time.time() - start)
# 9.918212890625e-05

Code for the second function
(updated to prevent 3-number outputs)

class Solution:
    def fourSum(self, nums, target):
        from itertools import combinations
        res = set()
        # Create all possible combinations

        for i in combinations(nums, 4):
            if sum(i) == target:
                # Turns the tuple of numbers into list of strings
                # Then joins them into a single string
                # This allows hashing for the set
                res.add(" ".join(sorted(list([str(x) for x in i]))))
            # Splits the strings into lists of ints
        return list([ [int(z) for z in x.split()] for x in res])


Is code optimization for branch predictor necessary now?

@rolfl's answer covers the major points very well.  In addition, I would recommend that you change the comment, removing the phrase "branch predictor."  A branch predictor is a part of the CPU which attempts to predict the result of a branch so that the CPU can speculatively execute the predicted branch.  A programmer can write code that optimizes branch prediction in assembly, or C, or other compiled languages for which the programmer can reliably predict the machine code that the compiler will emit.  In an interpreted language such as PHP or SQL, there is so much code between your source and the machine that optimizing for the branch predictor at the level of your PHP or SQL source no longer makes any sense.


Well GetStoredProcedureName is an instance property - you need an instance of the object to get the value of the property. The value belongs to an instance, not to the type. You either need to use static properties and lose the
generics or introduce a configuration source that maps type to a configuration object.

I'd sugges that the object has no need to know what its stored procedures are called so the latter suggestion seems to be the way to go.

Create a configuration class:

public class DataConfiguration<T>
{
    public string GetStoredProcedureName { get; set; }
}

public class DataConfigurationProvider
{
    public DataConfiguration<T> GetConfiguration<T>()
    {
        // some stuff.
    }
}

Then you can update your functions:

public RawDataAggregatedItems<T> GetRawDataAggregated<T>(int? id) where T : IRawDataAggregatedItem
{
    // _dataConfigurationProvider injected by constructor injection.
    var sprocName = _dataConfigurationProvider.GetConfiguration<T>().GetStoredProcedureName;
    try
    {
        using (var cn = Connection())
        {
            var cmd = new SqlCommand(sprocName, cn) { CommandTimeout = _commandTimeout, CommandType = CommandType.StoredProcedure };
            cmd.Parameters.Add(new SqlParameter("@periodId", SqlDbType.Int)).Value = id;
            return new RawDataAggregatedItems<T>(cmd.ExecuteReader());
        }
    }
    catch (Exception ex)
    {
        throw new Exception("Error fetching aggregated rawdata list.", ex);
    }
}

I've been a bit wooly on the specifics here but hopefully you can see yourself to a working solution!


Project Euler 22: Names scores alternative

a, dict, c and sum are all problematic names, for two different reasons. Single character variable names should be used sparingly, really only in brief contexts where the intent is quite clear like for i in range(10) where it's obvious that i is an integer and follows for loop conventions. for y in a is very unclear because you haven't made it obvious what y is or should be, and a would be much harder to follow if not for the fact that it's declared just above. Even so the choice of letters seems totally arbitrary. I'd replace a with f for file, since it's localised.

The other naming issue is that using the names dict and sum are actually overwriting builtin functions and should be avoided, especially as I'm going to suggest that you use sum, which you can't do if it's been overwritten.

Also instead of using a plain open, you should use with open(). That's Python's context manager which handles file closing for you. It ensures that a file is always closed correctly, even if an error arises or you don't call file.close(). Note, you didn't call a.close() so clearly this is useful:

with open('/home/Username/1st few programms/names.txt') as f:
    for line in f:
        names = line.split(",")
        names.sort()

Next, this code you're using makes no sense. You're iterating over each line in the file but just creating a new list of names each time. If all the names are stored on one line then this works but is redundant, and I'd instead suggest this:

with open('/home/Username/1st few programms/names.txt') as f:
    names = f.read().split(",")
names.sort()

read() will just read the full string of the file in so that then split can separate it based on commas. If you do have names on multiple lines, then you want the loop but you want to add more values to names each time:

names = []
with open('/home/Username/1st few programms/names.txt') as f:
    for line in f:
        names += line.split(",")
names.sort()

The algorithm that determines a person's score is quite unusual, so it would actually be best to create a function for it. One that takes a name and position in the list and returns their score. It can do largely what your inner loop does:

def name_score(index, name):
    localsum = 0
    for character in name:
        localsum += char_points[character]
    return localsum * (index + 1)

However, this is one of the places I'm going to suggest you use sum. You can pass a generator expression into sum to do this calculation efficiently in one line. A generator expression is a for loop like expression, here's how it'd look for this function:

def name_score(index, name):
    return sum(char_points[character] for character in name) * (index + 1)

You can see how there's the same for _ in syntax as before, just that now it's collapsed into one line. You no longer need to have a localsum and sum is faster than using a for loop.

Now with this function, the main loop is simplified to:

sum = 0
for i in range(len(names)):
    sum += name_score(i, names[i])
print sum

First though, let's get rid of names[i] as that's ugly. Use Python's enumerate function that allows you to both get the indices and values of a list together, like this:

for i, name in enumerate(names):
    sum += name_score(i, name)

This is much cleaner now, but we can also use sum in this case to remove your whole loop, in fact it can skip straight to printing the sum:

print sum(name_score(i, name) for i, name in enumerate(names))

Again, this is both more readable and much faster. This also means that you no longer have a sum value that needs to be renamed.


Check if the array contains duplicate values

Wasted memory

There is nothing in the description and the posted code to justify storing the input array and duplicates inside a class. This is a waste of memory.

If you just want to check if an array has duplicate values,
you should do just that. This means you could return early as soon as you found the answer:

public boolean hasDuplicate(int[] items) {
  Set<Integer> appeared = new HashSet<>();
  for (int item : items) {
    if (!appeared.add(item)) {
      return true;
    }
  }
  return false;
}

It's worth noting that fully reading the items array is also a wasted memory. You might even get a follow-up question "what if there are more numbers to check than fit in memory?". Instead of fully reading this array, consider streaming options, for example passing a Scanner, or Iterator<Integer> to hasDuplicate, which will read one number at a time, avoiding unnecessary I/O and memory usage. Just don't forget to close the input resource in the caller method after the computation is finished.

Idiomatic expressions

This is both tedious and not idiomatic:

return duplicates.size() > 0 ? true : false;

Use boolean expressions directly, and use the isEmpty method of collections (and strings) to check for emptiness:

return !duplicates.isEmpty();

A word about testing

  Note: I cannot use JUnit or any testing framework during the interview.

You cannot run a main method with tests either.
You can write down proper unit tests during an interview just as you can write the main method you did with tests.


Looking for a more condensed method of assigning values by using arrays and fixed ranges

The comment discussion in the original post directly relate to the differences between the ActiveWorkbook and ThisWorkbook. While you code may indeed work, it's not a guarantee. This reference (and this one) have good explanations to illustrate the differences between how you reference a workbook and why you should always pay specific attention to references (whether it's to the Workbook or Worksheet or Range).
As explained in the comments, because you specifically identify the worksheet for all the .Value2 data, you don't need to loop through all the worksheets. This will reduce the setup of your array to
Dim wbDataSource As Workbook
Set wbDataSource = Workbooks("Segment Trends Data.xlsx")

Dim Data(13) As Variant
With wbDataSource
    Data(0) = .Worksheets("Report1").Range("A1").Value2
    Data(1) = .Worksheets("Report1").Range("A5:H11").Value2
    Data(2) = .Worksheets("Report2").Range("A1").Value2
    Data(3) = .Worksheets("Report2").Range("A5:H11").Value2
    Data(4) = .Worksheets("Report3").Range("A1").Value2
    Data(5) = .Worksheets("Report3").Range("A5:H11").Value2
    Data(6) = .Worksheets("Report4").Range("A1").Value2
    Data(7) = .Worksheets("Report4").Range("A5:H11").Value2
    Data(8) = .Worksheets("Report5").Range("A1").Value2
    Data(9) = .Worksheets("Report5").Range("A5:H11").Value2
    Data(10) = .Worksheets("Report6").Range("A1").Value2
    Data(11) = .Worksheets("Report6").Range("A5:H11").Value2
    Data(12) = .Worksheets("Report7").Range("A1").Value2
    Data(13) = .Worksheets("Report7").Range("A5:H11").Value2
End With

Notice that I've changed the With clause to reference the wbDataSource workbook so that's it's very clear where all your data is coming from.
The code you've written actually doesn't need an array, in fact the array obscures what the code is really trying to do. What exactly is Data(0) or Data(11)? You might find it tedious, but I would more clearly define what information all those variables hold. As an example
Dim reportTitle As String
Dim reportDescription As String
Dim regionNumber As Long
Dim regionManager As String

With wbDataSource
    reportTitle = .Worksheets("Report1").Range("A1").Value2
    reportDescription = .Worksheets("Report1").Range("A5:H11").Value2
    regionNumber = .Worksheets("Report2").Range("A1").Value2
    regionManager = .Worksheets("Report2").Range("A5:H11").Value2
    ...
End With

Now when you come back to make an update to your code in six months, you don't have to remember what each of those array slots actually means.
Finally, getting back to the original question of your post, there's no magic or easy way to make the assignments to multiple destination worksheets. You've already defined the code names for each of the sheets, so the VBA you have is about as simple as you can make it. I still recommend the change to more descriptive variable names to make it clear which data you are copying to the destination worksheets.
With wsTTLUSCYTD
    .Range("A1").Value2 = reportTitle
    .Range("A5:H11").Value2 = reportDescription
End With

With wsCintiCYTD
    .Range("A1").Value2 = regionNumber
    .Range("A5:H11").Value2 = regionManager
End With


A program that accepts numbers and computes their sum, and displays smallest and largest number

Use maps to handle mappings

instead of having constants for each individual ratio, you might as well have a single constant that holds both the ratios and their respective strings, as well as being able to map one to the other.

Consider this:

const std::unordered_map<std::string, double> unit_ratios = {
  {"m", 1.0},
  {"cm", 0.01},
  {"ft", 0.3048},
  {"in", 0.0254}
};

int main() {
  std::vector<double> numbers;

  double temp;
  std::string temp_unit;
  while(cin>>temp>>temp_unit){
    try {
      numbers.push_back(temp * unit_ratios.at(temp_unit));
    }
    catch(const std::out_of_range&) {
      cout<<"Incorrect Unit\n";
    }
  }
...
}

Doesn't that look nicer? all the names and ratios nicely bundled together in one spot.

That's also why I've set it as a global constant in my example: The ratios and their name have nothing to do with the main function, they just are, so they should exist out of context.

Declare variables as late as possible

double sum{0}; should be declared as close as possible to the first use.

Use algorithms when possible.

You can use std::accumulate to calculate the sum:

double sum = std::accumulate(numbers.begin(), numbers.end(), 0.0);

Use front() and back() to access the first and last elements of a vector

You could make an argument that numbers[0] is as good as numbers.front(), but not for the last element.

cout<<"Smallest number: "<< numbers.front() << endl;
cout<<"Largest number: "<< numbers.back() << endl;

Do you really need to sort?

Sorting is a O(NlogN) operation, whereas std::max_element and std::min_element are both O(N).

Since you are only doing these two lookups through the vector, you might be better off just using these instead.

If you can use c++11, then std::minmax_element is even better, since you only have to do one pass.

don't use using namespace std;

Just... just don't. Please see every other C++ question on this site as to why.


Do you need a class?

Right now, I'm not sure you need a class. Your class has two methods, one of which is __init__, so this could be refactored to be a function

def get_data(item):
    location = f'Bridgewatch,Thetford,FortSterling,Martlock,Bridgewatch,Lymhurst'
    url = f"https://www.albion-online-data.com/api/v1/stats/Prices/{item}?locations={location}"
    # you also don't need these parentheses
    response = requests.get(url).text
    response_json = json.loads(response)
    if response_json != []:
        response_json = pd.DataFrame(response_json)[["item_id", "city", "sell_price_min"]]
        max = response_json.loc[response_json["sell_price_min"].idxmax()]
        min = response_json.loc[response_json["sell_price_min"].idxmin()]
        gain = max[2] - min[2]
        data = pd.DataFrame(
                [[max[0], max[1], min[1], min[2], max[2], gain]],
                columns=["ITEM", "CITY max ", "CITY min", "MIN_PRICE", "MAX PRICE", "GAIN"])

        return data

This minimizes the cost of constructing the class just to get a dataframe.

Checking the Value of json.loads

Now, I'm not completely sure what response.text will look like every time, but reading your code, it will always be a list. The fact that there's no else means that if your code doesn't satisfy the if statement, it will return None, which could lead to TypeErrors in your dataframe construction. It might be easier to make a generator, that way you can easily skip return values:

# set the argument to be an iterable

def get_data(items):
    columns=["ITEM", "CITY max ", "CITY min", "MIN_PRICE", "MAX PRICE", "GAIN"])
    location = f'Bridgewatch,Thetford,FortSterling,Martlock,Bridgewatch,Lymhurst'

    for item in items:
        url = f"https://www.albion-online-data.com/api/v1/stats/Prices/{item}?locations={location}"
        response = requests.get(url).text
        response_json = json.loads(response)

        # rely on the falsiness of empty lists and enforce that it will indeed be
        # a list type using isinstance
        if response_json and isinstance(response_json, list):
            # since response_json is a list, don't create a dataframe,
            # you can instead provide a key to the max and min functions
            maxval = max(response_json, key=lambda x: x['sell_price_min'])
            minval = min(response_json, key=lambda x: x['sell_price_min'])

            # Now you don't need to rely on an index
            gain = maxval['sell_price_min'] - minval['sell_price_min']
            vals = [maxval.pop('item_id')]
            for k in ('city','sell_price_min'):
                vals.append(maxval[k])
                vals.append(minval[k])
            vals.append(gain)
            yield dict(zip(vals, columns))

Now, in case the if statement isn't True, you won't get None from the function:

def func(a):
   if a<2:
       return [1,2]

df = pd.DataFrame([func(x) for x in range(4)], columns = ['a', 'b'])
# TypeError: object of type 'NoneType' has no len()

The benefit here is that now your get_data_frame function can be a lot easier to leverage:

def get_data_frame():
    item_list = pd.read_csv('items.txt', sep=':', names=['nuber', 'item']['item']

    # You also don't need to initialize the item_price dataframe

    # You can use a list comprehension, and because your items are
    # dictionaries, you don't need to specify the columns
    item_price = pd.DataFrame([a for a in get_data(item_list)])
    item_price.to_csv('data.csv')
    return item_price

read_csv

Now, the only other issue I can see is that you are collecting everything into memory multiple times with pd.read_csv. You really only want the item_id's, so just iterate over a file handle directly:

def file_iterate():
    with open('items.txt') as fh:
        for line in fh:
            # item is the second entry, so split on ':' and grab index 1
            yield line.split(':')[1].strip()

def get_data_frame():
    items = file_iterate()
    item_price = pd.DataFrame([a for a in get_data(items)])
    item_price.to_csv('data.csv')
    return item_price

The generators will allow you to keep one dataframe in-memory, and produces values one at a time.

try/except

The last thing I'd do is to ensure the program doesn't crash on a bad web request or attempt at json.loads:

from requests.exceptions import HTTPError

def get_data(items):
    columns=["ITEM", "CITY max ", "CITY min", "MIN_PRICE", "MAX PRICE", "GAIN"])
    location = f'Bridgewatch,Thetford,FortSterling,Martlock,Bridgewatch,Lymhurst'

    for item in items:
        url = f"https://www.albion-online-data.com/api/v1/stats/Prices/{item}?locations={location}"
        # wrap in try/except here
        try:
            response = requests.get(url).text
            response_json = json.loads(response)
        except JSONDecodeError as e:
            print(f'bad json for {item}')
            continue # skip it so it doesn't ruin your process, or you can raise it
        except HTTPError as e:
            print(f'HTTPError on {url}'
            continue # skip or you can raise
        except Exception: # Unexpected error
            raise
        # rest of function


Get a path between graph nodes using breadth-first search

I don't see that you are using add_node or get_node anywhere, but I'm assuming you would when actually using this class.

Nevertheless, I think these functions would better be called __setitem__ and __getitem__, allowing usage, such as g = Graph(); g[5] = Node(5) and print g[5]. This would also make initializing the graph easier, which leads me to my next recommendation.

I would expect the Graph class to take an argument on initialization to directly build a graph (without having to manually add every single node).

Lastly, get_node can be greatly simplified by using dict.get, which returns None when the key is not present in the dictionary.

class Graph:
    def __init__(self, nodes=None):
        self.nodes = dict()
        if nodes is not None:
            for _id in nodes:
                self[_id] = Node(_id)

    def __setitem__(self, _id, val):
        self.nodes[_id] = val

    def __getitem__(self, _id):
        return self.nodes.get(_id)

    def add_node(self, _id):
        self[_id] = Node(_id)

    ...

This allows initializing an instance like this: Graph([1,2,3]). It does not, however, allow initializing a nested structure.

Regarding your questions:

Use dict.get
I would maybe use _, cur_node = queue.get(0) to make it clearer that you don't need the priority here.
I think it is still quite readable.
deque does not seem too exotic to me, but then again, I don't perform job interviews, so who know.

Last but not least, I would have a look at whether you really need queue.PriorityQueue here. One of its features is that it is thread-safe, because it performs locking when adding or popping values from the queue. However, it also incurs a performance hit because of this (I saw a factor 2 being discussed for Python 2.6).

Instead you could roll your own implementation using heapq, similar to the one shown in the implementation details for heapq, maybe without the part about REMOVED entries, because you don't change the priority of a neighbour once you have calculated it. So you could use:

from heapq import heappush, heappop
import itertools

class PriorityQueue:
    def __init__(self, tasks=None):
        '''A new PriorityQueue.
        Parameters:
            tasks:    iterable of (priority, task) tuples'''
        self.pq = []                         # list of entries arranged in a heap
        self.counter = itertools.count()     # unique sequence count

        if tasks is not None:
            for priority, task in tasks:
                self.add_task(task, priority)

    def add_task(self, task, priority=0):
        'Add a new task'
        count = next(self.counter)
        entry = (priority, count, task)
        heappush(self.pq, entry)

    def pop_task(self):
        'Remove and return the lowest priority task. Raise KeyError if empty.'
        if self.pq:
            _, _, task = heappop(self.pq)
            return task
        raise KeyError('pop from an empty priority queue')

This should basically be how queue.PriorityQueue is implemented as well, but without the locking. Note that heapq is implemented in C, so it is quite fast. You would have to make some performance comparisons to see how this performs with respect to queue.PriorityQueue.


Good initial code.

No protection against buffer overflow.

char line[MAX_LINE_LENGTH];
while((c = getchar()) != EOF && c != '\n') {
  if (i < MAX_LINE_LENGTH) {  // add
    line[i++] = c;
  }
}

No check for "too long a line"

// add test
if (i  == MAX_LINE_LENGTH) {
  fprintf(stderr, "Input too long.\n");
  return EXIT_FAILURE;
}

Always add the null character termination

// if (c == '\n')  // comment out line
line[i++] = '\0';

Code looks wrong with the - 2, yet it appears code functions correctly.  The 2-ness needs explaining.  Below is a size_t version.  Note use of const.

void reverseLine(char reversedLine[], const char line[], size_t lineSize){
  if (lineSize > 0) {
    size_t lineLen = lineSize - 1;
    size_t i;
    for (i = 0; i < lineLen; i++) {
      reversedLine[i] = line[lineLen - i];
    }
    reversedLine[i] = '\0';
  }
}

Minor: for array sizing and indexing size_t is the best type.  int may be too narrow in extreme cases.  Yet keep in mind that size_t is some unsigned type.
Minor: "length" vs "size":  When these two are applied to strings, using "size" to refer to the array size of the string and "length" as the value return from strlen() adds clarity.  IMO, MAX_LINE_LENGTH should be LINE_SIZE or stay with MAX_LINE_LENGTH and use char line[MAX_LINE_LENGTH + 1]; ...  if (i < sizeof line) { ... if (i == sizeof line) {.

Advanced issue: Overlap

void reverseLine(char reversedLine[], char line[], int lineSize);

Strictly speaking, the function, reverseLine() does not, by its declaration, indicate that reversedLine[] and lineSize[] should not overlap.  It could fail in bizarre ways should they overlap.

C provides restrict to 1) indicate pointers should not point to overlapped data and 2) allow the compiler to perform additional optimizations that require that assumption.

// [] form also shifted to * form
void reverseLine(char * restrict reversedLine, const char * restrict line, int lineSize);

Alternatively code could be re-written to cope with overlapped buffers.  I'll leave that as an exercise.

Design idea:  In C, many of the basic string functions assume the destination array is big enough.  As the standard library functions are crafted for performance, checking size allocation is left as a responsibility to the caller.

reverseLine() could be re-designed to do that test.  Instead of leaving the size test to the caller, consider that reverseLine() is not a basic building block and it could check for sufficient memory.  As with such things, error handling is an important, but for now, TBD consideration.

// rLineSize is the space available at `rLine`
// The length of the string pointed to by `line` can use `strlen()`
void reverseLine2(char * restrict rLine, size_t rLineSize, const char * restrict line) {
  size_t lineSize = strlen(line) + 1;
  if (lineSize > rLineSize) Handle_Error();
  ...


Exercise 1_2 multiple console outputs. I would like to reduce the number of console output statements

Scope

This is really just limited to style and code formatting.

Two (almost) substantive points

You should get in the habbit of not:

using namespace std;

It can get you into name-clash issues later, as you progress.

You should be aware that std::endl flushes the stream buffer. This is often unnecessary, unwanted and can be slow if used in a tight loop. You should use '\n' for most situations. If you are worried about
platform specific line-ending, don't be. '\n' adapts, just like
std::endl.

Code formatting

Install clang-format or similar to help you with formatting.

All I did was to integrate your endl into the strings and hit "auto-clang-format" and I got this:

#include <iostream>

int main() {
  std::cout << "Hello everybody!\n"
            << "My name is AK.\n"
            << "Goodbye.\n"
            << "\n"

            // Poem
            << "Twinkle, twinkle, little bat!\n"
            << "How I wonder what you're at?\n"
            << "Up above the world you fly,\n"
            << "Like a tea-tray in the sky.\n";
  return 0;
}

Which is "good enough for me". Clang format is very tunable, and I have it configured to something which works for me, and my team, in 99% of cases. So we don't spend time fighting the formatting of the code.

The above style with "one streaming operator" << at the beginning of each line is what we use most of the time. It makes sense when you have literals interspersed with variables and/or function calls.

For this very specific (and rather atypical?) case, you could, as someone else pointed out, also just stream it all as one continuous literal. C++ allows you stop/start string literals like this:

#include <iostream>

int main() {
  std::cout << "Hello everybody!\n"
               "My name is AK.\n"
               "Goodbye.\n"
               "\n"

               // Poem
               "Twinkle, twinkle, little bat!\n"
               "How I wonder what you're at?\n"
               "Up above the world you fly,\n"
               "Like a tea-tray in the sky.\n";
  return 0;
}

Hope that helps.


Calculating the number of zeroes at the end of a factorial

This challenge looks familiar - I think I answered a similar challenge on our sister site, Programming Puzzles and Code Golf.  Those answers may not be as readable, though.

There's a couple of pieces of good news:

You don't need to count 2's in the prime factorization.  There will always be more 2's than 5's, so you can never have an unpaired 5.
You don't need to iterate over every number up to num if you see that we're just computing n/5 + n/25 + n/125 + ... (integer division).  If we define f(n) = n/5 + f(n/5) and f(0) = 0, we have a much faster version.  That can be implemented recursively, or fairly easily converted to iterative form.


Convert a String with comma separated latitudes and longitudes to a Seq[Coordinate]

Also you can write more human-readable and understandable algorithm with the help of extractors and method collect:

val Coord = """(.+?)\s+(.+)""".r

object Double { def unapply(s: String) = Try(s.toDouble).toOption }

def parseCoordinates(input: String): Seq[Coordinate] =
  input.split(',') collect {
    case Coord(Double(lat), Double(lan)) => Coordinate(lat, lan)
  }


A simple implementation of the producer/consumer pattern

Small nitpicks

Naming: Handler is very non-descriptive. Maybe try Consumer instead?
Naming: addItem does not describe a Consumers action, consume or pass would be a better fit IMHO

Design problems
Handler is a queue fused with a single consumer, so there will never be more than one consumer for the queue!.
If the consumer is not required to run on its own thread, the implementation could be simplified to:
template<typename Item>
class SingleConsumer {
private:
    std::function<void(Item&&)> consumer;
    std::mutex mut; // can be removed if consumer is thread-safe on its own

public:
    template<typename Callable>
    SingleConsumer(Callable&& callable) : consumer(std::forward<Callable>(callable)) {}

    void consume(Item&& item) {
        std::unique_lock<std::mutex> lock(mut); // not necessary if consumer is thread-safe on its own
        consumer(std::move(item));
    }
};

On the other hand, if the requirement is that the consumer has to run on its own thread, why fuse it with its own queue? If there is only one queue, you could run multiple consumers on it to share the workload if needed and/or producers by themselves don't have to decide which consumer to call!
template<typename Item>
class ConcurrentQueue {
private:
    std::mutex mut;
    std::queue<Item> queue;

public:
    ConcurrentQueue() : queue() {}

    bool try_pop(Item& item) {
        std::unique_lock<std::mutex> lock(mut);
        if(queue.empty()) return false;
        item = queue.front();
        queue.pop();
    }

    void push(Item&& item) {
        std::unique_lock<std::mutex> lock(mut);
        queue.push(std::move(item));
    }
};

template<typename Item>
class Consumer {
private:
    std::thread consumer_thread;
    ConcurrentQueue<Item>& queue;
    std::atomic<bool> is_running = ATOMIC_VAR_INIT(true);

public:
    template<typename Callable>
    Consumer(ConcurrentQueue<Item>& q, Callable&& callable) : consumer_thread([callable]() {
        run(std::forward<Callable>(callable));
    }), queue(q) {}

    ~Consumer() {
        is_running = false;
        consumer_thread.join();
    }

    template<typename Callable>
    void run(Callable&& consumer) {
        Item item;
        while(is_running) {
            while(is_running && !queue.try_pop(item)) /* do nothing */;
            if(!is_running) return;
            consumer(item);
        }
    }
};

Of course, this example can be expanded according to your needs!


Excel VBA - in a list, if cell equals specific value then

Don't know if it would be faster, but it would look cleaner to use a Select.

Sub ChangeTest()
    Dim LastRow As Long
    Dim i As Long
      LastRow = Range("M" & Rows.Count).End(xlUp).Row
      For i = 2 To LastRow
        Select Case Range("M" & i)
          Case "A", "B", "C"
            Range("L" & i) = "1"
          Case "D","E","F"
            Range("L" & i) = "2"
          Case "G","H","I"
            Range("L" & i) = "3"
        End Select
      Next i
End Sub


Using IServiceScopeFactory without implementing the Service Locator Pattern

I'm of the opinion that this is awesome, and I have a couple of suggestions to add. It's not "Service Locator" because you're explicitly constraining to the exact type that can be resolved---the explicit dependency is right up there in the constructor.

(I wish they'd bake this into .Net Core.)

Don't store the service-object

I think it would be better to replace T Service with T GetRequiredService(). If you're resolving a Transient service, it would be useful. Additionally, it makes for fewer changes when someone switches away from the built-in IServiceScopeFactory.

Finish implementing IDispose

See this answer on StackOverflow

Go Singleton

I see no reason to register as Scoped, considering what this does. It's using a Singleton, so make it Singleton.

Here's my tweaked version

public interface IServiceScopeFactory<T> where T : class
{
    IServiceScope<T> CreateScope();
}

public interface IServiceScope<T> : IDisposable where T : class
{
    T GetRequiredService();
    T GetService();
    IEnumerable<T> GetServices();
}

public class ServiceScopeFactory<T> : IServiceScopeFactory<T> where T : class
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public ServiceScopeFactory(IServiceScopeFactory serviceScopeFactory) => _serviceScopeFactory = serviceScopeFactory;

    public IServiceScope<T> CreateScope() => new ServiceScope<T>(_serviceScopeFactory.CreateScope());
}

public class ServiceScope<T> : IServiceScope<T> where T : class
{
    readonly IServiceScope _scope;

    public ServiceScope(IServiceScope scope) => _scope = scope;

    public T GetRequiredService() => _scope.ServiceProvider.GetRequiredService<T>();

    public T GetService() => _scope.ServiceProvider.GetService<T>();

    public IEnumerable<T> GetServices() => _scope.ServiceProvider.GetServices<T>();

    #region IDisposable/Dispose methods ( https://stackoverflow.com/a/538238/530545 )
    bool _disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool calledFromCodeNotTheGarbageCollector)
    {
        if (_disposed)
            return;
        if (calledFromCodeNotTheGarbageCollector)
        {
            // dispose of manged resources in here
            _scope?.Dispose();
        }
        _disposed = true;
    }

    ~ServiceScope() { Dispose(false); }
    #endregion

}

You'd register this like so:

services.AddSingleton(typeof(IServiceScopeFactory<>), typeof(ServiceScopeFactory<>));

And to work with your example, you'd use it like so (assuming you registered your ConmaniaDbContext):

public class Foo
{
    readonly IServiceScopeFactory<ConmaniaDbContext> _dbCtxFactory;

    public Foo(IServiceScopeFactory<ConmaniaDbContext> dbCtxFactory) => _dbCtxFactory = dbCtxFactory;

    public void Bar()
    {
        using var scope = _dbCtxFactory.CreateScope();
        var db = scope.GetRequiredService();
        //use service
    }
}

FYI/Backstory

FYI, I'm using this in a .Net Core 3.x app that's leveraging Gql.Net. This pattern makes it so I can actually use EFC. Gql.Net's field resolvers run in parallel, so if you don't do something like this, you cannot use your constructor-injected DbContext in more than one field, or you wind up getting this EFC exception (which is not unique to Gql.Net):

  [InvalidOperationException] A second operation started on this context
  before a previous operation completed. This is usually caused by
  different threads using the same instance of DbContext. For more
  information on how to avoid threading issues with DbContext, see
  https://go.microsoft.com/fwlink/?linkid=2097913.

I've confirmed this solves that "parallel execution in the same Http request" issue for me. I can now run multiple, concurrent tasks against the database from the same instance of a scoped service class. It's because with this solution, instead of all threads using the same DbContext that was injected into the constructor, they now each resolve their own, scoped DbContext instance when they need it.


Classifying the aspect ratio of the screen dimensions

The firs thing worth pointing out is that you are ignoring a lot of special meaning with your current approach. Aspect ratios are a function determined by Width : Height and thus we can use an aspect ratio and an inputted Width and Height to get the aspect we want, instead of looking through a list that are just saying the same thing in different ways.

I took your original code and calculated each aspect ratio in order. Here are the results:

'    1.77777777777778 16:9
'    1.6 16:9
'    1.77777777777778 16:9
'    1.77864583333333 16:9
'    1.77083333333333 16:9
'    1.77777777777778 16:9
'    2.13333333333333 16:9
'    1.6 8:5
'    1.25 8:5
'    1.33333333333333 8:5
'    1.33333333333333 4:3
'    1.33333333333333 4:3
'    1.25 4:3
'    1.33333333333333 4:3
'    1.33333333333333 4:3
'    1.33333333333333 4:3
'    1.33333333333333 4:3

A reduced list would look like this:

'1.77... ' 16:9
'1.6     ' 16:9
'1.778   ' 16:9
'2.133   ' 16:9
'1.6     ' 8:5
'1.25    ' 8:5
'1.33... ' 8:5
'1.33... ' 4:3
'1.25    ' 4:3

Aside from the couple of instances of a single ratio being matched to two different aspects, they are fairly consistent. So then I checked each of the original aspects and their results:

?16/9
 1.77777777777778
?8/5
 1.6
?4/3
 1.33333333333333

In turn, we have a very simple function to get an aspect ratio from a width and height:

Public Function GetAspectRatio(ByVal Width As Long, ByVal Height As Long) As String
    Select Case Round(Width/ Height, 3)
    Case Is <= 1.33
        GetAspectRatio = "4:3"
    Case Is <= 1.6
        GetAspectRatio = "8:5"
    Case Is > 1.6
        GetAspectRatio = "16:9"
    Case Else
        ' Error : Ratio not pre-defined.
    End Select
End Function

Then your original code becomes this:

Declare Function GetSystemMetrics32 Lib "User32" _
    Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long

Sub DisplayAspectRatio()
    Dim Width As Long
    Width = GetSystemMetrics32(0)

    Dim Height As Long
    Height = GetSystemMetrics32(1)

    MsgBox "Your aspect ratio is : " & GetAspectRatio(Width, Height)
End Sub

We could improve this a bit further by employing the use of constant values and such, but overall this will point you in the right direction.

Note that, with the improved code, I made sure to use clear variable names. Most users will understand what h means in context, but Height is clear to any user. Even better would be WindowHeight so that, even if your reader was completely dumb to reading code, they would know what that variable was. Same goes for naming Functions, and Subroutines.

Best of luck!


No need to convert to int

Since for all digits '0'...'9', comparison works consistently as you would expect from integers, no need to convert to integers.
So instead of this:

numlist = [int(i) for i in str(num)]

You can simplify to:

numlist = list(str(num))

(I would also rename numlist to digits.)

Use range(...)

Instead of manually decrementing loop indexes,
for example with  i -= 1,
it's more idiomatic to use a range(...).
For example, instead of:

i = len(numlist) - 1
while i > 0:
    if numlist[i] > numlist[i-1]:
        index_of_replace_num = i - 1
        break
    i -= 1

I recommend this writing style:

for i in range(len(numlist) - 1, 0, -1):
    if numlist[i] > numlist[i-1]:
        index_of_replace_num = i - 1
        break

Use early returns to reduce nesting

Instead of this:

if index_of_replace_num == -1:
    return -1
else:
    # many many lines of code ...

It becomes a bit more readable if you drop the else statement:

if index_of_replace_num == -1:
    return -1

# many many lines of code ...

Decompose to smaller functions

Instead of putting all the logic inside the next_bigger function,
it would be good to decompose to smaller logical steps,
which can be extracted into their own functions.
Decomposing to many smaller functions increases modularity of your programs,
makes testing easier,
and often leads to reduced duplication.

Alternative implementation

Consider this alternative implementation,
with the main method decomposed to smaller logical steps that are unit tested.
You can run these doctests with the command:

python -mdoctest next_bigger.py

Empty output means all tests pass (or that there are no tests).

In addition to doctests, it's of course recommended to write proper docstrings too, which I omitted for brevity.

def swap_first_with_higher(digits):
    """
    >>> swap_first_with_higher(list('59853'))
    ['8', '9', '5', '5', '3']

    """
    for pos in range(len(digits) - 1, 0, -1):
        if digits[0] < digits[pos]:
            digits[0], digits[pos] = digits[pos], digits[0]
            break
    return digits

def reversed_tail(digits):
    """
    >>> reversed_tail(list('89553'))
    ['8', '3', '5', '5', '9']

    """
    return [digits[0]] + digits[1:][::-1]

def next_biggest(num):
    """
    >>> next_biggest(59853)
    83559

    >>> next_biggest(111)
    -1

    >>> next_biggest(11211)
    12111

    """
    digits = list(str(num))
    for pos in range(len(digits) - 1, 0, -1):
        if digits[pos-1] < digits[pos]:
            left = digits[:pos-1]
            right = reversed_tail(swap_first_with_higher(digits[pos-1:]))
            return int(''.join(left + right))

    return -1


Avoid use dictionary when you need Array
I'm not sure why you would prefer to store your Array-like data in a dictionary. I would suggest use a real Array if you need an Array.
Order of Object.keys
You may read more details about the order of Object.keys return values from this post: Does ES6 introduce a well-defined order of enumeration for object properties? The order of Object.keys is defined in ES2020. It may not work as you want in older environments.
Anyway, relay on the order of Object.keys don't seems to be a good idea to me. You may always sort the keys after Object.keys if you want though.
Use Object.assign to convert to / from Array
When you need an Array, use an Array. You can try Object.assign which convert your dictionary into Array and vice versa. (But this only applied to "when you cannot change the interface due to any reason").
function filterData(data, value) {
    const arrayData = Object.assign([], data.map);
    const filteredArrayData = arrayData.filter(list => list.includes(value));
    const result = Object.assign({}, filteredArrayData);
    return result;
}


Removing Promise constructor wrappers

As @Peilonrayz mentioned in his comment, we can return the promises directly instead of wrapping them in Promise constructors.

From the MDN: Promise docs:

  The constructor is primarily used to wrap functions that do not already support promises.

Since we are already returning promises (and not wrapping callbacks, for example) we can remove the constructors.

For example, doWithBitstampProperties:

const doWithBitstampProperties = function() {
    return new Promise(function(resolve, reject){
        if (BITSTAMP_PROPERTIES) {
            resolve(BITSTAMP_PROPERTIES);
        } else {
            decryptBitstampProperties().then(resolve).catch(reject);
        }
    });
};

Could be rewritten to return the promise directly:

const doWithBitstampProperties = function() {
  if (BITSTAMP_PROPERTIES) {
    return Promise.resolve(BITSTAMP_PROPERTIES);
  }

  return decryptBitstampProperties();
};

Or, using the conditional operator if you preferred to be more terse:

const doWithBitstampProperties = function() {
  return BITSTAMP_PROPERTIES
    ? Promise.resolve(BITSTAMP_PROPERTIES)
    : decryptBitstampProperties();
};

We can repeat this pattern for the other functions and reduce the noise that all the resolve/rejects added:

const AWS = require('aws-sdk');
const crypto = require('crypto');
const got = require('got');

const CURRENCY_PAIR = 'btceur';
const TICKER_URL = `https://www.bitstamp.net/api/v2/ticker/${CURRENCY_PAIR}/`;
const BUY_LIMIT_ORDER_URL = `https://www.bitstamp.net/api/v2/buy/${CURRENCY_PAIR}/`;

if (!AWS.config.region) {
    AWS.config.update({ region: 'eu-central-1' });
}

const ENCRYPTED_BITSTAMP_CUSTOMER_ID = process.env.BITSTAMP_CUSTOMER_ID;
const ENCRYPTED_BITSTAMP_KEY = process.env.BITSTAMP_KEY;
const ENCRYPTED_BITSTAMP_SECRET = process.env.BITSTAMP_SECRET;
const VALUE = Number(process.env.VALUE);
const MINIMUM_VALUE = 5;

if (isNaN(VALUE) || VALUE < MINIMUM_VALUE) {
    throw new Error(`Invalid value [${value}], must be a number not less than [${MINIMUM_VALUE}].`);
}

const kms = new AWS.KMS();

const decrypt = function(encrypted) {
    return kms
        .decrypt({ CiphertextBlob: new Buffer(encrypted, 'base64') })
        .promise()
        .then(data => data.Plaintext.toString('ascii'))
};

let BITSTAMP_PROPERTIES;

const decryptBitstampProperties = function() {
    return Promise.all([
        decrypt(ENCRYPTED_BITSTAMP_CUSTOMER_ID),
        decrypt(ENCRYPTED_BITSTAMP_KEY),
        decrypt(ENCRYPTED_BITSTAMP_SECRET)
    ]).then(([customerId, key, secret]) =>
        BITSTAMP_PROPERTIES = { customerId, key, secret }
    );
})};

const doWithBitstampProperties = function() {
    return BITSTAMP_PROPERTIES
        ? Promise.resolve(BITSTAMP_PROPERTIES)
        : decryptBitstampProperties();
};

const createAuthData = function(customerId, key, secret) {
    const nonce = Date.now();
    const message = nonce + customerId + key;
    const signature = crypto
    .createHmac('sha256', new Buffer(secret, 'utf8'))
    .update(message)
    .digest('hex')
    .toUpperCase();

    return { key, signature, nonce };
};

const getAskPrice = function() {
  return got(TICKET_URL).then(response => {
    const result = JSON.parse(result);
    const ask = Number(result.ask);

    if (!isNaN(ask)) {
      return ask;
    }

    throw new Error(`Could not parse the ask price from [${BTCEUR_TICKER_URL}] response:\n${response.body}`);
  });
});

const buyLimitOrder = function(customerId, key, secret, value, askPrice) {
    const amount = value / askPrice;
    const roundedAmount = Math.ceil(amount * Math.pow(10,5)) / Math.pow(10,5);

    const order = {
        ...createAuthData(customerId, key, secret),
        amount: roundedAmount,
        price: askPrice
    };

    console.log(`Buying ${roundedAmount} of BTC for price ${askPrice} for total value of ${roundedAmount * askPrice}.`);

    return got.post(BUY_LIMIT_ORDER_URL, {
        body: order,
        form: true
    }).then(response => {
        return JSON.parse(response.body);
    });
};

const getAskPriceAndBuyLimitOrder = function(customerId, key, secret, value) {
    return getAskPrice()
        .then(askPrice => buyLimitOrder(customerId, key, secret, value, askPrice));
};

exports.handler = (event, context, callback) => {
    doWithBitstampProperties()
        .then(bitstampProperties =>
            getAskPriceAndBuyLimitOrder(bitstampProperties.customerId, bitstampProperties.key, bitstampProperties.secret, VALUE)
                .then(result => callback(null, result))
                .catch(error => callback(error)))
        .catch(error => callback(error));
};

A few other potential changes...

Preferring const over let to denote a variable can't be reassigned (but still mutable)
Date.now() can be used instead of (new Date()).getTime()
Returning early to prevent else blocks
Moving BITSTAMP_PROPERTIES declaration closer to where it's assigned
Using the spread operator to prevent mutating orders (Note: this is currently a stage 3 draft at time of writing)
Using template literals for more succinct strings
Using array matching instead of indices to for customerId, key and secret
Using node-fetch instead of got to be consistent with the browser's Fetch API. JSON requests would be of the form fetch(...).then(res => res.json()).then(data => ...) instead of calling JSON.parse


Recursively find TypeScript files imported/exported from an entry point

Update

As the OP is been updated and changed I want to change my answer, I'll live the original at the end.

I see you use Object Oriented other than functional, so I'll comment some I saw that is not ok for me.

Encapsulation broken

Looking at your code I see the broken of encapsulation. This means that from a piece of code you access or worst you try to change some internal data of an object.

You should not do that. Rather you should improve the object to provide a propper interface.

Here is an example from your code in handleFile():

...
const destFilePath = file.path.replace(baseDir, destDir);
copyFile(file, destFilePath);
...

The issue here is you have to know to that baseDir should match with the file path attribute.

A better way would be just:

copyFile(file, destDir);

in this case you conain inside the copyFile() function the details about using the path.replace... staff. So you avoid to copy a file in another part of your source code and forgot this part.

Another reason to put the logic inside the copyFile() function is that you could actually remove that line:

function copyFile(file: VinylFile, destFilePath: string): void {
    const destDir = path.dirname(destFilePath);
    ensureMakeDir(destDir);
    writeFile(destFilePath, file.contents.toString());
}

I think you just want to place the file name at the end of the new path. The first line of the function here, you just do a rollback of this part.

function copyFile(file: VinylFile, destDir: string): void {
    ensureMakeDir(destDir);
    const destFileName = path.join(destDir, path.basename(file.path));
    writeFile(destFileName, file.contents.toString());
}

This is a little bit better because you contain the VinyFile details in a single function, and you could change it without worring that something will broke in your code.

But is not the best!
A better solution will be if the file know how to copy to another path, in such a way you should not deal with the object internal details.

You should be able to do:

file.copyTo(destDir);

If you try to write such a method you will notice that the code needed is simplest and much clear.

And you could maintain all the object boundary safe from the code base.

Another small thing here. I saw you use the path package before, so please avoid some trick like:

file.path.replace(baseDir, destDir);

It is difficult to understand and easy to broke.

Also the getVinyl() could be removed, the VinylFile should know how to load his content properly.

Here on getChildren():
    while ((match = statementRE.exec(file.contents.toString())) && !isNil(match))

Correction

  I checked the Javascript RegEx documentation of exec and in the examples they show a case where you use exec() with the option g. In this case you could have a loop as the regex object save the lastIndex and consider just a substring.

  Anyway, if you remove g option exec() will behave differently, and that is dangerous.

  For that reason I found out that the following sentence is not accurate.

Not sure why you use a loop as exec should return the matching. As the file content is not changing you will loop forever.

And this part I'm sure is not working:

    debugger;
    const indexBarrel = path.resolve(resolvedPath, 'index.ts');

There is still the debugger... :)
I think you run this code on server side so that line have no effects, but please remove it, just in case.

The getChildren() function should be moved as a method of VinylFile. Here I use only es6 syntax as I don't know Typescript, but I think it will be easy to move on the proper syntax.

// should be a VinylFile attribute or a private const
const statementRE = /(import|export)\s*((\{[^}]*\}|\*)(\s*as\s+\w+)?(\s+from)?\s*)?([`'"])(.*)\6/ig;

hasChildren() {

   if (subFilesMatch != null) {

   }
   return false;
}

getChildren(): VinylFile[] {
    const children: VinylFile[] = [];

    let subFilesMatch = statementRE.exec(this.contents.toString()));
    if (!isNil(subFilesMatch)) {
        const filePath = subFilesMatch[FILE_PATH_MATCH_INDEX];

        // Again don't use triks rather use the packages features!
        if (path.extname(filePath) !== '.ts') {
            filePath += '.ts';
        }
        const childFileName = path.join(this.base, filePath);
        if (isFile(childFileName)) {
            // Here I just rearrange your code, but you have an issue here!
            // I don't know how many children you have on each file instance
            // but *getChildren()* is synchronous function, so the file
            // content load is blocking!
            const contents = loadContents(childFileName);
            const opts = {base: this.base, path: childFileName, contents}
            children.push(new VinylFile(opts));
        } else if(isDirectory(childFileName)) {
            ...
        }
    }

    return children;
 }

As prompted in the comment above, your method here, even the original function, is blocking code, as it load the file content of the children sinchronously.

You should convert this too in an async function. I don't know the syntax in Typescript.

Last but not last handleFile()
It is an async function and should return a promise and it doesn't.

Maybe Typescript is honoring the function signature and returning a promise in any case, and, I guess, in a working like mode, so you think the code is fine.

Please check this part too.

As I said before, you should create an array of promises and return it from getChildren(), and then return a Promise.all() from handleFile().

I'll do this in javascript.

Original answer

I'm not a big expert of functional programming, but your example did not fit.

I guess so.

The first point is that you create a list of random numbers. This end up in a different list each time.

In functional programming, a function should take input and produce output, and given the input it should return always the same output.

So, you just set up a trivial example, but in my above definition you just could notice other issues.

The parameter name resultList, is not the "resultList", is just the start list that is going to be fit of 10 random numbers.

function SampleRecursiveFunction(resultList) {
  // copy our list
  const result = [...resultList];

Instead of resultList you should have a different name like: inputList.

Another bad name is result.

You should use some much helpfull like: randomNumberList

  function SampleRecursiveFunction(inputList, maxLength = 10) {
      if (inputList.length >= maxLength)
          return [...inputList];

      let randomNumber = Math.random()*100;
      while(inputList.length > 0 &&
            inputList.indexOf(randomNumber) !== -1)
          randomNumber = Math.random()*100;

      return SampleRecursiveFunction([...inputList, randomNumber], maxLength);
  }

This is a small evolution of your function with recursion.

The function accept a new parameter that set the returned list max length.

An even better version could be like:

function GetRandomNumber(seed) {
    return function () {
        return Math.random() * seed;
    }
}

This function return a function that provide the proper next value.

In real case you could have a generation function instead, depending on what you're doing.

function SampleRecursiveFunction(inputList, getNewNumber, maxLength = 10) {
      if (inputList.length >= maxLength)
          return [...inputList];

      let randomNumber = getNewNumber();
      while(inputList.length > 0 &&
            inputList.indexOf(randomNumber) !== -1)
          randomNumber = getNewNumber();

      return SampleRecursiveFunction([...inputList, randomNumber], maxLength);
  }

And you could compose the function like this:

  console.log(SampleRecursiveFunction([], GetRandomNumber(100)));

The good of this is you could split your logic into small tasks and put them in functions. At the end you compose those functions and building your whole logic.

As we deal with random numbers, even my example is not pure functional, I just try to give you a review of your code example.

I think you should find a more detailed example on what you're tring to do to have a much usefull help.


There's a safe way to do that using System.Runtime.InteropServices.Marshal (link).
[StructLayout(LayoutKind.Sequential, Size = 8, Pack = 4)]
struct DataPacketStruct
{
    public byte Header { get; set; }
    public int Size { get; set; }

    public void Serialize(byte[] buffer, int startIndex)
    {
        int size = SizeOf();
        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(this, ptr, true);
        Marshal.Copy(ptr, buffer, startIndex, size);
        Marshal.FreeHGlobal(ptr);
    }

    public static DataPacketStruct Deserialize(byte[] buffer, int startIndex)
    {
        var result = new DataPacketStruct();
        int size = result.SizeOf();
        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.Copy(buffer, startIndex, ptr, size);
        result = (DataPacketStruct)Marshal.PtrToStructure(ptr, typeof(DataPacketStruct));
        Marshal.FreeHGlobal(ptr);
        return result;
    }

    public int SizeOf() => Marshal.SizeOf(this);
}

Also I used public properties and followed the Naming Guidelines in the example.
static void Main(string[] args)
{
    var data = new DataPacketStruct() { Header = byte.MaxValue, Size = int.MaxValue };
    byte[] a = new byte[8];
    data.Serialize(a, 0);
    Console.WriteLine(string.Join(" ", a.Select(x => x.ToString("X2"))));
    var data2 = DataPacketStruct.Deserialize(a, 0);
    Console.WriteLine(JsonSerializer.Serialize(data2, new JsonSerializerOptions { WriteIndented = true }));
    Console.ReadKey();
}

Output:
FF 00 00 00 FF FF FF 7F
{
  "Header": 255,
  "Size": 2147483647
}