... if you noticed any flaws ....

Problems with scrivi()

char * scrivi(const char * a, char * B) {

 char *targetdir = malloc(2048);
 strcpy(targetdir,a);
 strcat(targetdir,"/");
 strcat(targetdir,B);
 return targetdir;
 }

Magic number

Why 2048?  Big enough - who knows?  Makes more sense to find the size needed and allocate rather than risk undefined behavior of a buffer overflow with strcpy(targetdir,a);

strcpy(), strcat(), strcat()

Walking down the string 3 times.  Bad enough to do twice.   (With a larger code re-write, we could avoid all repetitive walks down a, that is far below.)

char * B better as const char * b

Use const.

No error checking

With a recursion function, out-of-memory is a concern.

Alternative

char * scrivi(const char *a, const char *b) {
  size_t a_len = strlen(a);
  size_t b_len = strlen(b);
  char *targetdir = malloc(a_len + 1 + b_len + 1);

  if (targetdir) {
    memcpy(targetdir, a, a_len);
    targetdir[a_len] = '/';
    memcpy(targetdir + a_len + 1, b, b_len + 1);
  }
  return targetdir;
}

Re-write trick

Rather than repetitive malloc()/free(), allocate once ever for a working file path buffer.

size_t file_path_size = PATH_MAX * 2;  // Let us be generous.
char file_path = mallloc(file_path_size);

Before code calls ricor1() the first time, fill in the directory path and pass how much used, how much total.

strcpy(file_path, argv[2]);
ricor1(argv[1], file_path, strlen(argv[2]), file_path_size);

When forming the the full path, rather than percorso = scrivi(nomedirectory, fdata->d_name); with its allocations, write at the right place.

int length = snprintf(file_path + used, file_path_size - used, "/%s", fdata->d_name);

When recursing, append the sub-directory name and re-curse with an updated length

ricor1(estensione, file_path, used + length, file_path_size);

Include ample size error checking.

Consider code only ever needs   1 file_path[] at a time.


Draw element border according to scroll amount

When you have a collection that you want to iterate over, and you don't particularly care about the index of each element, iterating by going through the collection's .length and manually incrementing an index counter anyway is a bit tedious and ugly. Collections almost always have iterators or a forEach method - it's nice to use those instead, when possible. In other words, rather than

