texts: How can I improve my Java MethodPointer?

texts:
This was just an experiment to see if I could replicate something like C++ function pointers in Java.  Basically, the idea was to have an object which represented a method call, and when you call .invoke() on that object, the method would run.

It feels a little sloppy to me, and I feel like there may be some tricks of Reflection and Generics that would make the code more elegant/usable which I haven't thought of or am not aware of.  Any tips or tricks?

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.jpgohlke.util.logging.LogUtil;

public class MethodPointer<T, R> {

    //Logger instance
    private static final Logger LOGGER = Logger.getLogger(MethodPointer.class);

    //Object fields
    private final Method method;
    private final Class<R> returnClass;
    private ArrayList<Object> args = new ArrayList<Object>();
    private T object = null;

    //Constructors
    public MethodPointer(Method method, Class<R> returnClass) {
        this.method = method;
        this.returnClass = returnClass;
    }

    public MethodPointer(Class<T> clazz, T object, String methodName, Class<R> returnClass, Class<?> ... paramClasses) {
        Method theMethod = null;
        try {
            theMethod = clazz.getMethod(methodName, paramClasses);
        }
        catch(NoSuchMethodException nsme) {
            LogUtil.log(LOGGER, Level.ERROR, "Unable to find method " + methodName + " in " + clazz.getSimpleName(), nsme);
            throw new IllegalArgumentException("Method signature does not exist in " + clazz.getSimpleName());
        }
        method = theMethod;
        this.object = object;
        this.returnClass = returnClass;
    }

    public MethodPointer(Class<T> clazz, String methodName, Class<R> returnClass, Class<?> ... paramClasses) {
        this(clazz, null, methodName, returnClass, paramClasses);
    }

    //Accessors and mutators
    public Method getMethod() {
        return method;
    }

    public Class<R> getReturnClass() {
        return returnClass;
    }

    public Object[] getArguments() {
        return args.toArray();
    }

    public void setArguments(Object ... args) {
        this.args = new ArrayList<Object>(Arrays.asList(args));
    }

    public void setArguments(ArrayList<Object> args) {
        this.args = args;
    }

    public T getObject() {
        return object;
    }

    public void setObject(T object) {
        this.object = object;
    }

    //Invoking the method
    public R invoke() throws Exception {

        if(Modifier.isStatic(method.getModifiers())) {
            object = null;
        }
        else if(object == null) {
            LOGGER.error("An object must be provided to invoke a non-static method upon.");
            throw new IllegalArgumentException("An object must be provided to invoke a non-static method upon.");
        }

        try {
            Object returnValue = method.invoke(object, args.toArray());
            if(returnClass.isInstance(returnValue)) {
                return returnClass.cast(returnValue);
            }
            else {
                LOGGER.error("Unable to return value from method invocation; the object is not an instance of " + returnClass.getSimpleName());
                return null;
            }
        }
        catch(Exception e) {
            LogUtil.log(LOGGER, Level.ERROR, "Unable to invoke method " + method.getName(), e);
            throw e;
        }
    }

    public R invoke(Object ... args) throws Exception {
        this.args.addAll(Arrays.asList(args));
        return invoke(returnClass);
    }

}


texts: Counting occurrences of "A…Z" substrings

texts:
I'm trying to write code in the simplest and cleanest way possible. I've found a few ways to shorten and simplify my code through functions that I've never seen before or through using other methods. I'd like to expand my knowledge on writing code using various (but simple) methods, and also expand my function 'vocabulary'.

What I mainly want to know is if there are other ways of writing the for loop such that it is much easier to read, and is shorter and simpler. Just yesterday I found out that the enumerate function exists, which made my life so much easier! :)

On to the question-

Substring Counter:
(I thought of this function as a programming challenge for myself)

A function that takes in a string and returns the amount of times 'A' ends with 'Z'. MUST ONLY CONTAIN 1 LOOP. Not sure how to explain these, but here are examples:
substring_counter(string)
It is assumed that the input is a string and that all characters are alphabetical and capital. I know I can put checks for all these but I'm mainly focusing on the logical way the code is written.

substring_counter('AZAAZ')
> 4

'AZAAZ' has 4 instances where it starts with 'A' and ends with 'Z'.

'AZAAZ'

'AZAAZ'

'AZAAZ'

'AZAAZ'

substring_counter('AZZ')
> 2

'AZZ' has 2 instances where it starts with 'A' and ends with 'Z'.

'AZZ'
'AZZ'

1st method (using slicing):

def substring_counter(string):
    counter = 0
    for num, x in enumerate(string):
        if x == 'A':
            if  string[num:].find('Z') != -1:
                counter += string[num:].count('Z')
    return counter

2nd method (using counters):

def substring_counter(x):
    counter=0
    word = 0
    for i in x:
        if(i == 'A'):
           word += 1
        elif(i == 'Z'):
           counter += word
    return counter

Which method is more understandable, or simpler? Which one should I be using?


texts:
My team is writing software to be able to grade a basic skills in word/excel/powerpoint test. We are trying to figure out the best way to verify that they included a correct image in their word doc. We know how to get the image file that they use through the xml of the word file. The problem is when we want to verify that the image is the one we expect to be there. Right now we are using the hash_file function in php:

//we know this is the correct hash for the image
$img_hash_correct = 'ab9df995315e2c5cbd0d5cf2210410afa44958c3ca55147497c7a6761340e058';

$hashed_file_submitted = hash_file("sha256", 'hashtest/word/media/image2.jpg');

if ($hashed_file_submitted == $img_hash_correct) {
   echo 'same image!   ';
} else {
   echo 'these are not the same   ';
}

This code has worked after doing some testing. Is this a reliable way to verify that a submitted image is what we are looking for, or is there a more reliable way that you know of?


texts: Algorithm maths quiz + write to a text file

texts:
Are there any ways I can clean this code up to make it more user-friendly?

import random #Random Function
import os

print("What is your name?") #Asking User Name
name = input().title() #.title() capitilises the first letter in each word, so when the name is printed in later code the first letter will always be capitilised.
class_name = input("Which class do you wish to input results for? ")
print (name, ", Welcome to the OCR Controlled Assessment Maths Test")
score = 0  #Set Score to 0
question = 0 #Set Question Number to 0
while question < 10: #After 10 Questions, it will stop asking the user questions.
    operator = random.randint(1,3)#Addition,Multiplication,Subtraction
    num1 = random.randint(1,25)#Random Number between 1 and 10 to be used in the questions
    num2 = random.randint(1,25)#Random Number between 1 and 10 to be used in the questions
    if operator == 1: #If Random Operator = 1, it will ask addition questions
        print("What is", num1, "+", num2)
        ans = num1 + num2

    elif operator == 2:#If Random Operator = 2, it will ask multiplication questions
        print("What is", num1, "*", num2)
        ans = num1 * num2

    else: #If Random Operator = 3/Else, it will ask subtraction questions.
        print("What is", num1, "-", num2)
        ans = num1 - num2

    while True:
      try:
        user_ans = int(input()) #The Answer the user inputs to the question asked
      except ValueError: #When anything but a interger is inputted.
        print ("That is not a valid answer")
        continue #Dosen't print Invalid Code Error
      else:
        break

    if user_ans == ans: #If user answer matches that of the question
        print("Correct")
        score += 1

    else: #If user answer dosen't match that of a question.
        print("Incorrect")

    question += 1 #When a question is answered, it will +1 until it equals 10 at which point it will stop.

print("Well done", name, "you scored", score, "/10") #Print Final Score out of 10

class_name = class_name + ".txt"    #adds '.txt' to the end of the file so it can be used to create a file under the name a user specifies

file = open(class_name , 'a')   #opens the file in 'append' mode so you don't delete all the information
name = (name)
file.write(str(name + " : " )) #writes the information to the file
file.write(str(score))
file.write('\n')
file.close()    #safely closes the file to save the information

viewscore = input("Do you wish to view previous results for your class").lower()

if viewscore == "yes".lower():
    f = open(class_name, 'r')
    file_contents = f.read()
    print (file_contents)
    f.close()

elif viewscore != "yes".lower():
    print ("Press any key to exit")
    ex = input ("")
    os._exit(0)


texts: Prevent recursive calls in WinForm event handlers

texts:
Changing TextBox.Text within the TextBox.TextChanged event can trigger a
recursive call to the same event handler. My class EventHelper is designed
to separate the action performed in the event handler from the mechanism that
prevents the recursive calls. The calls can be used as in:

public static class EventHelperTest
{
    public static void ExampleUsage()
    {
        var eventHelper = new EventHelper();

        var textBox = new TextBox();
        textBox.TextChanged += (s, e) => eventHelper.ExecuteOnce(() =>
        {
            textBox.Text = textBox.Text + "a";
        });

        textBox.Text = "trigger ";

        Debug.Assert(textBox.Text == "trigger a");
    }
}

where the EventHelper is:

public class EventHelper
{
    bool skip;

    public void ExecuteOnce(Action f)
    {

        if (skip)
            return;

        skip = true;
        f();
        skip = false;
    }
}

I am looking for a review of the EventHelper class.


texts: URL selection function that is designed to randomly assign users to different surveys until full

texts:
I'm trying to condense some of my code to make it more maintainable and to learn a few new tricks.

Below is a Python 2.7 / Django 1.6 function which is designed to assign users to one of three surveys in my application. I require a total of 30 responses in total, 10 each. Each user is to be assigned at random to one of the three surveys to complete, once a survey e.g. SurveyTwo has had 10 participants it is taken out of the selection pool.

The function returns a segment of the URL which is then used to update a button

START

My below code works fine, but in reality I have nine such paths and I am looking to improve on my implementation method.

Also, please suggest any tips on styling or techniques.

PathMax = 10
TotalMax = 30
TotalMaxCounter = 0
SurveyWizardOneCounter = 0
SurveyWizardTwoCounter = 0
SurveyWizardThreeCounter = 0
SurveyWizardFourCounter = 0

SURVEY_URLS = ['/surveyone/', '/surveytwo/', '/surveythree/']

def start(request):
    global TotalMaxCounter
    if TotalMaxCounter < TotalMax:

        survey_url = random.choice(SURVEY_URLS)

        if survey_url == '/surveyone/':
            print 'SurveyWizardOneCounter is: %s TotalMaxCounter is: %s' % (SurveyWizardOneCounter, TotalMaxCounter)
            if SurveyWizardOneCounter > PathMax:
                SURVEY_URLS.pop(0)

        elif survey_url == '/surveytwo/':
            print 'SurveyWizardTwoCounter is: %s TotalMaxCounter is: %s' % (SurveyWizardTwoCounter, TotalMaxCounter)
            if SurveyWizardTwoCounter > PathMax:
                SURVEY_URLS.pop(1)

        elif survey_url == '/surveythree/':
            print 'SurveyWizardThreeCounter is: %s TotalMaxCounter is: %s' % (SurveyWizardThreeCounter, TotalMaxCounter)
            if SurveyWizardThreeCounter > PathMax:
                SURVEY_URLS.pop(2)

        return render(request, 'start.html', {'survey_url': survey_url})
    else:
        return render(request, 'surveyfull.html')


texts: Should I put python3 argparse filetype objects in a contextlib stack?

