texts:
I'm creating a little proposal for the data access layer using Dapper ORM.

The code is based in an generic interface IStore:

public interface IStored
{
    int Execute(string Name);
    int Execute<Output>(string Name, Output Parameters) where Output : class;
    IEnumerable<Output> ExecuteReader<Output>(string Name) where Output : class;
    IEnumerable<Output> ExecuteReader<Input, Output>(string Name, Input Parameters)
        where Output : class
        where Input : class;
}

This is the implementation:

public class Stored : DataBaseContext, IStored
    {
        public Stored() : base() { }

        public int Execute(string Name)
        {
            try
            {
                Connection.Open();
                var result = Connection.Execute(Name, commandType: CommandType.StoredProcedure);
                Connection.Close();

                return result;
            }
            catch (Exception ex)
            {
                if (Connection.State == ConnectionState.Open)
                    Connection.Close();
                return -1;
            }
        }

        public int Execute<T>(string Name, T Parameters) where T : class
        {
            try
            {
                Connection.Open();
                var result = Connection.Execute(Name, Parameters, commandType: CommandType.StoredProcedure);
                Connection.Close();

                return result;
            }
            catch (Exception ex)
            {
                if (Connection.State == ConnectionState.Open)
                    Connection.Close();
                return -1;
            }
        }

        public IEnumerable<Output> ExecuteReader<Output>(string Name) where Output : class
        {
            try
            {
                Connection.Open();
                var result = Connection.Query<Output>(Name, commandType: CommandType.StoredProcedure);
                Connection.Close();

                return result;
            }
            catch (Exception ex)
            {
                if (Connection.State == ConnectionState.Open)
                    Connection.Close();

                return null;
            }
        }

        public IEnumerable<Output> ExecuteReader<Input, Output>(string Name, Input Parameters)
            where Output : class
            where Input : class
        {
            try
            {
                Connection.Open();
                var result = Connection.Query<Output>(Name, Parameters, commandType: CommandType.StoredProcedure);
                Connection.Close();

                return result;
            }
            catch (Exception ex)
            {
                if (Connection.State == ConnectionState.Open)
                    Connection.Close();

                return null;
            }
        }
    }

Is this code a good proposal? What can I do to improve it?


texts:
Description

Print all student names from a CSV file.

CSV Format:

CSV file does not contain string delimited by double quotes.
None of the cells has "," character or "\"" character.
There are exactly two columns.
No empty cells.

Code

csvread.pl

#!/usr/bin/perl

use strict;
use warnings;

my $filename = "students.csv";
open (STUDENTS,$filename) ||  die "Cannot Open '$filename'";

# get column names
my $line = <STUDENTS>;
chomp($line);
my @column_names = split(",",$line);

print "Printing Student ${column_names[1]}s...\n";

# get all names
while($line = <STUDENTS>){
    chomp($line);
    (my $id,my $name) = split(",",$line);
    print "$name\n";
}

#--------------------------------------------------------
# documentation
#

=head1 NAME

Print Student Names

=head1 SYNOPSIS

    chmod a+x ./csvread.pl
    ./csvread.pl

=cut

students.csv

ID,Name
1,Ashani
2,Sandeepani
3,Nimesha
4,Kaveesha
5,Abimani
6,Himadu
7,Vishmi
8,Shela
9,Vishvani
10,Claudia
11,Dinuwanthi
12,Anthonella
13,Sachini
14,Hiruni
15,Nimesha
16,Kavindi
17,Roshini
18,Dilini
19,Devinka
20,Noela
21,Nithmi
22,Azekah
23,Ishara
24,Andriya
25,Rishini
26,Shashini
27,Oshadhi
28,Sandali
29,Jehani
30,Thamasha
31,Shalini
32,Milka
33,Gihani
34,Sakuni
35,Piumi
36,Stefania
37,Kinkini
38,Shehana
39,Nimanshi
40,Emalsha
41,Shohani
42,Madusha
43,Nisaja
44,Kiyara
45,Dinithi
46,Sadunika
47,Sewmini
48,Rachel

Review

Conventions/Generic


texts:
Here's my code that takes a large string, and searches for the longest reoccurring substring. It compares the first letter with every other until it finds a match, then saves it. Then it compares the first 2 letters with every other until it finds a match then saves it. Then 3, 4, etc... Then it comes back around and starts with the second letter and checks the first letter, then the first 2, then the first 3, etc.

I plan on using this on text files as large as a novel. The time complexity is horrendous. I think it's O(n# of characters in the text file). Is there any other way to approach this?

def largest_substring(string):

    length = 0
    x=0
    y=0

    for y in range(len(string)):
        for x in range(len(string)):
            substring = string[y:x]
            if len(list(re.finditer(re.escape(substring),string))) > 1  and len(substring) > length:
                match = substring
                length = len(substring)
    return match


texts: Bash Script - batch rename files in current directory with preview

texts:
I have written the following script to automate my frequent usage of rename.
This saves me from always typing the whole command to the command line as well as doing a dry run with -n for testing before applying the pattern.

#!/bin/bash

 if [ ! -d ~/.script-history ]; then
     echo -e "Folder .script-history does not exist and gets created... \n";
     mkdir ~/.script-history\
      && { echo -e "created folder: ~/.script-history \n"; }\
      || { echo -e "could not create folder: ~/.script-history \n"; }
 fi

 history -r ~/.script-history/rename
 set -o vi
 search=""
 replace=""

 echo -e "Please enter token to be replaced: "
 read -e -r search
 history -s "$search"
 echo -e "Please enter replacement: "
 read -e -r replace
 history -s "$replace"
 history -w ~/.script-history/rename

 value=$(rename -n "s/$search/$replace/g" ./*)

 echo -e "$value"

 lines=$(echo -en "$value" | wc -m)

 if [ "$lines" -gt 0 ]; then
     read -p "Do you want to apply changes? [Y]es [n]o " yn
     case $yn in
         [yY]* ) echo "renaming files...";\
                 rename "s/$search/$replace/g" ./*\
                 && { echo "success :-)"; }\
                 || { echo "failed :-("; };;
         [nN]* ) echo "no changes have been made."; exit;;
         * ) echo "Are you kidding me???";;
     esac
 elif [ "$lines" -eq 0 ]; then
     echo -e "No matches found for <$search> !"
 fi

For making it easier to adjust or reuse the changes done with the script, I added a history, while the first part checks if the folder exists where I save my histories for script files. I do not quite understand this line set -o vi but it is working.
For me as a beginner it was quite tricky to get the script recognizing whether there are changes to be applied or not. My workaround here is the $lines variable, where I count the output of chars and then process with
"$lines" -gt 0 or "$lines" -eq 0.

One of the questions I have is about the usage of the A && B || C pipe. I use it quite frequently in my scripts, where ShellCheck reports the following:

  SC2015: Note that A && B || C is not if-then-else. C may run when A is true.

The other output of ShellCheck is:

  SC2162: read without -r will mangle backslashes.

I think it is ok, since the user is only expected to input YyNn. While I use the script on a daily basis, is the coding sufficient or where can it be improved?

The disadvantage of the script is that you have to type in both search and replacement before it checks if there are matches. An improvement could be to add a function that checks for that and returns to the search input when there are no matches.


texts: Getting a value from an Excel sheet column

texts:
The code below gets value from a column in an Excel sheet.  The values I get are B1, B2, B3, B4...., B100, ...Bn. All I need to do is strip out the char 'B' and convert the numeric string to integer and count how many times a particular integer has repeated.

The snippet below shows the string stripping the char 'B'. However I feel it can be done in better way but I don't know how.

if (range.Text.ToString() == "BayID")
{
    range = null;
    range = readSheet.get_Range(cell, Missing.Value);
    while (range.Text.ToString() != "")
    {
        range = null;
        string A1 = String.Empty, Val = String.Empty;
        char[] value = null;
        range = readSheet.get_Range(cell, Missing.Value);
        A1 = range.Text.ToString();
        value = A1.ToCharArray();
        j++;
        cell = "D" + j;
        for (int i = 1; i < value.Length; i++)
        {
            Val += value[i];
        }
   }
}


texts: Using for loops create new object with other objects with matching id's

texts:
I'm not sure if this is the best way to write this code..

object.array.forEach((item) => {
  object.otherarray.array.forEach((asset) => {
    if(item.fields.image.sys.id === asset.sys.id) {
      item.fields.image['fields'] = asset.fields;
    }
  })
});

any help would be appreciated!


texts: Importing Excel file to a database just once

texts:
How should I rewrite an if-return-else condition in the middle of this function?

def import_excel_to_database(xls_file_path)
  q_param = { report_type:report_type, item:product, exchange:exchange, product_exchange:row[0], date: row[2]} # timestamp_utc: row[2].strftime('%Q').to_i

  # if exsisted then return or continue the remaining
  if ImportHistory.where(q_param).exists?
    return false
  else
    ImportHistory.create(q_param)
  end

  xls = Roo::Excel.new(xls_file_path)
  xls.default_sheet = xls.sheets[0]
  columns = get_columns(xls.row(1))
  iterate_data_rows(xls_file_path, xls, columns)
end


texts:
Is it a good practice to initialize the max to -100000 and min to 100000? Is there any other way to initialize both min and max to 0?

 import javax.swing.*;
    import java.util.*;

public class arrayTajba
{
    public static void main(String[] args) throws Exception
    {
        String userStringInput = " ";
        String display = " ";
        int max = -100000;
        int min = 100000;
        int total = 0;
        double average;
        int i = 0;
        int [] num = new int [5];

        for (i = 0; i < num.length; i++)
        {
            userStringInput = JOptionPane.showInputDialog(null,"Please enter 5 numbers " + (i+1),"Input Table",JOptionPane.QUESTION_MESSAGE);
            num[i] = Integer.parseInt(userStringInput);

            display+=num[i] + ", ";
            total+=num[i];

            if (num[i] < min)
            {
                min = num[i];
            }
            if (num[i] > max)
            {
                max = num[i];
            }
        }
            average = total / num.length;

        JOptionPane.showMessageDialog(null,"The numbers you have entered are:\n" + display + "\nSum of all numbers is: " + total + "\nAverage is: " + average + "\nMinimum number is: " + min + "\nMaximum number is: " + max,"Output Table" ,JOptionPane.INFORMATION_MESSAGE);
        }
    }i


texts: Find the highest frequency of messages inside a time slot of 24 hours

texts:
I have a very large number (millions) of messages, each labeled with the unixtime it was sent in a SQLite database. Each message has its own userid, for the user that have sent it. I want to know what's the max number of messages that is sent within an 24hr timeslot for each user. The 24hr timeslot is defined as the time from one message to another. So if there are five messages, where the 5th one is sent 24 hours after the first one, 5 is the number I want.

I have code that gives me this frequency, but the problem is that the running time of this is just too large - and I guess thats partly because of my not-optimal code, and too high complexity. How can I optimize this?

    con = lite.connect(databasepath)
    userID = []
    messages = []
    messageFrequency = []
    with con:
        cur = con.cursor()
        #Get all UserID
        cur.execute('SELECT DISTINCT userid FROM MessageType1')
        userID = cur.fetchall()
        userID = [x[0] for x in userID]
        #For each UserID
        for user in userID:
            messageFrequency.append(0)
            #Get all MSG with UserID = UserID sorted by UNIXTIME
            cur.execute('SELECT unixtime FROM MessageType1 WHERE userID ='+str(user)+' ORDER BY unixtime asc')
            Messages = cur.fetchall()
            Messages = [x[0] for x in Messages]
            length = len(Messages)
            #Loop through every MSG
            for message in Messages:
                index = Messages.index(message)
                nextmessage = Messages[index+1]
                frequency = 0
                #Loop through every message that is within 24 hours
                while nextmessage < message+(24*60*60) and index<length-1:
                    #Count the number of occurences
                    frequency += 1
                    index += 1
                    nextmessage = Messages[index]
                #Add best benchmark for every message to a list
                if messageFrequency[-1]<frequency:
                    messageFrequency[-1] = frequency


texts:
I'm putting together a simple application container for learning purposes, and I would like to hear how you see this code. The application is the main class that will contain services, configuration and other related stuff.

I have identified 3 position where I can't decide on the design:

Each application should be supplied with configuration array. The configuration will be loaded automatically, so some class has to deal with it. Does Kernel class is the right place to put it? The Kernel class is intended to contain some common functions, like getRootPath(). Does it starts to violate SRP in this case?
Does getType() look like the right way to define type of application? Should i make it abstract or provide some default type in parent class?
Overall, does Kernel class fits the purpose of creating application instances and supplying required configuration and calling ready() on application?

namespace App;

interface Executable {
    public function run();
    public function ready();
}

abstract class Application implements Executable {
    const TYPE_WEB = 'web';
    const TYPE_CLI = 'cli';

    /**
    * Application name
    * @var string
    */
    protected $name = '';

    /**
    * Application configuration
    * @var array
    */
    protected $config = [];

    public function __construct($name, array $config=[]) {
        $this -> name = $name;
        $this -> config = $config;
    }

    public function ready() {
        // Application is ready, register services here...
    }

    public function run() {
        // Execute application lifecycle
    }
}

