Here is my development series (in parentheses: approx fast ratio compared with the previous, tested using strings cca 100 characters in size, see the comparison table below):

Get-LevenshteinDistanceOrig  (= 1×, for comparison): the original function body (Copy&Paste);
Get-LevenshteinDistanceOrig+ (> 3×, still insufficient): removed all time-expensive  Write-Verbose output;
Get-LevenshteinDistanceTry1  (> 50×, a substantial improvement): time-expensive pipeline to Measure-Object replaced by [math]::Min(n,m) static method (see .NET system.math class). The following are only minor advancement steps:
Get-LevenshteinDistanceTry2  (~ 1×..2×): slight algorithm renovation:

instead calculating the cost ($cost variable): if compared characters are equal then computing and comparing values $cellAbove, $cellLeft and $cellUpperLeft is useless as we already know the necessary value;
added: if strings are equal the LD is known (zero) and we can stop;

Get-LevenshteinDistance      (~ 2×): PoSH array implementation: instead  of two-dimensional comparison matrix used a rectangular jagged array.

Comparison table: .\CR\164518test.ps1 | Format-Table -AutoSize

cmdlet                       similarity runtime (ms) lengths  LD
------                       ---------- ------------ -------  --
Get-LevenshteinDistanceOrig  equal       6829.1053   106 106   0
Get-LevenshteinDistanceOrig+ equal       2010.4538   106 106   0
Get-LevenshteinDistanceTry1  equal         35.8835   106 106   0
Get-LevenshteinDistanceTry2  equal           .1795   106 106   0
Get-LevenshteinDistance      equal           .1539   106 106   0
Get-LevenshteinDistanceOrig  stochastic  6556.4117   106 102  79
Get-LevenshteinDistanceOrig+ stochastic  1932.6051   106 102  79
Get-LevenshteinDistanceTry1  stochastic    33.9023   106 102  79
Get-LevenshteinDistanceTry2  stochastic    28.3165   106 102  79
Get-LevenshteinDistance      stochastic    13.4852   106 102  79
Get-LevenshteinDistanceOrig  similar     6640.5884   106 102   4
Get-LevenshteinDistanceOrig+ similar     2023.8179   106 102   4
Get-LevenshteinDistanceTry1  similar       31.5843   106 102   4
Get-LevenshteinDistanceTry2  similar       14.9307   106 102   4
Get-LevenshteinDistance      similar        8.4234   106 102   4
Get-LevenshteinDistanceOrig  different   6613.5267   106 102 106
Get-LevenshteinDistanceOrig+ different   1943.7630   106 102 106
Get-LevenshteinDistanceTry1  different     35.1824   106 102 106
Get-LevenshteinDistanceTry2  different     27.1371   106 102 106
Get-LevenshteinDistance      different     13.8924   106 102 106

Column explanation:

cmdlet       - function name
similarity   - in brief "like" similarity of input strings
runtime (ms) - TotalMilliseconds
lengths      - lengths of input strings, space delimited
LD           - the Levenshtein Distance of input strings

Comparison script 164518test.ps1:

Function TestLD {
    param ([string]$Similarity = '')

    $aux = 0
    Write-Progress -Activity "LD info ($Similarity strings)" `
         -CurrentOperation 'Start' -PercentComplete $aux
    $cmdletTails = 'Orig','Orig+','Try1','Try2',''
    foreach ( $cmdletTail in $cmdletTails ) {
        $cmdlet = "Get-LevenshteinDistance$cmdletTail"
        $scriptBlock = { $LevenshteinDistance = & $cmdlet `
                -CompareString $strC -DifferenceString $strD }
        $TimeSpan = Measure-Command -Expression $scriptBlock
        $aux += [int](100 / $cmdletTails.Count)
        Write-Progress -Activity "LD info ($Similarity strings)" `
             -CurrentOperation $cmdlet -PercentComplete $aux
        [PSCustomObject]@{
            'cmdlet'     = $cmdlet
            'similarity' = $Similarity
            'runtime (ms)'   = $($TimeSpan.TotalMilliseconds.
                               ToString('#####.###0',$cultureinfo).
                                   PadLeft(10))
            'lengths'    = "$($strC.Length) $($strD.Length)"
            'LD'         = $LevenshteinDistance
        }
    }
}

. D:\PShell\CR\164518.ps1                        # reload the functions
$cultureinfo = [cultureinfo]::InvariantCulture   # my one is different
$strC='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum placerat leo ut turpis viverra lacinia'
$strD=$strC
TestLD -Similarity 'equal'
$strD='Cras efficitur nec orci et posuere. Suspendisse potenti. Quisque blandit auctor purus id facilisis est'
TestLD -Similarity 'stochastic'
$strC='a' * $strC.Length
$strD='a' * $strD.Length
TestLD -Similarity 'similar'
$strD='x' * $strD.Length
TestLD -Similarity 'different'

The main script 164518.ps1 (functions are defined here in the reverse order):

function Get-LevenshteinDistance{
    param(
        [string]$CompareString,
        [string]$DifferenceString
    )

    # Collect the string lengths
    $compareStringLength    = $CompareString.Length
    $differenceStringLength = $DifferenceString.Length

    # If either of the strings are empty the LD is known and we can stop
    if($compareStringLength -eq 0){return $differenceStringLength}
    if($differenceStringLength -eq 0){return $compareStringLength}
    # If strings are equal the LD is known and we can stop
    if ($CompareString -ceq $DifferenceString) { return 0 }

    # Build the comparison matrix as a (rectangular) jagged array
  # $comparisonMatrix = New-Object 'object[]' ($differenceStringLength+1)
    $comparisonMatrix = [System.Array]::CreateInstance([System.Object], ($differenceStringLength+1))
    for($index=0; $index -le $differenceStringLength; $index++){
        # Create row
      # $comparisonMatrix[$index]=New-Object 'object[]'  ($compareStringLength+1)
        $comparisonMatrix[$index]=[System.Array]::CreateInstance([System.Object], ($compareStringLength+1))
        # Populate the first column
        $comparisonMatrix[$index][0]=$index
    }
    # Populate the first row
    for($index=0; $index -le $compareStringLength; $index++){
        $comparisonMatrix[0][$index]=$index
    }

    # Calculate the Levenshtein distance by working through each position in the matrix.
    # Working the columns
    for($columnIndex=1; $columnIndex -le $compareStringLength; $columnIndex++){
        # Cycle each character in the list
        $compareCharacter = $compareString[$columnIndex-1] # multiple use => to a variable

        # Working the rows
        for($rowIndex=1; $rowIndex -le $differenceStringLength; $rowIndex++){
            # Cycle each character in the list (a variable for the only use)
          # $differenceCharacter = $differenceString[$rowIndex-1] # the only use

            # Calculate the cost
          if($compareCharacter -ceq $differenceString[$rowIndex-1]){
            $comparisonMatrix[$rowIndex][$columnIndex] = $comparisonMatrix[($rowIndex -1)][($columnIndex -1)]
          } else {
          # $cost = 1           # unneeded variable for the only use
            # The cell immediately above plus 1
            $cellAbove = $comparisonMatrix[($rowIndex-1)][$columnIndex] + 1

            # The cell immediately to the left plus 1
            $cellLeft =  $comparisonMatrix[$rowIndex][($columnIndex-1)] + 1

          # # The cell diagonally above and to the left             plus the cost ↓
            $cellUpperLeft = $comparisonMatrix[($rowIndex-1)][($columnIndex-1)] + 1

            # Select minumum of the of the last 3 cells calculations and assign it to the current matrix position.
            $comparisonMatrix[$rowIndex][$columnIndex] = [math]::Min([math]::Min($cellAbove,$cellLeft),$cellUpperLeft)
          }
        }
    }
    # The cacluated LD will now be in the bottom right of the matrix.
    return $comparisonMatrix[$differenceStringLength][$compareStringLength]
}

function Get-LevenshteinDistanceTry2{
    param(
        [string]$CompareString,
        [string]$DifferenceString
    )

    # Collect the string lengths
    $compareStringLength    = $CompareString.Length
    $differenceStringLength = $DifferenceString.Length

    # If either of the strings are empty the LD is known and we can stop
    if($compareStringLength -eq 0){return $differenceStringLength}
    if($differenceStringLength -eq 0){return $compareStringLength}
    # If strings are equal the LD is known and we can stop
    if ($CompareString -ceq $DifferenceString) { return 0 }
    # Build the comparison matrix and populate the first column and first row.
    $comparisonMatrix = New-Object 'object[,]' ($differenceStringLength+1),($compareStringLength+1)
  # $comparisonMatrix = [System.Array]::CreateInstance([System.Object], ($differenceStringLength+1),($compareStringLength+1))
    # Populate the first row
    for($index=0; $index -le $compareStringLength; $index++){
        $comparisonMatrix[0,$index]=$index
    }
    # Populate the first column
    for($index=0; $index -le $differenceStringLength; $index++){
        $comparisonMatrix[$index,0]=$index
    }

    # Calculate the Levenshtein distance by working through each position in the matrix.
    # Working the columns
    for($columnIndex=1; $columnIndex -le $compareStringLength; $columnIndex++){
        # Cycle each character in the list
        $compareCharacter = $compareString[$columnIndex-1]

        # Working the rows
        for($rowIndex=1; $rowIndex -le $differenceStringLength; $rowIndex++){
            # Cycle each character in the list
            $differenceCharacter = $differenceString[$rowIndex-1]

            # Calculate the cost
          if($compareCharacter -ceq $differenceCharacter){
            $comparisonMatrix[$rowIndex,$columnIndex] = $comparisonMatrix[($rowIndex -1),($columnIndex -1)]
          } else {
            $cost = 1    # a variable for the only use? Useless!

            # The cell immediately above plus 1
            $cellAbove = $comparisonMatrix[($rowIndex-1), $columnIndex] + 1

            # The cell immediately to the left plus 1
            $cellLeft =  $comparisonMatrix[$rowIndex,($columnIndex-1)] + 1

            # The cell diagonally above and to the left plus the cost
            $cellUpperLeft = $comparisonMatrix[($rowIndex-1),($columnIndex-1)] + $cost

            # Select minumum of the of the last 3 cells calculations and assign it to the current matrix position.
          # $comparisonMatrix[$rowIndex,$columnIndex] = $cellAbove,$cellLeft,$cellUpperLeft | Measure-Object -Minimum | select -ExpandProperty Minimum
          # $comparisonMatrix[$rowIndex,$columnIndex] = ($cellAbove,$cellLeft,$cellUpperLeft | Measure-Object -Minimum).Minimum
            $comparisonMatrix[$rowIndex,$columnIndex] = [math]::Min([math]::Min($cellAbove,$cellLeft),$cellUpperLeft)
          }
        }
    }
    # The cacluated LD will now be in the bottom right of the matrix.
    return $comparisonMatrix[$differenceStringLength,$compareStringLength]
}

function Get-LevenshteinDistanceTry1{
    #[cmdletbinding()]
    param(
        [string]$CompareString,
        [string]$DifferenceString
    )

    # Collect the string lengths
    $compareStringLength = $CompareString.Length
    $differenceStringLength = $DifferenceString.Length
    ##Write-Verbose "Comparision String: '$CompareString' with length '$compareStringLength'"
    ##Write-Verbose "Difference String: '$DifferenceString' with length '$differenceStringLength'"

    # If either of the strings are empty the LD is known and we can stop
    if($compareStringLength -eq 0){return $differenceStringLength}
    if($differenceStringLength -eq 0){return $compareStringLength}

    # Build the comparison matrix and populate the first column and first row.
    $comparisonMatrix = New-Object 'object[,]'  ($differenceStringLength+1),($compareStringLength+1)

    # Populate the first row
    for($index=0; $index -le $compareStringLength; $index++){
        $comparisonMatrix[0,$index]=$index
    }

    # Populate the first column
    for($index=0; $index -le $differenceStringLength; $index++){
        $comparisonMatrix[$index,0]=$index
    }

    # Calculate the Levenshtein distance by working through each position in the matrix.
    # Working the columns
    for($columnIndex=1; $columnIndex -le $compareStringLength; $columnIndex++){
        # Cycle each character in the list
        $compareCharacter = $compareString[$columnIndex-1]

        # Working the rows
        for($rowIndex=1; $rowIndex -le $differenceStringLength; $rowIndex++){
            # Cycle each character in the list
            $differenceCharacter = $differenceString[$rowIndex-1]

            ##Write-Verbose "Matrix location: [$rowIndex, $columnIndex]"
            ##Write-Verbose "Compare character: $compareCharacter - Difference character: $differenceCharacter"
            # Calculate the cost
            $cost=if($compareCharacter -ceq $differenceCharacter){0}else{1}
            ##Write-Verbose "Cost: $cost"

            # The cell immediately above plus 1
            $cellAbove = $comparisonMatrix[($rowIndex-1), $columnIndex] + 1
            ##Write-Verbose "Cell Above: [$($rowIndex-1), $columnIndex] + 1 = $cellAbove"

            # The cell immediately to the left plus 1
            $cellLeft =  $comparisonMatrix[$rowIndex,($columnIndex-1)] + 1
            ##Write-Verbose "Cell Left: [$rowIndex,$($columnIndex-1)] + 1 = $cellLeft"

            # The cell diagonally above and to the left plus the cost
            $cellUpperLeft = $comparisonMatrix[($rowIndex-1),($columnIndex-1)] + $cost
            ##Write-Verbose "Cell Upper Left: [$($rowIndex-1),$($columnIndex-1)] + cost($cost) = $cellUpperLeft"

            # Select minumum of the of the last 3 cells calculations and assign it to the current matrix position.
          # $comparisonMatrix[$rowIndex,$columnIndex] = $cellAbove,$cellLeft,$cellUpperLeft | Measure-Object -Minimum | select -ExpandProperty Minimum
            $comparisonMatrix[$rowIndex,$columnIndex] = [math]::Min([math]::Min($cellAbove,$cellLeft),$cellUpperLeft)
        }
    }
    # The cacluated LD will now be in the bottom right of the matrix.
    return $comparisonMatrix[$differenceStringLength,$compareStringLength]
}

function Get-LevenshteinDistanceOrig+{
    [cmdletbinding()]
    param(
        [string]$CompareString,
        [string]$DifferenceString
    )

    # Collect the string lengths
    $compareStringLength = $CompareString.Length
    $differenceStringLength = $DifferenceString.Length
    ##Write-Verbose "Comparision String: '$CompareString' with length '$compareStringLength'"
    ##Write-Verbose "Difference String: '$DifferenceString' with length '$differenceStringLength'"

    # If either of the strings are empty the LD is known and we can stop
    if($compareStringLength -eq 0){return $differenceStringLength}
    if($differenceStringLength -eq 0){return $compareStringLength}

    # Build the comparison matrix and populate the first column and first row.
    $comparisonMatrix = New-Object 'object[,]'  ($differenceStringLength+1),($compareStringLength+1)

    # Populate the first row
    for($index=0; $index -le $compareStringLength; $index++){
        $comparisonMatrix[0,$index]=$index
    }

    # Populate the first column
    for($index=0; $index -le $differenceStringLength; $index++){
        $comparisonMatrix[$index,0]=$index
    }

    # Calculate the Levenshtein distance by working through each position in the matrix.
    # Working the columns
    for($columnIndex=1; $columnIndex -le $compareStringLength; $columnIndex++){
        # Cycle each character in the list
        $compareCharacter = $compareString[$columnIndex-1]

        # Working the rows
        for($rowIndex=1; $rowIndex -le $differenceStringLength; $rowIndex++){
            # Cycle each character in the list
            $differenceCharacter = $differenceString[$rowIndex-1]

            ##Write-Verbose "Matrix location: [$rowIndex, $columnIndex]"
            ##Write-Verbose "Compare character: $compareCharacter - Difference character: $differenceCharacter"
            # Calculate the cost
            $cost=if($compareCharacter -ceq $differenceCharacter){0}else{1}
            ##Write-Verbose "Cost: $cost"

            # The cell immediately above plus 1
            $cellAbove = $comparisonMatrix[($rowIndex-1), $columnIndex] + 1
            ##Write-Verbose "Cell Above: [$($rowIndex-1), $columnIndex] + 1 = $cellAbove"

            # The cell immediately to the left plus 1
            $cellLeft =  $comparisonMatrix[$rowIndex,($columnIndex-1)] + 1
            ##Write-Verbose "Cell Left: [$rowIndex,$($columnIndex-1)] + 1 = $cellLeft"

            # The cell diagonally above and to the left plus the cost
            $cellUpperLeft = $comparisonMatrix[($rowIndex-1),($columnIndex-1)] + $cost
            ##Write-Verbose "Cell Upper Left: [$($rowIndex-1),$($columnIndex-1)] + cost($cost) = $cellUpperLeft"

            # Select minumum of the of the last 3 cells calculations and assign it to the current matrix position.
            $comparisonMatrix[$rowIndex,$columnIndex] = $cellAbove,$cellLeft,$cellUpperLeft | Measure-Object -Minimum | select -ExpandProperty Minimum
        }
    }
    # The cacluated LD will now be in the bottom right of the matrix.
    return $comparisonMatrix[$differenceStringLength,$compareStringLength]
}

function Get-LevenshteinDistanceOrig{
    [cmdletbinding()]
    param(
        [string]$CompareString,
        [string]$DifferenceString
    )

    # Collect the string lengths
    $compareStringLength = $CompareString.Length
    $differenceStringLength = $DifferenceString.Length
    Write-Verbose "Comparision String: '$CompareString' with length '$compareStringLength'"
    Write-Verbose "Difference String: '$DifferenceString' with length '$differenceStringLength'"

    # If either of the strings are empty the LD is known and we can stop
    if($compareStringLength -eq 0){return $differenceStringLength}
    if($differenceStringLength -eq 0){return $compareStringLength}

    # Build the comparison matrix and populate the first column and first row.
    $comparisonMatrix = New-Object 'object[,]'  ($differenceStringLength+1),($compareStringLength+1)

    # Populate the first row
    for($index=0; $index -le $compareStringLength; $index++){
        $comparisonMatrix[0,$index]=$index
    }

    # Populate the first column
    for($index=0; $index -le $differenceStringLength; $index++){
        $comparisonMatrix[$index,0]=$index
    }

    # Calculate the Levenshtein distance by working through each position in the matrix.
    # Working the columns
    for($columnIndex=1; $columnIndex -le $compareStringLength; $columnIndex++){
        # Cycle each character in the list
        $compareCharacter = $compareString[$columnIndex-1]

        # Working the rows
        for($rowIndex=1; $rowIndex -le $differenceStringLength; $rowIndex++){
            # Cycle each character in the list
            $differenceCharacter = $differenceString[$rowIndex-1]

            Write-Verbose "Matrix location: [$rowIndex, $columnIndex]"
            Write-Verbose "Compare character: $compareCharacter - Difference character: $differenceCharacter"
            # Calculate the cost
            $cost=if($compareCharacter -ceq $differenceCharacter){0}else{1}
            Write-Verbose "Cost: $cost"

            # The cell immediately above plus 1
            $cellAbove = $comparisonMatrix[($rowIndex-1), $columnIndex] + 1
            Write-Verbose "Cell Above: [$($rowIndex-1), $columnIndex] + 1 = $cellAbove"

            # The cell immediately to the left plus 1
            $cellLeft =  $comparisonMatrix[$rowIndex,($columnIndex-1)] + 1
            Write-Verbose "Cell Left: [$rowIndex,$($columnIndex-1)] + 1 = $cellLeft"

            # The cell diagonally above and to the left plus the cost
            $cellUpperLeft = $comparisonMatrix[($rowIndex-1),($columnIndex-1)] + $cost
            Write-Verbose "Cell Upper Left: [$($rowIndex-1),$($columnIndex-1)] + cost($cost) = $cellUpperLeft"

            # Select minumum of the of the last 3 cells calculations and assign it to the current matrix position.
            $comparisonMatrix[$rowIndex,$columnIndex] = $cellAbove,$cellLeft,$cellUpperLeft | Measure-Object -Minimum | select -ExpandProperty Minimum
        }
    }
    # The cacluated LD will now be in the bottom right of the matrix.
    return $comparisonMatrix[$differenceStringLength,$compareStringLength]
}

Please note case sensitivity of the above functions. For case insensitive Levenshtein Distance:

permanently: change -ceq to -eq in their two occurrences, or
ad hoc, in a particular case: use .ToUpper() or .ToLower() functions, e.g. as

Get-LevenshteinDistance -CompareString $strC.ToUpper() -DifferenceString $strD.ToUpper()
# or
Get-LevenshteinDistance -CompareString $strC.ToLower() -DifferenceString $strD.ToLower()


I suggest splitting:

Converting binary to ascii
Concatenating

After defining binaryToNumber and add. the final code will look much simpler:

var result = chars.map(binaryToNumber).reduce(add)


I think that there must be something wrong with the way CodeChef runs Python, or with the way it reports the times. The time limit for the problem is 8 seconds, but your Python submissions are passing even though they take 55 seconds and so ought to be out of time even with the five times allowance given to Python programs.

On my laptop, if I create about 80 megabytes of input:

import random
n, k = 10**7, 17
f = open('cr93327.data', 'w')
f.write('{} {}\n', n, k)
for _ in range(n):
    f.write('{}\n'.format(random.randrange(0, 10**7)))

Then this C program runs in 3.3 seconds:

#include <stdio.h>

int main() {
    unsigned n, k, i, m, count = 0;
    scanf("%u %u", &n, &k);
    for (i = 0; i < n; i++) {
        scanf("%u", &m);
        count += (m % k == 0);
    }
    printf("%u\n", count);
    return 0;
}

And this Python 3 program runs in 6.1 seconds:

import sys

n, k = map(int, next(sys.stdin.buffer).split())
count = 0
for i in map(int, sys.stdin.buffer):
    if not i % k:
        count += 1
print(count)

So Python is about twice as slow as C, not ten times as slow.


Prevent a UITextField from being input with aphabetic characters

If you want to disallow letters as input, why do you also test the old string of the text field? And why do you test, if the old and the new string contain a dot? The very simple solution to forbid letters is to use the one liner

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.rangeOfCharacter(from: CharacterSet.letters) == nil
}

or

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.rangeOfCharacter(from: CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")) == nil
}

if you want to be more specific about the disallowed characters.


Raw memory management should be incredibly rare and a last resort.

Your best bet will be some kind of container that can manage the memory for you. Returning a pointer to an allocated chunk of memory has all kinds of problems (who owns it and thus should delete[] it? what if you forget to release it? what about exception safety? etc).

In your situation, std::vector is almost certainly the right choice. It has essentially the same performance as a raw array if it's used wisely, and it gives pleasant, safe value semantics to an otherwise dangerous dynamic allocation.

In addition to the standard containers, it can also be valuable to know about std::shared_ptr and std::unique_ptr1. They give ownership semantics to memory allocations and facilitate safe handling of dynamically allocated memory. More plainly, they allow for the automatic releasing (e.g. delete or delete[]ing) of a memory allocation when the smart pointer (or all of the smart pointers in the case of std::shared_ptr) goes out of scope scope.

1 If you cannot use C++11, there are also some Boost smart pointers that do not require C++11.


Not a Singleton

class Database extends Singleton
{
    public function __construct(){

    }
}

This is not a singleton.  Add the following code:

$bd7 = new Config();

You have a new Config object.

class Config extends Singleton {

    protected function __construct() {

    }

}

This is a singleton.  It will give an error if you try to create a Config object directly.  Or

class Database extends Singleton {

}

Is a singleton that gives an error if you create a Database object directly as it inherits its constructor from its parent.

Registry

You don't need to use inheritance to get this functionality.

    public static function getInstance(){
        $class = get_called_class();
        if(!isset(self::$instance[$class]) || !self::$instance[$class] instanceof $class){
            self::$instance[$class] = new static(); // create and instance of child class which extends Singleton super class
            echo "new ". $class . PHP_EOL; // remove this line after testing
            return  self::$instance[$class]; // remove this line after testing
        }
        echo "old ". $class . PHP_EOL; // remove this line after testing
        return static::$instance[$class];
    }

Change to

    public static function getInstance($class, $object = null) {
        if (!isset(self::$instance[$class]) && $object != null) {
            self::$instance[$class] = $object;
        }

        return static::$instance[$class];
    }

or just

    public static function getInstance($key) {
        return static::$instance[$key];
    }

with

    public static function setInstance($key, $object) {
        static::$instance[$key] = $object;
    }

And change

$bd1 = Database::getInstance(); // new

to

Registry::setInstance('database', new Database());
$bd1 = Registry::getInstance('database');

Now, it's possible that in a real application you would make more use of what inheritance gives you.  But in this toy application, you don't.

I changed the name from Singleton to Registry, as better fitting this pattern.

You lose the just-in-time instantiation of the original, but you gain control over how it is instantiated.  An advantage of this form is that you can also do things like

Registry::setInstance('database', new MockDatabase());

Your original form prevented this, exacerbating the Singleton pattern's problems with user testing.

Nitpicks

/**
 * @dosc allows only one instance for each extending class
 * @example use it for database connection, config setup...
 * Be aware, singleton pattern is consider to be an antipatern and becaouse of it build it is hard to debug.
 * In most cases you do not need to use singleton patern so make a longer moment to think about it befor you use it.
 */

Without the spelling errors:

/**
 * @dosc allows only one instance for each extending class
 * @example use it for database connection, config setup...
 * Be aware, the singleton pattern is consider to be an anti-pattern
 * because it can be hard to debug.
 * In most cases you do not need to use singleton pattern
 * so take a longer moment to think about it before you use it.
 */

I also changed the wording a bit and broke up two lines so that they don't cause scrolling (at least in my browser).


DotNetZip: Adding files to archive faster in web app

Don't use ref parameters. It's very rarely needed and it's of no use in your CreateZip method.
Save the ZipFile directly to the Response.OutputStream instead of a temporary MemoryStream. This will allow you to start streaming the file while you're creating it.


Babel code in React component to display tasks

This looks pretty good. I don't really have any big comments, since I found it pretty easy to read. Nits:

you could remove the wrapping div with the id orderedList... The ol tag serves the same purpose, plus it's not a very specific name. I think it probably makes more sense to add a class to the ol with a value like tasks.
Generally don't use the index as a key. React uses these to figure out what to redraw. If you have some sort of ID, use that; if not, you can probably just use the task title, or a title + index. You want this to be specific... if the key too specific the component will get redrawn too much (generally not a problem). If the key is to general, components will be "stale"... not redrawn with the proper values.

Look good!


Your code has a major issue. It's breaking a basic rule of inheritance. The "base" class (Connection) does not specify a constructor. That is to say, any constructors that a child class may contain should take either no, or only optional arguments. That's what the Liskov principle states anyway.

Your DatabaseConnection extends Connection (BTW: an abstract extending an abstract... that smells, if you ask me), but it defines a constructor with non-optional arguments. This contradicts, and breaks the inherited contract defined by Connection.
PHP historically, has been very forgiving when it came to conflicting signatures, especially in the constructors, but as the manual says:

  When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.

That ship has sailed. Now in case you're wondering why this is such a big deal, look at the code below:

function checkConnection(Connection $con)
{//type-hint ensures instance of Connection is passed
    //for some reason, create a copy:
    $class = get_class($con);//get actual class
    $newInstance = new $class();//<-- No arguments!!
}

Now this function has to be allowed to assume that no arguments need to be passed to a constructor, if there even is a constructor. Simply because this function is hinting at Connection  instances. Because of the type-hint, the function can only assume the methods/properties that are declared by the Connection class are available, and that the instance that it is being passed is an instance (an extension) of this contract. Connection doesn't declare a constructor, so its children can only create a public, optional constructor.

Fix this issue ASAP.
Apart from that, I'd really like to see where you're going with this, because this abstract class Connection + abstract class DatabaseConnection seems like an awful lot of abstraction for what will, essentially, be a service locator, or DI container.

A DI Container, or SL shouldn't even care what kind of dependencies/services/objects it is injecting and instantiating. So there's even less need of these abstractions you've written from that perspective.

I'm also having doubts concerning the terminate method. If a piece of code uses a mysqli connection, and needs the connection to be open for some reason (ie: a prepared statement that is pending, a huge result set is being fetched in chunks,...), having the connections managed at a central level might cause conflicts. I'd say that the only place where the container can close connections is when it is being destroyed: if the container is going out of scope, all that it has spawned is probably gone, too.

Update - A crude example of a container:

Say you have config files, that define DB connections, which could look like this;

connections:
    db:
        readConnection:
            class: mysqli
            host: 127.0.0.1
            database: db
            username: user
            password: pass
        writeConnection:
            class: PDO
            host: 8.8.8.8
            database: db
            username: user
            password: pass

Now, a container would parse this config, and allow you to write something like this:

$mysqli = $container->get('connections.db.readConnection');

This get method would then parse the slug, and interpret the configuration it finds, to end up returning:

$path = explode('.', $slug);
$section = $this->getFullConfig();
foreach ($path as $key)
    $section = $section->get($key);
$class = $section->get('class');
return new $class(
    $section->get('host'),
    $section->get('database'),
    $section->get('username'),
    $section->get('password')
);

Note that this is a grossly oversimplified, but you get the idea.


Create an associative array with values as an array from an another associative array

By iterating through array_keys($rows), you are not using the $results associative array effectively.  You should be able to just write this:

foreach ($results as $result) {
    $rows[$result['id']][] = $result['year'];
}

Also, there is no need to call array_push() if you are appending just one item.  You can just assign $rows[] = with no index to indicate that you want to append one element.


Query performance of this Select Where each Column is a Select

You could try to use a PIVOT statement in order to convert values of several rows into columns. I show it for Abbestellungen.EssenTyp here. You will have to combine it with the rest of your query.

SELECT RefKundeId, [0] AS Fruehstuck, [1] AS Vesper, [2] AS Abendbrot
FROM (SELECT RefKundeId, EssenTyp FROM Abbestellungen WHERE [date] = @Datum) a
PIVOT
(
    MAX (EssenTyp)
    FOR EssenTyp IN ([0], [1], [2])
) AS pvt;

I am not sure which value you want to return for the EssenTyp columns. Your query returns the EssenTyp id, but your example result set returns 1. So may be you want a count? Then you would have to replace MAX(EssenTyp) by SUM (1) or COUNT(EssenTyp). If you are storing a number of meals say in a column Anzahl (german 'number'), then write SUM(Anzahl). In any case you need an aggregate function for the pivot operation.

Will it be faster? I don't know. Make experiments. Instead of making two independent pivot queries for Abbestellungen and Bestellung, you could combine the two in a UNION query and pivot them together:

SELECT
    RefKundeId,
    [0] AS Fruehstuck, [1] AS Vesper, [2] AS Abendbrot, [10] AS Menu1, [11] AS Menu2
FROM (
    SELECT RefKundeId, EssenTyp AS nr, 1 AS value
    FROM Abbestellungen
    WHERE [date] = @Datum

    UNION ALL

    SELECT B.RefKundeId, D.SpaltenNr + 10 AS nr, D.Anzahl AS value
    FROM
        Bestellung B
        INNER JOIN BestellDetails D
            ON B.BestellId = D.RefBestellId
    WHERE D.Datum = @Datum
) A
PIVOT
(
    SUM (value)
    FOR nr IN ([0], [1], [2], [10], [11])
) AS pvt;


Checks user level and limit the data before saving it to mongoDB

According to www.lizard.ws the original's function cyclomatic complexity is 29 and for the second version is 22. Both numbers are usually considered high, and teams aim for much lower values (debatable what the good range is though and will see within this answer why).

In order to reduce it, one way is to encapsulate the if statements, among with removing the code duplication and separate the responsibilities.

The next calls seem duplicate, so let's reduce them first.

providerSchema.pre('save', function (next) {

     var valid = true;
    if (this.level === 4) {
        if (this.description.length >= 80 || this.certifications.length > 5) {
            valid = false;
        }
    } else if (this.level === 3) {
        if (this.description.length >= 50 || this.certifications.length > 3) {
            valid = false;
        }
    } else if (this.level === 2) {
        if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {
            valid = false;
        }
    } else if (this.level === 1) {
        if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
            valid = false;
        }
    } else {
        if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
            valid = false;
        }
    }

    if (valid) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }
});

With this first refactoring we didn't gain much in terms of lowering CC, in fact it increased to 30, because of the added if statement. However this can let us to split the validation responsibility from enabling the actual feature (as @Margon mentioned).

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (this.description.length >= 80 || this.certifications.length > 5) {
                return false;
            }
        } else if (this.level === 3) {
            if (this.description.length >= 50 || this.certifications.length > 3) {
                return false;
            }
        } else if (this.level === 2) {
            if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {
                return false;
            }
        } else if (this.level === 1) {
            if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
                return false;
            }
        } else {
            if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
                return false;
            }
        }
        return true;
    }
});

The isValidFeatureRequest function is at 29 and providerSchema is at 2. We still need to work on.

Checking again the code duplication, I noticed the last two blocks have the the same checks for other levels than 2, 3 or 4, so let's merge them.

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (this.description.length >= 80 || this.certifications.length > 5) {
                return false;
            }
        } else if (this.level === 3) {
            if (this.description.length >= 50 || this.certifications.length > 3) {
                return false;
            }
        } else if (this.level === 2) {
            if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {
                return false;
            }
        } else {
            if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
                return false;
            }
        }
        return true;
    }
});

We gained the following figures

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 20

The CC for isValidFeatureRequest is now at 20, which is an improvement.
The check for description and certifications also seems to vary, so I can encapsulate it into a function.

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (descriptionOrCertificationsOffLimits(80, 5)) {
                return false;
            }
        } else if (this.level === 3) {
            if (descriptionOrCertificationsOffLimits(40, 3)) {
                return false;
            }
        } else if (this.level === 2) {
            if (descriptionOrCertificationsOffLimits(30, 0) || this.teaser || this.social.length > 0) {
                return false;
            }
        } else {
            if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
                return false;
            }
        }
        return true;
    }

    function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {
        return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;
    }
});

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 17
descriptionOrCertificationsOffLimits   | 2

CC is now at 17, slightly better.

There is lot to check in the last branch, so let's extract it into his own function.

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (descriptionOrCertificationsOffLimits(80, 5)) {
                return false;
            }
        } else if (this.level === 3) {
            if (descriptionOrCertificationsOffLimits(40, 3)) {
                return false;
            }
        } else if (this.level === 2) {
            if (descriptionOrCertificationsOffLimits(30, 0) || this.teaser || this.social.length > 0) {
                return false;
            }
        } else if (hasAny()) {
            return false;
        }
        return true;
    }

    function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {
        return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;
    }

    function hasAny() {
        return this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart;
    }
});

Which results into

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 10
descriptionOrCertificationsOffLimits   | 2
hasAny                                 | 8

We have now 4 functions with manageable complexities.
The hasAny function seems to have a large CC, compared to what it does. What we can do here is to improve its readability, by displaying one condition per line. This is also the moment when I think we can't do anything about this function, and is the time not to look at an arbitrary CC limit in order to squize the code just to pass the analyzer.

 function hasAny() {
        return this.description ||
            this.certifications.length > 0 ||
            this.teaser ||
            this.social.length > 0 ||
            this.locationLat ||
            this.locationLong ||
            this.workingHourEnd ||
            this.workingHourStart;
    }

Let's extract more, to check if it has a teaser or social data

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (descriptionOrCertificationsOffLimits(80, 5)) {
                return false;
            }
        } else if (this.level === 3) {
            if (descriptionOrCertificationsOffLimits(40, 3)) {
                return false;
            }
        } else if (this.level === 2) {
            if (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial()) {
                return false;
            }
        } else if (hasAny()) {
            return false;
        }
        return true;
    }

    function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {
        return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;
    }

    function hasTeaserOrSocial() {
        return this.teaser || this.social.length > 0;
    }

    function hasAny() {
        return this.description ||
            this.certifications.length > 0 ||
            this.teaser ||
            this.social.length > 0 ||
            this.locationLat ||
            this.locationLong ||
            this.workingHourEnd ||
            this.workingHourStart;
    }
});

Which results into

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 9
descriptionOrCertificationsOffLimits   | 2
hasTeaserOrSocial                      | 2
hasAny                                 | 8

The if followed by an inner if can be combined into and and operation so we can have this

 function isValidFeatureRequest() {
        if (this.level === 4 && descriptionOrCertificationsOffLimits(80, 5)) {
            return false;
        } else if (this.level === 3 && descriptionOrCertificationsOffLimits(40, 3)) {
            return false;
        } else if (this.level === 2 && descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial()) {
            return false;
        } else if ((this.level === 1 || this.level === 0) && hasAny()) {
            return false;
        }
        return true;
    }

The CC doesn't change, but it enables me to extract validation for every level, so I gain smaller functions, with smaller complexity.
Edit to fix a bug here - This step introduced a bug, as @Roland Illig mentioned in the comments (the story of my life when I refactor even a simple if).
After fixing it the CC actually increased with 2, to 11, as I introduced two new checks and I also had to add a new function. end of edit

function isValidFeatureRequest() {
    if (isLevel4AndNotValid()) {
        return false;
    } else if (isLevel3AndNotValid()) {
        return false;
    } else if (isLevel2AndNotValid()) {
        return false;
    } else if (isBellowLevel2AndNotValid()) {
        return false;
    }
    return true;
}

function isLevel4AndNotValid() {
    return this.level === 4 && descriptionOrCertificationsOffLimits(80, 5);
}

function isLevel3AndNotValid() {
    return this.level === 3 && descriptionOrCertificationsOffLimits(40, 3);
}

function isLevel2AndNotValid() {
    return this.level === 2 && (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial());
}

function isBellowLevel2AndNotValid() {
    return (this.level === 1 || this.level === 0) && hasAny();
}

Which are

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 5
isLevel4AndNotValid                    | 2
isLevel3AndNotValid                    | 2
isLevel2AndNotValid                    | 3
isBellowLevel2AndNotValid              | 3
descriptionOrCertificationsOffLimits   | 2
hasTeaserOrSocial                      | 2
hasAny                                 | 8

The isValidFeatureRequest still looks odd, I can remove the else statements and I can convert the last call into a return statement, which decrease the complexity with one point.

function isValidFeatureRequest() {
    if (isLevel4AndNotValid()) {
        return false;
    }

    if (isLevel3AndNotValid()) {
        return false;
    }

    if (isLevel2AndNotValid()) {
        return false;
    }

    if (isBellowLevel2AndNotValid()) {
        return false;
    }

    return true;
}

My final attempt is this:

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (isLevel4AndNotValid()) {
            return false;
        }

        if (isLevel3AndNotValid()) {
            return false;
        }

        if (isLevel2AndNotValid()) {
            return false;
        }

        if (isBellowLevel2AndNotValid()) {
            return false;
        }

        return true;
    }

    function isLevel4AndNotValid() {
        return this.level === 4 && descriptionOrCertificationsOffLimits(80, 5);
    }

    function isLevel3AndNotValid() {
        return this.level === 3 && descriptionOrCertificationsOffLimits(40, 3);
    }

    function isLevel2AndNotValid() {
        this.level === 2 && (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial());
    }

    function isBellowLevel2AndNotValid() {
        return (this.level === 1 || this.level === 0) && hasAny();
    }

    function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {
        return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;
    }

    function hasTeaserOrSocial() {
        return this.teaser || this.social.length > 0;
    }

    function hasAny() {
        return this.description ||
            this.certifications.length > 0 ||
            this.teaser ||
            this.social.length > 0 ||
            this.locationLat ||
            this.locationLong ||
            this.workingHourEnd ||
            this.workingHourStart;
    }
});

With the following resuts:

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 5
isLevel4AndNotValid                    | 2
isLevel3AndNotValid                    | 2
isLevel2AndNotValid                    | 3
isBellowLvel2AndNotValid               | 3
descriptionOrCertificationsOffLimits   | 2
hasTeaserOrSocial                      | 2
hasAny                                 | 8


Modifying an image URL based on hash options

Overall, it's reasonably tight code. You've taken steps to reduce method size, which is good.

To answer your questions specifically:

I think an instance variable would be better, because then you can avoid the else clauses you mention in 2. Those methods can then be reduced to 1 or 2 lines.
see 1. :)
If you create an image or picture object, it provides a convenient place to memoize results. I'm not sure this is that important though, as it's probably not likely you'd need to generate more than one URL for a given image in a single request.


FizzBuzz Optimisation | Modulus vs Decrement Operator Performance

Looks good - you're using only simple integer addition and subtraction.
Except for the division hidden here:
    std::cout << i << '\n';

Note that division by a constant isn't necessarily as expensive as you think: it's always possible for an optimising compiler to implement it in terms of multiplication and bitwise operations.  And a test for being an exact multiple is often simpler (think of the well-known algorithms for testing divisibility by 9 or 11 in decimal).
If you really want to drive up performance, consider storing the integer value as a string (any kind), and implement the ++ operation character by character.
You may also be interested in High throughput Fizz Buzz over on the Programming Puzzles site.


I highly recommend Java Concurrency in Practice by Brian Goetz et al. This will give you a solid foundation for building multi-threaded Java applications.

The biggest problem with RingBuffer is that it is not thread-safe. You must synchronize all read and write operations to be certain to see the latest values for fields. This doesn't mean you have to lock the structure the entire time.

This is explained far better in the book than I can here. The short of it is that without synchronization via memory barriers, the JVM is free to cache values read in one thread and miss writes happening in another.

Thread A calls get and sees that the buffer is empty.
Thread B calls add which updates the pointer.
Thread A calls get again, but without a memory barrier the cached pointer value tells it that the queue is still empty.

You'll need to add synchronization to guard any access of the pointers and size. Sometimes you can merely add synchronized to the method, but this usually hurts performance. You want to shrink your synchronized blocks to the bare minimum; prefer using synchronized (<lock>) blocks over synchronized methods.

Here are some other suggestions unrelated to concurrency:

RingBuffer composes an ArrayList so it should not extend AbstractList itself. It shouldn't even implement the basic List interface nor RandomAccess because it doesn't truly support the get operation. It should implement Queue instead.
As written, get allows reading outside the buffer. Are you sure you want to support this? See (1) above.
You don't need a class to hold an integer pointer given that it is internal to RingBuffer. A simple int is sufficient.
The modulo operator % should handle negative values already (test this!) so wrap could be simplified.


A simple randomized brute-force works for this problem. From the analysis:

  We can try these solutions anyway, or we can rely on our occasional
  friend, randomness! We can pick a random starting cell, repeatedly
  choose valid moves uniformly at random from the space of all allowed
  moves from our current cell, and, if we run out of available moves,
  give up and start over. For any case except for the impossible ones
  mentioned above, this approach finds a solution very quickly.

Python code:

from itertools import product, repeat
from random import choice

def main():
    T = int(input())  # the number of test cases

    for case in range(1, T+1):
        R, C = map(int, input().split())  # the numbers of rows and columns

        if R < 2 or C < 2 or R + C < 7:
            print('Case #{}: IMPOSSIBLE'.format(case))
        else:
            print('Case #{}: POSSIBLE'.format(case))

            while True:
                grid = [[False]*C for _ in repeat(None, R)]
                moves = []
                last = None
                for _ in repeat(None, R*C):
                    candidates = ([(r, c) for r, c in product(range(R), range(C)) if not grid[r][c]
                                   and r != last[0] and c != last[1] and last[0] - last[1] != r - c
                                   and last[0] + last[1] != r + c]
                                  if last is not None else list(product(range(R), range(C))))
                    if not candidates:
                        break
                    cell = choice(candidates)
                    moves.append(cell)
                    grid[cell[0]][cell[1]] = True
                    last = cell
                else:
                    for r, c in moves:
                        print(r+1, c+1)
                    break

main()


Validate particular id's depending on what process type is coming

I was not able to tell what your isValid method did upon first reading.  I therefore renamed the method to be more explicit about what the method is validating and changed the parameter order to reflect the new name.

I abstracted out the Logging and ID extraction into their own methods to make the code more readable and follow the single responsibility principle.  Now, each method works on the same level of abstraction and has a defined role.

I abstracted out the actual record validation checks ( i.e. isRecordValidForABCOrDEFProcessType ) to encapsulate the checking logic and also make the checks readable.  The longer method names make the code self documenting.

Finally, I gave the boolean expressions names as the expressions are the most vital logic of the record validation.  The logic will also be reread often, so you want the logic to be as clear as possible.

  public static boolean isRecordValidForProcessType( Record record, ProcessType processType ) {
    boolean isProcessTypeABCOrDEF = processType == ProcessType.ABC || processType == ProcessType.DEF;
    boolean isRecordValid = isProcessTypeABCOrDEF
      ? isRecordValidForABCOrDEFProcessType( record )
      : isRecordValidForNonABCOrDEFProcessType( record );

    if( isRecordValid == false )
        logInvalidRecordErrorForProcessType( record, processType );

    return isRecordValid;
  }

  private static boolean isRecordValidForABCOrDEFProcessType(Record record){
    String deviceId = getDeviceIdFromRecord(record);
    String clientId = getClientIdFromRecord(record);
    boolean doesRecordHaveValidIds = ( Strings.isNullOrEmpty(clientId) || Strings.isNullOrEmpty(deviceId) ) == false;
    return doesRecordHaveValidIds;
  }

  private static boolean isRecordValidForNonABCOrDEFProcessType(Record record) {
    String deviceId = getDeviceIdFromRecord(record);
    String clientId = getClientIdFromRecord(record);
    boolean doesRecordHaveValidIds = ( Strings.isNullOrEmpty(clientId) && Strings.isNullOrEmpty(deviceId) ) == false;
    return doesRecordHaveValidIds;
  }

  private static String getDeviceIdFromRecord(Record record) {
    return DataUtils.extract(record, "deviceId");
  }

  private static String getClientIdFromRecord(Record record) {
    return DataUtils.extract(record,"clientid");
  }

  private static void logInvalidRecordErrorForProcessType(Record record, Process processType){
    LogMetric.getInstance().increment(processType.name(), Metric.ID);
      logger.logError("invalid clientId and deviceId provided. ProcessType= ", processType,
                      ", Record= ", record);
  }


Changing the type of an object inside a method?

It stead of having a static method the basically does what polymorphism could do for you use polymorphism.

public class Person
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }

    public virtual void InitializeFromDictionary(Dictionary<string, string> row)
    {
        FirstName = row["FirstName"];
        LastName = row["LastName"];
    }
}

public class Patient : Person
{
    public string PatientID { get; private set; }
    public override void InitializeFromDictionary(Dictionary<string, string> row)
    {
       base.InitializeFromDictionary(row)
       PatientID = row["PatientID"];
    }
}

and then where ever you call

BuildUpPersonOrPatient(p,row);

do this instead

p.InitialieFromDictionary(row);

I've added an access modifier to the setters because unless you have a reason to be able to change those fields from outside the object you should encapsulate the possibility of chaning the state of an object. (It's surprising how seldom you have a modeling reason for that and not just a "for conviniece" reason)


Is this Java small pubsub memory implementation correct and effective?

Assuming requireNonNull(...) is java.util.Objects.requireNonNull(...) which throws an exception if null, then there is no need to have a separate local variable for the return value.
Assuming ofNullable(...) is java.util.Optional.ofNullable(...), then I would recommend removing the usage here because the code can be simplified:
// ofNullable(...).ifPresent(l -> ...);
// Simplified:
MyClass result = ...
if (result != null) {
    ...
}

It looks like your locking in MessageListener will cause a deadlock:

MemoryDataBus.subscribe(...) calls loopUntilShutdown which synchronizes on message
MemoryDataBus.publish(...) calls accept which has to wait because lock on message is still held, preventing it from updating message

Edit: No deadlock occurs because Object.wait() is used which releases ownership of the monitor (here field message).


Your direct definition of square-tree is correct.

Your definition using map calls square-tree; to make it properly recursive, call map-square-tree instead.  Further, you may recurse on the subtree itself.  This will make your code succinct.

(define (map-square-tree tree)
  (map (lambda (subtree)
         ((if (pair? subtree) map-square-tree square) subtree))
       tree))


Find k pairs with smallest sums in Python

There's no need for the special case not k, because that is already handled by the while k in the main loop.
In the initial loop over nums1 the expression nums2[0] gets computed twice. This could be avoided by storing the result in a local variable:

value2 = nums2[0]
heappush(min_heap, (value + value2, (value, value2), 0))

In the main loop there are some complicated expressions, culminating in:

heappush(min_heap, (curr_pair[1][0]+nums2[nums2_idx+1], (curr_pair[1][0],
    nums2[nums2_idx+1]), nums2_idx+1))

which I found hard to understand. Complex expressions can be made clearer by giving names to the subexpressions. In particular, we can use tuple assignment to give names to all the elements of the tuple:

_, pair, j = heappop(min_heap)
value1, _ = pair

The reason for writing the tuple assignment value1, _ = pair instead of the lookup value1 = pair[0] is that the tuple assignment shows the reader that the pair has exactly two elements. (And if it doesn't then Python will raise "ValueError: not enough values to unpack" or "ValueError: too many values to unpack", so we get some checking too).
Now the heappush call looks like this:

heappush(min_heap, (value1 + nums2[j + 1], (value1, nums2[j + 1]), j + 1)

Here the expression nums2[j + 1] gets computed twice. This could be avoided by using a local variable:

value2 = nums2[j + 1]
heappush(min_heap, (value1 + value2, (value1, value2), j + 1)

Now, it ought to strike you that there is a strong similarity between the revised code in §1 and §4 above. The duplication could be avoided by defining a local function, like this:

solution = []
heap = []

def add(value1, j):
    # Add the pair (value1, nums2[j]) to the heap if possible.
    if j < len(nums2):
        value2 = nums2[j]
        heappush(heap, (value1 + value2, (value1, value2), j))

for value1 in nums1:
    add(value1, 0)

while k and heap:
    k -= 1
    _, pair, j = curr_pair = heappop(heap)
    solution.append(pair)
    value1, _ = pair
    add(value1, j + 1)

return solution

Note that in this version of the code there is no longer any need for the special cases not num1 and not nums2. If nums1 is empty, then there will be no iterations for for value1 in nums1. If nums2 is empty, then j < len(nums2) will always be false, and so nothing will be added to the heap. Either way, there will be no iterations of the main loop and so the solution will be empty as required.
The revised code in §5 above always takes at least as many steps as there are elements in nums1. But this is wasteful in many cases. Consider something like:

kSmallestPairs(list(range(1000000)), [1, 2, 3], 1)

Since k=1, then result should be the single pair [(0, 1)]. But the initialization loop runs over all the million elements of nums1.

This could be avoided by initializing the heap with the single pair (nums1[0], nums2[0]) since we know that this is the pair with the smallest sum. And then when we pop a pair (nums1[i], nums2[j]) from the heap, we have to add two new pairs to the heap: that is, (nums1[i + 1], nums2[j]) and (nums1[i], nums2[j + 1]), as either of these pairs might be next in order after the pair we just processed.

However, we have to be careful to add each pair just once — after processing (nums1[1], nums2[0]) and (nums1[0], nums2[1]) we must not add the pair (nums1[1], nums2[1]) twice. This can be avoided by keeping a set of all the pairs we have added to the heap.

solution = []
heap = []     # Min-heap of (nums1[i] + nums2[j], i, j)
added = set() # Set of indexes (i, j) that have been added to heap.

def add(i, j):
    # Add (nums1[i] + nums2[j], i, j) to the heap if possible.
    if i < len(nums1) and j < len(nums2) and (i, j) not in added:
        added.add((i, j))
        heappush(heap, (nums1[i] + nums2[j], i, j))

add(0, 0)
while k and heap:
    k -= 1
    _, i, j = heappop(heap)
    solution.append((nums1[i], nums2[j]))
    add(i + 1, j)
    add(i, j + 1)
return solution


Main:

import java.util.Scanner;

class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        Student[] students = StudentRoll.gatherStudents(scanner);
        StudentRoll.printStudents(students);

    }
}

Student:

class Student {

    private int rollNumber;
    private String name;

    Student(int rollNumber, String name) {
        this.rollNumber = rollNumber;
        this.name = name;
    }

    int getRollNumber() {
        return rollNumber;
    }
    void setRollNumber(int rollNumber) {
        this.rollNumber = rollNumber;
    }

    String getName() {
        return name;
    }
    void setName(String name) {
        this.name = name;
    }
}

StudentRoll:

class StudentRoll {

    static Student[] gatherStudents(Scanner scanner){

        System.out.print("Number of students? ");
        int numberOfStudents = scanner.nextInt();

        System.out.println("Enter those " + numberOfStudents + " students one by one");
        Student[] students = new Student[numberOfStudents];

        for (int index = 0; index < numberOfStudents; index++) {
            System.out.println("Enter details for the next student no. ");
            System.out.print("Enter Name: ");
            String studentName = scanner.next();
            System.out.print("Enter Roll Number: ");
            int rollNumber = scanner.nextInt();
            students[index] = new Student(rollNumber, studentName);
            System.out.println("\n");
        }
        return students;
    }

    static void printStudents(Student[] students){
        int i = 1;
        for (Student x : students) {
            System.out.println("Student Number : " + i);
            System.out.println("Name -> " + x.getName());
            System.out.println("Roll Number -> " + x.getRollNumber() + "\n");
            i++;
        }
    }
}

I can't post many notes right now, but will as soon as I can. Think the main thing here is that your code isn't very object-oriented, but Java is an object-oriented language. It's also generally a good idea to name variables something other than num, so that when you're working on a method that has 5 different int variables, you aren't tempted to call them num1 , num2, etc., but what they actually represent. I'm also not a big fan of using a for-in when you reference an index, but it didn't seem like the worst thing in the world so I left it in there.


It looks like you may want to unset the 'item id' entry in your post array before you do the processing:

unset($_POST['item id']);

Then you can use foreach to loop over the key (idx) and value (operation).

foreach ($_POST as $idx => $operation)
{
    echo $idx . ' ' . $operation . '</br>';
    // perform operation.
}

The array_keys function was unnecessary because foreach can be used with associative arrays handling both their keys and values.


Use standard array notation
When you are accessing array elements, the idiomatic way in C is to write foo[bar] instead of *(foo + bar). So instead of:
int next_number = *((i * rows + arr) + col);

Write:
int next_number = arr[i * rows + col];

It is both shorted, and now it is clear what part the array pointer is and what part the index is.
Avoid unnecessary memory allocations
It's perfectly possible in C to return a struct by value. This avoids having to call malloc() and free(), and you no longer have to worry about its memory leaking, nor have to check whether malloc() succeeded. You do it like so:
max_vector find_col_peak(int *arr, int rows, int col) {
    max_vector vector;

    // set max to the first item of the column
    vector.col_index = 0;
    vector.index_value = *(col + arr);

    ...

    return vector;
}

About recursion
With the above you don't have to worry about freeing memory for vector anymore. However, recursive calls themselves could have some memory overhead, since each call needs some amount of space on the stack. With this algorithm, you only need log2(cols) recursion levels, so that won't be an issue even for huge inputs. Also, the compiler can turn these recursive calls into tail calls.


Takes json input and builds dynamic json output based on values in input: Looking for a better way to accomplish this

There are a few points in the existing code that I think could be improved.
Confusing function name write_new_json
Naming is important. Good names make your code more readable, and easier to understand. Bad names make it less readable. Names are bad when they don't describe what the thing is/does, or conversely, if they seem to describe something that the thing isn't/doesn't do.
Usually, the verbs "read" and "write" in programming refer to fetching data from, and sending data to, some external/system resource. Especially a file. So the name write_new_json() sounds like you're writing some JSON to a file. But that's not what the function is doing at all. It's actually transforming some JSON into some other kind of JSON. Therefore write_new_json() is a misleading name.
I would pick a new name that avoids write and probably even avoids json; describing the input and output formats of a function as "JSON" does nothing to capture the purpose of the function. How about build_clock_punches? build_time_logs?
Confusing variable name i
    for i in data:

Another naming nitpick. In most programming languages, it is conventional to name your loop counter variable i. In Python, this would be something like for i in range(0, 1000):.1 But in your case, i is not a loop counter; it is not even a number. Therefore the name is confusing. Try using a more descriptive name, e.g. for clock_punch in data: or for clock_event in data:.
Unnecessary use of in operator
        if i['clock_type'] in [3]:

You're using in because [3] is a list, but there doesn't seem to be any reason that [3] needs to be a list. You can just compare the value directly using the equality operator, e.g. if clock_event['clock_type'] == 3:.
Unnecessary variable break_count
As far as I can tell, you only use break_count to keep track of the length of request["break"]. Persistently tracking the length of a list in a separate variable is a bad idea: it is unnecessary, and it opens you up to bugs. Suppose you go in later and add a new line of code that changes the length of request["break"], but forget to add that second line of code that updates break_count? Or vice versa?
To find the length of a list directly, use len().
        if clock_event['clock_type'] == 3:
            last_break_index = len(request["break"]) - 1
            request["break"][last_break_index].update({"end": clock_event["end"]})

But wait! There's an even better approach here. Python offers a handy syntax for getting the last item in a list: my_list[-1].
        if clock_event['clock_type'] == 3:
            request["break"][-1].update({"end": clock_event["end"]})

And for the if break_count == 0: line, it is better to check for the non-existence of request["break"] directly.
        if clock_event['clock_type'] == 4:
            if "break" not in request:
                request.update({"break": []})

Too trusting
Your program assumes the input data will always be well-formed. What happens if it's not? Suppose the system that produces your input goes haywire, and you receive a break-start, and then two break-ends? Or receive a break-end without receiving any break-starts first? Or data with a mix of two or more names?2 Depending on the nature of the nonsense input, your program would either crash entirely, or produce a nonsense output of its own.
What your program should do in these cases is detect that something is wrong, and then throw some kind of exception that explains what the problem was. Unfortunately I don't have time to elaborate on every possible case you might encounter, so I'll have to leave that as an exercise for you.
Of course, if this is a school assignment or other non-real-world project where you have a guarantee that the data will be well-formed, you may not want to go through all the extra trouble. But it's something you should keep in mind for future projects.

Thoughts on using a data class
You mentioned wanting to use a data class to ingest the input data. If all you are planning to do is replace all the dicts in the list data with equivalent data class objects, and then run those objects through the same logic you have now...then you don't gain that much. You do get the type annotations, and there's nothing wrong with having those, but it's not a huge benefit.

1Technically, Python doesn't even have "loop counters" like some other languages do. All Python for-loops are foreach loops rather than "traditional" for-loops. But it's close enough that the conventions around i still apply.
2Actually, it seems perfectly reasonable for the upstream system to send you data for two or more names at once. You may want to enhance your code to support that (or not, I don't know your circumstances).


Report a status based on a list of results

Something like this maybe?

  @tailrec
  def trf(
    results: List[CreateResult.Result],
    conf: Option[CreateAllResult.Conflict] = None,
    nf:   Option[CreateAllResult.NotFound] = None,
    f:    Option[CreateAllResult.Failed] = None,
    defs: List[ChecklistRuleDefinition] = Nil
  ): List[CreateAllResult.Result] = results.map {
    case r: CreateResult.Conflict :: tail if conf.isEmpty =>
         trf(tail, Some(CreateAllResult.Conflict(r)), nt, f, Nil)
    case r: CreateResult.NotFound :: tail if nf.isEmpty  =>
         trf(tail, conf, Some(CreateAllResult.NotFound(r)), f, Nil)
    case r: CreateResult.Failed  if f.isEmpty =>
         trf(tail, conf, nf, Some(CreateAllResult.Failed(r)), Nil)
    case Ok(defn) :: tail if conf ++ nf ++ f isEmpty =>
         trf(tail, None, None, None, dfn :: defs)
    case _ if defs.isEmpty => conf ++ nf ++ f
    case _ =>  CreateAllResult.Ok(defs.reverse)
  }

Oh, wait you are only returning the first failure, are you? I didn't realize that at first, thought you wanted the first of each type.
Well, that makes it kinda simpler ...
How about this:

object Failure {
   def unapply(res: Result) = res match {
    case r: CreateResult.Conflict  => Some(CreateAllResult.Conflict(r))
    case r: CreateResult.NotFound  => Some(CreateAllResult.NotFound(r))
    case r: CreateResult.Failed => Some(CreateAllResult.Failed(r))
   }
}

def trf(results: List[CreateResult.Result]) = results
  .collectFirst { case Failure(r) => r }
  .getOrElse(CreateAllResult.Ok(
     results.collect { case r: CreateResult.Ok => r.definition }
   ))


My take on the algorithmic crush problem from HackerRank

The code is generally clean, however, maintaining the same algorithm will probably result in a timeout for this problem. Your current complexity is \$ O(N\cdot M) \$ which could be up to \$ 10^7 \times 10^5 \$ according to the problem statement.

A similar problem to this is the maximum interval overlap problem, discussed here. The problem is given the guest arrival and departure times in a party, find the interval with the maximum guests. It should be a good exercise to apply the same idea to this problem.


VB.net SQL match against Excel data to datagridview

You are repeatedly opening the DB connection in a loop:
For index As Integer = 0 To v.dgv.RowCount - 1
    Using conn As New SqlConnection(myconnection)
        Dim commandText As String = "select productnmbr,descr from database where productnmbr = @prodnmbr"
        Using command As SqlCommand = New SqlCommand(commandText, conn)
            conn.Open()
            With command.Parameters
                .AddWithValue("@prodnmbr", v.dgv.Rows(index).Cells(0).Value.ToString)
            End With
            ...
        End Using
    End Using
Next

There is overhead involved when opening a connection. You could just open it once,  leave it open, do your stuff, then dispose of it:
Using conn As New SqlConnection(myconnection)
    For index As Integer = 0 To v.dgv.RowCount - 1
        ' do something
    Next
End Using

Just moving code a bit should improve performance.
Something else: no need to read values from the DGV. This could even freeze your UI. Read the rows from the dataset instead, that is the one table it contains (match).
I see that you are also adding rows to the DGV but the better way would be to feed the underlying source, that is your datatable, possibly a bindingsource. Then let the DGV refresh itself.
I am not familiar with your SQL table but if the product table is not too large, I might be tempted to load it to a second datatable, then compare both datatable with LINQ for example (you will find code samples on Stack Overflow). The benefit is that all your data will be preloaded to memory and comparison should be quite fast if you're not doing it row by row. It depends on how much data there is.
Or do it differently: load your Excel file to a temporary table in your SQL server. Then compare the tables by doing a join, a stored procedure if you like.


List comprehensions

Whenever you see a list initialization to [],
later filled in by .append(...) calls in a loop,
consider rewriting with a list comprehension.
For example:

matrix = []
for row in range(M):
    matrix.append(list(map(int, input().split())))

Can be rewritten on a single line:

matrix = [list(map(int, input().split())) for _ in range(M)]

Note that I renamed row to _,
this is a common convention when then loop variable is unused.

Another example of that is this list comprehension later in your code:

ring = [[] for layer in range(layers)]

Like earlier, rename layer to _:

ring = [[] for _ in range(layers)]

Integer division with //

Instead of this:

layers = int(min(N, M)/2)

Another, a more natural way to achieve the same effect using integer division with //:

layers = min(N, M) // 2

Coding style

The body of this for-loop is overindented:

# rotate each layer
for level in range(layers):
        r = rotations % len(ring[level])
        ring[level] = ring[level][r:] + ring[level][:r]

Possibly it's a result of the copy-pasting?
Either way,
a PEP8 checker would catch this.
It's recommended to use four spaces for an indent level,
and to use only spaces and never tabs for indenting code.

Reducing duplicated code

The current implementation works like this:

put each layer into ring
rotate the values in each layer in ring
overwrite the layers in the matrix from ring

Step 1 and 3 have very similar code, as you yourself noticed.
One way to reduce that is to implement shifting in-place,
without using the additional storage ring,
by doing something like this (\$k\$ is the number of rotations):

save the first \$k\$ items in a list
overwrite the \$i\$-th values by the \$(i+k)\$-th values. The last \$k\$ values will come from the values we saved in the previous step.

Easier said than done? Yes. Calculating the \$(i + k)\$-th position will be tricky.

I'd say your original implementation with the similar lines is fine:
it's easy to understand, and it passed the tests anyway.


Counts "islands" of 1s in sea of 0s (2d array matrix)

The code seems correct. The only missing part is

  You may assume all four edges of the grid are all surrounded by water.

which means that numIslands may iterate

    for (int i = 1; i < grid.length - 1; i++) {
        for (int j = 1; j < grid[i].length - 1; j++) {

and do not bother destroyIsland with validating the surroundings.


Refactor multiple if condition in JavaScript/TypeScript

Indentation Your current indentation is a bit confusing - the function's opening block's { line is not balanced with the closing block } line. At a glance, it looks like the function is 4 lines long, and like there's an extra } at the very bottom of the snippet. Consider using an IDE which can prettily format code automatically, such as VSCode - it makes things much easier when you and anyone who reads the code can identify each block and its nesting level at a glance.
Spelling Spelling matters in programming - misspellings are a very common cause of bugs. Dashbaord should probably be renamed to Dashboard, rather than using the misspelled word everywhere (which would probably eventually cause a headache or few, especially if other developers have to go over the code).
Prefer const - don't use let unless you must reassign the variable name. Using const makes code more readable when you know there's no chance of the variable name being reassigned. Here, rather than reassigning the allData variable name, you may refactor to const by calling prepareChartData immediately, rather than reassign allData. For example:
if (this.selectedAttribute === Dashbaord.All && this.selectedComponent !== Dashbaord.All) {
    const groupedByComponent = this.pendingActionDataSet.groupByArray(x => x.component);
    allData = groupedByComponent[this.selectedComponent];
}

can turn into
if (this.selectedAttribute === Dashbaord.All && this.selectedComponent !== Dashbaord.All) {
    const groupedByComponent = this.pendingActionDataSet.groupByArray(x => x.component);
    this.prepareChartData(groupedByComponent[this.selectedComponent]);
}

If you don't like repeating this.prepareChartData everywhere, you could make it a bit shorter with:
// replace Data with the appropriate type below:
const prepareData = (data: Data) => {
  this.prepareChartData(data);
};

Comparisons As for your if statements, you can save the two comparisons being done in variables first, then use those variables:
const { All } = Dashboard; // note spelling
const attribIsAll = this.selectedAttribute === All;
const selectedIsAll = this.selectedComponent === All;
if (attribIsAll && selectedIsAll) {
  // ...
} else if (attribIsAll && !selectedIsAll) {
  // ...

Another option would be to group one of the truthy comparisons together, like so:
if (attribIsAll) {
  if (selectedIsAll) {
    this.prepareIntialData();
  } else {
    const groupedByComponent = this.pendingActionDataSet.groupByArray(x => x.component);
    prepareData(groupedByComponent[this.selectedComponent]);
  }
  return; // return early; avoid dense indentation later
}
if (selectedIsAll) {
  // ...
} else {
  // ...
}

Array test You have
if (!this.componentOptions.filter(x => x.value === this.selectedComponent).length) {

In general, if you want to check that no elements in an array satisfy a condition, it would be more semantically appropriate to use .some or .every:
const componentOptionSelected = this.componentOptions.some(
  option => option.value === this.selectedComponent
);
if (componentOptionSelected) {
  prepareData(groupedByComponent[this.selectedComponent]);
} else {
  this.selectedComponent = Dashboard.All; // note spelling
  prepareData(allDataByAttribute);
}


Removing Asterisks and neighbors from a string

Regular expressions are the right tool for this sort of problem, and your suspicions that your code is not great, is about right.... there's the + operator in regular expressions which will do what you want much more concisely. + matches 1-or-more times.

Consider the simple expression:

String compact = raw.replaceAll(".?\\*+.?", "");

That replaces all something-stars-something patterns with nothing.

Note, this pattern will have the following results:

ab*cd     ad
ab***cd   ad
a**b
ab****    a

etc.

The way the expression works is as follows:

Key features of the regex are:

\\*+ - * is normally a special character. We have to escape it with \\ to make it a normal *. The + is a 1-or-many match. What does this mean? It means that the expression \\*+ will match at least one * character, perhaps many of them in a row.
.? this is a non-greedy 0-or-1 match of any character. This requires some explaining. This will match at most 1 character, but, if the overall pattern will fail to match something, then the pattern can be tried again but matching nothing. What it means, is: "if possible, match 1 character - any character (including *)"

Putting them together, you get an expression that matches any character, if there is one, before an asterisk, as well as the asterisk, and any other asterisks that follow it, and finally any other character, if there is one.

See this in an ideone here: http://ideone.com/6yMSvx


Scraping all closed captions (subtitles) of a YouTube's creator's video library

Bug

This was probably a posting or a copy/paste bug - in create_file() you meant to name the first parameter to be filename instead of title.

Code Style and PEP8 notes

use more descriptive variable names - r, s, c, v are not good variable names
remove unused TimeoutException import, organize imports in groups and alphabetically (PEP8 reference)
move the comments before the functions into proper docstrings
avoid catching broad exceptions via bare except
follow PEP8 whitespace and newline usage guidelines - specifically, whitespaces around the operators, two newlines between the function definitions

Third-party Library Usage notes

BeautifulSoup constructor accepts a file-like object as well - you don't have to explicitly call .read() method
it is a good idea to specify BeautifulSoup's parser explicitly:

soup = BeautifulSoup(r, "html.parser")  # or "html5lib", or "lxml"

Otherwise, BeautifulSoup would pick a parser automatically depending on what is available. This would mean that on your machine it may pick, say, lxml - on someone else's - html5lib, on other's html.parser. And, there might be different results since different parser behave differently.
a bigger problem is that you are not actually using BeautifulSoup capabilities at all - you are post-processing the "soup" with regular expressions. It looks like you can achieve the same by calling the .get_text() method on the "soup" object
for better reusability I would probably assume chromedriver is in PATH instead of hardcoding the path to it explicitly
you can reuse WebDriverWait instance instead of re-instantiating it multiple times
you never close the driver instance
time.sleep() is generally unreliable when used for waiting for something with selenium - recheck if you actually need it

Code Organization notes

You are passing driver to multiple methods - it may be a good idea to have a class with a driver and wait attributes for better reusability.

Some Syntax Sugar

you can construct a list of videos with a list comprehension:

[(video.text, video.get_attribute("href"))
 for video in driver.find_elements_by_class_name("yt-uix-tile-link")]

you can unpack the list of videos into filename and a link:

for filename, link in videos:

Modified Code:

import sys
import time
import urllib.request

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

class YoutubeSubtitlesScraper:
    def __enter__(self):
        self.driver = webdriver.Chrome()

        self.wait = WebDriverWait(self.driver, 10)

        self.driver.get(start_url)
        self.display_all_videos()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.driver.close()

    def display_all_videos(self):
        """Clicks on "Load More" button to display all users videos."""
        while True:
            try:
                element = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "yt-uix-load-more")))
                element.click()
            except TimeoutException:
                break

    def subtitles(self):
        """Visits video's page, enables 'CC' to scrape the subtitles and generates filename, link and the subtitles content."""
        videos = [(video.text, video.get_attribute("href"))
                  for video in self.driver.find_elements_by_class_name("yt-uix-tile-link")]

        for filename, link in videos:
            self.driver.get(link)
            self.enable_subtitles()

            link = self.get_subtitles_link()
            yield filename, link, self.scrape_subtitles(link) if link else "No Closed Caption"

    def enable_subtitles(self):
        """Clicks on CC(Closed Caption) button in YouTube video."""
        show_subtitles_button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "ytp-subtitles-button")))
        show_subtitles_button.click()

    def get_subtitles_link(self):
        """Finds string in performance timings that contains the substring 'srv3' which is the subtitles link."""
        time.sleep(1)
        timings = self.driver.execute_script("return window.performance.getEntries();")

        for timing in timings:
            for value in timing.values():
                if "srv3" in str(value):
                    return value
        return ""

    def scrape_subtitles(self, subtitle_link):
        """HTML parses subtitles."""
        response = urllib.request.urlopen(subtitle_link)
        soup = BeautifulSoup(response, "lxml")
        return soup.get_text(strip=True)

def create_file(filename, link, subtitles):
    """Creates file for the subtitle."""
    title = "".join([c for c in filename if c.isalpha() or c.isdigit() or c == ' ']).rstrip()

    with open(title + '.txt', 'w') as subtitles_file:
        subtitles_file.write('LINK: ' + link + '\n')
        subtitles_file.write(subtitles)

if __name__ == "__main__":
    start_url = sys.argv[1]

    with YoutubeSubtitlesScraper(start_url) as scraper:
        for filename, link, content in scraper.subtitles():
            try:
                create_file(filename, link, content)
            except:
                print("Can't create file for: " + filename + " : " + link)

(not tested)

Note how we made the class a context manager by defining the __enter__() and __exit__() magic methods.


I'm assuming that you did read about the solution that runs in constant time, but wanted to add your own non-constant solution.

continue

Your continue statements are unnecessary; you can just remove them.

Naming

Your naming violates every standard for Java. Java uses camelCase and doesn't allow names to start with uppercase letters.

It is also generally discouraged to use numbers in names if they can be avoided, which in this case they can: n1 could be called three, and n2 could be five. If you want to stay flexible, use firstMultiple and secondMultiple or something similarly expressive.

Constants

As n1 and n2 are constants, I would declare them as static fields.

Comments

As your solution is not straightforward, I would add a comment or two about how it works.

Efficiency

In case you're interested, here are the results that I get if I compare your solution with the solutions from the other thread (mentioned in the comments):

name                       per call (mean, ns)     per call (median, ns)     95th percentile (ns)     total (ms)     runs
three loops                280                     277                       256                      0.224          1000000
without function calls     392                     392                       362                      0.3136         1000000
getSum                     694                     695                       641                      0.5552         1000000
with function calls        3739                    3766                      3338                     2.9912         1000000


Why my listview style change when I loop the javascript twice?

I can't see anything wrong with your code in terms of why it gives you different styles. I would however ensure you have a consistent coding standard.

For example my coding standards usually include:

Always declare variables. Variable maks is never declared here (I'm going to assume it is never declared.) Change it to var maks = -1;
Always use { and }. This will ensure you don't screw up a block.

if(data[result][i].bulan > maks)
    maks = data[result][i].bulan;

would become:

if(data[result][i].bulan > maks)
{
    maks = data[result][i].bulan;
}

Its just proofing for us who make mistakes from time to time.
make local variables where possible

if (resultArray[i].bulan === bulanVal && !types[resultArray[i].type]) {
    types[resultArray[i].type] = true;
    count++;
}

could be:

 var current = resultArray[i];
 if (current.bulan === bulanVal && !types[current.type]) {
    types[current.type] = true;
    count++;
}

It means less look ups. Most of the time its easier to read.


The root of the problem is you have ~3100 items in the page. This could be simplified by using pagination. If this is a traditional page, page the output. If this is a webapp, you may have all ~3100 in memory, but don't render it all. Besides, there's no point rendering ~3100 items unfiltered anyways. Who scrolls through ~3100 items?

Granted that you don't have any other option but to render it all and filter on the spot, the next problem with your code is that it generates a lot of jQuery objects. Every time you call the $() function, a jQuery object is generated.

// Here, the $(v)
var list = $.makeArray(lis.map(function(k, v) {
    return $(v).text().toLowerCase();
}));

// Here, the $(value)
lis.each(function(index, value) {
    if (list[index].indexOf(userInput) >= 0) {
        count++;
        $(value).show();
    } else {
        $(value).hide();
    }
});

One way to avoid this is to collectively do the show and hide instead of doing it per item. In the following code, it gathers all elements to show and to hide, wraps both arrays in jQuery and calls show and hide.

var toShow = [];
var toHide = [];
lis.each(function(index, value){
  if (list[index].indexOf(userInput) >= 0) {
    toShow.push(this);
  } else {
    toHide.push(this);
  }
});

$(toShow).show();
$(toHide).hide();

Notice that I only called $() twice, and .show() and .hide() once instead of per item. We just avoided creating ~3100 jQuery objects!

Another way to improve this code is to use native operations whenever possible. It's not that they're faster by themselves, but you reduce reliance to jQuery, avoiding creation of jQuery objects when ordinary arrays would have sufficed.

var list = $.makeArray(lis.map(function(k, v) {
  return $(v).text().toLowerCase();
}));

This code above could have been simplified into

var list = lis.get().map(function(element){
  return (element.innerText || element.textContent).toLowerCase();
});

In the "improved version", notice that 1) it uses a native array instead of jQuery in the first place, allowing the use of the native array.map and 2) it doesn't call $() in the callback at all. We just avoided ~3100 jQuery objects again!

Now back to your toggling code, I think I see an update you did before my answer by adding/removing classes. That's a good move because 1) styling should be done in CSS and 2) show and hide uses inline styles. They are hard to override from a stylesheet. The only way you could is to use !important which you should generally avoid.

As for your question about removal vs hiding, I'd say go for hiding. As far as I know, removals are slow. This is even worse when there are stuff attached to the elements in question. For instance, removing an element with jQuery handlers attached. jQuery has to clean them up, remove references to data and handlers etc. If removals aren't done properly, you could have a lot of lingering things in memory.


What if your $description variable is empty? You are only checking if you're on the front page, or home page, and set it to blog description from wordpress, and if you're not, you're setting it to your post meta value.

What about categories? Tags? other archive pages?

The

if($description)

Will return what? False. Why? Because it's a description, not a boolean.

You should check it with

if(isset($description) && $description !== '')

If the variable is set and not empty string you'll get a true as a value that will pass the if test.

I'd do it like this:

<?php
if (is_page() || is_single()) {
    $description = get_post_meta(get_the_ID(), 'description', true);
} else {
    $description = get_bloginfo('description');
}

if (isset($description) && $description !== '') {
    ?>
    <meta name="description" content="<?php echo htmlspecialchars($description); ?>" />
    <?php
}
?>

If you're on a single post or a page, you'll get the post meta, and if you're anywhere else, you'll get blog description. And then output it only if it's set and not empty.

My advice is to see all the cases that can come up with conditional tags and set your description accordingly ;)


There are few problems with this macro.

It relies on an undocumented layout of FILE structure
It cannot be nested (try it with -Wshadow)
It assumes that the block is always left through the end
It may create suprises:

    for (....) {
        with_fopen(fp, ...) {
            int rc = do_something(fp);
            if (rc == -1) {
                break;
            }
        }
    }

The programmer (with or without Python background) expects the outer loop to be broken. Instead the loop hidden inside with is.

Nice try however.


One of the main features of NumPy is that you can work with matrices without explicit looping.  To get the diagonal, use np.identity().  To set everything else, use broadcasting.

def make_matrix(value, dim):
    return value - value * dim * np.identity(dim, dtype=np.double)

param and N don't mean anything to me.  I suggest value and dim.  The function name should preferably be make_matrix, according to PEP 8.


use regex to separate a list of serial numbers into multiple lists with matched prefix

You can do this with re.findall. Instead of iterating over each string, you can combine all the serial numbers into one string and use regex to find all the matches (this implementation assumes there are no spaces in the serial number).
import re

string_list = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']
string = ' '.join(string_list)
matches = re.findall(r"([^0-9])", string)
numbers = re.findall(r"([0-9]{3})", string)
prefixes = ''.join(c for c in matches).split()
result_dict = {}
for prefix, number in zip(prefixes, numbers):
    if prefix not in result_dict.keys():
        result_dict[prefix] = []
    result_dict[prefix].append(prefix + number)

The first re.findall searches for any string that is not a number. The second finds any succession of three numbers. The next line combines the characters in matches, and since we denoted that we separated each serial number by ' ', we can split using the same value. Then, we use the same code present in your question to populate the result dictionary.


Multiple AFNetworking calls In a view controller

There is nothing wrong with multiple network requests, it will not have any impact on battery that you need to worry about.

Your code however needs a lot of work. None of these network requests should be happening inside a ViewController. It's purpose is to configure the View and handle user actions, nothing else.