texts:
I just read the Lib/argparse.py code (class FileType) on http://hg.python.org/cpython/file/default/Lib/argparse.py. File objects are opened without the with statement. For safe file opening/closing, should I instead encapsulate my argparse.ArgumentParser() in a contextlib stack like below? I feel very stupid for asking a question like this, but I am very much in doubt about the proper procedure.

import argparse
import contextlib
import gzip
import os
import fileinput
import sys

def main():

    with contextlib.ExitStack() as stack:
        input = argparse(stack)
        process_arguments(input)

def argparse(stack):

    parser = argparse.ArgumentParser()
    parser.add_argument('--input', default=[sys.stdin], nargs='+')
    d_args = vars(parser.parse_args())
    if d_args['input'] != [sys.stdin]:
        input = stack.enter_context(fileinput.FileInput(
            files=d_args['input'], openhook=hook_compressed_text))
    else:
        input = stack.enter_context(sys.stdin)

    return input

def hook_compressed_text(filename, mode):

    ext = os.path.splitext(filename)[1]
    if ext == '.gz':
        f = gzip.open(filename, mode + 't')
    else:
        f = open(filename, mode)

    return f

Here the class FileType from Lib/argparse.py:

class FileType(object):
    """Factory for creating file object types

    Instances of FileType are typically passed as type= arguments to the
    ArgumentParser add_argument() method.

    Keyword Arguments:
        - mode -- A string indicating how the file is to be opened. Accepts the
            same values as the builtin open() function.
        - bufsize -- The file's desired buffer size. Accepts the same values as
            the builtin open() function.
        - encoding -- The file's encoding. Accepts the same values as the
            builtin open() function.
        - errors -- A string indicating how encoding and decoding errors are to
            be handled. Accepts the same value as the builtin open() function.
    """

    def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
        self._mode = mode
        self._bufsize = bufsize
        self._encoding = encoding
        self._errors = errors

    def __call__(self, string):
        # the special argument "-" means sys.std{in,out}
        if string == '-':
            if 'r' in self._mode:
                return _sys.stdin
            elif 'w' in self._mode:
                return _sys.stdout
            else:
                msg = _('argument "-" with mode %r') % self._mode
                raise ValueError(msg)

        # all other arguments are used as file names
        try:
            return open(string, self._mode, self._bufsize, self._encoding,
                        self._errors)
        except OSError as e:
            message = _("can't open '%s': %s")
            raise ArgumentTypeError(message % (string, e))


texts:
I come from a C background and have now just begun C++.
This also means that I am not focussing on the algorithm, but more on C++ idioms.

Description:

  If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

main.cpp:

#include <iostream>

#define UPPER_BOUND 1000

int main() {
    int sum = 0;

    for (int i = 1; i < UPPER_BOUND; ++i) {
        if (i % 3 == 0 || i % 5 == 0) {
            sum += i;
        }
    }

    std::cout << "The sum of the natural numbers below " << UPPER_BOUND << " that are multiples of 3 and 5 is " << sum;

    return 0;
}

I will add files to GitLab here and make changes to them as I receive feedback.
Feel free to make changes to existing solutions.


texts:
I am interested in seeing how people would refactor this code to make it more readable, remove local variables, etc. The code checks a string against a number of arrays. The first (0) field of each array is the root word and the rest of the words are its synonyms. The idea is to replace any word in the user-provided string with the root word or provide the user-supplied word if none were found.

import java.util.Arrays;

public class Synonymiser {

    private final static int ROOT_WORD = 0;

    private String[][] mSynonyms;

    public Synonymiser(String[]... synonyms) {
        super();
        this.mSynonyms = synonyms;
    }

    public String normaliseString(String inStr){
        String[] inArr = inStr.split(" ");
        boolean matchFound;

        for (int i = 0; i < inArr.length; i++){
            matchFound=false;
            for (String[] synonymArr : mSynonyms){
                 for(int j = 0 ; j < synonymArr.length; j++){
                     if (inArr[i].equalsIgnoreCase(synonymArr[j])){
                         inArr[i] = synonymArr[ROOT_WORD];
                         matchFound = true;
                     }
                     if (matchFound) break;
                 }
                 if (matchFound)  break;
            }
        }
        return Arrays.toString(inArr);
    }

    public static void main(String [] args){
        String[] ar1 = new String[] {"one", "two", "three", "four", "five"};
        String[] ar2 = new String[] {"six", "seven", "eight"};
        Synonymiser s = new Synonymiser(ar1, ar2);

        System.out.println(s.normaliseString("one two seven bulb"));
    }

}


texts:
I was given that assignment recently as part of a coding interview.

The idea is to find if a gtin is valid or not valid.

The requirements are the following:

make sure the input is in a string format
the length must be either 8,12,13,14,17 or 18

The algorithm is the following:

TL;DR: You need to multiply all odd positions by 3 and you have to remove the last position. For example if the GTIN is 13, you need to multiply the 12th position by 3, the 11th position by 1, the 12th position by 3 and so on.

If the GTIN is 8, you need to multiply the 7th position by 3, the 6th by 1, the 5th by 3 and so on.

Once done, you sum all the elements and you find the nearest equal or higher multiple of ten and you substract this from the sum you have obtained. The integer that you obtained should be equal to the last digit (13th position if the GTIN is 13).

If it is not, then the GTIN is an incorrect one.

Here is my code

 def gtin_check(gtin: str)-> str:
    if not isinstance(gtin, str) or len(gtin) not in (8,12,13,14,17,18):
        return 'Not a string'
    else:
        gtin_lst = [int(x) for x in gtin]
        #print("step 1 - give the gtin but as a list of integers",gtin_lst)
        gtin_lst.reverse()
        #print("step 2 reverse the gtin",gtin_lst)
        gtin_original = gtin_lst #saving the list to gtin_original
        #print("step 3 : gtin original still reverse",gtin_original)
        gtin_lst = gtin_original[1:]
        #print("step 4 - gtin_lst starting from the first element",gtin_lst)
        gtin_original.reverse()
        #print("step 5 - gtin original without reverse , going back to normal ",gtin_original)

        # arriving at the algorithm part
        gtin_lst = [x*3 if i%2 == 0 else x for i,x in enumerate(gtin_lst)]
        #print('step 6 - multiplying by 3 of integers on odd position',gtin_lst)
        som_gtin1 = sum(gtin_lst)
        #print('step 7 - gtins summation',som_gtin1)

        if (som_gtin1 % 10):
            som_gtin2 = som_gtin1 + (10 - som_gtin1 % 10) # (10 // gcd(som_gtin1, 10)) *  som_gtin1 #int(round(som_gtin1, -1)) #som_gtin1 + (10 - som_gtin1 % 10)
        else:
            som_gtin2 = som_gtin1
        #print('step 8 : multiple of 10 instead of equal or higher summation',som_gtin2-som_gtin1)

        if (som_gtin2 - som_gtin1) == gtin_original[-1]:
            return True
        else:
            return False

The code does what I want but I feel it is not pythonic enough. Any suggestions or insight on how can I write a lighter code are welcomed.

update 1:

Example 12345670 will put True. 12345678 will put False.

update 2:

Since MJ713's feedback, I've commented my code just to make sure you understand my code. Let me know if you have any issues in reading it. I've amended my code to fix the bugs, MJ713 mentionned.


texts:
In sort(arr), I want to sort an array. Children must be beneath their parent. And children of the same parent are sorted using orderPos value.
I guess the complexity of this algorithm is quite high, is there a way to make it more performant for very long lists?
(the language used here is typescript)
     interface data { id:number; parentPK:number; orderPos:string; children: data[] }

 function sort(arr:data[]) {  const sorted : data[] = [];
  let parent: data = {children: [] , id : 0 , orderPos:'0' , parentPK:0} ;   let i = 1;

  // detect parent of all , parent pk is -1 , assumes theres only one root element whose parent id is -1
    arr.forEach(x => {

    if (x.parentPK == -1) {
      parent = x;
      sorted.push(x);
      arr.splice(arr.indexOf(x), 1);
      return;
    }   });   // root element is now first in the array   // get root's children and place them beneath their parent (sorted by orderPos)

  let temp: data[] = arr
    .filter(x => x.parentPK === (parent && parent.id))
    .sort((a, b) => parseInt(a.orderPos, 10) - parseInt(b.orderPos, 10));   sorted.push(...temp);   temp.forEach(x => parent.children.push(x));   while (i < arr.length - 1) {
    // new parent
    parent = sorted[sorted.indexOf(parent) + 1];
    // place children beneath parent
    temp = arr.filter(x => x.parentPK === (parent && parent.id)).sort((a, b) => parseInt(a.orderPos, 10) - parseInt(b.orderPos, 10));
    temp.forEach(x => parent.children.push(x));
    sorted.splice(sorted.indexOf(parent) + 1, 0, ...temp);
    i++;   }

  return sorted; }

  let array : data[] =  [ { id: 4, parentPK : 1, orderPos:'100' , children:[]}, {id:1, parentPK : -1, orderPos:'1', children:[] }, { id:2, parentPK : 1, orderPos:'51',children:[] }, {id:3, parentPK : 2, orderPos:'1',children:[] }, {id:5, parentPK : 2, orderPos:'10',children:[] } ]
let sortedArray = sort(array)
console.log('sorted array : ',sortedArray.map(element => [element.id, element.parentPK,element.orderPos] ))


texts: General Retry Strategy #3 with TryResult

texts:
I wanted to use the Try helper from @DmitryNogin's General Retry Strategy #2 but each attempt to implement it revealed another thing that is missing.

In my review I mentioned that it would be useful to be able to log the exceptions but later I came to the conclusion that perhaps it would be better to implement something similar to the ParallelLoopResult - this is how the TryResult was formed.

public struct TryResult
{
    public TryResult(bool isCompleted, IEnumerable<Exception> exceptions) : this()
    {
        IsCompleted = isCompleted;
        Exceptions = exceptions;
    }

    public bool IsCompleted { get; private set; }

    public IEnumerable<Exception> Exceptions { get; private set; }
}

Then I added it to the base class:

public abstract class Try
{
    public static readonly Try Never = new Never();
    public static readonly Try Once = Retry(delay: 0, times: 0, ratio: 0);

    public static Try Retry(int delay, int times, double ratio) =>
        RetryAfter(from i in Enumerable.Range(0, times)
                   select delay * Math.Pow(ratio, i) into d
                   select (int)d);

    public static Try RetryAfter(params int[] delays) => RetryAfter(delays.AsEnumerable());
    public static Try RetryAfter(IEnumerable<int> delays) => new Retry(delays);

    public void Execute(Action action) => Execute(action, CancellationToken.None);
    public abstract TryResult Execute(Action action, CancellationToken cancellationToken);

    public Task ExecuteAsync(Action action) => ExecuteAsync(action, CancellationToken.None);
    public Task ExecuteAsync(Action action, CancellationToken cancellationToken) =>
        ExecuteAsync(() => { action(); return Task.CompletedTask; }, cancellationToken);

    public Task ExecuteAsync(Func<Task> action) => ExecuteAsync(action, CancellationToken.None);
    public abstract Task<TryResult> ExecuteAsync(Func<Task> action, CancellationToken cancellationToken);

}

and adjusted the implementations:

class Never : Try
{
    public override TryResult Execute(Action action, CancellationToken cancellationToken)
    {
        return new TryResult(true, Enumerable.Empty<Exception>());
    }
    public override Task<TryResult> ExecuteAsync(Func<Task> action, CancellationToken cancellationToken)
        => Task.FromResult<TryResult>(new TryResult(true, Enumerable.Empty<Exception>()));
}

