texts: Temperature converter that seems to violate SRP

texts:
I've written this class for two purposes (I think only this fact shows that this code violates SRP): convert weight from one unit to another and to represent them accurate or not accurate. So class methods can be used for calculation and the present method rounds the value for presentation. I don't like this code - can you propose better solution?

class Temperature

  UNITS = %w(C F)
  DEFAULT_UNITS = "C"

  attr_reader :value, :units

  def initialize(value, units = DEFAULT_UNITS)
    @value = value
    @units = units.to_s
  end

  def as(units, accurate)
    return unless UNITS.include?(units.to_s)
    value = units.to_s == @units ? @value : self.class.try("#{@units.downcase}_to_#{units.downcase}", @value)
    accurate ? value : self.class.new(value, units).present
  end

  def default(accurate = false)
    as(DEFAULT_UNITS, accurate)
  end

  def present
    value.round(1)
  end

  def self.c_to_f(val)
    val * 9 / 5 + 32
  end

  def self.f_to_c(val)
    (val - 32) * 5 / 9
  end

end


texts:
This is my Player file. It is mainly for saving purposes. Is it easy to understand and read? Anything I should add or change for improvements?

#Programmer: DeliriousSyntax
#Player.py
#Date: November 22, 2015

import math

class User:
    def __init__(self, user, class_type):
        self.user = user
        self.level = 1
        self.xp = 1
        self.Class = class_type
        self.dex_attr = 0
        self.tech_attr = 0
        self.strength_attr = 0
        self.health_attr = 0
        self.energy_attr = 0
        self.boss_kills = 0
        self.ordinary_kills = 0
        self.towns_visited = 0
        self.money_earned = 0
        self.money = 0
        self.black_jack_wins = 0
        self.beers = 0
        self.houses = 0
        self.rent = 0
        self.shops = 0

    @property
    def drinking_class(self):
        if self.beers <= 25:
            return "Teetotaler"
        elif self.beers <= 250 and self.beers > 25:
            return "Light Drinker"
        elif self.beers > 250:
            return "Alcoholic"

    @property
    def health(self):
        return 110 + (self.health_attr * 4)

    @property
    def energy(self):
        return 50 + (self.energy_attr * 4)

    @property
    def strength(self):
        return 15 + self.strength_attr

    @property
    def tech(self):
        return 15 + self.tech_attr

    @property
    def dex(self):
        return 15 + self.dex_attr

    @property
    def lvl_xp(self):
        return int(math.sqrt(float(self.level) * 999) * self.level)

    def update_level(self):
        while self.xp >= self.lvl_xp:
            self.level+=1
            print("Level Up! \nLevel {} reached! {}xp to next level.".format(lvl, lvl_xp))

    def stats(self):
        return('\n\n==============Player Stats===============\n' +
            '|-{:<17}-|-{:^17}-|\n'.format(' Name', self.user)   +
            '|-{:<17}-|-{:^17}-|\n'.format(' Class', self.Class) +
            '|-{:<17}-|-{:^17}-|\n'.format(' Level', self.level) +
            '|-{:<17}-|-{:>8}/{:<8}-|\n'.format(' XP', self.xp, self.lvl_xp)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Boss Kills', self.boss_kills)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Normal Kills', self.ordinary_kills)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Towns Visited', self.towns_visited)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Drinking Class', self.drinking_class)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Gambling Wins', self.black_jack_wins)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Houses', self.houses)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Houses Sold', self.houses)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Rent Collected', self.rent)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Shops', self.shops)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Money', self.money)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Total Money', self.money_earned))

##This is for testing
p = User(' Arse Face', 'Assassin')
def stats():
    Stats = p.stats()
    print(Stats)


texts: Python differential analysis of heat loss across a pipe

texts:
I made a differential equation solver to forecast heat loss through a pipe with heat loss coefficient contours. It does what I want it to do but I had to use global variables to change the outputs of my simulation function - is there a better way to deal with this issue? Another problem I have is that my code is very slow - when I increase dx the answer seems to become less accurate (the graphs seem to approach a single result past 0.0001)

import scipy
# R_w = 0.028# W/mk air heat loss ocefficient
R_w = 0.654# W/mk water heat loss ocefficient
R_f = 0.042 # W/mk pipe heat loss coefficient
r = 0.2 # m pipe radius
T_0 = 50 # C initial temperature
T_a = 20 # C ambiant temperature
dx = 0.0001 # m differential distance
L = 25 # m length of pipe

def heat_balance(T_1,T_2):
   heat_in = (T_1-T_2) * scipy.pi * r**2 * R_w
   heat_out = ( (T_1 + T_2) / 2 - T_a ) * 2 * r * scipy.pi * dx * R_f
   return abs(heat_in-heat_out)

def simulation():
   T = [T_0]
   X = [0]
   print 'r is ',R_f
   import numpy as np
   from scipy.optimize import minimize
   for x in np.arange(dx,L,dx):
     X.append(x)
     fun = lambda s: heat_balance(T[-1],s)
     T.append(float(minimize(fun,T[-1]-dx,method="SLSQP")['x']))
   return([T,X])

from matplotlib import pyplot as plt
typs = ['+','x','|','_','*']
#typs = ['D','s','8','p','^']
cols = ['red','blue','black','purple','brown']

for i, rf in enumerate([7,14,50,100,200]):
    R_f = 1.0/rf
    ans = simulation()
    plt.scatter(ans[1],ans[0],c=cols[i],marker=typs[i],s = 100,label=rf,lw=3)

plt.legend(fontsize=20,title='Pipe Insolation R Value')
plt.xlabel('Distance (m)',fontsize=20)
plt.ylabel('Average Temperature (C)',fontsize=20)
plt.show()


texts: Shell Script (Bash) to sum multiples of different arguments below a number

texts:
I'm interested in learning how to create shell scripts with bash so here's one of my first exercises, taken from here. It is an extension of the problems Elementary - 4 and 5.

The goal of the program is to sum all multiples or ARG1 or ARG2 below the user's input number.

#!/bin/bash
echo "This program will find all the multiples of ARG1 or ARG2 below or equal to your number and sum them up. Please input your limit:"
read limit

commonMultiple=`expr $1 \* $2`

sumArg1=0
sumArg2=0
sumCommonMultiple=0

for (( i = 0; i <= $limit; i+=$1 )); do
    sumArg1=`expr $sumArg1 + $i`
done
for (( i = 0; i <= $limit; i+=$2 )); do
    sumArg2=`expr $sumArg2 + $i`
done
for (( i = 0; i <= $limit; i+=$commonMultiple )); do
    sumCommonMultiple=`expr $sumCommonMultiple + $i`
done

echo "The result is `expr $sumArg1 + $sumArg2 - $sumCommonMultiple`."

This works perfectly but I'd like the input of more experienced programmers. I don't think my logic is efficient. There must be something obvious I'm missing that could have made my code a lot simpler.

Disclaimer: apparently some of the stuff I used is outdated. I'll take it into account for my future code.*


texts:
Thanks to Gurkenglas for the help with the previous iteration: Haskell - Pig Latin Translator!

Given the constraint that the newtypes are required, what improvements could be made to the following Pig Latin translator?

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}

import Control.Monad (when)
import Data.Char (toLower, toUpper)
import System.IO (hFlush, stdout)

newtype PigLatin = PigLatin String

instance Show PigLatin where
  show :: PigLatin -> String
  show (PigLatin x) = x

instance Monoid PigLatin where
  mempty :: PigLatin
  mempty = PigLatin ""

  mappend :: PigLatin -> PigLatin -> PigLatin
  mappend (PigLatin a) (PigLatin b) = PigLatin $ a ++ " " ++ b

plMap :: (String -> String) -> PigLatin -> PigLatin
plMap f (PigLatin x) = PigLatin $ f x

newtype English = English String
  deriving (Eq)

safeTail :: [a] -> [a]
safeTail (_:xs) = xs
safeTail [] = []

quitCommand :: English
quitCommand = English "\\q"

wordToPig :: English -> PigLatin
wordToPig (English word@(x:_)) = PigLatin $ if isVowel x
                                              then word ++ "yay"
                                              else rearrangedWord ++ "ay"
    where rearrangedWord = drop (length initialConsonants) word ++ initialConsonants
          initialConsonants = takeWhile isConsonant word
          isConsonant = not . isVowel
wordToPig (English "") = PigLatin ""

isVowel :: Char -> Bool
isVowel letter = letter `elem` ['a', 'e', 'i', 'o', 'u']

englishWords :: English -> [English]
englishWords (English input) = map English $ words input

sentenceToPig :: English -> PigLatin
sentenceToPig = plMap (capitalize . safeTail) . foldl mappend mempty . map wordToPig . englishWords

capitalize :: String -> String
capitalize (x:xs) = toUpper x : map toLower xs
capitalize [] = ""

putStrNow :: String -> IO ()
putStrNow message = do
  putStr message
  hFlush stdout

prompt :: String -> IO English
prompt promptInput = do
  putStrNow promptInput
  input <- getLine
  return $ English input

main :: IO ()
main = do
    input <- prompt "> "
    when (input /= quitCommand) $ do
      print $ sentenceToPig input
      main


texts:
So this is my solution to the following leetcode problem: https://leetcode.com/problems/largest-divisible-subset/description/

How could I optimize this code?
I think the run time is \$\mathcal{O}(n^2)\$, is that correct?

def largest_divisible_subset(nums)
return nums if nums.length < 2
nums.sort!
max_result = {}
(0).upto(nums.length - 1) do |i|
    j = i - 1
    result = Set.new

    while j >= 0
       if nums[i] % nums[j] == 0
          if max_result[nums[j]] && max_result[nums[j]].length > result.length
             result =  max_result[nums[j]].dup
          elsif result.length == 0
             result.add(nums[j])
          end
       end

        j -= 1
        break if result.length > nums[0..j].length
    end

    result.add(nums[i])
    max_result[nums[i]] = result
end

   max_result.values.max{|a,b| a.length <=> b.length }.to_a
end


texts:
I wrote this Ruby code that takes data from a survey.  Seeing as it is my first Ruby project, I know it can be written much better. How could some of this code be written in more idiomatic Ruby? This code is extracted from a Rails model (the rest of the model is tame).

def prepare_anova_data

  n = surveys_completed

  (1..n).each do |i|
    anova_summary = create_anova_summary!(no_clusters: i)

    Axis.all.each do |axis|
      clusters_for_axis = cluster(axis.id, i)

      clusters_for_axis.each_with_index do |cluster_axis_summary, index|

        cluster_name = cluster_axis_summary[:name]
        scores = cluster_axis_summary[:data]

        scores.each do |key, value|
          anova_summary.anova_datas.create!(no_clusters: i, cluster_no: index, question_code: key, mean_score: value)
        end
      end
    end
  end
end