class WebApplication extends Application {
    public function getType() {
        return self::TYPE_WEB;
    }
}

class ConsoleApplication extends Application {
    public function getType() {
        return self::TYPE_CLI;
    }
}

abstract class Kernel {
    /**
    * Instantiated applications
    * @var Executable[]
    */
    private static $apps = [];

    /**
    * Creates new application
    * @param string $name Application name
    * @param string $type Application class
    */
    public static function createApp($name, $type) {
        /* Some validations skipped */

        $app = self::$apps[$name] = new $type($name, self::loadConfiguration($name));
        $app -> ready();

        return $app;
    }

    private static function loadConfiguration($name) {
        /* Load configuration from files and from multiple places */
        return [
            'key' => 'value'
        ];
    }

    public static function getRootPath() {
        // Return path to document root
    }
}

/**************/
App\Kernel::createApp('test', 'WebApplication') -> run();


texts:
After the feedback for my last script, I realized I should be using functions and trying to adhere to the style guide. I tried to do that here, though still very beginner.

The rounding in Python confused me a bit, and originally the program got stuck for some numbers when the range narrowed down to 1. I think it should work for all cases now (only tested 1-1000).

# Users chooses number in given range, comp guesses

HIGH_NO = 10000
LOW_NO = 1

def getno():
    # Get a number in range from user.
    x = ""
    while not x or x > HIGH_NO or x < LOW_NO:
        print("Enter a number between %s and %s" % (LOW_NO, HIGH_NO))
        x = input()
        try:
            x = int(x)
        except ValueError:
            x = getno()
    return(x)

def approxhalf(lowno, highno):
    # Find integer approx halfway point between two values.
    x = abs(round((lowno+highno)/2))
    return x

def guessno():
    # Computer finds number by halving
    no1 = LOW_NO
    no2 = HIGH_NO
    userno = getno()
    compguess = ""
    count = 0

    while compguess != userno:
        count += 1
        compguess = approxhalf(no1, no2)

        if abs(no2-no1) > 2 or compguess == userno:
            print('%s. I guess %s' % (count, compguess))
            if compguess > userno:
                no2 = compguess
            elif compguess < userno:
                no1 = compguess
            elif compguess == userno:
                print("Got it!")
            else:
                print("wtf dude")
        else:
            # For when the low and high no.s are consecutive
            if no1 == userno:
                print('%s. I guess %s' % (count, no1))
                print("Got it")
                break
            elif no2 == userno:
                print('%s. I guess %s' % (count+1, no2))
                print("Got it")
                break
            else:
                print("I.. I don't understand")

def main():
    while True:
        guessno()
        print('\n')

main()


texts: Best practice for URL's architectural Design in Django

texts:
I have been designing websites with Django for a while and I have also designed various sites. But here is a question that comes to mind at the beginning of any new project:
What is the best URLs architectural Design that creates both logical and meaningful URLs path as well as pluggable apps?
I will explain my question with a practical example.
Practical Example And Problem
Suppose that we have project with these features:

It has three applications called Shop, Blog and Support.

It has three URL section:
2.1. Public section: that start with /.
2.2. Consumer panel: that start with /panel.
2.3. Administrator panel: that start with /administrator.

Each application has 3 views. For example Shop has: public_shop_view, panel_shop_view and administrator_shop_view.
Now, What is the best URL design for this project? I describe two possible answers here for URLs design.
Solution 1:
project/urls.py
path('', include('Shop.urls', namespce='Shop')),
path('', include('Blog.urls', namespce='Blog')),
path('', include('Support.urls', namespce='Support')),

Shop/urls.py
path('shop/', views.public_shop_view, name='public_shop_view'),
path('panel/shop/', views.panel_shop_view, name='panel_shop_view'),
path('administrator/shop/', views.administrator_shop_view, name='administrator_shop_view'),

Blog/urls.py
path('blog/', views.public_blog_view, name='public_blog_view'),
path('panel/blog/', views.panel_blog_view, name='panel_blog_view'),
path('administrator/blog/', views.administrator_blog_view, name='administrator_shop_view'),

Support/urls.py
path('support/', views.public_support_view, name='public_support_view'),
path('panel/support/', views.panel_support_view, name='panel_support_view'),
path('administrator/support/', views.administrator_support_view, name='administrator_support_view'),

Solution 2:
In this solution we create three apps (Public, Panel, Administrator) that just have urls.py file (to follow the interface strategy):
project/urls.py
path('', include('Public.urls', namespce='Interface')),
path('panel/', include('Panel.urls', namespce='Panel')),
path('administrator/', include('Administrator.urls', namespce='Administrator')),

Public/urls.py
from Support import views as support_views
from Blog import views as blog_views
from Shop import views as shop_views

path('support/', support_views.public_support_view, name='public_support_view'),
path('blog/', blog_views.public_blog_view, name='public_blog_view'),
path('shop/', shop_views.public_shop_view, name='public_shop_view'),

Panel/urls.py
from Support import views as support_views
from Blog import views as blog_views
from Shop import views as shop_views

path('support/', support_views.panel_support_view, name='panel_support_view'),
path('blog/', blog_views.panel_blog_view, name='panel_blog_view'),
path('shop/', shop_views.panel_shop_view, name='panel_shop_view'),

Administrator/urls.py
from Support import views as support_views
from Blog import views as blog_views
from Shop import views as shop_views

path('support/', support_views.administrator_support_view, name='administrator_support_view'),
path('blog/', blog_views.administrator_blog_view, name='administrator_blog_view'),
path('shop/', shop_views.administrator_shop_view, name='administrator_shop_view'),

Now, What is the best practice? Solution 1 or solution 2 or other solution?


texts: A simple calculator to calculate the frequency of a recessive allele

texts:
It's based on the Hardy-Weinberg formula. I used the easygui module because I don't fully understand events in Tkinter yet. It's my first relatively useful script so any constructive criticism would be helpful.

from __future__ import division
import sys
from easygui import *
def calculate_frequency(recessive,total):
    q = (recessive/total)**0.5 #square root of q^2
    p = 1-q #since p + q = 1, p = 1-q
    hzDominantNum = round((p**2)*total,2) #number of homozygous dominant, not percent
    hzRecessiveNum = round((q**2)*total,2)
    heterozygousNum = round((2*p*q)*total,2)
    hzDominantFreq = round((p**2)*100,2) #frequency (percent)
    hzRecessiveFreq = round((q**2)*100,2)
    heterozygousFreq = round((2*p*q)*100,2)
    return hzDominantNum,hzRecessiveNum,heterozygousNum,hzDominantFreq,hzRecessiveFreq,heterozygousFreq #returns all calculations to be printed
while True: #loops program until terminated
    msg = "Leave Total as 100 if you want to enter the percent." #main message lets user know how to input as percent
    fieldNames = ["How many have the recessive trait","Total population"]
    fieldValues = ['',100] #first one is blank, the second is defaulted to 100 to make inputing percents easier
    test = 0 #tests if the proper information has been entered. Test will equal 1 if the conditions are met.
    while test == 0:
        fieldValues = multenterbox(msg=msg, title='Enter information about the population', fields=fieldNames, values=fieldValues)
        if fieldValues == None: sys.exit() #None is returned when the user clicks "Cancel"
        elif not fieldValues[0].isdigit() or not fieldValues[1].isdigit():
            if not ccbox("Please fill out all fields.",'ERROR',('OK','Quit')): sys.exit()
        elif int(fieldValues[0])>int(fieldValues[1]):
            if not ccbox("The amount of people with the recessive trait can't be bigger than the total population.",'ERROR',('OK','Quit')): sys.exit()
        else: test=1
    recessive = int(fieldValues[0])
    total = int(fieldValues[1])

    hzDominantNum,hzRecessiveNum,heterozygousNum,hzDominantFreq,hzRecessiveFreq,heterozygousFreq = calculate_frequency(recessive,total)
    #displays all the information
    msg = str(hzDominantNum)+'/'+str(total)+' ('+str(hzDominantFreq)+'%) are normal (homozygous dominant).\n'+'''
    '''+str(heterozygousNum)+'/'+str(total)+' ('+str(heterozygousFreq)+'%) are carriers (heterozygous).\n'+'''
    '''+str(hzRecessiveNum)+'/'+str(total)+' ('+str(hzRecessiveFreq)+'%) have the recessive trait (homozygous recessive).'
    #sees if user wants to quit or continue
    if not ccbox(msg=msg, title='RESULTS', choices=('Continue', 'Quit'), image=None): sys.exit()


texts: Find the 2 distinct highest values in an array

texts:
I want to know if there is a way to improve my code.  It finds the two highest values in an array, and these numbers need to be distinct.

I don't want to sort the values; I just want to find them.

My idea is to create a new array if the length is even and compare the pair of values to find the minimum and maximum values.

So, later, I find the second highest value.

package doze;

public class Elementos {

    public int maxValue(int array[], int arrayLength) {

        arrayLength = array.length;

        if ((arrayLength % 2) > 0) {
            arrayLength++;
            int aux[] = array;
            array = new int[arrayLength];
            for (int i = 0; i < aux.length; i++) {
                array[i] = aux[i];
            }
            array[(arrayLength - 1)] = aux[(arrayLength - 2)];
        }

        int maxValue = array[0];
        int minValue = array[0];
        int i = 0;

        while (i != arrayLength) {
            if (array[i] > array[i + 1]) {
                if (array[i] > maxValue) {
                    maxValue = array[i];
                }
            if (array[i + 1] < minValue) {
                minValue = array[i + 1];
            }
            } else {
                if (array[i + 1] > maxValue) {
                    maxValue = array[i + 1];
                }
                if (array[i] < minValue) {
                    minValue = array[i];
                }
            }
            i += 2;
        }

        int secondMaxValue = minValue;
        i = 0;
        while (i != arrayLength) {
            if ((array[i] > minValue) && (array[i] < maxValue)) {
                minValue = array[i];
                secondMaxValue = minValue;
            }
            i += 1;
        }

        return maxValue;
    }
}


