Iterate over a short list, pairing the elements with the sequential elements of a longer list

Creating a "manual" iterator using iter and then calling next can be tricky, as you found out.
Once an iterator is exhausted, it raises a StopIteration to signal its end.
If you do not catch that in a try/except block, your program will exit ungracefully.

Luckily, message, being a list, is perfectly iterable without being explicit about it.
Simply using it in a for loop will do the iter/next magic for you, and the loop will exit once StopIteration is reached, without error.

zip is a built-in so you can iterate over multiple iterables at once.
zip will iterate until the shortest of the passed iterables is exhausted.
This can be tricky if you expect the iterables to be of the same length.
There is currently talk about a strict flag in the Python ideas mailing list, which would throw errors if strict=True and the iterables are of different lengths.

Assuming you meant to include from itertools import cycle, alongside cycle, of course message is exhausted first.
cycle being infinite, this suprises no one in this case.
The for loop then simply ends after the last message element.

This hopefully does what you want to do:

from itertools import cycle

keys = [3, 1, 20]
message = ["a", "b", "c", "d", "e", "f"]

print(keys, message, sep="\n", end="\n" * 2)

for key, letter in zip(cycle(keys), message):
    print(f"{key}: {letter}")

print("Okay, it worked!")

This is more like your version, needlessly verbose.
Never do this in reality!
However, it can help you understand what is going on in your case:

from itertools import cycle

keys = [3, 1, 20]
message = ["a", "b", "c", "d", "e", "f"]

print(keys, message, sep="\n", end="\n" * 2)

message_iter = iter(message)

for key in cycle(keys):
    try:
        print(f"{key}: {next(message_iter)}")
    except StopIteration:
        break  # Break out of infinite loop

print("Okay, it worked!")


Optimizing PHP script fetching entire HTML pages

Performing this task in parallel would help greatly although PHP is not the best language to do so in.

I would do so by spawning PHP processes by POSTing to other PHP scripts (asynchronously), possibly posting to them the links they should get. You would need to store whether the line is available or not in a database, I would use SQLite in this case (it doesn't need a server to be setup).

So a possible setup could look something like:

Master Process: Splits the main link file into n parts then POSTs the parts to the child pages. It would need to know when the child processes are finished, it could do so by having a polling loop that checks if the number of rows in the database is equal to the number of links, you would need to make sure you put in a sleep function so it doesn't poll too often. When the child processes are done and the polling breaks out, you could then take the data in the database and convert it to CSV.

Child Processes: This page receives a set of links via POST, it then goes through each one checking if it contains the string and marking the result down in the database.

I would not use this for production code, PHP is not made for this and there are lots of things that could go wrong. If it was possible I would do this sort of thing in languages with built in parallelism such as Golang or Clojure.


We can replace some custom functions or constructs by standard library ones:

\(x:_) -> x is called head
not . even is called odd

Next, 1 is not a prime, and 1 does not have a prime factorization. Since product [] yields 1, we can use [] instead in prmfctrs'.

The worker prmfctrs' is a mouthful. Workers are usually called the same as their context (but with an apostrophe, so primefactors') or short names like go.

And last but not least, we can use @ bindings to pattern match on the head, tail and the whole list at once.

If we apply those suggestions, we get

import Data.List (group)

toPerfectSquare :: Int -> Int
toPerfectSquare n = product . map head . filter (odd . length) . group $ primefactors n

primefactors :: Int -> [Int]
primefactors n = go n 2 [3,5..]
  where
    go m d ds@(p:ps) | m < 2     = []
                     | m < d^2   = [m]
                     | r == 0    = d : go q d ds
                     | otherwise = go m p ps
      where (q, r) = quotRem m d

In theory, we can even get rid of a parameter in go, namely the d, so that we always just look at the list of the divisors:

import Data.List (group)

toPerfectSquare :: Int -> Int
toPerfectSquare n = product . map head . filter (odd . length) . group $ primefactors n

primefactors :: Int -> [Int]
primefactors n = go n $ 2 : [3,5..]
  where
    go m dss@(d:ds) | m < 2     = []
                    | m < d^2   = [m]
                    | r == 0    = d : go q dss
                    | otherwise = go m ds
      where (q, r) = m `quotRem` d

We could also introduce another function \$f\$, so that for any \$a,b \in \mathbb N\$ we get a pair \$(n,y) \in \mathbb N^2\$ such that

$$
a^n y = b
$$
If we had that function, we could write use it to check easily whether the power of a given factor is even or odd. However, that function and its use in toPerfectSquare are left as an exercise.


Apply classes to selected XHTML elements based on content

You could just create the class based on the value of the td.

Input (I added a td that should not be modified by the stylesheet.)

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Title</title>

                A1
                A2
                B1
                B2
                C1
                C2
                ignore me

XSLT 2.0

<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xpath-default-namespace="http://www.w3.org/1999/xhtml">
  <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="tds" select="('A2','B1','B2','C1','C2')"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="td[normalize-space()=$tds]">
    <xsl:copy>
      <xsl:attribute name="class"
        select="concat('mytable-',lower-case(normalize-space()))"/>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Output

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <title>Title</title>

            A1
            A2
            B1
            B2
            C1
            C2
            ignore me

Notes:

In my match, I didn't use the // abbreviated syntax (match="//td"); I just used match="td".
I used xsl:param instead of using the sequence ('A2','B1','B2','C1','C2') directly in the match so that it could be passed in at runtime. This would allow you to change which td elements were modified without changing the actual code.
Try to use a select attribute on xsl:attribute, even when outputting plain text (<xsl:attribute name="class" select="'mytable-c2'"/>). This prevents creating unnecessary RTF's (result tree fragments).
I use normalize-space() when creating the class to strip any leading/trailing whitespace in the text() node.
After creating the class attribute, we do an xsl:apply-templates on @*. If there is an existing class attribute, it will overwrite what we just created. If this is a possibility, I'd do an xsl:apply-templates on @*, then create the new class attribute (overwrites the existing class or you can concat the new and old), and then finally do the xsl:apply-templates on node().


Instead of parsing an Int with the catch (e: NumberFormatException) { ... }, consider using the String.toIntOrNull() extension:

val x = readLine().toIntOrNull() ?: run {
    println("You didn't type a valid number.")
    return
}

In Kotlin extension functions, reference the members of the receiver type without explicit this: this.size → size unless the name is ambigous.
Instead of (0 until this.size / 2).map { this.elementAt(it) }, you could just use take(size / 2) (but see below why you should not).
The approach you take to check in which half the item can be located and move the binary search window to a half of the list (by copying or removing the first half) changes the run time of the algorithm significantly: while binary search should take \$ O(log n) \$ time to find an element, your implementation additionally performs \$ O(n/2 + n/4 + n/8 + ...) = O(n) \$ operations checking the first half and then copying or removing the items, making the search asymptotically as slow as serial search through the list. Consider checking only the item in the middle of the list (the assumption that the list is sorted allows you to do that) and then using .subList(...) to get a view of a portion of the original list, in \$ O(1) \$ time.


Directory.EnumerateDirectories(str1, "*", SearchOption.AllDirectories).ToArray();

Calling ToArray on this is counterproductive because this method returns directory names one by one (in a deferred fasion) as you go and request them. By using ToArray you go over directory names twice. First creating the array and then in your for loop. The EnumerateDirectories is a perfect candidate to be used with Parallel.ForEach or with AsParallel.

For example this is on my machine with 20k empty directories faster by approx 3 sec then the normal loop:

var emptyDirectories = Directory
    .EnumerateDirectories(str1, "*", SearchOption.AllDirectories)
    .AsParallel()
    .Where(d => !Directory.EnumerateFileSystemEntries(d).Any())
    .ToList();

Here you not only take the advantage of the AsParallel but also of the Any that does not have to enumerate all entries but stops as soon as at least one is found.

To delete the empty directories you can use the ForAll extension o a parallel enumeration:

var emptyDirectories =
    from d in Directory.EnumerateDirectories(str1, "*", SearchOption.AllDirectories).AsParallel()
    where !Directory.EnumerateFileSystemEntries(d).Any()
    select d;

emptyDirectories.ForAll(d => { /* delete directory */ });

The above method will of course delete only the last directory. If you want to delete directories that are empty after deleting the last empty directory you need to repeat the process:

var deleted = false;
do
{
    deleted = false;
    emptyDirectories.ForAll(d => { Directory.Delete(d); deleted = true; });
}
while(deleted);

The counterpart of the EnumerateDirectories is the EnumerateFiles method that you can use same way and you can figure out this part yourself ;-)


Not much to improve upon, just some minor housekeeping.

Help the end user!

If I was using this script, and forgot to put one or both of the filepaths when calling the script, there would be this error: IndexError: list index out of range. This error wouldn't help the user in a significant way. Consider this:

try:
    path1 = sys.argv[1]
    path2 = sys.argv[2]
except IndexError:
    raise Exception("Usage: python3 jpg_to_png.py <path to input folder> <path to output folder>")

This gives the user a detailed message on how the use your script.

Remove commented code.

Code you don't need anymore adds useless clutter, and can make your code harder to read.


Check if a Binary Tree  is aBinary Search Tree

There are some serious problems with this function.

Issues of correctness

Code won't compile: If BinaryNode indeed has fields named getData, getLeftChild, and getRightChild that are of type String, then you can't use operators < and > on them.  For strings, as with any object, you have to use a.compareTo(b).
No consideration for unbalanced or incomplete trees: If a node has only one child, what happens?
Check for tree == null after tree.getRootData: There's no point in checking for tree == null, since it would have crashed on tree.getRootData with a NullPointerException already if that were the case.
Recursive check is insufficient: As @user2668926 points out, you have to verify that all nodes within a subtree fall within a range of values.

Serious violations of style conventions

Using an uppercase variable name: In Java, variable names should be lowerCase, except constants, which should be ALL_CAPS.  By naming a variable Node, you hurt readability tremendously by making it look like the name of a class.
Using getSomething as field names: The convention is that getSomething() is the name of a getter method (i.e., a member function), usually corresponding to an instance variable named something.  Instead, you seem to have instance variables named getRootData, getData, getLeftChild, and getRightChild in your BinaryTree and BinaryNode classes, which is exceedingly weird.

I consider these two issues to be extremely serious, even if the compiler accepts the code and the algorithm runs.  These are not "merely" conventions — they are major traps for anyone else who works with your code, enough for every programmer to go facepalm.

Less serious issues of style

Distinction between BinaryTree and BinaryNode: Wrapping nodes as trees and unwrapping the tree's root node is cumbersome.  Do you really have to make a distinction between trees and nodes?  Could you not just treat any node as a tree rooted there?
Use of generics: The BinaryTree class is genericized, so your code should also aim to be generic.  The method signature should look something like