def cluster(axis_id, no_clusters)

  # Get all the questions for the axis specified
  @questions ||= self.survey.questions.where(axis_id: axis_id).pluck('id')

  clusterer =diana_clusterer(@questions, no_clusters)

  # Calculate the mean scores per cluster, eg. Cluster 1: question 1: 2, question 2, 3.5 etc.
  series_data = []
  clusterer.clusters.each_with_index do |cluster, index|

    question_means_for_cluster = {}

    # For every question, go through the current cluster and add up all of the scores to
    # caluculate the cluster mean
    for i in 0...@questions.count
      sum = 0
      count = 0

      # data_items is an array containing each respondent's survey scores (as an array)
      cluster.data_items.each do |item|
        sum += item[i]
        count += 1
      end

      question_means_for_cluster[Question.survey_code(@questions[i])] = (sum.to_d / count).round(2)
    end

    # Chartkick requires a hash in this format
    series_data << {name: "Cluster #{ index + 1 }", data: question_means_for_cluster}
  end

  # Don't forget to add the overall mean scores to the result.
  series_data << overall_mean_values(clusterer, @questions)
end

def overall_mean_values(clusterer, questions)

  overall_question_means = {}

  # For each question, go through every item (array of individual survey scores) in every cluster and add up the scores
  # This gets the Survey Group average for each question in the survey
  for i in 0...questions.count
    sum = 0
    count = 0

    # Unpack the clusters here, we don't need the clusters, we just want to use the already retrieved data for
    # this survey group and merely sum it all up by question.
    clusterer.clusters.each do |cluster|
      cluster.data_items.each do |item|
        sum += item[i]
        count += 1
      end
    end

    overall_question_means[Question.survey_code(questions[i])] = sum.to_d / count
  end

  # This format is required for the Chartkick libary
  { name: 'Overall', data: overall_question_means }
end

private

def diana_clusterer(questions, no_clusters)

  # Get all the responses for the survey group into an array (of arrays)
  answers = []
  self.members.each do |member|
    answers << member.responses.where(question_id: questions).pluck('score')
  end

  # Use the AI4R library to create a cluster using the Diana Algorithm
  data_set = DataSet.new(data_items: answers, data_labels: questions)
  Diana.new.build(data_set, no_clusters)
end


texts:
This query produces the results I want.

Is there a less wordy or more effective way to write this query?

Criteria:
1. Vendor in detail record must have a record in TRANSEFFECTIVE
2. Get the most recent (begin_frame) record from TRANSDETAIL
3. Tells me if the vendor has any other categories in the TRANSMODAL table.

In this case,

Since DDAN has a detail record and has record in TRANSEFFECTIVE, report that DDAN has an AIR,GROUND,and SEA modal record.

Since POKE has a detail record and has record in TRANSEFFECTIVE, report that POKE has only AIR and GROUND modal records.

select vend_code,
       vend_numb,
       description,
       freight_mode
from (
select vend_code,
       vend_numb,
       begin_frame,
       freight_mode,
       freight_count,
       description,
      row_number() over (partition by vend_code,
                                      vend_numb,
                          (case modal_class_code
                           when 'A1' then 1
                          when 'A2' then 1
                           when 'G1' then 2
                           when 'S1' then 3
                          end)
                         order by vend_code,
                                  vend_numb) as modal_class_count
from
(
select td.modal_vend_code as vend_code,
       td.modal_vend_numb as vend_numb,
       td.modal_begin_frame as begin_frame,
        td.modal_description as description,
       te.modal_vend_begin_frame as te_begin,
       te.modal_vend_close_frame as te_close,
       tm.modal_class_code       as modal_class_code,
       case tm.modal_class_code
           when 'A1' then 'AIRFREIGHT'
           when 'A2' then 'AIRFREIGHT'
           when 'G1' then 'GROUND'
           when 'S1' then 'SEABOUND'
           else 'UNKNOWN'
        end as freight_mode,
      rank() over (partition by td.modal_vend_code,
                                td.modal_vend_numb
                       order by td.modal_begin_frame desc) as freight_choice,
       count(*) over (partition by td.modal_vend_code,
                                   td.modal_vend_numb) freight_count
from  transdetail td
inner join transeffective te on td.modal_vend_code = te.modal_vend_code
                             and td.modal_vend_numb = te.modal_vend_numb
inner join transmodal  tm  on td.modal_vend_code = tm.modal_vend_code
                          and td.modal_vend_numb = tm.modal_vend_numb
 )
   where freight_choice=1
)
where modal_class_count=1
;


texts: POSIX shell script using a string to store command arguments

texts:
Background

I’ve started putting all my configuration files (which include many shell files) under version control.  In the Git repository, I’ve configured a pre-commit hook that runs the checkbashisms utility from Debian’s devscripts package on each sh file in the repository as a simple sanity check to ensure that I don’t inadvertently introduce Bash-specific syntax into scripts that should be POSIX compatible.

Reason for using POSIX sh

I’m using /bin/sh as the interpreter for this pre-commit hook as it’s quicker for systems where /bin/sh is a link to dash. Committing files shouldn’t take a noticeable amount of time.

I don’t want to run checkbashisms if the only files staged for committing are non-shell files and for performance, I only want to execute checkbashisms command once and supply as arguments the names of all the relevant files that should be checked.

Arguments that may contain spaces

While I don’t normally create files with names containing unusual characters, I tried to write this script to be reasonably robust (without becoming overly complex, harder to read and prone to error on various inputs).

In a more fully-featured shell such as Bash, I’d process a list of file name arguments using an array. However, a plain POSIX shell (such as dash) doesn’t support array variables.

My solution

When using a POSIX shell, the positional parameters can often be used as a substitute but in this case, I couldn’t see how I could easily modify them to only add the filenames of shell scripts.  The technique I used was to split fields using newlines (not spaces) and to use a string to store the arguments to be passed to checkbashisms.

I’ve verified that it works with filenames containing spaces and single quotes – but due to to how the shell represents names containing other characters, it doesn’t work with filenames containing double quotes, tabs, etc. This is fine as I really don’t expect to have to process such filenames.

However, it feels hacky and I don’t know if I’m introducing the potential for other errors (“unknown unknowns”). Modifying IFS is explicitly not recommended by Greg’s Wiki. I thought I’d post here in the hope that the robustness and/or maintainability of the code can be improved.

Script

#!/bin/sh

# Check shell scripts for Bashisms if the `checkbashisms` utility is installed.
# Called by "git commit" with no arguments.  This hook should exit with a
# non-zero status after issuing an appropriate message if it wants to stop the
# commit.
# Allows for files with spaces or single quotes in their name – but not any
# other unusual characters.

set -u  # -o nounset – exit with failure if an unset shell variable is referenced.
set -e  # -o errexit – exit script if any command fails.
set -o noclobber  # prevent shell redirection from over-writing files.

if ! command -v checkbashisms >/dev/null 2>&1; then
  echo "‘checkbashisms’ is not available; it can be installed from the ‘devscripts’ package."
else
  echo "Checking for Bashisms in shell scripts..."

  # Use only newline characters (not spaces) to split filenames.
  IFS="