texts: Simple Bash Parallel Tool (env_parallel dies on big env)

texts:
This is a simple tool to parallelize execution of multiple tasks in Bash, since env_parallel can't handle the environment size (or something of the sort - dies for mysterious reasons.) I'd love to hear your critique.

#
# Simple parallel executor. Takes a list of commands and executes each in its own child process. Assumes commands are distinctly named.
# Returns with 0 if all are successful. Otherwise, prints out their stdout/stderr outputs and returns with 1.

function simple_par () {

    local TMP_FILE="${WRITABLE_DIR}/simple_par_$(uuidgen)"
    touch $TMP_FILE

    for prog in "$@"
    do
        local PROG_TMP="${TMP_FILE}_${prog}_$(uuidgen)"
        (
            ( $prog 1>$PROG_TMP 2>&1 )
            echo "$?" >> $TMP_FILE
        ) &
    done

    while true
    do
        RESULT_COUNT=$(wc -l ${TMP_FILE} | awk '{ print $1 }')

        if [[ $RESULT_COUNT -eq $# ]]; then
            if [[ $(cat $TMP_FILE) == *"1"* ]]; then
                echo "Failed at least one command"
                for prog in "$@"
                do
                    echo "OUTPUT FOR: $prog"
                    cat ${TMP_FILE}_${prog}_*
                    rm ${TMP_FILE}_${prog}_*
                done

                rm $TMP_FILE
                return 1
            else
                return 0
            fi
        fi

        sleep 5
    done
}


texts: Mockup in C of hardware implementation for multiplication of signed integers

texts:
I challenged myself to implement multiplication of signed integers using only +, -, >>, <<, &, |, ^, and conditionals, though I would like to improve my method to not use conditionals if possible in the future. Any input would be very helpful.

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

int multiply(int, int);

int main() {
    int a, b, c, i;
    bool equal;

    srand(time(NULL));

    for (i = 0; i < 100; i++) {
        // 0x8000 to ensure no integer overflow is possible
        a = (rand() % 0x8000) * (rand() % 2 ? -1 : 1);
        b = (rand() % 0x8000) * (rand() % 2 ? -1 : 1);
        c = multiply(a, b);
        equal = (c == a * b);

        printf("%-11d * %-11d = %-11d (%s)\n", a, b, c, (equal ? "Success" : "Failure"));

        if (!equal) {
            return EXIT_FAILURE;
        }
    }

    return EXIT_SUCCESS;
}

int multiply(int a, int b) {
    struct {
        unsigned char index : 5;
    } bit;

    int c = INT_MAX & a, // remove sign bit
        d = INT_MAX & b,
        sign = (INT_MIN & a) ^ (INT_MIN & b), // sign of product
        mask = 0x40000000,
        prod = 0;

    bit.index = 30; // keeping track of mask bit index

    do {
        prod += (mask & c ? d << bit.index : 0);
    } while ((bit.index--) && (mask >>= 1));

    return sign | (prod & INT_MAX);
}


texts:
I'm an experienced programmer that also has a little experience with functional programming, although mostly theoretical (as in hobby-level reading and very minor projects).

I recently decided to work through the new book "Beginning Haskell" to get up to speed with Haskell and try to crank out something worthy of a github repo. Early in the book you are asked to implement a Client ADT including some supportive data types for Person and Gender. I did it like this and I'm not liking it at all:

data Gender = Male | Female | Unknown | None
              deriving (Show, Eq)

data Person = Person { fName :: String, lName :: String, gender :: Gender }
              deriving (Show, Eq)

data Client = GovOrg { code :: String,     name :: String }
            | Individual { code :: String, person :: Person }
            | Company { code :: String,    name :: String, contact :: Person }
              deriving (Show, Eq)

After this you are asked to write a function that takes [Client] and returns the count for the different genders, e.g. "out of the 20 clients listed, we have 5 male, 5 female, 10 unknown". Let's call it countGenders. Below is the code I've ended up with, and I feel that it's a complete mess and lacks any feeling of clarity or elegance. I think my OOP-brain is forcing me into bad designs. I'll walk you through the lines below. Once again I am not at all happy with this.

First we have a result data type. Could be just an (Int, Int, Int), but I feel like the location in the tuple isnt a natural fit with what the data should represent (as opposed to Point Int Int):

data GenderCount = GenderCount { male :: Int, female :: Int, unknown :: Int }

Then we have the top level function that is supposed to be invoked. Maps genderCount across a [Client], which results in [(Int, Int, Int)], then unzips those and sums each list.

countGenders :: [Client] -> GenderCount
countGenders cs = GenderCount (sum m) (sum f) (sum u)
    where (m, f, u) = unzip3 $ map genderCount cs

Then we have genderCount, which maps a Client to a result tuple (Male, Female, Unknown):

genderCount :: Client -> (Int, Int, Int)
genderCount c = case cGender c of
                     Male    ->  (1, 0, 0)
                     Female  ->  (0, 1, 0)
                     Unknown ->  (0, 0, 1)
                     None    ->  (0, 0, 0)

Last we have cGender, which gets the gender from a client (using RecordWildCards extension):

cGender :: Client -> Gender
cGender GovOrg {}         = None
cGender Individual { .. } = gender person
cGender Company { .. }    = gender contact

As you can see this is all a mess. But I'm having trouble thinking of how to refine it. I feel like my data model is bloated, which bleeds over into too many functions to do something that should be really simple. I would appreciate any feedback on the data model, the functions or anything else.

Here is the entire code if you want to look it over in full context: http://pastebin.com/Vymcd6Bj


texts: Improving Custom Comparator.compare() method

texts:
I have the class SeguimientoSeccion with this relevant attributes

public class SeguimientoSeccion implements Serializable {
    private Integer id;

    private Transportista transportista;
    private String fijacion;
    private Integer month;
    private Integer year;
}

I created a custom comparator to sort by

year - Integer
month - Integer
fijacion - String
Transportista.nombre - String

SeguimientoSeccionComparator.java (class I want to improve)

public class SeguimientoSeccionComparator implements Comparator<SeguimientoSeccion>
{
    public int compare(SeguimientoSeccion o1, SeguimientoSeccion o2)
    {
        int result = o1.getYear().compareTo(o2.getYear());

        if (result == 0) {
            result = o1.getMonth().compareTo(o2.getMonth());
        }

        if (result != 0) return result;

        if (o1.getFijacion() == null && o2.getFijacion() == null)
            result = 0;
        else if (null == o1.getFijacion())
            result = 1;
        else if (null == o2.getFijacion())
            result = -1;
        else
            result = o1.getFijacion().compareTo(o2.getFijacion());

        if (result != 0) return result;

        if (o1.getFijacion() == null && o2.getFijacion() == null)
            result = 0;
        else if (null == o1.getTransportista())
            result = 1;
        else if (null == o2.getTransportista())
            result = -1;
        else
            result = o1.getTransportista().getNombre().compareTo(o2.getTransportista().getNombre());

        return result;
    }
}

EXTRA INFO:

equals and hashCode autogenerated by Eclipse IDE:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((fijacion == null) ? 0 : fijacion.hashCode());
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    result = prime * result + ((month == null) ? 0 : month.hashCode());
    result = prime * result
            + ((transportista == null) ? 0 : transportista.hashCode());
    result = prime * result + ((year == null) ? 0 : year.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    SeguimientoSeccion other = (SeguimientoSeccion) obj;
    if (fijacion == null) {
        if (other.fijacion != null)
            return false;
    } else if (!fijacion.equals(other.fijacion))
        return false;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    if (month == null) {
        if (other.month != null)
            return false;
    } else if (!month.equals(other.month))
        return false;
    if (transportista == null) {
        if (other.transportista != null)
            return false;
    } else if (!transportista.equals(other.transportista))
        return false;
    if (year == null) {
        if (other.year != null)
            return false;
    } else if (!year.equals(other.year))
        return false;
    return true;
}


texts:
This function works as such:

Use_Inclusions and Use_Exclusions are either true or false
File_Type_Exclusions is a slice of files types
General_Inclusions is a slice of directories/files
General_Exclusions is a slice of directories/files

The code:
func FileCheck(file string)bool{
    if InvalidExtension(config.Exclusions.File_Type_Exclusions,file) && config.Settings.Use_Inclusions{
      return false
    }
    if !config.Settings.Use_Exclusions && !config.Settings.Use_Inclusions{
      return true
    }else if !config.Settings.Use_Exclusions && config.Settings.Use_Inclusions{
      // Only backup if included
      ok := IsSlice(config.Inclusions.General_Inclusions,file)
      if !ok{
        return false
      }
    }else if config.Settings.Use_Exclusions && !config.Settings.Use_Inclusions{
      // Only backup if not excluded
      if IsSlice(config.Exclusions.General_Exclusions,file){
        return false
      }else{
        return true
      }
    }else if config.Settings.Use_Exclusions && config.Settings.Use_Inclusions{
      //Backup if not exluded unless explicitly included
      ok := IsSlice(config.Inclusions.General_Inclusions,file)
      exclude := Is(config.Exclusions.General_Exclusions,file)

      if !exclude && ok{
        return true
      }else if exclude && ok{
        return true
      }else if !ok && !exclude{
        return true
      }else{
        return false
      }
    }else{
      panic(errors.New(fmt.Sprintf("Error: The combinantion of %t,%t is not possible",config.Settings.Use_Exclusions,config.Settings.Use_Inclusions)))
    }
  return false
}

func Is(slice []string, value string)bool{
  for _,elem := range slice{
    if elem == value{
      return true
    }else if strings.Contains(value,elem){
      return true
    }
  }
  return false
}

//Checks if values in sliceA are in the file path at all
func IsSlice(sliceA []string , file string)bool{
  files := strings.Split(file,"\\")
  file = strings.Join(files[3:],"\\")
  for _,elemA := range sliceA{
    if strings.Contains(file,elemA){
      return true//,strings.Replace(elemA,elemB,"",1)
    }else if strings.Contains(elemA,file){
      return true
    }
  }
  return false//,""
}


texts: Benchmarking of SQL data crunching using a common datum

texts:
@nhgrif and I were curious about a couple different ways to aggregate a number of records based on a duplicate/common datum. Two different ideas will be shown. Any advice on all code but especially making it perform better is appreciated.

Note: @nhgrif did not write most of this, so if it's wrong it's my fault...

Make a bunch of data

Code:

set search_path = test;
-- create tables to seed a large number of records
drop table if exists contract_number_seed;
create table contract_number_seed(
    contract_number int
    );
insert into contract_number_seed
    (contract_number)
    select * from generate_series(1, 100000)
    ;
drop table if exists serial_number_seed;
create table serial_number_seed(
    serial_number int
    );
insert into serial_number_seed
    (serial_number)
    select * from generate_series(1, 10)
    ;
drop table if exists status_seed;
create table status_seed(
    status text
    );
insert into status_seed (status)
values (NULL), ('one'), ('two'), ('three');
-- generate a whole bunch of records from seed tables
drop table if exists seeded;
select
    contract_number_seed.contract_number,
    serial_number_seed.serial_number,
    status_seed.status
into seeded
from contract_number_seed
cross join serial_number_seed
cross join status_seed;
-- Query returned successfully: 4000000 rows affected, 11368 ms execution time.

Just for the record:

set search_path = test;
select * from seeded;
-- Total query runtime: 8056 ms.
-- 4000000 rows retrieved.

Using LEFT OUTER JOIN

PS: Capitalization is different in this; @nhgrif wrote it and I was lazy.
PPS: Table aliases are not that great but I'm just benchmarking, please forgive...

SET SEARCH_PATH = test;
SELECT
    seeded.Serial_Number,
    COUNT(one.Contract_Number) as One,
    COUNT(two.Contract_Number) as Two,
    COUNT(three.Contract_Number) as Three
FROM seeded
  LEFT JOIN seeded as one
    ON one.Contract_Number = seeded.Contract_Number
    AND seeded.Status = 'one'
  LEFT JOIN seeded as two
    ON two.Contract_Number = seeded.Contract_Number
    AND seeded.Status = 'two'
  LEFT JOIN seeded as three
    ON three.Contract_Number = seeded.Contract_Number
    AND seeded.Status = 'three'
GROUP BY seeded.Serial_Number, seeded.Status;

I found the performance of this to be abysmal:

Total query runtime: 3096218 ms. -- ~30 minutes
10 rows retrieved.

A faster way... Using case when ... then

set search_path = test;
select
        seeded.Serial_Number,
    case
        when seeded.Status = 'one' then 1
        else 0
        end,
    case
        when seeded.Status = 'two' then 2
        else 0
        end,
    case
        when seeded.Status = 'three' then 3
        else 0
        end
from seeded
group by seeded.Serial_number, seeded.Status;

Performance:

Total query runtime: 5609 ms.
40 rows retrieved.

Are there better ways to do this? I found the first way to work OK on small queries but really lack on big ones. I found the 2nd one to be fast, however any new column in seeded.Serial_Number requires a refactoring of the queries...


texts: Is this code a good solution for this task?

texts:
interface IJuiceable
{
    void MakeJuice();
}
interface ISliceable
{
    void MakeSlices();
}

class Fruit:IJuiceable,ISliceable
{
    public string Name { get; set; }
    public void MakeJuice()=>Console.WriteLine($"Juice from {Name}");

    public void MakeSlices()=>Console.WriteLine($"Slices of {Name}");
}

class Fresh
{
    List<IJuiceable> juices = new List<IJuiceable>();
    List<ISliceable> slices = new List<ISliceable>();

    public void AddToJuices(IJuiceable fruit)=>juices.Add(fruit);
    public void AddToSlices(ISliceable fruit)=> slices.Add(fruit);

    public void MakeFreshes()
    {
        juices.ForEach(x => x.MakeJuice());
        slices.ForEach(x => x.MakeSlices());
    }
}


texts: JavaScript Code for image rotation on a web page

texts: How does this look for basic image rotation?  What is there to be improved here?


texts: Generate dynamic surveys using Python Flask

texts:
I'm building a web app using Flask to offer surveys to users. The number of questions on the survey and the type of questions isn't known until runtime. I finally have the code working properly, and would like some feedback on how pythonic the code is and what I can do to improve it.

To account for a single form page that can display multiple types of questions, I have the following in my forms.py file (I'm going with the PEP 8 notation that lines 99 characters long is acceptable for teams that prefer it):

class FieldsRequiredForm(FlaskForm):
    class Meta:
        def render_field(self, field, render_kw):
            render_kw.setdefault('required', True)
            return super().render_field(field, render_kw)

Here is the route code:

@bp.route('/survey/<string:slug>', methods=['GET', 'POST'])
def survey(slug):
    class SurveyForm(FieldsRequiredForm):
        pass

    survey = Survey.query.filter_by(slug=slug).first_or_404()
    questions = survey.questions
    question_ids = [question.id for question in questions]
    if 'answers' not in session:
        session['answers'] = json.dumps({id: None for id in question_ids})
        form = F()
    answers = json.loads(session['answers'])
    if request.method == 'POST':
        record_submitted_answer()
        answers = json.loads(session['answers'])
    if None in answers.values():
        question = get_next_question()
        SurveyForm.question_id = HiddenField(default=question.id)
        if question.category == 'word':
            SurveyForm.answer = StringField(question.question)
        elif question.category == 'likert':
            SurveyForm.answer = RadioField(question.question, choices=tuple(likert().items()))
        SurveyForm.submit = SubmitField('Submit')
    else:
        SurveyForm.answer = StringField()
    form = F()
    if form.validate_on_submit():
        if None not in answers.values():
            write_answers_to_database(survey=survey)
            if survey.ty:
                lines = iter(survey.ty.splitlines())
            else:
                with open('app/static/ty.txt', 'r') as f:
                    lines = f.readlines()
            ty = [line.strip() for line in lines]
            return render_template('ty.html', ty=ty)
        return redirect(url_for('survey.survey', slug=slug))
    return render_template('survey.html', form=form)

Please, tell me what I did wrong or could have done better.


texts: Implementation of Trie data structure accommodating varying number of children

texts:
I've used the Trie data structure to solve the following problem:

  Given an array of words, print all anagrams together. For example, if the given array is {"cat", "dog", "tac", "god", "act"}, then output may be "cat tac act dog god".

The following is my C++ implementation which can accommodate varying number of children.

#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <algorithm>
using namespace std;

struct Trie_node_base
{
    vector<Trie_node_base*> child;
    int num_of_child;

    Trie_node_base(int n)
    {
        num_of_child = n;
        for(int i = 0; i < n; ++i)
            child.push_back(NULL);
    }
};

struct Trie_node : public Trie_node_base
{
    bool is_word;
    vector<vector<string>::const_iterator> head;

    Trie_node(int num):Trie_node_base(num), is_word(false){}
};

class Trie
{
public:
    Trie(int n=26)
    {
        root = new Trie_node(n);
    }
    ~Trie()
    {
        destroy(root);
    }

    void insert_trie_node(const string& w, vector<string>::const_iterator ind);
    Trie_node* get_root_node()
    {
        return root;
    }

private:
    Trie_node* root;
    void destroy(Trie_node* root);
};

void Trie::insert_trie_node(const string& w, vector<string>::const_iterator ind)
{
    Trie_node* r = root;

    string::const_iterator runner = w.begin();
    for(; runner!=w.end(); ++runner)
    {
        char cur_char = *runner;
        int i = cur_char - 'a';

        if(r->child[i] == NULL)
        {
            r->child[i] = new Trie_node(r->num_of_child);
        }
        r = (Trie_node*)r->child[i];
    }

    if(!r->is_word)
        r->is_word = true;
    r->head.push_back(ind);
}

void Trie::destroy(Trie_node* root)
{
    vector<Trie_node_base*>::iterator it = (root->child).begin();

    for(; it != (root->child).end(); ++it)
    {
        if(*it != NULL)
            destroy((Trie_node*)(*it));
    }

    delete root;
}

void traversal_trie(const vector<string>& word_arr, Trie_node* r)
{
    size_t i;

    if(r->is_word)
    {
        vector<vector<string>::const_iterator>::iterator it = (r->head).begin();
        for(; it != (r->head).end(); ++it)
        {
            cout << *(*it) << endl;
        }
    }

    for(i = 0; i < r->num_of_child; ++i)
    {
        if(r->child[i] != NULL)
            traversal_trie(word_arr, (Trie_node*)r->child[i]);
    }
}

void cluster_anagrams(const vector<string>& word_arr, size_t size)
{
    Trie* trie = new Trie(26);

    vector<string>::const_iterator it = word_arr.begin();
    for(; it != word_arr.end(); ++it)
    {
        string cur_str = *it;
        sort(cur_str.begin(), cur_str.end());
        trie->insert_trie_node(cur_str, it);
    }
    traversal_trie(word_arr, trie->get_root_node());
}

int main()
{
    const char* word_arr[] = {"cat", "dog", "tac", "god", "act", "gdo"};
    size_t size = sizeof(word_arr) / sizeof(word_arr[0]);
    vector<string> word_arr1(word_arr, word_arr+size);

    cluster_anagrams(word_arr1, size);

    system("pause");
    return 0;
}


texts:
I wrote the below enum from which I need to extract the name and its value:

public enum UserEnum {
    TreeUser("/tree"), ParentUser("/parent");

    private String value;

    UserEnum(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}

This is the way I am using the above UserEnum in my code base:

// extract TreeUser
String nameOfTree = UserEnum.TreeUser.name();
String valueOfTree = UserEnum.TreeUser.value();

// extract ParentUser
String nameOfParent = UserEnum.ParentUser.name();
String valueOfParent = UserEnum.ParentUser.value();

// and I am using UserEnum this way as well to make name1=value1,name2=value2
String mapping = UserEnum.TreeUser.name() + "="
                + UserEnum.TreeUser.value() + "," + UserEnum.ParentUser.name() + "="
                + UserEnum.ParentUser.value();

I am opting for a review to see whether I can simplify anything in my enum.


texts: Joining tables by skipping the intermediate parent table

texts:
We've tables adm_app, quals_data to which personal_data is a parent table. We are retrieving data from another table sub_marks which has a foreign key of quals_data and the query is like this

select
      sub_marks.obtain_marks,
      sub_marks.convertion_marks,
      sub_marks.max_marks
from sub_marks
inner join quals_data ON quals_data.id = sub_marks.quals_data_id
inner join adm_app on quals_data.personal_data_id = adm_app.personal_data_id
where adm_app.app_no = 2000;

You can see that we've skipped the join with personal_data because we are not using its data anywhere. Is this a good way of writing a query? Previously we wrote query like this

select
      sub_marks.obtain_marks,
      sub_marks.convertion_marks,
      sub_marks.max_marks
from sub_marks
inner join quals_data ON quals_data.id = sub_marks.quals_data_id
inner join personal_data ON personal_data.id = quals_data.personal_data_id
inner join adm_app on adm_app.personal_data_id = personal_data.id
where adm_app.app_no = 2000;


texts: Binary Search Tree implementation with topological validation

texts:
import sys

class Node:
    def __init__(self, value):
        self.left = None
        self.right = None
        self.value = value

    def __str__(self):
        return f"{self.value} "

class Sum:
    def __init__(self, val):
        self.s = val

    def getS(self):
        return self.s

    def update(self, val):
        self.s += val

class BST:
    def __init__(self):
        self.root = None

    def insert(self, key):
        curr = self.root
        parent = None
        if self.root:
            while curr and curr.value != key:
                parent = curr
                if curr.value < key:
                    curr = curr.right
                else:
                    curr = curr.left
        else:
            self.root = Node(key)
            return

        if parent:
            if parent.value < key:
                parent.right = Node(key)
            else:
                parent.left = Node(key)

    def delete(self, key):
        pass

    def _doFind(self, root, key):
        if root:
            if root.value == key:
                return root
            if root.value < key:
                self._doFind(root.right, key)
            else:
                self._doFind(root.left, key)

    def find(self, key):
        self._doFind(self.root, key)

    def _inorder(self, root):
        if root:
            self._inorder(root.left)
            print(root, " ")
            self._inorder(root.right)

    def inorder(self):
        self._inorder(self.root)

    def _preorder(self, root):
        if root:
            print(root, " ")
            self._preorder(root.left)
            self._preorder(root.right)

    def preorder(self):
        self._preorder(self.root)

    def _postorder(self, root):
        if root:
            self._postorder(root.left)
            self._postorder(root.right)
            print(root, " ")

    def postorder(self):
        self._postorder(self.root)

    def sumRToL(self, root, s):
        if root:
            self.sumRToL(root.right, s)
            s.update(root.value)
            root.value = s.getS()
            self.sumRToL(root.left, s)

    def sumelementsfromRtoLinplace(self):
        s = Sum(0)
        self.sumRToL(self.root, s)

    def validate(self, root, low, high):
        # Look for iterative solutions as well, probably using some stack
        return (not root) or (low <= root.value <= high and (
                self.validate(root.left, low, root.value) and self.validate(root.right, root.value, high)))

    def validatebst(self):
        max = sys.maxsize
        min = -sys.maxsize - 1
        return self.validate(self.root, min, max)

    def isSameTree(self, p, q):
        # Task : Can a level order solve this. Any non-recursive solutions as stack depth is not reliable?
        """
         Checks the value as well as topological order
        :type p: Node
        :type q: Node
        :rtype: bool
        """
        if not p and not q:
            return True
        elif p and q and p.value == q.value:
            return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        return False

def test_main():
    bst = BST()
    bst.insert(1)
    bst.insert(2)
    bst.insert(3)
    bst.insert(4)
    bst.insert(5)
    # bst.root.left = Node(34) # Mess up the tree
    # bst.insert(2)
    # bst.insert(3)
    # bst.insert(4)
    # bst.insert(5)
    # bst.sumelementsfromRtoLinplace()
    # bst.inorder()
    bst1 = BST()
    bst1.insert(1)
    bst1.insert(2)
    bst1.insert(3)
    bst1.insert(4)
    bst1.insert(5)

    print('Same tree : ', bst.isSameTree(bst.root, bst1.root))
    print("Valid Tree : ", bst.validatebst())

if __name__ == '__main__':
    test_main()

P.S : I had to create the Sum class as there's no way to share the same primitive int across stack calls as there is no pass by reference in Python. I wanted to avoid using global variables throughout.


texts: Randomly sampling a population and keeping means: tidy up, generalize, document?

texts:
This is part from an answer to a Stack Overflow question. The OP needed a way to perform calculations on samples from a population, but was hitting memory errors due to keeping samples in memory.

The function is based on part of random.sample, but only the code branch using a set is present.

If we can tidy and comment this well enough, it might be worth publishing as a recipe at the Python Cookbook.

import random

def sampling_mean(population, k, times):
    # Part of this is lifted straight from random.py
    _int = int
    _random = random.random

    n = len(population)
    kf = float(k)
    result = []

    if not 0 <= k <= n:
        raise ValueError, "sample larger than population"

    for t in xrange(times):
        selected = set()
        sum_ = 0
        selected_add = selected.add

        for i in xrange(k):
            j = _int(_random() * n)
            while j in selected:
                j = _int(_random() * n)
            selected_add(j)
            sum_ += population[j]

        # Partial result we're interested in
        mean = sum_/kf
        result.append(mean)
    return result

sampling_mean(x, 1000000, 100)

Maybe it'd be interesting to generalize it so you can pass a function that calculates the value you're interested in from the sample?


texts: Is it okay to use multiple repositories from inside a single service implementation in Spring?

texts:
I currently have two entities, Adress and Company. They both have DTOs to perform CRUD operations.

AddressCreateDto:

@Getter
@Setter
public class AddressCreateDto {

    @NotNull
    private String address1;

    private String address2;

    @NotNull
    private String city;

    @NotNull
    private String state;

    @NotNull
    private int zipCode;

    @JsonIgnore
    private final Long createdBy = 1L;

    @JsonIgnore
    private final Date createdDate = new Date();

    @JsonIgnore
    private final Long lastModifiedBy = 1L;

    @JsonIgnore
    private final Date lastModifiedDate = new Date();

}

CompanyCreateDto:

@Getter
@Setter
public class CompanyCreateDto {

    @NotNull
    private String name;

    @NotNull
    private AddressCreateDto address;

    @JsonIgnore
    private final Long createdBy = 1L;

    @JsonIgnore
    private final Date createdDate = new Date();

    @JsonIgnore
    private final Long lastModifiedBy = 1L;

    @JsonIgnore
    private final Date lastModifiedDate = new Date();

}

In my CompanyServiceImpl file, I am using both the CompanyRepository and the AddressRepository but I don't know if this is bad practice. The code works, but not sure if there is a better way of rewriting this so that it follows a specific set of conventions.

CompanyServiceImpl:

@Service
public class CompanyServiceImpl implements CompanyService {

    private final CompanyRepository companyRepo;

    private final AddressRepository addressRepo;

    @Autowired
    public CompanyServiceImpl(CompanyRepository companyRepo, AddressRepository addressRepo) {
        this.companyRepo = companyRepo;
        this.addressRepo = addressRepo;
    }

    @Override
    public CompanyReadDto create(CompanyCreateDto dto) {
        Address address = ObjectMapperUtils.map(dto.getAddress(), Address.class);
        address = addressRepo.save(address);

        Company company = ObjectMapperUtils.map(dto, Company.class);
        company.setAddress(address);

        return ObjectMapperUtils.map(companyRepo.save(company), CompanyReadDto.class);
    }

    ...

}

EDIT:

CompanyReadDto:

@Getter
@Setter
public class CompanyReadDto {

    @Id
    @NotNull
    private Long id;

    @NotNull
    private String name;

    @NotNull
    private AddressReadDto address;

}

AddressReadDto:

@Getter
@Setter
public class AddressReadDto {

    @Id
    @NotNull
    private Long id;

    @NotNull
    private String address1;

    private String address2;

    @NotNull
    private String city;

    @NotNull
    private String state;

    @NotNull
    private int zipCode;

}


texts:
I currently have a languages.js set up as such:

var MaterialProperties = 0;
var YieldStrength = 1;
var OtherPhrases = 2;

//continue to list other phrases - there are 40+

var English = [
    "Material Properties",
    "Yield Strength",
    "Other Phrases"
];

var Chinese = [
    // Chinese string that means "Material Properties",
    // Chinese string that means "Yield Strength",
    // Other phrases in Chinese
];

var SelectedLanguage = English; //default

Then I have the user select via dropdown box the language they would like, calling setLanguage(selected_language), which sets SelectedLanguage to either "English" or "Chinese", depending on the value of the dropbox selection.

Everywhere in my HTML where it should read "Material Strength" (or corresponding string in Chinese), I reference this as SelectedLanguage[MaterialProperties], which is the same as saying English[0] or Chinese[0], which returns the correct string.

Is there a better, more efficient, cleaner way to do this?


texts: How to add exceptions in a class that reads a config file?

texts:
I am using Boost for reading a config file that is in the .json format. I am using a class to do this and I am calling exit(message) in case of bad values or default value gotten by Boost get() function.

The class is here:

class ConfigFile
{
private:
  PTree m_ptConfig;

  void failedGetValue(const std::string& message)
  {
    std::cout << message << std::endl;
    //TODO throw exception
    exit(EXIT_FAILURE);
  }

public:
  ConfigFile(const std::string& name);
  ~ConfigFile();

  double getVal1()
  {
    std::string path = "path.to.val1";
    double val1 = m_ptConfig.get<double>(path, -1);

    if (val1 < 0)
    {
      std::string msg = "getVal1() failed or val1 < 0";
      failedGetValue(msg);
    }

    return val1;
  }
  double getVal2() {/*the same as before*/};
  // ... more values the same way
};

If I want to throw exceptions like MyConfigFileException instead of calling exit:

class MyConfigFileException : public MyIOException // MyIOException is derived from std::exception
{
private:
  std::string m_msg;

public:
  MyConfigFileException(const std::string msg) : msg(msg) {}
  virtual const char* what() const throw()
  {
    return m_msg.c_str();
  }
};

How would you suggest I do this? Shall I just throw it? Shall I catch where the getValX() function is called or I shall catch it in main()? I am new to exceptions.


texts: Fastapi with Aiohttp not providing expected results

texts:
I am new to asynchronous programming in python. Below are two scripts(which perform the same operation) one in Fastapi + aiohttp while other is basic Flask + requests library:
## Flask

def fetch1(url):
    x = requests.get(url)                 # First hit to the url
    data = x.json()                       # Grab response
    return fetch2(data['uuid'])           # Pass uuid to the second function for post request

def fetch2(id):
    url2 = "http://httpbin.org/post"
    params = {'id': id}
    x = requests.post(url2, json=params)
    return x.json()

@app.route('/')
def main():
    url = 'http://httpbin.org/uuid'
    data = fetch1(url)
    return {"message":"done"}

and the fastapi couterpart:
async def fetch1(session, url):
    async with session.get(url) as resp:
        data = await resp.json()
        return await fetch2(session, data['uuid'])

async def fetch2(session, id):
    url2 = "http://httpbin.org/post"
    params = {'id': id}
    async with session.post(url2, json=params) as resp:
        return await resp.json()

@app.get("/")
async def main():
    url = 'http://httpbin.org/uuid'
    async with aiohttp.ClientSession() as session:
        data = await fetch1(session, url)
        return {"message":"done"}

As a sample benchmark testing (Using Apache Bench), I had fired 500 requests at 100 concurrency, while Flask took 7 seconds(approx) to complete the operation fastapi  takes 4.5 to do the same(which is not that great).Is my async code blocking in nature or Am I missing something.Any help will be appreciated.


texts: jquery script for inserting and deleting text

texts:
Unfortunately I get 3 warnings at jslint. Could someone please help?

I already tried a lot, but didn't get it yet.

Here's a jsfiddle: http://jsfiddle.net/KYjF9/21/

JSlint options:

/*jslint browser: true indent: 2 */ /*global $ jQuery alert*/

JavaScript:

var Typing = function (el, toType, period) {
  "use strict";
  this.toType = toType;
  this.el = el;
  this.loopNum = 0;
  this.period = parseInt(period, 10) || 2000;
  this.txt = '';
  this.tick();
  this.isDeleting = false;
};

Typing.prototype.tick = function () {
  "use strict";
  var fullTxt = this.toType[this.loopNum % this.toType.length];

  if (this.isDeleting) {
    this.txt = fullTxt.substring(0, this.txt.length - 1);
  } else {
    this.txt = fullTxt.substring(0, this.txt.length + 1);
  }

  $(this.el).html('' + this.txt + '');

  var delta = 300 - Math.random() * 100;

  if (this.isDeleting) { delta /= 2; }

  if (!this.isDeleting && this.txt === fullTxt) {
    delta = this.period;
    this.isDeleting = true;
  } else if (this.isDeleting && this.txt === '') {
    this.isDeleting = false;
    this.loopNum = this.loopNum + 1;
    delta = 500;
  }

  setTimeout(this.tick.bind(this), delta);
};

var data = {
  "text": {
    "list": ["hello", "hallo", "hola", "what", "ever"],
    "period": "3000"
  }
};

$(document).ready(function () {
  "use strict";
  var toType = data.text.list;
  var period = data.text.period;
  $(".js").each(function () {
    if (toType) {
      new Typing(this, toType, period);
    }
  });
});


texts:
I'm still relatively new to C++ and I've written a program that could do with being a bit shorter and faster.

I use this same set of for loops many times to cycle through the whole tree of values. I'll use the JSON format to show you a much shortened version of the tree (in reality the tree has another layer of depth with many more values):

{
  "WorldOne": {
    "Earth": {
      "Japan": "Tokyo",
      "America": "New York"
    },
    "Moon": {
      "Dark Side": "Crater One"
    }
  }
}

I then parse this and fill a large vector with these values. The format of the vectors can be seen in the loop below.

My program then, depending on the parameters I set, cycles through to grab the data contained within.

This is the loop I am using over and over again:

for ( auto cWorld : fWorldVec ) //vector of world pointers
        {
            for ( auto cPlanet : ( cWorld )->fPlanetVector )
            {
                for ( auto cCity : cPlanet.fCityVector )
                {
                     for (auto cValue : cCity.fValueVector)
                     {
                          // Then I do stuff
                          // e.g:
                          ConstructSomething( ( cWorld )->getWorldId(), cPlanet.getPlanetId(), cCity.getCityId(), cValue.getValueId() );
                          // I know the above JSON didn't contain values,
                          // but it does in my code for reasons that aren't worth mentioning
                          // This loop is used so many times throughout my code
                          // It would be wonderful to simply be able to grab the data much faster
                     }
                }
            }
        }

I apologise if this question is too vague, but I really need a speed boost or even to make this loop shorter.  I'd like any improvements on the format of my tree or how to condense these loops.

I was thinking along the lines of making some kind of address table with pointers - but I can't quite think of a way to do it.


texts: Generating matrix/image kernel from List

texts:
I have another question from same program where is full code, but this question focus only single process/function of that program.

My problem is performance when creating dynamic Image kernel from list of pixels.

List contains multiple single 4 byte Integer which is grayscale of pixel.

I have tried 3 different approach, still not happy with the time what it takes.

I think my basic idea about generating matrices is wrong.

Approach 1

def getKernels(self, pixels, width):
    kernels = []
    pixels = [x for sublist in pixels for x in sublist] #2D list to 1D
    for i in range(0,len(pixels)):
        x = (i % width) #Calc pixel x-cordinate
        y = math.floor(i / width) #Calc y-cordinate
        try:
            kernel = [pixels[(x-1)+((y-1)*width)],pixels[(x)+((y-1)*width)],pixels[(x+1)+((y-1)*width)],pixels[(x-1)+(y*width)],pixels[(x)+(y*width)],pixels[(x+1)+(y*width)],pixels[(x-1)+((y+1)*width)],pixels[(x)+((y+1)*width)],pixels[(x+1)+((y+1)*width)]]
        except Exception as e:
            kernel = [0] #Cannot create fullsize kernel so just make it black
        kernels.append(kernel) #Add kernel to kernels list
    return kernels

Function execute time 0.2249772548675537 seconds
With this project I can live with that time, but kernel generation is ugly and "hardcoded" so I cant change size of it.

Approach 2

    def getKernels(self, pixels, width):
        kernels = []
        pixels = [x for sublist in pixels for x in sublist]  #2D list to 1D
        for i in range(0,len(pixels)):
            tx = (i % width) #Calc pixel x-cordinate
            ty = math.floor(i / width) #Calc y-cordinate
            kernel = []
            for y, x in self.kernelGenerator(ty,tx,3): #Pass current pixel index cordinates and size of kernel
                try:
                    index = (x)+((y)*width) #Calc index
                    if index > -1 and index < len(pixels):  #Check that index is in list bounds
                        kernel.append(pixels[index])
                    else: #Out of list bounds make pixel black
                        kernel.append(0)
                except Exception as e:
                    raise e
            kernels.append(kernel)
        return kernels

    def kernelGenerator(self, x, y, size):
        if size % 2 == 0 or size < 3: #Because pixel has to be "center" of my kernel
            print("Kernel size should be odd and greater than 2")
            raise
        kernel = []
        for i in range(math.ceil(-size/2),math.ceil(size/2)):
            for j in range(math.ceil(-size/2),math.ceil(size/2)):
                kernel.append((x+i,y+j))
        return kernel

Function execute time 1.236647605895996 seconds
Ok, now I can change my kernel size but costs time.

Approach 3

    def getKernels(self, pixels):
        kernels = []
        for ty, row in enumerate(pixels): #get pixel Y-cordinate and row
            for tx, px in enumerate(row): #get pixel X-cordinate and px
                kernel = []
                for y, x in self.kernelGenerator(ty,tx,3):
                    try:
                        kernel.append(pixels[y][x])
                    except Exception as e:
                        kernel.append(0)
                kernels.append(kernel)
        return kernels

    def kernelGenerator(self, x, y, size):
        if size % 2 == 0 or size < 3: #Because pixel has to be "center" of my kernel
            print("Kernel size should be odd and greater than 2")
            raise
        kernel = []
        for i in range(math.ceil(-size/2),math.ceil(size/2)):
            for j in range(math.ceil(-size/2),math.ceil(size/2)):
                kernel.append((x+i,y+j))
        return kernel

Function execute time 0.8910479545593262 seconds
Approach 3 is now best. Comments got me thinking this again, still execute time is IMO too much.

Any suggestions to improve it?


texts:
I have to transform a response into the internal Coordinate record, some of the fields are lists and I need to handle empty lists case.

Records:

newtype GeoResponse =
  GeoResponse
    { results :: [ResultResponse]
    }
  deriving (Eq, Show, Generic)

newtype ResultResponse =
  ResultResponse
    { locations :: [LocationResponse]
    }
  deriving (Eq, Show, Generic)

newtype LocationResponse =
  LocationResponse
    { latLng :: CoordinateResponse
    }
  deriving (Eq, Show, Generic)

data CoordinateResponse =
  CoordinateResponse
    { lat :: !Double
    , lng :: !Double
    }
  deriving (Eq, Show, Generic)

Mapper function:

toCoordinate :: GeoResponse -> Coordinate
toCoordinate (GeoResponse (ResultResponse [LocationResponse (CoordinateResponse lat lng)]:_)) =
  Coordinate lat lng
toCoordinate _ = Coordinate 0 0

So I didn't find a better way to get Coordinate without pattern match, but it looks a bit ugly to me.

Do you have any suggestion to improve my code?


texts: Low-level methods with temperature conversion program

texts:
This is my first program to convert temperatures. I have a very basic knowledge of Python and I tried using only what I already knew to make the program. What are some improvements I can make, or how can I re-create this in an easier way?

temp_string = raw_input("What is the Temperature: ")

x = int(temp_string)

print x

temp_type = raw_input("Would you like to convert to Celsius or Fahrenheit?: ")

input_type = str(temp_type)

def convert_fahrenheit(x):
    x = (x - 32) * 0.556
    print x

def convert_celsius(x):
    x = (x * 1.8) + 32
    print x

if input_type == str("c"):
    convert_fahrenheit(x)
elif input_type == str("celsius"):
    convert_fahrenheit(x)
elif input_type == str("Celsius"):
    convert_fahrenheit(x)
elif input_type == str("C"):
    convert_celsius(x)
elif input_type == str("f"):
    convert_celsius(x)
elif input_type == str("fahrenheit"):
    convert_celsius(x)
elif input_type == str("Fahrenheit"):
    convert_celsius(x)
elif input_type == str("F"):
    convert_celsius(x)
else:
    print "You have not entered a valid conversion"


texts:
I want to ask question about a better way for implementing single endpoint REST.
I want to build a rest API but I want it to only have single endpoint like: graphql, where you only have like: host/graphql.
I already doing this example in laravel where you need to put a key and method to go to a certain API.
The body look like this (example of calling product API with single endpoint).
Calling get all product:
    {
     "key":"product/all",
     "method":"GET"
    }

And this is the get one (product/{id}):
    {
    "key":"product",
    "method":"GET",
    "payload":"{\"id\":\"1\"}"
    }

This is also work fine with post, put and delete.
Here is the single endpoint code (I use php laravel as example because it fast to make API):
    public function bridge(Request $request)
    {

        $host = "http://127.0.0.1:8000/api/";
        if ($request->has("payload")) {
            $bounds = html_entity_decode($request->payload);
            $payload = json_decode($bounds, true);
        }
        if (strtoupper($request->method) == "POST") {
            try {
                $url = $host . $request->key;
                $request = Request::create($url, 'POST', []);
                $response = Route::dispatch($request);
                return $response;
            } catch (\Throwable $th) {
                $data["data"] = [];
                $data["success"] = false;
                $data["code"] = 500;
                $data["message"] = $th->getMessage();
                return $data;
            }
        } else if (strtoupper($request->method) == "PUT") {
            try {
                $url = $host . $request->key . '/' . $payload['id'];
                $request = Request::create($url, 'PUT', []);
                $response = Route::dispatch($request);
                return $response;
            } catch (\Throwable $th) {
                $data["data"] = [];
                $data["success"] = false;
                $data["code"] = 500;
                $data["message"] = $th->getMessage();
                return $data;
            }
        } else if (strtoupper($request->method) == "DELETE") {
            try {
                $url = $host . $request->key . '/' . $payload['id'];
                $request = Request::create($url, 'DELETE', []);
                $response = Route::dispatch($request);
                return $response;
            } catch (\Throwable $th) {
                $data["data"] = [];
                $data["success"] = false;
                $data["code"] = 500;
                $data["message"] = $th->getMessage();
                return $data;
            }
        } else {
            $url = $host . $request->key;
            try {
                if ($request->has("payload")) {
                    $url = $host . $request->key . "/" . $payload['id'];
                }
                $request = Request::create($url, 'GET');
                $response = Route::dispatch($request);
                return $response;
            } catch (\Throwable $th) {
                $data["data"] = [];
                $data["success"] = false;
                $data["code"] = 500;
                $data["message"] = $th->getMessage();
                return $data;
            }
        }
    }

As you can see there. It is calling the API twice "bridge" and the "key" API.
The cons here:

call request twice;
you can only put one /{id} variable (or more if you declare it).

Pros:

it only one endpoint so it will be easy to make an api helper in the frontend (maybe XD).

Can you show me a better way of doing this?
Tell me your tips and thought or maybe show some code (any language is fine).


texts: React Image component that loads and blurs an image onto a canvas

texts:
My react.js Image component will load an image from a URL or base64 string, do some processing on it and put it on a canvas. The "preload" prop is a 10x10 pixel image that is blurred just a little bit to make it look smoother.

The blur algorithm itself is very fast (I also tried removing it, but got the same results in performance), but the component itself seems to be extremely slow, especially in lists. A page that needs to load a list (12 items for example) of images usually takes about 200-600ms before it renders in the DOM. This is unacceptable.

export default class Image extends React.Component {
  constructor(props, context) {
    super(props, context)

    // Initial state
    this.state = {
      preloadReady: false,
      sourceReady: false,
    }

    this.loadImage = this.loadImage.bind(this)
  }

  setImage(props) {
    this.ctx1.clearRect(0, 0, this.refs.preloadElement.width, this.refs.preloadElement.height);
    this.ctx2.clearRect(0, 0, this.refs.completeElement.width, this.refs.completeElement.height);
    this.img1.src = props.preload;
    this.img2.src = props.src;
  }

  onImageLoaded(type) {
    if (type == 'pre') {
      this.load(this.img1, this.ctx1, this.refs.preloadElement, true, (this.props.preloadBlur || 5), false);
      this.setState({preloadReady: true});
    }
    if (type == 'src') {

      // Blur?
      let blur = this.props.sourceBlur == undefined ? false : true;
      let blurScale = this.props.sourceBlur || 0;

      this.load(this.img2, this.ctx2, this.refs.completeElement, blur, blurScale, true);
      this.setState({sourceReady: true});
    }
  }

  load(img, ctx, canvas, blur, blurScale, smooth) {
    var data, filtered;

    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img ,0 ,0 ,img.width,img.height,0,0, canvas.width, canvas.height);

    // Blur the image?
    if (blur) {
      data = ctx.getImageData(0, 0, canvas.width, canvas.height);
      filtered = Blur(canvas, 0, 0, img.width, img.height, blurScale);
      ctx.putImageData(filtered, 0, 0);
    }
  }

  loadImage(props) {
    // Creates images in memory
    this.img1 = new window.Image();
    this.img2 = new window.Image();

    // Canvas context
    this.ctx1 = this.refs.preloadElement.getContext('2d');
    this.ctx2 = this.refs.completeElement.getContext('2d');

    // Event listeners
    this.img1.onload = this.onImageLoaded.bind(this, 'pre');
    this.img2.onload = this.onImageLoaded.bind(this, 'src');

    // Set CORS fix
    this.img1.crossOrigin = "anonymous";
    this.img2.crossOrigin = "anonymous";

    // Load images
    this.setImage(props)
  }

  componentWillUnmount() {
    this.img1.onload = null;
    this.img2.onload = null;
  }

  componentDidMount() {
    this.loadImage(this.props)
  }

  shouldComponentUpdate(props, state) {
    if (this.props.src !== props.src) {
      this.setState({sourceReady: false, preloadReady: false}, () => {
        this.setImage(props)
      });
    }
    return true
  }

  render () {
    let {state, props} = this,
    classes = {
      src: state.sourceReady ? 'ready' : '',
      pre: state.preloadReady ? 'ready' : '',
    };

    return (

          <canvas ref="preloadElement" style={{width: props.width, height: props.height}} className={'preload tr_quick ' + classes.pre}></canvas>
          <canvas ref="completeElement" style={{width: props.width, height: props.height}} className={'src tr_quick ' + classes.src}></canvas>
          {props.showImg ? () : null}

    )
  }
}

Like I said, this is a very slow component. I'd like to make it faster while still keeping the great features like blurring.


texts:
I am new to python and to the StackExchange sites. I made an age calculator but i want to improve it till it's a reliable thing. Can i shorten the code? What can be Done more? Does it need any additions?
Thanks in advence.
from datetime import datetime

print("A simple program to calculate your age")
print()

date = datetime.now()
year = int(date.year)
month = int(date.month)
day = int(date.day)
input_year = int(input("Enter the year you were born: "))
if input_year <= 0 or input_year > 2020:
    print("don't you know your birthday??")
    exit()
input_month = int(input("Enter the month you were born: "))
if input_month <= 0 or input_month > 12:
    print("don't you know your birthday??")
    exit()
input_day = int(input("Enter the day you were born: "))
if input_day <= 0 or input_day > 31:
    print("don't you know your birthday??")
    exit()
age_year = year - input_year
age_month = month - input_month
if age_month < 0:
    age_year = age_year - 1
    age_month = 12 - (input_month - month)
age_day = day - input_day
if age_day < 0:
    age_month = age_month - 1
    age_day = 31 - (input_day - day)
print("you are " + str(age_year) + " years, " + str(age_month) + " months and " + str(age_day) + " days old.")


texts:
I'm working on a web-based on/off controller for multiple switches. I'm looking for a good way to manage the current state of a switch and updating the current state on change.

So far I've got a lib.json file which looks like this:

{
    "Lights":[{
        "name": "light-one",
        "pin":"3",
        "command":"gpioDo",
        "actions": {
            "on":"1",
            "off":"0"
        }
    },{
        "name": "light-two",
        "pin":"5",
        "command":"gpioDo",
        "actions": {
            "on":"1",
            "off":"0"
        }
    },{
        "name": "light-three",
        "pin":"7",
        "command":"gpioDo",
        "actions": {
            "on":"1",
            "off":"0"
        }
    }],
    "Locks":[{
        "name": "lock-one",
        "pin":"8",
        "command":"gpioDo",
        "actions": {
            "on":"1",
            "off":"0"
        }
    },{
        "name": "lock-two",
        "pin":"12",
        "command":"gpioDo",
        "actions": {
            "on":"1",
            "off":"0"
        }
    }]
}

A web-page is dynamically created using some jQuery and appropriate groups of buttons are created according to the lib.json.

On the server I take that lib.json file and create a state object via this little snippet (note that on initial run all states must be off):

var state = [];
var lib = JSON.parse(fs.readFileSync('lib.json', 'utf8'));
...
for (i in lib) {
  for (x in lib[i]){
    state.push({pin:lib[i][x].pin, val:0});
  }
}

which produces:

[ { pin: '5', val: 0 },
  { pin: '7', val: 0 },
  { pin: '8', val: 0 },
  { pin: '12', val: 0 } ]

When a web-page button is pushed, the server receives a string containing misc elements of the lib.json referencing a command with parameters to perform.

It also updates the state object to represent the change with an updateVal() command.

function updateVal(pinId, valId){
  var i;
  for (i = 0; i < state.length; ++i) {
    if (state[i].pin == pinId) {
      state[i].val = valId;
    }
  }
}

I also have a controller designer which allows you to create groups of buttons which in turn modifies the lib.json. It's basically a hacked up JSON tree editor.

How efficient is this code? Could I be doing something better, and if so, what? I can imagine that creating and updating a state key and value in lib.json could be more effective and reliable.


texts:
I'm making a Mario clone in pygame and I have just wrote a function proccesses inputs and acts as a state machine for Mario. Everything is working just as I want it, but I was wondering if you can think of any more efficient way to write this code.

A note that these methods are all a part of a class called mario.

def __init__(self):
    #The inputs currently binded to each of marios actions.
    self.keybinds = {
        'right': K_RIGHT,
        'left' : K_LEFT,
        'jump' : K_z,
        'spd'  : K_LSHIFT
    }

    # The current state mario is in.
    # Valid states: 'stand', 'air', 'death'.
    self.state = 'stand'

    # The current action mario is doing.
    # Valid actions: 'none', 'walk', 'run', 'jump'.
    self.action = 'none'

    # The current direction mario is facing.
    # Valid values: 'r', 'l'.
    self.faceDir = 'r'

    # The direction that the user wants mario to be moving in
    self.des_dir = 'n'

    # The current speed mario is moving at.
    # Valid speeds: 'norm', 'fast'.
    self.spd = 'norm'

    # A boolean based on whether a character instance can jump.
    self.canJump = True

    self.crnt_mdx = 2.7 # The current max x velocity mario can move at.

    self.slow_dx = 2.7 # The max x velocity mario can move at when he is walking.
    self.fast_dx = 4.7 # The max x velocity mario can move at when he is running.

def processInput(self, keys, keyup):
    #keys = a list of all keybord keys currently being pressed.
    #I have imported a module that has a bunch of variables that represent each key.
    #keyup = the current key that was just released, if any.

    if keyup == self.keybinds['jump']:
        self.canJump = True

    if self.state == 'stand' or self.state == 'air':
        if keys[self.keybinds['right']]:
            self.moveHorz('r')
            self.accelerate('r')
            self.set_crnt_acc('r')
            self.faceDir = 'r'
            self.des_dir = 'r'
        elif keys[self.keybinds['left']]:
            self.moveHorz('l')
            self.accelerate('l')
            self.set_crnt_acc('l')
            self.faceDir = 'l'
            self.des_dir = 'l'
        else:
            if self.state == 'stand' and self.horzDir != 'n':
                self.slowDown()
            self.des_dir = 'n'

    if self.state == 'stand':
        if keys[self.keybinds['spd']]:
            self.crnt_mdx = self.fast_dx
        else:
            self.crnt_mdx = self.slow_dx

        if keys[K_z] and self.canJump:
            self.canJump = False
            self.action = 'jump'
    else:
        pass


texts: HTML page listing product characteristics

texts:
I am using below code in site. i am using lot of html "br" tags. Is this the proper way? or may i add css class for those lines instead of
 tags to give space between lines?

3D Sublimation Vacuum Heat Transfer Press Printer Machine ST-3040

It is a all-in-one machine that can transfer many sublimation blanks, mug, latte mug, plate, hat, t-shirt, iphone/ipad case, metal, glass, crystal, etc.

a) Feature / Intelligent:

1. Easy operation. You can only need to set the temperature and time.

2. Well-designed user interface.

Needs no operations other than placing the workpieces in and taking them out.

b) Multi-functional:

1.It can widely print on mug, glass, crystal, acrylic, plastic, wood, metal, stone, fabric, etc.

2.It can print on mugs of different shape and size with corresponding fixtures.

3.large print size; clear print effect; accurate color rendition; better performance than traditional heat transfer printers.

c) Delicate