the same for Retry:

class Retry : Try
{
    IEnumerable<int> Delays { get; }

    public Retry(IEnumerable<int> delays)
    {
        Delays = delays;
    }

    public override TryResult Execute(Action action, CancellationToken cancellationToken)
    {
        var exceptions = new List<Exception>();

        foreach (var delay in Delays)
        {
            try
            {
                action();
                return new TryResult(true, exceptions);
            }
            catch
            {
                cancellationToken.WaitHandle.WaitOne(delay);
                cancellationToken.ThrowIfCancellationRequested();
            }
        }
        return new TryResult(false, exceptions);
    }

    public override async Task<TryResult> ExecuteAsync(Func<Task> action, CancellationToken cancellationToken)
    {
        var exceptions = new List<Exception>();

        foreach (var delay in Delays)
        {
            try
            {
                await action();
                return new TryResult(true, exceptions);
            }
            catch
            {
                await Task.Delay(delay, cancellationToken);
            }
        }

        return new TryResult(false, exceptions);
    }
}


texts: Is this an optimal implementation for the knapsack algorithm?

texts:
I have implemented a solution for the knapsack problem while breaking an item is allowed. I've used the dictionary data structure where I used weight as a key and value per weight as a value. After that, I sorted the dictionary by value and filled the knapsack until there's no space left.

Here is my python code -

def calculateKnapsack():
    userinputNW = list(map(int, input().split()))
    n = userinputNW[0]
    weight = userinputNW[1]
    weightvaluedict = {}
    revenue = 0
    for x in range(n):
        vw = list(map(int, input().split()))
        weightvaluedict[vw[1]] = vw[0]/vw[1]
    weightvaluedict = {k: v for k, v in sorted(
        weightvaluedict.items(), key=lambda item: item[1], reverse=True)}
    for k, v in weightvaluedict.items():
        if weight == 0:
            break
        if k < weight:
            revenue += k * v
            weight -= k
        else:
            revenue += weight * v
            weight = 0
    return revenue

I'm confused if it is an optimal solution or not. I searched online and most of the tutorial used 2D array. I wanted to ensure my code's optimality. Suggestions are welcome.

Thanks. And also this is my first question on the Code review platform so please forgive me if I did anything wrong.


texts: Comparison of Fibonacci (Multinacci) Functions in Python3

texts:
After coming up with a formula on this Stack Overflow question, defeating recursion limits and finding a few new ways of calculating these numbers (as per this Stack Overflow question), I decided that it was time to write up the solutions and submit them for a proper review.

For those that are not familiar with Fibonacci and more generally, Multinacci numbers, here are the rules:

The numbers correspond to the number of pairs of rabbits at year n
Rabbits take 1 year to mature
Rabbits reproduce after they mature, to produce 1 (or k in the case of Multinacci) pairs of rabbits
There is 1 pair at year 1, and none at year 0

from functools import lru_cache

limit = 100

# Classic recursive
def fibnum1(n, k=1):
    """Returns the multinacci number of order k at generation n"""
    if n <= 0:
        return 0
    if n == 1 or n == 2:
        return 1
    # build up the cache as needed to defeat recursion bounds
    global limit
    if n > limit:
        for temp_n in range(limit, n, 100):
            _fibnum(temp_n, k)
        limit = n + 100
    return _fibnum(n, k)

# Recursive with matrix multiplication
def fibnum2(n, k=1):
    """Returns the multinacci number of order k at generation n"""
    if n <= 0:
        return 0
    if n == 1 or n == 2:
        return 1
    return _matrix_fib(n, k)[1]

# Iterative
def fibnum3(n, k=1):
    """Returns the multinacci number of order k at generation n"""
    if n <= 0:
        return 0
    fibnums = [0, 1, 1]
    for i in range(3, n+1):
        fibnums.append(fibnums[i-1] + k * fibnums[i-2])
    return fibnums[n]

# Helper for fibnum1, memoized of course
@lru_cache(maxsize=None)
def _fibnum(n, k=1):
    if n <= 0:
        return 0
    if n == 1 or n == 2:
        return 1
    return _fibnum(n-1, k) + k * _fibnum(n-2, k)

# Helper for fibnum2, memoized of course
@lru_cache(maxsize=None)
def _matrix_fib(n, k):
    if n == 1:
        return [0, 1]
    else:
        f = _matrix_fib(n // 2, k)
        c = k * f[0] * f[0] + f[1] * f[1]
        d = f[1] * (f[1] + 2 * k * f[0])
        if n % 2 == 0:
            return [c, d]
        else:
            return [d, k * c + d]

As you can see, there are three distinct functions here for calculating these numbers: fibnum1, fibnum2, and fibnum3. They are nearly functionally identical, as all 3 are super fast (memoization for the win!) and work for relatively big numbers quite well. fibnum2 will fail eventually (dumb recursion limit...), but it is at too large of a number to be practically reached. I would like a comparative review, along with any other comments on any aspect of the code.


texts:
This is my first attempt at writing a C program, it a generic stack that can grow accordingly. It appears to work correctly, however I am worried that is just a fluke and I could be doing something very wrong.

I would greatly appreciate any feedback/criticism.

I am aware I should split this out into a .h and .c file but for demonstration purposes I have listed it as one.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct Stack
{
    void** data;
    int capacity;
    int count;
} Stack;

void stack_init(Stack *stack, int capacity)
{
    stack->data = (void**)malloc(capacity * sizeof(void*));
    stack->capacity = capacity;
    stack->count = 0;
}

void stack_push(Stack *stack, void* entry)
{
    if (stack->count >= stack->capacity)
    {
        stack->capacity *= 2;
        stack->data = (void**)realloc(stack->data, stack->capacity * sizeof(void*));
    }

    stack->data[stack->count] = entry;
    stack->count++;
}

void* stack_pop(Stack *stack)
{
    stack->count--;
    return stack->data[stack->count];
}

bool stack_is_empty(Stack *stack)
{
    return (stack->count == 0);
}

int main()
{
    Stack myStack;

    stack_init(&myStack, 2);

    for (int i = 0; i < 2; i++)
    {
        stack_push(&myStack, i);
    }

    while (!stack_is_empty(&myStack))
    {
        printf("%d\n", (int)stack_pop(&myStack));
    }

    return 0;
}


texts:
I have a situation in a class tries to create a group of same type of components and if some component fails then it needs to decide whether it should continue or throw the exception. Now the behavior whether to continue or re-throw depends in the context in which that class is used.

So a obvious solution was to pass the behavior from outside in a constructor, which is effectively a strategy pattern.
For now I had two implementations:

ContinuePolicy
AbortPolicy

These both policies were stateless so I created a single instance for them. Now I needed a strategy called SingleSuccessPolicy ( which ignores exception if atleast one of the components is successfully created). Now the problem is that to know whether all are failing or there is at least one success, the strategy needs to store some state (possibly count of components to be created). The side effect of it is that it makes creating a single instance infeasible.

Java Code:

class GroupComponent {
   private final ComponentExceptionPolicy exceptionPolicy;
   public GroupComponent(ComponentExceptionPolicy policy, GroupData data) {
      this.exceptionPolicy = policy;
   }

   public void createComponents() throws Exception {
      for(ComponentData compData : data.getComponentsData()) {
         try {
           createComponent(compData)
         } catch (Exception e) {
           policy.apply(compData, e);
         }
      }
   }
}

Code for Strategies:

public interface ComponentExceptionPolicy {
    public void apply(ComponentData data, Exception e);
}

class ContinuePolicy extends ComponentExceptionPolicy {
    @Override
    public void apply(ComponentData data, Exception e) throws Exception {
      //just log it and continue
    }
}

class AbortPolicy extends ComponentExceptionPolicy {
    @Override
    public void apply(ComponentData data, Exception e) throws Exception {
       throw e;
    }
}

class MaximumFailuresPolicy extends ComponentExceptionPolicy {
   private int n; //the expected size of group component

   MaximumFailuresPolicy(int n) {
       this.n = n;
   }

   @Override
   public void apply(ComponentData data, Exception e) {
      //on each exception I decrement count
      if(--n == 0) { //check if exception threshold is reached
         //as soon as found that all have failed then exception is thrown,
         //if any of component succeeds, then n will not reach to 0 and it
         //will just continue
         throw e;
      } else {
         //just log
      }
   }
}

EDIT:

To clarify, MaximumFailuresPolicy is meant to check that atleast one of the component should be initialized successfully. Maybe I have named it incorrectly

Is it a proper way to achieve this? Any help is appreciated.


texts: Getting rid of HTML file inputs once and far all

texts:
They've always annoyed me, and as a matter of principle, would like to leave my HTML/CSS intact and have the various file upload plugins work with consistent behavior with any styled element.

The following script places a transparent file input over a selected input.  Note that solutions such as triggering an upload script based on another element being clicked are not supported by all browsers, so please do not recommend doing so. One deficiency of my current solution is that cursor pointer doesn't work with Chrome.  Another is that I have not addressed border radius on the new element, and will consider doing to in the future.  I am also sure there are other changes that should be made.  Please advise of recommended changes.

See https://jsfiddle.net/4noentrp/2/ for a working example.

PS.  I would think all file upload plugins should default to similar functionality.  Agree?

jQuery.fn.extend({
    makeInput: function (o) {
        var arr = [];
        this.each(function () {
            var $this = $(this);
            if ( $this.is( "input:file" ) ) {var elem=$this;}
            else {
                var position = $this.position();
                var elem = $('<input/>', $.extend({},o,{
                    type: 'file',
                    style: 'height: ' + $this.outerHeight() + 'px;width: ' + $this.outerWidth() + 'px;top: ' + position.top + 'px;left:' + position.left + 'px;margin-top:' + $this.css('marginTop') + ';position:absolute;cursor:pointer;z-index:9999;opacity:0;filter: alpha(opacity=0)'
                    }
                )).insertAfter(this);
            }
            arr.push(elem[0]);
        });
        return $(arr);
    }
});

$('.makeInput').makeInput({name:'bla'}).fileupload({
    add: function (e, data) {
        alert(data.originalFiles[0].name+' submitted');
    }
});

Related HTML and CSS is shown below, however, the primary script is the JavaScript located above.

bla bla blainlinebla bla bla

block

float

position-static

position-absolute

position-relative

a {
    border: 1px solid black;
}
p {
    width: 120px;
    border: 1px solid black;
}
#float {
    float:right;
}
#position-absolute {
    position: relative;
    left: 30px;
    top: 80px;
}
#position-relative {
    position: relative;
    left: 30px;
    top: 80px;
}
#position-static {
    position: static;
}


texts:
I'm looking for an optimum way to join two Dataframes where the same record exists in both. Examples would be:

dat1 = pd.DataFrame({"id": [1,2,3,4,5], "dat1": [34,56,57,45,23]})
dat2 = pd.DataFrame({"id": [2,3,4], "dat2": [19,19,20]})

dat1
   id  dat1
0   1    34
1   2    56
2   3    57
3   4    45
4   5    23

dat2
   id  dat2
0   2    19
1   3    19
2   4    20

With the aim being to create overall_data:

overall_data
   id  dat1  dat2