"  # POSIX way to set IFS to newline (be careful with indentation).
  set -f  # Disable globbing of pathnames.
  # Arrays are not defined by POSIX so store arguments in a string variable.
  filenames=""

  # Get list of filenames that have been staged for committing.
  for file in $(git diff --cached --name-only); do
    # Only process shell scripts.
    case "$file" in *.sh|shell/*.sh)
      # Add file to list of arguments (separated by newlines).
      filenames="$filenames
$file"  # again, be careful with indentation of the code.
    esac
  done;

  # If any shell files have been staged, check their syntax for Bashisms.
  if [ "$filenames" ]; then
    if checkbashisms $filenames; then   # no quotes for field-splitting.
      printf "(No Bashisms found)"
    else
      exit 1
    fi
  fi

  # Restore file globbing and IFS.
  unset IFS
  set +f
fi

# Further code to check for other issues ...


texts: Making two sequential asynchronous requests using promises

texts:
The following code is making two asynchronous requests to obtain the desired data. The second request needs to access the data from the first request, hence I need to nest it. I know that it is better to chain promises, but this is a case where nesting seems necessary.

However the lint raises a warning: avoid nesting promises. Should I ignore the warning or there is a better way to rewrite the code?

function get_note_full(note_id) {
  return db.collection('notes').doc(note_id).get()
    .then(doc => {
      const data = doc.data();
      return get_author_data(data.author_uid)
        .then(author => {
          return ({
              id: note_id,
              title: data.title,
              text: data.text,
              author: author
            });
        });
    });
}


texts:
My objective has been to build a custom dropdown like the one on Amazon's search scope selector. I do this by positioning a styleable element on top of a standard select list. I then use jQuery to keep the styleable element in sync with the select list. My code works fine, but I would love to learn how to do it cleaner. Currently, I do the syncing twice - on page load and on change. Is it possible to refactor my code using on()? (or similar).

prev() is the styleable element.

// Sync is performed on page load
var $select = $('select');
$select.each(function(index, value) {
  var optionText = $(this).find('option:selected').text();
  $(this).prev().text(optionText);
});

// Sync is performed on change event
$('select').change(function() {
  var optionText = $(this).find('option:selected').text();
  $(this).prev().text(optionText);
});


texts: Network traffic flow detection using pandas dataframe

texts:
I have a pandas dataframe containing network traffic of multiple hosts:

df = pd.read_csv ( "traffic.csv",skipinitialspace=True,
                                           usecols=['frame.time_epoch','ip.src','ip.dst','tcp.srcport','tcp.dstport','frame.len','tcp.flags','Protocol'],na_filter=False,encoding="utf-8" )

complete = pd.read_csv ( "traffic.csv",skipinitialspace=True,
                                       usecols=['frame.time_epoch','ip.src','ip.dst','tcp.srcport','tcp.dstport','frame.len','tcp.flags','Protocol'],na_filter=False,encoding="utf-8" )

I would like to group traffic flow, which 'frame.len' sign show the direction of packets. To do so, for each host first I set the sign of the 'frame.len' by comparing 'ip.dst' with host IP:

complete.loc[(complete['ip.dst'] == hostip[i])  ,'frame.len'] = complete['frame.len'] * -1

then I replace the 'ip.src' and 'tcp.srcport' with 'ip.dst' and 'tcp.dstport' and vis verca for incoming packets whose 'frame.len' get negative value.

complete.loc[(complete['frame.len'] < 0),'ip.src'] = df['ip.dst']
complete.loc[(complete['frame.len'] < 0),'ip.dst'] = df['ip.src']
complete.loc[(complete['frame.len'] < 0),'tcp.srcport'] = df['tcp.dstport']
complete.loc[(complete['frame.len'] < 0),'tcp.dstport'] = df['tcp.srcport']

and then I group each flow by the following criteria:

complete_flow =
complete.groupby(['ip.src','ip.dst','tcp.srcport','tcp.dstport','Protocol'])

Is there a simpler way using pandas dataframe features?


texts: Accessing a certain I/O controller using memory-mapped I/O

texts:
I have a program that accesses a certain I/O controller using memory-mapped I/O. I currently store the base address of this controller in a const variable.

This leads to a code structure something like this:

gpio.h:

int gpioFunc (unsigned int pin, unsigned int func);

int setGpio (unsigned int pin, unsigned int val);

gpio.c:

#include "gpio.h"
unsigned volatile int* const gpioAddr = (unsigned int*) 0x20200000;

int gpioFunc (unsigned int pin, unsigned int func)
{
    //code that uses the variable
}

int setGpio (unsigned int pin, unsigned int val)
{
    //code that uses the variable
}

main.c:

#include "gpio.h"
void main ()
{
    gpioFunc (16,1);
    setGpio(16,0);
    hlt();
}

I have always been uncertain of the best practices in C as to where to put constants.  Does this way make sense, or would it be better practice to put it somewhere else?  If so, where?


texts:
Given a String and dictionary of words, break the string in minimum space sentence.

Ex:
inputStr = "ilikefacebook"
dictionary = {"i","like","face","book","facebook"}
Possible Strings:
i like face book - 3 spaces
i like Facebook - 2 spaces - this is expected answer.

Here's a trivial solution. It's a simple solution, but the runtime performance is poor O(n2). There must be better ways of doing this.

public class MyClass {

    public static void main(String[] args) {

        String input = "IlikeFacebook";

        HashSet<String> dict = new HashSet<String>();
        dict.add("i");
        dict.add("like");
        dict.add("face");
        dict.add("book");
        dict.add("facebook");

        int left = 0;
        int right = input.length();
        int count = -1;

        boolean[] status = new boolean[input.length()];

        while (left < right) {
            for (int i = 0; i <= right; i++) {
                String word = input.substring(i, right);
                word = word.toLowerCase();
                if (dict.contains(word)) {
                    count++;
                    right = i;
                    System.out.println(" -> " + word);
                }
            }

        }
        System.out.println(" Space count " + count);
    }

}

Can anyone provide a better and efficient solution of this problem?


texts:
This script is called trash and it goes on the path.

Usage: trash [OPTIONS] [TRASH_FILES]...

How clean/readable do you think this is? Is Python the right tool for the job?

#!/usr/bin/env python3
import os
import sys
import shutil
import itertools
from pathlib import Path
import click

first = next

def candidate_names(path):
    '''unused_names('f.txt') yields f.txt, f.txt_1, f.txt_2, ...'''
    yield path
    for i in itertools.count(1):
        yield path.with_name('{path.name}_{i}'.format(**locals()))

default_trash_dir = '~/.trash'

@click.command()
@click.argument('trash_files', nargs=-1)
@click.option('--trash-dir', default='', metavar='<trash_dir>', help=
'''destination for trash. Defaults to ${{TRASH_DIR}}, and then '{}'.'''
              .format(default_trash_dir))
def trash(trash_files, trash_dir):
    '''Safely trash the given files by moving them into a trash_dir.

Files are stored by their path relative to either ~ or / (preferring ~
if possible)

If an existing item with the same name is already in the trash, I
add _1, _2, ... to the end of the filename.

Metadata is copied; See Python documentation on shutil.copy2 for
details.

    \b
    $ touch a
    $ mkdir b
    $ touch b/c
    $ touch /tmp/d
    $ trash a b/c /tmp/d
    /home/sam/subdir/a -> /home/sam/.trash/subdir/a
    /home/sam/subdir/b/c -> /home/sam/.trash/subdir/b/c
    /tmp/d -> /home/sam/.trash/_root/tmp/d
    $ touch a
    $ trash a
    /home/sam/subdir/a -> /home/sam/.trash/subdir/a_1

    '''

    # get/make trashdir
    if not trash_dir:
        # empty-string and non-existence are treated the same way
        trash_dir = os.environ.get('TRASH_DIR', '')
        if not trash_dir:
            trash_dir = default_trash_dir
    trash_path = Path(trash_dir).expanduser()
    trash_path.mkdir(exist_ok=True, parents=True)

    for trash_file_ in trash_files:
        trash_file = Path(trash_file_)
        if not trash_file.exists():
            print("{}: not found".format(trash_file))
            sys.exit(1)

        # get absolute path
        trash_file = Path(trash_file_).resolve()

        # get a destination which does not already exist
        try:
            trash_dest_candidate = trash_path / trash_file.relative_to(Path.home())
        except ValueError:
            trash_dest_candidate = trash_path / '_root' / trash_file.relative_to('/')

        trash_dest = first(filter(lambda path: not path.exists(),
                                 candidate_names(trash_dest_candidate)))

        trash_dest.parent.mkdir(exist_ok=True, parents=True)
        print('{} -> {}'.format(trash_file, trash_dest))

        try:
            shutil.move(trash_file, trash_dest)
        except Exception as e:
            print(str(e))
            sys.exit(2)

if __name__ == '__main__':
    trash()


texts:
I have written a C function to parse an IP address that should match the regular expression ^\d+.\d+.\d+.\d+ and nothing else.
Additionally all bytes are limited to 0-255.

I tried to catch all invalid inputs, but I am unsure if there are any edge cases I missed or if it could be simplified.

The function is intended to be used in an embedded system. Therefore I don't want to use external libraries (or anything in stdio.h) and code size is most important.

I am not really looking for stylistic advice, but rather a functional review.

// Returns the number of characters parsed or 0 if not successful
unsigned int StringToIp(uint8_t addr[4], const char* ipSrc, const size_t ipSrcLen) {
    char* ipPtr = ipSrc;
    int16_t current = -1;
    uint8_t addrIdx = 0;
    for (int i = 0; i < ipSrcLen, addrIdx < 4; i++) {
        char c = *ipPtr++;
        if (c == '.') {
            if (current == -1) return 0;  // 2 consecutive dots or dot at beginning
            addr[addrIdx++] = current;
            current = -1;

        } else {
            uint8_t digit = c - '0';
            if (digit >= 10) {
                // Invalid character
                if (addrIdx == 3 && current >= 0) {
                    // Invalid character at the end is treated as the end of the address
                    addr[addrIdx++] = current;
                    ipPtr--;
                    break;
                }
            }

            if (current == -1) {
                // first digit of current byte
                current = digit;

            } else {
                // further digits
                current = current * 10 + digit;
                if (current > 255) return 0;  // current byte greater than 255 => invalid
            }
        }
    }

    if (addrIdx == 3 && current >= 0) {
        // write last byte (necessary if at end if string)
        addr[addrIdx++] = current;
    }

    if (addrIdx == 4) {
        // valid IP address
        return ipPtr - ipSrc;

    } else {
        // invalid IP address
        return 0;
    }
}

I also wrote the inverse function. Here I am quite sure I got all cases, but the divisions are suboptimal, because the microcontroller has no dedicated divider. Which means extra code for the divisions has to be generated and this bloats the code size and reduces the speed (which is somewhat less important to me).

Is there any why to avoid the divisions?

unsigned int IpToString(char ipDst[4*3+3+1], const uint8_t addr[4]) {
    char* ipPtr = ipDst;
    for (int i = 0; i < 4; i++) {
        uint8_t current = addr[i];

        uint8_t h = current / 100;
        current -= h * 100;
        uint8_t d = current / 10;
        current -= d * 10;
        uint8_t o = current;

        if (h > 0) *ipPtr++ = '0' + h;
        if (h > 0 || d > 0) *ipPtr++ = '0' + d;
        *ipPtr++ = '0' + o;
        if (i < 3) *ipPtr++ = '.';
    }
    *ipPtr = '\0';
    return ipPtr - ipBuffer;
}


texts:
You guess a word, and if its letter(s) is in the same spot as a hidden word's, you add [] around the letter.  If it's in the hidden word, but not in the same spot, you add()).

As of now, I have a whole bunch of loops which I find makes the program un-compact. I would love to see some tips on how to shorten this program!  Efficiency isn't a problem.  I am looking for compactness.

word = list("tiger")
guesses = 0
holder = 1
while holder == 1:
    s = list(input("Please input what you think the word is"))
    while len(s) > 5 or len(s) < 5:
        print("Please guess a five - letter word!")
        s = list(input("Please input what you think the word is"))
    s2 = s
    for i in range (0, len(word)):
        if word[i] == s[i]:
            letter = ("[",s[i],"]")
            lette = "".join(letter)
            s2[i] = letter
    for i in range (0, len(word)):
        for j in range (0, len(word)):
            if s[i] == word[j]:
                letter2 = ("(", s[i],")")
                letter2 ="".join(letter2)
                s2[i] = letter2
    print(s2)
    guesses = guesses +1
    print ("You have used", guesses, "guesses/guess")
    s3 = ["[t]", "[i]", "[g]", "[e]", "[r]"]
    if s2 == s3:
        print("You WIN!")
        holder = 2


texts:
This is an answer to this problem.

Basically, given an array, swap the given number of elements in the array.

The solution that came to my mind: since we always swap at least two elements, pick two random indices and swap array[first_random] with array[second_random].  Then, if there's more to swap, find index that was not swapped yet and swap it with one of previously swapped.

This might be confusing a little, but it works. I am curious whether there are some other, better approaches.

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

void print_arr(int a[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        printf("%d ",a[i]);
    }
        printf("\n");
}

void swap(int a[], int i, int j) {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

int next_idx(int swapped[], int s_count, int size) {
    int n, i;
    char in_arr;
    while (1) {
        in_arr = 0;
        n = rand() % size;
        for (i = 0; i < s_count; i++) {
            if (swapped[i] == n) {
                in_arr = 1;
                break;
            }
        }
        if (!in_arr) {
            break;
        }
    }
    return n;
}

void swap2_or_more(int a[], int size,int count) {
    srand(time(NULL));
    int i, j, s_count = 0;
    int swapped[size];
    i = rand() % size;
    swapped[s_count] = i;
    s_count++;
    do {
        j = rand() % size;
    } while (i == j);  // make sure indexes are different
    swapped[s_count] = j;
    s_count++;

    swap(a, i, j);
    count -= 2;
    while (count) {
        i = next_idx(swapped, s_count, size);
        j = rand() % s_count;
        swap(a, i, swapped[j]);
        swapped[s_count] = i;
        s_count++;
        count--;
    }
    printf("swapped indexes:\n");
    print_arr(swapped, s_count);
}

int main(void)
{
    int a[] = {1,2,3,4,5,6,7,8,9,10};
    swap2_or_more(a, 10, 5);
    printf("array after swap:\n");
    print_arr(a, 10);
    return 0;
}


texts:
I'm in the process of working on a client's site. I have a section containing a ul with list items and a div containing the slides that are triggered when clicking on an li item.

For instance,
Item One
 triggers
...
.

Here is the jQuery portion:

var slidesNav = $('#slides-nav > li'),
    slidesContent = $('#slides-content').find('div'),
    id = '',
    slideId = '';

// Set initial state of slides to hidden, except the first one.
slidesContent.hide().first().slideDown();

var setClickEvents = function (id) {

    $('#nav-' + id).on('click', function () {
        slideId = $('#slide-' + id);

        if (slideId.css('display') !== 'block') {
            slidesContent.slideUp();
            slideId.slideDown();
        }
    });
};

for (var i = 0; i < slidesNav.length; i++) {
    id = $(slidesNav[i]).attr('id').substr('4');

    // assign click events
    setClickEvents(id);
}

If my solution can be improved, please explain as my ultimate goal is to become a better programmer.

Here is a jsbin with the full code. It's a variation of the original for the client.


texts:
We're storing the xml communications with an external service in a text in the db and in a before_create I've got the following:

  # filter opera password
  def remove_password!
    self.request.gsub!  /UserPassword\>[^\<]*\<\//,
                        'UserPassword>[FILTERED]</'
  end

Is there a better, safer way of doing it?


texts: Pre-commit hook to prevent large file commits

texts:
I've written the below bash script to run as a pre-commit hook. The intention is to check the git staging area for any files larger than 1mb, and prevent the commit if any are present.

#!/bin/sh
too_big() {
    bytez=$(cat "$(git rev-parse --show-toplevel)/$1" | wc -c)
    if [ "$bytez" -gt 1000000 ] ; then
        cat <<EOF
Error: Attempting to commit a file larger than approximately 1mb.
Commiting large files slows jenkins builds, clones, and other operations we'd rather not slow down.
Consider generating, downloading, zipping, etc these files.
Offending file - $1
EOF
        exit 1
    fi
}

# If you want to allow large files to be committed set this variable to true.
allowbigfiles=$(git config --bool hooks.allowbigfiles)

# Redirect output to stderr.
exec 1>&2

if [ "$allowbigfiles" != "true" ]
then
  set -e
  git diff --name-only --cached $1 | while read x; do too_big $x; done
fi

Edit:
The final script ended up as part of a library of client side Git Hooks


texts: WOMOIWIW: What Org-mode Opens is What I Want

texts:
Motivation
Previously, on the Emacs stack exchange:

In Org mode, when I open a link (C-c C-o) [...] [that] contains a wildcard, such as file:3_o*.pdf, Emacs opens it through dired instead [...] within Emacs.
I would instead have it open the first match of that pattern in the system application …

The handling of file: links is hard-coded in Org mode. If there is any wildcard in the given path, then org-link-open will nope out of the situation and instead call dired. And while one could change Org mode's source code in the local elisp files, I remembered that you can change the arguments or results of functions with advices.
Solution
I opted for an advice :around org-link-open with the following code:
(defun my-org-expand-file-link (link)
  "Expand a pattern in LINK to the first matching file.

Returns the original LINK if no file matches the pattern in LINK or if it is not
a link of type 'file:'.  See info node `(org)External links' for more information."
  (let ((type (org-element-property :type link))
        (path (org-element-property :path link)))
    (cond
     ((equal type "file")
      (let ((candidates (file-expand-wildcards path)))
        (if candidates
            (org-element-put-property (org-element-copy link) :path (car candidates))
          link)))
     (t link))))

(defun my-org-link-open-advice (orig-fun link &rest args)
  "Advice for ORIG-FUN that expands patterns in 'file:' LINKs.
See `my-org-expand-file-link' for more information.
Optional argument ARGS are passed as-is."
  (apply orig-fun (my-org-expand-file-link link) args))

(advice-add 'org-link-open :around #'my-org-link-open-advice)

So whenever you open a link with C-c C-o (org-open-at-point which calls org-link-open), you end up with a concrete file.

Some remarks
I recommend using a custom link type like first: or wrapping the code above minor mode, as the advice is somewhat invasive and might surprise users that really want to get a list of matching files instead.
I'm open to any feedback on the elisp code, especially since I'm still a elisp newbie.


texts:
This is a continued discussion from (4 sum challenge) by return count only.

  Problem

  Given four lists A, B, C, D of integer values, compute how many tuples
  (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

  To make problem a bit easier, all A, B, C, D have same length of N
  where \$0 \le N \le 500\$. All integers are in the range of \$-2^{28}\$ to \$2^{28} - 1\$
  and the result is guaranteed to be at most \$2^{31} - 1\$.

  Example:

  Input:

A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

  Output:

2

  Explanation:

  The two tuples are:

  (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
  (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

I'm wondering if there are any ideas to have a solution less than \$O(n^2)\$ time complexity.

Source code in Python 2.7,

from collections import defaultdict
def four_sum(A, B, C, D):
    sum_map = defaultdict(int)
    result = 0
    for i in A:
        for j in B:
            sum_map[i+j] += 1
    for i in C:
        for j in D:
            if -(i+j) in sum_map:
                result += sum_map[-(i+j)]

    return result

if __name__ == "__main__":
    A = [1, 2]
    B = [-2, -1]
    C = [-1, 2]
    D = [0, 2]
    print four_sum(A,B,C,D)


texts: Jasmine test involving a sequence of actions

texts:
I am writing test cases in JavaScript and jQuery, the framework is Jasmine and Karma.

describe('When a user selects a multiple-response Hotspot response', function () {

    it('Then allow highlighting multiple responses', function (done) {
        utils.clickHotspotElementAtIndex(view, 1, function() {});
        utils.clickHotspotElementAtIndex(view, 0, function() {});
        utils.clickHotspotElementAtIndex(view, 2, function() {});
        setTimeout(function() {
            expect(utils.verifyHotSpotHasBeenHiglightedAtIndex(view, 0)).toBe('true');
            expect(utils.verifyHotSpotHasBeenHiglightedAtIndex(view, 1)).toBe('true');
            expect(utils.verifyHotSpotHasBeenHiglightedAtIndex(view, 2)).toBe('true');
            done();
        }), 2000});
    });

What it does is:

click on element 1, sync action
click on element 0, sync action
click on element 2. sync action
When the main thread is free, wait for 2 seconds and then
expect element 0 has been highlighted
expect element 1 has been highlighted
expect element 2 has been highlighted

Is there a more elegant way to do this?


texts:
I am studying C++ and after I learned about some functions of the library cctype like isdigit I decided to make a program that validates user input only to be an integer number. So input like 123as, :$ or +.234 are invalid, however I decided to keep the plus or minus sign, i.e., input like -24 or +142 are valid. Below is my code:

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

bool integer_valid(string s);
int get_integer();

int main()
{
    int number;

    number = get_integer();
    cout << "The integer number is:\t" << number << "\n" << endl;

    system("pause");
    return 0;
}

bool integer_valid(string s)
{
    int i, length_s;
    bool is_valid = true;

    length_s = s.length();

    if (length_s == 0)
        is_valid = false;
    else
    {
        if (length_s == 1)
        {
            if (!isdigit(s[0]))
                is_valid = false;
        }
        else
        {
            if (s[0] == '+' || s[0] == '-' || isdigit(s[0]) != 0)
            {
                for (i = 1; i < length_s; i++)
                {
                    if (!isdigit(s[i]))
                        is_valid = false;
                }
            }
            else
                is_valid = false;
        }
    }
    return is_valid;
}

int get_integer()
{
    int new_number;
    string number;
    bool is_valid;

    do {
        cout << "Enter an integer number:\t";
        getline(cin, number);
        cout << "\n";

        is_valid = integer_valid(number);

        if (is_valid == false)
            cout << "ERROR. The entered number must be an integer.\n" << endl;
    } while (is_valid == false);

    new_number = stoi(number);

    return new_number;
}

I'm aware that in general is a bad practice to use using namespace std, but since my program has less tan 100 lines of code I think it's really not a big issue here. Moreover, I wonder if there is another (simpler/faster) way to validate integer numbers?

EDIT: Answering to the comment made by Roland Illig, I would say yes. More exactly, any kind of integer should be valid, but as far as I know, int has a defined size, so if I want to valid long integers I should use the type long long int and also the function stoll, right?

Any feedback would be greatly appreciated.


texts: Ensure that a directory reflects a specified Git commit

texts:
I have a method that looks like the method below, and I can't help but shake the feeling that it can be improved. It doesn't really "read" well, and it seems like checkout could be called only once, somehow.

def ensure_correctness
  if exist?
    unless correct_version?
      delete!
      checkout
    end
  else
    checkout
  end
end

def checkout
  run_command(['git', 'clone', '--depth', '1', url, path])
end

def exist?
  Dir.exist?(path)
end

def delete!
  FileUtils.rm_rf(path)
end

def correct_version?
  commit_sha_short == desired_commit_sha_short
end

The best I could come up with is moving the code from failing correct_version? to a new method (which probably isn't a terrible idea, but I wonder if I can do better).

I feel like I'm missing something really obvious here...


texts: Hash Map Library for any type (Void Pointers)

texts:
This is a hash map library for C that stores void* pointers with char* strings (null terminated) for keys

//  ColiisionHashMap
//  Copyright © 2015 Leo Dastur.
//

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

typedef struct HashMapNode {
    char* key;
    void* data;
} HashMapNode;

typedef struct HashLocation {
    HashMapNode** nodes;
    int numberNodes;
} HashLocation;

typedef struct HashMap {
    int mapSize;
    struct HashLocation** hasharray;

} HashMap;

HashMap* newHashMap(int mapSize) {
    if (mapSize<=0) {
        abort(); //Zero Mapsize is bad
    }
    HashLocation** array= calloc(mapSize, sizeof(HashLocation*));

    for (int i = 0; i<mapSize; i++) {
        array[i] = malloc(sizeof(HashLocation));
        array[i]->nodes=NULL;
        array[i]->numberNodes=0;
    }

    HashMap* aHashMap = calloc(1, sizeof(HashMap));
    aHashMap->mapSize = mapSize;
    aHashMap->hasharray = array;
    return aHashMap;
}

int keyHash (HashMap* aHashMap, char* key, int key_len) {
    int charSum=0;
    int i;
    for (i=0; i<key_len; i++) {
        charSum+=key[i];
    }
    return charSum % aHashMap->mapSize;
}

int getStringlen(char* astring) {
    strlen(astring);
/*
    int counter=0;
    while (astring[counter]!='\0') {
        counter++;
    }
 */
    return (int) strlen(astring); /*counter;*/

}