1.Uneven dot surface enlarges the heating area.

2.Die casting aluminium alloy and far-infrared coating.

3.Even heating.

4.Clear print effect; accurate color rendition.

d) Concise

1.Made of flame-resistant heat insulating materials.

2.Safe, light, and streamline heat insulating strip.

3.Compact practical internal structure. Modern exterior.

e) Efficient

1.Large volume: 300 x 420 x 110 (mm).

2.Can print 12 mugs at one time.

f) Green&Compact

Built-in high performance acticarbon air filter.

Effectively filter the exhaust gas.

Long exhaust pipe.

108 flip design, easy operation, space saving.

Safe Software & hardware dual control of temperature. Each one will start automatically once the other one is failure.
15 minutes no operation off.

Specifications

Model: ST-3042

Voltage: 110 V /220 V 50 Hz /60 Hz

Power: 2800W

CBM: 0.18CBM

Printing Size: 300 x 420 x 110 mm

Vacuum Pump: 12 V/10 W

Max Vacuum: -640 mmHg

Pressure: -0.06 ~ 0.07 Pa

N.W: 24kg

Packing Size: 690 x 620 x 380 mm


texts:
I'm toggling the class of an element with this code but I'm pretty sure it can be written more efficiently.

$('.expandable_header').click(function() {
    toggle_expandable_icon($(this).find('i')[0]);
    $(this).nextUntil('tr.expandable_header').slideToggle(100, function(){
    });
});