0   2    56    19
1   3    57    19
2   4    45    20

At the moment my method is:

dat3 = dat1['id'].isin(dat2['id'])
dat3 = pd.Dataframe(dat3)
dat3.columns = ['bool']
dat4 = dat1.join(dat3)
overall_data = dat4(dat4['bool'] == True)

Though this feels very messy. Is there a nicer way to do this?


texts:
What I'm asking for is the review of a particular implementation of the haversine formula, found under:
http://blog.julien.cayzac.name/2008/10/arc-and-distance-between-two-points-on.html
This site is linked under the wikipedia article: http://en.wikipedia.org/wiki/Haversine_formula

Problem: I get the wrong distance for the points:

lat/lon, lat2/lon2

36.987814/-122.107887,   38.989185/-122.116728

I get a distance of 4336622.8812906 (meters)
however according to http://www.movable-type.co.uk/scripts/latlong.html it should be about 222.5 km.

If somebody could point out the error in this implementation, that would be great:

inline double getDist(double *gp) {
    /// @brief The usual PI/180 constant
    static const double DEG_TO_RAD = 0.017453292519943295769236907684886;
    /// @brief Earth's quatratic mean radius for WGS-84
    static const double EARTH_RADIUS_IN_METERS = 6372797.560856;

    double latitudeArc  = (gp[0] - gp[2]) * DEG_TO_RAD;
    double longitudeArc = (gp[1] - gp[3]) * DEG_TO_RAD;
    double latitudeH = sin(latitudeArc * 0.5);
    latitudeH *= latitudeH;
    double lontitudeH = sin(longitudeArc * 0.5);
    lontitudeH *= lontitudeH;
    double tmp = cos(gp[0]*DEG_TO_RAD) * cos(gp[2]*DEG_TO_RAD);
    return EARTH_RADIUS_IN_METERS*2.0 * asin(sqrt(latitudeH + tmp*lontitudeH));
}


texts: Flag words that would be difficult for an early reader

texts:
This is part of a project I made a couple of years ago and was looking at again. Its purpose is to check text for words that an early reader (about a late kindergarten or first grade level) would likely be unable to read. It does this by checking for CVC (consonant-vowel-consonant) and CVCE (consonant-vowel-consonant-E) words as well as slight variations on the CVC that begin or end with common two-letter combinations. (For example, an early reader should have little trouble with a word like "clap."). It also checks for  words on the pre-primer Dolch lists. (These are common "sight words" that kids should immediately recognize.)

Is there any way to make this more efficient? In particular, as I look at it, there are an awful lot of "if" statements. Is there some way to cut down on those, or does it even matter?

Also, do you think this is readable as is, or is there anything I should do to format it better?

Here is the "core" of the code:

    # Check if a word could be CVC or CVCE

def check_pattern(text):
    while len(text) >= 3:
        l= [text[0], text[1], text[2]]
        if l[0] in vowels:
            return False
        elif l[1] not in vowels:
            return False
        elif l[2] in vowels:
            return False
        else:
            return True

# Check if a word is CVC.
def check_CVC(text):
    pattern = check_pattern(text)
    if pattern == False:
        return False
    elif len(text) != 3:
        return False
    else:
        return True

# Check if a word is CVCE.
def check_CVCE(text):
    pattern = check_pattern(text)
    if pattern == False:
        return False
    elif len(text) != 4:
        return False
    elif text[3] != "e":
        return False
    else:
        return True

#Check if a word begins with a consonant blend or digraph. If so, read as if one letter
def check_bb (text):
    if len(text) >= 3:
        st= text[0]+text[1]
        if st in IC:
            p = list(text)
            del p[1]
            text = "".join(p)
            return text
        else:
            return text
    else:
            return text

#Check if a word ends with a consonant blend, digraph, or double letter. If so, read as if one letter
def check_eb (text):
    if len(text) >= 3:
        end = text[-2]+text[-1]
        if end  in FC:
            p = list(text)
            del p[-1]
            text = "".join(p)
            return text
        else:
            return text
    else:
            return text
# Strip off any punctuation at the end of a word.
def no_punct(text):
    punct = ["!", ".", "?", ",", ";", ":"]
    if text[-1] in punct:
        p = list(text)
        del p[-1]
        text = "".join(p)
        return text
    else:
        return text
#Check if a word is preprimer, primer, or easily decodable
def check_readable(text):
    word = no_punct(text)
    lc = word.lower()
    merge_start = check_bb(lc)
    merge_end = check_eb(merge_start)
    CVC = check_CVC(merge_end)
    CVCE = check_CVCE(merge_end)

    if CVC == True:
        return True
    elif CVCE == True:
        return True
    elif lc.lower() in preprimer:
        return True
    elif lc.lower() in primer:
        return True
    else:
        return False
#Flag words in a text that are not easily decodable, preprimer, or primer
def flag(text):
    words = text.split()
    i = 0
    while i < len(words):
        r = check_readable(words[i])
        if r == False:
            words[i] = "*" + words[i] + "*"
            i += 1
        else:
            i += 1
    text = " ".join(words)
    return text

For reference, here is the link to the entire code, including the letter/blend/word lists and a Tkinter GUI: https://github.com/casinclair/Reader


texts: How to improve wordfeud solver algorithm?

texts:
I created a simple wordfeud solver that checks what words can be created with the supplied letters.

public void GetResults(string characters)
{
    // place all the characters we have in a dictionary with key=letter, value=amount
    var charCount = SplitCharacters(characters);

    // get all the unique letters (the keys)
    char[] individualChars = charCount.Keys.ToArray();

    // create a regex for these letters, because only those letters are allowed in a word
    string regex = @"^[" + new string(individualChars) + "]+$";

    // get all the words that contain only the letters we have on our board
    IEnumerable<string> possibleWords = _words.Where(x => Regex.IsMatch(x, regex));

    // walk through the words that have only the letters on our board, and check if
    // there are sufficient letters on our board to create that word
    IEnumerable<string> results = possibleWords
        .Where(x => SplitCharacters(x).All(y => charCount[y.Key] >= y.Value) && x.Length > 1)
        .OrderByDescending(x => x.Length)
        .Take(25);

    // convert the words to ViewModel objects to display in the view
    foreach (string result in results)
    {
        Results.Add(new ResultViewModel { Word = result });
    }
}

private Dictionary<char, int> SplitCharacters(string characters)
{
    char[] chars = characters.ToLower().ToCharArray();

    var charCount = new Dictionary<char, int>();

    foreach (char c in chars)
    {
        if (!charCount.ContainsKey(c))
        {
            charCount[c] = 1;
        }
        else
        {
            charCount[c]++;
        }
    }

    return charCount;
}

It works, but I think this can be done more efficient. I worked this out on my own, but I feel like I'm creating too many new arrays/enumerables for all the steps in the algorithm. It runs quite fast on my PC (core i7 2600) but it's a little bit slow on my Surface tablet.

Can this be done more efficiently?


texts: Interpret YYYYMMDD as the nth day of the year

texts:
I am provided a bunch of dates in the format (YYYYMMDD) such as:

date='20170503'

My goal is to convert that date into the number of days in the given year. For example, it would convert:

20170130 to 30
20170201 to 32
20151231 to 365

Here is my solution:

import pandas as pd
my_date = pd.to_datetime(date, format='%Y%m%d')
my_ordinal = 736329 - 365*(2017 - my_date.year)
print(datetime.toordinal(my_date) - my_ordinal)

Is there a better way to do this without making it much more complex? Note that pandas is already in the program, so there is no extra burden in using it.


texts:
I have been making a jQuery morphing button type thing.

jsFiddle

$(document).ready(function() {

    var morphObject = {

        button: $('button.morphButton'),
        container: $('div.morphContainer'),
        overlay: $('div.overlay'),
        content: $('h1, p'),

        init: function() {
            this.buttonPress();
        },

        buttonPress: function() {
            var mO = morphObject;

            this.button.on('click', function() {

                mO.button.fadeOut(200);
                setTimeout(mO.containerMove, 200);

                });

        },

        containerMove: function() {
            var mO = morphObject;
                span = $('span.close');

            mO.overlay.fadeIn();

            mO.container.animate({
                top: 300,
                left: '50%',
                width: 600,
                height: 400,
                marginLeft: -300 },
                400, function() {
                    mO.content.fadeIn();
                    span.fadeIn();
                    mO.close();
            });

        },

        close: function() {
            var mO = morphObject;

            if ( mO.container.find('span.close').length ) return;

            $('X').appendTo(mO.container);

            var span = $('span.close');

            mO.overlay.add(span).on('click', function() {
                mO.content.fadeOut();
                span.fadeOut();
                mO.overlay.fadeOut();
                setTimeout(mO.animateBack, 200);
            });

        },

        animateBack: function() {
            var mO = morphObject;

            mO.container.animate({
                top: 150,
                left: '20%',
                width: 200,
                height: 70,
                marginLeft: -100 },
                400, function() {
                    mO.button.fadeIn(300);
            });

        }

    }

    morphObject.init();

});

Basically, I would love to have any feedback on what I can improve. Please tell me if I have used any bad coding practises or methods which will cause slow performance.


texts: A method that shows maps users are a part of

texts:
A little background:

My app has two models called mapgroups and usergroups. A map belongs to a group and a user belongs to group. You can go in a group and add maps which is how maps are "assigned" to a user. These will show up on their dashboard.

class User < ApplicationRecord
  def fetch_maps
    @groups = self.groups
    @maps = Array.new

    @groups.each do |g|
      g.maps.each do |m|
        @maps << m
      end
    end

    return @maps
  end
end

In order to display the maps the user should have shown in their dashboard I created a fetch_maps method to call on the current user.

Im wondering if there is any way to clean this up or really just any feedback. This is the first method I have written with current Ruby knowledge.

Edit:

Mapgroup Model

class Mapgroup < ApplicationRecord
  belongs_to :map, optional: true
  belongs_to :group, optional: true
end

Usergroup Model

class Usergroup < ApplicationRecord
  belongs_to :user, optional: true
  belongs_to :group, optional: true
end


texts:
have started learning Java recently and was looking into some easy algorithms.
I found the Sieve Of Erastothenes algorithm here

I am trying to get better at writing good code for my solutions. Please give me your suggestions.

import java.util.Scanner;

public class SieveofErastothenes {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter the prime number ceiling");
        int ceiling = keyboard.nextInt();
        keyboard.close();
        prime(ceiling);

    }

    private static void prime(int n) {

        // create an array with 0 and 1 where 1= Prime and 0= Non Prime
        int[] isPrime = new int[n + 1];
        // set all values to 1
        for (int i = 2; i <= n; i++) {
            isPrime[i] = 1;

        }

        int upperbound = (int) Math.sqrt(n);
        for (int i = 2; i <= upperbound; i++) {
            if (isPrime[i] == 1) {
                for (int j = 2; j * i <= n; j++) {
                    isPrime[j * i] = 0;
                }
            }
        }

        printprime(isPrime, n);

    }

    private static void printprime(int[] isPrime, int n) {
        for (int i = 0; i <= n; i++) {
            if (isPrime[i] == 1) {
                System.out.println(i);

            }
        }

    }
}

A few online tutorials use a boolean array to set all the values as true or false whereas I am using an integer array and setting the values to 0 and 1 initially.Does this make any difference in the performance?