void mapAdd(HashMap* aHashMap, char* key, char* data) {
    int key_len = getStringlen(key);
    int hashed_key = keyHash(aHashMap, key, key_len);

    HashMapNode* dataNode = malloc(sizeof(HashMapNode));
    dataNode->key=key;
    dataNode->data=data;

    HashLocation* theHashlocation = aHashMap->hasharray[hashed_key];
    if (theHashlocation->nodes==NULL) {
        theHashlocation->nodes = calloc(1, sizeof(HashMapNode*));
        theHashlocation->nodes[0]=dataNode;
        theHashlocation->numberNodes=1;
    } else {
        realloc(theHashlocation->nodes, theHashlocation->numberNodes+1);
        theHashlocation->nodes[theHashlocation->numberNodes] = dataNode;
        theHashlocation->numberNodes++;
    }

}

void* mapGet(HashMap* aHashMap, char* key) {
    int key_len = getStringlen(key);
    int hashed_key = keyHash(aHashMap, key, key_len);

    HashLocation* theHashLocation = aHashMap->hasharray[hashed_key];
    if (theHashLocation->nodes==NULL) {
        return NULL;
    }
    if (theHashLocation->numberNodes==1) {
        HashMapNode* dataNode = theHashLocation->nodes[0];
        return dataNode->data;
    }
    else {
        //Get Node Array, Search Node Array for key, return that node's data. Return NULL if key is not found.
        HashMapNode** nodeArray = theHashLocation->nodes;
        int array_len = theHashLocation->numberNodes;
        HashMapNode* dataNode = NULL;

        for (int i = 0; i < array_len; i++) {
            if (!strcmp(nodeArray[i]->key, key) ) {
                dataNode = nodeArray[i];
                // printf("Found Key");
                break;
            }
            //else printf("Didn't Find it yet");
        }
        if (dataNode==NULL) {
            return NULL;
        }
        else return dataNode->data;
    }
}