public class BSTVerifier {
    public static <T extends Comparable> boolean isBST(BinaryTree<T> tree) {
        ...
    }
}

Alternatively,

public class BSTVerifier<T extends Comparable> {
    public boolean isBST(BinaryTree<T> tree) {
        ...
    }
}


Converting Date object in CoffeeScript to string (with a weird format)

First of all, your given sample features zero-padded 2-digit months and milliseconds which you currently don't reproduce.

The mentioned 'smell' is probably caused by

the 'manual' zero-padding of the timezone offset and its many if-else branches
the many hardcoded numbers and strings
the long illegible string concatenation

We can get rid of the self-made zero-padding by using String.padStart() or - if compatibility is a concern - one of its many alternative implementations.

We can't really get rid of the many hardcoded constants, but we can name them to make them meaningful and less magic in appearance:

const seperators = ['/', '/', ' ', ':', ':', ':', ' ', '', '', ''];

We can then replace the large string concatenation expression by leveraging one of those array's reduce or map method:

function formatDate(date) {
  const values = [
    date.getMonth() + 1,
    date.getDate(),
    date.getFullYear(),
    date.getHours(),
    date.getMinutes(),
    date.getSeconds(),
    date.getMilliseconds(),
    date.getTimezoneOffset() > 0 ? '-' : '+',
    Math.abs(date.getTimezoneOffset() / 60),
    Math.abs(date.getTimezoneOffset() % 60)
  ];
  const digits = [2, 2, 4, 2, 2, 2, 3, 0, 2, 2];
  const seperators = ['/', '/', ' ', ':', ':', ':', ' ', '', '', ''];

  return values.map((value, i) =>
    value.toString().padStart(digits[i], '0') + seperators[i]
  ).join('');
}

console.log(formatDate(new Date()));

That's it. I don't see how we can leverage any other built-in method to shorten above task. Using JavaScript's built-in Date.toLocaleTimeString('en-US', options) gets us pretty far, but it is missing timezone offset and millisecond options and introduces unwanted separators:

const options = {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false
};

console.log(new Date().toLocaleString('en-US', options));

PS: Above code should translate pretty easily to coffeescript, but as I am not very well versed in that language, I chose to give code samples in vanilla JS.

Edit: Instead of getDay() you probably want to use getDate().


Building a frequency dictionary from a Pandas dataframe

Yes, iterating through a dataframe usually is at odds with the spirit of dataframes and numpy arrays. They are best suited for vectorized operations, which are operations applied in bulk to rows/columns of the data structure.

Assuming that you've cast templates as an int64 or similar, you can use pd.groupby to do the same sort of grouping as you are doing with your dictionary:

import pandas as pd

df
        amino_acid  templates
0  CAWSVGQYSNQPQHF        118
1    CASSLRGNQPQHF        635
2    CASSHGTAYEQYF        468
3  CASSLDRLSSGEQYF        239
4    CSVEDGPRGTQYF         51
5  CASSLDRLSSGEQYF         66    # I've added this extra row here to show the effect

# these act as Series objects, so you can add together the
# grouped templates values
df.groupby('amino_acid')
# pd.groupby object

# use pd.Series.sum() to do this:
df.groupby('amino_acid').sum()

                 templates
amino_acid
CASSHGTAYEQYF          468
CASSLDRLSSGEQYF        305    # this was added for the two amino acids
CASSLRGNQPQHF          635
CAWSVGQYSNQPQHF        118
CSVEDGPRGTQYF           51

So what's going on in df.groupby? Well, you give it what to group on first. In this case, you group on the value for amino_acid. This creates a data structure that looks quite familiar if you've used itertools.groupby: tuples of (grouping key, DataFrame) pairs, where the DataFrame is a subset that matches the key. For example:

tmp = [(x, y) for x,y in df.groupby('amino_acid')]

[('CASSHGTAYEQYF',       amino_acid  templates
2  CASSHGTAYEQYF        468),
('CASSLDRLSSGEQYF',         amino_acid  templates
3  CASSLDRLSSGEQYF        239
5  CASSLDRLSSGEQYF         66),
('CASSLRGNQPQHF',       amino_acid  templates
1  CASSLRGNQPQHF        635),
('CAWSVGQYSNQPQHF',         amino_acid  templates
0  CAWSVGQYSNQPQHF        118),
('CSVEDGPRGTQYF',       amino_acid  templates
4  CSVEDGPRGTQYF         51)]

And per the docs, [df.sum] will return the sum on the specified axis (1 by default). So, for tmp[1], which contains two rows:

tmp[1][1].sum()

amino_acid    CASSLDRLSSGEQYFCASSLDRLSSGEQYF
templates                                305
dtype: object

Where 305 is the sum. The pd.groupby object as a whole supports the .sum call, so we are able to call it like we did above.

# Now, using `to_dict`, you can see that you want what's inside templates
df.groupby("amino_acid").sum().to_dict()

# {'templates': {'CASSHGTAYEQYF': 468, 'CASSLDRLSSGEQYF': 305, 'CASSLRGNQPQHF': 635, 'CAWSVGQYSNQPQHF': 118, 'CSVEDGPRGTQYF': 51}}

# so use the templates attribute to grab it
df.groupby("amino_acid").sum().templates.to_dict()
# {'CASSHGTAYEQYF': 468, 'CASSLDRLSSGEQYF': 305, 'CASSLRGNQPQHF': 635, 'CAWSVGQYSNQPQHF': 118, 'CSVEDGPRGTQYF': 51}

This applies the operations within the dataframe, which is more efficient than a loop. The analogue that you were trying to use could leverage defaultdict from the collections module, as well. It prevents the need to check for a key's existence, speeding up the loop immensely:

from collections import defaultdict

# specify your input type here
sequence_counts = defaultdict(int)

# it is more pythonic to use tuple-unpacking in loops
# as indexing is less readable
for amino, template in zip(df.amino_acid, df.templates):
    sequence_counts[amino] += template

Also, by iterating over the zip object directly, you don't copy data into memory. list will aggregate all of the members into a data structure, whereas zip is a generator that will just produce the members one at a time until exhausted. It's like the difference between for x in range and for x in list(range):

# This will just run for a really really really long time
for i in range(1000000000000):
    print(i)

# This will crash your computer, it will never
# get to the print statement, because it must evaluate
# list(range) before it starts the loop
for i in list(range(1000000000000)):
    print(i)


Caching a JS selector then only using it once

My general rule of thumb is to cache a selector lookup within a given function so you only look it up once for each function invocation, but to not cache it globally.

If something was being called hundreds or thousands of times in a loop, you would want to cache it outside the loop just for common sense efficiency.

Caching things globally is pretty much never needed for user event types of things because the performance of looking up a few objects in the DOM is super fast when compared to any sort of user action time.  In other words, you wouldn't be able to tell the difference so you might as well go with the most maintainable and reliable code which avoids unnecessary globals.


One big issue with this code is that you've got a tight coupling between the business logic and the presentation.  For example, the method play() really jumps out:

public function play(){

    return '<input type="button" value="Play" onclick="window.location = \'?play=1\'">';

}

From its name I'd think that this method plays something (a game? A piece of music? A role in a play? Another issue is clear, unambiguous naming of classes, methods and variables).  I wouldn't expect it to output the HTML markup for a button with a JavaScript event attached to it.

This might not seem like a big deal, and in this particular case it probably isn't.  But ask yourself this, how much work would you need to do if whoever set you this project decided half way though that it should run through the command line instead of a web browser?

Ideally, your PHP classes should contain no presentation logic at all.  They should return data structures (arrays, scalar types, simple data transfer objects, etc) to the outside world, and then a separate process should take that information and render it to the user in a suitable presentation.  The classes that do the actual work (the business objects) should implement all the logic and rules needed to accomplish a task without any concern as to how the results of that task are presented.

