Adding elements to a hash from an output The script currently loops through an output line-by-line, picking out elements of interest and adds them to a hash data structure. If a key already exists (in this case the interface name), it appends data to it.

I can work with a data structure, but I am never happy with the approach I take of looping through the data line by line.

Is there a cleaner way of achieving this?

#!/usr/bin/env perl

use strict;
use warnings;
use feature 'say';

my $output = <<END;
1C:C1:DE:AC:15:C2   192.168.50.16     236263      dhcp-snooping   50    FastEthernet3/0/8
00:24:B5:F7:1A:E3   192.168.58.77     225905      dhcp-snooping   58    FastEthernet3/0/8
00:22:64:A6:E5:C6   192.168.50.61     139103      dhcp-snooping   50    FastEthernet3/0/38
00:1B:25:2E:91:2F   192.168.51.42     222285      dhcp-snooping   51    FastEthernet4/0/15
00:23:7D:4F:18:A5   192.168.51.36     382530      dhcp-snooping   51    FastEthernet4/0/21
C8:F4:06:E0:32:7C   192.168.57.47     258924      dhcp-snooping   57    FastEthernet4/0/21
18:A9:05:1E:5C:B3   192.168.49.21     256946      dhcp-snooping   49    FastEthernet2/0/34
00:22:64:1B:F7:8C   192.168.49.18     192605      dhcp-snooping   49    FastEthernet2/0/21
00:23:7D:50:68:A4   192.168.51.110    381036      dhcp-snooping   51    FastEthernet4/0/26
00:21:E1:FE:E0:94   192.168.57.87     177812      dhcp-snooping   57    FastEthernet2/0/6
00:23:7D:4E:BA:02   192.168.49.80     167839      dhcp-snooping   49    FastEthernet2/0/31
00:23:7D:4F:1A:23   192.168.51.95     293268      dhcp-snooping   51    FastEthernet2/0/36
5C:E2:86:F5:B3:04   192.168.57.48     177809      dhcp-snooping   57    FastEthernet2/0/31
END

my @data = split /\n/, $output;

use Data::Dumper;

my %data_str;
foreach my $line (@data) {
    my @output_data = split /\s+/, $line;
    # Interface already found, append IP and MAC
    if ( exists $data_str{ $output_data[5] }
        && $data_str{ $output_data[5] } eq $data_str{ $output_data[5] } )
    {
        push $data_str{ $output_data[5] },
            { $output_data[1] => $output_data[0] };
    }
    # Add IP address and MAC address to hash
    else {
        $data_str{ $output_data[5] }
            = [ { $output_data[1] => $output_data[0] } ];
    }
}

say Dumper( \%data_str );

You don't have to write code for testing of key existence because autovivification will do the work for you. So your cycle can be written as simple:

foreach my $line (@data) {
    my ($mac, $ip, $if) = (split /\s+/, $line)[0,1,5];
    push @{$data_str{$if}}, {$ip => $mac};
}

It is good practice to name your data instead of pollute indexes all over your code. It is much better if they are all in one place. Alternative way is:

my ($mac, $ip, undef, undef, undef, $if) = split /\s+/, $line;

which shows line structure visually.

Another thing is your data structure. Why it has hash value which is array of hashes with IP as one key and mac address. This structure is not good to work with. If I would have to find which MAC belong to given IP I would have to write something like

sub get_mac {
    my ($hash, $if, $ip) = @_;
    for my $x (@{$hash->{$if}}) {
       return $x->{$ip} if exists $x->{$ip};
    }
    return ();
}

which is slow and tedious. Much better is construct two level hash:

foreach my $line (@data) {
    my ($mac, $ip, $if) = (split /\s+/, $line)[0,1,5];
    $data_str{$if}{$ip} = $mac;
}

Now if I would like to know MAC of given IP

my $mac = $data_str{$if}{$ip};

Easy and efficient. I still can get all IPs and MACs

my @ips = keys %{$data_str{$if}};
my @macs = values %{$data_str{$if}};

I can also make original pairs out of this structure

my @pairs = map {+{$_ => $data_str{$if}{$_}}} keys %{$data_str{$if}};


Finding the number which satisfies specific conditions I saw this question somewhere:

There is an 8-digit number. The first digit from left to right determines how many zeroes are in the number. The second digit tells you how many 1s are in the number, the third digit tells you how many 2s are in the number and so on, until the 8th digit, which tells you how many 7s are in the number. Find the number.

I wrote a piece of code in Python to find out the digit. Apart from the conditions mentioned above, I have a few additional checks like 'sum of digits should be 8' and 'no 8 or 9 should be present in the number'. This is just brute force since I take every number and check for conditions. I was curious to know if there is any better way of solving the problem.

def returnStat(number, digit, count):
    number = str(number)
    digit = str(digit)
    print "Analysing for ",digit," to see if it appears ",count, " times in ",number,"."
    actCnt = number.count(digit)
    count = str(count)
    actCnt = str(actCnt)
    if (actCnt == count):
        return 1
    else:
        return 0
def validateNum(number):
    numList = str(number)
    if '8' in numList:
        print "Skipping ",number, " since it has 8 in it"
        return (-1)
    elif '9' in numList:
        print "Skipping ",number, " since it has 9 in it"
        return (-1)
    elif (sum(int(digit) for digit in numList) != 8):
        print "Skipping ",number, " since its sum is not equal to 8"
        return (-1)
    index = 0
    flag = 0
    for num in numList:
        if (returnStat(number,index,num)) :
            index = index+1
            continue
        else:
            flag = 1
            break
    if (flag == 1):
        return (-1)
    else:
        return number

for num in range(0,80000000):
    number = '{number:0{width}d}'.format(width=8,number=num)
    desiredNum = "-1"
    desiredNum = validateNum(number)
    if (desiredNum == -1):
        print number," does not satisfy all "
        continue
    else:
        print "The number that satisfies all contition is ",number
        break

Testing for self-descriptiveness is easy if you use the built-in collections.Counter to do the counting for you:

from collections import Counter

def self_descriptive(n):
    """Return True if n is self-descriptive, that is, if n is made up of
    digits d0 d1, ..., then d0 of them are 0, d1 are 1, and so on.

    >>> self_descriptive(1210)
    True
    >>> self_descriptive(310100)
    False

    """
    digits = [int(d) for d in str(n)]
    return Counter(digits) == +Counter(dict(enumerate(digits)))

And then the solution is a one-liner:

next(filter(self_descriptive, range(10**7, 8*10**7)))

But this takes so long that it's faster to solve the problem by hand:

   Consider how many zeroes there are. It's easy to rule out 8, 7, and 6, so could there be 5? This would require the number to be \$ 5abcd100 \$, with \$ a ≥ 1 \$ and \$ b = c = d = 0 \$, but this doesn't work: either \$ a = 1 \$ but there are two 1's, or \$ a > 1 \$ and there is only one 1.
 There can't be 3 (or fewer) zeroes, because that leaves 4 (or more) non-zeroes, adding up to at least 1 + 2 + 3 + 4 = 10 other digits, which is too many.
 So that leaves 4 zeroes. This requires the number to be \$ 4abc1000 \$ with \$ a ≥ 1 \$ and either \$ b = 0 \$ or \$ c = 0 \$ (but not both). If \$ b = 0 \$ then \$ c ≥ 1 \$ but this is not possible because that would require 3 of some digit, so it must be \$ c = 0 \$ and the (only) answer is \$ 42101000 \$.


Optimization of matrix determinant calculation I have this algorithm that calculates the matrix determinant using recursive divide-and conquer-approach:

int determ(int a[max][max],int max) {
  int det=0, p, h, k, i, j, temp[max][max];
    //base case omitted
    for(p=0;p<max;p++) {
      h = 0;
      k = 0;
      for(i=1;i<max;i++) {
        for( j=0;j<max;j++) {
          if(j==p) {
            continue;
          }
          temp[h][k] = a[i][j];
          k++;
          if(k==max-1) {
            h++;
            k = 0;
          }
        }
      }
      det=det+a[0][p]*pow(-1,p)*determ(temp,max-1);
    }
    return det;
}

I want to optimize the main loop (with a loop unwinding or any strategy that can reduce the execution time).  Any suggestion?

Sorry, it is not a divide and conquer, it's a combinatorial explosion. The timing complexity

$$T(n) = nT(n-1)$$

evaluates to n! - exponential growth. There is no way to heal the code; you have to choose another algorithm.


Elegantly handle github API requests exceptions I have this code which creates a team using the github API and returns the team-id(success) or -1(failure).

My problem is with the error handling. When the request responses with an error status code I try to deal with a few different types of failure.  It looks like a mess!

Is there any way to make it more readable/elegant?

I'd also like to know if I am catching all the reasonable exceptions that can be thrown by requests.

def create_team(org,team_name):
    '''
    Try to create a team and return its id
    if already exisits return id
    '''
    try:
        data = {
            "name": team_name,
            "permission": "push"
        }
        headers = {'Authorization': 'token '+OAUTH_TOKEN}

        response = requests.post(GH_API_URL+'orgs/'+org['login']+'/teams',
                                    headers=headers,
                                    data = json.dumps(data))

        response.raise_for_status() #throw exception if request does not retun 2xx

        #http status is 2xx, team must have been created
        json_response = json.loads(response.text)
        return json_response['id'] #get id of new team from response

    except requests.exceptions.HTTPError as e:

        if response.status_code == 422: #Unprocessable Entity
            json_response = json.loads(response.text)
            if json_response['errors'][0]['code'] == 'already_exists': #Unprocessable because already exists
                print(' not created, team already exists!!!')

                #get the id of existing team
                team_id = get_teamID_from_name(org, team_name)

                return team_id
            else:  #Unprocessable for some other reason
                print(' HTTP error: '+str(e))

        else: #other HTTP error != 422
            print(' HTTP error: '+str(e))

    except requests.exceptions.RequestException as e:
        print('Connection error: '+str(e))

    return -1

In case you were wondering why I don't just check for the existence of the team BEFORE trying to create it. That's because the normal case for this function is that the teams do not already exist and the github API is quite slow. As it stands it takes several minutes to process a groups with 50 teams and 100 students. Checking for team existence would add a few more minutes to the runtime.

One way to slightly speed-up is by reducing the overhead of the requests module. Currently your code has to establish a connection once for every team, re-transmitting the authentication API code and so on. This is a solved problem, you could use sessions.

You would have to start it with a context-manager in you outer function (where you loop over all of the team-names to create) and pass the session object to the create_team function.

I also shuffled some code out of the try block, you should have only the least possible amount in there, so you can be sure what exactly raised an error. I also inserted early returns, but there are other schools of thought which prefer a single exit for functions at the cost of having more code in the try block.

I also tried including a bare bones implementation for your outer function, but yours might be slightly different, of course.

I used str.format, where applicable instead of string addition.

import requests

OAUTH_TOKEN = "XXX"
HEADERS = {'Authorization': 'token {}'.format(OAUTH_TOKEN)}
GH_API_URL = "http://github.com/XXX"

def create_teams(org, team_names):
    with requests.Session() as session:
        session.headers.update(HEADERS)
        for team_name in team_names:
            create_team(session, org['login'], team_name)