Is there a more efficient way of handling collisions, and
what else could I do to make this a real-world usable map?


texts: Code for calculating the books dispatched

texts:
Recently I came across this, here is an excerpt from it,

  This is another problem about Indraneel's library. His library has one
  long shelf. His books are numbered and he identifies the books by
  their number. Each book has a distinct number.

  He has lost many books, since many of his friends borrow his books and
  never bother to return them. He does not want to lose any more books
  and has decided to keep a record of all books that he lends to his
  friends. To make the task of borrowing a book a little difficult, he
  has given the following instructions to his friends: when they borrow
  a book, they must record in a register its position from the left
  among the books currently on the shelf.

  Suppose there are 5 books in the library and they are arranged as
  follows:

  26  1  42  15  3

  If someone walks in and borrows the book 42, then he will record 3 in
  the register because this book is the third from the left on the
  shelf. Now the shelf looks like this:

  26  1  15  3

  If the next person borrow the book 3, he writes down 4 in the register
  since this is currently the fourth book from the left on the shelf,
  and so on.

  Indraneel knows the initial arrangement of the books in his library at
  the time that he introduced the register system. After a while he
  examines his register and would like to know which books have been
  borrowed. Your task is to write a program to help Indraneel solve this
  problem.

My approach is count from left if the value of the book is -1 then skip the the book , when the count is equal to the count of the book then print the name of the book and make that value -1.But this approach though correct is giving time limit exceeded on a handful of testcases. Anyone having a better approach for this problem?

Here is the code:

#include <iostream>
#include <vector>

int main(){
    //Input for the number books with the values
    int m;
    std::cin >> m;
    std::vector<int>books(m);

    for(int i=0;i<m;i++){
        std::cin>>books[i];
    }
    //Input for the dispatches made
    int n;
    std::cin >> n;
    std::vector<int>taken(n);

    for(int i=0;i<n;i++){
        std::cin >> taken[i];
    }

    for(int i=0;i<n;i++){
        int bookNum = taken[i]-1;                       //Get the position of book needed
        int k=0;
        for(int j=0;j<m;j++){                          //Go through the book array
            if(books[j] != -1){
                if(k == bookNum){
                    std::cout << books[j] << std::endl; //Display the name if the k is equal
                    books[j] = -1;
                    break;
                }
                k++;                                    //Increment k if the value of the book is not negative
            }
        }
    }

    return 0;
}

Here are the testcases.


texts: Three functions for computing simple arithmetic

texts:
Here is my code where I have 3 functions that do simple arithmetic:

#include <stdio.h>

/* The following Code Contains 3 functions
 * that compute simple arithmetic such as
 * computing the sum of 3 integers and divison
 * of three floating integers.
 */
 void getSum(int x, int y, int z);
 double doDiv(float one, float two, float three);
 void getDiv(float a, float b, float c);

 int main()
 {
    getSum(100,242,62);
    getDiv(100.0,25.0,2.0);
    return 0;
 }

/*The function getSum accepts three int
 *values and computes the sum of all three and prints
 *the result via standard output.
 */

 void getSum(int x, int y, int z)
 {
    int sum = x + y + z;
    printf("%i\n",sum);

 }

/*The function doDiv accepts three floating
 *values and computes the divison of first two.
 *Finally it divides the result by the third
 * floating value and returns the final answer.
 */

 double doDiv(float one,float two, float three)
 {
    float answer;
    answer = one/two;
    answer = answer/three;
    return answer;
 }

/* The function getDiv accepts three floating values
 * and then calls the doDiv function. The three accepted
 * values are passed as parameters in the function call.
 */

 void getDiv(float a, float b, float c)
 {
    float finalAnswer;
    finalAnswer = doDiv(a,b,c);
    printf("%f\n", finalAnswer);
 }

I have tried my best to comment each function but I am not sure if I am doing it correctly. Can someone please advise me on making my comments better, naming variables better and anything else that can help me utilize coding standards correctly?

I would like to pick up the habit now while I am still writing small lines of code so I can take it forward with me when I write bigger codes.

Any suggestions on how I can comment better, name variables better, write code more elegant are welcome. Also, do I comment the method declarations on top?


texts: Combine neighboring parts of an array based on a condition

texts:
I have written this code which takes a one dimensional array, for example:

{"abc","ade","sss","fgw","asd","lka","o"}

and turns it into an array of arrays, combining the elements which do not meet the condition.

For the condition m=>!m.Contains("a") for example, the output will be:

{{"abc","ade"},{"sss"},{"fgw"},{"asd","lka"},{"o"}}

The code works, but i suspect there is a linq way to do it, and refrain from using temporary variables that i dislike.

    public static string[][] combineBy(this string[] inp,Func<string,bool> f)
    {
        List<string[]> holdElements = new List<string[]>();
        while (inp.Length!=0)
        {
            if (f.Invoke(inp[0]))
            {
                holdElements.Add(new string[] { inp[0] });
                inp = inp.Skip(1).ToArray();
            }
            else
            {
                var toAdd = inp.TakeWhile(n => !f.Invoke(n));
                holdElements.Add(toAdd.ToArray());
                inp = inp.Skip(toAdd.Count()).ToArray();
            }
        }
        return holdElements.ToArray();
    }


texts:
I created a very basic "image projector" that shows the current one and shows the next on clicking into the image.

And yeah, it works, but I don't think that's a very elegant way to do it. Any advice please?

Bear in mind I'm just starting my JavaScript classes and that's my third assignment, but the teacher is not really helpful when it comes to clean code, for him if it works, it works :/

Anyway, here's the full code: http://jsfiddle.net/AngelCJ/F5Hg7/

And the messy part:

/* loads the first image of the ul element using the n counter */
window.onload = function loadFirst() {
    var n=0;
    document.getElementById("list").children[n].style.display="block";
    /* onclick event, add +1 to the counter */
    document.getElementById("btn").onclick = function slider(){
        n++;
        /* and display the corresponding image */
        document.getElementById("list").children[n].style.display="block";
        /* while deleteing the previous one */
        document.getElementById("list").children[n-1].style.display="none";
        /* if we reach the final image */
        if(n==3) {
            /* shows the final image */
            document.getElementById("list").children[3].style.display="block";
            /* and after we click on it */
            document.getElementById("btn").onclick = function slider(){
                /* deletes it to leave the space to the first one */
                document.getElementById("list").children[3].style.display="none";
                /* returning to it loading the function to start again */
                loadFirst();
            }
            return;
        }
    }
}


texts:
I'm trying to improve my algorithm to make it faster. Also might help to have a few sets of eyes for any bugs or gaps in logic I didn't catch. One thing to note: because of the nature of the algorithm, there will be periods at the beginning and end of the data that are dead zones, where a peak/valley will not be detected.

The jist of the algorithm is to step through overlapping windows of the data, do some linear regression and pick out points by standard deviation. Because of the overlapping feature we can decide how many "angles" a point needs to be detected as a peak for it to be valid. Then we go and only take the highest peak from a group of consecutive peaks.

I have highly stationary data; what I may or may not want to detect as a peak varies, and I wanted the most robust algorithm so I can use something like Bayesian optimization to set the best parameters.

This is more or less how I'd like my algorithm to function for my specific use case; I'm not really looking for feedback on that, more on whether my code translates these goals correctly and if it's the most computationally efficient way to do things.

def get_peak_valley(arr, threshold, window_size, overlap, req_angles):
    # validate params
    window_size = int(round(window_size))
    req_angles = int(round(req_angles))
    window_step = int(round(window_size * (1 - overlap)))
    if window_step == 0:
        window_step = 1
    if req_angles == 0:
        req_angles = 1

    # get all points that classify as a peak/valley
    ind = 0
    peak_inds, valley_inds = [], []

    while ind + window_size <= len(arr):
        flattened = detrend(arr[ind:ind + window_size])
        std, avg = np.std(flattened), np.mean(flattened)
        lower_b = avg - std * threshold
        upper_b = avg + std * threshold
        for idx, val in enumerate(flattened):
            if val < lower_b:
                valley_inds.append(idx + ind)
            elif val > upper_b:
                peak_inds.append(idx + ind)
        ind += window_step

    # discard points that have counts below the threshold
    peak_counts = Counter(peak_inds)
    pk_inds = [c for c in peak_counts.keys() if peak_counts[c] >= req_angles]

    valley_counts = Counter(valley_inds)
    vly_inds = [c for c in valley_counts.keys() if valley_counts[c] >= req_angles]

    # initialize iterator to find to best peak/valley for consecutive detections
    if len(pk_inds) == 0 or len(vly_inds) == 0:
        return pk_inds, vly_inds

    if pk_inds[0] < vly_inds[0]:
        curr_event = 'peak'
        best_val = arr[pk_inds[0]]
    else:
        curr_event = 'valley'
        best_val = arr[vly_inds[0]]

    #iterate through points and only carry forward the index that has the highest or lowest value from the current group
    best_ind, new_vly_inds, new_pk_inds = 0, [], []

    event_inds = sorted(pk_inds + vly_inds)

    for x in event_inds:
        if x in pk_inds:
            is_peak = True
        else:
            is_peak = False

        if is_peak and curr_event == 'valley':
            new_vly_inds.append(best_ind)
            curr_event = 'peak'
            best_val = arr[x]
            best_ind = x
            continue
        if not is_peak and curr_event == 'peak':
            new_pk_inds.append(best_ind)
            curr_event = 'valley'
            best_val = arr[x]
            best_ind = x
            continue

        if is_peak and curr_event == 'peak' and arr[x] > best_val:
            best_val = arr[x]
            best_ind = x
        elif not is_peak and curr_event == 'valley' and arr[x] < best_val:
            best_val = arr[x]
            best_ind = x

    if curr_event == 'valley':
        new_vly_inds.append(best_ind)
    if curr_event == 'peak':
        new_pk_inds.append(best_ind)

    return new_pk_inds, new_vly_inds