This concept is known as separation of concerns.  A concern is a particular part of the software package you're developing which shouldn't be tightly bound (coupled in the lingo) to other parts of your package (sorry I can't really word it better than that).  Implementing the rules and maintaining the state of the game is one concern, getting user input and displaying output to the user is a different concern.  While there obviously has to be some coupling you should try to minimize the degree that one is bound to the other.  Additionally, it's generally considered preferable for the part of the program responsible for presentation (which will typically be unique to that program) to know something about the business objects than it is for the business objects (which may get used across a wide range of applications) to know something about the presentation.

A related issue is reliance on $_SESSION inside your class.  Again this has to do with separation of concerns.  The $_SESSION array and its associated methods (session_start (), etc) are a data storage mechanism.  Data storage is a separate concern from the business logic, so again you should try to separate the code that handles storing the game state out from the code that implements the business logic.  In the case of $_SESSION there's the additional problems of it being tightly coupled to HTTP and that the session_start () function can't be called once headers have been sent to the client.  Again, ask yourself how hard would it be to adapt your code to work in a command line or to use a database instead of the PHP session to store state?


Replace an element of a list to get maximum sum of subsequence

It's actually a really nice programming quiz.

You tried to implement a linear (\$\mathcal{O}(n)\$ time) solution, and this is the correct final aim, but, I think, you agree that the current solution is hard to understand especially without any comments.

So let's start from something easy-to-understand and not very efficient. But this will allow us to check a correctness of your solution in a first place.

Brute-force solution (\$\mathcal{O}(n^2)\$ time)

It is clear that this task is related to the maximum subarray problem except the condition of replacing by N. So let's make a loop through all positions of the original array; on every iteration let's replace the current element of the array by N and find the largest sum by Kadane's algorithm.

'''
Kadane's algorithm for the Maximum subarray problem
Returns maximum sum
'''
def max_subarray(arr):
    max_sum = -sys.maxint
    cur_sum = 0
    for a in arr:
        cur_sum += a
        max_sum = max(cur_sum, max_sum)
        cur_sum = max(cur_sum, 0)
    return max_sum

def find_replaceable_element0(arr, n):
    max_sum = arr[0]
    max_sum_index = 0
    cur_sum = 0
    for i, a in enumerate(arr):
        arr[i] = n #replace by N in position i
        cur_sum = max_subarray(arr)
        arr[i] = a #change back
        if (cur_sum > max_sum or
                (cur_sum == max_sum and arr[max_sum_index] > arr[i])): #find the smallest
            max_sum = cur_sum
            max_sum_index = i
    return arr[max_sum_index], max_sum

Now we can check correctness of your solution.

import random
random.seed(123)
for i in range(10000):
    arr = random.sample(range(-10, 10), 5)
    n = random.randint(-5, 5)
    if (find_replaceable_element0(arr, n) != find_replaceable_element(arr, n)):
        print(find_replaceable_element0(arr, n))
        print(find_replaceable_element(arr, n))
        print(arr, n)
        break

And for this parameters L = [-9, 9, -3, 8, 4], N = -5 your solution gives M = -3, S = 16. That's wrong because changing -9 on N you can get S = 18.

For sure this task can be solved in \$\mathcal{O}(n)\$ time and \$\mathcal{O}(1)\$ additional memory, but extensive testing should be priority number one.


@__mod__.route('/', methods=['GET'])
@__mod__.route('/<filename>', methods=['GET'])

Seeing as you end up handling these two routes in completely different ways, why don't you just implement two functions?

def get(filename=None):
    """ Get a list of all Images or a single Image """

    couchdb.init_app(current_app)
    image = Image()

I don't know what these class does, but I suspect its not really an Image given the methods called on it. It seems more like an image library or something.

    if filename is None:
        results = image.view('images/all')
        filenames = []
        for result in results.all():

            if result._attachments:

Attributes starting with underscores are usually intended to be private. You usually shouldn't be accessing them.

                for attachment in result._attachments.keys():

If you are checking for an empty _attachments above (as opposed to None), you don't need to.  The loop will execute zero times for an empty dictionary. Also, you don't need keys() because the default iteration for a dictionary is keys

                    filenames.append(url_for('.get', filename=attachment))

You did post an edit with a comprehensionified version.

filenames = [url_for('.get', filename=attachment)
             for result in results
             if result._attachments
             for attachment in result._attachments]

The same issues exist here as with the explicit for loop. Its also a bit long and complex I might do the following

attachments = [result._attachments for result in results if result._attachments]
attachments = [attachment for attachment for attachments in attachments]
attachments = [url_for('.get', filename = attachment) for attachment in attachments]

Better? maybe. maybe not.

        response = make_response(simplejson.dumps(filenames), 200)
        response.headers['Content-Type'] = 'application/json'
        return response
    else:
        results = image.view('images/all', key=filename)

        if results.first() is not None:
            try:
                image_file = image.get_db().fetch_attachment(results.first(), filename)
                image_doc = results.first()._attachments[filename]
                response = make_response(image_file, 200)
                response.headers['Content-Type'] = image_doc['content_type']
                return response

I'd consider a utility function that calls make_response and sets a content_type.

            except ResourceNotFound:
                abort(404)

It is recommended that you put as little as possible in your try blocks. You only want to catch exceptions from where it is expected to be thrown. I'm not sure where you it is coming from in your code.

        else:
            abort(404)


Checking if a number is prime in NASM Win64 Assembly

Style: Indent your operands to a consistent column, so mnemonics of different length don't make your code look so ragged.  And use local .label labels inside functions.

Comment code that depends on non-standard behaviour: stdout is only guaranteed to be line-buffered, and isn't automatically flushed when you read stdin in ISO C.  Some systems (like Linux) do need fflush(stdout) after a printf of a string that doesn't end with a newline.  But I tried building a win64 executable by linking with mingw64 gcc, and running it under wine64, and it did actually print the prompt, to my surprise.

Normally you'd want to write a program like this to take its input as a command-line argument, instead of prompting for it with stdio at all.  (Then you just use strtoul or atoi, or sscanf, or even a hand-written loop to convert the ASCII decimal string to integer.)

Correctness problem: rbx is a call-preserved register in the x64 Windows calling convention.  Pick a call-clobbered scratch register, like rcx, or r8..r11.
 https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/x64-architecture.  If main's caller happens not to crash when you return after stepping on its RBX, you got lucky.

Use 32-bit operand operand-size when possible, and make sure operand-size is consistent.  You're only reading a 32-bit int with scanf("%d", &number), and the upper 32 bits are left zero from your dq 0.  It makes no sense to reserve 64 bits of space and then only ask scanf to write the low 32 of it.

See also The advantages of using 32bit registers/instructions in x86-64

Worse, you do cdq (sign extend EAX into EDX:EAX), but then you use 64-bit idiv rbx which divides RDX:RAX by RBX.  If your number input was -15 (base 10), your 128-bit dividend would be 0x00000000FFFFFFFF00000000FFFFFFF1.  Dividing that by a small integer would make the quotient overflow RAX, raising #DE (divide exception).  I didn't test your original version to see if I could provoke that with negative inputs; I changed to using %u for scanf and printf.

It's unclear why you'd want signed division.  Is this program supposed to work for negative inputs?  Your loop condition exits the loop if the counter is less than 2 (signed compare).  Unsigned lets us handle a larger range of inputs with faster 32-bit division.

Use 32-bit division for 32-bit numbers, it's about 2.5x faster than div r64 on Skylake, with similar performance ratios on other Intel CPUs.  See Trial-division code runs 2x faster as 32-bit on Windows than 64-bit on Linux for details.  (idiv and div are pretty similar in performance.  idiv r32 has a faster best-case throughput on Haswell than div r32, according to Agner Fog's instruction tables (https://agner.org/optimize/).  (1 per 8 vs. 9 clock cycles, and 1 fewer uop.  But for 64-bit division, div r64 has better throughput than idiv r64).

You were only checking the low 32-bits of the 64-bit remainder, too.  Since your original input was limited to 32-bit, this might be safe.  So possibly not a correctness problem.

Check a register for zero with test reg,reg, not cmp reg,0.  It saves a byte of code-size.  If the next instruction was js instead of jz, it would also have an advantage of micro-fusing into a compare+branch uop on more CPUs.

Use registers instead of static storage for your tmp variables, especially inside the loop.   That's what registers are for.  Static storage like you're using is equivalent to C static unsigned long long isPrime = 0;, instead of using an automatic storage variable that the compiler could optimize into a register.

asm doesn't have "variables", that's a high level concept that you can implement however you want, with registers, static storage, stack space, or whatever.  The normal way is to use registers and comment your code to keep track of what's where.  Anything that makes your code slower or larger defeats the purpose of writing in asm in the first place.  A compiler would easily make more efficient asm than what you've written.  (This is normal when you're a beginner, so don't feel bad about it, but be aware that looking at compiler output is another good way to learn efficient ways to do things in asm.  See How to remove “noise” from GCC/clang assembly output?)

Don't create a 0/1 boolean and then test it, just branch on the original condition and lay out your code to minimize the amount of jumping around.

You might want to save a 0/1 so you can exit with success or failure, making it possible to use this code as a prime-test in a script or something.  I did that in my version below, so I could verify its correctness with this bash one-liner on Linux.  (I tested it on Linux by using mov rdi, rcx / mov rsi, rdx before every scanf/printf to adapt for the calling convention difference between x86-64 System V and x64 Windows.)

 # check that all the numbers we think are non-prime actually have at least 2 prime factors (expect empty output because we filter out all lines with 2 spaces in `factor` output)
for i in $(seq 3 2 9999 );do echo $i | ./win-primes >/dev/null || echo $i ;done | factor | grep -v ' .* '

# check that all the numbers we think are prime only have 1 prime factor (no lines with multiple spaces in the factor output
for i in $(seq 3 2 9999 );do echo $i | ./win-primes >/dev/null && echo $i ;done | factor | grep ' .* '

Speaking of branching, it's possible to branch much less.  See Why are loops always compiled into do while style tail jumps.

Put one of the conditional branches at the bottom of the loop, and another inside as a break condition.  In my version below, notice that I put the .notprime block after the ret at the end of the main function.  Putting a block out-of-line means you don't have to jump over it in the other path of execution.  Branch layout is a hard problem, figuring out which code can fall through into what other code, and with what values in registers, is part of the fun of writing branchy asm code.  (As opposed to simple loops with mostly SIMD instructions, then the fun in in branchless logic.)

Speaking of which, I probably should have laid out my loop so the fall-through and less-branching case was non-primes.  We expect them to be more common, and jumping around less in the common case is generally best for I-cache footprint and other front-end factors.  The loop naturally lends itself to checking both things in that order after division, though, so I'd have to do some extra setup to skew the loop and put the n%c == 0 branch at the bottom.

Pretty much never use mov rcx, symbol to get a static address into a register.  With nasm -fwin64, it assembles to the 10-byte mov r64, imm64 encoding, which is larger and typically slower to decode and/or fetch from uop cache than a 7-byte RIP-relative LEA.  Also, it needs a load-time fixup for ASLR.

If static addresses fit in 32-bit signed immediates (true in some systems), they usually also fit in 32-bit unsigned, so mov ecx, symbol is shorter (only 5 bytes).

mov ecx, symbol: 5 bytes, mov r32, imm32.  Best choice in position-dependent code (and usable in Windows with LargeAddressAware = no)
mov rcx, strict dword symbol: 7 bytes, mov r/m64, sign_extended_imm32.  Never use, except for kernel code (high addresses).
mov rcx, strict qword symbol: 10 bytes, mov r64, imm64.  Never use.
mov rcx, symbol with nasm -fwin64 is equivalent to strict qword
lea rcx, [rel symbol]: 7 bytes, normally the best choice if mov ecx, symbol isn't available and/or for position-independent code.    (You used default rel so you don't need the rel in every addressing mode).

I don't have a Windows system to test on, but x86_64-w64-mingw32-ld win-primes.obj will link all 4 of these into an executable.  (Unlike trying to link a Linux PIE executable, where 32-bit relocations aren't accepted at all).

Windows executables can be Large Address Aware or not.  If not, pointers will be 32-bit (I think all pointers, not just static code/data label addresses).  Or actually 31-bit, so zero-extension and sign-extension both work, I think, allowing [array + rdx*4] addressing modes.  Anyway, in a Windows non-largeaddress executable, you can use mov ecx, symbol to put a symbol address into a register with only 5 bytes.  It's a tradeoff between needing a load-time fixup (for ASLR) of the immediate in the machine code vs. costing 2 extra bytes for a RIP-relative LEA.

mov reg,immediate can execute on more ports than RIP-relative LEA in some CPUs, but back-end port pressure is not usually a problem for these instructions (no input dependencies so they can run any time there's a spare cycle on the port they're scheduled to).

Don't use BITS 64.  All that does is let you accidentally assemble 64-bit machine code into a 32-bit object file instead of getting an assemble-time error on push rbp, because rbp isn't a register outside of 64-bit mode.

nasm -fwin64 sets the target bitness to 64-bit.  The only time bits 64 is useful for fully 64-bit code is if you want to make a flat binary, e.g. for turning asm into shellcode or a bootloader.  (nasm -fbin doesn't have bin64 or any other option for setting the target mode.)

The main use-case for bits 64 is if you're writing code that starts out in 16 bit mode, and switches the CPU to 64-bit mode.  So the first part of the code would be bits 16, then you might have some bits 32 code that you reach with a jmp far, or maybe go straight to bits 64 after setting up a GDT.  If you're not doing that or didn't understand this paragraph, you don't need and shouldn't use bits 64.

Put your read-only constant data in .rdata, not .data  The .data section is for mutable static data.  Grouping read-only data together into .rdata is good because 1) it catches bugs if you accidentally write to it, and 2) whole pages that are unmodified can be shared between different processes running the same executable.  (shared memory mapping.)  Note that runtime relocation fixups from stuff like mov ecx, symbol in an executable or DLL using ASLR will prevent sharing.