var el = document.querySelectorAll(".animateBorder");
for (var i = 0; i < el.length; i++) {
  // lots of lines referencing el[i]

you may use

const borderContainers = document.querySelectorAll(".animateBorder");
for (const borderContainer of borderContainers) {
  // lots of lines referencing borderContainer

Don't call the collection el - I, and most other developers, would ordinarily expect a variable named el to contain an element. Since what you have is a collection of elements, it would be good to be precise and make that clearer with the variable name, else a script reader or writer is more likely to get confused by it and make a mistake as a result.

You define the event argument, but never use it:

document.addEventListener("scroll", (event) => {

If you're not going to use an argument, it would be better to leave it out entirely, that way there's one less variable readers of the script have to be mindful of:

document.addEventListener("scroll", () => {

scroll events can sometimes fire very frequently (like 50 in a second or two):

const div = document.querySelector('div');
window.addEventListener('scroll', () => {
  div.textContent = Number(div.textContent) + 1;
});
body {
  height: 2000px;
}

0

Given these sorts of events, and given that you might be iterating over a non-trivial number of animateBorder elements, and each of those animateBorder's descendant s, you might be right to consider the performance implications of your code.

One way to improve would be to retrieve values only when necessary. For example, rather than doing window.innerHeight / 2 || document.documentElement.clientHeight / 2; for every scroll, and also for every animateBorder item that exists during that scroll event, you could retrieve the value just once, on pageload. You can also retrieve the scrollTop when a scroll event occurs, rather than for every animateBorder element in a scroll event. Another option would be to add a small debouncer - only iterate through the elements and change their styles once, say, 50ms has passed since the last style change has taken place.

You define

partLenght

Spelling matters in programming. Misspelled words are a very easy source of bugs. Use partLength instead.

Variables named _0 and _100 are pretty weird - it doesn't look like a normal variable name, but almost like a numeric literal with the new _ optional separators, eg:

console.log(
  1_000_000
);

Better to call the variables something easily understandable with English words instead, maybe spanTopOffset and spanBotOffset.

You have

if (direction == "horizontal") {

and a few other uses of == as well. Always use strict equality with === and !== instead - otherwise, if you use loose equality, you'll be requiring everyone that reads the code (including you) to be sure of all of the weird type coercion rules invoked by loose equality.

Since it's 2020, best to write at least in ES2015 syntax (which you're already partially doing with =>). If you're going to use ES2015 syntax, use it everywhere - never use var, since it has too many problems. Define variables with const instead (or let if you have no choice but to reassign the variable).

To clarify the logic in the comparisons against currentPos, consider using else-if and else instead, to make it clear that exactly one of the conditions may be fulfilled. I'd also add comments indicating what exactly each condition means.

Or, an alternative would be to simply calculate the percentage required regardless, then constrain its values to between 0 and 100 - then set the width or height to that constrained percentage:

// 0 when current position before or at top of span section
// between 0 and 100 when current position is between top and bottom of span section
// 100 when current position is after bottom of span section
const percentScrolledThisElement = Math.min(
  100,
  Math.max(
    0,
    Math.round(((currentPos - spanTopOffset) * 100) / partLength)
  )
);
if (direction === "horizontal") {
  span.style.width = percentScrolledThisElement + "%";
} else {
  span.style.height = percentScrolledThisElement + "%";
}

const borderContainers =  document.querySelectorAll(".animateBorder");
// If screen size changes, you can add a resize event to reassign this:
const mHeight = window.innerHeight / 2 || document.documentElement.clientHeight / 2;
document.addEventListener("scroll", () => {
  const currentPos = document.documentElement.scrollTop + mHeight;
  for (const borderContainer of borderContainers) {
  const { offsetTop, offsetHeight } = borderContainer;
    const { count } = borderContainer.dataset;
  const partLength = offsetHeight / count;
  const elEnd = offsetTop + offsetHeight;
    borderContainer.querySelectorAll('span').forEach((span, i) => {
   const offset = i * partLength;
   const spanTopOffset = offsetTop + offset;
   const spanBotOffset = spanTopOffset + partLength;
   const { direction } = span.dataset;

      // 0 when current position before or at top of span section
      // between 0 and 100 when current position is between top and bottom of span section
      // 100 when current position is after bottom of span section
      const percentScrolledThisElement = Math.min(
        100,
        Math.max(
          0,
          Math.round(((currentPos - spanTopOffset) * 100) / partLength)
        )
      );
      if (direction === "horizontal") {
        span.style.width = percentScrolledThisElement + "%";
      } else {
        span.style.height = percentScrolledThisElement + "%";
      }
  });
 }
});
#lipsum {
  max-width: 680px;
  margin: 0 auto;
}

.animateBorder {
  display: flex;
  outline: 1px solid red;
  height: 300px;
  width: 50%;
  align-items: center;
  justify-content: center;
  position: relative;
}

span {
  display: block;
  background-color: green;
  position: absolute;
}
span.b-top {
  top: 0;
  width: 0;
  height: 2px;
}
span.b-top.d-right {
  left: 0;
}
span.b-top.d-left {
  right: 0;
}
span.b-right {
  right: 0%;
  height: 0;
  width: 2px;
}
span.b-right.d-up {
  bottom: 0;
}
span.b-right.d-down {
  top: 0%;
}
span.b-bottom {
  top: 100%;
  width: 0;
  height: 2px;
}
span.b-bottom.d-right {
  left: 0;
}
span.b-bottom.d-left {
  right: 0;
}
span.b-left {
  left: 0%;
  height: 0;
  width: 2px;
}
span.b-left.d-up {
  bottom: 0;
}
span.b-left.d-down {
  top: 0%;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacinia mi eget efficitur pretium. Aliquam neque mauris, commodo sed leo quis, rutrum rhoncus dui. Nulla in sollicitudin magna. Aliquam at fermentum metus. Integer ac diam id urna placerat ornare. Integer consequat condimentum sem, quis finibus mi hendrerit non. Morbi quis fringilla purus, consequat imperdiet mauris. Sed dictum pretium tellus, eget euismod sem.

Morbi suscipit magna nibh, vel tempus justo fermentum non. Nullam metus sapien, viverra quis viverra ac, ullamcorper ut neque. Maecenas eget orci quis libero aliquam gravida id in ligula. Mauris molestie consectetur erat, sed pharetra magna. Fusce consequat luctus libero sit amet posuere. Aliquam ultricies purus a nunc molestie elementum. Aliquam erat volutpat.

  top,right,bottom

  left,bottom

Nam at ligula leo. Integer eu ante vitae nisi pellentesque feugiat in vitae neque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante odio, placerat eu tincidunt in, luctus a diam. Aenean sed elit nunc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur a ullamcorper orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Proin finibus elit sed urna tempus, in volutpat ipsum volutpat.

Praesent nunc elit, aliquam id sagittis in, ornare a dui. Vestibulum aliquam sem sit amet risus porttitor, ornare fringilla ex tristique. Vivamus quis augue id enim placerat finibus. In ullamcorper, tortor eu finibus euismod, sapien felis eleifend urna, feugiat convallis metus purus sed ante. Pellentesque volutpat egestas mi, in luctus mauris. Suspendisse pellentesque sed enim eu maximus. Donec vestibulum orci nunc, sed egestas mauris iaculis vel. Aenean malesuada bibendum turpis eget lobortis. Sed et ex non lorem varius interdum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent ultrices vehicula pretium. Aliquam mollis dolor ut commodo viverra. Nam nibh mauris, hendrerit et ipsum sed, aliquet auctor lacus. Maecenas tincidunt neque sed enim facilisis sagittis.

  top,right,bottom

Ut ornare, metus eu consectetur pulvinar, mi ipsum egestas nibh, et rhoncus odio nulla quis massa. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis tincidunt turpis nunc, vitae pretium velit condimentum non. Nunc eleifend ipsum porttitor ligula mattis faucibus. Etiam ac neque vitae nibh finibus lobortis. Morbi laoreet auctor metus, quis sagittis lectus posuere at. Aenean quis gravida lorem. Mauris aliquam, purus nec congue blandit, erat ligula ornare erat, eu malesuada augue nunc in dolor. Mauris vestibulum condimentum suscipit. Suspendisse id nibh sed ex ornare tempus vel vitae velit. Quisque sem enim, sodales nec leo et, fermentum finibus lacus. Suspendisse sit amet rutrum arcu.

Morbi nec efficitur nibh, a condimentum justo. Nunc enim nunc, gravida sed convallis eget, pulvinar nec ex. Pellentesque vitae feugiat massa. Phasellus fermentum orci eu commodo pulvinar. Ut eget porttitor purus. Nam posuere, tortor eleifend condimentum fermentum, lacus quam luctus diam, id congue tortor tortor vel nulla. Vivamus iaculis luctus mauris et dictum. Curabitur rutrum felis eros, vitae tempus risus pellentesque in.

Ut tempor feugiat efficitur. Donec cursus sem consequat malesuada malesuada. Curabitur eu turpis quis tortor aliquet lobortis. Aliquam venenatis, nibh at porttitor faucibus, ex tortor viverra elit, vitae egestas ante augue ut tellus. Phasellus venenatis finibus blandit. Suspendisse sit amet eros vitae odio iaculis accumsan. Pellentesque eu nunc dolor. Vestibulum sed massa at orci ornare bibendum.

Pellentesque nec justo ornare, iaculis turpis ut, vestibulum orci. Integer vel sem sed justo dapibus tempor. Nam hendrerit at sem eu lobortis. Duis id urna ac odio lobortis aliquet. Praesent id porttitor purus. Quisque et nibh in diam accumsan congue ac in velit. Proin libero mauris, interdum sollicitudin mauris id, dignissim ultrices metus. Etiam lacinia augue vitae suscipit euismod. Aliquam pulvinar dui semper lectus accumsan, auctor sagittis erat convallis. Donec faucibus id velit a consectetur.

Suspendisse sodales pretium molestie. Morbi vulputate posuere porta. Duis dictum ultrices facilisis. Sed lobortis libero ipsum, eget tempus turpis blandit sed. Curabitur egestas dolor metus, quis iaculis dolor mattis vitae. Donec ac accumsan leo. Aenean maximus sapien eros.

Praesent leo risus, sagittis ut sapien eget, convallis aliquam lacus. Donec posuere, mauris nec fringilla dictum, purus velit imperdiet purus, vel aliquam magna dui sit amet urna. Phasellus consequat purus id erat ornare congue quis non neque. Donec odio lectus, tincidunt eu sapien sit amet, fringilla dignissim felis. Nunc blandit vehicula ligula quis suscipit. Aenean nec auctor augue. Integer semper mauris eleifend, luctus est sit amet, hendrerit tellus. Donec at erat nec nulla convallis aliquam. Donec laoreet sit amet arcu at pretium. Sed et consequat augue, eget ultricies massa. Suspendisse luctus nulla at eros elementum fringilla.

Duis volutpat erat nec feugiat lacinia. Praesent eget consectetur arcu. Duis fringilla imperdiet libero, eget tincidunt metus tincidunt vel. Suspendisse dignissim quis velit a tempor. Curabitur finibus nec tellus ac aliquet. Cras porttitor efficitur tristique. Maecenas bibendum lacus dui, in mattis tortor aliquam vel. Vestibulum quis tortor semper, consequat nulla eget, lacinia ante. Phasellus ornare vel massa nec eleifend. In aliquet ultricies augue.

Nam ante augue, condimentum non nulla in, imperdiet dignissim augue. Curabitur sodales ullamcorper turpis, vitae convallis lacus vulputate eget. In mollis ipsum eleifend porttitor egestas. Aenean orci mi, scelerisque euismod justo id, luctus hendrerit tortor. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In lobortis vitae dui ac efficitur. Nullam iaculis vulputate mi, sed pharetra turpis ultrices non. Pellentesque vitae sodales orci, non vulputate odio. Aliquam eu molestie ex. Maecenas pellentesque lorem est, quis lacinia odio tincidunt nec. Suspendisse pharetra est et magna tincidunt scelerisque.

Vestibulum eu finibus orci. Sed non egestas felis. Vestibulum et nisi vel metus faucibus mattis. Vivamus at ligula sodales, commodo nisl vitae, pharetra tellus. Phasellus quis magna blandit, suscipit magna ac, interdum sem. Cras facilisis dui eu dolor efficitur, sed commodo velit placerat. Sed tempus tortor sit amet nunc dignissim, sit amet vestibulum mi luctus. Donec eget elit ex. Aenean sodales viverra est. Sed accumsan mauris turpis, eu rhoncus lacus volutpat eu. Curabitur et consectetur felis. Nullam at nulla vestibulum, eleifend quam ac, tristique odio. Phasellus sapien ante, blandit ultricies eros at, semper viverra elit.

Sed dictum accumsan efficitur. Sed convallis lobortis porttitor. Nullam vitae lorem sed felis semper tincidunt. Mauris ut ipsum purus. Cras ultricies pharetra tellus sit amet accumsan. Quisque sed nulla lorem. Aliquam pulvinar a nisi sit amet semper. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla aliquam scelerisque erat et facilisis.

Cras ac varius odio, in sollicitudin sapien. Nunc tincidunt vulputate tortor ac euismod. Phasellus dignissim et orci sit amet malesuada. Sed suscipit lectus libero. Maecenas ac aliquam diam, sit amet feugiat nibh. Duis vehicula sem nec tincidunt viverra. Donec non dolor nulla. Curabitur iaculis justo vitae vehicula egestas. Phasellus efficitur volutpat faucibus. Morbi ligula nisl, porttitor nec lectus non, accumsan ornare augue. Nullam imperdiet nisl eu urna bibendum finibus nec vel augue. Phasellus vestibulum dui at interdum sollicitudin. Etiam ac commodo metus. Vestibulum augue metus, commodo vitae felis venenatis, aliquet feugiat mauris. Duis consequat dui enim, in posuere lorem aliquet vitae.


Async Task with multiple requests in android

If you want to call the services in sequence, use IntentService.

if you are getting confused, check out the video link below and other related videos by Google. They have explained it how and when to use different APIs for threading work.

https://www.youtube.com/watch?v=9FweabuBi1U&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE&index=7


Using an Edit box in a table views header section to insert the values into the table using swift

Random Fixes

You don't need to pre-pend with self in self.title = "Testing" or self.tableView.

var data = ["Apple", "Apricot"] as NSMutableArray

This doesn't need to be declared as an NSMutableArray.  Swift defines a mutable array like this
    var data = ["Apple", "Apricot"]
and if you wanted it to be non-mutable, then declare it with let

Remove the functions that Xcode auto populated your code with if you aren't actually doing something in them.  This includes didReceiveMemoryWarning, awakeFromNib, and setSelected.

Subclassing

I think you're incorrectly labeling the parts of a UITableView in your description.  Going by your comp, the UITextField and Add button are contained inside a tableHeaderView.  This shouldn't be subclassed as a UITableViewCell - if you look at the documentation for the tableHeaderView property of a UITableView you'll see its a UIView.  Let's just rename the InputToListCell as InputToListView and change it to a UIView.

Passing Data From the Header View to the TableView

As a general rule in iOS, a view that is a component of a larger system shouldn't know anything about nor should it be able to control that larger system.  Here, the component is the InputToListView and its parent is the UITableView.  The InputToListView shouldn't have an array of its own.  When it is declared in the ViewController, its button property should add a selector that is called inside the ViewController.  Delete both tableView and array properties from it.

func createHeader(){
    headerView = NSBundle.mainBundle().loadNibNamed("InputToListView", owner: nil, options: nil) as! InputToListView
    // delete the next line - the cell shouldn't need to know anything about what the table view has or doesn't have
    // the tableview already has its own array that it is using as its source of data
    //headerViewCell.setTableViewWithData(self,data: data)
    tableView.tableHeaderView = headerViewCell
    headerView.button.addTarget(self, action: "addButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
}

func addButtonPressed() {
// 1 access the headerView's textField property
// 2 check to see if the the textField has text by unwrapping it and if it has characters to display in the table view
// 3 add that text to the tableView's data array
// 4 either insert a new row into the tableView (preferred) or reload the tableView (messy)
}

Notice that the headerView should be a property of the ViewController.  That way you can access its textView property to use its text to add to the ViewController's array.  Conversely, you can declare a callback closure in the addButtonPressed: function of the header view and pass in the textView's text.


Excel VBA script – concatenates multiple values using Loop

The approach I took to your problem led me to separate it into two stages: the first determine the locations of the source data and the second processes the data to perform the concatenation.

Initially capturing your source data, I used the following data setup:

A few things to note:

Always use Option Explicit for the reasons listed there
Always define and set references to all Workbooks and Sheets
Work with Arrays, Not With Ranges

And so, based on those concepts, the setup method looked like this:

Option Explicit

Sub DataSetup()
    Dim wb As Workbook
    Set wb = ThisWorkbook

    Dim ws As Worksheet
    Set ws = wb.Sheets("Sheet1")

    Dim staticText(1 To 3) As String
    staticText(1) = ws.Range("A2")
    staticText(2) = ws.Range("A3")
    staticText(3) = ws.Range("A4")

    Dim startRow As Long
    Dim lastRow As Long
    Dim loopRange As Range
    startRow = 4
    lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
    Set loopRange = ws.Cells(startRow, "C").Resize(lastRow - startRow + 1, 1)

    Dim userRange As Range
    startRow = 3
    lastRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).Row
    Set userRange = ws.Cells(startRow, "E").Resize(lastRow - startRow + 1, 1)

    Dim results As Variant
    results = LoopAndConcat(staticText, loopRange, userRange)

    Dim resultsRange As Range
    Set resultsRange = ws.Range("G2").Resize(UBound(results, 1), 1)
    resultsRange = Application.Transpose(results)
End Sub

You may notice that I didn't pass arrays to the LoopAndConcat function. We only really need that data as an array inside the function, no where else.

Inside the work of the concatenating function, I took advantage of the fact that your static data is limited to three strings. Because of this, you can do all the work in a single loop. Working from arrays and storing the results in an array makes this function very fast. The resulting array of data can be located anywhere in the workbook you need it, the function doesn't need to care where those results end up.

Function LoopAndConcat(fixedText() As String, _
                       loopArea As Range, _
                       userArea As Range) As Variant
    '--- for speed, copy the data to memory arrays
    '    (expected Range is "n" rows by one column)
    Dim loopData As Variant
    Dim userData As Variant
    loopData = loopArea
    userData = userArea

    '--- establish results array, properly sized
    Dim results() As Variant
    ReDim results(1 To UBound(userData, 1)) As Variant

    Dim finalText As String
    Dim i As Long
    Dim j As Long
    j = 1
    For i = 1 To UBound(userData, 1)
        finalText = fixedText(1) & loopData(j, 1) & _
                    fixedText(2) & userData(i, 1) & _
                    fixedText(3)
        results(i) = finalText
        j = j + 1
        If j > 3 Then
            j = 1
        End If
    Next i
    LoopAndConcat = results
End Function

My results:


Finding acronyms with >=1 letters at the start of each consecutive word

Correctness

Your code allows partial acronyms which doesn't seem right. "I'm seeking a clean and efficient way to determine whether one string is an initialism/acronym of another."
recursive_split('aei', 'an example is this')
# [('a', 'an'), ('e', 'example'), ('i', 'is')]

Performance 1

A list comprehension being fed into a for loop is not idiomatic. It would be better if you move the expression into the for's expression.
for i in range(4):
    s1_sub = s1[:i]

It should be clear if len(s1_sub) != i then s1_sub == s2[:len(s1_sub)] is going to call the body multiple times with the same values. To address this wastage we can bound the for loop.
for i in range(min(4, 1 + len(s2))):

Rather than s1_sub!='' we can start the range at 1.
for i in range(1, min(4, 1 + len(s2))):

If len(s1) < len(s2) then we are wasting iterations of the for loop when we could just adjust the range.
for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):

If s1[:i] != s2[:i] then i+1 will always be false too. You should instead break if this is ever false.
for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):
    s1_sub = s1[:i]
    if s1_sub != s2[:i]:
        break
    # do stuff

We don't need to slice s1 and s2 to compare the values. We can just index. This makes the range a little simpler.
for i in range(min(3, len(s1), len(s2))):
    if s1[i] != s2[i]:
        break
    s1_sub = s1[:1 + i]

def recursive_split(s1, s2, mapping=[]):
    for i in range(min(3, len(s1), len(s2))):
        if s1[i] != s2[i]:
            break
        s1_sub = s1[:1 + i]
        mapping_ = mapping + [(s1_sub, s2.split()[0])]
        if s1_sub == s1:
            return mapping_
        rec = inner(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)
        if rec is not None:
            return rec

Clean code
Many of the changes above have increased the readability of your code.

The names s1 and s2 aren't very descriptive.

Performance 2
These are some more advanced performance changes. Depending on the person the decreased readability may not outweigh the performance gains.

Rather than using mapping=[] you can use a closure and pass a fresh mapping.
def recursive_split(s1, s2):
    def inner(s1, s2, mapping):
        for i in range(min(3, len(s1), len(s2))):
            if s1[i] != s2[i]:
                break
            s1_sub = s1[:1 + i]
            mapping_ = mapping + [(s1_sub, s2.split()[0])]
            if s1_sub == s1:
                return mapping_
            rec = inner(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)
            if rec is not None:
                return rec
    return inner(s1, s2, [])

Constantly calling s2.split() and ' '.join(s2.split()[1:]) are very wasteful. Instead you could call str.split once and just work with the split list.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        try:
            s2 = s2s[s2_index]
        except IndexError:
            return None
        for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):
            s1_sub = s1[:i]
            if s1_sub != s2[:i]:
                break
            mapping_ = mapping + [(s1_sub, s2s[s2_index])]
            if s1_sub == s1:
                return mapping_
            rec = inner(s1[len(s1_sub):], s2_index + 1, mapping_)
            if rec is not None:
                return rec
    s2s = s2.split()
    return inner(s1, 0, [])

We don't need to add s2s[s2_index] to mapping_ because s2_index only ever increases by 1 each time so we can do that outside of inner.
mapping_ = mapping + [s1_sub]

ret = inner(s1, 0, [])
if ret is None:
    return None
return list(zip(ret, s2s))

With mapping + [s1_sub] will make near duplicate copy each time you recurse. We can improve the performance by mutating the mapping.
To do this we just append to the stack where you did mapping + [s1_sub] and then pop after any recursion.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        try:
            s2 = s2s[s2_index]
        except IndexError:
            return None
        for i in range(min(3, len(s1), len(s2))):
            if s1[i] != s2[i]:
                break
            s1_sub = s1[:1 + i]
            mapping.append(s1_sub)
            if s1_sub == s1:
                return mapping
            else:
                rec = inner(s1[1 + i:], s2_index + 1, mapping)
                if rec is not None:
                    return rec
            mapping.pop()
    s2s = s2.split()
    ret = inner(s1, 0, [])
    if ret is None:
        return None
    return list(zip(ret, s2s))

We can do something similar to s1. However instead of appending and popping we can pop in the for loop and then extend after the for loop. As such we just need to reverse s1.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        try:
            s2 = s2s[s2_index]
        except IndexError:
            return None
        s1_sub = []
        for i in range(min(3, len(s1), len(s2))):
            s1_sub.append(s1.pop())
            if s1_sub[-1] != s2[i]:
                break
            mapping.append(s1_sub)
            if not s1:
                return mapping
            else:
                rec = inner(s1, s2_index + 1, mapping)
                if rec is not None:
                    return rec
            mapping.pop()
        s1.extend(s1_sub[::-1])
    s2s = s2.split()
    ret = inner(list(reversed(s1)), 0, [])
    if ret is None:
        return None
    return [
        (''.join(s1_sub), s2)
        for s1_sub, s2 in zip(ret, s2s)
    ]

We can use generators and a couple of tricks to reduce the line count.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        s2 = s2s[s2_index]
        s1_sub = []
        for i in range(min(3, len(s1), len(s2))):
            s1_sub.append(s1.pop())
            if s1_sub[-1] != s2[i]:
                break
            mapping.append(s1_sub)
            if not s1:
                yield mapping
            elif s2_index + 1 < len(s2s):
                yield from inner(s1, s2_index + 1, mapping)
            mapping.pop()
        s1.extend(s1_sub[::-1])
    s2s = s2.split() or ['']
    rets = (
        [(''.join(s1_sub), s2) for s1_sub, s2 in zip(ret, s2s)]
        for ret in inner(list(reversed(s1)), 0, [])
    )
    return next(rets, None)

Given your examples it would be better to use a greedy search. For each letter you recurse straight away however if you went from the point we break in the for loop then inner would never return None on your example data.
def recursive_split(s1, s2):
    def inner(s1, s2_index, mapping):
        s2 = s2s[s2_index]
        s1_sub = []
        for i in range(min(3, len(s1), len(s2))):
            s1_sub.append(s1.pop())
            if s1_sub[-1] != s2[i]:
                break
        while s1_sub:
            mapping.append(s1_sub)
            if not s1:
                yield mapping
            elif s2_index + 1 < len(s2s):
                yield from inner(s1, s2_index + 1, mapping)
            mapping.pop()
            s1.append(s1_sub.pop())
        # nonlocal counter
        # counter += 1
    # counter = 0
    s2s = s2.split() or ['']
    rets = (
        [(''.join(s1_sub), s2) for s1_sub, s2 in zip(ret, s2s)]
        for ret in inner(list(reversed(s1)), 0, [])
    )
    ret = next(rets, None)
    # print(counter)
    return ret

This prints 0, if you uncomment the code, where as the previous code printed 2 because it recursed on a from an and e from ex.

We can remove the recursion and so we can remove the stack frames.
In the previous example it should be clear that mapping is acting like a stack and we can actually get s2_index from it.
Additionally we can see that the code is quite reliant now on the fact that we're mutating s1.
So we can think of the code another way.

Build the rest of the stack based on the state of s1.

At first this is just the same as the for i in range(...) loop.
If there are no matches, s1_sub is empty, then we have to start the popping process.
Otherwise we add the value to the stack.
Then if the length of the stack is the same as s2s then we have a value to return.

Pop from the stack.

If we make a value in the stack empty, then we need to pop again from the stack, otherwise we'll have an infinite loop. As the builder will just build the exact same way.
If we pop from the entire stack, we're done.

def recursive_split(s1, s2):
    s1_ = list(reversed(s1))
    s2s = s2.split()
    stack = []
    while True:
        while len(stack) < len(s2s):
            s1_sub = []
            for value in s2s[len(stack)]:
                if not s1_ or value != s1_[-1]:
                    break
                s1_sub.append(s1_.pop())
            if not s1_sub:
                break
            else:
                stack.append(s1_sub)
                if len(stack) == len(s2s):
                    return [(''.join(values), s2) for values, s2 in zip(stack, s2s)]
        for _ in range(len(stack)):
            s1_.append(stack[-1].pop())
            if stack[-1]:
                break
            stack.pop()
        else:
            return


Google Crawler. Searches the 100 first google results for some term

Some thoughts:

Usually when naming an interface, you want to give some hint as to what actions that interface describes.  Here I don't quite understand what implementing GoogleProxy should be able to do for the implementing class.  What do getting a response and parsing a URL have to do with a proxy? What do these methods have to do with Google specifically? Would this interface better be named as HttpClient or something like that which indicates that these are the methods that need to be implemented by a class to enable the request/response aspects of crawling?
You might consider adding @throws in your interface documentation for parseUrl().  Not that this really does anything, but perhaps at least it can drive code consistency in having implementing classes throw appropriate exceptions and might help when working in an IDE.
In your getHttpResponse() implementation, you are doing nothing to either handle underlying exceptions that can be thrown by the Guzzle Client or indicate that the function might throw (why no doc blocks in implementing class?).
You should namespace your interface file.
In your parseUrl(), I think it is problematic that you are parsing the query string into the same array that you put your parse_url() results into.  Why not just create a new array here to eliminate confusion over what your intent is and to eliminate any possibility of overwriting date in $link() (if you ever wanted to do anything else with that data.
Should you really throw an exception if the URL value in the query string is not valid? I would think that this could be an expected occurrence that you might need to handle as you have no control over this input. Does this really represent an unexpected state in your application as is often the intended use for throwing exceptions?
Should you add some validation for the parametric input to both of these functions (i.e. non-zero length string, properly formed URL). In your getHttpResponse() implementation you can get as far as attempting to make a (relatively expensive) call on a remote host even if you have an empty string or invalid URL passed to the method.  I generally think it good practice to enforce some basic level of validation on parameters passed to public methods, perhaps throwing InvalidArgumentException or similar before getting into method logic such that you are failing fast and failing loudly when bad input is passed.
From looking at your wider library on Github, it seems as if you are trying to work with dependency injection. If you want to be consistent in this approach, I would think your implementing classes would need to take on dependencies such as the Guzzle client in their constructors, as opposed to within the methods that are implementing the interface.
With the above thought in mind, I am actually not sure that what you have right now is even best modeled as an interface vs. class inheritance since all the proxy classes you currently have implemented don't really do much outside of implement these two methods.


You should also make heavy use of the filter functions of PHP.

<?php

if (filter_input(INPUT_POST, "form_id", FILTER_UNSAFE_RAW) === filter_input(INPUT_SESSION, "form_id", FILTER_UNSAFE_RAW)) {
  $username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
  $password = filter_input(INPUT_POST, "password", FILTER_UNSAFE_RAW);

  if ($username && $password) {
    $database->query("SELECT `username`, `password`, `active` FROM `admin` WHERE `username` = :username AND `password` = :password LIMIT 1");
    $database->bind(":username", $username);
    $result = $database->resultset();

    if (isset($result[0]) && password_verify($password, $result[0]["password"])) {
      echo "Welcome!";
    }
  }
}


Java 8 Stream to produce all permutations of an array using recursion

Not a review, but an extended comment:

I strongly advise against recursion here. The permutations have a natural (lexicographic) ordering, and given a permutation it is easy to construct a next one.

This hints that to achieve true streaming: implement nextPermutation() method, and pass it to Stream.iterate() as an unary operator.


Attempt at method to draw diamond (recursive or not ?)

You can make this a recursion exercise with two parts:

1) Write a recursive method to repeat a char n times.

Signature:

public static String getCharRepeatedTimes(final char c, final int times)

(Read at end to see a solution)

2) Write a recursive method to create a diamond pattern.

Signature for recursive start method:

public static String getDiamondWithSize(final int size)

Signature for recursive "work" method:

private static String getDiamondWithSize(final int size, final int currentSize)

Hint 1: You can use the method from 1)
Hint 2: Think about a pattern in the diamon and how to exploit it.

(Read at end to see a solution)

Let us start with 1):