texts: Determine whether a magazine contains the words needed for a ransom note

texts:
This is a website Question on Hackrrank called Hash Tables: Ransom Note:
Given the words in the magazine and the words in the ransom note, print "Yes" if we can replicate the ransom note exactly using whole words from the magazine; otherwise, print "No".
Here is an example input:
6 4
give me one grand today night
give one grand today

Output: Yes
And another:
6 5
two times three is not four
two times two is four

Output: No

def checkMagazine(magazine, note):

    #Creating 2 Empty Dictionaries for the "Magazine" and the "Note" then filling them up
    UniqueWordsMag = set(magazine)
    UniqueCountMag = [0]*len(UniqueWordsMag)
    UniqueWordDictMag = dict(zip(UniqueWordsMag, UniqueCountMag))

    UniqueWordsNote= set(note)
    UniqueCountNote = [0]*len(UniqueWordsNote)
    UniqueWordDictNote = dict(zip(UniqueWordsNote, UniqueCountNote))

    for i in magazine:
        if i in list(UniqueWordDictMag.keys()):
            UniqueWordDictMag[i] += 1

    for i in note:
        if i in list(UniqueWordDictNote.keys()):
            UniqueWordDictNote[i] += 1

    #Checking for existance in the magazine then checking for the correct count, print no if it does not fulfil conditions
    Success = False
    DesiredCount = len(note)
    Count = 0

    for index,i in enumerate(UniqueWordsNote):
        if i in list(UniqueWordDictMag.keys()):
            if UniqueWordDictNote[i] <= UniqueWordDictMag[i]:
                Count += UniqueWordDictNote[i]
            else:
                break
        else:
            break

    if Count == DesiredCount:
        Success = True
        print("Yes")
    else:
        print("No")

It's called from this main program, that's provided by the challenge:

def main():
    mn = input().split()

    m = int(mn[0])

    n = int(mn[1])

    magazine = input().rstrip().split()

    note = input().rstrip().split()

    checkMagazine(magazine, note)

if __name__ == "__main__":
    main()

My code is currently taking too long on some lists (e.g. lists of size 30,000 or more).  Are there any optimisations I can make to make this a bit more legible and faster?


texts: Automatic C++ enum to string mapping macro

texts:
I have long been looking for an elegant, one-line solution to map enum to strings automatically, for use with the << and >> stream operators.

I know that a lot of macros have been proposed to achieve that, but I never found a really simple scheme, with only one macro call.

This is my attempt, and I would be interested to discuss the advantages and limitations of this approach...

Definitions:

#include <string>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>

#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)
#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)
#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)
#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)
#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)
#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)
#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)
#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)
#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)
#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)
#define MAKE_STRING10_(str) #str

#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)
#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)

#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \
    attribute std::istream& operator>>(std::istream& is, name& e) { \
        const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
        std::string str; \
        std::istream& r = is >> str; \
        const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \
        const std::vector<std::string> enumStr(name##Str, name##Str + len); \
        const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \
        if (it != enumStr.end())\
            e = name(it - enumStr.begin()); \
        else \
            throw std::runtime_error("Value \"" + str + "\" is not part of enum "#name); \
        return r; \
    }; \
    attribute std::ostream& operator<<(std::ostream& os, const name& e) { \
        const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
        return (os << name##Str[e]); \
    }

Usage:

enum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);

class Essai {
public:
    enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);

};

int main() {
    std::cout << Essai::Item1 << std::endl;

    Essai::Test ddd = Essai::Item1;
    std::cout << ddd << std::endl;

    std::istringstream strm("Item2");
    strm >> ddd;

    std::cout << (int) ddd << std::endl;
    std::cout << ddd << std::endl;
}


texts:
I'm trying to toggle a dropdown box that will appear and disappear upon clicking the button.

var clickState = false;

$("#show").on("click", function() {
  if (!clickState) {
    $(".animated").removeClass("off");
    renewElement($(".animated"));
    $(".animated").addClass("on");
    clickState = true;
  } else if (clickState) {
    $(".animated").removeClass("on");
    renewElement($(".animated"));
    $(".animated").addClass("off");
    clickState = false;
  }
});

function renewElement(e) {
  var newElement = e.clone(true);
  e.remove();
  $(".container").append(newElement);
}
.controls {
  text-align: center;
}
button {
  display: inline-block;
}
.textbox {
  width: 280px;
  margin: 0 auto;
  background: tomato;
  padding: 10px;
}
.animated {
  max-height: 0;
  overflow: hidden;
  animation-name: none;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}
.triangle {
  content: " ";
  width: 0;
  height: 0;
  border: 10px solid;
  border-color: transparent transparent tomato transparent;
  position: relative;
  left: 50%;
  top: -9px;
  margin-left: -7px;
}
.on {
  animation-name: slideOpen;
  animation-direction: normal;
}
.off {
  animation-name: slideOpen;
  animation-direction: reverse;
}
@keyframes slideOpen {
  0% {
    max-height: 0px;
    padding: 0px;
  }
  100% {
    max-height: 150px;
  }
}

  <button id="show">Show div</button>

text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

I'm using a clickState boolean to keep track of the on and off presses, creating the toggle.
I'm also cloning the entire div and recreating it so that the animation will refresh properly. It seems that without this, the animation will only run once.
The animation is connected to the element with the .addClass() method.

I'm new to animation, but I can't help but feel I'm writing some really hideous code here. For starters, the code is clearly not reusable. I would also like to know if there is a better way of repeating the animation without cloning and then appending the element.

Feel free to fork my pen on CodePen to test any changes.


texts:
I'm trying to create an API middleware which will react to every 401 response from the API. I've tried to search for possible solutions, but I'm kinda lost here.

I have created a special 401 response on server-side, which returns me a proper JSON with 401 status code and I basically process it in the middleware and always call for RECEIVE_IS_AUTHENTICATED action if such status is returned.

Small note, I understand this is nowhere near finished code, but I'm just wondering, If you guys think that terminating 401s like this is generally a good idea.

import { RECEIVE_IS_AUTHENTICATED } from '../constants/ActionTypes'

const BASE_URL = 'http://127.0.0.1:8000/'

function callApi(endpoint) {

    let config = {}

    return fetch(BASE_URL + endpoint, config)
        .then(response =>
            response.json().then(json => {
                if (!response.ok) {
                    if (response.status === 401) {
                        json.unauthorized = true;
                    }
                    return Promise.reject(json)
                }
                return json
            })
        )

}

export const CALL_API = Symbol('Call API')

export default store => next => action => {

    const callAPI = action[CALL_API]

    if (typeof callAPI === 'undefined') {
        return next(action)
    }

    let { endpoint, types } = callAPI

    const [ requestType, successType, errorType ] = types

    return callApi(endpoint).
        then(
            response => next({
                response,
                type: successType
            }),
            error => {
                if (error.unauthorized) {
                    return next({
                        type: RECEIVE_IS_AUTHENTICATED,
                        isAuthenticated: false,
                    })
                }

                return next({
                    error: error.message || 'Unknown API call error',
                    type: errorType
                })
            }
        )

}


texts: Uses subproblems to solve large problem (maximization of value within space)

texts:
If this question is not a good question for this board, I will remove it. I am looking for ideas on how I could improve the code as I am a beginner trying to learn how to program.

Here I have a program that creates a subproblem for each item that is entered into this function in order to solve a greater problem. I am currently reading a book on algorithms called Grokking Algorithms and he explained this concept and I decided to turn it into code in order to learn.

What the algo does: for each potential item that could go into a bag, it creates an array with the highest value for each amount of pounds the bag can carry. As the algo progresses to the next item, it compares current value of the next item with past maximum values at each pound value to see if it can add to the past maximum value for a given amount of pounds.

I have been programming for less than a year so forgive me if I don't seem to code very well. This is my first dive into dynamic programming.

Anyway, are there any ways that I could have improved the following code to make it more efficient? (Less lines but same type of function)

#This is the code for creating the empty backpack and then filling it with objects

def backpack_creator(size_of_backpacks, amount_of_objects):
    backpack_array = []
    for item in amount_of_objects:
        spaces = []
        for space in range(size_of_backpacks):
            spaces.append(0)
        backpack_array.append(spaces)
    return backpack_array

Backpack = {}
#first value in array is the weight in lbs, second value is actual value
Backpack["water"] = [3, 10]
Backpack["book"] = [1, 3]
Backpack["food"] = [2, 9]
Backpack["jacket"] = [2, 5]
Backpack["camera"] = [1, 6]

empty_backpack = backpack_creator(6,Backpack)
#ending of code to create empty backpack

def backpack_loader(the_items,empty_bag):#this takes the object with the items in it: the_items AND the empty backpack: empty_bag
    bag_to_be_filled = empty_bag
    items_object = the_items
    i = 0
    for item in items_object:
        j = 0
        items_weight = items_object[item][0]
        item_current_value = items_object[item][1]
        for slot in bag_to_be_filled[i]:
            lbs_available_in_slot = j + 1 #because arrays start at 0, a slot cannot be worth 0 pounds so I add one to j
            if i-1 < 0 and lbs_available_in_slot-items_weight >= 0: #if no array can be checked beforehand, take current
                bag_to_be_filled[i][j] = item_current_value
                j += 1
                continue
            elif i-1 < 0 and lbs_available_in_slot-items_weight < 0: #like first if except not enough space for current
                j += 1
                continue
            elif i-1 >= 0 and lbs_available_in_slot-items_weight <= 0: #last array can be checked but not enough space
                old_value = 0
            else:
                #the -1 after items_weight returns lbs_available_in_slot back into array slot value
                #this takes the max value that was found after deducting current weight in the last sub-array
                old_value = bag_to_be_filled[i-1][lbs_available_in_slot-items_weight-1]
            bag_to_be_filled[i][j] = max(bag_to_be_filled[i-1][j], item_current_value + old_value)
            j += 1
        i += 1
    return bag_to_be_filled

loaded_backpack = backpack_loader(Backpack,empty_backpack)
print loaded_backpack


texts: Performance of the String searching algorithm

texts:
I am trying to solve a string matching question mentioned here. I recently learned the Knuth–Morris–Pratt algorithm and tried to implement it to solve this question. But I am getting a TLE for this code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Gogl {
    static int count=0;
    public static void main(String[] args)
    {
        MyScannergogl sc=new MyScannergogl();//used own input function
        String text=sc.next();
        String pattern=sc.next();
        KMP(text,pattern);

            System.out.println(count);

    }
    static int[] computeTempArray(String pattern)
    {
        int lsp[]=new int[pattern.length()];
        int index=0;
        int i;
        for(i=1;i<pattern.length();)
        {
            if(pattern.charAt(i)==pattern.charAt(index))
            {
                lsp[i]=lsp[index]+1;
                i++;
                index++;
            }
            else
            {
                if(index!=0)
                {
                    index=lsp[i-1];
                }
                else
                {
                    lsp[i]=0;
                    i++;
                }
            }
        }
        return lsp;
    }
    public static void KMP(String text,String pat)
    {
        int lsp[]=computeTempArray(pat);
        int i=0;
        int j=0;
        while(i<text.length() )
        {

            if(text.charAt(i)==pat.charAt(j))
            {
                i++;
                j++;
            }
            else
            {
                if(j!=0)
                {
                    j=lsp[j-1];
                }
                else
                {
                    i++;
                }
            }
            if(j==pat.length())
            {
                count++;
                j=0;
            }
        }

    }

}

I couldn't understand where am I wrong. Whether I have not properly implemented the algorithm or is there some other problem I am not aware of. As I know that KNP is really fast so should have crossed the time limit.


texts: Playing sound in JavaFX when button is pressed, window pops up

texts:
So I made a class for playing a sound in JavaFX when a button is pressed, a window pops up... I don't know about the quality of the code though. I don't know if I used the best way to play the sound. It's meant to be used to play small mp3 or wav files (not longer than 5 seconds) I made it so you can adjust the volume of it (i.e. an option menu where you can adjust your notification sound menu)

Here's the code:

public class Sound {

String file;
Media sound;
MediaPlayer player;

public Sound(String file) {
    this.file = file;
    this.sound = new Media(new File(file).toURI().toString());
    this.player = new MediaPlayer(sound);
}

public void play(){
    player.play();
}

public void stop(){
    player.stop();
}

public void setVolume(double value){
    player.setVolume(value);
}

public double getVolume(){
    return player.getVolume();
}
}

//A little GUI with a button that plays a sound and a volume slider for that sound

public class MusicPane extends Pane {

String path;
Sound sound;
public MusicPane(String path) {

    this.path = path;
    this.sound  = new Sound(path);

    //if this button is pressed, it plays the sound
    Button button = new Button("play");
    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            //first stop a playing sound, then start the sound
            sound.stop();
            sound.play();
        }
    });

    //Slider to adjust the volume
    Slider slider = new Slider();
    slider.setMin(0);
    slider.setMax(1.0);
    slider.setValue(sound.getVolume());

    slider.valueProperty().addListener(new InvalidationListener() {
        @Override
        public void invalidated(Observable observable) {
            sound.setVolume(slider.getValue());
        }
    });
    this.getChildren().addAll(button, slider);
}
}