function toggle_expandable_icon(elem) {
    var toOpen = 'fa-plus-circle';
    var toClose = 'fa-minus-circle';
    if (elem.classList.contains(toOpen)) {
        elem.classList.replace(toOpen, toClose);
    } else {
        elem.classList.replace(toClose, toOpen);
}};

Not pointless to say js is not my mother tongue.


texts: Is this a proper way to cancel an onMouseOver which uses setTimeout? (Vanilla JS)

texts:
I've got a working solution for an onMouseOver event which rolls over a set of images and replaces them in the element. Due to my lack of knowledge in JS I would like to know if this is a proper solution. It works in Chrome and Firefox.

The solution sets attributes (i.e. isRunning="true", isCanceled="true") , reads them depending on the user action (onMouseOver, onMouseOut) and determines if the action should be continued.

Contraint: The solution must stay in Vanilla JS. No libraries may be used.

Thanks for any suggestion!

var thumbNails = {
  123: [
    "https://image.flaticon.com/icons/svg/188/188234.svg",
    "https://image.flaticon.com/icons/svg/188/188235.svg",
    "https://image.flaticon.com/icons/svg/188/188236.svg",
    "https://image.flaticon.com/icons/svg/188/188237.svg",
    "https://image.flaticon.com/icons/svg/188/188238.svg",
    "https://image.flaticon.com/icons/svg/188/188239.svg",
    "https://image.flaticon.com/icons/svg/188/188240.svg",
    "https://image.flaticon.com/icons/svg/188/188241.svg",
    "https://image.flaticon.com/icons/svg/188/188242.svg"
  ]
};