texts: Making complex array initializations more readable

texts:
I have a function in the C++ program, which does simple computations and writes result to two arrays - result[53] and var1_new[53]. It contains two code blocks:

The first one -

double result[53];

result[0] = ((var1[13] * 1) + (var2[7] * 2)) / var3[0];
result[1] = ((var1[21] * 1) + (var2[7] * 2)) / var3[1];
result[2] = ((var1[12] * 2) + (var2[7] * 3)) / var3[2];
result[3] = ((var1[25] * 2) + (var2[7] * 3)) / var3[3];
//And so on, up to result[52]

And the second one -

double var1_new[53];

for (int x = 0; x < 53; ++x)
{
    var1_new[x] = var1[x];
}

var1_new[13] += result[0];
var1_new[21] += result[1];
var1_new[12] += result[2];
var1_new[25] += result[3];
//And so on, up to var1_new[52]

The blocks above use equal array indexes pattern - 13, 21, 12, 15, etc. The pattern is hardcoded.

This code runs pretty fast, thus I don't want to increase performance, but I'm thinking about readability - the function that contain code blocks is very complex. How can I make it more readable? Is it even possible?


texts:
I wrote two pretty simple classes for one of my projects. This is the first time I met such a problem, so I would like to ask you if I managed to tackle the problem the right way / with good implementation.

The background is quite simple: You have a Channel that might be either busy or not. If the Channel is busy, it means it was taken by a ServiceRequest. Once the request is processed the Channel should be open again.

I googled a little bit and found ideas to use the PropertyChangeListener. Code down below. Please give me all the comments you can regarding the code quality / problem solving here. Thank you!

Test:

@Unroll
def "when request is processed and finished channel is free again"() {
    given:
    def channel = new Channel()
    def request = new ServiceRequest()
    request.addPropertyChangeListener(channel)
    when:
    channel.setRequest(request)
    request.finish();
    then:
    assert !channel.isBusy() && channel.request == null
}

Channel class:

public class Channel implements PropertyChangeListener{

    private boolean busy;
    private ServiceRequest request;

    public Channel() {
        this.busy = false;
    }

    public boolean isBusy() {
        return busy;
    }

    public ServiceRequest getRequest() {
        return request;
    }

    public void setRequest(final ServiceRequest request) {
        this.request = request;
        busy = true;
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        request = null;
        busy = false;
    }
}

ServiceRequest class:

public class ServiceRequest {

    PropertyChangeSupport support = new PropertyChangeSupport(this);

    private String id;

    public ServiceRequest() {
        id = "randomlygeneratedid";
    }

    void addPropertyChangeListener(final PropertyChangeListener l) {
        support.addPropertyChangeListener(l);
    }

    public void finish() {
        id = "";
        support.firePropertyChange("id", id, "");
        support.firePropertyChange("request", null, null);
        support.firePropertyChange("busy", null, false);
    }

    public String getId() {
        return id;
    }
}


texts:
I have read so many times that one should not subclass standard containers.
Is there cases that one can subclass them ?
for example, I have the following case:

struct Materials
{

  std::map<std::string, std::unique_ptr<Material>> materials;

  void setFrom(const Database& db);
  void echo(std::ostream&) const;

};

I want my materials class to act like a map, so I have to add methods like

Material& getMaterial(std::string& key);
void addMaterial(std::string& key, Material& material);

which could have been avoided if I just sublcassed the container.

 struct Materials:public std::map<std::string, std::unique_ptr<Material>> materials;
    {
      void setFrom(const Database& db);
      void echo(std::ostream&) const;
    };

is this a horrible thing to do ?


texts:
I had to make this blackjack game for school, but this is only the first part. We only had to use a random value between 2 and 11 to generate the cards, as we will have a library of cards later, and the dealer will keep pulling cards until their total value is at or equal to 17. The player needs to decide whether they want to hit or stay, and will always bet $25. I want to clean up the code to make it clearer, as it seems a bit messy.

import random

def main():

  restart = True

  bank_balance = 1000
  player_name = input("Please enter your name: ")
  while (bank_balance >= 25 and restart == True):

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
    print (f"Betting $25")
    bank_balance-=25

    deal_hand = play_hand(player_name)

    play=input("Type 'y' to play again, or type any key to quit" + '\n')

    if (play == 'y'):
      restart=True
      print('\n')
    elif (play != 'y'):
      print('Thanks for playing ')
      restart=False

def play_hand(name):

  player= []
  dealer= []

  play_again = True

  dealer.append(random.randint(1, 11))

  player.extend([random.randint(1, 11), random.randint(1, 11)])

  print ('The dealer received card of value', *dealer)
  print(name, 'received cards of value', player[0], 'and', player[-1])
  print(f'Dealer total is {sum(dealer)}')
  print(f"{name}'s total is {sum(player)}", '\n')

  stay = False
  bust = False

  while (sum(player) <= 21 and stay == False and play_again == True):
    hors= input(f"Type 'h' to hit and 's' to stay ")
    if (hors == 'h'):
      new_card= random.randint(1, 11)
      player.append(new_card)
      print(f'{name} pulled a {new_card}')

      print(f'Dealer total is {sum(dealer)}')
      print(f"{name}'s cards are", *player)
      print(f"{name}'s total is {sum(player)}", '\n')

    elif (hors == 's'):
      stay=True
      print('stay')

  if (sum(player) > 21 ):
    bust = True
    print('You busted!')

  while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
    dealer.append(random.randint(1, 11))

    print('The dealers total is', sum(dealer), '\n')

  if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
    print("The dealer wins!")
  elif (sum(player) <= 21 and sum(player) > sum(dealer)):
    print("You win!")
  if (sum(dealer) > 21):
    print ('You win! The dealer busted!')
  if (sum(dealer) == sum(player)):
    print('Its a Tie! ')

main()


texts: Fast execution of function which resembles matrix multiplication

texts:
I am trying to make the following function as fast as possible on large matrices. The matrices can have dimensions in the range of 10K-100K. The matrix values are always between 0 and 1. The function resembles matrix multiplication, but with log operations in the inner loop. These log operations appear to be a bottleneck.

I tried various ways of using Numba and Cython. I also tried writing as much as I could with Numpy. I also experimented with doing fewer memory lookups, but this did not seem to give much advantage. The fastest version is below. High precision is greatly preferred, but if there is a way to increase speed at its expense, that would also be appreciated. Thank you for your feedback.

import numpy as np
import numba
from numba import njit, prange

@numba.jit(nopython=True, fastmath=True, parallel=True)
def f(A, B):

    len_A = A.shape[0]
    len_B = B.shape[0]
    num_factors = B.shape[1]
    C = np.zeros((len_A, len_B))

    for i in prange(len_A):
        for j in prange(len_B):
            for a in prange(num_factors):

                A_elem = A[i,a]
                B_elem = B[j,a]
                AB_elem = (A_elem + B_elem)/2

                C[i,j] += A_elem * np.log(A_elem/AB_elem) + \
                          B_elem * np.log(B_elem/AB_elem) + \
                          (1-A_elem) * np.log((1-A_elem)/(1-AB_elem)) + \
                          (1-B_elem) * np.log((1-B_elem)/(1-AB_elem))

    C = (np.maximum(C, 0)/2*num_factors)**0.5
    return C

#A = np.random.rand(10000, 10000)
#B = np.random.rand(10000, 10000)
#f(A, B)


texts:
The affine cipher is a simple mathematical substitution cipher. If you're interested in the details behind how it works, this page goes further into detail.

After writing a program to encrypt and decrypt text using the affine cipher, I felt that it seemed needlessly cluttered. I have also noticed that there are no questions related to the affine cipher on Code Review, at least not for C++.

Here's the code:

#include <iostream>
#include <algorithm>
#include <numeric>
#include <cmath>

int gcd(int a, int b);
int modInverse(int a, int b); // from https://rosettacode.org/wiki/Modular_inverse#C.2B.2B

int main(){
    std::string choice;
    do{
        std::cout << "Encrypt or Decrypt? [e/d] = ";
        std::getline(std::cin, choice);
        std::transform(choice.begin(), choice.end(), choice.begin(), ::tolower);
    } while(choice.length() > 1 || choice != "e" && choice != "d");

    std::cout << "\nInput string: ";
    std::string input;
    std::getline(std::cin, input);

    int a, b;
    do{
        std::cout << "\na and b must be coprime\na = ";
        std::cin >> a;
        std::cout << "b = ";
        std::cin >> b;
    } while(std::cin.fail() || gcd(a,b) != 1);

    std::cout << '\n';

    if(choice == "e"){
        for(int i = 0; i < input.length(); ++i){
            if(input[i] >= 'a' && input[i] <= 'z'){
                std::cout << (char)((a * (input[i] - 'a') + b) % 26 + 'a');
            } else if(input[i] >= 'A' && input[i] <= 'Z'){
                std::cout << (char)((a * (input[i] - 'A') + b) % 26 + 'A');
            } else{
                std::cout << input[i];
            }
        }
    } else{
        for(int i = 0; i < input.length(); ++i){
            if(input[i] >= 'a' && input[i] <= 'z'){
                std::cout << (char)(modInverse(a, 26) * (26 + input[i] - 'a' - b) % 26 + 'a');
            } else if(input[i] >= 'A' && input[i] <= 'Z'){
                std::cout << (char)(modInverse(a, 26) * (26 + input[i] - 'A' - b) % 26 + 'A');
            } else{
                std::cout << input[i];
            }
        }
    }

    std::cout << '\n';
    return 0;
}

int gcd(int a, int b){
    return b == 0 ? a : gcd(b, a % b);
}

int modInverse(int a, int b){
    int b0 = b, t, q;
    int x0 = 0, x1 = 1;
    if (b == 1) return 1;
    while (a > 1) {
        q = a / b;
        t = b, b = a % b, a = t;
        t = x0, x0 = x1 - q * x0, x1 = t;
    }
    if (x1 < 0) x1 += b0;
    return x1;
}

Here is an example output for the encryption side:

Encrypt or Decrypt? [e/d] = e

Input string: Hello World!

a and b must be coprime
a = 5
b = 9

Sdmmb Pbqmy!

And here is an example output for the decryption side:

Encrypt or Decrypt? [e/d] = d

Input string: Sdmmb Pbqmy!

a and b must be coprime
a = 5
b = 9

Hello World!

I am using the modInverse() function from Rosetta Code. This is quasi-related to my ongoing series of classical ciphers. So far I have done a simple Caesar cipher and an Atbash cipher.

How can I improve this code, both for readability and for efficiency?


texts: Leave at most max_dup consecutive duplicate elements in a list

texts:
I need to remove excessive duplicates of a particular element from the list, that is, if there's more than max_dup duplicates of selected elements in a slice of the list, leave at most max_dup elements in place. Obviously, stability (retaining order of elements in the list) is a must.

Example:

>>> remove_excessive_duplicates([1, '', '', '', 2, '', 3, '', '', '', '', '', 4, ''])
[1, '', '', 2, '', 3, '', '', 4, '']

The code I wrote:

def remove_excessive_duplicates(lst, dup='', max_dup=2):
    new_lst = []
    dcnt = 0
    for elem in lst:
        if elem == dup:
            dcnt += 1
        else:
            dcnt = 0
        if dcnt > max_dup:
            continue
        new_lst.append(elem)
    return new_lst