texts:
I have a simple socket.io server written in node. Everything is working just fine, however I am curious whether what I am doing is acceptable.
I am especially interested in this line

listOfMessages = listOfMessages.slice(-1000);

Essentially what I am doing is each time a new user connects, I resize the array and send the newly connected user the last 1000 messages.

I do not want to let the array grow without bounds since the server can stay running indefinitely.

var listOfMessages = [];

io.on('connection', function(socket){
  console.log('a user connected (id=' + socket.id + ').');

  // This way list of messages doesn't grow larger than 1000...
  listOfMessages = listOfMessages.slice(-1000);
  // Loop over the list of messages and send them to the new connections
  for (index = 0; index < listOfMessages.length; index++) {
      socket.emit('chat message', listOfMessages[index]);
  }

  // When we recieve a message
  socket.on('chat message', function(msg){
    console.log('message: ' + msg + ' from client (id=' + socket.id + ').');
    socket.broadcast.emit('chat message', msg);
    listOfMessages.push(msg);
  });
});

Some feedback on whether this is acceptable or good practice is what I'm looking for.


texts:
I am currently implementing this paper on generalised end to end loss: https://arxiv.org/pdf/1710.10467.pdf
A batch of N speakers and M utterances are fed to the model which outputs an embedding vector of size P for each utterance.
The first step for calculating loss is constructing a cosine similarity matrix between each embedding vector and each centroid (for all speakers). [5]
Additionally when calculating the centroid for a true speaker (embedding speaker == centroid speaker), the embedding itself is removed from the centroid calculation to prevent trivial solutions. [8]
I have attempted to do this using matrices to maximise model training performance, however it's my first time working solely with linear algebra and would really appreciate if somebody could verify that my solution is correct given the requirements above.
The code runs and produces a value, I would like to make sure this value is correct.
@tf.function
def optim_similarity(embedded,w,b, N=64, M=10, P=256):

    # Create a view of the batch with an dimension for each "class" (speaker)
    embedded_split = tf.reshape(embedded,(N,M,P))

    # Calculate false speaker centroids
    centers = tf.reduce_mean(embedded_split,axis=1)

    # Calculate true speaker centroids
    center_except = (tf.reduce_sum(tf.repeat(embedded_split,M,0),axis=1) - embedded) / M-1

    # Consruct equal shape matrices for centroids and embedding vectors
    center_matrix = tf.reshape(tf.repeat(centers,N*M),(N,N*M,P))
    embedded_matrix = tf.broadcast_to(embedded,(N,N*M,P))

    # Create a boolean mask for true speaker centroids
    mask = tf.cast(tf.reshape(tf.repeat(tf.eye(N),P*M),(N,N*M,P)),bool)

    # Construct correct center matrix
    center_matrix = tf.where(mask,center_except,center_matrix)

    # Calculate loss and scale by weights and bias
    return w*tf.keras.losses.cosine_similarity(center_matrix,embedded_matrix) + b


texts:
I'm working on an implementation of the HTTP PATCH method for WebAPI. I know there are packages like JsonPatch and OData Delta for that, but they don’t work for me. JsonPatch is too complicated and OData Delta can't work with Int32 an Guid.

When I send PATCH to the API I need mapping to model the class only, those properties that are in JSON.

Let's say I have model Person:

class Person
{
   public int Id { get; set; }
   public string Name { get; set; }
   public int? Age { get; set; }
}

The I send JSON using HTTP PATCH:

{
   "Name": "new,
   "Age":null
}

So, person should be updated: name set to "new" and age set to null. For that I created a Patch class:

public sealed class Patch<TModel> : DynamicObject where TModel : class {
    private readonly IDictionary<PropertyInfo, object> _changedProperties = new Dictionary<PropertyInfo, object>();
    public override bool TrySetMember(SetMemberBinder binder, object value) {
        var propertyInfo = typeof(TModel).GetProperty(binder.Name);
        if (propertyInfo != null) {
            _changedProperties.Add(propertyInfo, value);
        }
        return base.TrySetMember(binder, value);
    }

    public void Apply(TModel delta) {
        foreach (var property in _changedProperties) {
            object value = ChangeType(property.Value, property.Key.PropertyType);
            property.Key.SetValue(delta, value);
        }
    }

    private static object ChangeType(object value, Type type) {
        try {
            if (type == typeof(Guid)) {
                return Guid.Parse((string)value);
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
                if (value == null) {
                    return null;
                }
                type = Nullable.GetUnderlyingType(type);
            }
            return Convert.ChangeType(value, type);
        } catch {
            return null;
        }
    }
}

And use it like:

[HttpPatch]
public IEnumerable<string> Patch([FromBody] Patch<Person> person) {
    person.Apply(_person);

I need some sugestions on how it can be improved and made safer. I do not have any idea about what kind of refactoring I can use here. How can I handle, for example, IEnumerable properties?


texts:
Given two python lists a and b. These lists may intersect (It is possible that lists intersect more than once). An example:

a = [1,2,5,7,6,9,1,3,1,2,6,6,3,1,2,6,1,3]
b = [3,1,2]

There are 4 intersections:

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

For each intersection I can write equality: u + a + v == w + b + t

I need to write a function that returns lists u, v, w, t. For this example these lists are:

1. u = [3], v = []
   w = [],  t = [5, 7, 6, 9, 1, 3, 1, 2, 6, 6, 3, 1, 2, 6, 1, 3]

2. u = [],  v = []
   w = [1, 2, 5, 7, 6, 9, 1], t = [6, 6, 3, 1, 2, 6, 1, 3]

3. u = [],  v = []
   w = [1, 2, 5, 7, 6, 9, 1, 3, 1, 2, 6, 6], t = [6, 1, 3]

4. u = [], v = [1, 2]
   w = [1, 2, 5, 7, 6, 9, 1, 3, 1, 2, 6, 6, 3, 1, 2, 6, 1], t = []

The following is a function I implemented (there is precondition: len(lhs) >= len(rhs)):

def get_additions(lhs, rhs):
    results = []
    szl = len(lhs)
    szr = len(rhs)
    i = 1 - szr
    while i < szl:
        a = max(0, i)
        b = max(0, -i)
        c = min(i + szr, szl)
        d = min(szr, szl - i)

        if (lhs[a:c] == rhs[b:d]):
            u = rhs[0:b]
            v = rhs[d:szr]
            w = lhs[0:a]
            t = lhs[c:szl]
            results.append((u, v, w, t))
        i += 1
    return results

How to make it better?


texts: Handling exceptions with FileInputStream

texts:
Could you please tear my code apart? It's an exercise from CodeGym. Recently I changed a few things within my coding practices, namely:

Not writing all my solutions on main. Instead, trying to create methods to make the code more organised.
Instantiating the class on main to call the methods.
Using try with resources
Pay close attention to indentation

I have on specific question. What types of comments would you write on that code, if any.

Thanks!

/*
ABCs
The first parameter of the main method is a file name.
Count the letters of the English alphabet in the file.
Display the number of letters.
Close the streams.

Requirements:
1. You don't need to read anything from the console.
2. Create a stream to read from the file passed as the first argument of the main method.
3. You need to count the letters of the English alphabet in the file and display the number.
4. You must count both uppercase and lowercase letters.
5. The stream used to read the file must be closed.

*/

import java.io.FileInputStream;
import java.io.IOException;

public class Solution {
    private void countLetters (String args) {
        char[] array = new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

        int count = 0;
        try (FileInputStream in = new FileInputStream(String.valueOf(args))) {
            int ch;
            while ((ch = in.read()) != -1) {
                for (int i = 0; i < array.length; i++) {
                    if (ch == array[i]) {
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("General I/O exception: " + e.getMessage());
        }

        printCount(count);
    }

    private void printCount (int count) {
        System.out.println(count);
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.countLetters(args[0]);
    }
}


texts: Jquery Max character with character count for input and textarea

texts:
I have got this working ok, I just think that it can be improved and reduce the amount of code. If anybody could help that would be brilliant.

// Max Length Input
$('input[maxlength]').each(function() {
    var maxCharLength = $(this).attr("maxlength");

    if(maxCharLength < 0 || maxCharLength > 5000){
    } else {
        var charLength = $(this).val().length;
        $(this).after(" " + charLength + " of " + maxCharLength + " characters used");
        $(this).keyup(function() {
            var charLength = $(this).val().length;
            $(this).next("span").html(charLength + ' of ' + maxCharLength + ' characters used');

            if(charLength == maxCharLength ) {
                $(this).next("span").html(' Maximum of ' + maxCharLength + ' characters used.');
                $(this).next("span").addClass("red");
            } else { $(this).next("span").removeClass("red"); }
        });
    }
});

// Max Length textarea
$('textarea[maxlength]').each(function() {
    var maxCharLength = $(this).attr("maxlength");

    if(maxCharLength < 0 || maxCharLength > 5000){
    } else {
        var charLength = $(this).val().length;
        $(this).after(" " + charLength + " of " + maxCharLength + " characters used");

            $('textarea[maxlength]').keyup(function(){

                var limit = parseInt($(this).attr('maxlength'));
                var text = $(this).val();
                var chars = text.length;

                $(this).next("span").html(chars + ' of ' + limit + ' characters used');

                if(chars > limit){
                    var new_text = text.substr(0, limit);
                    $(this).val(new_text);

                    $(this).next("span").html(' Maximum of ' + limit + ' characters used.');
                    $(this).next("span").addClass("red");
                } else { $(this).find("span").removeClass("red"); }
            });
    }
});


texts:
I have to list a integers from a text file separated by newlines into a python list. I ended up with the code above which works (for my case) but certainly is far form optimal.

def readIntegers(pathToFile):

    f = open(pathToFile)
    contents = f.read()
    f.close()

    tmpStr = ""

    integers = []

    for char in contents:

        if char == '\r':
            integers.append(int(tmpStr))
            tmpStr = ""
            continue

        if char == '\n':
            continue

        tmpStr += char

    return integers

Now I have much less code, but I'm not sure for which cases split() works correctly.

def readIntegers(pathToFile):

    with open(pathToFile) as f:
        a = [int(x) for x in f.read().split()]
    return a


texts:
To practice with SFINAE, template meta programming, functional programming and monads in C++, I decided to try writing a skinny version of the two functions (monadic binding and return) that make std::optional a monad.
Here's the result:
#include <optional>
#include <utility>
#include <vector>

template<typename T, typename TD = std::decay_t<T>, typename = void>
struct is_optional : std::false_type {};

template<typename T, typename TD>
struct is_optional<
    T,
    TD,
    std::enable_if_t<std::is_same_v<TD,std::optional<typename TD::value_type>>>
    > : std::true_type {};

template<typename T>
inline constexpr bool is_optional_v = is_optional<T>::value;

template<typename T, typename F, typename = void>
struct MBind {
    inline constexpr auto operator()(T&&, F&&) const noexcept = delete;
};

template<typename T, typename F>
struct MBind<T, F, std::enable_if_t<
    is_optional_v<T> && is_optional_v<decltype(std::declval<F>()(std::declval<T>().value()))>
    >> {
    template<typename Opt = T, typename Fun = F>
    inline constexpr auto operator()(Opt&& opt, Fun&& f) const noexcept {
        return opt ? f(*std::forward<T>(opt)) : decltype(f(*std::forward<T>(opt))){};
    }
};

inline constexpr auto mbind = [](auto&& t, auto&& f) noexcept {
    return MBind<decltype(t), decltype(f)>{}(
            std::forward<decltype(t)>(t),std::forward<decltype(f)>(f)
            );
};

inline constexpr auto mreturn = [](auto&& x){
    return std::make_optional(std::forward<decltype(x)>(x));
};

int main()
{
    auto xxx1 = mbind(std::optional<int>{1}, [](auto){ return mreturn(3.3); }); // Ok
    //auto xxx2 = mbind(std::optional<int>{1}, [](auto){ return 1; });          // wrong F
    //auto xxx3 = mbind(std::vector<int>{1,2}, [](auto){ return mreturn(3); }); // wrong T
}

A few points on which I'd like to receive some feedback, beside any other comments that the code above needs.

I know I've written a meta-function is_optional_v which doesn't really enforce that T satisfies the general concept of a maybe, but requires that it is exactly a std::optional; my target was not to learn writing concepts (yet).
For invalid types I've deleted the operator() that actually does the binding, so I have no place to put any message like "this is not a `std::optional`, man"; the same hold also for the metafunction is_optional_v; actually, probably the latter, not MBind::operator(), should be responsible for issueing a compiler message about the input being not a std::optional, whereas MBind::operator() should probably be responsible for complaining about the monadic function passed in. (Probably I think this is really a matter of personal preference, as I think this is what Louis Dionne says here.)
I have tried to perfect forwarding things whenever it makes sense, but I'm not really sure I've done it the right way.
I have templated MBind and not (just) its operator() to allow me partial specialization so that I could use the SFINAE-std::enable_if idiom.
I have defaulted the template parameters of operator() to those of the class, because (as explained above) I didn't want to make everything that behaves like an optional a monad; I think I would do that via tag dispatching when I get more comfortable with this stuff.
Have I exagerated with inline and constexpr? Or, is any of those superfluous or inherently a bad idea?


texts:
This code is part of a larger code that generates an Arithmetic Quiz, although the code I have show below just saves the score that the user got on the test and their name. When saving the code it checks if the user has taken the quiz before. If the user has taken the quiz before it saves it as 'Older Score' or 'Oldest Score', however if the user has not taken the quiz before it generates a new row for them. Additionally it works out the average score and highest score for all users it has the data for. For my task I'm supposed to make the code as short as possible.

name = ""+first_name+" "+last_name
rows_data = []
class_file_names = ['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
scan = open(class_file_names[int(math_class)-1], 'r+')
rows = csv.reader(scan)
for row in rows:
    rows_data.append(row)
scan.close()
class_file_names=['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
csvfile=open(class_file_names[int(math_class)-1], 'w', newline="")
fieldnames = ['Student Name', 'Oldest Score', 'Older Score', 'Latest Score', 'Average', 'Highest']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
nameFound=False
for x in rows_data[1:]:
    if x[0] == name:
        x[3]=x[2]
        x[2]=x[1]
        x[1]=str(score)
        x[4]=(int(x[1])+int(x[2])+int(x[3]))/3
        x[5]=max(x[1],x[2],x[3])
        nameFound=True
    writer.writerow({'Student Name': x[0], 'Oldest Score': x[3], 'Older Score': x[2], 'Latest Score': x[1], 'Average': x[4], 'Highest' : x[5]})

if nameFound==False:
    writer.writerow({'Student Name': name, 'Latest Score': score, 'Older Score': '0', 'Oldest Score': '0', 'Average': score, 'Highest': score})
csvfile.close()
input("Test complete! Press anything to close.")


texts: Arranging Buttons on a Process Enumerating Application

texts:
I had the following piece of code for populating a list of currently running processes in an IT Self-Help application :

var proclist = ProcessHelper.GetProcList();

var i = 0;
var j = 0;

foreach (var process in proclist)
{
    if (process.ButtonText == "") continue;
    var button = new Button();

    if (i < 7)
    {
        button.Location = new Point(10, 30 * i + 65);
    }
    else if ((i > 6) & (i < 14))
    {
        button.Location = new Point(150, 30 * j + 65);
        j++;
    }
    else
    {
        button.Location = new Point(290, 30 * j + 65);
        j++;
    }

    i++;

    button.Click += (x, y) => button.Visible = false;
    button.Click += (x, y) => process.Kill();

    button.Text = process.ButtonText;

    button.Image = process.ThumbNail;
    button.ImageAlign = ContentAlignment.MiddleLeft;

    processTab.Controls.Add(button);

    button.Width = 130;
    button.Height = 25;
    button.TextAlign = ContentAlignment.MiddleLeft;
}

And today I realised, that if a user has more than 14 applications running, my logic falls apart on the third column and displays the items like this :

I managed to fix this with the following amendment (added a new variable for the third column) :

var proclist = ProcessHelper.GetProcList();

// For placing each button - need a var for each column
var i = 0;
var j = 0;
var k = 0;

foreach (var process in proclist)
{
    if (process.ButtonText == "") continue;
    var button = new Button();

    if (i < 7)
    {
        button.Location = new Point(10, 30 * i + 65);
    }
    else if ((i > 6) & (i < 14))
    {
        button.Location = new Point(150, 30 * j + 65);
        j++;
    }
    else
    {
        button.Location = new Point(290, 30 * k + 65);
        k++;
    }

    i++;

    button.Click += (x, y) => button.Visible = false;
    button.Click += (x, y) => process.Kill();

    button.Text = process.ButtonText;

    button.Image = process.ThumbNail;
    button.ImageAlign = ContentAlignment.MiddleLeft;

    processTab.Controls.Add(button);

    button.Width = 130;
    button.Height = 25;
    button.TextAlign = ContentAlignment.MiddleLeft;
}

And now the items appear correctly :

However, I couldn't help but think that this is not a very clean fix, because I just hard-coded in another column, and if a user every has 21 + applications open, the issue will occur again!

finally, I came up with this :

var i = 0;
var j = 0;
var column = 10;

foreach (var process in proclist)
{
    if (process.ButtonText == "") continue;
    var button = new Button();

    if ((i > 0) & ((i % 7) == 0))
    {
        j = 0;
        column = column + 140;
    }

    button.Location = new Point(column, 30 * j + 65);

    j++;
    i++;

    button.Click += (x, y) => button.Visible = false;
    button.Click += (x, y) => process.Kill();

    button.Text = process.ButtonText;

    button.Image = process.ThumbNail;
    button.ImageAlign = ContentAlignment.MiddleLeft;

    processTab.Controls.Add(button);

    button.Width = 130;
    button.Height = 25;
    button.TextAlign = ContentAlignment.MiddleLeft;
}

Which (as far as I can tell), will arrange the buttons correctly as long as there aren't so many that they go out of the window (which is highly unlikely in this environment). Here is a screenshot of the new version in action :

Hopefully this is the right place to post this - any feedback is extremely welcome!


texts:
This function generates all factors of an input n.

It begins at the square root of n, and checks numbers down to zero. When a factor x is found, then another factor must be n divided by x.

Also, if n is odd, only odd numbers need to be checked.

from math import sqrt

def factors(n):
    """
    Generates all factors of n. Iterates from sqrt(n) down to zero.
    When a factor x is found, another factor must be n divided by x.
    If n is odd, only odd numbers need to be checked.

    >>> sorted(list(factors(1001)))
    [1, 7, 11, 13, 77, 91, 143, 1001]
    """
    root = sqrt(n)
    start = int(root)  # Default starting number is sqrt(n)

    if n % 2 == 0:
        step = -1  # n is even, so check both evens and odds
    else:
        step = -2  # n is odd, so check only odds
        start = start // 2 * 2 + 1  # Round start to odd number

    if root.is_integer():
        yield int(root)  # sqrt(n) is a factor of n
        # Start at numbers < sqrt(n), so that sqrt(n) is not yielded twice
        start += step

    for x in range(start, 0, step):
        if n % x == 0:
            yield x
            yield n // x

For example,

>>> sorted(list(factors(1000)))
[1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000]

This takes 31 iterations. But when the number is odd:

>>> sorted(list(factors(1001)))
[1, 7, 11, 13, 77, 91, 143, 1001]

This takes only 16 iterations.

I'm wondering if there are other tricks that could make the process more efficient.