function rollover(element) {
  var id = element.getAttribute("id");
  if (!isRunning(element)) {
    setRunning(element, "true");
    setImageSrc(element, thumbNails[id][0]);
    start(1, thumbNails[id], element);
  }
}

function start(startIndex, thumbNails, element) {
  if (!isCanceled(element) && startIndex < thumbNails.length) {
    setTimeout(function() {
      if (!isCanceled(element)) {
        setImageSrc(element, thumbNails[startIndex]);
      }
      startIndex++;
      console.log("currentIndex: " + startIndex + " - Running? " + isRunning(element) + " - Cancel? " + isCanceled(element));
      start(startIndex, thumbNails, element);
    }, 700);
  } else {
    setRunning(element, "false");
    setCanceled(element, "false");
  }
}

function cancel(element) {
  console.log("cancel");
  if (isRunning(element)) {
    setCanceled(element, "true");
  }
}

// HELPERS

function isRunning(element) {
  return element.getAttribute("isrunning") === "true";
}

function setRunning(element, state) {
  element.setAttribute("isrunning", state);
}

function isCanceled(element) {
  return element.getAttribute("iscanceled") === "true";
}

function setCanceled(element, state) {
  element.setAttribute("iscanceled", state);
}

function setImageSrc(element, url) {
  element.setAttribute("src", url);
}
<html>
<head>
</head>
<body>
  <img id="123" onmouseover="rollover(this)" onmouseout="cancel(this)" src="https://image.flaticon.com/icons/svg/188/188238.svg" width="100" height="100">