def create_team(session, org_name, team_name):
    '''
    Try to create a team and return its id.
    If it already exists return id
    '''
    data = {
        "name": team_name,
        "permission": "push"
    }
    url = '{}orgs/{}/teams'.format(GH_API_URL, org_name)
    try:
        response = session.post(url, data=json.dumps(data))
        response.raise_for_status()  # throw exception if request does not return 2xx
    except requests.exceptions.HTTPError as e:
        if response.status_code == 422:  # Unprocessable Entity
            json_response = json.loads(response.text)
            # Unprocessable because already exists
            if json_response['errors'][0]['code'] == 'already_exists':
                print('{} not created, team already exists!!!'.format(team_name))
                # get the id of existing team
                return get_teamID_from_name(session, org, team_name)
        # Unprocessable for some other reason or other HTTP error != 422
        print(' HTTP error: {}'.format(e))
        return -1

    except requests.exceptions.RequestException as e:
        print('Connection error: {}'.format(e))
        return -1

    # http status is 2xx, team must have been created
    json_response = json.loads(response.text)
    return json_response['id']  # get id of new team from response


Filter some Apache Conf to extract all ServerName and ServerAlias, then output them one per line #!/bin/bash
#extractApacheResolutionName

GrepAndFilter="ServerName|ServerAlias"
RemoveBadMatch="s/^\s*($GrepAndFilter)\s+//gI"
RemoveTrailingWhitespaces="s/\s*$//"
RemoveComas="s/,//g"
ReplaceSpacesWithNewLines="s/ +/\s/g"

grep --line-buffered -Ei "$GrepAndFilter" /dev/stdin \
    | sed -E "$RemoveBadMatch; $RemoveTrailingWhitespaces; $RemoveComas; $ReplaceSpacesWithNewLines"

The script is to be used mainly to gather all the URLs of a remote Httpd Configuration, and output them one URL per line, such as

ssh hostname "cat /etc/httpd/conf.d/*.conf" | extractApacheResolutionName

Nb : the actual script contains a sort

... | rev | sort -u | rev

... but that's another question I asked on StackOverflow, because I would like to extract it to another piece of software.

What can I do to improve my script ?

from a readability point of view ?
from a performance point of view ?

What is "bad match" in here?

RemoveBadMatch="s/^\s*($GrepAndFilter)\s+//gI"

My understanding is that this pattern is used to remove the $GrepAndFilter prefix from lines, with any surrounding whitespace. I don't see that prefix as "bad match" in any sense of the word. It seems RemoveFilterPrefix would be a better fit.

Here, instead of \s*$ as the pattern, I'd use \s+$,
to emphasize that the content will be modified only when there are non-zero trailing whitespaces.

RemoveTrailingWhitespaces="s/\s*$//"

Here, the pattern doesn't match the name:

ReplaceSpacesWithNewLines="s/ +/\s/g"

I think you meant \n as the replacement,
because \s doesn't have a special meaning in a replacement string,
so as written,
this command will replace spaces with the letter s.

grep assumes /dev/stdin as input by default, no need to specify it explicitly.

In many systems, the Apache configuration files often contain ServerName and ServerAlias on commented out lines.
The posted script won't work with such lines,
and I can easily imagine such lines in production systems too.
I suggest to make the script more robust by excluding commented lines.
This could be as simple as making the first filter more strict:

GrepAndFilter="^\s*(ServerName|ServerAlias)\s+"


Rewrite apply function to use recursion instead Probably the hardest part of learning lisp has been to think in the "lisp way" which is elegant and impressive, but not always easy. I know that recursion is used to solve a lot of problems, and I am working through a book that instead uses apply to solve a lot of problems, which I understand is not as lispy, and also not as portable.

An experienced lisper should be able to help with this logic without knowing specifically what describe-path, location, and edges refer to. Here is an example in a book I am working through:

(defun describe-paths (location edges)
  (apply (function append) (mapcar #'describe-path
               (cdr (assoc location edges)))))

I have successfully rewritten this to avoid apply and use recursion instead. It seems to be working:

(defun describe-paths-recursive (location edges)
  (labels ((processx-edge (edge)
         (if (null edge)
         nil
         (append (describe-path (first edge))
             (processx-edge (rest edge))))))
    (processx-edge (cdr (assoc location edges)))))

I would like some more seasoned pairs of eyes on this to advise if there is a more elegant way to translate the apply to recursion, or if I have done something unwise. This code seems decent, but would there been something even more "lispy" ?

Lisp is a multiparadigm language.

apply is just as lispy as recursion, and, in a way, much more so (think in HOFs)!

Style

Please fix indentation.
Please write #'foo instead of (function foo).

Implementations

The first (HOF) version can be much more efficiently rewritten in using mapcan (provided defscribe-path returns fresh lists):

(defun describe-paths (location edges)
  (mapcan #'describe-path
          (cdr (assoc location edges)))))

The second (recursive) version can be made tail recursive using an accumulator. This would help some compilers produce better code.

(defun describe-paths-recursive (location edges)
  (labels ((processx-edge (edge acc)
             (if (null edge)
                 acc
                 (processx-edge (rest edge)
                                (revappend acc (describe-path (first edge)))))))
    (nreverse (processx-edge (cdr (assoc location edges))))))

Note the use of revappend/nreverse instead of append to avoid quadraticity.


Checking a numeric palindrome Given A and B, count the numbers N such that A ≤ N ≤ B and N is a
  palindrome.

  Input:

  First line contains T, the number of testcases. Each testcase consists
  of two integers A and B in one line.

  Output:

  For each testcase, print the required answer in one line.

  Constraints:

  1 ≤ T ≤ 10

  0 ≤ A ≤ B ≤ 10^5

private static boolean[] isPalindrome = isPalindrome();
    public static void main(String args[] ) throws NumberFormatException,
IOException{
       BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        int totalTestCase = Integer.parseInt(reader.readLine());
        StringBuilder outputPalindromeCount = new StringBuilder();
        for (int i = 0; i < totalTestCase; i++) {
            String[] input=reader.readLine().split(" ");
            int startNo = Integer.parseInt(input[0]);
            int endNo = Integer.parseInt(input[1]);
            int totalFoundPalindrome = getPalindromeCount(startNo, endNo);
            outputPalindromeCount.append(totalFoundPalindrome + "\n");
        }
        System.out.println(outputPalindromeCount);

    }

    private static int getPalindromeCount(int startNo, int endNo) {
        int totalPalindromeFound = 0;
        for (int i = startNo; i <= endNo ; i++ ){
            if(isPalindrome[i]){
                totalPalindromeFound++;
            }
        }
        return totalPalindromeFound;
    }

    private static boolean[] isPalindrome() {
        boolean[] isPalindrome = new boolean[100001];
        Arrays.fill(isPalindrome, 0, 10, true);
        for (int i = 10; i <= 100000; i++) {
            if (checkForPalindrome(i)) {
                isPalindrome[i] = true;
            }
        }
        return isPalindrome;
    }

    private static boolean checkForPalindrome(int i) {
        int divNo = 1;
        while (i / divNo >= 10) {
            divNo = divNo * 10;
        }

        while (i != 0) {
            int startingDigit = i / divNo;
            int lastDigit = i % 10;
            if (startingDigit != lastDigit) {
                return false;
            }
            i = (i % divNo) / 10;
            divNo = divNo / 100;

        }
        return true;
    }

}

For this input:

6
0 0
1 1
1 10
1 9
1 1000
1000 100000

this code took 0.18 seconds. It's taking almost 0.18-0.20 seconds for various sets of input (link of all inputs and time).

What are the other Efficient way of checking palindromes (not just a way of conversion to a string and then check but really efficient)?

How could have I optimized the above code further (apart from BitSet which is a trade off for runtime)?

isPalindrome is a very unfortunate name in this code:

Names starting with "is" are typically methods returning a simple boolean
... but in this code isPalindrome is a parameterless method returning a boolean array
... and at the same time there is also a boolean array called isPalindrome

It would be better to use different names for the method and the array,
and neither should start with the word "is".

In the isPalindrome method, you could shorten this:

        if (checkForPalindrome(i)) {
            isPalindrome[i] = true;
        }

to this:

        isPalindrome[i] = checkForPalindrome(i);

I'm a big fan of descriptive variable names,
but I think you went a bit overboard, for example here:

private static int getPalindromeCount(int startNo, int endNo) {
    int totalPalindromeFound = 0;
    for (int i = startNo; i <= endNo ; i++ ){
        if(isPalindrome[i]){
            totalPalindromeFound++;
        }
    }
    return totalPalindromeFound;
}

I would simplify some of the names there to:

private static int getPalindromeCount(int start, int end) {
    int palindromeCount = 0;
    for (int i = start; i <= end; i++) {
        if (isPalindrome[i]) {
            palindromeCount++;
        }
    }
    return palindromeCount;
}

The numbers 100001 and 100000 are magic.
It would be good to create a constant from 100000 with a descriptive name.

A small tip: it's a lot easier to parse simple input using a Scanner, with its nextInt and nextLine methods,
instead of a BufferedReader and Integer.parseInt.

Also, why build output in a StringBuilder if you will print its contents anyway inside the same method.
You could just print the results directly.


Program to shorten URL and decode it back to get original URL TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

My approach:

import java.util.HashMap;
import java.util.Random;
import java.lang.StringBuilder;

public class Codec {

     //HashMap to store the longUrl and the randomly generated string
     HashMap<String,String> urlMap = new HashMap<>();

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        Random rand = new Random();
        int urlLen = 6;
        char [] shortURL = new char[urlLen];
        String randChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

        for(int i = 0; i < urlLen; i++ )
            shortURL[i] = randChars.charAt(rand.nextInt(randChars.length()));

        StringBuilder sb = new StringBuilder("http://tinyurl.com/");
        sb.append(new String(shortURL));
        System.out.println(sb);

        urlMap.put(sb.toString(),longUrl);

        return sb.toString();

    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {

            return urlMap.get(shortUrl);

    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));

With regards to the above code, I have the following questions:

Is there a better approach to do this question?
Can I decrease the number of lines or variables used in the program?
Can I improve the space and time complexity of the program?

Reference

Flawed approach

There are severals flaws in the current approach:

The program doesn't check if the generated key already exists for a different URL. And it might. And when it does, the new value will overwrite the old one. The old value will be no longer retrievable.
encode returns a different output for the same input, with very high probability. In fact you can make the program run out of memory by calling encode on the same string enough times.
The implementation wastes a lot of memory. There's no need to use the full tiny URL as the key of the cache, the unique part would be enough, and divide the storage size of the keys by 3.
It's unrealistic to expect a URL shortening service to run forever without server reboots. Since this implementation doesn't use any storage outside RAM, all previously stored URLs will be completely lost when the process is restarted.

Technical issues

There are many technical implementation flaws:

No need to create a new Random in every call of encode. Better use a shared instance.
Magic numbers and strings should be constants or class parameters: the target key length (6), the alphabet.
The names are not great. urlLen is not the length of a URL, but the length of the unique part only (6 letters). randChars are not "random chars", but an alphabet from which to pick a random character.
It's a bad practice to print to stdout from methods that are not particularly designed to print stuff.
Prefer to declare variables using interface types: Map instead of HashMap.
Using a StringBuilder is overkill, a simple concatenation with + would be better.


Is date 18+ years old? Considering that:

the passed parameters are all numbers
the passed date is a valid date

It should return:

true if the date is 18 or more years old
false otherwise

function isDate18orMoreYearsOld(day, month, year) {
    var maxBirthDate = new Date();
    maxBirthDate = new Date(maxBirthDate.setYear(maxBirthDate.getYear() - 18));
    var maxYear = maxBirthDate.getYear();
    var maxMonthOnMaxYear = maxBirthDate.getMonth() + 1;
    var maxDayOnMaxMonthOnMaxYear = maxBirthDate.getDate();
    if (year > maxYear) {
        return true;
    }
    if (year == maxYear) {
        if (month > maxMonthOnMaxYear) {
            return true;
        }
        if (month == maxMonthOnMaxYear) {
            if (day >= maxDayOnMaxMonthOnMaxYear) {
                return true;
            }
        }
    }
    return false;
}

Despite I don't want to lose maintainability and readability, I feel it could possibly have a lesser number of conditional statements.

Is there any improvement you suggest?

Also, if you spot any cases that the function fails it's very welcome.

What about this:

function isDate18orMoreYearsOld(day, month, year) {
    return new Date(year+18, month-1, day) <= new Date();
}

The month - 1 is required because JS months start at 0.


creating own javascript join and push methods I'm a newbie trying to write my own push() and join(). This isn't very serious, just an exercise.
This is what I got so far

function Errey(...values){
    this.name=values
    }
Errey.prototype={
  constructor:Errey,
    //join method
  myJoin(union = ' '){
  let result=""
  const length = this.name.length
  for(let i=0; i<length; i++)
  {
   i<length-1 ? result += this.name[i] + union: result+=this.name[i]
  }
  return result
  },
    //push method
    myPush(value){
    this.name = [...this.name, value]
    return this.name.length
    }
  }

//run a few examples
const myArray = new Errey("3","blue","1","brown")
//we'll mutate myArray anyways using const or let
let joined  = myArray.myJoin()
let a = myArray.myPush("hey")
console.log("joined new array: ",joined, "\n\npush-mutated array: ", myArray.name, "\n\npush return value: ", a)

I'm aware an object is returned instead of an array. I guess you might help me out there. Should I use factory functions here? I don't know how would I create a prototype for such a thing...
Any improvements on the main code you'd suggest?

first of all you can use the "new" class syntax instead of changing the prototype directly.
This is how I would do it:
class Errey {
    #currentArray;

    constructor(...elements) {
        this.#currentArray = elements;
    }

    get errey() {
        return this.#currentArray;
    }