public static String getCharRepeatedTimes(final char c, final int times) {
    if (times == 0)
        return "";
    return String.valueOf(c) + getCharRepeatedTimes(c, times - 1);
}

And continue with 2):

public static String getDiamondWithSize(final int size) {
    return getDiamondWithSize(size, 2 - (size & 1));
}

The start method can be done in two ways. Starting from the outer area to the inner area or vice-versa. I have done the out->in way. If you allow even and odd diamonds, then we have to manage the start or end size in the correct way. There the 2 - (size & 1) part, which is 2 for even size and 1 for odd size.
The idea is now to create the outer lines first and append it to the next inner part then. Until the inner part is the full part.

private static String getDiamondWithSize(final int size, final int currentSize) {
    if (currentSize == size)
        return getCharRepeatedTimes('*', size) + "\n";
    final int nonDiamondSpace = (size - currentSize) / 2;
    final String currentLine = getCharRepeatedTimes(' ', nonDiamondSpace) + getCharRepeatedTimes('*', currentSize) + "\n";
    return currentLine + getDiamondWithSize(size, currentSize + 2) + currentLine;
}

The + concatenation could be replaced by StringBuilder , insert and append. For clarity and the exercise purpose, it is not done here.

Suggestions for your code:

public static void drawDiamond(String seed, int turn, final int centerLevel) {
    ...
    if (turn <= centerLevel)

Noone would expect this if the method is called. At least for me, it is unclear how the argument centerLevel is related to the size of the diamond. You should add at least some JavaDoc, I would prefer to change the behavior.

    turn++;
    drawDiamond(seed, turn, centerLevel);

In general, you should avoid to change arguments, if possible. In this case, we can go with this:

    drawDiamond(seed, turn + 1, centerLevel);

This looks a bit complex:

    if( turn <= centerLevel ){
        seed += "**";
    } else {
        if( seed.length() >= 3 ) {
             seed = seed.substring(1,seed.length()-1);
        } else {
            seed = "";
        }
    }

You should add at least some comments. And you can decrease the branch depth by one:

    if (turn <= centerLevel) //until the mid is reached, increase by two stars
        seed += "**";
    else if (seed.length() >= 3) //until the end is reached, reduce by 2 chars
        seed = seed.substring(1, seed.length() - 1);
    else //finished
        seed = "";

Rest is more a subjective view. I would rather introduce a method to generate a char/String repeated n times than doing it inside the diamond method. And I would avoid the seed argument as shown above.


Conditional validation for credit card payment information on form submission

Incomplete code

Your question's code is missing so much information there is not much to review.

Because of this I can only review the code in regard to exactly the logic your function performs.

Style points

Don't add code that is not needed. Eg

The variable input is a copy of element having two names for the same reference will lead to confusion, mistakes and bugs.
You add a function to form submit, and all it does is call validateForm. Set the listener to validateForm eg form.addEventListener('submit', validateForm) and avoid the middle man.

Good code does not repeat AKA is DRY (Don't Repeat Yourself).

Examples of repeated code;

You call errorMessage, with the same 3 last arguments five times. Create a function and just pass the first argument, let the function call errorMessage with the rest of the arguments.
You repeat the same statement if (creditOptionChecked()) { three times. Again hand the repetitive source code to a function..

Variables that do not change and/or should not change should be declared as constants. eg const value = element.value; rather than let value = element.value;
Array.from requires an array like argument. Array like arguments are all iterable thus you do not need to create an array before you iterate. The line Array.from(inputElements).forEach(element=> { can be written as inputElements.forEach(element => { or for (const element of inputElements) {

Array iterators (example Array.forEach) are not as efficient as for or while loops. Using for or while loops when you can also gives you a better sense of the code complexity, while using a little less memory and power.

Example

Rewriting your function to be compatible with the original under all possible unknown states using the above points.

form.addEventListener("submit", e => {
    var input;
    const error = valid => errorMessage(valid, input, input.value, e);
    const optError = valid => creditOptionChecked() && error(valid);
    for (input of inputElements) {
        if (input === name) { error(isValidName) }
        else if (input === email) { error(isValidEmail) }
        else if (input === creditNumber) { optError(isValidCreditCard) }
        else if (input === zip) { optError(isValidZipCode) }
        else if (input === cvv) { optError(isValidCvv) }
        else if (input == fieldSetActivity) { validateCheckboxes(e) }
    }
});

There are some improvements that can be made depending on the unknowns, maybe needing no if statements at all, but I likely waste both of our times if I speculate.


How to reduce responsibility of the main function in strategy pattern (python)

The strategy design pattern is useful mostly when you want to parametrize an algorithm with different behaviours. That implies you would have more than one strategy, which is not the case here. As such, calling this a strategy might be confusing.

Instead, it might be better to view your class as a decorator that can cache the result of a computation in a file. However, that would raise two questions:

Why is the cached data independent from the process that can produce the data, and why is the cached data independent of the input? For example, this behaviour might not be expected:

def multiply_by_2(*xs):
  return [2 * x for x in xs]

def add_3(*xs):
  return [x + 3 for x in xs]

cache.run(multiply_by_2, 1, 2, 3)  #=> [2, 4, 6]
cache.run(multiply_by_2, 3, 4, 5)  #=> [2, 4, 6]
cache.run(add_3,         1, 2, 3)  #=> [2, 4, 6]

That the function may be changed can be prevented by providing the process to the constructor, i.e. associating a cache file with a function before your cache is queried. A different function would then get a different cache.

That the data may vary between invocations is difficult to prevent unless you also store the input data in the file. You may be interested in looking at the functools.lru_cache() decorator that can cache the last n calls in memory, and looks up the correct cache entry by argument values.
If the cache object decorates an existing function (and effectively just offers a single public method run(), then it may be convenient to let the cache also offer a function-like interface: either by implementing a __call__() method, or by actually just using nested functions. With the latter approach, you might implement a decorator like:

def cache(filename, forcecreate=False):
  def inner(process):
    def cached(*input):
      ...  # basically your run() method
    return cached
  return inner

Used like:

@cache("foo.data")
def cache_me(a, b, c):
  ...

result = cache_me(1, 2, 3)

or:

cached_multiply_by_2 = cache("multiply by 2.data")(multiply_by_2)
result = cached_multiply_by_2(1, 2, 3)

It is also possible to do this with an object with a __call__() method. Such an object is actually preferable for debugging since you can inspect the properties of an object.

Other notes:

The self.t field is never read. It can be safely removed.
While __post() reads from self.output, the corresponding __pre() method does not write to that variable, returning a result instead. It would be better if either both methods directly access the self.output state or both methods are "pure" so that __post() would take an parameter.
The names of pre and post are slightly confusing. I would associate them with asserting preconditions and postconditions. Instead, they load() and store() cached data.
Your cache format is unable to cache a None value. When a None is loaded, the process is re-run again. Instead, load/store the data within a container, e.g. a single-element list. Then an empty list indicates the absence of a value, whereas a single-element list (even if that element is None) indicates the presence of a value.
if not self.output is None: would usually be written as if self.output is not None:.
The outer parentheses in if (Path(self.filename).is_file()): are unnecessary.
Output like print("File exists") deep inside your code is not a good idea. If you want to do logging, use a dedicated logging function that is switched off by default. If you output logging, prefer writing to sys.stderr rather than sys.stdout.
any([i is None for i in inputs]) creates a list unnecessarily. A generator expression is sufficient: any(i is None for i in inputs).
It is weird that your class checks the arguments for None-ness. If the wrapped process() cannot handle nones it should check that itself. Or you could define a separate decorator that you could apply independently:

def all_not_none(function):
  @functools.wraps(function)
  def inner(*args):
    if any(x is None for x in args):
      raise ValueError(...)
    return function(*args)
  return inner

(Using the functools.wraps decorator fixes docstrings and names of the returned function object to imitate the original function more closely.)


Python converter: number-to-English - Project Euler 17

Here's one using modulo % and list joining that uses your original NUMBER_WORDS dict:

def int_to_english(n):
    english_parts = []
    ones = n % 10
    tens = n % 100
    hundreds = math.floor(n / 100) % 10
    thousands = math.floor(n / 1000)

    if thousands:
        english_parts.append(int_to_english(thousands))
        english_parts.append('thousand')
        if not hundreds and tens:
            english_parts.append('and')
    if hundreds:
        english_parts.append(NUMBER_WORDS[hundreds])
        english_parts.append('hundred')
        if tens:
            english_parts.append('and')
    if tens:
        if tens < 20 or ones == 0:
            english_parts.append(NUMBER_WORDS[tens])
        else:
            english_parts.append(NUMBER_WORDS[tens - ones])
            english_parts.append(NUMBER_WORDS[ones])
    return ' '.join(english_parts)

It works up to 999,999, but could be extended further with a little customisation.


Concisely, robustly, temporarily stashing c++ iostream formats

One tiny improvement I'd suggest is that the stored state can all be declared const:

const std::ios_base::fmtflags flags;
const std::streamsize width;
const std::streamsize precision;
const charT fill;

There are no implications for assignability of fmtstash objects, as we already had a reference member.


Personally, I think the flag is not the best idea, or at least not, in the scenario you have added it, as it looks like a global variable.

The scenario you have set up now, poses a few problems as you present it, nl:

setTimeout(() => {
  if (!responseReturned) {
     timedOut = true;
     spanSubmitErr.style.display = "inline";
  }
}, 8000);

This doesn't interact with the request at all, at most, the user will see something on his screen, however the response will still be running, and your code may eventually react on it, so you are pretty much unsure if it really worked.

But don't forget that any callback you create should be canceled in the end (through setTimeout (see PatrickRoberts comment below) or setInterval), so that there is no need for you to check if a response returned ;). I personally still prefer the setInterval and clearInterval methods to do that.

Suggested rewrite ES5

function fetch() {
  return new Promise( function (resolve) {
    var timeout = (Math.random() * 10 + 1) * 1000;
    console.log('Waiting ' + timeout + ' ms');
    setTimeout( function() {
      resolve();
    }, timeout);
  });
}

function _fetch( options ) {
  if (!options) {
    options = {
      timeout: 5000
    };
  }
  return new Promise( function(resolve, reject) {
    var interval = setInterval( function() {
      clearInterval( interval );
      reject( { statusCode: 504, status: 'timeout - client' } );
    }, options.timeout || 5000 );
    fetch().then( function( response ) {
      clearInterval( interval );
      resolve( response );
    } ).catch( function( error ) {
      clearInterval( interval );
      reject( error );
    } );
  });
}

function test() {
  var internal = function q() {
    _fetch().then( function() {
      setTimeout( function() {
        q();
      }, 0 );
    }).catch( function( result ) {
      console.log( result );
    });
  };
  internal();
}

test();

Suggested rewrite ES6

If your code base is not to large, or if you are willing to put the time in for refactoring, I would suggest you wrap fetch with your own function, like in the following code sample.

You know that fetch will return a Promise, so create your own version of fetch, which you could then export if necessary, and redirect your files that point to the fetch functionality to your own implementation.

// random method that waits certain time, then resolves
const fetch = () => {
  let timeout = (Math.random() * 10 + 1) * 1000;
  console.log(`waiting ${timeout}`);
  return new Promise((resolve) => {
    setTimeout( () => resolve(), timeout);
  });
}

const _fetch = ( opt = { timeout: 5000 } ) => {
  return new Promise( (resolve, reject) => {
    console.time('interval');
    let interval = setInterval(() => {
      console.timeEnd('interval');
      clearInterval( interval );
      reject({ message: 'timeout occured', statusCode: 504, status: 'timeout - client' });
    }, opt.timeout );
    fetch().then( (...args) => {
      console.timeEnd('interval');
      clearInterval( interval );
      resolve(...args);
    }).catch( (...args) => {
      console.timeEnd('interval');
      clearInterval( interval );
      reject(...args);
    });
  } );
}

async function runRandomTest() {
  let ok = 1;
  while (ok) {
    await _fetch().catch( (...args) => {
      console.log(...args);
      ok = false;
      });
  }
  console.log('test completed');
}

runRandomTest();

Explanation of rewrite

The biggest change would be here, that the fetch function gets wrapped, and called from _fetch, which you would then use inside your code

If you look at it, it works slightly different, nl:

function _fetch( options ) {
  if (!options) {
    options = {
      timeout: 5000
    };
  }
  return new Promise( function(resolve, reject) {
    var interval = setInterval( function() {
      clearInterval( interval );
      reject( { statusCode: 504, status: 'timeout - client' } );
    }, options.timeout || 5000 );
    fetch().then( function( response ) {
      clearInterval( interval );
      resolve( response );
    } ).catch( function( error ) {
      clearInterval( interval );
      reject( error );
    } );
  });
}

It returns it's own promise, and uses the setInterval. In case the result is returned (or another error is thrown), the clearInterval is called and the promise gets handled by either resolve or reject. In case the interval occurs, the promise gets rejected, and the clearInterval is also called.

Note that if you run the test (at least the es6 one), you can see the time it took before the timeout occured, and it will not run longer. Neither does the then method of the fetch still execute. It is true however that your httprequest will still be open, but I don't think that should be such a huge problem, as it will not interact with your own code anymore.

It is still important though to handle the catch of the fetch and pipe it through, so that the interval gets cleared, but that you also get notified of the other errors that might have occured during the request.


TimeSpan don't support years so how do I deal with it? Is there could be smarter solution?

I would propose an alternative method of calculating your time, using seconds and DateTimes:

open System

let startDate = DateTime.Parse ("2012-09-12")
let now = DateTime.Now;
let currentRuntime = (now - startDate).TotalSeconds
let timePerGig = currentRuntime / 7.7;
let tenDate = startDate + TimeSpan.FromSeconds (10.0 * timePerGig);

With that done, you can do whatever you like to represent the final date relative to the current date.

An overly simplistic example is as follows:

printf "%d years %d months %d days" (finalDate.Year - now.Year) (finalDate.Month - now.Month) (finalDate.Day - now.Day)

Of course, you would have to account for roll-over for days and months in any final piece of code, but it illustrates how you could pull the date parts back out.


There are some very good things about this code.

It makes good use of library functionality, which is one of the big strengths of Python. A lot of programmers spend unnecessary amounts of time rewriting things that others have already done, so it's good to see the habit of just using things like askopenfilename as provided.

I also like the use of comments. There are two traps that people fall into with comments: one is not writing any, and the other is writing comments that just say what the code is already saying. A comment like "Update the window" before win.update() would be pointless, whereas your comment "See progress for each row" explains clearly and concisely what the intention behind that update is.

That said, I am slightly confused by two of your comments. It's almost midnight here and I may be misreading the code, but it looks to me as if the first for loop is going from left to right one column at a time, and the second for loop is going one row at a time. If so, those comments are the wrong way round. It's important to make sure that comments are kept up to date and accurate, or they can mislead the person reading the code (even if it's future you.)

You mention it running quite slowly. Now the general rule is that when something runs slowly, you use a tool called a profiler to work out which bits of the code are taking time. I haven't run one on this code, but in my experience that print line is probably taking a surprising amount of time. We always assume that text is easy for computers, which it kind of is, but if you think about it the computer has to set maybe a couple of thousand pixels to update that text for every one pixel that it's doing the greyscale calculation for. Although it's really useful to have such lines while developing something, it's usually worth taking them out once they have served their purpose.

Finally, I'll rattle through a few python best practices that are generally worth bearing in mind.

Your function displayimage does two jobs. It first loads an image from a file, and then creates a window and puts it on the screen. Now, you have made good use of python's multi-return functionality to let you do that cleanly, but usually best practice is that every function should do one thing and do it well. I would suggest cutting that function in half: one function could take a file name and return an image, and a second function should take an image and set up a window for it.
Python programmers usually prefer naming things with snake_case for variable names and function names, which means join lowercase words with underscores. That is purely a convention, but sticking to conventions helps to read code more fluently.
It is generally discouraged to use import *. That is because it is not clear what comes from where. If I want to look at the documentation for, say, Image then I don't know whether to look at the graphics documentation or somewhere else. Even worse, there's a whole bunch of stuff in packages that you're not using, and it can trip you up if you don't realise it's there. For example you could imagine that your graphics module could also have a function called asksaveasfilename. (Ok, probably not that one, but it serves for an example) Then when you call asksaveasfilename you get all sorts of confusion because it could call the wrong one. Even worse, if you update your packages then graphics which didn't have asksaveasfilename before might have it now, and the behaviour of your program changes in entirely unexpected ways.

I hope this is helpful.

Josiah


Focusing on performance, I recommend to split the lookup table into an array of letters and an array of cumulative relative frequencies.

Iterating and accessing compact array elements is much faster compared to accessing object properties.

Also, in contrast to array iteration, the for..in iteration order of object properties is not guaranteed and thus less robust (as pointed out by Mike Brant in the comments).

Moving the lookup table out of the function body into either a closure or a module level constant gives you a speed advantage at least for non-optimizing JavaScript compilers.

A binary search strategy would find the letter corresponding to a random frequency value in O(log n) steps compared to O(n) steps for the current linear search. However, the constant binary search overhead is too big and the array small enough that the linear search performs better in practice.

I get the following performance test results in Firefox 53:

Test:                 Ops/sec:
Original               1,787,627   94% slower
Linear array search   31,399,828   fastest
Binary array search   28,691,914   9% slower

See also the performance test given by @hjpotter92 in the comments.

Here is the winning linear array search module implementation:

/** English language alphabet. */
export const letters = [
    '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'
];

/**
 * English language cumulative letter frequencies × 100000.
 * @see http://en.wikipedia.org/wiki/Letter_frequency
 */
export const frequencies = [
    8167,  9659,  12441, 16694,
    29396, 31624, 33639, 39733,
    46699, 46852, 47624, 51649,
    54055, 60804, 68311, 70240,
    70335, 76322, 82649, 91705,
    94463, 95441, 97801, 97951,
    99925, 100000
];

/**
 * Return a random letter from a - z according to their relative
 * frequencies in the English language.
 *
 * @return {string} random letter from a - z.
 */
export default function randomAtoZ() {
  let random = Math.random() * 100000;
  for (let i = 0, length = letters.length; i < length; i++) {
    if (random < frequencies[i]) {
      return letters[i];
    }
  }
}


AppVersion Struct & VersionParse Exception

I am working on an app that will interact with assembly (app) versions

There's a class, System.Version, that might be suitable for your needs. System.Version:

  Represents the version number of an assembly, operating system, or the common language runtime.

It has Major, Minor, Build, and Revision properties.

If you still want to roll your own, my advice is to

Make AppVersion immutable
Be stricter about the values you allow
Implement IEquatable<AppVersion>
Consider implementing IComparable<AppVersion>

In general, you should avoid mutable structs.

From MSDN

  X DO NOT define mutable value types.

  Mutable value types have several problems. For example, when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value.

See also: Why are mutable structs “evil”?

With the code as written, this works just fine:

appVersion.Version = "   +123 . -4236 . +0 . -789";

Use the overloads of int.Parse/int.TryParse that take a NumberStyles argument. If you provide constructors as suggested below, check that the values passed in are non-negative.

From MSDN

  ✓ DO implement IEquatable<T> on value types.

  The Object.Equals method on value types causes boxing, and its default implementation is not very efficient, because it uses reflection. Equals can have much better performance and can be implemented so that it will not cause boxing.

I find it hard to imagine not ever wanting to compare app versions, so you will probably want to implement IComparable<AppVersion>.

I would recommending getting rid of the Version property entirely. Instead, provide one or more constructors like

public AppVersion(int majorVersion, int minorVersion)

public AppVersion(int majorVersion, int minorVersion, int buildNumber)

...

and then provide static methods AppVersion Parse(string) and bool TryParse(string, out AppVersion).

Also, you should be aware of the existence of auto-implemented properties.


I will not mention again that I find the outdenting of Dim statements hurt readability. Instead I'll focus on this part:

On Error Resume Next
    Set wbTest = Workbooks(strTargetName)
    IsWorkbookOpen = (wbTest.Name = strTargetName)
On Error GoTo 0

What error are you expecting to trap here?

Workbooks(strTargetName)

This will raise runtime error 9 - Subscript out of range. By then you already know everything you need to know.

(wbTest.Name = strTargetName)

This will raise runtime error 91 - Object variable or With block variable not set - but you already know if that call is going to work before you even try it.

This would be cleaner - slightly overkill with error-handling, but cleaner:

Public Function IsWorkbookOpen(ByVal wbFullFileName As String) As Boolean

    On Error GoTo CleanFail
    IsWorkbookOpen = Not Workbooks(wbFullFileName) Is Nothing

CleanExit:
    Exit Function
CleanFail:
    Err.Clear
    Resume CleanExit
End Function

Notice the difference between strTargetName and wbFullFileName: "str" says "that's a string". "wb" says "that's something about a workbook". Both are Hungarian, only one of them is doing it right. Avoid prefixes that indicate the type.


3-Digit Narcissistic Numbers Program - Python

Nice solution, it's already efficient and easy to understand. Few general suggestions:

Avoid calling a variable sum: sum is a built-in function in Python, calling a variable sum prevents you from using such function.
time.perf_counter vs time.time: running your code I get 0.0 running time on Windows, which doesn't provide a useful information. Use time.perf_counter to get a better precision.
Make a function and return a result: if you wrap the code in a function it is easier to reuse and test. Additionally, instead of printing the numbers, add them to a list and return the final result. Printing only the result is typically faster than printing the numbers one by one.
Armstrong numbers: a narcissistic number is also called Armstrong number and here there is an efficient approach that I slightly modified to fit this question:
from itertools import combinations_with_replacement

def armstrong(n):
  numbers = []
  order = len(str(n))
  for k in range(1, order):
      a = [i ** k for i in range(10)]
      for b in combinations_with_replacement(range(10), k):
          x = sum(map(lambda y: a[y], b))
          if x > 0 and tuple(int(d) for d in sorted(str(x))) == b:
              numbers.append(x)
  return sorted(numbers)

Extending the definition of Narcissistic number to:

An n-digit number that is the sum of the nth powers of its digits

The Narcissistic numbers till 1000000 are:
1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834

Runtime:
             n=1_000_000      n=10_000_000
Original:     3.374 s            40.26 s
Armstrong:    0.036 s            0.098 s

Full code:
import time
from itertools import combinations_with_replacement

def original(n):
    numbers = []
    for number in range(1, n):
        order = len(str(number))
        total_sum = 0
        var = number
        while var > 0:
            digit = var % 10
            total_sum += digit ** order
            var //= 10
        if number == total_sum:
            numbers.append(number)
    return numbers

def armstrong(n):
    numbers = []
    order = len(str(n))
    for k in range(1, order):
        a = [i ** k for i in range(10)]
        for b in combinations_with_replacement(range(10), k):
            x = sum(map(lambda y: a[y], b))
            if x > 0 and tuple(int(d) for d in sorted(str(x))) == b:
                numbers.append(x)
    return sorted(numbers)

# Correctness
assert original(1000) == armstrong(1000)

# Benchmark
n = 1_000_000

initial_time = time.perf_counter()
original(n)
total_time = time.perf_counter() - initial_time
print(f'Original: {round(total_time, 3)} s')

initial_time = time.perf_counter()
armstrong(n)
total_time = time.perf_counter() - initial_time
print(f'Armstrong: {round(total_time, 3)} s')


calloc, malloc, free and realloc wrappers to store the size being allocated

Check alignment.

I don;t believe you are correctly aligning your objects.

2. Realloc is wrong.

if realloc returns NULL the original pointer is not deallocated.

MemWrapper* mem2 = static_cast<MemWrapper*>( realloc( mem1, size + MEMWRAPPER_SIZE ) );
if ( !mem2 ) return NULL;

Here if realloc fails you have just leaked memory (as mem1 is still valid).

The standard usage pattern for realloc is:

 void* data = malloc(size);
 ...

 void* extra = realloc(data, newSize);
 if (extra) {
     data = extra;   // only reset data if the realloc worked.

 }


Performant code requires a different style.
When you are working with a lot of data, or need it done fast, it pays to optimise everything. That means that you have to forgo many of the idiomatic coding styles that have come around since ES6.
Some points regarding your code

Don't repeat calculations. Eg you calculate the pixel chanel index 4 times in setPixelColor. Should be once.
Destructuring is SLOW, I mean forever slow, until browsers get round to making destructuring as performant as standard assignment dont use it in performance code.
Move frequent code and variables close to the scope you use the, You have setPixelColor and getPixelColor outside the function, thus it takes extra time to locate these functions.
Most devices are 64bit these days, and low end is 32 bits. Moving a byte takes just as long as moving a 4 bytes as a 32bit long or 8 bytes as 64bit long. Create a 32bit typed array so you can move a pixel in a quarter of the time.
Use 32Bit variables to store colors (eg [255, 0, 0] is 0x0000FF (NOTE 32bit pixels are backwards ABGR the opposite to CSS colors RGBA))
The source of your GC overload is the line for (const n of [[r+1,c], [r-1,c], [r,c+1], [r,c-1]]) { You create an array that contains 4 populated array. A million pixels in a image is small fry, but 5 million arrays is crazy.
Avoid getting values from getters, eg cvs.width is likely a getter. Get the value and store it in a variable scoped as close as possible to where you use it.
You work in rows, and columns (x,y) but the pixel data is a single array. Index directly when you can.
Use local scope, rather than pass variables if you must call functions inside performance loops..
If you can avoid calling functions, its quicker inline.
Use lookup tables to reduce math calculations.
Run in strict mode as it give a slight performance increase, and would also have spotted the undeclared variable p. Because you did not declare it, it becomes a global, and thus access would be much slower than a local. As it is in the heart of the function this will cost you many CPU cycles.

Example
The following does it all in about 1/4 of the time.
See comments for info relating to above comments.

(function () {
    "use strict"; // Always for performant code

    // Colors as 32bit unsigned ints. Order ABGR
    const black = 0xFF000000;
    const red = 0xFF0000FF;
    const green = 0xFF00FF00;
    const blue = 0xFFFF0000;
    const yellow = red | green;
    const magenta = red | blue;

    const cvs = document.getElementById("paint");
    const width = cvs.width;  // Get potencial slow accessors into vars.
    const w = cvs.width;  // alias
    const height = cvs.height;
    const size = width * height;
    const ctx = cvs.getContext('2d');

    // black background
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, width, height);

    const imageData = ctx.getImageData(0, 0, width, height);

    // Use 32bit buffer for single pixel read writes
    const d32 = new Uint32Array(imageData.data.buffer);

    const start = [
        [40 * w + 40, red],  // work in precalculated pixel indexes
        [10 * w + 20, green],
        [23 * w + 42, blue],
        [300 * w +333, yellow],
        [200 * w + 333, magenta]
    ];
    const pixOff = [w, -w, 1, -1];  // lookup for pixels left right top bottom
    const pixOffX = [0, 0, 1, -1];  // lookup for pixel x left right

    const queue = [];  // keep queue content as simple as possible.
    for (const pixel of start) {
        queue.push(pixel[0]);     // Populate the queue
        d32[pixel[0]] = pixel[1]; // Write pixel directly to buffer
    }

    while (queue.length) {
        const idx = queue.shift();
        const x = idx % w; // Need the x coord for bounds test
        for (let i = 0; i< pixOff.length; i++) {
            const nIdx = idx + pixOff[i];
            if (d32[nIdx] === black) {   // Pixels off top and bottom
                                         // will return undefined
                const xx = x + pixOffX[i];
                if (xx > -1 && xx < w ) {
                    d32[nIdx] = d32[idx];
                    queue.push(nIdx);
                }
            }
        }
     }
     for (const pixel of start) { d32[pixel[0]] = pixel[1] }
     ctx.putImageData(imageData, 0, 0);
})();
<canvas id="paint" width=500px height=500px />


One area you could improve performance is by making it a doubly linked list.

At the moment your deleteLast() method is an O(n) operation, meaning it needs to traverse the entire list to delete the last element. And since this is the case, there's no real reason for keeping a reference to it at all.

If each Node had a next and a prev Node, your delete last could look something like,

last.prev.next = null

and let the garbage collector worry about the rest.
You would of course still need to check that all of these values are okay to use like this before hand.

LinkedLists are supposed to be good at adding and deleting elements from the start. And if it's a doubly linked list, also the end.

As side note, I would prefer to see your Node class as a private class inside your linked list class. As this Node class probably shouldn't be used anywhere else.

Your public interface is a bit unusual, for a list, I would expect to have public methods like list.add(element), list.removeAt(0) etc.

list.insertFirst(data) is an implementation detail, this should be a private method that's called when the list is empty. if I wanted to insert an element at the head of the list, I would prefer list.insertAt(0)

Another thing that stands out is your deleteNode method. This is definitely an implementation detail leaking out. A user of the list shouldn't know at all about Nodes.

The method doesn't even take a node, it takes an int, I would prefer list.delete(element).

Also, your list won't properly support duplicate values, if I have 3 nodes with the value if 5, and I try to delete 5, it will delete the first node with a value of 5 it finds.

As another side, you should make as many variables private as possible.


Stop using double underscore.
The double underscore is reserved for the implementation it definitely should not be used in "user code".

See: What are the rules about using an underscore in a C++ identifier?

Recursive template Call.

You use a recursive technique to call the Write() method for all your sinks. I prefer to use the loop technique (I would say this is a more modern approach but I have no reference for that). But I find it clearer as you don't need the empty terminating function call.

private:
    using Tuple=std::tuple<Sinks...>;

    template<std::size_t... index>
    static void writeToLogs(char const* m, std::integer_sequence<std::size_t, index...> const&)
    {
        auto ignore = {(std::get<index>(s_Sinks).Write(m),true)...};
    }

public:
    static void Log(const char* msg)
    {
        writeToLogs(msg, std::make_index_sequence<std::tuple_size<Tuple>::value>());
    }

Design

Everybody and their grandson tends to want to write a logger at some point in time. The trouble is we already have a good logger built into the *nix world (syslog). If you are not using syslog to do your logging you are doing it wrong.

It (syslog) already does everything you need to do and more and there is a whole ecosystem built around it for monitoring. Now there is nothing wrong with writing a wrapper around syslog but you have to be smart about it (the current ones are very smart).

Log(debug, getSomeMessage());

This should not call the function getMessage() if the debugging level is set to production. That would be a complete wast of time and resources as debug messages are currently being ignored.


Simple C# console application to read from csv and query DB

readCSV

This function has no reason to be public, make it private. Also its name is misleading, it's not just reading CSV file but also connecting to DB and saving output...

string outputFile = filePath + @"\outputFile.txt";

Do not blindly concatenate paths, use Path.Combine(). Also filename should be moved to configuration (or if immutable to a const member).

string queryString = null;

You do not need to declare a variable at the top of your method, it's usually better to declare as late as possible (best if together with its initialization).

using (TextFieldParser parser = new TextFieldParser(@"c:\users\myuser\Documents\spellcheck.csv"))

Do not hardcode paths. Never. Read it from configuration, command line or asks for them. Here you do not even use Environment.GetFolderPath()!

string eval = field;

It serves no purpose, just drop it.

queryString = "select Name from myTable where Logic like '%" + eval + "%' and active = '1'";

Do not ever ever build SQL commands like that. Use parameters, code may be broken because of deliberate SQL injection attacks or because of unescaped input data.

SpellingReader.connectToDB(outputFile, queryString, eval);

You're connecting to DB multiple times, it's probably a waste: you'd better keep connection open until you processed all input lines.

connectToDB

public static void connectToDB(string outputFile, string queryString, string eval)

This function has no reason to be public, make it private. Also here the name is misleading, you're not just connecting to DB but also querying data and writing output...

eval parameter has not a truly meaningful name, you'd better pick something more close to your domain.

SqlConnection conn;
conn = new SqlConnection(connectionString);

There is no reason to split this code in two lines, moreover you do not dispose connection in case of errors (use using).

SqlDataReader reader = command.ExecuteReader();

You do not dispose this object in case of errors.

using(StreamWriter file...

Some LINQ may make your code shorter and more readable (if you do not have a huge number of lines to write).

Minor issues

In C# usually functions are PascalCase, also you should be consistent with spacing (if ( or while(?)

What to do?

Let's first make clear what your application is doing:

Read all words from an input file (each word is separated with comma and each line contains multiple words).
For each word check if there is a record in the database where Logic column contains given text.
Print Name column of those records.

Let's write some code (let me assume the number of input words is reasonable - it fits in memory):

static IEnumerable<string> ReadAllWords(string path)
{
    var words = new List<string>();
    using (var parser = new TextFieldParser(path))
    {
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");

        while (!parser.EndOfData)
            words.AddRange(parser.ReadFields());
    }
}

Now let's query DB:

static IEnumerable<string> FindRecordsByWord(SqlConnection connection, string word)
{
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT Name FROM myTable WHERE Logic LIKE @word AND active = '1'";
        command.Parameters.AddWithValue("@word","%" + word+ "%");

        using (var reader = command.ExecuteReader())
            yield return reader["Name"];
    }
}

Let's put some pieces together:

var mispelledWords = ReadAllWords(InputFile); // From configuration or cmdline
using (var conn = new SqlConnection("MyConnectionString")) // From configuration!!!
{
    var recordsWithMispelledNames = mispelledWords
        .SelectMany(w => FindRecordsByWord(conn, w).Select(n => $"Found {w} in {n}"));

    File.WriteAllLines(OutputFile, recordsWithMispelledNames);
}

Note that you may now refactor out some simple logic:

static IEnumerable<string> FindRecordsByWordList(IEnumerable<string> words)
{
    using (var conn = new SqlConnection("MyConnectionString")) // From configuration!!!
    {
        return mispelledWords
            .SelectMany(w => FindRecordsByWord(conn, w).Select(n => $"Found {w} in {n}"));
    }
}

Your Main() function will then be as simple as:

File.WriteAllLines(OutputFile,
    FindRecordsByWordList(ReadAllWords(InputFile)));

Few more notes:

There is space for more abstractions (input type, output type) but I'd keep code as simple as possible until you actually need it.
You should specify input/output file encoding (don't really rely on default settings and magic guesses, you'll be surprised).
There are debates around AddWithValue() usage, decide if you like it or not.
There is not any error checking (see also Know when to retry or fail when calling SQL Server from C#?)


Ramda - Forming a string based on array of word positions

This is a great question.

I found no easy Ramda functional way to solve this, but you could just use a forEach approach. I find it easier to read.

const {forEachObjIndexed, forEach} = R;

const song = {
  "99": [0, 7],
  "bottles": [1, 8],
  "of": [2, 9],
  "beer": [3, 10],
  "on": [4],
  "the": [5],
  "wall": [6]
};

let words = [];

forEachObjIndexed((indexes, word) => forEach(idx => words[idx] = word, indexes), song);

console.log(words.join(' '));


Find purpose-built libraries which are actively maintained. For example, anti-xss:

$harm_string = "Hello, i try to  your site";
$harmless_string = $antiXss->xss_clean($harm_string);

$harm_string = "";
$harmless_string = $antiXss->xss_clean($harm_string);

$harm_string = "CLICK";
$harmless_string = $antiXss->xss_clean($harm_string);

$harm_string = "CLICK";
$harmless_string = $antiXss->xss_clean($harm_string);

$harm_string = '
';
$harmless_string = $antiXss->xss_clean($harm_string);

$harm_string = '
';
$antiXss->removeEvilAttributes(array('style')); // allow style-attributes
$harmless_string = $antiXss->xss_clean($harm_string);

$harm_string = "\x3cscript src=http://www.example.com/malicious-code.js\x3e\x3c/script\x3e";
$harmless_string = $antiXss->xss_clean($harm_string);

$harm_string = "";

$antiXss->removeEvilHtmlTags(array('iframe'));

And a UTF8 library for data you are sending:

UTF8::json_enocde(array(1, '¥', 'ä')); // '[1,"\u00a5","\u00e4"]'

UTF8::html_encode('中文空白'); // '&#20013;&#25991;&#31354;&#30333;'

UTF8::utf8_decode(UTF8::utf8_encode('-ABC-中文空白-')); // '-ABC-中文空白-'

Implement Content Security Policy(CSP) on the web server as well. For example:

default-src 'self' https:; connect-src 'self' https: http:; font-src 'self' https:; frame-src *; img-src
 'self' https: http: data:; media-src 'self' https:; object-src 'self' https:; script-src 'sha256-q590j1fW
+aERb666H10h55ePy0sxRjUYCiOmJPftXDs=' 'self' https: 'unsafe-eval' 'unsafe-inline' http:; style-src 'self'
 https: 'unsafe-inline' http:; report-uri /tracking/csp?action=listing_frame&controller=embed&req_uuid
=cff37d5d-4c12-4c8b-b288-1ce0d103a25c&version=c7fc601874a5350c79eceb33ba6d4c09a433035f;

  default-src is set to 'self' which means it's setting all CSP rules to only allow src attribute from a same-origin. In short, you should only be able to load src from a relative endpoint.
  frame-src is set to wildcard (*) so we can load external src links in frames (iframe, frame, frameset). Because we're injecting HTML past the body element, we cannot use frame or frameset. The WAF has made it next to impossible to use iframe.
  script-src has 'self' supplied after the sha256 hashed script for unsafe-inline and unsafe-eval, but https does not have 'self' supplied meaning we can load external scripts for execution.

References

anti-xss repo: public function testXssClean()
PayloadsAllTheThings/XSS injection at master · swisskyrepo/PayloadsAllTheThings
UTF8 can be tricky – especially with PHP – DerEuroMark
voku/portable-utf8:  Portable UTF-8 library - performance optimized (unicode) string functions for php.
Airbnb – When Bypassing JSON Encoding, XSS Filter, WAF, CSP, and Auditor turns into Eight Vulnerabilities | Brett Buerhaus
How to protect PHP application from XSS attacks: CSP 3 nonce | PHP & Symfony Tips


There is no // try, catch, else in javascript.

Instead I would do:

var success = false, state = null;
try {
    response = UrlFetchApp.fetch(url);
    success = true;
    error = "Up";
    state = "Site up: ";
} catch(ex) {
    success = false;
    error = ex;
    state = "Site down: ";
}

insertData(status, url, row, error, response.getResponseCode(), state);


int v = arr.get(right);

I assume v holds the partitioned item. But I don't know what you mean by v, so you can make your variable names more clear. Java's convention is to use CamelCase for variable names, so you might want to do that.

   if (right - i == 0 || right - i == 1) return;

As I understand it, if right - i is either 0 or 1, the method will return. So why not just check if right - i is less than or equal 1?

    if (right - i <= 1) return;

It might be more readable to put your statements inside braces, I think:

        while(arr.get(++i) < v);
        while(v < arr.get(--j) && j != 0)

might be confusing: Perhaps it would be more understandable if you do this:

        while(v < arr.get(--j) && j != 0) {
            if(j == 1)break;
        }

Regarding that code, the condition j != 0 will never be false because the loop will stop when j becomes 1. I think you can eliminate the if statement like this:

        while(v < arr.get(--j) && j > 1);

Currently your method signature is:

public static void sort(List<Integer> arr, int left, int right)

If we want to sort all items, we might call it as:

sort(list, 0, list.size()-1);

It might be better to write an overloaded method for convenience, Like this:

public static void sort(List<Integer> arr) {
    sort(arr, 0, arr.size()-1);
}

Now if someone wants to sort all items in the list, they don't have to provide the beginning and end of the sort.


Uploading multiple files to server with PHP and JavaScript

The approach
In the beginning of this answer I would like to make a distinct note which is a bit off the actual code review.
You need to change your priorities in writing a code. For the moment you are focused  more on the SEO part, trying to provide PHP users with reference answers to common questions. That's a good goal per se, either for the users and for your own good, but it shouldn't overshadow the main purpose of the code - to perform a certain task. In short, you need more practice with using a code you share with other people. I would even say that your intent should be first to solve the actual problem you have at hand and then share your experience, not just decide to write a reference answer out of the blue.
I took a liberty to make this note because it makes the actual impact on the code you write, particularly in regard of the error handling.
Error handling
There are two kinds of errors, "business logic errors" that aren't actually errors but rather regular cases handled by the application, and "real" errors that occur unexpectedly and have to be fixed by a programmer.
Such errors like 'Extension not allowed' or 'File size exceeds limit' are not real errors. That's just business logic-related conditions, whose results have to be conveyed back to the user in order to let them to fix the issue on their side. But you are bluntly catching them and writing into error log where they hardly help anyone. I assume this logic is the direct consequence of your approach. Were you try to use your own code in a real life application, this flawed error handling would become immediately apparent.
So in order fo fix this issue first create a distinct kind of exception
class FileUploadUserException extends Exception {}

it will let you to catch only this particular kind of exception:
       } catch (FileUploadUserException $e) {
            $errors[] = $e->getMessage();
       }

whereas real errors have to be handled elsewhere, either in the dedicated handler or at least a global try catch around the entire application code as it makes no sense to write a repeated error_log call in every distinct chunk of code.
Another approach would be to avoid exceptions at all and use that $errors array you were intended to use at first.
Security
I would remove htm files from the list as it's a clear XSS attack on your own site.
I would also consider not using the original filenames as they would create a real mess with all sorts of weird characters and possible overwrite each other. The simplest solution would be just md5() from the file contents.
Usability
There is one simple trick that could greatly simplify the handling code. Instead of naming your field name as files[], make them enumerated, like files1, files2, ...
it will let you to handle them the most natural way using foreach, eliminating the need of count() call, a counter and even distinct variables to hold certain values from $_FILES array:
$extensions = ['jpg', 'jpeg', 'png', 'gif', 'html', 'txt', 'pdf', 'doc'];

foreach ($_FILES as $file) {
    $file_ext = strtolower(end(explode('.', $file['name'])));
    $destination = $path . $file['name'];
    ...
    move_uploaded_file($file['tmp_name'], $destination);
}


Iterator-like interface for extracting records from a blob

Some random comments:

The behaviour of flexible array members are defined in the C99 standard, but undefined in C90. Because of that reason, you might want to add a compiler switch guard against C90 compilers:

#if !defined __STDC_VERSION__ || (__STDC_VERSION__ < 199901L)
  #error Code must be compiled as C99 or later.
#endif

Why is the data binary data char and not uint8_t? char may or may not be signed, depending on the compiler.
Consider inlining get_next_obj(). Since you return the struct by value, even good C compilers will generate a lot of overhead code from that. If you can weed out at least the internal return-by-value, the algorithm will be a bit faster.
Any reason why the record objects can't hold a prev pointer? That is, why can't they be a double-linked list instead of a single linked one? And on the topic of linked lists, you may want to consider changing the type of the next pointer:

typedef struct record_ {
    uint32_t id;     // id
    char *key;       // pointer to key in the blob
    char *value;     // pointer to value in the blob
    record_ *next;   // pointer to the next record
    record_ *prev;   // pointer to the previous record
} record;

Or perhaps stuff all the record objects into a real linked list ADT.


If ActionScript supports enums use an enum instead of the many booleans. If not, use a string with one constant for every state. It's also better than the booleans. For example:

...
else if (state == FADE_INT_ASDF) {
   state = CODE_OF_NEXT_STATE;
   gameState = GameState.READY;
}
...

If the logic was more complicated it would be worth implementing the State pattern.

If the booleans were replaced to an enum/string constants you can create a new setTimer function which could remove some code duplication:

private function setTimer(int timeout, IntroState/String newState) : void {
    var timer : Timer = new Timer(timeout);
    timer.addEventListener(TimerEvent.TIMER, function() {
        timer.stop();
        state = newState;
    });
    timer.start();
}


You say "recursively resolve", but in fact resolve is not recursive. It returns Prop A is Prop B is ${prop_c} instead of Prop A is Prop B is Prop C, if you call it with Prop A is ${prop_b}. If you call it with prop_a, as advertised, it returns prop_a.
You allow nested ${} in you syntax. What is your semantics of it?
Do you have any test cases for this. The bug and Unclear semantics of nested parens for instance, strongly indicate you should have.
Since you access the super class through its public interface, namely the the singe call to the super.getProperty you could instead pass the properties as a parameter. It will improve usability. Then you can make the static, if you wish. Since the method does not refer to any instance members otherwise.
StringBuffer and Stack have built in synchronization, whose overhead you can avoid by using StringBuilder and ArrayList.

Here is the test code to save others some effort:

import java.util.Properties;
import java.util.Stack;

public class Main {
    public static String resolve(Properties props,  String s ) {
          StringBuffer sb = new StringBuffer( 256 );
          Stack<StringBuffer> stack = new Stack<StringBuffer>();
          int len = s.length();

          for( int i = 0; i < len; i++ ) {
            char c = s.charAt( i );

            switch( c ) {
              case '$': {
                if( i + 1 < len && s.charAt( i + 1 ) == '{' ) {
                  stack.push( sb );
                  sb = new StringBuffer( 256 );
                  i++;
                }
                break;
              }

              case '}': {
                if( stack.isEmpty() ) {
                  throw new IllegalArgumentException( "unexpected '}'" );
                }

                String name = sb.toString();

                sb = stack.pop();
                sb.append( props.get(name) );
                break;
              }

              default: {
                sb.append( c );
                break;
              }
            }
          }

          if( !stack.isEmpty() ) {
            throw new IllegalArgumentException( "missing '}'" );
          }

          return sb.toString();
        }

    public static void main(String[] args) {
        Properties props = new Properties();

        props.setProperty("prop_a", "Prop A is ${prop_b}");
        props.setProperty("prop_b", "Prop B is ${prop_c}");
        props.setProperty("prop_c", "Prop C.");

        System.out.println(resolve(props, "Prop A is ${prop_b}"));
        System.out.println(resolve(props, "prop_a"));
        System.out.println(resolve(props, "${prop_a}"));
        System.out.println(resolve(props, "${${prop_b}}"));
    }
}


Python is often described as a "batteries included" kind of language, and this is no exception.

There's a module just for IP address manipulation and another module to generate random numbers. Put together, they do exactly what you want, in a way that's slightly more readable (IMO).

For this example, I'll assume that the variable v contains either 4 or 6.

from random import getrandbits
from ipaddress import IPv4Address, IPv6Address

if v == 4:
    bits = getrandbits(32) # generates an integer with 32 random bits
    addr = IPv4Address(bits) # instances an IPv4Address object from those bits
    addr_str = str(addr) # get the IPv4Address object's string representation
elif v == 6:
    bits = getrandbits(128) # generates an integer with 128 random bits
    addr = IPv6Address(bits) # instances an IPv6Address object from those bits
    # .compressed contains the short version of the IPv6 address
    # str(addr) always returns the short address
    # .exploded is the opposite of this, always returning the full address with all-zero groups and so on
    addr_str = addr.compressed

print(addr_str)

Here, addr_str will hold a fully random IPv4 or IPv6 address.

You can even generate random addresses from a subnet like this:

from random import getrandbits
from ipaddress import IPv4Network, IPv4Address

# network containing all addresses from 10.0.0.0 to 10.0.0.255
subnet = IPv4Network("10.0.0.0/24")

# subnet.max_prefixlen contains 32 for IPv4 subnets and 128 for IPv6 subnets
# subnet.prefixlen is 24 in this case, so we'll generate only 8 random bits
bits = getrandbits(subnet.max_prefixlen - subnet.prefixlen)

# here, we combine the subnet and the random bits
# to get an IP address from the previously specified subnet
addr = IPv4Address(subnet.network_address + bits)
addr_str = str(addr)

print(addr_str)

Here, addr_str will always contain IP addresses like 10.0.0.184, 10.0.0.42 and so on. It works the same way with IPv6 addresses, except in that case you'd have to import IPv6Network and IPv6Address instead.


Reading text from the web and writing to a JSON file

saveListOfAllCitiesIntoJsonFile () {
    var filePath = './Data/AllCitiesAvailableOnWeb.json';

Now if I was a consumer of this API, the function name is very vague in a sense that I don't know where that file is or what the file is for. What is this JSON file you speak of? Why is it saving cities?

If you start to reason "read the source code", then that's the wrong way to write code. Better if you either make the function more flexible by letting the caller provide a path or make the name more meaningful in what it does. That way, the caller knows where the file is going to or what that file is for.

var CITY_COUNT = pageElements["CityCount"];
var AllCity = homePageElements['AllCity'];
var CityList = homePageElements['CityList'];

I'm saving cities, but what are pageElements and homePageElements? Where do they come from? How are they related to the function that's saving to the JSON? It's best if you break apart functions into small units of functionality. Functions that do too much are hard to test or even eyeball for flaws.

Aside from the comment given, where it advises to NOT construct JSON this way, you are also hitting the filesystem for every chunk of syntax. That's inefficient. Constructing JSON using the stringify function will allow you to create a string once. You can then write that string to the filesystem once. No chunks. No multiple writes.

I suggest you break this operation into two: One function that reads the data into a data structure, and another function that accepts the data structure, serializes it and writes to the file.

function getCitiesFromPage(pageElements, homePageElements){
  // traverse and collect cities from pageElements and homePageElements
  return cities;
}

function writeCitiesToFile(data, path){
  // serialize data and write to path
}

function saveCitiesToFile(){
  let cities = getCitiesFromPage(pageElements, homePageElements);
  writeCitiesToFile(cities, './Data/AllCitiesAvailableOnWeb.json');
}


Find the kth-to-last element of a singly linked list

1. Review

There is no docstring. What does kthToLastNode do? What does it return? A docstring would explain that you have to pass k=1 to get the last item, k=2 to get the second-to-last item, etc.
It would be more useful, I think, if kthToLastNode returned the \$k\$th-to-last node instead of printing the node's value and returning the length of the linked list.
If you pass a value for k that's out of range (for example, longer than the length of the linked list) then there should be some error handling. For example, you might raise an exception.
Using a global count means that kthToLastNode can only be called once: if you call it again count has the wrong value and the function prints nothing and returns the wrong result.

2. Alternative approaches

Instead of recursing, iterate! Here are two implementation ideas.

Iterate over the list twice, first to find its length, and then to find the \$k\$th-to-last node. It would be worth making a separate function to find the length: this will make the code clearer, and we might have other places where we need to find the length, so if we make a function we'll be able to reuse it.

def linked_list_length(node):
    "Return the length of the linked list starting at node."
    length = 0
    while node:
        length += 1
        node = node.next
    return length

def kth_to_last_node(node, k):
    """Return the kth-to-last node of the linked list starting at node.
    Pass k=1 for the last node, k=2 for the next-to-last node, and so
    on. Raise IndexError if k is out of range.

    """
    length = linked_list_length(node)
    if k < 1 or k > length:
        raise IndexError("index out of range")
    for _ in range(length - k):
        node = node.next
    return node

This uses \$O(1)\$ space but has to traverse the list twice.
Append the nodes one by one to a queue of length \$k\$, so that when we reach the end of the list, the first element of the queue will be the \$k\$th-to-last node. We can implement the queue using collections.deque.

from collections import deque

def kth_to_last_node(node, k):
    """Return the kth-to-last node of the linked list starting at node.
    Pass k=1 for the last node, k=2 for the next-to-last node, and so
    on. Raise IndexError if k is out of range.

    """
    queue = deque(maxlen=k)
    while node:
        queue.append(node)
        node = node.next
    if k < 1 or len(queue) != k:
        raise IndexError("index out of range")
    return queue[0]

This traverses the list once but uses \$O(k)\$ space.

3. General discussion

Recursion and iteration are very similar: anything you can do with one, you can do with the other. In some cases the code is simpler and clearer if you use recursion, in other cases if you use iteration, and sometimes it doesn't make much difference. So it's hard to give general advice: there's no real substitute for trying both and seeing which you like better! For example, here's a case where recursion was nicer.

In the case of singly linked lists, it's worth pointing out that we don't have much need for this data structure in Python, because the built-in list data type is nearly always better than a linked list. You can get the \$k\$th-to-last element of the list a by writing a[-k], and this takes \$O(1)\$ time and \$O(1)\$ space.

The cases in which we do want to use linked lists in Python are those in which we need to efficiently insert new elements into the middle of a list. See this answer for a rare example. But in these cases we probably don't need to find the \$k\$th-to-last element.