</body>
</html>


texts: Calculate quote volumes (for a financial instrument) within numeric constraints

texts:
The function below is part of a trading system. Its purpose is to assign a volume (order size) to a bid (buy) quote and and ask (sell) quote, depending on the value of the position_size argument.

This trading system strictly cannot exceed a position limit of 100 in either direction, so our order volumes need to never exceed 100 when combined with the absolute value of current position.

However there is one caveat. Occasionally, for uncontrollable external reasons, a bid or ask (buy or sell order) will be executed twice before its price can be re-adjusted.

So any bid_volume or ask_volume returned by this function needs to be at most, half the value of 100 - position_size, in order to account for the occasional double execution.

Thats why at any step of the if-else blocks below, doubling the ask_volume or bid_volume plus current_position will not exceed 100.

What is the fastest way to achieve this with Python, other than the below code?

def adjust_volume(position_size):

    # Long.
    if position_size > 0:

        if position_size < 45:
            bid_volume = 45 - position_size
            ask_volume = 50

        elif position_size >= 45 and position_size < 65:
            bid_volume = 65 - position_size
            ask_volume = 50

        elif position_size >= 65 and position_size < 82:
            bid_volume = 82 - position_size
            ask_volume = 50

        elif position_size >= 82 and position_size < 100:
            bid_volume = 91 - position_size
            ask_volume = 85

    # Short.
    elif position_size < 0:

        abs_position_size = abs(position_size)

        if position_size > -45:
            bid_volume = 10
            ask_volume = 45 - abs_position_size

        elif position_size <= -45 and position_size > -65:
            bid_volume = 50
            ask_volume = 65 - abs_position_size

        elif position_size <= -65 and position_size > -82:
            bid_volume = 50
            ask_volume = 82 - abs_position_size

        elif position_size <= -82 and position_size > -100:
            bid_volume = 75
            ask_volume = 85 - abs_position_size

        elif position_size == 0:

            bid_volume = 30
            ask_volume = 30

    return position_size, bid_volume, ask_volume