    push(...elements) {
        const startLength = this.#currentArray.length;
        elements.forEach((curEl, index) => this.#currentArray[index + startLength] = curEl);
        return this.#currentArray.length;
    }

    join(union = " ") {
        return this.#currentArray.reduce((prev, cur) => prev + union + cur);
    }
}

//run a few examples
const myArray = new Errey("3","blue","1","brown")

console.log(myArray.join(", "));
console.log(myArray.push("Subscribe", "To", "Him"));
console.log(myArray.errey);

push:
the standard array.prototype.push allows for multiple elements to be added at once, so I allow multiple elements and loop over them using forEach, you could also do [...this.#currentArray, ...elements] (or use Array.prototype.concat()).
join:
here I use reduce to create a join operation. Reduce takes the first 2 elements and applies a function on them (in this case a + union + b), makes them the new first element and repeats that until there is only one element left, our joined erray.
I also made the internal Array private using the prefixed # and created a getter (get errey()) instead, this way the internal array can only be changed using the push method.
Using the factory pattern (which I personally prefer):
const Errey = (...elements) => {

    const push = (...newElements) => {
        const startLength = elements.length;
        newElements.forEach((curEl, index) => elements[index + startLength] = curEl);
        return elements.length;
    };

    const join = (union = " ") => elements.reduce((prev, cur) => prev + union + cur);

    const get = () => elements;

    return {
        push,
        join,
        get,
    };
};

const myArray = Errey("3","blue","1","brown")

console.log(myArray.join(", "));
console.log(myArray.push("Subscribe", "To", "Him"));
console.log(myArray.get());


99 bottles of beer on the wall in Python 3 This is my try on the 99 bottles of beer on the wall lyrics, made in Python 3. I am a beginner willing to learn so be gentle :)

def lyrics():
    if count > 1:
        print(f"{count} bottles of beer on the wall,")
        print("")
        print(f"{count} bottles of beer.")
        print("")
        print("Take one down, pass it around,")
        print("")
    else:
        print(f"{count} bottle of beer on the wall.")
        print("")
        print(f"{count} bottle of beer on the wall,")
        print("")
        print(f"{count} bottle of beer.")
        print("")
        print("Take it down, pass it around,")
        print("")
        print("No more bottles of beer on the wall.")

def bottles():
    global count
    while count > 1:
        lyrics()
        count = count - 1
        if count > 1:
            print(f"{count} bottles of beer on the wall.")
            print("")
        else:
            lyrics()

if __name__ == '__main__':
    count = 99
    bottles()

You have the wrong version of 99 bottles of beers
Global variables are bad except for constants (and some special cases)
print() is equal to print('') but there are two other amazing solutions.
If you come from another language, forget all you know about loops

1.

Ok the first fix is easy, just add:

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

to the end

2.

The second is very important for all your future projects. Use arguments instead of global variables. Using globals is only ok if you define constants of if your script is short, but as soon as your project grows, it will become unmanageable. Globals are also less performant than locals because locals can only be modified in the function itself, that permits the compiler to do assumptions which can't be done with globals. Avoid globals as much as possible.

3.

print('hello')
print('')
# is the same as
print('hello', end='\n') # '\n' is a newline which is the default
print()
# which is the same as
print('hello')
print()
# which is the same as
print('hello', end='\n\n')
# which is the same as
print('hello\n')
# which is the same as
print('he', end='llo')
print()
print()

In summary, either use end='\n\n' or append \n to your string.

4.

In Python, there is this concept of iterable, for i in range(start, end, step) is the way you do the classic looping over integers. range(10) is an iterator that will take all the values from 0 to 9, you know what, lists, tuple, dictionaries files, and even strings are iterables for i in 'babar': print(i). That's why while loops are less used in python, it is because iterables are cool, don't use a while.

def bottles():
    for i in range(99, 1, -1):
        print(f"{i} bottles of beer on the wall, {i} bottles of beer.")
        print(f"Take one down, pass it around, {i-1} bottles of beer on the wall\n")
    i -= 1
    print(f"{i} bottle of beer on the wall, {i} bottle of beer.")
    print("Take it down, pass it around, No more bottles of beer on the wall.\n")
    print("No more bottles of beer on the wall, no more bottles of beer.")
    i = 99
    print(f"Go to the store and buy some more, {i} bottles of beer on the wall.\n")
    bottles() # remove this line if you don't like beers

bottles()

Update:

Apparently, OP can't use numbers, this version doesn't contain numbers:

def bottles(count):
    for i in reversed(range(count+True)):
        s='s' if i-True else ''
        print(f"{i} bottle{s} of beer on the wall, {i} bottle{s} of beer.")
        if not i-True: break
        print(f"Take one down, pass it around, {i-1} bottle{s} of beer on the wall\n")
    print("Take one down, pass it around, no more bottles of beer on the wall\n")
    print("No more bottles of beer on the wall, no more bottles of beer.")
    print(f"Go to the store and buy some more, {count} bottles of beer on the wall.\n")
    bottles(count)  # If you don't want to go to the store and buy some more remove this line

bottles(99)
```


How to implement HasMany() relationship with PHP? Suppose User and Item are two models, and User has many Item. Both models are derived from the parent Model class. In order to retrieve the list of all items a particular user has:

    $user = new User(100);  // User with ID = 100
    $items = $user->getItems();

Now suppose that there are two tables in a database, users and items. In order to find all the items a particular user owns:

    SELECT * FROM users INNER JOIN items ON (users.item_id = items.id) WHERE users.id = 100

I'm trying to implement this functionality as a PHP magic method. Basically what this means is that if you call $users->getItems(), getItems() is not actually a defined method in User. Instead, it will invoke $users->__call('getItems', FUNCTION_ARGS); So basically:

    class Model {
        ...
        function __call($method_name, $args) { /* ? */ }

How would I go about implementing this?

I have the feeling that there is something wrong with your database structure. According your query, user will have exactly one item?

If one user can have many items and the items belongs only to this user, your schema should look like:

User:
ID Name ...

Item
ID Name UserId ...

So your query will look like

SELECT * FROM Item where UserId=100

If the items are shared you need a additional table

UserItemRelation
UserID ItemID

SELECT i.* FROM Item as i, UserItemRelation as r WHERE i.ID=r.ItemID and r.UserID=100

In both cases there is no need to join the User table as you know already the user ID.

Do get this into an abstract method in your model class you have to extract every information related to your concrete class into abstracts methods. Just as a draft:

function __call($method_name, $args)
{
     if (isRelationGetter($method_name))
     {
         return getRelatedEntities(extractField($method_name))
     }
     ....
}

function isRelationGetter ($method_name)
{
    $field=extractField($method_name);
    return isRelationField($field)
}

abstract function isRelationField($field);
abstract function getFieldInfo($field);
abstract function getPrimaryKey();

function getRelatedEntities($field)
{
    $fieldInfo=getFieldInfo($field)
    $query="SELECT * FROM "+$fieldInfo['foreignTable]+" where $fieldInfo['foreignKeyField]="+getPrimaryKey();
    //any database abstraction here
    return fetchAll($query)
}

As you see, a lot of magic.

If you write your own ORM let me recommend to automatically generate some abstract classes between your entity classes and your model and add all the getter to this abstract class. The getter itself can then call getRelatedEntities and you get rid of all this name guessing. Of course it would be easier to use an existing ORM.


Finding the right property value from array of objects I have a below snippet, here I am using array.find to find the first success case and end it. So here is the code snippet
const USERS_LIST = [
  {
    key: "john",
    location: "dublin",
  },
  {
    key: "joe",
    subKeys: [
      {
        key: "jane",
        locaction: "washington",
      },
      {
        key: "mary",
        location: "newyork",
      },
    ],
  },
  {
    key: "chris",
    location: "amsterdam",
  },
];

so what I am trying here is I go through each object in USERS_LIST and check for a subKeys property. If a subKeys property is present, loop through that and check whether that key is eligible. If it's eligible then I need to stop it or it will pass to the next subkey. If I don't find any subKeys eligible then iterate to the next USERS_LIST object then it takes the key and checks for eligible, whichever I find the first I do a callback and stop executing.
I am able to solve this with this snippet
USERS_LIST.find((user) => {
      if (user?.subKeys) {
        user.subKeys.find((subUser) => {
          let subUserStatus = checkEligible({
            action: subUser.key,
          });
          if (subUserStatus) {
            callback(subUser.location);
            return true;
          }
          return false;
        });
      } else {
        let userAccess = checkEligible({ action: user.key });
        if (userAccess) {
          callback(user.location);
          return true;
        }
      }
      return false;
    });

Is there a better way using with array.some or any other functions where I can achieve the same output.

Another way to write the same thing is:
const findUser = list => list.find(u => {
  if(u.subKeys) {
    return findUser(u.subKeys);
  }
  if(checkEligible({action: u.key}) {
    callback(u);
    return true; // necessary to stop the loop
  }
});

findUser(USERS_LIST);

Once that you only need to receive a list, check if is eligible and do something with this, you can use recursion to avoid the callback repeating in user.subKeys.find and USERS_LIST.find.
Also, the return false is not necessary because the iteration of Array.prototype.find will only stop when there is a return value equivalent to true and a function without a explicit return statement will have the implicit return value of undefined:
const noop = () => {};
console.log(noop()) // undefined


Fading HTML elements in and out after timed delays using jQuery I recently launched my first website, and despite being very proud of how far I've come, I know that my code is more "I got it to work" than "It works the best that it can." I'd like some criticism, and insight into how you would accomplish the same effect.

This script shows and hides overlapping Divs to tell a story through text about myself. I want to retain the granular control over how long each div stays visible, but simplify this code.

<script>
    $(document).ready(function(){
     $("button.button").click(function(){
      $("h1.about-title").fadeOut(300, function() {
       $("div.b").delay(500).fadeIn(300).delay(4000).fadeOut(300, function(){
        $("div.c").delay(500).fadeIn(300).delay(4000).fadeOut(300, function(){
         $("div.d").delay(500).fadeIn(300).delay(4000).fadeOut(300, function(){
          $("div.e").delay(500).fadeIn(300).delay(5000).fadeOut(300, function(){
           $("div.f").delay(500).fadeIn(300).delay(5000).fadeOut(300, function(){
            $("div.g").delay(500).fadeIn(300).delay(5000).fadeOut(300, function(){
             $("div.h").delay(500).fadeIn(300).delay(4000).fadeOut(300, function(){

               });
              });
             });
            });
           });
          });
         });
        });
       });
      });
</script>

an example of this running can be found at http://www.erikgratz.com/about.html

I suspect I could have saved a lot of time and code with a loop or some variables. How would you accomplish this same effect?

Explicit question

  Criticize my Javascript

So... you have some JavaScript that uses the jQuery library, and there are a lot of nested function calls. Obviously that isn't very flexible, and some might say it looks daunting with all of those nested callbacks.

Implicit question

i.e. How can I simplify this?

There are numerous ways to achieve this... but one way is to use function partials to simplify the callbacks.

Consider the function below, which checks for a next sibling element using .next():

function fadeInOutNext(elementCollection) {
   elementCollection.delay(500).fadeIn(300).delay(getDelayForElement(elementCollection)).fadeOut(300, function() {
     const next = elementCollection.next();
     if (next) {
       fadeInOutNext(next);
     }
   });
 }

With this function, the nested callbacks can be reduced:

$("button.button").click(function(){
 $("h1.about-title").fadeOut(300, fadeInOutNext.bind(null, $("div.b")));
});

As well as the function to get the delay between fading in and out:

function getDelayForElement(elementCollection) {
  if (elementCollection.is('.e, .f, .g')) {
    return 5000;
  }
  return 4000;
}

See the complete code in the snippet below:

 function getDelayForElement(elementCollection) {
  if (elementCollection.is('.e, .f, .g')) {
    return 5000;
  }
  return 4000;
 }
 function fadeInOutNext(elementCollection) {
   elementCollection.delay(500).fadeIn(300).delay(getDelayForElement(elementCollection)).fadeOut(300, function() {
     const next = elementCollection.next();
     if (next) {
       fadeInOutNext(next);
     }
   });
 }
 $(document).ready(function() {
   $("button.button").click(function(){
     $("h1.about-title").fadeOut(300, fadeInOutNext.bind(null, $("div.b")));
   });
 });
/* ------------------------------THE RESET----------------------------*/

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  background-color: black;
}

ol,
ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/*-----------MY CODE-----------*/

* {
  font-family: Futura, Futura-Medium, "Futura Medium", "Century Gothic", CenturyGothic, "Apple Gothic", AppleGothic, "URW Gothic L", "Avant Garde", sans-serif;
  color: white
}

.frontpage {
  font-family: Futura, Futura-Medium, "Futura Medium", "Century Gothic", CenturyGothic, "Apple Gothic", AppleGothic, "URW Gothic L", "Avant Garde", sans-serif;
  text-transform: uppercase;
  letter-spacing: 8px;
  font-size: 3.5em;
  text-align: center;
  padding-top: 1.25em;
  z-index: 1;
  position: relative;
  color: white;
  text-shadow: 0 0 15px black;
}

.frontname {
  font-size: 2em;
  padding-bottom: .2em;
}

.navbar {
  font-family: Futura, Futura-Medium, "Futura Medium", "Century Gothic", CenturyGothic, "Apple Gothic", AppleGothic, "URW Gothic L", "Avant Garde", sans-serif;
  letter-spacing: 3px;
  background-color: #000;
  position: fixed;
  top: 0;
  width: 100%;
  color: white;
  margin: 0px;
  padding 0px;
}

.name {
  float: left;
  padding: 2em;
  text-transform: uppercase;
}

.links {
  float: right;
  text-decoration: none;
  color: white;
  padding: 2em .45em;
}

.list {
  font-size: .45em;
  list-style-type: none;
  text-decoration: none;
}

a {
  text-decoration: none;
}

.pagetitle {
  text-align: center;
  font-size: 3em;
  text-transform: uppercase;
  letter-spacing: 4px;
}

.SDmain {
  margin-top: 45px;
}

/*----------PAGE SPECIFIC STYLES-----------*/

.contactinfo {
  text-align: center;
  letter-spacing: px;
  font-size: 1.5em;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.contact-social-media-block {
  position: fixed;
  left: 50%;
  bottom: 0;
  transform: translate(-50%)
}

.sm {}

.contact-social-media {
  height: 8vh;
  width: 8vw;
}

.email-link {
  text-decoration: none;
}

.about-title {
  font-size: 10em;
  text-transform: uppercase;
  text-align: center;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.about-body {
  text-align: center;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 2em;
}

.b {
  display: none;
}

.c {
  display: none;
}

.d {
  display: none;
}

.e {
  display: none;
  font-size: 1.5em;
}

.f {
  display: none;
}

.g {
  display: none;
}

.h {
  display: none;
}

.article {
  color: white;
  width: 85%;
  margin: auto;
  margin-top: 1em;
}

.article-title {
  font-size: 1.75em;
  text-transform: uppercase;
}

.article-sub,
.article-date,
.port-sub {
  font-family: helvetica;
  font-style: italic;
}

.article-body,
.port-desc {
  text-indent: 1.75em;
  line-height: 1.2em;
}

.port-table {
  display: table;
  margin-top: 1.25em;
}

.port-row {
  display: table-row;
  margin-top: 1.25em;
}

.port-image {
  display: table-cell;
  float: left;
  width: 35%;
  margin: 0 2.5%;
}

.port-text {
  display: table-cell;
  float: right;
  width: 55%;
  margin: 0 2.5%;
}

.port-title {
  font-size: 2em;
  text-transform: uppercase;
}

/*-----------Animations and JQuery---------*/

.button {
  background-color: transparent;
  border: none;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  text-align: center;
  position: fixed;
  bottom: 5%;
  left: 50%;
  transform: translate(-50%)
}

.preopen {
  left: 150% !important;
}

.open {
  left: 50% !important;
}

.closed {
  left: -50% !important;
}

.transition {
  -webkit-transition: left 0.3s ease-out;
  -moz-transition: left 0.3s ease-out;
  -o-transition: left 0.3s ease-out;
  transition: left 0.3s ease-out;
}

.preopen2 {
  opacity: 0 !important;
}

.open2 {
  opacity: 1 !important;
}

.closed2 {
  opacity: 0 !important;
}

.transition2 {
  -webkit-transition: opacity 0.3s ease-out;
  -moz-transition: opacity 0.3s ease-out;
  -o-transition: opacity 0.3s ease-out;
  transition: opacity 0.3s ease-out;
}

#text1 {
  min-width: 67vw;
}

/*------------------FERNTS-----------------*/

@font-face {
  font-family: Futura;
  src: url(fonts/futuramedium.otf) format('opentype');
}

@font-face {
  font-family: Futura-Medium;
  src: url(fonts/futural-webfont.svg);
}

/*----------VIDJER---------*/

#myVideo {
  position: fixed;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  z-index: 0;
}

/*-----------MEDIA QUERIES-------------*/

@media all and (min-width: 1800px) {
  .frontname {
    font-size: 5em;
  }
  .list {
    font-size: 1em;
  }
  .break {
    display: none;
  }
  .contactinfo {
    font-size: 4em;
    letter-spacing: 6px;
  }
  .pagetitle {
    padding-top: 1em;
    font-size: 11em;
  }
  .navbar {
    font-size: 3em;
  }
  .about-title {
    font-size: 40em;
  }
  .port-row {
    font-size: 3em;
  }
  .article {
    font-size: 3em;
  }
}

@media all and (min-width: 1200px) and (max-width: 1799px) {
  .frontname {
    font-size: 3em;
  }
  .list {
    font-size: 1em;
  }
  .break {
    display: none;
  }
  .contactinfo {
    font-size: 2em;
    letter-spacing: 6px;
  }
  .pagetitle {
    padding-top: 1em;
    font-size: 5em;
  }
  .navbar {
    font-size: 1.4em;
  }
}

@media all and (min-width: 900px) and (max-width: 1199px) {
  .break {
    display: none;
  }
  .contactinfo {
    font-size: 1em;
    letter-spacing: 4px;
  }
  .pagetitle {
    padding-top: 1em;
    font-size: 4.5em;
  }
  .navbar {
    font-size: 1em;
  }
}

@media all and (min-width: 600px) and (max-width: 899px) {
  .frontname {
    font-size: 2em;
  }
  .list {
    font-size: .6em
  }
  .contactinfo {
    letter-spacing: 4px;
  }
  .pagetitle {
    padding-top: 1em;
    font-size: 4.5em;
  }
  .navbar {
    font-size: 1em;
  }
}

@media all and (max-width: 599px) {
  .frontname {
    font-size: 1.4em
  }
  .list {
    font-size: .6em
  }
  .contactinfo {
    font-size: 1em;
    letter-spacing: 2px;
  }
  .pagetitle {
    font-size: 3em;
  }
  .navbar {
    font-size: .5em;
  }
  .about-title {
    font-size: 4em;
  }
}

Hello

Welcome.
My name is Erik.
I enjoy Minimalism.

I made this happen with
Javascript and JQuery.

I like Java as well.
Programs just make sense to me.

I have made apps for android, websites for my friends, and I am looking for new projects.
You can find my other works in the Portfolio.

I write about my life occasionally. If that interests you, it drains out of my head into my Blog.

I am currently seeking my first job in Software Development.

My Resume can be found on the Contact page.

Thank you for reading.

  <button class="button" id="b"> Play </button>


Find values in list which sum to a given value within tolerance This is really a follow on from a question I asked earlier this year on Stack Overflow. I received a great answer to the following problem:

  I'm trying to code up something simple and pythonic to identify
  combinations of values from a list which sum to a defined value,
  within some tolerance.

  For example:

  if A=[0.4,2,3,1.4,2.6,6.3] and the target value is 5 +/- 0.5, then the
  output I want is (2,3), (1.4,2.6), (2,2.6), (0.4,2,3), (0.4,3,1.4)
  etc. if no combinations are found then the function should return 0 or
  none or something similar.

I implemented the suggestion in my code. However, the method has quickly become the performance limiting step in my code. It's fairly quick to run each iteration but it is being run many, many times.

Can you see any way to optimise this function or replace it with something much faster?

def findSum(self, dataArray, target, tolerance=0.5):
    for i in xrange(1, len(dataArray)+1):

        results = [list(comb) for comb in list(itertools.combinations(dataArray, i))
                   if target-tolerance < sum(map(float, comb)) < target+tolerance]

        if len(results) != 0:
            return results

In keeping the same algorithm, there's a bunch of extra work you're doing that's slowing you down. I am using the word slow loosely, since the one example you provided is still more or less instantaneous and the timings I performed were based on 100,000 runs.

Leave iterables alone

You wrap your combinations() call with list(). This means that you have to do actually create all the combinations up front, then iterate over them. But you never actually need all of them at once. You just need them one at a time. Changing your body to:

results = [list(comb) for comb in itertools.combinations(dataArray, i)
           if target-tolerance < sum(map(float, comb)) < target+tolerance]

drops runtime from 2.64s to 2.45s. Furthermore, comb is going to be a tuple, so that's fine as is too:

results = [comb for comb in itertools.combinations(dataArray, i)
           if target-tolerance < sum(map(float, comb)) < target+tolerance]

Down to 2.24s. Another 10%.

Building lists for no reason

Our numbers are already summable, no need to cast them to float first. You're making a whole bunch of extra lists that you're immediately discarding - just to be able to do a sum. But you can already do a sum:

results = [comb for comb in itertools.combinations(dataArray, i)
           if target-tolerance < sum(comb) < target+tolerance]

That alone brings us down to 1.10s. An enormous savings.

Comparisons

One comparison is faster than two comparisons, so let's just do the one:

results = [comb for comb in itertools.combinations(dataArray, i)
           if abs(sum(comb) - target) < tolerance]

Down to 1.04s.

What do you actually want

This doesn't yield all of the potential partial sums. It will yield some sums if any exist, and will return None otherwise - but it won't give you all of them. If you want all of them, you'll have to loop through all of the is. If you just want the first one, then this:

for i in xrange(1, len(dataArray)+1):
    for comb in itertools.combinations(dataArray, i):
       if abs(sum(comb) - target) < tolerance:
        return comb

just got reduced to 0.67s.

As Joe Wallis suggests, you probably want:

for i in xrange(1, len(dataArray)+1):
    for comb in itertools.combinations(dataArray, i):
       if abs(sum(comb) - target) < tolerance:
        yield comb

That way the caller can decide if one is sufficient or if all of them are needed.


Need help with valid knight moves in Chess Last weekend I was writing a short PHP function that accepts a starting move and returns valid knight squares for that move.

<?php

/* get's starting move and returns valid knight moves */

echo GetValidKnightSquares('e4');

function GetValidKnightSquares($strStartingMove) {

  $cb_rows = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8);
  $valids  = array(array(-1, -2), array(-2, -1), array(-2, 1), array(-1, 2), array(1, 2), array(2, 1), array(2, -1), array(1, -2));

  $row = substr($strStartingMove, 0, 1);
  $col = substr($strStartingMove, 1, 1);

  $current_row = $cb_rows[$row];
  if(!in_array($current_row, $cb_rows)) {
    die("Hey, use chars from a to h only!");
  }

  $current_col = $col;
  if($current_col > 8) {
    die("Hey, use numbers from 1 to 8 only!");
  }

  $valid_moves = '';

  foreach ($valids as $valid) {
    $new_valid_row = $current_row + $valid[0];
    $new_valid_col = $current_col + $valid[1];

    if(($new_valid_row <= 8 && $new_valid_row > 0) && ($new_valid_col <= 8 && $new_valid_col > 0)) {
      $row_char = array_search($new_valid_row, $cb_rows);
      $valid_moves .= $row_char . "$new_valid_col ";
    }
  }

  return "Valid knight moves for knight on $strStartingMove are: $valid_moves";
}

?>

Could you please take a look at it and share your thoughts about it?  The code can also be found here.

I was kinda 'criticized' about the code. One guy said it's messy, too long and not 'clever' enough. So I needed second opinion on it, a code review if you like. I think there is a place for improvement (always), but for me this was the first time I've coded something related with Chess. I've found something like this that caught my attention:

if ((abs(newX-currentX)==1 and abs(newY-currentY)==2) or (abs(newX-currentX)==2 and abs(newY-currentY)==1)) {
  /* VALID MOVE FOR A KNIGHT */
}
else {
  /* INVALID MOVE FOR A KNIGHT */
}

First of all, a function called GetValidKnightSquares shouldn't be translating chessboard locations. Any code that performs a distinct operation and can be named should be extracted into its own function. It makes everything much easier to read and understand. Name things.

Second, I would probably leverage whatever data structure you choose for your board to determine the valid moves on that board. The structure I'm going to choose looks like this:

-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, "8a", "8b", "8c", "8d", "8e", "8f", "8g", "8h", -1,
-1, "7a", "7b", "7c", "7d", "7e", "7f", "7g", "7h", -1,
-1, "6a", "6b", "6c", "6d", "6e", "6f", "6g", "6h", -1,
-1, "5a", "5b", "5c", "5d", "5e", "5f", "5g", "5h", -1,
-1, "4a", "4b", "4c", "4d", "4e", "4f", "4g", "4h", -1,
-1, "3a", "3b", "3c", "3d", "3e", "3f", "3g", "3h", -1,
-1, "2a", "2b", "2c", "2d", "2e", "2f", "2g", "2h", -1,
-1, "1a", "1b", "1c", "1d", "1e", "1f", "1g", "1h", -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1

It's a one-dimensional array that represents the ranks and files of the  two-dimensional board. The negative ones are there to pad the board and make it easier to detect when a piece has moved out of play. (We'll see this later.) This type of data structure is called a Mailbox (because some old-timer thought it looked like one, I guess) and it's very common in chess programming.

Here's how to generate it:

// converts an index in the mailbox into its corresponding value in algebraic notation
function i2an($i) {
    $files = "abcdefgh";
    return 10 - floor($i / 10) . $files[($i % 10) - 1];
}

function generateEmptyBoard() {
    $row = array();
    for($i = 0; $i < 120; $i++) {
        $row[] = ($i < 20 || $i > 100 || !($i % 10) || $i % 10 == 9)
            ? -1
            : i2an($i);
    }
    return $row;
}

This gives us the array we saw above. All that's left is to use it:

function knightMoves($square, $board) {
    $i = an2i($square);
    $moves = array();
    foreach(array(8, -8, 12, -12, 19, -19, 21, -21) as $offset) {
        $move = $board[$i + $offset];
        if ($move != -1) {
            $moves[] = $move;
        }
    }
    return $moves;
}

// converts a position in algebraic notation into its location in the mailbox
function an2i($square) {
    return (10 - $square[0]) * 10 + strpos("abcdefgh", $square[1]) + 1;
}

Notice that the mailbox's borders make it very easy to tell when we've moved to a position off the board.

Here are some examples:

$board = generateEmptyBoard();
print_r(knightMoves("1h", $board));
print_r(knightMoves("5b", $board));
print_r(knightMoves("6c", $board));

Output:

$ php knights.php
Array
(
    [0] => 2f
    [1] => 3g
)
Array
(
    [0] => 6d
    [1] => 4d
    [2] => 3a
    [3] => 7c
    [4] => 3c
    [5] => 7a
)
Array
(
    [0] => 5a
    [1] => 7e
    [2] => 5e
    [3] => 7a
    [4] => 4b
    [5] => 8d
    [6] => 4d
    [7] => 8b
)

What's cool is that you can use this mailbox throughout your entire application by substituting some representation of actual pieces for the location names in the inner elements. It's useful for more than just your narrow problem, in other words.


Expand spreadsheet ranges to lists of cells in Scala Problem

Spreadsheet cells are referenced by column and row identifiers. Columns are labeled with alphabetical characters, starting with "A", "B", "C", ...; rows are numbered from 1 in ascending order.  Write a function that takes in a string identifying a range of cells in a spreadsheet and returns an ordered list of cells which compose that range.

Example:

"A3:D5" -> ["A3", "A4", "A5", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4", "D5"]
"A3:D4" -> ["A3", "A4", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4"]

Here is scala implementation of the same ,

import scala.language.postfixOps

object PrintSpreadSheet extends App {

  val validAlphabets = ('A' to 'Z').toSeq

  def cells(range: String): Seq[String] = {
    val corners = (range split ":") flatMap { corner =>
      Seq(corner.head, corner.last)
    }
    val rows = (corners filter (r => validAlphabets.contains(r))) sorted
    val cols = (corners filter (c => !validAlphabets.contains(c))) sorted

    (rows.head to rows.last) flatMap { r =>
      (cols.head to cols.last) map { c =>
        r.toString + ":" + c.toString
      }
    }
  }
  cells("A1:D5") foreach println
}

I couldn't get your code to compile until I took out the sorted. The output was still good so I don't know what purpose it was supposed to serve.

There's no point in casting validAlphabets to a Seq[Char].  As a Range[Char] the contains() method still works. Better still would be to cast it to a Set[Char]. Then the syntax is more concise and the lookup is faster.

val rows = corners filter validAlphabets
val cols = corners filter (!validAlphabets(_))

Due to the use of .head and .last, this solution won't handle rows past 9. There are also a number of input errors that it won't catch. These can be addressed if you use a Regex to parse the input.

def cells(range: String): Seq[String] = {
  val format = "([A-Z])(\\d+):([A-Z])(\\d+)".r
  val format(colStart, rowStart, colEnd, rowEnd) = range

  for {
    c <- colStart.head to colEnd.head    //from String to Char
    r <- rowStart.toInt to rowEnd.toInt  //from String to Int
  } yield s"$c:$r"  //back to String
}

This will throw if the input string doesn't match the expected format. If you'd prefer it print the error and return nothing (an empty Seq[String]) then you can use a match statement instead, with a default case _ => for the format failure.

Notice that I use a for comprehension here. Whenever you see a map() inside a flatMap() that's a flag indicating that a for might do the same thing in a clearer/cleaner manner.


A Scala script for beautify scientific notation strings from Excel Excel renders scientific notation in the engineering fashion, e.g. “4.2E-5”. That’s OK, but when you are writing a scientific paper, it’s likely that you want it to look like this: “4.2×10⁻⁵”.

I have come up with a Scala script that does the job perfectly well:

import java.awt.Toolkit
import java.awt.datatransfer.{StringSelection, DataFlavor}

/**
 * Created by IDEA on 13/10/15.
 */
object Scientific {
  val superscriptMap = {
    var tmp = collection.mutable.Map(
      '0' -> '\u2070',
      '1' -> '\u00b9',
      '2' -> '\u00b2',
      '3' -> '\u00b3'
    )
    val x = ('4' to '9').zip('\u2074' to '\u2079').toList
    for ((k, v) <- x) {
      tmp.update(k, v)
    }
    tmp.toMap
  }
  type ExponentTuple = (Int, String)

  def dealWithSign(s: String): ExponentTuple = {
    if (s.head == '+') {
      (1, s.tail.dropWhile(_ == '0'))
    } else if (s.head == '-') {
      (-1, s.tail.dropWhile(_ == '0'))
    } else {
      (1, s)
    }
  }

  def snBeautify(s: String): String = {
    val s1 = s.split("[Ee]").take(2)
    require(s1.length == 2)
    val coefficient = s1(0)
    val (sign, exponent) = dealWithSign(s1(1))
    val part1 = coefficient + '\u00d7' + "10"
    val part2 = exponent.map(superscriptMap(_))
    // if the number is negative, provide a superscript minus
    if (sign < 0) part1 + '\u207b' + part2
    else part1 + part2
  }

  def snBeautify1(s: String): String = {
    s.split("\\s").map(snBeautify(_)).mkString("\n")
  }

  def snBeautify(printOut: Boolean = true): Unit = {
    val toolkit = Toolkit.getDefaultToolkit
    val clipboard = toolkit.getSystemClipboard
    val s1 = clipboard.getData(DataFlavor.stringFlavor).asInstanceOf[String]
    val s2 = snBeautify1(s1)
    val s2Select = new StringSelection(s2)
    if (printOut) println(s2)
    clipboard.setContents(s2Select, s2Select)
  }
}

object Test1 {
  //  val s = List("4.2E+5", "4.2e5", "4.2e-5", "4.2E-5", "-4.2e-5")
  //  s.map(snBeautify(_))
  //  snBeautify1(s.mkString("\n"))
  //  val s1 = "1.74E-11\n2.72E-12\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n6.42E-12\n7.13E-11\n4.02E-11\n7.84E-12\n5.87E-12\n1.55E-11\n1.07E-10\n1.04E-10\n3.81E-11\n4.46E-11\n4.46E-11\n4.46E-11\n4.46E-11\n1.23E-10\n2.45E-11\n8.24E-12"
  //  snBeautify1(s1)
  // Copy the cells you want to reformat first
  Scientific.snBeautify()
}

Not a native Excel solution, but at least Scala is much nicer than VBA.

You can copy the cells you want to reformat and then run the snBeautify function, the reformatted numbers now sits in the clipboard ready for you to paste into Excel or Word.

One advantage of this solution is that it's equally applicable to LibreOffice or OpenOffice.

You can also easily modify this into a shell script and bind it to a certain keyboard shortcut.

Any suggestion for improvement of any kind is welcome.

The code is OK, it looks quite readable, but still some things may be cleaned a bit.

Encapsulation

Members are public by default, so some of them should be hidden, since they do not seem (and do not need) to be used from outside: private val superscriptMap, private def dealWithSign.

Don't Use Mutable Collections

Scala favors immutability and using things from scala.collection.mutable should be justified. There is a simple way here to bypass the mutability by concatenation of two maps:

private val superScriptImmutable = Map(
  '0' -> '\u2070',
  '1' -> '\u00b9',
  '2' -> '\u00b2',
  '3' -> '\u00b3'
) ++ ('4' to '9').zip('\u2074' to '\u2079').toMap

Use Matchers

if.. else if.. else are too much from imperative style; matchers should be used instead:

private def dealWithSign2(s: String): ExponentTuple = {
  def dropZeros(str : String) = str.dropWhile(_ == '0')
  s.head match {
    case '+' => (1, dropZeros(s.tail))
    case '-' => (-1, dropZeros(s.tail))
    case _ => (1, s)
  }
}

Misc

There should be a general check for input data that the args contain numbers. I've tried to pass "test" string to snBeautify and it returned java.util.NoSuchElementException: key not found: s, which is not explicit from the user's point of view.

ExponentTuple type does not seem to be used elsewhere except in the optional return type declaration in dealWithSign function. The type and the declaration can be removed without any harm.

In snBeautify() functions, s1 and s2 should be renamed according to their meaning, something like original and beautified. I'd also suggest to extract clipboard operations into dedicated functions, for example:

private def getFromClipboard = {
  val clipboard = Toolkit.getDefaultToolkit.getSystemClipboard
  clipboard.getData(DataFlavor.stringFlavor).asInstanceOf[String]
}


Duplicate integers in an array Code shows duplicate values of integers in an array with indexes and the number of occurrences. Can you please critique my code and provide your thoughts on where I should improve my code?

import java.util.Set;
import java.util.HashMap;
import java.util.Map;
import java.util.HashSet;

public class DuplicatesInAnArray {

    private static class ShowIndexDuplicateData<T> {
        private static final String NEW_LINE = System
                .getProperty("line.separator");
        private Set<T> indices;
        private int count;

        public ShowIndexDuplicateData(Set<T> indices, int count) {
            this.indices = indices;
            this.count = count;
        }

        public Set<T> getIndices() {
            return indices;
        }

        public int getCount() {
            return count;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("Count: ").append(getCount()).append(" Indices: ")
                    .append(getIndices()).append(NEW_LINE);

            return sb.toString();
        }
    }

    public static void duplicatesInAnArray(Integer[] array) {
        if (array == null || array.length <= 1) {
            System.out.println("");
        }

        Map<Integer, ShowIndexDuplicateData<Integer>> map = new HashMap<>();

        for (int i = 0; i < array.length - 1; i++) {

            if (map.containsKey(array[i])) {
                ShowIndexDuplicateData<Integer> showIndexDuplicateData = map
                        .get(array[i]);
                showIndexDuplicateData.count++;
                showIndexDuplicateData.indices.add(i);
            } else {
                int count = 1;
                Set<Integer> indices = new HashSet<>();
                indices.add(i);
                ShowIndexDuplicateData<Integer> showIndexDuplicateData = new ShowIndexDuplicateData<>(
                        indices, count);
                map.put(array[i], showIndexDuplicateData);
            }
        }
        System.out.println(map);
    }

    public static void main(String[] args) {
        Integer[] array = { 5, 6, 1, 2, 3, 3, 6, 1 };
        DuplicatesInAnArray.duplicatesInAnArray(array);
    }
}

You don't need to use Set since indexes can never repeat.  Use a List isntead.
You don't need to keep track of the count.  You can just get indices.size().  That makes ShowIndexDuplicateData class unnecessary.
You probably should be dealing with int[] rather than Integer[].  There aren't many reasons to have a Integer[]

With that, you can really simplify this (using java 8):

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
.....

static final String FORMAT = "%s: count=%s, indices=%s%n";

public static void duplicatesInArray(int[] ary) {
    IntStream.range(0,ary.length).boxed()
            .collect(groupingBy(i -> ary[i], toList()))
            .forEach((num, lst) -> System.out.printf(FORMAT, num, lst.size(), lst));
}


File path unified in Windows/MacOS/Linux We are all tremendously happy about back slashes in Windows file systems and do not think that their sole purpose is to make life complicated for smart people who are capable of using different OS. Upvote if disagree [ :) ].

Converting paths from/to Windows backward slashes is a pretty monotonous task. Here is a library class to help with it. GitHub

OSPath path = @"/foo\bar.txt";

// Windows output
WriteLine(path);            // \foo\bar.txt
WriteLine(path.Windows);    // \foo\bar.txt
WriteLine(path.Unix);       // /foo/bar.txt

// MacOS output
WriteLine(path);            // /foo/bar.txt
WriteLine(path.Windows);    // \foo\bar.txt
WriteLine(path.Unix);       // /foo/bar.txt

It also helps converting between relative and absolute paths:

OSPath ap = "/foo/bar";
WriteLine(ap.Relative.Unix); // foo/bar
WriteLine(ap.Absolute.Unix); // /foo/bar

OSPath rp = "foo/bar";
WriteLine(rp.Relative.Unix); // foo/bar
WriteLine(rp.Absolute.Unix); // /foo/bar

And to perform path arithmetic (Windows output):

OSPath root = @"/foo\bar";
WriteLine(root + "file.txt");        // \foo\bar\file.txt
WriteLine(root + "file.txt" - root); // file.txt

Library class is:

public class OSPath
{
    public static readonly OSPath Empty = "";

    public static bool IsWindows => DirectorySeparatorChar == '\\';

    public OSPath(string path)
    {
        Path = path.Trim();
    }

    public static implicit operator OSPath(string path) => new OSPath(path);
    public static implicit operator string(OSPath path) => path.Normalized;
    public override string ToString() => Normalized;

    protected string Path { get; }

    public string Normalized => IsWindows ? Windows : Unix;
    public string Windows => Path.Replace('/', '\\');
    public string Unix => Volumeless.Path.Replace('\\', '/');

    public OSPath Relative => Volumeless.Path.TrimStart('/', '\\');
    public OSPath Absolute => IsAbsolute ? this : "/" + Relative;

    public bool IsAbsolute => IsPathRooted(Path);
    public bool HasVolume => IsAbsolute && Path[1] == ':';
    public OSPath Volumeless => HasVolume
        ? (this - GetPathRoot(Path)).Absolute
        : this;

    public OSPath Parent => GetDirectoryName(Path);

    public bool Contains(OSPath path) =>
        Normalized.StartsWith(path);

    public static OSPath operator +(OSPath left, OSPath right) =>
        new OSPath(Combine(left, right.Relative));

    public static OSPath operator -(OSPath left, OSPath right) =>
        left.Contains(right)
        ? new OSPath(left.Normalized.Substring(right.Normalized.Length)).Relative
        : left;
}

There are a couple of things that bother me:

1) I don't think you have properly implemented relative and absolute paths. At least in Windows: absolute path = working directory + relative path. Your class only does this conversion correctly, if working directory is root directory, which is almost never the case in .Net. I don't know how things are in Linux, but from Windows perspective this is a surprising behavior. It should be either well documented or fixed.

2) You assume that 1:1 two-way conversion always exists. But does it? Windows is not case sensitive, Linux is. Windows has one letter volumes, Linux does not. Those are just a few differences off the top of my head. You  can replace slashes all you want but that won't give you volume information.

3) How would you add macOS to current implementation? AFAIR, it is very much like Linux, but not exactly the same, is it? To me it looks like you would have to pretty much rewrite the entire thing. This is a good indication that overall design can be improved.


Is there a better way to create constants in javascript? Isn't there a better way to create my constants that I can use elsewhere in my code ?

export default class AppConstants {
}

Object.defineProperty(AppConstants, 'APP_NAME', { value: 'iVoc'})
/*
*...
*Other constants
*/

Class syntax should not be used for single instance (static) objects (really class should never be used). Use an Object literal and freeze it.

const AppConstants = Object.freeze({
   NAME : "iVoc",
   VERSION : "0.1B",
});


Importing modules for private use in Python There's something I completely dislike when importing a module in an interactive Python shell, typing the name of the module, hitting tab and getting the automatic completion cluttered with other modules that the module itself had imported (but are internal implementation details that are not really useful for me).

Example:

a.py

import os
import datetime

def foo():
    now = datetime.datetime.now()
    print os.path.join(map(str, (now.year, now.month, now.day)))

shell

$ ipython
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
Type "copyright", "credits" or "license" for more information.

IPython 5.5.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import a

In [2]: a.
           a.datetime a.py
           a.foo      a.pyc
           a.os

I don't care that module a depends on datetime and os, that is distracting me from what the module provides (foo).

So I have started to make my imports private, like this:

a.py

import os as _os
import datetime as _datetime

def foo():
    now = _datetime.datetime.now()
    print _os.path.join(map(str, (now.year, now.month, now.day)))

shell

$ ipython
iPython 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
Type "copyright", "credits" or "license" for more information.

IPython 5.5.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import a

In [2]: a.
           a.foo
           a.py
           a.pyc

Is this considered pythonic at all? I feel like it's a little bit too verbose, but I think simplifying the end user's experience should be above saving some extra tokens per import.

NO
This is not pythonic... and this is ugly... aaah, I can't get that code out of my head...
There is this thing called __all__
1. How does it work
Make a list, put everything you want to make public in it and boom, you're done.
2. What it doesn't do
You will still be able to do my_module.datetime if datetime is imported in my_module
3. What does it do
When you do from my_module import *, it doesn't import datetime.  Autocomplete will use __all__ if it exist.
4. What are some great conventions that goes with this
You can put it in the __init__.py if it exists
5. Show me
Numpy uses the warning module but it doesn't pollute your namespace.
>>> import numpy
>>> 'warnings' in dir(numpy)
True
>>> 'warnings' in numpy.__all__
False
>>> from numpy import *
>>> warnings
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'warnings' is not defined

Update:
Every autocomplete in the world* uses __all__ except ipython which uses "some custom logic"(github issue). So I believe the most pythonic solution is go complain on the github issue.
*extrapolation of "the editors I use"


Vectorized crosstabulation in Python for two arrays with two categories each I have two Python lists, label and presence. I want to do cross-tabulation and get the count for each block out of four, such as A, B, C, and D in the below code.

Both the lists have values True and False.
I have tried Pandas' crosstab function. However, it's slower than my code which is below.
One problem with my code is it's not vectorized and is using a for loop which slows things down.

Could the below function in Python be made any faster?
def cross_tab(label,presence):
    A_token=0
    B_token=0
    C_token=0
    D_token=0
    for i,j in zip(list(label),list(presence)):
        if i==True and j==True:
            A_token+=1
        elif i==False and j==False:
            D_token+=1
        elif i==True and j==False:
            C_token+=1
        elif i==False and j==True:
            B_token+=1
    return A_token,B_token,C_token,D_token

Some sample data and example input and output.
##input
label=[True,True,False,False,False,False,True,False,False,True,True,True,True,False]
presence=[True,False,False,True,False,False,True,True,False,True,False,True,False,False]

##processing
A,B,C,D=cross_tab(label,presence)
print('A:',A,'B:',B,'C:',C,'D:',D)

##Output
A: 4 B: 2 C: 3 D: 5

Edit: Answer provided by Maarten Fabre below is working perfectly. To anyone who will stumble here in future, the logic flow is as follows.
Goal: find a way for vectorization: Below are the solution steps

Analyze and find unique value at each evaluation. This will help save logical output in single array.
By multiplying 2 with any given array and adding resultant array with other array we can get results in single array with unique coded value for each logic.
Get count of the unique element in array and fetch values.
Since calculation can be done in arrays without loop, convert list into np array to allow vectorized implementation.

Algorithm
If you look at your code, and follow the if-elif part, you see that there are 4 combinations of i and j

i      j     : result
True,  True  : A
False, True  : B
True,  False : C
False, False : D

If you use the tuple (i, j) as key, you can use a dict lookup
{
    (True, True): "A",
    (False, True): "B",
    (True, False): "C",
    (False, False): "D",
}

Or simpler:
{
    (True, True): 3,
    (False, True): 1,
    (True, False): 2,
    (False, False): 0,
}

The choice of numbers is deliberate, since when you use True as 1 and False as 0, you can do
def crosstab2(label, presence):
    for i, j in zip(label, presence):
        yield i * 2 + j

c = collections.Counter(crosstab2(label, presence))
print('A:',c[3],'B:',c[1],'C:',c[2],'D:',c[0])

This is not faster than your original solution, but this is something you can vectorize
label = np.array([True, True, False, False,False, False,True, False, False, True, True, True, True, False])
presence = np.array([True, False, False, True, False, False, True, True, False, True, False, True, False, False])
c = collections.Counter(label * 2 + presence)
print('A:',c[3],'B:',c[1],'C:',c[2],'D:',c[0])

Which is significantly faster, even if you account for the few seconds of overhead for the creation of the numpy arrays
Formatting
Try to follow pep8.

spaces around operators (=, +, ...)
spaces after a ,

naming
I try to give collections of elements a plural name. In this case, I would use labels., so if you ever need to iterate over them, you can do for label in labels, which is a lot more clear than for i in label:
list
The extra call to list in  zip(list(label),list(presence)) is not necessary. zip takes any iterable, and doesn't modify it in place.


Capturing clicks on list items I am using jQuery's collapsible lists grouped and named #List01, #List02, #List03, etc. My code captures clicks on list elements and remembers list items' ID for further processing. Each group has identically looking code so I was wondering how I could encapsulate it in one function.

$(document).on('click', '#List01 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});
$(document).on('click', '#List02 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});
$(document).on('click', '#List03 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});

$(document).on('click', '#List01 li, #List02 li, #List03 li', function () {
        var anchor = $(this).find('a');
        sessionStorage.KenID = anchor.attr('id');
        changePage();
});

The , should do the trick.


Showing the minimum of letters needed for a palindrome This shows the minimum of letters needed for a palindrome.  It needs tweaking since it works fine for words 1-9 characters, but becomes slow for words with 10-12 characters, and for 13+ characters it really takes a lot of time. Any help is appreciated.

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <malloc.h>

typedef struct _el {
    char ch;
    struct _el* next;
} lst;

typedef struct _lst {
    char* string;
    struct _lst* next;
} elmt;

char* _remove(char*, int);
int min(int , int);
elmt* _ncptr(char [], int, elmt*, int );
int minfinal(char [], int, int );
elmt* _add(elmt* root, elmt* elm);
int _count(elmt* root);
int _last_p(elmt* root);
int ispnd(char [], int);
int __exist (elmt* root, char* str, int h);
int max(int, int);
lst* add(lst* root, char n);
int exist(lst* root, char n);

int main() {
    int l, min;
    char b[50];
    printf("Insert the word:");
    scanf("%s", b);
    l = strlen(b) - 1;
         printf("%d letters needed.\n", minfinal(b, 0, l));
    _getch();
    return 0;
}

int min(int a, int b) {
    return ((a>b) ? b : a);
}

elmt* _ncptr(char v[], int quant, elmt* root, int count) {
    int cnt_, lvar;
    int len = strlen(v)-1;
    if(!root) {
        root = (elmt*)malloc(sizeof(elmt));
        root->string = (char*)malloc(len+1);
        strcpy(root->string, v);
        root->next = '\0';
    }
    if(quant == 0) return root;
    if(count > 0) {
        int i;
        elmt *n_el, *tmp = root;
        i = 0;
        while(i < count) {
            int j;
            j = 0;
            for(j = 0; j < strlen(tmp->string); j++) {
                n_el = (elmt*)malloc(sizeof(elmt));
                n_el->string = _remove(tmp->string, j);
                n_el->next = '\0';

                if(__exist(root, n_el->string, i+j+1)) continue;
                root = _add(root, n_el);
            }
            tmp = tmp->next;
            i++;
        }
        return( _ncptr( v, quant-1, root, _count(root)-count ) );
    }
    else {
        //MAYBE IT's FIRST CALL OF THE FUNCTION
        int i,j;
        elmt* n_el;
        i = strlen(v);
        for(j = 0; j < i; j++) {
            n_el = (elmt*)malloc(sizeof(elmt));
                n_el->string = _remove(v, j);
                n_el->next = '\0';
                root = _add(root, n_el);
        }
        return( _ncptr( v, quant-1, root, _count(root) ) );
    }
}

char* _remove(char* str, int i) {
    int j,k;
    char* nstr = (char*)malloc(strlen(str));
    nstr[0] = '\0';
    for(j = 0, k = 0; j < strlen(str); j++) {
        if(j == i) { continue; }

        nstr[k] = str[j];
        k++;
    }
    nstr[k] = '\0';
    return nstr;
}

elmt* _add(elmt* root, elmt* elm) {
    elm->next = root;
    return elm;
}

int _count(elmt* root) {
    long int l_var;
    for( l_var = 0; root && root->string; l_var++, root=root->next );
    return l_var;
}

int minfinal(char v[], int n, int i) {
    elmt* g = NULL;
    if(ispnd(v, i)) return 0;

    g = _ncptr(v, i, g, 0);

    return( strlen(v) - _last_p(g) );
}

int ispnd(char v[], int z) {
    int i, j, k;
    k = 0;
    for(i = 0, j = z; i < j; i++, j--) {
        if(v[i] != v[j]) {
            k = 1;
            break;
        }
    }
    return !k;
}

int _last_p(elmt* root) {
    int l_var = 0;
    for(; root; root=root->next ) {
          if(strlen(root->string) == 0) continue;
        if(!ispnd(root->string, strlen(root->string)-1)) continue;
        l_var = max( l_var, strlen(root->string) );
    }
    return l_var;
}

int __exist (elmt* lstt, char* str, int h) {
    int i,j;
    for(j=0; lstt, j <= h; lstt = lstt->next, j++ ) {
        i = strcmp(lstt->string, str);

        if(!i) return 1;
    }
    return 0;
}

int max(int a, int b) {
    return (a > b ? a : b );
}

This is an obvious candidate: (there are more lines containing this anti-pattern):

for(j = 0, k = 0; j < strlen(str); j++) {...}

Will result in the strlen being called on every iteration, nmaking the whole thing an O(N*N) operation.

A better way to do the same would be:

size_t len,j,k;

len = strlen(str);
for (j=k=0; j < len;j++) {...}

Next:

char* _remove(char*, int);
elmt* _ncptr(char [], int, elmt*, int );
elmt* _add(elmt* root, elmt* elm);
int _count(elmt* root);
int _last_p(elmt* root);
int __exist (elmt* root, char* str, int h);

Identifiers with leading underscores are reserved for the implementation and / or the library.

In short: don't use them (unless you are implementing the implemnetation or the library, but in that case you would not ask this question, methinks)

Next: the _remove function is terrible. I malloc() one byte too short, calls strlen() at every heartbeat, and ignores the existing string functions.

char *newremove(char *org, size_t pos) {
    size_t len;
    char *new;

    len =  strlen(org)
    new = malloc(1+len);

    if (pos < len) {
      memcpy(new, org, pos);
      memcpy(new+pos,org+pos+1, len-pos);
      }

    else {
      memcpy(new, org, len+1);
      }

return new;

}


Enhanced Hashmap - Add a number to all keys/values I had the below problem in a coding test and I got 28/30 tests passes and 2 failed due to a time-out.

Problem You have created a programming language and now you have decided to add hashmap support to it. It was found that in
common programming languages, it is impossible to add a number to all
hashmap keys/values. So, you have decided to implement your own
hashmap in your new language with following operations.

insert x y - insert and object with key x and value y
get x - return the value of an object with key x
addToKey x - add x to all keys in map
addToValue y - add y to all values in map

Your task is to implement this hashmap, apply the given queries, and
to find the sum of all the results for get operations

For Example

For queryType=["insert","insert","addToValue","addToKey","get"] and query=[[1,2],[2,3],[2],[1],[3]], the output should be hashMap(queryType,query)=5.

Explanation

insert 1 2 - hashmap will be {1:2}
insert 2 3 - hashmap will be {1:2,2:3}
addToValue 2 - hashmap will be {1:4,2:5}
addToKey 1 - hashmap will be {2:4,3:5}
get 3 - value is 5

Input/Output

[execution time limit] 3 seconds (Java)
[input] array.string queryType
Array of query types. its is guaranteed that each queryType[i] any one of the above mentioned operation
1<=queryType.length<=10^5
[input] array.array.integer query
Array of queries, where each query is mentioned by 2 numbers for insert and one number for others
Key values are in range [-10^9,10^9]

Below is my solution in Java
long hashMap(String[] queryType, int[][] query) {
        long sum = 0;
        Integer currKey = 0;
        Integer currValue = 0;
        Map<Integer, Integer> values = new HashMap<>();
        for (int i = 0; i < queryType.length; i++) {
            String currQuery = queryType[i];
            switch (currQuery) {
            case "insert":
                HashMap<Integer, Integer> copiedValues = new HashMap<>();
                if (currKey != 0 || currValue != 0) {
                    Set<Integer> keys = values.keySet();
                    for (Integer key : keys) {
                        copiedValues.put(key + currKey, values.get(key) + currValue);
                    }
                    values.clear();
                    values.putAll(copiedValues);
                    currValue = 0;
                    currKey = 0;
                }
                values.put(query[i][0], query[i][1]);
                break;
            case "addToValue":
                currValue += values.isEmpty() ? 0 : query[i][0];
                break;
            case "addToKey":
                currKey += values.isEmpty() ? 0 : query[i][0];
                break;
            case "get":
                copiedValues = new HashMap<>();
                if (currKey != 0 || currValue != 0) {
                    Set<Integer> keys = values.keySet();
                    for (Integer key : keys) {
                        copiedValues.put(key + currKey, values.get(key) + currValue);
                    }
                    values.clear();
                    values.putAll(copiedValues);
                    currValue = 0;
                    currKey = 0;
                }
                sum += values.get(query[i][0]);
            }
        }
        return sum;
    }

Is there any other data structure I can use instead of hashmap or Can I improve my code to be more linear?

I would suggest you create your own OffsetIntegerMap that can map between integers and handle an offset on the keys and values.
You don't necessarily have to implement the HashMap from scratch, define your own limited interface and implement it with an existing Map<Integer, Integer> through composition.
By handling the offsets separately from the keys and values the complexity of the offset operations end up O(1) instead of O(n) when doing recalculations and the Map<> put and get operations stay at their original O(1).
An example an "OffsetIntegerMap":
import java.util.HashMap;
import java.util.Map;

public class OffsetIntegerMap {
    private final Map<Integer, Integer> actualMap;
    private int keyOffset = 0;
    private int valueOffset = 0;

    public OffsetIntegerMap() {
        actualMap = new HashMap<>();
    }

    public int size() {
        return actualMap.size();
    }

    public boolean isEmpty() {
        return actualMap.isEmpty();
    }

    public boolean containsKey(int key) {
        var keyWithoutOffset = key - keyOffset;
        return actualMap.containsKey(keyWithoutOffset);
    }

    public boolean containsValue(int value) {
        var valueWithoutOffset = value - valueOffset;
        return actualMap.containsValue(valueWithoutOffset);
    }

    public Integer get(int key) {
        var keyWithoutOffset = key - keyOffset;
        var value = actualMap.get(keyWithoutOffset);
        if (value == null) return null;
        return value + valueOffset;
    }

    public Integer put(int key, int value) {
        var keyWithoutOffset = key - keyOffset;
        var valueWithoutOffset = value - valueOffset;
        var oldValue = actualMap.put(keyWithoutOffset, valueWithoutOffset);
        if (oldValue == null) return null;
        return oldValue + valueOffset;
    }

    public Integer remove(int key) {
        var keyWithoutOffset = key - keyOffset;
        var oldValue = actualMap.remove(keyWithoutOffset);
        if (oldValue == null) return null;
        return oldValue + valueOffset;
    }

    public void clear() {
        actualMap.clear();
        keyOffset = 0;
        valueOffset = 0;
    }

    public int getKeyOffset() {
        return keyOffset;
    }

    public void setKeyOffset(int keyOffset) {
        this.keyOffset = keyOffset;
    }

    public int getValueOffset() {
        return valueOffset;
    }

    public void setValueOffset(int valueOffset) {
        this.valueOffset = valueOffset;
    }

    public void addToValues(int toAdd) {
        this.valueOffset += toAdd;
    }

    public void addToKeys(int toAdd) {
        this.keyOffset += toAdd;
    }
}

By encapsulating the offset logic the processing loop also becomes much simpler without refactoring much of anything:
static long hashMap(String[] queryType, int[][] query) {
    long sum = 0;
    var map = new OffsetIntegerMap();
    for (int i = 0; i < queryType.length; i++) {
        String currQuery = queryType[i];
        switch (currQuery) {
            case "insert":
                map.put(query[i][0], query[i][1]);
                break;
            case "addToValue":
                map.addToValues(query[i][0]);
                break;
            case "addToKey":
                map.addToKeys(query[i][0]);
                break;
            case "get":
                sum += map.get(query[i][0]);
        }
    }
    return sum;
}


Multi-threaded LinkedList Implementation I am learning to write a multi-threaded linked list class implementation with basic functionality such as push to front or back, pop_back and read. I came up with this implementation:

#include <iostream>
#include <thread>
#include <mutex>
std::mutex m;
template<class T>
class Node{
    public:
    T data;
    Node* next;
    Node(T data):data(data),next(NULL){}
};
template<class T>
class List{
  Node<T> *head;
  public:
  List():head(NULL){}
  List(const List<T>&)=default;               //default copy constructor
  List& operator =(const List<T>&)=default;   //default assignment
  List(List<T>&&)=default;                    //default move constructor
  List& operator =(List<T>&&)=default;        //default move assignment
  void push_front(T val){                    //push data to front
    std::lock_guard<std::mutex> lock(m);
    Node<T>* temp=new Node<T>(val);
      if(head==NULL)
        head=temp;
      else{

          temp->next=head;
          head=temp;
      }
  }
  void pop_back(){                      //pop from back
      std::lock_guard<std::mutex> lock(m);
      Node<T>* cur=head;
      while(cur->next->next)
      cur = cur->next;
      Node<T>* temp=cur->next;
      delete(temp);
      cur->next=NULL;
  }
  T front(){                 //return front of Linkedlist
      if(head!=NULL)
      return head->data;
      return -1;
  }
  void push_back(T val){                    //push at back
      std::lock_guard<std::mutex> lock(m);
      Node<T>* temp=new Node<T>(val);
      if(head==NULL)
        head=temp;
      else{
          Node<T>* cur=head;
          while(cur->next)
          cur = cur->next;
          cur->next=temp;
      }
  }
  int size(){               //return size
      int size=0;
      Node<T>* cur=head;
      while(cur){
        size++;
        cur=cur->next;
      }
      return size;
  }
  void display(){            //read from linked list
      std::lock_guard<std::mutex> lock(m);
      Node<T>* cur=head;
      while(cur){
          std::cout<<cur->data<<" ";
          cur = cur->next;
      }
      std::cout<<"\n";
  }
  ~List(){
    Node<T>* current = head;
    Node<T>* next;
    while (current != NULL) {
        next = current->next;
        delete current;
        current = next;
    }
  }
};

But, I am not very sure if I covered it right. Please share some opinions on how to make it perfect.
Also, I am targeting C++11, so please throw some pointers/suggestions in that area also.

In particular, I am looking for is answers to these questions:

Is this a correct approach for acquiring mutex in push() and display(), in a multi-threaded environment?
How can I prioritize the read/delete/write operations. For example, suppose 1 thread is displaying the data and another thread comes which wants to pop_back from the data. How do I make the changes so that my 2nd thread gets the priority while 1st thread was using my node.
I have not much worked with C++11 — I just started it few months ago — so I would like to know what more I should have in my class.
In case there are any possible bugs in this code, please let me know that too.

About the code:

List& operator =(const List<T>&)=default; and List(const List<T>&)=default; provide excellent opportunity to get double delete with 100% chance of success.
Your linked list required data to be copyable and it copies it on usage. It is bad, since now you cannot store data like std::unique_ptr that are not copyable. Also it is inefficient as it will have to copy large data structures like std::vector instead of moving their internal data around. Utilize std::move in functions like push_back/push_front.
Functions front()/back() should return data by reference so user can modify them. Also you ought to implement their const versions that return data by const reference (or by value for trivial enough data types).
std::list stores also the size of the list so the function call is lazy unlike your implementation. People generally assume that size() is a fast operation which is not the case in your implementation.
Normally in a linked-list you store both head and tail as otherwise all operations regarding the other end are ridiculously slow.
std::cout is not exactly thread safe. It doesn't crash or cause malfunctions but it might can mingle the characters you print. In a multi-threaded environment you need a logger.
Wait... your linked-list doesn't provide any options for iterating over elements. Only adding / deleting / exploring elements at the head/tail and even those are slow. You need iterators or something. One important aspect of a linked list is ability to move elements from one list to another efficiently. This functionality doesn't exist in this implementation.
Your mutex m is shared across all your linked lists-instances and types. If you want any sensible implementation of multi-threaded linked with mutexes list you ought to privately store a std::unique_ptr<std::mutex> for each instance of the linked-list.
Honestly, I don't know why you want to use a linked list or implement one - it is one of the slowest and most inefficient data structures.

In general, I don't think that it is a good idea to make a thread-safe linked-list. Make a concurrent linked-list at most I'd say (I not too familiar on this topic as far as I am aware it is still being researched). Just use std::list and have an associated mutex nearby so whenever user wants to do something with the list - they have to lock the mutex. It might be annoying to write and relying on the user to use it right is problematic but frequently user needs to make composite operations (several in a row without interruptions) which will result in program errors if another users locks the list in between these operations and does something with it.