It works, but I'm wondering if there's some cleverer way to do it, or the one that uses logic of some Python builtins to achieve the same goal.


texts: jQuery form change listener, modularized using ES6

texts:
I have the following javascript code that I'm trying to modularize using ES6:

import $ from 'jquery';

$('.select-element').change(function() {
  const $this = $(this);
  const $nextElements = $this.nextall();
  const $nextElement = $this.next();
  $this.val() === 0 ?
    $nextElements.addClass("hidden") :
    $nextElement.removeClass("hidden");
});

Here is what I've done:

import $ from 'jquery';

export default class FormListener {
  constructor(selector=".select-element") {
    $(selector).change(this.change);
  }
  change() {
    let $item = $(this);
    let value = $item.val();
    let $nextElements = $item.nextAll();
    let $nextElement = $item.next();
    value === 0 ?
      $nextElements.addClass("hidden") :
      $nextElement.removeClass("hidden");
  }
}

Then in my code, rather than simply insert the first version inside a <script> tag, I do this:

import FormListener from './form-listener');
new FormListener();

I got the basic ideas from the jQuery code organization docs but tried to use a class rather than a function. Is this the proper way to modularize a simple jQuery listener? Is there a better coding pattern to follow to achieve my goal?


texts:
I wrote a simple bash script in order to batch convert Markdown files via pandoc and it is working for me. But I have the feeling the code is dirty. Could you help me improve it?

#!/bin/bash

rm -r out; mkdir out