position_size, bid_volume, ask_volume = adjust_volume(-76)

print("bid_volume:", bid_volume)
print("ask_volume:", ask_volume)


texts: Write a wrapper to REST API with asyncio

texts:
I want understand how to correctly structure a functional asyncio-based program.

The code below wraps two external APIs to provide the client a simple send_weather() function. Its structure reflects my current understanding of ansynchronous programming and the very little I've grasped of functional programming.

import asyncio
from functools import partial

import aiohttp

SUCCESSFUL_PUSH = {'deleted': True}  # Value specific to fake push service

async def _post(headers, url, data):
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.post(url, json=data, verify_ssl=False) as response:
            return await response.json()

async def _get(headers, url):
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get(url, verify_ssl=False) as response:
            return await response.json()

def make_comms(headers):
    get = partial(_get, headers)
    post = partial(_post, headers)
    return get, post

async def _notify(post, message, user):
    url = f"https://api.keen.io/dev/null?user={user}"  # Fake push service
    return await post(url, message)

async def _find_city(get, city):
    url = f"https://www.metaweather.com/api/location/search?query={city}"
    obj_list = await get(url)
    if obj_list:
        return obj_list[0]
    return None

async def _city_weather(get, city_id):
    url = f"https://www.metaweather.com/api/location/{city_id}"
    return await get(url)

async def _send_weather(get, post, city, user):
    city_data = await _find_city(get, city)
    if city_data is None:
        print("Could not find city")
        return
    forecast_data = await _city_weather(get, city_data["woeid"])
    weather = forecast_data["consolidated_weather"][0]["weather_state_name"]
    message = f"Current weather in {city}: {weather}"
    reply = await _notify(post, {"message": message}, user)
    if reply == SUCCESSFUL_PUSH:
        print(f"Current weather in {city}: {weather}")
    else:
        print(f"Push notification to {user} failed: {reply}")

def init(get, post):
    return partial(_send_weather, get, post)

if __name__ == "__main__":
    HEADERS = {"Content-Type": "application/json"}
    get, post = make_comms(HEADERS)
    send_weather = init(get, post)
    asyncio.run(send_weather("Glasgow", "Bob"))

How to structure an asynchronous functional program?


texts: C++ Coding Exercise - Maximum unit to load into a truck given it size

texts:
You are assigned to put some amount of boxes onto one truck. You are given a 2D vector of box_types where box_type[0] is the number of a type of box and box_type[1] is the units per box for that type. You are also given an integer value for the truck size, this the maximum boxes you can put in the truck. Return the maximum unit that can be put in a given truck.
Example
input : box_types = {{1, 3}, {2, 2}, {3, 1}}
truck_size = 4
output: 8
Explanation:
There are

1 box of type 0
2 box of type 1
3 box of type 2

where 0, 1, 2 is the index of the vector
You can take all the boxes of the first type, second type and one box from the third type
max_unit = (1 * 3) + (2 * 2) + (1 * 1) = 8
Here is my implementation
#include <iostream>
#include <algorithm>
#include <vector>

void sort_boxtypes(std::vector<std::vector<int>> &box_types)
{
    std::sort(
        box_types.begin(), box_types.end(),
        [](const std::vector<int>& a, const std::vector<int> &b)
        {return a[1] > b[1]; }
    );
}
int maximum_units(std::vector<std::vector<int>> box_types, int truck_size)
{
    sort_boxtypes(box_types);
    int max_unit = 0;
    for(const auto& box_type : box_types)
    {
        truck_size -= box_type[0];
        if(truck_size >= 0)
            max_unit += box_type[0] * box_type[1];
        else
        {
            max_unit += (box_type[0] + truck_size) * box_type[1];
            return max_unit;
        }
    }
    return max_unit;
}

int main()
{
    std::vector<std::vector<int>> box_types = {{5, 10}, {2, 5}, {4, 7}, {3, 9}};
    int max = maximum_units(box_types, 10);
    std::cout << max << '\n';

}


texts:
In order to learn Prolog, I have implemented the cat command in Prolog. I want to know if the code is idiomatic and what could be improved.

File args.pl:

:- module(args, [withFilesOrUserInput/2]).

withFilesOrUserInput(StreamFunction, []) :-
    call(StreamFunction, user_input).

withFilesOrUserInput(StreamFunction, [Filename]) :-
    withFile(StreamFunction, Filename).

withFilesOrUserInput(StreamFunction, [Head|Tail]) :-
    withFile(StreamFunction, Head),
    withFilesOrUserInput(StreamFunction, Tail).

withFile(StreamFunction, Filename) :-
    open(Filename, read, StreamIn),
    call(StreamFunction, StreamIn),
    close(StreamIn).

File cat.pl:

:- use_module(args).

main(Argv) :-
    prompt(_, ''),
    withFilesOrUserInput(catStream, Argv).

catStream(Stream) :-
    copy_stream_data(Stream, user_output),
    flush_output(user_output).

Note: I'm using SWI-Prolog.


texts:
Input:

items = [{
  name: 'b',
  updatedAt: '1'
}, {
  name: 'a',
  updatedAt: '2'
}]

Args:

sort: {
  term: 'updatedAt',
  order: '-1'
}

Function:

items.sort((a, b) => {
  return this.sort.order * (
  a[this.sort.term] > b[this.sort.term] ? 1 : -1
)

Questions:

Is this the cleanest/simplest approach?
Will this function fail in some cases?


texts:
I'm trying to find pangrams ie sentences that contain all the letters of the alphabet, for instance "The quick brown fox jumps over the lazy dog".

I'm an absolute beginner in elisp, and it ended up being a really difficult exercice for me. My idea what to put all the letters in a set check if all the letters of the alphabet are in this set.

I don't think it was a very good idea because elisp doesn't seem to really have sets, so I ended up using a hashmap, which seems very clunky.

Another things that really bothers me is the two if in is-pangram. I feel that they make the function really difficult to reason about, although it's doing something very basic.

(defun add-to-hashmap (hashmap item)
  "Insert ITEM into HASHMAP and return HASHMAP."
  (puthash item t hashmap)
  hashmap)

(defun iter-hashmap-keys (hashmap)
  "Return a sequence of the keys in HASHMAP"
  (let ((keys '()))
    (maphash
     (lambda (key _) (setq keys (cons key keys)))
     hashmap)
    keys))

(defun get-letters (s)
  "Return the set of letters in S.
The set is a hashmap where keys are ascii characters and values are `t`."
  (setq letters (make-hash-table :test 'equal))
  (seq-reduce
   (lambda (hashmap letter) (add-to-hashmap hashmap (downcase letter)))
   (split-string s "")
   letters))

(defvar ALPHABET
  (let* ((letters (get-letters "abcdefghijklmnopqrstuvwxyz"))
         (_ (remhash "" letters)))
    letters))

(defun is-pangram (s)
  "Return `t` is S is a pangram, `nil` otherwise."
  (setq letters (get-letters s))
  (if (seq-some
       ;; this function returns returns `nil` if the given letter is
       ;; *present* in the set, and `t` otherwise. That way, seq-some
       ;; returns a non-nil value when there's a letter that is *not* in
       ;; the set.
       (lambda (letter) (if (gethash letter letters) nil t))
       (iter-hashmap-keys ALPHABET))
      nil
      t))

(provide 'pangram)
```