(On non-Windows, the equivalent section is .rodata).

Omit the frame pointer, like gcc -fomit-frame-pointer (on by default with optimization enabled).  You're not accessing the stack through RBP anyway, so you're not saving any code size by having it available instead of using offsets relative to RSP.  So those extra instructions are just costing you code-size and uops for no benefit.  mov rsp, rbp (note that you got this backwards but it's ok because you'd already adjusted RSP so they were equal again anway) + pop rbp is equivalent to leave.  leave costs 3 uops total, one more than mov + pop on Intel CPUs, but it's only 1 per function.  If you already have your stack pointer pointing at the saved RBP value, you should just pop rbp instead of leave or mov + pop.

You actually should use stack space to scanf into, instead of static storage, though.

You're not checking for errors from scanf.  If the user enters invalid input, scanf will return 0 and leave number unmodified, so 0.  That's pretty much ok for asm.  It doesn't get stuck in an infinite loop or crash.

In most languages that would be a big no-no, but you wouldn't normally write the input/output code in asm for real in the first place.

So as long as you're aware you're doing so, leave out error checking if you want.  You can always single-step in a debugger and print RAX after function calls, or even trace all the system calls your program makes.  (See the bottom of https://stackoverflow.com/tags/x86/info for debugging tips.)

Here's how I'd write it

Incorporating some of the things mentioned in other answers as well, like counting up from small divisors (quickly rule out most numbers), and only counting up to ~sqrt(n) because divisors come in pairs.  This vastly speeds up the code for large primes like 2^31-1 = 2147483647.  My version is dominated by startup overhead for that on Linux; perf stat says task clock = 0.339985 ms.  arith.divider_active only reports 180k clock cycles out of ~950k clocks total on my i7-6700k Skylake (including kernel time).  The inner loop should saturate the division unit and just bottleneck on div throughput.

;; bits 64
default rel

extern printf
extern scanf

section .rdata   ;; I typically put static data at the end, but here is fine too
;;    number: dq 0        ; use stack space for these
;    isPrime: dq 1
;    counter: dq 0        ; and just a register for this.

    prompt: db "Which number would you like to check? ", 0
    scan_fmt: db "%u", 0                                   ; %u instead of %d
    numberIsPrime: db "%u is prime", 10, 0
    numberIsNotPrime: db "%u is not prime", 10, 0

section .text

global main
main:
;    push rbp
;    mov rbp, rsp   ; unneeded, we're not using the stack frame

    stack_reserve: equ 32+8
    sub    rsp, stack_reserve   ; shadow space for callees + 8 bytes for stack alignment

    lea    rcx, [prompt]
    call   printf             ; magically flushes stdout with Windows C library

    ; memory from rsp+0 .. rsp+31 has potentially been stepped on by printf
    ; leave RSP where it is, ready for another call

;;; scanf into that 8-byte block of stack space above the shadow space, or into our *own* shadow space
    lea    rdx, [rsp+32]        ; stack addresses are normally 64-bit, can't get away with edx
    lea    rcx, [scan_fmt]
    mov    dword [rdx], 0       ; instead of error check, set n = 0 in case of I/O error
    call   scanf
    ;cmp   eax, 1               ; success = exactly 1 conversion
    ;jnz   .scanf_fail          ; TODO: error check

    mov    r8d, [rsp+32]        ; r8d: 32-bit unsigned number to be checked

    cmp    r8d, 3
    jbe   .prime                ; 2 is prime, and let's consider 0 and 1 prime as well.
                                ; catch 3 here so the loop can avoid the 3%3 == 0 corner case

    test   r8b, 1               ; all *other* even numbers (LSB=0) are non-prime
    jz    .notprime

    ;; n >= 5 at this point
    mov    ecx, 3               ; ECX: trial divisor counter
.divloop:                  ; do {
    mov    eax, r8d
    xor    edx, edx
    div    ecx                ; *much* faster than div rcx

    test   edx, edx
    jz    .notprime           ; if (n%c == 0) goto notprime

    add    ecx, 2             ; we've already ruled out all the even divisors

    cmp    eax, ecx
    ja    .divloop         ; while( n/c > (c+2) );
    ;; loop until c*c > n, i.e. until c >= sqrt(n), because divisors come in pairs
    ;; The c*c == n exact case is caught by the edx==0 test

    ;; Checking based on c*(c+2) lets us exit even earlier,
    ;;  and saves instructions because we can add before cmp
    ;; It's safe: I checked against a known-good primality test.
    ;; It works because any numbers between c*c and c*(c+2) are either prime
    ;;  or have smaller prime factors that we already found

;; fall-through: n is prime
.prime:
    lea    rcx, [numberIsPrime]
    mov    byte [rsp+32], 0
.print:
    mov    edx, r8d        ; n
    call   printf          ; format string already set one of 2 ways
;    mov rsp, rbp
;    pop rbp          ; just use LEAVE if you need this

    ;xor    eax,eax    ; return 0
    movzx  eax, byte [rsp+32]    ; return isprime(n) ? EXIT_SUCCESS(0) : EXIT_FAILURE(1)
    add    rsp, stack_reserve
    ret

.notprime:
    mov    byte [rsp+32], 1            ; store return value on the stack (above printf's shadow space).
                                       ;;  Typically you'd use a call-preserved register but we didn't need any for anything else
    lea    rcx, [numberIsNotPrime]
    jmp   .print
   ;; function tail-duplication would also be an option instead of jmp back
   ;; i.e. call printf  here and fall through to a mov eax,1 / ret

Note the comments describing conditions that hold when execution reaches that comment line.  I find that useful for keeping track of what previous conditions have ruled out.

This actually does one better than checking n/c > c as the loop condition.  n/c > c+2 doesn't miss any primes, and will exit the loop one iteration sooner sometimes.  It also saves instructions by not having to copy the old ecx to edx so you can compare against the old value.

A more intuitive / more-obviously-correct version that does n/c > c needs an extra mov edx,ecx

.divloop:                  ; do {
    mov    eax, r8d
    xor    edx, edx
    div    ecx

    test   edx, edx
    jz    .notprime           ; if (n%c == 0) goto notprime

    mov    edx, ecx           ; save old c for compare
    add    ecx, 2             ; we've already ruled out all the even divisors

    cmp    eax, edx
    ja    .divloop         ; while( n/c > c );

Using the division result in the loop condition means out-of-order execution can't evaluate the loop condition ahead of div progress.  So it won't be able to hide the branch mispredict when we leave the loop.

If we had calculated sqrt(n) ahead of time with something like this:

cvtsi2ss   xmm0, r8      ; signed 64-bit source = zero-extended r8d = uint32_t => float
sqrtss     xmm0, xmm0
cvtss2si   r9d,  xmm0    ; upper bound for ecx = sqrt(n)
;; or maybe we'd need to use sd instead of ss to avoid maybe rounding down

then the divide execution unit would have been busy doing that for about 3 cycles on Skylake.  That might actually be worth it; the branch mispredict penalty is probably higher.  Avoid stalling pipeline by calculating conditional early
.  Skylake has relatively great throughput for FP sqrt, older CPUs are worse.  But it's still slow compared to multiply.  If the throughput cost of one sqrt is less than the branch-mispredict penalty + div latency, then this wins for primes (where we eventually exit the loop by falling through the cmp/ja which OoO exec can't check until the div result for that iteration is ready.)

More importantly, most of the time you'll leave the loop from finding a divisor, unless you expect your inputs to usually be primes, and that branch unavoidably depends on the div result; that's the whole point of doing division.  So on the whole, doing an actual sqrt ahead of time to calculate a loop bound isn't worth it vs. using the clever trick of comparing the divisor and quotient.

To put it another way, an extra sqrtsd at the start delays all the div instructions including the last one by however long sqrt occupies the divider (before an integer div can start).  Or maybe one div could start while cvtsi2sd is running.  But anyway, that's approximately how many extra cycles it would add before execution of the last test/jz uop can detect that the loop should have exited, and starts branch mispredict recovery.

(I'm assuming that the loop-exit branch does mispredict.  This is normal unless you have a loop that runs for the same number of iterations repeatedly, and that count is under about 22 or 23 for Skylake.  It's IT-TAGE branch predictors are based on branch history, so this loop with 2 branches in it might only accurately predict the loop-exit for trip counts of <= ~11 even if the loop has the same trip-count repeatedly.  Neither of those things are probably common.)

sqrtss is faster than sqrtsd.  A double can exactly represent every 32-bit integer (in fact up to ~53 bits, the size of its significand).  But We're probably find with rounding to the nearest float; a 32-bit float has more range than even int64_t so there's no risk of overflow to +Inf.  The only worry is that (float)n could round down, and we could miss a composite like n = prime^2.  You could compensate by always adding half the distance between representable floats for numbers in the size range 232-1, but the extra div operations we end up doing for large primes costs more than just spending a few extra cycles for double.

Even if we could cheaply do int->float conversion with rounding towards +Inf, any rounding up would mean extra loop iterations for large n.  But if we only need correctness for large n and speed for small n, it would be fun.  But changing the MXCSR rounding mode isn't worth it.

If we did use double sqrtsd, we could check check for n being a perfect square just by looking at the FP inexact flag when square-rooting and converting to integer.  If both of those operations are exact, then n was a perfect square.  (But you'd have to reset the IE flag in MXCSR first, and that's slower than just integer squaring and comparison.)


Yes you can move the output away from the code, however that's usually difficult to do with this type of procedural code. The code is extremely tightly bound, which makes separation harder than it should be!

The two function you call are fine as they are. So lets focus on those for now.

getAvailableThemes()

This function, since it's only being called once, is what I believe to be clutter. I don't see a need to separate it from the main logic. Doing so only increases the amount of times we need to look back at the code.

Also, I see no reason to cut of "Directory" in $themeDir. Spell it out for clarity.

getThemePreview()

Is the return value a "preview" or a "file"? Perhaps a better name would be getThemePreviewFile.
We can refactor the code a lot:

$preview = '../themes/'.$theme.'/preview.png';

if(!file_exists($preview)) {
    $preview = 'images/nopreview.png';
}
return $preview;

I shortened it, and I added the extension into the literal because it doesn't look like the extension will change.

Now for the main file!

wcx_themes.php

First off, indentation should be key here. Indentation is also missing here! Readability is very important.

foreach($themeDir as $themeDir) - I don't like this at all. Collections should be pluralized.
The immediate solution to separating the HTML and the PHP that I can think of, is a templating library. Other than that, you could store the HTMl in a string, and then use sprintf or another form of replacement to build the output.


Another suggestion, to go on top of Heslacher's:

Make the (short)((short)inputBuffer[... a method.

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static short BytesToShort(byte a, byte b)
{
    return (short)(a << 8 | b);
}

The MethodImplOptions.AggressiveInlining enumeration value tells the C# compiler to try to inline the method as much as possible. That is, if you come form a C/C++ environment, it is very similar to macro's.

The C++ macro:

#define LERP(a,b,c) (((b) - (a)) * (c) + (a))

In C# could be written as:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Lerp(double a, double b, double c)
{
    return (b - a) * c + a;
}

And effectively be the same thing. The compiler would try to inline the method body instead of the method whenever possible.

This should help performance, while allowing you to move some of the more mundane code away from the main area you would be working.

Note: this does not guarantee that this is the choice the compiler would make, nor does it preclude you from doing other optimization strategies. However, for a method this small and simple, it would likely make that choice in the end.

https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions(v=vs.110).aspx

This means, that you could essentially do:

for (int i = 0; i < sensorData.Length; i++)
{
    sensorData[i] = BytesToShort(inputBuffer[startposition++], inputBuffer[startPosition++]);
}

With no ill-effects.


You have no extra spacing between functions except before the main() function, which has several returns.  I would put a single return between each function to make it clear where they begin and end without even looking.

You use spaces between variables and operators inconsistently, and you should be consistent:

printArray(arr, arr_size);
heap_sort(arr,0,arr_size-1);

for (i=0; i < n; i++)

There are others as well.  I would recommend using a space for readability.

I would put spaces around variables in function definitions as well:

void heapify(int[],int,int);

You don't need two return 0;s at the end of main().

While not absolutely necessary, it might help prevent bugs if you use braces around one-line ifs and loops:

for (i=0; i < n; i++)
    printf("%d ", arr[i]);

Your brace style here is rather peculiar:

if(size%2){
    if(a[l+i]<a[l+i/2])
        swap(a,l+i,l+i/2);
    i--;}

That final brace should be written on the line below.  I would use more spaces and braces as well:

if(size % 2) {
    if(a[l + i] < a[l + i / 2]) {
        swap(a, l + i, l + i / 2);
    }
    i--;
}


Implementing lock within a Python script

General Feedback

This code is fairly straight-forward and easy to read. There are only three functions and none of them extend beyond thirteen lines. If you really wanted more atomic functions you could abstract some functionality from get_info, for instance the code that parses each listing.

The name link doesn’t feel as appropriate for a string literal that represents a URL as something like url_template. Also see the related section below about naming constants.

The description was somewhat vague and didn’t specify whether each listing should correspond to an individual list within the returned list but if so, one could use itemstorage.append() instead of itemstorage.extend().

Suggestions

While it isn’t a requirement, it is recommended that each function have a docstring.

  All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings.1

Additionally, while constants aren’t really different than variables in python, idiomatically uppercase letters are used for the naming constants in python as well as many other languages. As was mentioned above, url_template feels more appropriate for the string currently named link so it may improve readability to use uppercase letters to signify that is a constant: URL_TEMPLATE.

1https://www.python.org/dev/peps/pep-0257/


Improving performance of moving arrays into an array

I tried some alternative approaches, and got this result:

Time for orig: 0.15900921821594238
Time for concat: 0.18401050567626953
Time for block: 0.16700983047485352
Time for stack_ravel: 0.1760098934173584
Time for stack_flatten: 0.32501864433288574

It's worth pointing out that I'm on a 32-bit machine with not enough RAM to hang with you. So I used smaller arrays. You'll want to correct the code and try for yourself. Also, my validation is really minimal, so you should probably improve that as well.

import time
import numpy as np

COMBINED_SHAPE = (3_000 * 3_000)

def time_func(f):
    start_time = time.time()
    ca = f()
    assert np.shape(ca)[0] == COMBINED_SHAPE
    print(f"Time for {f.__name__}:", time.time() - start_time)

def load_partial():
    partial = np.empty(shape=(COMBINED_SHAPE // 10))
    return partial

def orig():
    st, en = 0, 0
    combined_array = np.empty(shape=COMBINED_SHAPE)

    for i in range(10):
        X_np = load_partial()
        st = en
        en += np.shape(X_np[:])[0]
        combined_array[st:en] = X_np[:]

    return combined_array

def concat():
    ca = np.concatenate([load_partial() for _ in range(10)])
    return ca

def block():
    ca = np.block([load_partial() for _ in range(10)])
    return ca

def stack_ravel():
    ca = np.stack([load_partial() for _ in range(10)])
    ca = np.ravel(ca)
    return ca

def stack_flatten():
    ca = np.stack([load_partial() for _ in range(10)]).flatten()
    return ca

if __name__ == '__main__':
    time_func(orig)
    time_func(concat)
    time_func(block)
    time_func(stack_ravel)
    time_func(stack_flatten)


First off, your naming convention. You have a function name CountString, which to me states that you are either counting a string (?) or something along those lines. A better name would be FriendlyNumber or HumaneNumber.

count in a similar manner, means tracking an iterator. It could become input, rawValue etc.

Now, to the actual function. You can make use of a log function to compute your suffix (base 10), and the same for referring to your index in suffix list, as well as getting the absValue.

Instead of concatenating different parts of string, use a string.format, which would also remove your call to tostring.

Lua has a ternary operator, which can be done using and..or statements. Based on your version of lua engine (4.x, 5.{1, 2, 3}), you might have different implementation of the log function. A sample code would be:

-- For Lua 5.1
local suffixChars = { "", "k", "M", "G", "T", "P", "E" }
local l, f, a = math.log10, math.floor, math.abs  -- Lua 5.2+ have math.log(x, base)

function FriendlyNumber(rawValue)
  local absValue = a(rawValue)
  local prefix = rawValue < 0 and "-" or ""
  local log = f(l(absValue) / 3)
  -- I was calculating log first, but I needed floor(1/3rd) of it,
  -- and later had to multiply by 3 again, so computing the 1/3rd here only
  local suffix = suffixChars[1 + log]
  absValue = absValue / (10 ^ (log * 3))
  local str = ("%%.%df"):format((absValue < 1000 and absValue > 10) and 0 or 1):format(absValue)
  return ("%s%s%s"):format(prefix, str, suffix)
end

Working sample (and output):

-12 -12
1.0 1
50  50
999 999
1.5k    1500
25k 24999
123k    123456
1.2M    1234567
12M 12345678
123M    123456789
1.2G    1234567890


Bug

I tried converting "10' from base 10 to base 2 (i.e. binary) and the output was 250, which is invalid for a base 2 number.

Also, when I ran convertBase("3", 10, 3) the output was 0, not "10"

Your Question

  am I using modern coding conventions/practices?

Originally, before I added the javascript tag, this question only had the ecmascript-6 tag. I don't see many features of es-6 in your code, like let and const, arrow functions, default parameters, etc. So judging from an ecmascript-6 point-of-view, I would say No. See the rewrite below which utilizes those features.

const convertBase = (inNumber, inBase = 10, outputBase = 10) => {
  let result = [];
  if (typeof inNumber !== "number" && typeof inNumber !== "string") {
    throw new Error("You input is not a number or a string.");
  }
  const encodings = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
  if (typeof inNumber === "number") {
    inNumber = JSON.stringify(inNumber);
  }
  if (inBase === outputBase) {
    return inNumber;
  }
  inNumber = inNumber.toLowerCase();
  inNumber = inNumber.split("").map(item => encodings.indexOf(item));
  inNumber = inNumber.reverse();
  inNumber = inNumber.map((item, index)  => item * Math.pow(inBase, index));
  let res = 0;
  inNumber.forEach(item => res += item);
  let ones = res % outputBase;
  let remainder = (res - res % outputBase) / outputBase;
  result.unshift(ones);
  let left = remainder > 1;
  while (left) {
    ones = remainder;
    remainder = (remainder - remainder % outputBase) / outputBase;
    result.unshift(ones);
    left = remainder > 1;
  }
  return result.map(item => encodings[item]).join("");
};
console.log('convertBase("10", 10, 11):',convertBase("10", 10, 11))

Re-declarations

The code inside the while loop contains variable declarations for variables declared outside the loop:

var ones = res % outputBase;
var remainder = (res - res % outputBase) / outputBase;
result.unshift(ones);
var left = remainder > 1;
while (left) {
  var ones = remainder;
  var remainder = (remainder - remainder % outputBase) / outputBase;
  result.unshift(ones);
  var left = remainder > 1;
}

While the Javascript engine won't "chuck a wobbly1"2 (though somebody who has to update your code might), those assignment statements inside the while loop could exist without the var keyword, and for the sake of readability, probably should not have var at the beginning.

Simplification

The first versions of Ecmascript (i.e. 1 and 5) have had parseInt() and Number.prototype.toString(), which should be enough to implement the desired functionality (though note that the supported base values are 2-36, not 0-26).

const convertBase = (inputNumber, inputBase = 10, outputBase = 10) =>
  parseInt(inputNumber, inputBase).toString(outputBase);

console.log('convertBase("10", 10, 11):', convertBase("10", 10, 11)); // "a"
console.log('convertBase("3", 10, 3):', convertBase("3", 10, 3)); // "10"
console.log('convertBase("4", 10, 3):', convertBase("4", 10, 3)); // "11"
console.log('convertBase(10, 10, 2):', convertBase(10, 10, 2)); // "1010"

1http://spencertipping.com/js-in-ten-minutes/js-in-ten-minutes.pdf
2https://english.stackexchange.com/a/129277/213844


Determining if a file or URL is a git repo or archive

Well the easiest option is to extract parts into separate methods, no?

In unpack_archive the handling of File.extname seems buggy for zip
files?  At least it's different to the same case statement in
get_files.

File.readable? is used, but the other case in bash is missing the
question mark.

I don't know enough about Ruby and Chef, but I also saw that the
not_if arguments are specified in two different ways; maybe it's
possible to use the same way for both directives?

With two additional functions it looks a bit less redundant and more to
the point, however I guess there's still space for further improvements:

# Takes a file and or a url decides if it is a git repo or an archive.
# Downloads or clones it. to the destination.
# Do not enter url with trailing slash.
def get_files(url, file, destination)
  case File.extname(file)
  when '.tar.gz', '.zip' then unpack_archive(url, file, destination)
  when '.git' then git_clone(url, file)
  else fail ArgumentError, "dunno how to handle #{file}"
  end
end

def git_clone(url, file)
  git 'destination' do
    repository "#{url}/#{file}"
    reference 'master'
    user node['apache']['user']
    action :sync
  end
end

def get_extract_command(file)
  case File.extname(file)
  when '.tar.gz' then "tar -xC #{destination} -f #{file};"
  when '.zip' then "unzip -d #{destination} -qo #{file};"
  else fail ArgumentError, "dunno how to extract #{file}"
  end
end

def unpack_archive(url, file, destination)
  directory = "#{Chef::Config['file_cache_path'] || '/tmp'}/#{file}"
  remote_file directory do
    owner 'root'
    group 'root'
    mode '0644'
    source "#{url}/#{file}"
    not_if File.readable?(file)
  end
  extract = get_extract_command(file)
  bash "Extract #{file}" do
    cwd ::File.dirname(directory)
    code extract
    not_if { ::File.readable(file) }
  end
end


Looking to simplify my first python Rock, paper, Scissors project

game_end = True
while game:
    if point_player == 3:
        game_end = False
    elif point_ai == 3:
        game_end = False
    if game_end:

        ...

    else:
        if point_ai > point_player:
            print("The A.I won! RIP U")
        else:
            print("Dang! You won this time.")
        exit()

Could be simplified to:
while True:
    if point_player == 3 or point_ai == 3:
        break

        ...

if point_ai > point_player:
    print("The A.I won! RIP U")
else:
    print("Dang! You won this time.")

All of the
while rock:
    print("Oh! That's a tie no points.")
    break

Could be written as:
if rock:
    print("Oh! That's a tie no points.")

Instead of point_ai = point_ai + 1, you can shorten that to point_ai += 1. I would also separate out the code that decides who wins as it makes it a little bit easier to understand what is going on with the logic.
    winner = 'tie' # should be either 'player', 'tie', or 'ai'
    if ai_response == "Rock":
        if scissor:
            winner = 'ai'
        if paper:
            winner = 'player'
    elif ai_response == "Paper":
        if rock:
            winner = 'ai'
        if scissor:
            winner = 'player'
    elif ai_response == "Scissor":
        if rock:
            winner = 'player'
        if paper:
            winner = 'ai'

    if winner == 'tie':
        print("Oh! That's a tie no points.")
    if winner == 'player':
        print("Looks like you beat the A.I! +1 Point")
        player_points += 1
    if winner == 'ai':
        print("Oh, you lost :( +1 to A.I")
        ai_points += 1

It feels weird having the rock, paper, scissors Booleans to represent the choice the player made, and then having a string for the choice the ai made. I would use the same data type for both. If we stuck with using strings for both, and with some changes to some variable names, we get:
while True:
    if player_points == 3 or ai_points == 3:
        break
    print("Choose an option. (R,P,S)")
    player_choice = input()
    if player_choice == 'R':
        player_choice = 'Rock'
    elif player_choice == 'P':
        player_choice = 'Paper'
    elif player_choice == 'S':
        player_choice = 'Scissor'
    else:
        print("That's not an option")
        exit()
    print("=======================")
    print("You chose " + player_choice)
    ai_choice = random.choice(option)
    print("The A.I chose " + ai_choice)
    print("=======================")

    winner = 'tie' # should be either 'player', 'tie', or 'ai'
    if ai_choice == "Rock":
        if player_choice == 'Scissor':
            winner = 'ai'
        if player_choice == 'Paper':
            winner = 'player'
    elif ai_choice == "Paper":
        if player_choice == 'Rock':
            winner = 'ai'
        if player_choice == 'Scissor':
            winner = 'player'
    elif ai_choice == "Scissor":
        if player_choice == 'Rock':
            winner = 'player'
        if player_choice == 'Paper':
            winner = 'ai'

    if winner == 'tie':
        print("Oh! That's a tie no points.")
    if winner == 'player':
        print("Looks like you beat the A.I! +1 Point")
        player_points += 1
    if winner == 'ai':
        print("Oh, you lost :( +1 to A.I")
        ai_points += 1

    print("You have " + str(player_points) + " points")
    print("The A.I has " + str(ai_points) + " points.")
    print("=======================")

That looks worse in some ways, mostly because of the longer variable names, but everything is going to get better soon. I think now it's about time to break this game up into multiple functions. I like to have all of my print statements in a separate from the logic. In this case, I'm going to keep all of the print statements inside of the start_game function, and we'll put all of the logic outside of the start_game function. This helps us easily read through and understand what is going on, and then if we're having a problem, we can investigate the particular function whose logic is producing incorrect results. This also makes it easier to unit test the logic.
def get_players_choice():
    print("Choose an option. (R,P,S)")
    player_choice = input()
    if player_choice == 'R':
        player_choice = 'Rock'
    elif player_choice == 'P':
        player_choice = 'Paper'
    elif player_choice == 'S':
        player_choice = 'Scissor'
    else:
        player_choice = False

    return player_choice

def get_ai_choice():
    return random.choice(option)

def calculate_winner(player_choice, ai_choice):
    ''' returns either 'player', 'tie', or 'ai' '''
    winner = 'tie'
    if ai_choice == "Rock":
        if player_choice == 'Scissor':
            winner = 'ai'
        if player_choice == 'Paper':
            winner = 'player'
    elif ai_choice == "Paper":
        if player_choice == 'Rock':
            winner = 'ai'
        if player_choice == 'Scissor':
            winner = 'player'
    elif ai_choice == "Scissor":
        if player_choice == 'Rock':
            winner = 'player'
        if player_choice == 'Paper':
            winner = 'ai'
    return winner

def display_results(winner):
    if winner == 'tie':
        print("Oh! That's a tie no points.")
    elif winner == 'player':
        print("Looks like you beat the A.I! +1 Point")
    elif winner == 'ai':
        print("Oh, you lost :( +1 to A.I")

    print("You have " + str(player_points) + " points")
    print("The A.I has " + str(ai_points) + " points.")
    print("=======================")

def start_game():
    player_points = 0
    ai_points = 0
    while True:
        if player_points == 3 or ai_points == 3:
            break

        player_choice = get_players_choice()
        if player_choice is False:
            print("That's not an option")
            exit()

        print("=======================")
        print("You chose " + player_choice)
        ai_choice = get_ai_choice()
        print("The A.I chose " + ai_choice)
        print("=======================")

        winner = calculate_winner(player_choice, ai_choice)

        if winner == 'player':
            player_points += 1
        elif winner == 'ai':
            ai_points += 1

        display_results(winner)

    if ai_points > player_points:
        print("The A.I won! RIP U")
    else:
        print("Dang! You won this time.")

Now a little improvement as we refactor. This is kind of like chess, the more you do it, the more patterns just jump out at you. Let's start with the get_players_choice function. One pattern is that when asking for input from the user, instead of requiring 'R', 'P', 'S', we can grab the first character, lowercase it, and then check against that. We would then be accepting 'r', 'R', 'rock', 'Rock', or anything else that starts with the letter 'r'. Some other things:
    print("Choose an option. (R,P,S)")
    player_choice = input()

Is the same as
player_choice = input("Choose an option. (R,P,S)")

While I said I like to keep the print statements and the logic separate, display_results is a function that is obviously all about displaying text on the screen, and in the same way it would be expected that a function called get_players_choice is doing more than just logic. We're going to be using the input function, and that requires asking the user for input, and it requires telling them if the input is invalid. Anyhow, here is my revised get_players_choice function.
def get_players_choice():
    while True:
        player_choice = input("Choose an option (R,P,S), or push enter to exit")

        if not player_choice: # If they pushed enter
            return False

        first_char = player_choice[0].lower()

        if first_char == 'r':
            return 'Rock'
        elif first_char == 'p':
            return 'Paper'
        elif first_char == 's':
            return 'Scissor'

        print("That's not an option")

That display_choices and display_results can actually be combined together. And we end up with this as the final result. There are still some additional improvements that can be made, but what those are matters on what your goals are. Is it important that the code can be extended easily? Is performance important? Do you like object oriented designs? Etc.
''' A Rock Papers Scissors game '''
import random

def get_players_choice():
    while True:
        player_choice = input("Choose an option (R,P,S), or push enter to exit: ")

        if not player_choice: # If they pushed enter
            return False

        first_char = player_choice[0].lower()

        if first_char == 'r':
            return 'Rock'
        if first_char == 'p':
            return 'Paper'
        if first_char == 's':
            return 'Scissor'

        print("That's not an option")

def get_ais_choice():
    return random.choice(["Rock", "Paper", "Scissor"])

def calculate_winner(player, ai):
    ''' Takes either 'Rock', 'Paper', or 'Scissors', for both the player and the ai.
        returns either 'player', 'tie', or 'ai' '''

    if ai == "Rock":
        if player == 'Scissor': return 'ai'
        if player == 'Paper':   return 'player'

    elif ai == "Paper":
        if player == 'Rock':    return 'ai'
        if player == 'Scissor': return 'player'

    elif ai == "Scissor":
        if player == 'Rock':   return 'player'
        if player == 'Paper':  return 'ai'

    return 'tie'

def display_round_outcome(player_choice, ai_choice, winner, player_points, ai_points):
    print("=======================")
    print("You chose " + player_choice)
    print("The A.I chose " + ai_choice)
    print("=======================")

    if winner == 'tie':
        print("Oh! That's a tie no points.")
    elif winner == 'player':
        print("Looks like you beat the A.I! +1 Point")
    elif winner == 'ai':
        print("Oh, you lost :( +1 to A.I")

    print(f"You have {player_points} points")
    print(f"The A.I has {ai_points} points.")
    print("=======================")

def start_game():
    player_points = 0
    ai_points = 0

    while True:
        if player_points >= 3 or ai_points >= 3:
            break

        player_choice = get_players_choice()
        ai_choice = get_ais_choice()

        if player_choice is False:
            break

        winner = calculate_winner(player_choice, ai_choice)

        if winner == 'player':
            player_points += 1
        elif winner == 'ai':
            ai_points += 1

        display_round_outcome(player_choice, ai_choice, winner, player_points, ai_points)

    if ai_points > player_points:
        print("The A.I won! RIP U")
    elif ai_points == player_points:
        print("It's a tie.")
    else:
        print("Dang! You won this time.")

print("|=========================|")
print("|    Rock Paper Scissor   |")
print("|       (R) (P) (S)       |")
print("|=========================|")
print("Would you like to start? y/n")
answer = input()
if answer == "y":
    print("Welcome to the game of Rock Paper Scissors")
    start_game()
elif answer == "n":
    print('Well ok then.. Fine leave')
else:
    print("That's not an option.")

Let me know what questions you have, and what I wrote to quickly and didn't do a good job in explaining me decisions with. But I hope that kind of helps seeing how I would refactor this code, and hopefully you can see how much easier it is to read and debug the final version when you have everything split chunks of code. The difference is a lot more obvious when it's complicated code that you wrote a long time ago, or that something else wrote, and you're trying to figure out what is going on.

Edit:
My brother came to a very similar conclusion for how he would refactor this code, but he found a shorter way of checking who the winner is. Here is his calculate_winner function.
what_beats_what = {
  'Paper': 'Rock',
  'Scissors': 'Paper',
  'Rock': 'Scissors',
}

def get_winner(user_weapon, ai_weapon):
    if what_beats_what[user_weapon] == ai_weapon:
        return 'USER'
    elif what_beats_what[ai_weapon] == user_weapon:
        return 'AI'
    else:
        return 'TIE'

Also, it's impossible for the game to end in a tie as whoever reaches 3 points first will always be the winner.


// init your element
var $nav = $('div.single-level-nav');
// use a boolean var to check if the element is already shrinked
var navShrinked = false;

$(window).on('scroll', function() {
  if ($(this).scrollTop() > 1){
    // add class only once
    if(!navShrinked) {
      $nav.addClass("shrunk");
      navShrinked = true;
    }
  }
  else{
    // remove class only once
    if(navShrinked) {
      $nav.removeClass("shrunk");
      navShrinked = false;
    }
  }
});
body {
  height: 1500px;
}
.single-level-nav {
  height: 100px;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #000;
  transition: height .3s;
}
.single-level-nav.shrunk {
  height: 50px;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>


Converting between std::wstring and std::string

I would, and have, redesign your set of functions to resemble casts:

std::wstring x;
std::string y = string_cast<std::string>(x);

This can have a lot of benefits later when you start having to deal with some 3rd party library's idea of what strings should look like.


Keep It Simple For the User
Rather than making the user type the word Exit it might be better to ask the user
Are you done yet(y/n)? and accept a simple yes/no answer. It also might be better if the answer was not case sensitive so accept Y, y, N and n.

Exit From Main() When Possible
The Main() function may contain clean up code so exiting from the ExitProgram() function may not be the best idea. A second problem I see with the ExitProgram() function is that it is called before the user ever enters a calculation. There are two possible ways to handle this, one would be to move the call to ExitProgram() to after the calculation is performed, the other would be to have a function that contains a do while loop that calls Calc within the loop and tests ExitProgram() in the while condition.

Function Complexity
The function Calc() is overly complex (it does too much) and should be multiple functions. One of the functions should get the user input, and a second function should do the calculation. This would be applying two programming principles, the Single Responsibility Principle and the KISS Principle.

The Single Responsibility Principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

The Keep It Simple (KISS) Principle is an engineering principle that predates computers, basically it is keep the implementation as simple as possible.


if diff < 0:
        target_qc = is_qc + deg2qc(abs(diff))
    else:
        target_qc = is_qc + deg2qc(-diff)

If diff < 0, then abs(diff) == -diff, just the same as the else case. The

    target_qc = is_qc + deg2qc(-diff)

(no if's and else's) should suffice. The else case (that is, abs(diff) > 180.0) also can be rewritten as

    if diff < 0:
        target_qc = is_qc + deg2qc(-diff - 360)
    else:
        target_qc = is_qc + deg2qc(-diff + 360)

where the cases only differ in signs of 360, which suggests that you are looking for the remainder -diff % 360; notice that python supports the remainder of floats.

To get rid of ugly leading -, you may want to calculate diff as

    diff = target_deg - is_deg


Implementing a cancellable "infinite" loop

Your catch statement is catching any error (EVERY ERROR), which is not a good thing.  I assume there are several errors that you are anticipating, but you shouldn't catch them all.  You will run into bugs and won't know what is going on because the errors will be bulked into your cancellation.

I would catch only the exceptions that you know about and are ready for, meaning that you have a solution for that exception.

You also might want to set it so that right before WaitForFile is exited, it closes the file no matter what happens inside the method.


Builder pattern that forces all members to be initialized at compile-time

Would such a pattern actually be useful in practice?

Not really in my opinion. In C++20 you can use designated initializer lists like {.min = 10, .max = 20} and I mean if the argument is not clear from the context than there are various ways to improve this, even today.

A comment. Foo f(/*min=*/10);
User-defined literals Rectangle r(10_width, 200_height);
Strong types: Player p(Position(10, 10));
Variables: const int size = 10; Square s(size);

This also doesn't work with non-copyable, non-moveable types, although those are rare in practice. The members also need to be default constructible unfortunately.

Some thoughts:

Note that your code has undefined behavior, since two of the variables are not set on the first call.
The build function is required in Java, but in C++ you can use a conversion operator. Although this suffers from the same problem that expression templates have: Using type deduction will not get you a Foo.
Delete copy construction for the builder object, since there is no reason to copy it.
Don't use 0 and 1 for bools please; false and true is clearer IMO.
Consider using noexcept and constexpr (if applicable).

  Is there an elegant way of sharing the member variables of the Builder objects, despite the results of each setter call being of a different type? (For cheap-to-move types, I am thinking along the lines of a "data block"-like struct, that gets moved from this into the result.)

Yes that's a good idea. Here's my take on it:

template <bool x_set = false, bool y_set = false, bool z_set = false>
struct FooBuilder {
  constexpr FooBuilder() noexcept = default;
  FooBuilder(const FooBuilder &) = delete;
  FooBuilder &operator=(const FooBuilder &) = delete;

  constexpr auto x(int val) noexcept {
    members_.x_ = val;
    return FooBuilder<true, y_set, z_set>(std::move(*this));
  }
  constexpr auto y(int val) noexcept {
    members_.y_ = val;
    return FooBuilder<x_set, true, z_set>(std::move(*this));
  }
  constexpr auto z(int val) noexcept {
    static_assert(!z_set, "cannot set z twice!");
    members_.z_ = val;
    return FooBuilder<x_set, y_set, true>(std::move(*this));
  }

  constexpr operator Foo() noexcept {
    static_assert(x_set && y_set && z_set, "all members must be set");
    return {members_.x_, members_.y_, members_.z_};
  }
  constexpr Foo build() noexcept { return *this; }

private:
  template <bool... args>
  constexpr FooBuilder(FooBuilder<args...> &&other) noexcept
      : members_{std::move(other.members_.x_), std::move(other.members_.y_),
                 std::move(other.members_.z_)} {}

  template <bool, bool, bool> friend struct FooBuilder;

  struct Proxy {
    int x_, y_, z_;
  } members_{};
};

There is still a lot of boilerplate, but unfortunately it cannot be removed since C++ doesn't have reflection yet.


Updating a chart from Yahoo Finance CSV files

Did you read or even try this code before posting it? Sorry if this seems rude, but it just seems obvious that if this was run you would immediately notice something was wrong. I'm mostly looking at the PHP code here, as it is full of issues. The JS appears to be fine, except I would consider moving those graphs into a separate functions. More on that below.

PHP

Wow, so many things on just the first line.

Only do one thing per line, this helps with legibility. Also, try to avoid putting statements on the same line as the opening or closing php tags, unless opening and closing them on the same line (templates usually).

Don't assign variables in statements (if, while, etc...) as it can lead to mistakes. PHP allows this, but IMO they should deprecate it. Though they probably won't because it might cause issues with the way for loops are declared. It is very easy to forget a second equals sign and mistakenly assign a new value to a variable that you were actually trying to compare, and your IDE wont catch it because its valid. If you get in the habit of not doing this then you know that if you ever see it while troubleshooting you know you've found your issue. And if your IDE is smart enough it will warn you about accidental assignments.

Double quotes are used to tell PHP that the following string has a character or variable that needs to be escaped. As such PHP requires a little bit of extra processing power to read that string than if it were just single quoted. The speed is really negligible and is not really a "good" reason for making this switch, but I like to point it out anyways. This is a very controversial issue, so take it or leave it.

The first line rewritten:

<?php
$row = 1;
$handle = fopen( 'table.csv', 'r' );
if( $handle !== FALSE )  {

Correct me if I'm wrong, but doesn't your for loop just print once on each while iteration? In this case, why loop at all? The same thing can be accomplished with array_shift() or by specifying the first index.

echo array_shift( $data );
//or to avoid manipulating array
echo $data[ 0 ];

Why are all of your for loops only looping once? What is their purpose? Let me read you your code and you can follow along. Starting inside the while loop and doing the following on each iteration.

Increment unused row variable
Loop once

Echo first element of new CSV array
End of loop, increment a counter that won't really be used

Loop once with a specific number that's not used

Use first counter to point at the second value of array, Do nothing with it
End of loop, increment a counter that isn't used

Loop once with another specific number that's not used

Use first counter to point at the second value of array, Do nothing with it
End of loop, increment a counter that isn't used

Close file early so that only first entry was retrieved and while loop ends early

I'm not sure what those other loops are being used for, but If you want to do something every 5th iteration just add an if statement with a mod of 5.

if( $c % 5 === 0 ) {

What is the purpose of $row, $c1, and $c2? These variables are unused. And What is the purpose of just declaring $data[ $c ] in each of these loops, it doesn't do anything. At least the first loop echoed it.

Why are you closing your handle while you are still using the file? Close it after the loop unless you meant to only fetch the first entry.

JS

You can reduce the amount of work you are doing by following the "Don't Repeat Yourself" (DRY) Principle. You should also look at the Single Responsibility Principle to break up that ready function a little more. Now, my JS is a little rusty, but here's how I'd apply the DRY principle. I have not tested it, but hopefully it gets the point across.

function graph( properties ) {
    graph = new AmCharts.AmGraph();
    for( property in properties ) {
        graph[ property ] = properties[ property ];
    }

    return graph;
}

graph1Properties = {
    type : "column",
    title : "Income",
    valueField : "income",
    lineAlpha : 0,
    fillAlphas : 1
};
graph1 = graph( graph1Properties );
chart.addGraph( graph1 );

graph2Properties = {
    type : "line",
    title : "Expenses",
    valueField : "expenses",
    lineThickness : 2
};
graph2 = graph( graph2Properties );
chart.addGraph( graph2 );


Haskell-like function composition function

There's no need to use a struct compose_t to wrap operator(), you can just move operator() out of it and rename it compose():
template <typename F, typename G>
constexpr decltype(auto) compose(F&& f, G&& g) noexcept {
    return [&f,&g](auto&& x){
        return f(g(std::forward<decltype(x)>(x)));
    };
}

Now it is also much closer to the code written in this post you mentioned, except of course you are limited to composing only two unary functions.
Other than that, if you can live with the restrictions you have, I see nothing wrong with your implementation.


Creating a proper workflow through version control and a Makefile

I don't know anything about Flask, but there are definitely problems with the Makefile:

dev: relclean venv test

In a parallel build, the building of the relclean target can overlap with that of venv and test; you might want to add some ordering there (or put .NOTPARALLEL: as a target).

The rules for clean and dev don't create their targets, so need to be marked with .PHONY.

All makefiles should have .DELETE_ON_ERROR to avoid partially-written files satisfying the dependencies.

The install target doesn't appear to depend on anything.  So make install may well install an out-of-date product.  On further reading, the install target doesn't look like a conventional install step - perhaps it would be better named as update-server or something?

Overall, it looks more like a job for a script than a Makefile, unless you are actually going to make use of Make's dependency engine.  Perhaps something like this:

#!/bin/bash

# Definitions
server=server
user=${USER:-user}

export FLASK_APP=octlive/__init__.py
export FLASK_DEBUG=1

# Actions
action()
{
do case "$1" in
       clean)
           find . -name \*~ -delete
           find . -name \*.pyc -delete
           ;;
       test)
           ../venv/bin/flask run --host=0.0.0.0
           ;;
       venv)
           virtualenv ../venv
           ../venv/bin/pip install -r require.txt
           ;;
       relclean)
           action clean
           rm -rf ../venv
           ;;
       dev)
           action relclean
           action venv
           action test
           ;;
       install)
           ssh "$user@$server" /var/www/app/install.sh
           ;;
   esac
}

for arg in "$@"
do action "$arg"
done


Python script that launches a process that it needs to clean up after and kill on receiving SIGTERM/SIGINT

UPPER_CASE is reserved for constants, and your globals assuredly aren't constants. If you wish for a cleaner solution, you could possibly make a class and pass in instance methods to signal.signal.

Your final raise SystemExit seems unneeded.

You can use line.endswith('.ext') instead of slicing.

It's hard to give more detailed analysis without a better understanding of what the code is trying to do.


Detecting the attachment of a DataContext

If by:

  While there is no datacontext the view shows an indefinite progressbar.

You mean that the view's DataContext is null until the ViewModel is loaded, then you can simply use this:

<Border Visibility="{Binding, Converter={StaticResource IsNullToVisibilityConverter}, Mode=OneWay, FallbackValue=Visible}" >
    <views1:CircularProgressBar Visibility="Visible" />
</Border>

Which is to say, bind directly to the view model property path (which will be null until the view model is loaded) and convert a null value to mean 'Collapsed' and a non-null value to mean 'Visible'.

This removes the need for an IsLoaded boolean property per view model.

Of course, you will need to write the converter.


Structure

Firstly, try not to use the global keyword. This keyword should really be used only if you HAVE to. A simple solution for this is to implement a class that wraps around all of the functions:

class MyFileManager(object):
    def __init__(self, filename='', save_filename=''):
        self.filename = filename
        self.save_filename = save_filename

    # Re-named `program` function
    def save_users_list(self, list_name):
        ...

    def get_filename(self):
        self.filename = askopenfilename(filetypes=(("Text files", "*.txt"),
                                                   ("All files", "*.*")))

    def get_save_file(self):
        self.save_filename = asksaveasfilename(filetypes=(("Text files", "*.txt"),
                                                          ("All files", "*.*")))

Now your button declarations would look like this (see here for the reasoning behind using lambda for go_button):

manager = MyFileManager()
filename_button = tkinter.Button(window, text="Browse", command=manager.get_filename)
save_filename_button = tkinter.Button(window, text="Browse", command=manager.get_save_file)
go_button = tkinter.Button(window, text="GO!", command=lambda: manager.save_users_list(
                                                                   list_name.get()))

Naming

Notice how in my examples above I use_underscores instead of camelCase for variable names. This is the Python convention.
When thinking of variable names, err on the side of being too verbose rather than too brief: list_name_label is a much better name than listNameLBL.
You mostly do a good job of this, but for GUI widgets remember to append the type of widget in the variable name. You forgot to do this on your filename button widget.

program Function

Your orignal function has a few problems/tweaks that can be made:

The name is very ambiguous. Update it to better reflect what the function does.
You used the with statement to open filename. However, when you open saveName you don't. Because of that you forgot to close() that file. ALWAYS use with when accessing files as it will save you these mistakes.
I prefer to always say which mode we are opening files in. So add the mode ('r') to the with statement.
Try to make the amount of time a file is open the smallest it can be. So instead of having filename open for the duration of the function only keep it open when creating longList.
Instead of doing multiple string concatenations, use format() to create your finList.
There is no need for the parens around variables.

Here is my version of your program function. Assume it is inside the class I outlined above:

def save_users_list(self, list_name):
    with open(self.filename, 'r') as file:
        numbers_list = [line.strip() for line in file.readLines()]

    with open(self.save_filename, 'w') as file:
        file.write('{} = {}'.format(list_name, str(numbers_list)))

As a final general comment, take a look at PEP8, the official Python style guide. It will help your code look and feel more Pythonic.


I'm solely going to post on your coding structure rather than the method of procedure for the task your code does.

In validateNumber(), your indentation starts out good and then goes downhill from there.

}else {
var len = $txtBox.val().length;
var index = $txtBox.val().indexOf(',');
if (index > 0 && event.keyCode == 44) {
return false;
}
if (index > 0) {
var charAfterdot = (len + 1) - index;
if (charAfterdot > 6) {
        return false;
}

with whitespace added would transform into:

} else {
    var len = $txtBox.val().length;
    var index = $txtBox.val().indexOf(',');
    if (index > 0 && event.keyCode == 44) {
        return false;
    }
    if (index > 0) {
        var charAfterdot = (len + 1) - index;
        if (charAfterdot > 6) {
            return false;
        }

Your naming conventions could be improved also:
For example, charAfterdot into charAfterDot.

Instead of blindly comparing random event.keyCodes with numbers, declare the numbers before hand as constants.

const BACKSPACE = 8;
const TAB = 9;
const LEFT_ARROW = 37;
const RIGHT_ARROW = 39;

However, your version of JavaScript may not support constants, so use var in that case, and then just:

if (event.keyCode == BACKSPACE || event.keyCode == TAB || event.keyCode == LEFT_ARROW || event.keyCode == RIGHT_ARROW)

Declaring constants is a much clearer way of programming, than comparing to random numbers.


Looks good! Just one little thing that I, personally would do to remove one .toLowerCase call per item: map it first. So, instead of calling .toLowerCase in the filter, you can do this:

words.map(w => w.toLowerCase)
     .filter(w => w.sorted == sorted_word && w != origin_word)

You've also got a random newline before the end of the class.

Aside from that little niggle, it looks good! There's... really not much I can say. It's short code.


Adding thousand separator to various number types

There is no common base type for numeric types, unfortunately.

You could still reduce the repetitiveness of your code though, by encapsulating the common structure in a single function:

    private static string AddThousandsSeparator(Object numeric, int numberOfDecimalPlaces)
    {
        // note this would crash when passed a non-numeric object.
        // that's why it's private, and it's the class's responsibility
        // to limit the entry points to this function to numeric types only
        return String.Format("{0:N" + Math.Max(0, numberOfDecimalPlaces) + "}", numeric);
    }

    public static string WithThousandsSeparator(this decimal value, int numberOfDecimalPlaces)
    {
        return AddThousandsSeparator(value, numberOfDecimalPlaces);
    }

    public static string WithThousandsSeparator(this int value, int numberOfDecimalPlaces)
    {
        return AddThousandsSeparator(value, numberOfDecimalPlaces);
    }

    public static string WithThousandsSeparator(this double value, int numberOfDecimalPlaces)
    {
        return AddThousandsSeparator(value, numberOfDecimalPlaces);
    }

    public static string WithThousandsSeparator(this long value, int numberOfDecimalPlaces)
    {
        return AddThousandsSeparator(value, numberOfDecimalPlaces);
    }

A few side remarks:

There is no point in calling ToString() on the result of String.Format. String.Format already returns a string.
Math.Max is a more concise alternative for the conditional reassignment. (For what it's worth, Kotlin provides readable extension functions as syntax sugar for this sort of thing, eg.  someNumber.coerceAtLeast(0) - trivially easy to reimplement them in C# for readability).
I also corrected the naming slightly. It's "thousands" separator (plural), plus I think With... makes it clearer what the function does. The ToSomething phrase conventionally means a value is getting converted to Something, as if you were converting the number to the thousands separator itself - obviously nonsensical - rather than just adding it to the formatting.


Moving WordPress database and files to new host

Make input validation more user-friendly

You ask to enter host, user and port, and if one of them is empty you exit.
If I entered a host and a user and accidentally pressed enter for port (empty), I would be very unhappy with the script.

It would be better to put the prompting logic in a loop,
and repeat forever until a non-empty value is entered.
Ideally in a function, to reduce code duplication.

Exit with non-zero code on error

When exiting with error,
it's recommended to use a non-zero exit code.

~ is the same as $HOME

I prefer writing ~ because it's shorter.

Use printf instead of echo -e

The flags of echo are not portable.
To get the behavior of echo -e,
I suggest to make it a habit to use printf instead.

Replace awk + grep with just awk

In this command you use a combination of awk and grep:

eval $(awk -F "[()']" '/^define\(/{printf "%s='\''%s'\''\n", $3, $5;}' < wp-config.php | grep DB_*)

You can do what grep does here in awk,
which will be more efficient.
The difference will be negligible in this example,
but it's good to make it a habit to avoid additional processes when easily possible.

Replace multiple sed calls when one is enough

This code rewrites the same file 3 times:

sed -i -e "s;\(define([[:space:]]*'DB_USER',[[:space:]]*\)\(.*\)\()\;\);\1'$local_db_user'\3;g"

  wp-config.php
      sed -i -e "s;(define([[:space:]]'DB_PASSWORD',[[:space:]])(.)()\;);\1'$local_db_password'\3;g" wp-config.php
      sed -i -e "s;(define([[:space:]]'DB_NAME',[[:space:]])(.)()\;);\1'$local_db_name'\3;g"
  wp-config.php

One sed would be enough, using multiple -e parameters.

Pointless cleaning up

Resetting the variables at the end of the script seem pointless.
This is only useful if you source this script, which seems unlikely.
If you run this script (as opposed to sourcing it),
then the variables you defined or modified will not be visible after the script has completed.


Animated scrolling when intra-page links are clicked

Get the "respective" div in a more general way from the link's href attribute:

$('a[href=#certificados], a[href=#team], a[href=#house], a[href=#contact]').click(function(e){
    e.preventDefault();
    $("html, body").animate({ scrollTop: $(this.hash).offset().top }, 1000);
    // this.hash would be equivalent to $(this).attr("href") in your case
});

Probably you also can use a much better selector now - maybe selecting those links by a common class.