for f in src/*.md
do
    filename=$(basename "$f")
    filename="${filename%.*}"
    echo "Processing $filename"
    pandoc "$f" -o "out/$filename.epub"
    pandoc "$f" -o "out/$filename.pdf"
done


texts: Get the difference between two dates, in the most convenient unit

texts:
I use the following code in Javascript to get the difference between two Date objects. I want the result to return the difference in:

seconds if the result is less than 60 secs
minutes if the result is less than 60 mins
hours if the result is less than 24 hours
days otherwise

The code is very long and I see lots of code duplication. Isn't there a smarter/shorter way to do this (without using a library)?

function dateDiff(a, b) {
  let utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getUTCHours(), a.getUTCMinutes(), a.getUTCSeconds());
  let utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate(), b.getUTCHours(), b.getUTCMinutes(), b.getUTCSeconds());

  let result = (utc2 - utc1) / (1000 * 60 * 60 * 24);
  let floor = Math.floor(result);
  if (floor > 0) return floor + "d";

  result *= 24;
  floor = Math.floor(result);
  if (floor > 0) return floor + "h";

  result *= 60;
  floor = Math.floor(result);
  if (floor > 0) return floor + "min";

  result *= 60;
  floor = Math.floor(result);
  if (floor > 0) return floor + "sec";
}


texts: Convert camelCase and PascalCase to Title Case

texts:
I'm trying to take camelCase and PascalCase strings into a function and spit them out as Title Case. This function also needs to be able to handle odd PascalCase strings with capitalized abbreviations such as "CDReceiverBox" and return a readable string - "CD Receiver Box".

My current working solution:

function splitCamelCase(camelCaseString) {
    const result = camelCaseString
        .replace(/([A-Z][a-z])/g, " $1")
        .replace(/([A-Z]+)/g, " $1")
        .replace(/ +/g, " ")
        .replace(/^ +/g, "");

    return result.charAt(0).toUpperCase() + result.slice(1);
}

I would like to condense the amount of replace statements I'm using by at least combining the first two replace statements and the last two together since they are semi similar. The more concise I can make this the better.

CodePen: https://codepen.io/andrewgarrison/pen/dEQrMy


texts: Storing transactions with amounts and payment types

texts:
I have a table where I'm storing a row for each transaction that records the type of transaction along with the amount of money being recorded for the transaction type. I then need to write a report to sum the amounts of various types.

At the moment I'm doing this with a series of CTE's, but I'm sure there's a better way:

;with cte_foodCard as (
    select  isnull(sum(cast(o.FinancialContribution as money)), 0) as 'FoodCardContributions'
    from    dbo.CriticalAssistanceInternalOutcomes as o
    where   upper(o.PaymentType) = 'FOOD CARD'
), cte_fuelCard as
(
    select  isnull(sum(cast(o.FinancialContribution as money)), 0) as 'FuelCardContributions'
    from    dbo.CriticalAssistanceInternalOutcomes as o
    where   upper(o.PaymentType) = 'FUEL CARD'
), cte_gocard as
(
    select  isnull(sum(cast(o.FinancialContribution as money)), 0) as 'GoCardContributions'
    from    dbo.CriticalAssistanceInternalOutcomes as o
    where   upper(o.PaymentType) in ( 'GO CARD' , 'GOCARD')
), cte_invoicePayment as
(
    select  isnull(sum(cast(o.FinancialContribution as money)), 0) as 'InvoicePaymentContributions'
    from    dbo.CriticalAssistanceInternalOutcomes as o
    where   upper(o.PaymentType) = 'INVOICE PAYMENT'
)
select *
from cte_foodCard , cte_fuelCard, cte_gocard, cte_invoicePayment

For more context, a sampling of the data from development (needs better rules and cleanup) looks like:

select  o.Id ,
        o.FinancialContribution ,
        o.PaymentType
from dbo.CriticalAssistanceInternalOutcomes as o


texts:
I had a coding assignment task(interview) for a senior data engineer role, JSON data validation. Every record in the input json indicates a customer record, I need to write a script to validate that all records confirms to few business rules and few more field type/length restrictions.

I used object-oriented, meta-data driven approach to write this parser in Python. However, I got negative feedback for the task and I am hoping to get some feedback on the code. Here is the git repo with some extra readme for the context and Business rules - https://github.com/YADAAB/jsonparser

I am looking for some inputs on coding style, overall design, object-oriented approach etc.

An example of email validation since the stackXchange wants me to add some code in the question :)

        email_regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
    try:
        if(re.search(email_regex,self.line_dict[field_name])):
            return True
        else:
            self.error_dict[field_name] = str(self.error_dict.get(field_name, '')) + 'Invalid email'

Would love to answer any specific questions. Thanks for checking!


texts: Build a dictionary based on split string

texts:
I've written a simple script that takes a string filled with brackets and strings and builds them to a dictionary.

Example Input:

string_1 = '(()())'
string_2 = '((a)(b))'
string_3 = '(a(a)b(b)c)'
string_4 = 'a(a(a)b(b)c)b'
string_4 = 'a[a{a}b{b}c]b'
string_5 = 'beginning(content[word]{another word})outside'

Output for string5 and the other examples:

[
('0-8', 'beginning'),
('9', '('),
('10-16', 'content'),
('17', '['),
('18-21', 'word'),
('22', ']'),
('23', '{'),
('24-35', 'another word'),
('36', '}'),
('37', ')'),
('38-44', 'outside')
]

def sort(dictionary):
    return sorted(dictionary.items(), key=lambda v: int(v[0].split("-")[0]))

def join(a, b):
    return ''.join([repr(a), '-', repr(b - 1)]) if a != b else repr(b)

class Positions:
    def __init__(self, name):
        self.name = name
        self.content = {}  # creates a new empty list for each bracket

    def push(self, pos, content):
        self.content[pos] = content

def convert_string(string):
    string_content = string
    string = Positions(string)
    pos = 0
    start_of_str_pos = 0
    internal_string = ''
    for char in string_content:
        if char in ['(', '{', '[', ')', '<', '}', ']', '>']:
            string.push(repr(pos), repr(char))
            if internal_string != '':
                string.push(join(start_of_str_pos, pos), internal_string)
                internal_string = ''
            start_of_str_pos = pos + 1
        else:
            internal_string += char
        pos += 1

    if internal_string != '':
        string.push(''.join([repr(start_of_str_pos),
                             '-', repr(pos - 1)]), internal_string)
    print sort(string.content)


texts:
This my first foray in F#, and I cannot think (yet) functional.  I have implemented an interface for a discount curve and the implementation for a piecewise constant instant rate implementation.

I would like to have your opinion on how to make this more F#.  Should I keep the second input of the constructor as an array or a sequence?

Also, as I pre-compute all possible values between the first point and the end_date, I could have done a tail recursion and lazily populate the cache, but I was wondering about efficiency: I did not have time to write the tail-recursion and do a timing comparison.

module public DiscountCurve =
    type IDiscountCurve =
       abstract member Df : System.DateTime -> double

    type DfPieceWiseInstant(end_date:System.DateTime, points:(System.DateTime * double)[]) =
        let start_date = fst(points.[0])
        let end_date = end_date
        let cache : double array = Array.zeroCreate ((end_date - start_date).Days + 1)
        let points = points
        do
            cache.[0] <- 1.
            for idx in { 0 .. (points.Length - 1) } do
                let cache_idx_start = max 1 (fst(points.[idx]) - start_date).Days
                let cache_idx_end =
                    if idx+1 < points.Length then
                        (fst(points.[idx+1]) - start_date).Days - 1
                    else
                        (end_date - start_date).Days - 1
                let cache_idx_df = exp (-snd(points.[idx])/365.)
                for cache_date in seq { cache_idx_start .. cache_idx_end-1 } do
                    cache.[cache_date] <- cache.[cache_date-1] * cache_idx_df

        interface IDiscountCurve with
            member this.Df(date) =
                cache.[(date - start_date).Days]


texts: A small printf-like function using variadic templates

texts:
I'm looking to get some feedback on a small printf-like function I wrote that provides simplified behavior similar to boost::format:

#ifndef EXT_FORMAT_HPP__
#define EXT_FORMAT_HPP__
// ext::format
// Implements a variadic printf-like function providing behavior similar to
// boost::format
#include <regex>
#include <sstream>
#include <string>
#include <utility>

namespace {

inline std::string format_helper(
    const std::string &string_to_update,
    const size_t) {
  return string_to_update;
}

template <typename T, typename... Args>
inline std::string format_helper(
    const std::string &string_to_update,
    const size_t index_to_replace,
    T &&val,
    Args &&...args) {
  std::regex pattern{"%" + std::to_string(index_to_replace)};
  std::string replacement_string{(std::ostringstream{} << val).str()};
  return format_helper(
      std::regex_replace(string_to_update, pattern, replacement_string),
      index_to_replace + 1,
      std::forward<Args>(args)...);
}

} // namespace

namespace ext {

template <typename... Args>
inline std::string format(const std::string &format_string, Args &&...args) {
  return format_helper(format_string, 1, std::forward<Args>(args)...);
}

} // namespace ext

#endif

Usage example:

#include "format.hpp"
#include <iostream>

struct foo {
  int value;
  foo(int val) : value{val} {
  }
};

std::ostream &operator<<(std::ostream &os, const foo &f) {
  os << "foo(" << f.value << ")";
  return os;
}

int main() {
  double tmp = 37.382;
  std::cout << ext::format("%1 + %2 * %1 = %3", 5, tmp, 5 + tmp * 5) << std::endl;

  // Support user defined types provided the appropriate operator<< overload is defined.
  foo a_foo(55);
  std::cout << ext::format("Here is a foo constructed with 55: %1", a_foo) << std::endl;
};

This is not written to replace boost::format; it's intended to be used as a header-only include with a very limited scope. As currently written, it is possible to supply too few or too many arguments to the parameter pack. Passing too few arguments will return a string that still has format specifiers. Passing excess arguments are simply ignored and you pay the price of excess calls to std::regex_replace, which will do nothing. With that in mind, I'm looking for any and all feedback.


texts: Maximum sum of non-consecutive elements of an array

texts:
You are given a list of houses on a street, with the numeric value
  representing the amount of money stashed away in each house.

  Write a method to find the maximum amount of money you can steal. You
  cannot steal from any two adjacent houses, otherwise you will be
  caught! Use Dynamic Programming!

  Examples:

  robbery([60, 50, 20, 32, 20, 50]) → 142
  robbery([40, 25, 25, 30]) → 70

I would like to ask for a review of the following solution.

def robbery(amounts):
    amounts = iter(amounts)
    prev, total = 0, next(amounts, 0)
    for x in amounts: prev, total = total, max(total, prev + x)
    return total

Here's my code on Gist:
https://gist.github.com/Jeffchiucp/6dbd481ce4bc208e6da68bc8e920bf3f


texts:
import java.util.ArrayList;

public class SumsOfPerfectPowers {

    ArrayList<Long> numList = new ArrayList<Long>(5000001);
    // status of whether a number is power number
    boolean[] result = new boolean[5000001];

    public SumsOfPerfectPowers() {
        numList.add((long) 0);
        numList.add((long) 1);
        for (int i = 2; i <= 2237; i++) {
            int j = 2;
            double value;
            while ((value = Math.pow(i, j)) <= 5000000) {
                numList.add((long) value);
                j++;
            }
        }

        int len = numList.size();
//      System.out.println(len);
        int value;
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                value = (int) (numList.get(i) + numList.get(j));
                if (value <= 5000001) {
                    result[value] = true;
                }
            }
        }

    }

    static {
    }

    public int howMany(int a, int b) {
        int sum = 0;
        for(int i=a;i<=b;i++) {
            if(result[i]) {
                sum ++;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        SumsOfPerfectPowers test = new SumsOfPerfectPowers();

        System.out.println(test.howMany(0, 1));
        System.out.println(test.howMany(5, 6));
        System.out.println(test.howMany(25, 30));
        System.out.println(test.howMany(103, 103));
        System.out.println(test.howMany(1, 100000));

    }

}

Is this piece of code well-coded?
Are there any bad habits here?
What can be improved?


texts:
This code computes the Minimum Spanning Tree of a given graph using Kruskals Algorithm.

It works successfully and I have provided test cases within the code.

I would like feedback on code efficiency (Choice of ds and functions/function size) and anything else to improve the code (Aside from pep 8 compliance, that is something I will be working to fix soon)

Thank you

class Graph:

  def __init__(self):

    self.graph = []
    self.edges = []
    self.parents = {}
    self.size = {}

  def addnode(self, key1, key2, edge=0):

    if key1 not in self.graph:
      self.graph.append(key1)
    if key2 not in self.graph:
      self.graph.append(key2)

    self.edges.append([key1, key2, edge])

  def getparent(self, vertex):

    while self.parents[vertex] != -1:
      vertex = self.parents[vertex]

    return vertex

  def union(self, vertex, neighbour):

    x_par = self.getparent(vertex)
    y_par = self.getparent(neighbour)
    if self.size[x_par] <= self.size[y_par]:
      self.parents[x_par] = y_par
      self.size[y_par] += self.size[x_par]
    else:
      self.parents[y_par] = x_par
      self.size[x_par] += self.size[y_par]

  def kruskal(self):

    mst = []
    total = 0

    for key in self.graph:
      self.parents[key] = -1
      self.size[key] = 1

    self.edges.sort(key = lambda x:x[2])

    for edge in self.edges:
        vertex, neighbour, weight_edge = edge
        x_par = self.getparent(vertex)
        y_par = self.getparent(neighbour)
        if x_par != y_par:
          self.union(x_par, y_par)
          mst.append(edge)
          total += weight_edge

    print(mst)
    print('mst of weight:', total)

if __name__ == '__main__':
  g = Graph()
  g.addnode(0, 1, 10)
  g.addnode(0, 2, 6)
  g.addnode(0, 3, 5)
  g.addnode(1, 3, 15)
  g.addnode(2, 3, 4)
  g.kruskal()


texts: Plot heat map from csv file using numpy and matplotlib

texts:
There's a csv file with format:

x0, y0, v00
x0, y1, v01
...
x1, y0  v10
...

And what I want to do is to plot a heat map, in which at location (x, y) the value v is plotted with corresponding color. Below is my current implementation.

import random
import numpy as np
import matplotlib.pyplot as plt

def create_test_csv(file):
    random.seed(42)
    f = open(file, "w")
    for x in range(300):
        for y in range(600):
            value = random.randrange(255)
            f.write(str(x) + "," + str(y) + "," + str(value) + "\n")

def get_xyz_from_csv_file(csv_file_path):
    '''
    get x, y, z value from csv file
    csv file format: x0,y0,z0
    '''
    x = []
    y = []
    z = []
    map_value = {}

    for line in open(csv_file_path):
        list = line.split(",")
        temp_x = float(list[0])
        temp_y = float(list[1])
        temp_z = float(list[2])
        x.append(temp_x)
        y.append(temp_y)
        z.append(temp_z)
        map_value[(temp_x, temp_y)] = temp_z

    return x, y, map_value

def draw_heatmap(x, y, map_value):

    plt_x = np.asarray(list(set(x)))
    plt_y = np.asarray(list(set(y)))
    plt_z = np.zeros(shape = (len(plt_x), len(plt_y)))

    for i in range(len(plt_x)):
        for j in range(len(plt_y)):
            if map_value.has_key((plt_x.item(i), plt_y.item(j))):
                plt_z[i][j] = map_value[(plt_x.item(i), plt_y.item(j))]

    z_min = plt_z.min()
    z_max = plt_z.max()
    plt_z = np.transpose(plt_z)

    plot_name = "demo"

    color_map = plt.cm.gist_heat #plt.cm.rainbow #plt.cm.hot #plt.cm.gist_heat
    plt.clf()
    plt.pcolor(plt_x, plt_y, plt_z, cmap=color_map, vmin=z_min, vmax=z_max)
    plt.axis([plt_x.min(), plt_x.max(), plt_y.min(), plt_y.max()])
    plt.title(plot_name)
    plt.colorbar().set_label(plot_name, rotation=270)
    ax = plt.gca()
    ax.set_aspect('equal')
    figure = plt.gcf()
    plt.show()
    return figure

if __name__ == "__main__":
    csv_file_name = "test.csv"
    create_test_csv(csv_file_name)
    x, y, map_value = get_xyz_from_csv_file(csv_file_name)
    draw_heatmap(x, y, map_value)

Function create_test_csv() created a test csv file. Function get_xyz_from_csv_file() create x, y coordinates list and a dict which key is tuple (x,y) and value is v. Function draw_heatmap() plot the heat map using list x, y and dict map_value.

It works but I would like to know if there is some more straightforward way to this, especially the transition from CSV to the matrix that created the heat map. It might worth to notice that in my real case the coordinate may not be integer.


texts: Find spiral 2D matrix (List of Lists) of ints in a clockwise spiral

texts:
I got this question during my interview with Microsoft.

The question called 2D Snake. I'm wondering if my solution 1 passes the test, but if my solution 1 different from solution 2.

  Let's have some fun with 2D Matrices! Write a method find_spiral to
  traverse a 2D matrix (List of Lists) of ints in a clockwise spiral
  order and append the elements to an output List of Integers.

  Example:

  Input Matrix:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

  Output List: [1, 2, 3, 6, 9, 8, 7, 4, 5]

Solution 1

def find_spiral(matrix):

    output = []

    while matrix:
        row = matrix.pop(0)
        output.extend(row)
        matrix = zip(*matrix)[::-1]

    return output

Solution 2

def find_spiral(matrix):
    spiral_list = []
    if matrix == None or len(matrix) == 0:
        return list
    m = len(matrix)
    n = len(matrix[0])
    x=0
    y=0

    while(m>0 and n>0):
        if(m==1):
            i = 0
            while i < n:
                spiral_list.append(matrix[x][y])
                i += 1
                y += 1
            break
        elif(n==1):
            i = 0
            while i < m:
                spiral_list.append(matrix[x][y])
                i += 1
                x += 1
            break

        i = 0
        while i < n-1:
            spiral_list.append(matrix[x][y])
            i+=1
            y+=1

        j = 0
        while j < m-1:
            spiral_list.append(matrix[x][y])
            j+=1
            x+=1

        i = 0
        while i < n-1:
            spiral_list.append(matrix[x][y])
            i+=1
            y-=1

        j = 0
        while j < m-1:
            spiral_list.append(matrix[x][y])
            j+=1
            x-=1

        x+=1
        y+=1
        m=m-2
        n=n-2

    return spiral_list

Test cases:

Input
[[1,2],[3,4]]
Expected Result
[1, 2, 4, 3]
Input
[[1,2],[3,4]
Expected Result
[1, 2, 4, 3]

Input
[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Expected Result
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

input
[[1,2],[3,4]
Expected Result
[1, 2, 3, 4, 5, 6, 12, 18, 17, 16, 15, 14, 13, 7, 8, 9, 10, 11]

Input
[[1,0],[0,1]]
Expected Result
[1, 0, 1, 0]

Input
[[1,2,3],[4,5,6],[7,8,9]]
Expected Result
[1, 2, 3, 6, 9, 8, 7, 4, 5]


texts: Run dir scan as fast and efficient as possible / clean code

texts:
I'm not a very experience python programmer. But I want to make my code as fast and efficient as possible as well as write it clean and therefore got the advice to share it here. So I'm having the following code, which works well but isn't very fast as I have dirs bigger than 4TB and I'm executing that code in my network. So I'm looking for advice, to read out all data in one path instead of doing redundant second scanning of dirs and files. Any advice would be appreciated!
I'm also thinking of how to implement multiprocessing but I think that wouldn't help much as a lot is IO.

def get_size_and_fcount_pathlib(scan_path):
    """Gets the total size of given dir and counts how many folders and files are in the given
    path directory and return a file count, folder count and all types as a sum"""
    root_directory = Path(scan_path)
    total_size = 0
    all_types_count = 0
    file_count = 0
    folder_count = 0
    for f in root_directory.glob('**/*'):
        if f.is_file():
            file_count += 1
            total_size += f.stat().st_size
            if not str(f.name).startswith("."):
                all_types_count += 1
        if f.is_dir():
            folder_count += 1
    size_gb = ", ".join(map(str, (round(total_size/1000/1000/1000, 2), 'GB'))).replace(', ', '')

    print('Amount of all types searched: {}'.format(all_types_count))
    print('Amount of files searched:     {}'.format(file_count))
    print('Amount of folders searched:   {}'.format(folder_count))
    print('Directory size in GB:         {}'.format(size_gb))

    file_count_collection = [size_gb, all_types_count, file_count, folder_count]
    return file_count_collection


texts:
I finally converted my horrific HTML regex parsing:

if (
    $info =~ /
    Platform\sType<\/td>\n\s+(.*?)<\/b>(.*?)<\/td>.*
    Codeset<\/td>\n\s+(.*?)<\/i>.*
    Status<\/td>\n\s+\n\s+
(.*?)<\/div>
.*
    Instance\sID<\/td>\n\s+(.*?)<\/td>.*
    Instance\sName<\/td>\n\s+(.*?)<\/td>.*
    Brand<\/td>\n\s+(.*?)<\/span>.*
    Date\sAdded<\/td>\n\s+(.*?)<\/td>.*
    Date\sUsed<\/td>\n\s+(.*?)<\/td>.*
    Date\sModified<\/td>\n\s+(.*?)<\/td>.*
    Flavor\sid<\/td>\n\s+(\d+)<\/td>.*
    Flavor\sname<\/td>\n\s+(.*?)<\/td>.*
    Image\sgroup\sid<\/td>\n\s+(.*?)<\/td>.*
    Image\sid<\/td>\n\s+(.*?)<\/td>.*
    Image\sname<\/td>\n\s+(.*?)<\/td>.*
    Customer\suid<\/td>\n\s+<input(?:.*?)value="(.*?)">.*
    Back\sreference<\/td>\n\s+<input(?:.*?)value="(.*?)">.*
    HG\sserver\sid<\/td>\n\s+<input(?:.*?)value="(.*?)">.*
    HG\sMigration\sState<\/td>\n\s+(?:.*?)<option\sselected="selected">(.*?)<\/option>.*
    HG\sUsed<\/td>(?:.*?)selected="selected">(.*?)<\/option>.*
    HG\slast\smodified<\/td>(?:.*?)value="(.*?)">.*
    Box\sIP<\/td>\n\s+.*
    Box\sHostname<\/td>\n\s+(.*?)\s\(<a.*
    Volumes<\/td>\n\s+\n\s+(.*?)<\/td>.*
    Addons<\/td>\n\s+\n\s+(.*?)<\/td>.*
    Main\sIP<\/td>\n\s+(?:.*?)data-ip="(.*?)"(?:.*?)inline-block">(.*?)<\/div>.*?

(.*?)<\/table>
    /xsm
  )
{

To what I hope is the right way of doing things, however, I feel like there could be some improvements.

my $tree = HTML::TreeBuilder->new;
$tree->parse_file($file_name);
$tree->eof();
my $t = Text::ASCIITable->new({headingText => 'HAL Server Report'});
$t->setCols('Field', 'Result');
$t->alignCol({Result => 'left'});
my $table = $tree->look_down(_tag => 'table', class => 'grid');
foreach my $tr ( $tree->look_down(_tag => 'tr') ) {
    last if $tr->look_down(_tag => 'td', class => 'key', sub { $_[0]->as_text() eq 'Meta' });
    my @tmp;
    my $count = 0;
    foreach my $td ( $tr->look_down(_tag => 'td') ) {
        if ( $count < 2 ) {
            if ( $td->look_down(_tag => 'select') ) {
                    my $select = $td->look_down(_tag => 'option', sub { $_[0]->attr('selected') });
                    push @tmp, $select->as_text() if $select;
            } elsif ( $td->look_down(_tag => 'input') ) {
                    my $input = $td->look_down(_tag => 'input', sub { $_[0]->attr('value') });
                    push @tmp, $input->attr_get_i('value') if $input;
            } elsif ( $td->look_down(_tag => 'table', class => 'concise') ) {
                    my @ips;
                    foreach my $td2 ( $td->look_down(_tag => 'tr') ) {
                        my $ip = $td2->look_down(_tag => 'td', sub { $_[0]->attr('data-ip') });
                        push @ips, $ip->attr_get_i('data-ip') if $ip;
                    }
                    push @tmp, join ", ", @ips;
            } else {
                push @tmp, $td->as_trimmed_text();
            }
        }
        $count++;
    }
    if ( $tmp[0] =~ /^([a-zA-Z0-9]+)([ a-zA-Z0-9]+?)$/ ) {
        $t->addRow($tmp[0], $tmp[1]);
    }
}
print $t;


texts: Nested routes and proper place for a function?

texts:
I have a Rails app and in it I have two models, widget and votes. Votes are used to keep track of the desirability of a widget.

In my models I have:

class Vote < ActiveRecord::Base
    belongs_to :widget
end

class Widget < ActiveRecord::Base
    has_many :votes
end

I am trying to figure out the best way to route votes up and votes down. At the moment I am leaning towards this:

resources :widgets do
  member do
      put :vote_up
      put :vote_down
  end
end

Where the respective functions reside in the widgets' controller and it creates and saves votes in that controller. However, I realize that this doesn't really fit correctly with the MVC idea (votes should be created and built in their own controller). Is this acceptable or should I be doing something more like:

resources :widgets do
  resources :votes do
    member do
        put :vote_up
        put :vote_down
    end
  end
end


texts:
I have created a function that will remove outliers from a series of data. Generally the data n dimensional. Loosely, an outlier is considered an outlier if it +/- deviates by 1.5 standard_deviation's from the mean (see code for more detailed explanation of what constitutes an outlier).

The function can handle N dimensional arrays. It uses numpy and my code admittedly does not utilise numpy's iteration techniques. So I would appreciate how to improve this code and utilise numpy more.

import cv2
import numpy as np

def remove_outliers(data, thresh=1.5, axis=(0,1), use_median=False):
    # Post: Remove outlier values from data. A value in data is considered an outlier if it is NOT mean-std_deviation*thresh < value < mean+std_deviation*thresh

    res                 = []
    median              = np.median(data, axis)
    mean, std_dev       = cv2.meanStdDev(data)
    measure             = median if use_median else mean
    lower_thresh        = np.subtract(measure, np.multiply(std_dev, thresh))
    upper_thresh        = np.add(measure, np.multiply(std_dev, thresh))

    # Handle arrays that are n dimensional
    if len(data.shape) == 3:
        data = data.reshape((int(data.size/3), 3))

    for v in data:
        if np.all(v > lower_thresh) and np.all(v < upper_thresh):
            res.append(v)

    return res

if __name__ == "__main__":
    arr = np.array([10,99,12,15,9,2,17,15])
    print(arr)
    print(remove_outliers(arr, axis=0, thresh=1.5))

    arr = np.array([[(0,10,3),(99,255,255),(100,10,9),(45,34,9)]], dtype='uint8')
    print(arr)
    print(remove_outliers(arr, thresh=1.5))


texts:
This code animates my main game sprite by increasing the animation frame. First I check if the character is moving, then I increase the animation counter until it reaches the desired speed, and then if so, I increase the animation frame.

How can I make it more elegant and optimised in terms of speed?

       if (moving){
        anispeed++;
        if (anispeed==animaxspeed){
            anispeed=0;
            animationframe++;
            if (animationframe==3) animationframe=0;
        }


texts:
I tried to solve a  merge two sorted list problem in leetcodes:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        """
        Plan:
        Compare l1 and l2 and merge the remainders
        """
        l3_head = ListNode(0)
        l3_cur = l3_head

        while l1 and l2: #assert both exist
            if l2.val < l1.val:
                l3_cur.next = l2 #build l3's node
                l2 = l2.next #this is i++
            else:
                l3_cur.next = l1
                l1 = l1.next
            l3_cur = l3_cur.next #find the next to build
        if l1:
            l3_cur.next = l1
        if l2:
            l3_cur.next = l2

        return l3_head.next

I assumed this is a decent solution but got:

Runtime: 56 ms, faster than 23.98% of Python3 online submissions for Merge Two Sorted Lists.
Memory Usage: 13.1 MB, less than 5.06% of Python3 online submissions for Merge Two Sorted Lists.

How could I improve my solution?


texts: Find top two clothing sizes in the array

texts:
I was recently asked this question in an interview. Here is the solution I came up with. Please let know if I could have done this differently or in a more efficient manner.

The question is as follows:

  Determine The Top Two Clothes Sizes In The Following Array

["XS","S","S","M","L","XL","XLL","XL","XL","M","M","M","XS","XS","XS","XS"]

  The solution should be [ 'XS', 'M' ] since XS occurs 5 times and M
  occurs 4 times.

function determineTopTwo(arr){
let map = {};
let resultArr = [];
let result = [];
for(let i = 0; i < arr.length; i++){
    if(!map[arr[i]]){
        map[arr[i]]=1;
    }else{
        map[arr[i]]++;
    }
}

for(key in map){
    resultArr.push([map[key],key]);
}
let newArr = resultArr.sort((a,b)=>{
    return a[0]-b[0];
});

result.push(newArr[newArr.length-1][1], newArr[newArr.length-2][1]);
return result;
}


texts: Loose string matching for words in postal addresses

texts:
I'm trying to compare every element in a vector with every other.

From a dataframe of addresses, I extract streets for a zip code. And a vector of these street strings (like "123 main avenue") is the input.

streets <- c ("123 main avenue", "123 main ave", "456 paul st",
              "456 paul street", "1 r parkway", "1 r pkwy")

I want to test for similarity of strings (like the one before with "123 main ave"). I could use string distance on the substrings, but preferred grep.

I want to avoid the nested for loop, but cannot think of anything better. Here's what I am trying to do:

compare = function(postal_code)
{
streets <- as.vector(props[props$Zip == postal_code,]["Street"])
cnt <- lengths(streets)[1][1]

#Assume two streets "123 main ave" and "123 main avenue"

for (i in 1:cnt)
{
    for (j in 1:cnt)
    {

    prop1 = streets[[1]][i]
    prop2 = streets[[1]][j]

    #split "123 main avenue" into parts
    prop1_parts = strsplit(trimws(prop1), ' ')
    prop2_parts = strsplit(trimws(prop2), ' ')
    prop1_parts_count = length(prop1_parts[[1]])
    prop2_parts_count = length(prop2_parts[[1]])

    #only if the parts of the two streets are equal
    if (prop1_parts_count == prop2_parts_count)
        {
            #compare apples to apples: 123 with 123, main with main, and ave with avenue
           for (x in 1:prop1_parts_count)
            {
                part1 = prop1_parts[[1]][x]
                part2 = prop2_parts[[1]][x]

                if (part1 == part2) { matched = matched & TRUE }
                else {
                    #ignore number parts like 123
                    if (any(grep("[[:alpha:]]", part1)) & any(grep("[[:alpha:]]", part2))) {
                    #check if avenue is in ave or ave is in avenue
                    if (any(grep(part1, part2)) | any(grep(part2, part1))) {
                            matched = matched & TRUE
                            print(paste0(prop1, '-', prop2))
                        }
                    }
                    else {
                        matched = matched & FALSE
                        break #to pass to the next string
                    }
                }
            }
        }
    }
 }
}

For a vector with 104 streets, the comparisons should be (104*103)/2; but with this code it is 104**2; and for these 10816 comparisons, the benchmark is:

I compiled the function as well but no improvement in the execution time.

Any elegant/quick way to improve this code is appreciated.


texts: Evaluating an XPath with document.evaluate() to get an array of nodes

texts:
The Problem Statement:

  Filter all nodes with an existing attribute that starts with a specific string (temp for example purposes). Print an array of node string representations as a result.

The Code:

var result = document.evaluate("//*[@*[starts-with(name(), 'temp')]]", document, null, XPathResult.ANY_TYPE, null);

var node = result.iterateNext();
var nodes = [];
while (node) {
  nodes.push(node);
  node = result.iterateNext();
}
console.log(nodes);

The code is a bit bulky for such a straightforward problem. Is there a simpler and a more concise way to get an array of nodes from a document.evaluate() result?