texts:
I am writing code to update data in the sample table (i.e. stbl) atoms of a video/audio file and found that in my method UpdateValues slows down to almost a crawl when executed. The line values.Add(value) was determined to be where the greatest time was taken through the debugger. Stepping through the program it was determined to take ~10mS to process. This List<int> is not touched by any other portion of the program. No other code appears to affect this list during the process.

public byte[] UpdateValues(int offset, string varName)
{
    //Create initial list
    List<int> values = new List<int>();
    //Set initial position to offset from (size, name, flags, count)
    int position = ((varName == "stsz") ? 20 : 16);
    //temporary byte array
    byte[] tempSize = new byte[4];

    //continue until position is equal to length of data
    while (position < this.data.Length)
    {
        //Get value from position
        Array.Copy(this.data, position, tempSize, 0, 4);

        if (BitConverter.IsLittleEndian)//Check for Endianess
            Array.Reverse(tempSize);//Reverse if necessary

        //update the value to include the new offset
        int value = BitConverter.ToInt32(tempSize, 0) + offset;

        //Add the new value to a list
        values.Add(value);//fixed from 'Values', no change in output time
        //increment the location
        position += 4;
    }

    //Sets the values back to the original location as updated
    return SetValues(values, varName);
}

The SetValues method is not slow and takes less than a second to complete:

public byte[] SetValues( List<int> values, string name )
{
    int location = 0;

    int _size = (values.Count * 4) + ((name == "stsz")? 20 : 16);
    this.data = new byte[_size];
    byte[] temp = BitConverter.GetBytes(_size);
    if (BitConverter.IsLittleEndian)
        Array.Reverse(temp);

    //add size into first 4
    Array.Copy(temp, 0, this.data, location, temp.Length);
    location += temp.Length;

    //add box type label
    temp = Encoding.ASCII.GetBytes(name);
    Array.Copy(temp, 0, this.data, location, temp.Length);
    location += temp.Length;

    //add FLAGS
    temp = new byte[(name == "stsz")? 8 : 4];//add 4 bytes of 0 flags and version
    Array.Copy(temp, 0, this.data, location, temp.Length);
    location += temp.Length;

    //add Entry Count
    temp = BitConverter.GetBytes(values.Count);
    if (BitConverter.IsLittleEndian)
        Array.Reverse(temp);
    Array.Copy(temp, 0, this.data, location, temp.Length);
    location += temp.Length;

    //Add list of offsets to total
    foreach (int a in values)
    {
        temp = BitConverter.GetBytes(a);
        if (BitConverter.IsLittleEndian)
            Array.Reverse(temp);
        Array.Copy(temp, 0, this.data, location, temp.Length);
        location += temp.Length;
    }
    return this.data;
}


texts: Monte Carlo estimation of the Hypergeometric Function

texts:
I am trying to implement the algorithm described in the paper Statistical Test for the Comparison of Samples from Mutational Spectra (Adams & Skopek, 1986) DOI: 10.1016/0022-2836(87)90669-3:

$$p = \dfrac{\prod\limits_{i=1}^{N}(R_i!)\prod\limits_{j=1}^{M}(C_j!)}{T!\prod\limits_{i=1}^{N}\prod\limits_{j=1}^{M}(X_{ij}!)}$$

The math is easy to follow in this script although very large numbers will be generated. Would using the mpmath module be my best bet for accuracy? I notice that many of my long numbers have an excessive amount of 0s possibly due to rounding errors? I want to optimize this function to generate the p-value as accurately as possible. Speed is important but not the priority. I would prefer to implement the algorithm myself although I understand there may be hypergeometric probability functions in SciPy and PyMC. I have yet to find this specific algorithm implemented in a Python module.

How can I improve the precision of the very large numbers? Would working with log computations be ideal?
Are there any module hypergeometric functions available for this specific algorithm flavor?
Am I using the decimal module appropriately?

data.dat

dsum    csum
1   0
1   2
3   9
2   1
2   1
1   0
1   0
10  0
2   3
3   0
15  0
1   28
etc.

hyperg.py

from __future__ import division   # Division is now float not integer
import numpy as np
import pandas as pd
from math import factorial as fctr
from decimal import Decimal

def factorfunc(num):
    """Returns factorial of x"""
    return Decimal(fctr(num))

def main():
    """Return the Monte Carlo Hypergeometric probability"""
    frame = pd.read_csv(r'c:\dev\hyperg\data.dat', sep='\t', header=0)

    colsum_1 = sum(frame['dsum'])
    colsum_2 = sum(frame['csum'])
    full_sum = colsum_1 + colsum_2
    length = len(frame)

    frame.index = frame.index + 1
    frame2 = pd.DataFrame(frame.apply(np.sum, axis=1)).applymap(factorfunc)
    frame3 = frame.applymap(factorfunc)

    binner = 1
    for index in xrange(length):
        binner*= frame2.iloc[index]
    numerator = long(binner) * fctr(colsum_1) * fctr(colsum_2)

    binner = 1
    for index in xrange(length):
        first, second = frame3.iloc[index]
        binner *= int(first) * int(second)
    denominator = long(binner) * fctr(full_sum)
    return numerator / denominator

if __name__ == '__main__':
    HYPERGP = main()
    print HYPERGP


texts:
As you can see from the code below, my set function accepts two types of parameters:  either strings or arrays. Now, ideally I would like to be using operator overloading to handle this, but since PHP doesn't offer anything like that I am stuck with code like this. Is there a better way to write this (or perhaps a better way to address the problem altogether)?

class View {
   // stores file passed to View
   private $template;

   // setter function for template variables
   public function set($var, $content) {
      if (is_array($var) && is_array($content)) {
         if (sizeof($var) == sizeof($content)) {
            foreach ($var as $vari) {
               foreach ($content as $contenti) {
                  $this->template = str_replace("{" . "$vari" . "}", $contenti, $this->template);
               }
            }
         }
      }
      else {
         $this->template = str_replace("{" . "$var" . "}", $content, $this->template);
      }
   }
}


texts: Function to return the sum of multiples within a range

texts:
Project Euler problem 1 says:

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

I have written a program that will return the sum of the multiples of any list of positive integers. So for example if I wanted to know the sum of every integer that was a multiple of 3 and 5 that is less than 10 I would add 3,5,6, and 9 to get 23.

My function can do this for any number of positive integers, between any range that starts from 1.

# Function to return sum of multiples that are within a certain range
def MultiplesSum(multiple, end, start=1):
    mSum = 0
    naturals = range(start, end)
    offset = -start
    if start == 0:
      raise ZeroDivisionError('Cannot start with the number 0')
    for num in multiple:
      for i in naturals:
        if i % num == 0 and naturals[i+offset] != 0:
          # print mSum,"+", i,"=",i+mSum
          mSum += i
          naturals[i+offset] = 0
        i += 1
    return mSum

problem1 = MultiplesSum([3,5,2], 16)
print problem1
# prints 88


texts:
I just picked up C++ today and I wonder if this is c++-like. I have a bit of experience with Java.

This is a program that takes a number as input and outputs its prime factorization in no particular order.

Specific questions:

Am I using std::vector correctly? With all the insert, maybe there is a better way? Similarly, am I using std::map correctly?
I've never understood what uint_32 is. I understand that it forces the compiler to make the number 32 bits instead of whatever the system decides. Do I need it here?
Is there anything that a C++ programmer wouldn't do that screams "That only happens in Java/other languages" to you?

Note that I am not worried about efficiency, although if there are improvements, those suggestions are definitely welcome.

#include <iostream>
#include <vector>
#include <map>

std::vector<int> primeFactorize(int n) {
    std::vector<int> result;
    for (int i = 2; i * i <= n; ++i) {
        if (n % i == 0) {
            auto f1 = primeFactorize(i), f2 = primeFactorize(n / i);
            result.insert(result.begin(), f1.begin(), f1.end());
            result.insert(result.begin(), f2.begin(), f2.end());
            return result;
        }
    }
    result.push_back(n);
    return result;
}

int main(int argc, char** argv) {
    int n;
    std::cin >> n;
    auto factors = primeFactorize(n);
    // Map is designed <factor, exponent>
    std::map<int, int> factorMap;
    for (int factor : factors) {
        if (factorMap.count(factor) == 0) {
            factorMap[factor] = 1;
        } else {
            ++factorMap[factor];
        }
    }
    bool isFirst = true;
    for (auto keyValuePair : factorMap) {
        if (isFirst) {
            isFirst = false;
        } else {
            std::cout << "*";
        }
        std::cout << keyValuePair.first << "^" << keyValuePair.second;
    }
    return 0;
}


texts: Blurring a given image using moving average in Python 3

texts:
I've tried solving the following HackerRank question:

  Write a function blur_image() that takes as a parameter an image in the form of a nested list A and blurs it by averaging each pixel value with four of its neighboring pixels (Top, Bottom, Right, and Left).  Note: not all of the neighbors are available in boundary cases.  You have to write suitable conditions accordingly.

My Solution:

import ast
A = input()
A = ast.literal_eval(A)

def blur_image(a):
    result = []
    for i in range(len(a)):
        row = []
        for j in range(len(a[i])):
            total, count = a[i][j], 1
            if i + 1 < len(a): total, count = total + a[i+1][j], count + 1
            if j + 1 < len(a[i]): total, count = total + a[i][j+1], count + 1
            if i - 1 > -1: total, count = total + a[i-1][j], count + 1
            if j - 1 > -1: total, count = total + a[i][j-1], count + 1
            row.append(round(total/count, 2))
        result.append(row)
    return result

print(blur_image(A))

I would appreciate any suggestions and advice you can give me to improve this solution. Please note that my focus is to solve this without using any modules.


texts: Find and select image files from webpage

texts:
For some reason, I feel like this is a bit messy and could be cleaner. Any suggestions?

I'm selecting any image files ending in .png or .jpg, and removing any image source files that contains avatar (meaning it's a header image or an avatar).

def self.images(url)
  proxy_addr = 'http://localhost:'
  proxy_port = 8080
  doc = Nokogiri::HTML(open(url), proxy: "#{proxy_addr}#{proxy_port}")
  images = doc.css('img[src$="jpg"], img[src$="png"]').select do |uri|
    uri['src'] =~ %r{^http://(\d+|media)}
  end
  images.map { |uri| uri['src'] }.reject { |uri| uri =~ /avatar/ }
end


texts:
I created a project to better understand CI3, while developing it I tried to introduce localization elements.
When I tried to localize the view everything messed up. I made a helper to identify if the user choose a language different than default language then load the right language.

function lang_load($lang_file)
{
    if($this->session->get_userdata('language'))
    {
        $this->lang->load($lang_file,$this->session->get_userdata('language'));
    }else
    {
        $this->lang->load($lang_file);
    }
}

so everytime instead use

$this->lang->load($lang_file);

I use

lang_load($lang_file)

I use it on Controllers and in the Views, but I guess it is breaking the MVC principle when used on view side.


texts: Running a given command after each change in a file

texts:
I would love to hear some comments on this small script, which (I hope) reduces repetitive tasks such as page refreshing, compilation and so on to minimum.

# -*- coding: utf-8 -*-
# Author: Jacek 'Sabr' Karolak (j.karolak@sabr.pl)
# Watch [files] for change, and after every change run given [command]
#
#
# Example watchdog script: safari.py
#  #!/usr/bin/env python
#  # -*- coding: utf-8 -*-
#
#  from loop import Loop
#
#  if __name__ == "__main__":
#      Loop(["osascript", "-e", """tell application "Safari"
#              do JavaScript "window.location.reload()" in front document
#          end tell"""]).run()
#   EOF
#
# Make safari.py executable (chmox +x safari.py) or use it with python.
# python safari.py FILES_TO_WATCH
# Whenever FILES_TO_WATCH change, refresh Safari in background :-)
#

__all__ = ["Loop"]

import argparse, subprocess
from os import getcwd, listdir, stat
from os.path import exists
from time import sleep

class Loop(object):

    def __init__(self, cmd):
        self._command = cmd
        self._files_to_watch = {}

    def _watchdog(self):
        '''Check wheter any file in self._files_to_watch changed,
        if so fire self._command'''

        check_file = lambda f: stat(f).st_mtime
        files = self._files_to_watch

        any_file_changed = False

        while True:

            # Check each file for st_mtime change (modification)
            for f in files.keys():
                actual_mtime = check_file(f)
                if not files[f] == actual_mtime:
                    any_file_changed = f
                    files[f] = actual_mtime

            if any_file_changed:
                # run command
                print('File: \'{}\' changed since last check.'\
                        .format(any_file_changed))
                any_file_changed = False
                subprocess.call(self._command)

            # sleep before next check
            sleep(0.5)

    def _set_files_to_watch(self, files):
        '''Process args files wheter they exists and include current directory
        content if requested.'''
        if '.' in files:
            files.remove('.')
            # combine all other given files with current working directory
            # content, without dot files
            files += [f for f in listdir(getcwd())\
                    if not f.startswith('.')]

        # make f list unique
        files = set(files)

        # check rights (in order to perform system stat) and wheter they exist
        for f in files:
            if not exists(f):
                msg = 'file \'{}\' does not exists, or I don\'t\
                        have access rights.'.format(f)
                raise IOError(msg)

        # save files to watch in instance variable
        self._files_to_watch = dict.fromkeys(files)

        # set modification times
        for file_key in self._files_to_watch.keys():
            self._files_to_watch[file_key] = stat(file_key).st_mtime

    def run(self):
        '''Parses command line arguments, processes files list,
        and fires watchdog.'''
        parser = argparse.ArgumentParser(description='Checkes wheter given \
                files change, when they do, runs given command.')
        parser.add_argument('files', metavar='F', type=str, nargs='+',\
                help='list files to process, if you add . in list it will\
                watch also all non dot files in current dir.\
                If you want to have all non dot files and some dot ones use:\
                \n.file1 .file2 .file2 . .file3 it will combine specified dot\
                files and all others.')

        args = parser.parse_args()

        self._set_files_to_watch(args.files)

        print('Started watching...')
        self._watchdog()

if __name__ == '__main__':
    pass


texts: "Ringing in the New Year (2011→ 2012)" puzzle

texts:
I am  trying to solve the puzzle RINGING IN THE NEW YEAR.

  Start at 2011. By moving through the maze and doing any arithmetic operations you encounter, exit the maze with a result of 2012. You may pass through an operation several times, but not twice in a row.

  2011  2012

My solution is to construct an breadth first search tree of the graph, and go through it, do the arithmetic operations.

In my windows 7 machine, it takes 29s to get the result.

How to make it better? (Improvement of algorithm or better way of compiling)

module Main where

import Data.Ratio
import Data.Tree

data Label = Label
  { f1     :: (Rational -> Rational)
  , accept :: Bool
  , f2     :: (Rational -> Rational)
  , value  :: Rational
  , disp   :: [String]
  }

initial = Node (Label (const 2011) False (const 2011) 2011 [""])
               [ Node (Label (const 2011) False (+7) 0 ["+7"]) center1
               ]

label1, label2, label3, label4 :: Label
label1 = Label (+7)         False (/2)          0 ["+7", "/2"]
label2 = Label (/2)         False (+7)          0 ["/2", "+7"]
label3 = Label (subtract 5) True  (*3)          0 ["-5", "*3"]
label4 = Label (*3)         True  (subtract 5) 0 ["*3", "-5"]

tree1, tree2, tree3, tree4 :: Tree Label
tree1 = Node label1 center2
tree2 = Node label2 center1
tree3 = Node label3 center4
tree4 = Node label4 center3

center1, center2, center3, center4 :: Forest Label
center1 = [ tree3, tree4, tree2 ]
center2 = [ tree3, tree4, tree1 ]
center3 = [ tree4, tree1, tree2 ]
center4 = [ tree3, tree1, tree2 ]

travel :: Tree Label -> [Label]
travel t = map rootLabel $
                      concat $ takeWhile (not . null) $
                      iterate (\ts -> concat $ map step ts) [t]

step :: Tree Label -> Forest Label
step (Node l sub) = map update sub
  where
    update (Node l' sub') = Node l'{ accept = (accept l') && ((f1 l') v == 2012)
                                   , value = ((f2 l').(f1 l')) v, disp = disp l ++ disp l'} sub'
    v = value l

main = (print . (\l -> concat (disp l) ++ " = " ++ show (value l))) $ head $ filter accept $ travel initial


texts: tcl script to parse C++ source code for type identifiers

texts:
Experimenting with vera++ to validate some C++ source files.
https://bitbucket.org/verateam/vera/wiki/Home

vera++ is expandable by providing your own rules in tcl. To interface with the vera++ parser the following interface is provided:
https://bitbucket.org/verateam/vera/wiki/ScriptAPI

Using the above I have written a rule to look for type identifiers and validate that they have an initial uppercase letter.

#!/usr/bin/tclsh
# Check that Type identifiers have an initial uppercase letter.

# namespace TypeName
# class TypeName
# struct TypeName
# enum TypeName {  EnumTypeName1, EnumTypeName2 }
#
# Will ignore `using clauses`
#   using <Stuff> ;
#
# Thus when "using" stuff from other namespace we don't check (as they don't belong to us)
# Also it allows you to convert any external types to local names.
#
#   #include <sys/socket.h>
#   #include <sys/types.h>
#   // STUFF
#           sockaddr_in serv_addr;
#           // STUFF
#           if (::connect(socket, reinterpret_cast<struct sockaddr*>(&serv_addr), sizeof(serv_addr)) < 0)
#                                                   ^^^^^^^^^^^^    this fails.
# But you can write it like this:
#
#           using SockAddr = struct sockaddr;   // Allowed because >using <stuff>;< is ignored.
#           if (::connect(socket, reinterpret_cast<SockAddr*>(&serv_addr), sizeof(serv_addr)) < 0)
#

set state "start"
foreach f [getSourceFileNames] {
    foreach t [getTokens $f 1 0 -1 -1 {}] {
        set tokenName [lindex $t 3]
        set checkTypeName 0
        if {$tokenName == "space"} {
            #ignore space
        } else {
            if {$state == "start" && $tokenName == "namespace"} {
                set state "CheckIdnetifier"
            } elseif {$state == "start" && $tokenName == "class"} {
                set state "CheckIdnetifier"
            } elseif {$state == "start" && $tokenName == "struct"} {
                set state "CheckIdnetifier"
            } elseif {$state == "start" && $tokenName == "using"} {
                set state "using"
            } elseif {$state == "using" && $tokenName == "semicolon"} {
                set state "start"
            } elseif {$state == "using"} {
                #ignore
            } elseif {$state == "start" && $tokenName == "enum"} {
                set state "enum"
            } elseif {$state == "enum" && $tokenName == "identifier"} {
                set checkTypeName 1
            } elseif {$state == "enum" && $tokenName == "leftbrace"} {
                set state "enumOpen"
            } elseif {$state == "enumOpen" && $tokenName == "identifier"} {
                set checkTypeName 1
            } elseif {$state == "enumOpen" && $tokenName == "comma"} {
                # ignore
            } elseif {$state == "enumOpen" && $tokenName == "rightbrace"} {
                set state "start"
            } elseif {$state == "CheckIdnetifier" && $tokenName == "identifier"} {
                set checkTypeName 1
                set state "start"
            } else {
                set state "start"
            }
        }
        if {$checkTypeName} {
            set identifier [lindex $t 0]
            set firstLetter [string index $identifier 0]
            if {[expr ! [string is upper $firstLetter]]} {
                set lineNumber [lindex $t 1]
                report $f $lineNumber "Objects >$identifier< (Type) should have an initial upper case letter"
            }
        }
    }
}


texts:
I have a function that returns rows from my database, and it works fine, but I was told that it was poorly written, and there is a lot of unnecessary code in it. I'm wondering if there is a simpler, easier way to rewrite this function.

function gd($query) {

    global $connect;
    $fetch = mysqli_query($connect, $query);
    $count = mysqli_num_rows($fetch);

    while ($row=mysqli_fetch_array($fetch,MYSQLI_NUM)) {

        $count --;
        $arrayCount = count($myArray);

        $tempArrayCount = 0;
        while($tempArrayCount < $arrayCount){
            $array[$count][$tempArrayCount]= $row[$tempArrayCount];
            $tempArrayCount++;
        } //end of while($tempArrayCount < $arrayCount)

    } //end of while ($row=mysqli_fetch_array($fetch,MYSQLI_NUM))

    return $array;

} //end of function gd($query)


texts:
I have made a method which returns a list of all songs on my device. Now I want to get a list of albums out of these songs.

What I basically do is go through every song I have in my list, check if its album is already in the list and if not I create a new album.

This method will take some time since there are 1400 songs on my device so I wondered how I can make this method any faster? Also, any other improvements?

public static ArrayList<Album> loadAlbums( Context c ){
    ArrayList<Song> tmpList = getAllSongs( c);
    ArrayList<Album> albumList = new ArrayList<Album>();

    for( Song s : tmpList ){

        boolean added = false;

        for( Album a : albumList ){

            if( a.getAlbumName().contentEquals( s.getAlbum() ) && a.getArtistName().contentEquals( s.getArtist() ) ){
                a.addSong( s.getPath() );
                added = true;
            }
        }

        if( !added ){
            Album a = new Album( s.getAlbum() );
            a.setAlbum_id( s.getAlbumId() );
            a.setArtistName( s.getArtist() );
            a.addSong( s.getPath() );

            albumList.add(a);
        }

    }

    tmpList = null;
    return albumList;
}


texts: Program that generates random IQ numbers and multiplies them by a user-entered multiplier

texts:
My code is working well and uses a lot of mechanics in C++, however, I want to know if there are any ways to make my code better, some possible problems in use. this is a simple program and I started yesterday.

What other mechanics could I implement to make the code better? And where can I find more information about those mechanics?

// IQ rand generator by ashar rahman

#include "stdafx.h"         //includes rand and other related commands
#include <stdlib.h>         //something windows wants
#include <iostream>         //allows for c++ IO interaction
#include <time.h>           //allows for srand time manipulation
#include <cstdlib>          //standard c++ libraryu

using namespace std;        //tells compiler to use std for all namespaces ex. std::cout --> cout

class IQClass{              //class containing all IQ generating, name and multiplyer selection related functions.
public:

    int y;                  //random IQ storage integer
    long int a;             //answer after  multiplyer storage integer, long for larger numerical answers
    int m;                  //multiplyer container
    char name[80];          //char array container for user name supporting upto 80 bytes

    void nameInput() {      //function including input prompt for user name
        cout << "What is your name?\n\n";       //prints 'What is your name?' with cout \n are line returns
            cin >> name;                        //allows user to input name with cin
    };

    void multiplierSelection() {        //function contains input prompt for multiplier
        cout << "\nWhat should the multiplier be?\n\n ";                    //prints
            cin >> m;                                                           //asks for input to fill m variable
    }

    void calc() {   //function contains equasion to find answer of y*m
        a = y*m;                                        //equasion
    }

    void print() {                      //function contains printing of answer, random IQ, multiplyer, and name, endl is another line return type
        cout << name << "'s IQ is probably: " << y << endl << "That times:     " << m << " is " << a << endl;
    }

    void randGen() {            //creates random sequence
        y = rand() % 160;           //out of 160 finds random value
    };

private:

};

    IQClass IC;                 //changes identifer for IQCLass ex.              IQClass.nameInput(); ---> IC.nameInput

int main()
{
     srand(time(NULL));             //generates random seed once for rand to use

     IC.nameInput();                                            //allows user to input name
     IC.multiplierSelection();                              //allows user to select multiplier

        for (int x = 0; x < 100;) {             //prints 100 random IQs for user and the answers relative to the multiplier
            IC.randGen();                               //generates random sequence
            IC.calc();                      //calculates product
            IC.print();                     //prints answer(s)
         x = x + 1 ;
     };
    return 0;           //ends program with return code of 0
}

As you can see I have annotated everything for maximum explanation and so I can review/remember it if I forget.  Are any of the comments wrong and if so, how can they be improved?


texts:
My code works for user output alignment to the right side by maximum length of 4 different user input.
I have 2 question.

Is there a simplier way for append method in my code ?
Is there a simplier way for right alignment by maximum legth of 4 different user input.

Thank You for Your Time...

"""
Main purpose of this code is alignment of the user output to the right
"""
# Take Input from User
name = input("Name: ")
surname = input("Surname: ")
age = input("Age: ")
occupation = input("Occupation: ")
person_dict = {"Name": name, "Surname": surname, "Age": age, "Occupation": occupation}

# Calculate Maximum Character Length
len_list1 = []
len_name = len(name)
len_list1.append(len_name)
len_surname = len(surname)
len_list1.append(len_surname)
len_age = len(age)
len_list1.append(len_age)
len_occupation = len(occupation)
len_list1.append(len_occupation)
a = max(len_list1)

# Output
print(f'Name:       {person_dict["Name"]:>{a}}\n'
      f'Surname:    {person_dict["Surname"]:>{a}}\n'
      f'Age:        {person_dict["Age"]:>{a}}\n'
      f'Occupation: {person_dict["Occupation"]:>{a}}'
      )


texts:
Maintain current element as the top element in the input stack. Pop all the elements on the ordered stack which are greater than the current element and push them in to the input stack and maintain a count of these elements. Now push the current element into the ordered stack and pop the count number of elements from the input stack and push them into the ordered stack and return the ordered stack.

public class sortStackInAscending {

    public static void main(String args[]) {
        Stack<Integer> inputStack = new Stack<>();
        int size = 1000;
        Random ran = new Random();
        while (size > 0) {
            inputStack.push(ran.nextInt(size));
            size--;
        }
        Stack<Integer> orderedStack = sortStack(inputStack);
        printStack(orderedStack);
    }

    public static void printStack(Stack<Integer> anyStack) {
        int size = anyStack.size();
        Stack<Integer> tempStack = new Stack<>();
        int temp;
        while (size > 0) {
            temp = anyStack.pop();
            System.out.print(temp + " ");
            tempStack.push(temp);
            size--;
        }
        System.out.println();
        anyStack = tempStack;

    }

    public static Stack<Integer> sortStack(Stack<Integer> inputStack) {
        Stack<Integer> orderedStack = new Stack<>();
        int count = 0;
        int currentElement;
        while (!inputStack.isEmpty()) {
            currentElement = inputStack.pop();
            // pop elements > current element from ordered stack and
            // push them into input stack and maintain the count
            while (!orderedStack.isEmpty()
                    && currentElement < (int) orderedStack.peek()) {
                inputStack.push(orderedStack.pop());
                count++;
            }
            // insert the current element into its correct position in ordered
            // stack
            orderedStack.push(new Integer(currentElement));
            // pop count number of elements from input stack and push them into
            // ordered stack
            while (count > 0) {
                orderedStack.push(inputStack.pop());
                count--;
            }
        }
        return orderedStack;
    }
}


texts: Drilldown navigation menu by replacing divs

texts:
I made an attempt at a menu, that comprises of just replacing
s by showing and hiding. Kind of like a drill-down technique. I have the feeling that it is extremely long-winded. Can anyone offer a cleaner technique?

$(document).ready(function () {
    $('.first').show();
    $('.second, .all, .seventh, .sixth').hide();

    $('.first').click(function () {
        $('.first, .second').hide();
        $('.second').show();
        return false;
    });
});

$('.third').click(function () {
    $('.second').hide();
    $('.all, .seventh').show();
    return false;
});

$('.forth').click(function () {
    $('.second').hide();
    $('.sixth,.eighth').show();
    return false;
});

$('.fifth').click(function () {
    $('.fifth, .sixth').hide();
    $('.second').show();
    return false;
});

$('.nineth').click(function () {
    $('.seventh, .nineth').hide();
    $('.second').show();
    return false;
});

$('.eighth').click(function () {
    $('.sixth, .fifth').hide();
    $('.second').show();
    return false;
});
table {
    text-align:center;
    width:80%;
    cursor:pointer;
}
tr {
    width:50%;
    background:red;
}

Choose a Department

Technology

Vehicles

Headphones

Watches

Back

            Engine-Powered

            Human-Powered

Back

Top


texts:
This is my Java 8 code for a console calculator. I just want to know if it can be improved in any way. Just so you know i am a real beginner just got into java about a couple of weeks ago.

    import java.util.Scanner;

public class Algorithm1 {
public static int FirstNumber, SecondNumber;
public static float TheAnswer;
public static String Action;
public static Scanner ScanInt1, ScanString;
public static boolean hasString;
public static boolean hasString2, hasInt;
public static void main(String args[]){
hasString = false;//sets up the booleans
hasString = false;
hasInt = false;
ScanInt1 = new Scanner(System.in);
ScanString = new Scanner(System.in);
System.out.println("Give your First input please.");
while  (FirstNumber < 1){
FirstNumber = ScanInt1.nextInt();
}
System.out.println("Give your Second input please.");
hasString = true;
if (SecondNumber < 1){
SecondNumber = ScanInt1.nextInt();
}
else {
System.out.println("Now * or / or + or -");
hasString2 = true;
}
Action = ScanString.nextLine();
System.out.println(Answer());
}
public static float Answer(){
//This method is for the math
    if (Action.equals("*")){
        TheAnswer = FirstNumber * SecondNumber;

    }
if (Action.equals("/")){
    TheAnswer = FirstNumber / SecondNumber;

}
if (Action.equals("+")){
    TheAnswer = FirstNumber + SecondNumber;

}
if (Action.equals("-")){
    TheAnswer = FirstNumber - SecondNumber;

}
return TheAnswer;
}

}


texts:
we are trying to implement an object pool. The objects contained are reusable but not thread safe, and creation costs a lot so we went with this idea.

We expect that the user of this object will need to wait in case the pool doesn't have an object to give.

There is a maxSize and an initialSize so that we create new objects only when needed. We still need to think of an adjusting size but for now we are fine like this.

We also expect to be predictive on the requests per second so we don't really expected that a user of this pool will wait for a long time.

Here you see the production code:

class MyObjectPool<out T>(private val factory: () -> T, private val maxPoolSize: Int = 2, initialSize: Int = 1) {
    private val queue: BlockingQueue<T> = ArrayBlockingQueue<T>(maxPoolSize, true)
    val totalCount = AtomicInteger(0)
    init {
        for (i in 0 until initialSize) {
            val element = factory()
            queue.put(element)
            totalCount.incrementAndGet()
        }
    }
    fun <D> withObject(function: (T) -> D): D {

        var nextObject: T = queue.poll()

        val currentCount = totalCount.get()
        if (nextObject == null && currentCount < maxPoolSize) {
            if (totalCount.compareAndSet(currentCount, currentCount + 1)) {
                nextObject = factory()
            }
        }
        if (nextObject == null) {
            nextObject = queue.take()
        }
        val result = function(nextObject)
        queue.put(nextObject)
        return result
    }
}

and here is the test we use to check that everything is running fine on contention:

    @Test
    fun `I can test for correctness`() {
        val threadPool = Executors.newCachedThreadPool()

        val objectPool = MyObjectPool(factory, 10, 5)

        val successCount = AtomicInteger()
        val failCount = AtomicInteger()

        val cyclicBarrier = CyclicBarrier(30 + 1)

        for (i in 1..30) {
            threadPool.execute(Runner(objectPool, cyclicBarrier, successCount, failCount))
        }

        cyclicBarrier.await()
        cyclicBarrier.await()

        assertThat(objectPool.totalCount.get(), `is`(10))
        assertThat(successCount.get(), `is`(30))
        assertThat(failCount.get(), `is`(0))
    }

    class Runner(private val objectPool: MyObjectPool<String>, private val cyclicBarrier: CyclicBarrier, private val successCount: AtomicInteger, private val failCount: AtomicInteger) : Runnable {
        override fun run() {
            cyclicBarrier.await()
            try {
                objectPool.withObject {
                    Thread.sleep(1000)
                    it
                }
                successCount.incrementAndGet()
            } catch (e:MyObjectPool.PoolExaustedException) {
                failCount.incrementAndGet()
            }

            cyclicBarrier.await()
        }
    }
}

This usage of the CyclicBarrier is basically the one used on Java Concurrency in Practice, so I think it's pretty solid, but given we don't have much work experience with the java.concurrency package, we would like a second set of eyes on it.


texts:
Given a dataframe with three columns of text blobs to search through, which can be found in this Gist.

And three keywords that I want to identify in this text:

branches_of_sci = ['bio', 'chem', 'physics']

I've written the following code to identify the presence of these keywords:

dfq_col = ['Text A', 'Text B', 'Text C']

for branch in branches_of_sci:
    for col in dfq_col:
        temp_list = []
        for row in df[col]:
            if type(row) is not str:
                temp_list.append(False)
            elif type(row) is str:
                temp_list.append(row.find(branch)>0)
        df[branch] |= temp_list

This is the result of the data I linked to:

I think the main problem here is that I'm using a for-loop when I should be using some sort of dataframe-specific function, but I'm not sure how to restructure the code to accomplish this.


texts: Comparing a selected attribute of a color with a given value

texts:
I need to call different functions depending on which enum value is used as parameter.
it's working as it should do, but I wanted to ask if there's a proper way to do this without lacking a good performance?

public enum Comparator
{
   Greater=1,Equal=0,Lower=-1
}
public enum ComparableValues
{
    R,G,B,Yellow,Violett,Turquoise,Sum,Average,Intensity
}
public override bool Process(Color cl,Comparator Comp,ComparableValues SelectedValue,float Value)
{
    if (SelectedValue == ComparableValues.R)
    {
        return Value.CompareTo(cl.R) ==(int) Comp;
    }
    if (SelectedValue == ComparableValues.G)
    {
        return Value.CompareTo(cl.G) == (int)Comp;
    }
    if (SelectedValue == ComparableValues.B)
    {
        return Value.CompareTo(cl.B) == (int)Comp;
    }
    if (SelectedValue == ComparableValues.Average)
    {
        return Value.CompareTo(cl.Average()) == (int)Comp;
    }
    return Value.CompareTo(cl.Sum()) == (int)Comp;
}

I know that it could be done by a Function table, like this:

Dictionary<Tuple<ComparableValues, Comparator>, Func<Color, float, bool>>

or by a Dictionary-in-Dictionary or a Dictionary with these ints enums merged to an int...

But obviously all these variants don't feel like they would be proper C#-state of the art stuff.


texts:
As part of a larger project I'm working on, I've made a function that aims to replicate, as best as I can, the placeholder part of the console.log() function usable in most browsers.

It replaces %s, %d , %i , %f and ,%o. It works by having 'unlimited' parameters (the replacements), looping through the parameters, checking for any placeholders and replacing them by index with the parameter given. The switch is for checking whether the passed parameter (replacement) is the correct type - if not, it will add NaN, just like the real console would.

My main questions are:

Is my code readable?
Are there any better ways to do any part of this?
Can it be cleaned up anymore?

function replacePlaceholders(string) {
    var args = Array.prototype.slice.call(arguments).splice(1); //get all the extra arguments (exclude the original string)
    var counter = 0; //set a counter

    for (var i = 0; i < args.length; i++) { //loop through the extra arguments (should match the number of placeholders in the string)
        var match = /%s|%d|%i|%f|%o/.exec(string); //regex
        if (match) { //if match found
            var index = match.index; //store the index
            switch (match[0]) { //check whether the placeholder has a real value with the correct type
                case '%s': //for strings
                    string = (typeof args[counter] == 'string') ? string.substr(0, index) + args[counter] + string.substr(index + 2) : string.substr(0, index) + NaN + string.substr(index + 2);
                    break;
                case '%d': //for numbers....
                case '%i':
                case '%f':
                    string = (typeof args[counter] == 'number') ? string.substr(0, index) + args[counter] + string.substr(index + 2) : string.substr(0, index) + NaN + string.substr(index + 2);
                    break;
                case '%o': //for objects
                    string = (typeof args[counter] == 'object') ? string.substr(0, index) + args[counter] + string.substr(index + 2) : string.substr(0, index) + NaN + string.substr(index + 2);
                    break;
            }
        }
        counter++;
    }
    return string;
}

console.log(replacePlaceholders("string %s %d %i %f %o", 'string', 1, 4, 5.5, {one: 1})); //test case

You can test this here - check the console for the returned string.


texts: Project Euler Problem 530: sum of sum of greatest common divisors

texts:
Here is a description of Project Euler problem 530:

  Every divisor \$d\$ of a number \$n\$ has a complementary divisor \$n/d\$.

  Let \$f(n)\$ be the sum of the greatest common divisor of \$d\$ and \$n/d\$ over all positive divisors \$d\$ of \$n\$, that is \$\displaystyle f(n)=\sum_{d/n}\gcd\left(d, \frac{n}{d}\right)\$.

  Let \$F\$ be the summatory function of \$f\$, that is \$\displaystyle F(k) = \sum_{n=1}^{k}f(n)\$.

  You are given that \$F(10)=32\$ and \$F(1000)=12776\$.

  Find \$F(10^{15})\$.

My solution for Euler Problem 530 is as follows:

import java.math.BigInteger;

public class problem530 {

public static void main(String[] args) {

    double start = System.nanoTime();

    BigInteger result = BigInteger.ZERO;
    BigInteger one = BigInteger.ONE;

    for (long i = 1; i <= 1000; i++){
            if ( i == 1) {
                result = result.add(one);
            }
            if (PrimeTest.testLong(i) == true) {
                result = result.add(one).add(one);
            }
            else if (i != 1 && PrimeTest.testLong(i) == false) {
                result = result.add(one);
                for(long j = 1; j*2 <= i; j++) {
                    if (i%j == 0) {
                    long sub = i / j;
                    result = result.add(BigInteger.valueOf(GCD(sub, j)));
                }
            }
        }
    }

    System.out.println(result);

    double duration = (System.nanoTime() - start)/1000000000;

    System.out.println("Your code took " + duration + " seconds to execute.");

}
}

I have PrimeTest and GCD written in libraries. The code works (it returns the correct answer for the test cases). It takes unimaginably long to get the answer for \$F(10^{15})\$ though (essentially, I won't get the answer). I'm looking for ways to optimise it.

At this link, @alan wrote something there about a sieve (presumably in C++?) which I don't quite understand. Does anyone have any ideas for optimisation?

I perform GCD operations using the Eulerian algorithm.
Prime Testing is performed for:

n = 1; n*n <= (number being tested); n++

To give an idea of how long this code takes to execute:

It ran F(10)=32 in 0.008 seconds.
It ran F(1000)=12766 in 0.019 seconds.
It ran F(100,000)=2907546 in 29.724 seconds.

This was the optimisation suggested in another post on codereview.

It seems to me that the alternative summation suggested there is wrong! F(10) would give you 22, not 32. I'm not sure how the alternative summation was derived.


texts: Checking if a sequence is almost strictly increasing

texts:
The question

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

My java solution
boolean almostIncreasingSequence(int[] sequence) {

    Integer[] arr = new Integer[sequence.length];

    for(int ctr = 0; ctr < sequence.length; ctr++) {
        arr[ctr] = Integer.valueOf(sequence[ctr]); // returns Integer value
    }
    System.out.println("Integer :: " + arr);
    List<Integer> al = new ArrayList<Integer>();

    // adding elements of array to arrayList.
    Collections.addAll(al, arr);
    System.out.println("list :: " + al);
    int save, flag = 0;
    for(int i=0; i<al.size(); i++) {
        save = al.get(i);
        al.remove(i);
        if(al.size()==1) return true;
        for(int j=0; j<al.size()-1; j++) {
            if(al.get(j+1) > al.get(j)) {
                flag = 0;
                continue;
            }
            else {
                flag = 1;
                break;
            }
        }
        if(flag == 0) {
            return true;
        }
        al.add(i,save);
    }

    if(flag == 1)
        return false;
    return true;
}

Here, I have created 2 for loops because in the first loop I'm generating the list where each index will be removed and in the second loop I'm iterating over the new list which has removed the element.
like sample array is {1,2,4,3} then in the first loop I'm creating an array which will be {2,4,3},{1,4,3},{1,2,3} and {1,2,4}. In the second loop I'm iterating over all these 4 arrays to compare each element.
The problem
For some of the test cases, it shows that it takes more than 3 seconds to execute this. But, I'm not sure where can I make a change to execute it faster. I don't have access to the test case.


texts: Removing numbering gaps in a series of filenames

texts:
I've recently started programming and have been working through some problems such as the one below:

Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap.

I was able to solve with below, but I can't imagine this being the most elegant solution - just seems very convoluted and overcomplicated. I would like to build good habits and train myself to write more efficient code - any suggestions for how can this be optimized/shortened?

#! python3
# fillGap.py - finds all files with given prefix in folder
# and locates gaps in numbering and fills the gap

import os, re, shutil

# Arguments: folder, prefix
def fillGap(folder, prefix):

    # Create regex with prefix + number + extension
    prefixRegex = re.compile(r'(%s)((\d)+)(\.[a-zA-Z0-9]+)' % prefix)

    # Make sure folder path is absolute
    folder = os.path.abspath(folder)

    # Create list with all files that match regex
    fileList = []
    for item in os.listdir(folder):
        if os.path.isfile(os.path.join(folder, item)) and prefixRegex.search(item):
            fileList.append(item)

    # Look for the starting number by incrementing, starting from 0
    Number = 0
    Completed = False
    while True:
        for filename in fileList:
            mo = prefixRegex.search(filename)
            if Number == int(mo.group(2)):
                length = len(str(mo.group(2)))
                fileList.remove(filename)
                Completed = True
                break
        Number += 1
        if Completed == True:
            break

    # Increment from starting number, finding next largest file and renaming
    nextNumber = Number
    while True:
        for filename in fileList:
            mo = prefixRegex.search(filename)
            if nextNumber == int(mo.group(2)):
                # New number including prefixed zero's
                subNumber = '0' * (length - len(str((Number)))) + str(Number)
                # New filename with updated number
                newFileName = prefixRegex.sub(r'%s%s\4' % (prefix, subNumber), filename)
                shutil.move(os.path.join(folder, filename), os.path.join(folder, newFileName))
                fileList.remove(filename)
                Number += 1
        if len(fileList) == 0:
            break
        nextNumber += 1


texts: Comparing pixels against RGB value in NumPy

texts:
Assume I created an image in NumPy:

image = imread(...)

And the image is RGB:

assert len(image.shape) == 3 and image.shape[2] == 3

I want to check (i.e. get a boolean mask) which pixels are (R=255, G=127, B=63) in a cleaner and efficient way:

mask = (img[:, :, 0] == 255) & (img[:, :, 1] == 127) & (img[:, :, 2] == 63)

This code worked for me. However - please correct me if I'm wrong - this code is creating three intermediate masks and, since I'm processing images, those masks will be pretty big.

I need help with:

Is there a way to make boolean masks occupy 1 bit per element, instead of 1 byte per element?
Is there a way to solve the same problem without creating the three intermediate boolean masks?

This code did not work:

mask = img == (255, 127, 63)

neither this:

mask = img[:, :, :] == (255, 127, 63)

since the comparison was performed element-wise, and the resulting values were performed element-wise, yielding a 3-dimension (w, h, 3) boolean mask.


texts: E-Mail Automatisation Project with smtplib but did not use MIMEMultipart

texts:
The goal of the project is to automate sending the same e-mail to a list of people with the same text (except the salutation "Dear Name of Person") with an HTML signature and a PDF attachment.

For this purpose, I have:

An Excel list with Name, E-Mail, Subject and a "sent?" field (that has to be marked once the e-mail is sent) as seen on this picture: https://imgur.com/pxYiRvx
an HTML file with the e-mail template. To avoid having too much code in the python file, I saved the HTML e-mail separately. The text was written very simple between p tags and the signature was created with the help of the following tool: https://www.hubspot.com/email-signature-generator?utm_source=create-signature
The send_email.py file, which code is shown here:

#!/usr/bin/python

import smtplib
import pandas as pd
from email.message import EmailMessage
import openpyxl

#E-Mail Credentials
EMAIL_ADDRESS = 'example@gmail.com'
EMAIL_PASSWORD = 'Password1!'
#/// ----- ///

#Read HTML E-Mail Template
with open('template.html', 'r') as f:
        html_string = f.read()
#/// ----- ///

#Load XLS Workbook for writing
file = "EmailList.xlsx"
wb = openpyxl.load_workbook(file)
ws = wb.active
#/// ----- ///

#1.1 Loading E-Mail Recipient List with Pandas for reading
email_list = pd.read_excel("EmailList.xlsx")

#1.2 Get all the Names, Email Addreses, Subjects and Messages
xls_names = email_list['Name']
xls_emails = email_list['Email']
xls_subjects = email_list['Subject']

#1.3 Loop through the emails
for index in range(len(xls_emails)):
    name = xls_names[index]
    email = xls_emails[index]
    subject = xls_subjects[index]

#1.4 Create E-Mail (loop)
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = EMAIL_ADDRESS
    msg['To'] = email
    msg.set_content(html_string.format(name=name), subtype='html')

    #Load Attachments
    files = ['halle.pdf']

    for file in files:
        with open(file, 'rb') as f:
            file_data = f.read()
            file_name = f.name

        msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

    #try to send mail
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

        try:
            smtp.send_message(msg)
            print('\n Email to {} successfully sent!\n'.format(email))

            #loop for check feedback in XLS
            for column in ws.iter_cols(1):
                for cell in column:
                    if cell.value == email:
                        ws.cell(row=cell.row, column=4).value = 'check!'
                        wb.save("EmailList.xlsx")

        except Exception as e:
            print('\n\n Email to {} could not be sent :( because {}'.format(email, str(e)))

The questions I have are:

Is the code ok?
Do I need to have a plain text alternative for the
HTML e-mail? Or is this overrated?
I saw many many posts importing and using MIMEMultipart, MIMETextimport, MIMEBase****t and what not. I did not use it, but of course I am wondering if I have something
wrong?


texts:
Is this an efficient way to handle page requests in MVC?

index.php:

require 'Classes/Autoloader.php';
Autoloader::start();
Session::start();

new Bootstrap();

Bootstrap.php

class Bootstrap {
    private $controller = null,
            $action = null,
            $args = null;

    public function __construct() {
        $this->manage_url();
        if($this->page_exist()){
            $this->request();
        } else {
            $error = new ErrorController();
            $error->error404();
        }
    }

    private function request(){
        $controller = new $this->controller();
        if(!$this->args){ $controller->{$this->action}(); }
        else{
           $count_args = count($this->args);
           switch ($count_args) {
               case 1:
                   $controller->{$this->action}($this->args[0]);
                   break;
               case 2:
                   $controller->{$this->action}($this->args[0], $this->args[1]);
                   break;
               case 3:
                   $controller->{$this->action}($this->args[0], $this->args[1], $this->args[2]);
                   break;
               case 4:
                   $controller->{$this->action}($this->args[0], $this->args[1], $this->args[2], $this->args[3]);
                   break;
           }
        }
    }

    /**
     * Get controller, action and parametes
     */
    private function manage_url(){
        $uri = $_SERVER['REQUEST_URI'];
        $uri = trim($uri, '/');
        $this->remove_query_or_hash($uri);
        $exploded_uri = explode('/', $uri);
        $this->controller = Util::istruthy_or($exploded_uri[0], 'Main').'Controller';
        $this->action = Util::istruthy_or($exploded_uri[1], 'index');
        $this->args = array_slice($exploded_uri, 2);
    }

    private function remove_query_or_hash(&$uri){
        $query = strpos($uri, '?');
        $hash = strpos($uri, '#');
        if($query!==FALSE||$hash!==FALSE){
            $idx =  $query < $hash ? $hash : $query;
            $uri = substr($uri, 0, $idx);
        }
    }

    private function page_exist(){
        $controller = class_exists($this->controller);
        $method = method_exists($this->controller, $this->action);
        if(!$controller||!$method){
            return FALSE;
        }
        return TRUE;
    }
}

Util istruthy_or():

public static function istruthy_or(&$var, $val = NULL){
    return isset($val) ? ($var ? $var : $val) : ($var ? $var : NULL);
}


texts: Optimize narrow phase contact detection for phyiscs simulation code

texts:
I'm trying to optimize the narrow phase of the contact detection in my code. I'm using OpenMP for multithreading.
That is the starting code:
// Narrow Phase
        const unsigned int NbPairs = pair_manager_->get_n_pairs();
        delete[] sum_rad_;
        sum_rad_ = new double[NbPairs];
        delete[] distance_vector_;
        distance_vector_ = new Vector3d[NbPairs];
        delete[] sq_dist_;
        sq_dist_ = new double[NbPairs];
        const Pair * Pairs = pair_manager_->get_pairs();
        int n_active = 0;
        auto * active = new bool[NbPairs];
#pragma omp parallel default(none) shared(active, Pairs, n_active) firstprivate(NbPairs) num_threads(current_num_threads_)
        {
#pragma omp for schedule(static)
            for (int i = 0; i<NbPairs; i++) {
                const int id_0 = Pairs[i].id_0_;
                const int id_1 = Pairs[i].id_1_;
                sum_rad_[i] = radius_[id_0]+radius_[id_1];
                distance_vector_[i] = position_[id_1]-position_[id_0];
                sq_dist_[i] = distance_vector_[i].squaredNorm();
            }
            Pair * PairsNonConst = pair_manager_->get_pairs_non_const();
#pragma omp for schedule(static) reduction(+:n_active)
            for (int i = 0; i<NbPairs; i++) {
                if (sq_dist_[i]<sum_rad_[i]*sum_rad_[i]) {
                    active[i] = true;
                    n_active++;
                } else {
                    PairsNonConst[i].data_id = -1;
                    active[i] = false;
                }
            }
        }
        delete[] active_pairs_;
        active_pairs_ = new int[n_active];
        n_active_pairs_ = n_active;
        int j = 0;
        // FIXME: is it possible to include it in the parallel loop? -> I guess so, then do merge reduction
        for (int i = 0; i<NbPairs; i++) {
            if (active[i]) {
                active_pairs_[j] = i;
                j++;
            }
        }
        assert(j==n_active_pairs_);
        delete[] active;

The pair manager contains the candidate contact pairs, which has to be checked in the narrow phase. I only have spherical objects, so this is fairly easy (if squared sum of radii is larger than the squared distance of the objects, then we have a contact).
In a previous developing phase, I splitted the two for loops to get performance benefits, so that the first one does not contain any if statement. So, in the first one I calculate all the relevant quantities for all contact candidates, in the second one I have to check every candidate for actual contact.
After that, I have to loop over the active array and save the indexes of each active contact pair. In another part of the code, I'll then loop over this array active_pairs_ and calculate the contact forces, i.e. by indirectly accessing sq_dist_ and distance_vector_ in this way:
#pragma omp for schedule(static)
for (int i=0; i<n_active_pairs_; i++) {
   int id_pair = active_pairs_[i];
   const Vector3d distance = distance_vector_[id_pair];
   // ...
}

Ideally, I would like to save only the quantities for the actual contact pairs in sum_rad_, distance_vector_, and sq_dist_ so that in this for loop I can only loop over those arrays.
Also, this would save me the last serial loop in the narrow phase. On the other hand it would mean merging the two loops in the parallel region (unless someone has a better idea on how to do that).
Last but not least, with my approach, I cannot have a proper first touch (important on NUMA systems). It would be nice to get this somehow as well.
What are your thoughts?


texts: Javascript map/filter/reduce over facebook messenger data

texts:
Context: I am making a website that allows people to upload their Facebook Messenger data, and see data visualizations for conversations. It is a React front-end, and a nodejs back-end. It doesn't store anything in a database at the moment, but there is a caching layer to deal with different sessions. So once the user uploads their facebook messenger data, the nodejs back-end is supposed to crunch the numbers and aggregate different statistics.

The json looks like:

{
  "participants": [{"name":"Adam"}, {"name":"Bob"}, {"name":"Chris"}],
  "messages": [
    {
      "sender_name": "Adam",
      "timestamp_ms": 1533332999910,
      "content": "I am editing my stackexchange question right now",
      "type": "Generic"
    },
    {
      "sender_name": "Bob",
      "timestamp_ms": 1533332999910,
      "content": "Okay, good luck",
      "type": "Generic"
    }
  ],
  "title": "High School Friends",
  "is_still_participant": true,
  "thread_type": "RegularGroup",
  "thread_path": "inbox/highschoolfriends__aAe4vb"
}

messages is an array of objects, with common text messages having the shape of the above, with other fields that are optional like photos, audio_files, etc.

To compute the set up the data I use:

let jsonMessages = require('../analytics/message_1.json');

let participants = jsonMessages.participants;
let messages = jsonMessages.messages;

let people =  participants.map(function(person) {
    return person.name;
});

So now the data is a javascript object.

So my question: Am I missing something obvious about the map/filter/reduce powers by doing a big for loop of filters? Would this pass code review for an internal analytics tool?

Here is what I have tried:

let people = ['Adam', 'Bob', 'Chris', 'Dave'];

people.forEach(function (person) {
    let obj = {};
    obj.name = person;
    obj.messageCount = messages.filter((obj) => obj.sender_name === person).length;

    obj.photoMessageCount = messages.filter((obj) => ((obj.sender_name === person) && ((obj.photos != null) )).length;

    obj.videoGifMessageCount = messages.filter((obj) => ((obj.sender_name === person) && ((obj.gifs !=null) || (obj.videos!= null))).length;

    obj.audioMessageCount = messages.filter((obj) => ((obj.sender_name === person) && (obj.audio_files != null))).length;

    obj.richContentMessageCount = obj.photoMessageCount + obj.videoGifMessageCount + obj.audioMessageCount;

    stats.push(obj);
});


texts:
I'm trying to improve my programming skills (not just using one language). I don't have a group of other programmers to bounce ideas off other than on the web - so please forgive me if I have posted this in the wrong place.

I'd like to improve my coding in this example. Here's my Python sketch that takes a number and converts it to either Fahrenheit or Celsius. It takes a number to convert with checks in place in the calc function, incase no text is entered (I could also check whether the values entered are computable but I've not done this). It uses type casting to convert the text entry string to an int and if you tick the checkbox it will calculate Fahrenheit. It uses one class to define the whole GUI layout as this could be a sub window in a larger GUI i.e. this could be a class among three or more as part of a larger GUI.

I'd appreciate your feedback about the code and what could be done to make it more efficient e.g. layout, code structure and general feedback. I'd appreciate it.

from Tkinter import Tk, Label, Button, Checkbutton, Entry, W,LEFT, RIGHT, CENTER
import Tkinter as tk

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("Celsius <-> Farenheit")

        self.var = tk.IntVar()

        self.label = Label(master, anchor=CENTER, text="Temperature Conversion")
        self.label.grid(columnspan=3, rowspan=2, sticky=W)

        #self.labelInput = Label(master, text="Enter temperature", borderwidth=2, relief="solid")
        #self.labelInput.grid(row=2, column=1)

        self.textEntry = Entry(master, text="enter temperature")
        self.textEntry.grid(row=2, column=1)

        self.calculate_button = Button(master, text="Convert", command=self.calc)
        self.calculate_button.grid(row=2, column=2)
        #self.labelInput.pack(side=LEFT)

        self.converstion_type = Checkbutton(master, text="Farenheit",  variable=var)
        self.converstion_type.grid(row=3, column=1)
        #self.labelInput.pack(side=RIGHT)

        self.output = Label(master, text="...")
        self.output.grid(row=3, column=3)

        self.outputInput = Label(master, text="Converted Temperature", borderwidth=2, relief="solid")
        #self.outputInput.grid(row=1, column=2)
        #self.outputInput.pack(side=RIGHT)

    def calc(self):
        entry = self.textEntry.get()
        if(entry != "" and var.get()==False):
            #convert celsius to celsius
            val =  5*(int(entry)-32)/9
            self.output.config(text=str(val))

        elif(entry != "" and var.get()==True):
            #convert celsius to farenheit
            val =  9*(int(entry)/5) + 32
            self.output.config(text=str(val))

root = Tk()
var = tk.IntVar()
my_gui = MyFirstGUI(root)
root.mainloop()


texts: Functional testing issue - Feels like one long test

texts:
I'm using Selenium to test a PHP site that goes through the following process:

Register user
Log in
Fill out Form 1 and submit
Fill out Form 2 and submit
Fill out Form 3 and submit
(tear down) Delete user

A real user would go through these steps in this order.

I've read in places that tests should be bite-sized, and to avoid asserting a lot of things in each test. So I've written my tests like this:

function testRegister() {
    //...
}

/**
 * @depends testRegister
 */
function testLogin() {
    //...
}

/**
 * @depends testLogin
 */
function testFillForm1() {
    //...
}

/**
 * @depends testFillForm1
 */
function testFillForm2() {
    //...
}

/**
 * @depends testFillForm2
 */
function testFillForm3() {
    //...
}

This way my tests execute in the correct order.

However, splitting up my tests is merely cosmetic. Since each test is dependent on the success of the previous one, it may as well be one long test.

It also causes another problem. If testFillForm2 fails, I have no way of re-running the test on its own, I have to wait for all the other tests to complete each time because of the dependencies.

Is there a better approach I can take?


texts: Helper to convert arbitrary function into a custom deleter

texts:
If you want to use a custom deleter in unique_ptr you either have to pass a functor or the signature of a delete function as template argument. If you have a freestanding delete function (often from a C API) you have to pass the actual address of the function to every instance of your unique_ptr. To avoid that I created a little template that converts a freestanding delete function into a functor.

template<auto* FN>
struct Deleter;

template<typename Ptr, void(*FN)(Ptr*)>
struct Deleter<FN>
{
    void operator()(Ptr* ptr)
    {
        FN(ptr);
    }
};

Usage:

#include <memory>

// Delete function
void delete_float(const float* ptr)
{
    delete ptr;
}

int main()
{
    // How you normally specify a deleter
    std::unique_ptr<float, decltype(&delete_float)> float_ptr1(new float(3.141), &delete_float);

    // With the helper template
    std::unique_ptr<float, Deleter<&delete_float>> float_ptr2(new float(3.141));
}


texts: Counting the proportion of vowels in substrings

texts:
I'm looking for an algorithm to make my code faster and better for big strings.

Problem link

Let the simple prettiness of a string be the count of vowels (I, E, A, O, U, Y) divided by the length of the string.  Find the sum of the simple prettiness of all substrings of a given string (with precision within 1 part per million), where the input string may be up to 5∙105.

Let's say I have the following input:

IEAIAIO

The output should be like this:

28.000000

Second ex:

BYOB
5.833333

Third ex:

YISVOWEL
17.050000

My solution gives me Time Limited Exceeded on big strings.

#include <bits/stdc++.h>
using namespace std;
int main()
{

    string s;
    while (cin>>s)
    {

        long double sum=0.0;

        for (int i = 0; i < s.length(); i++)
        {
            for (int j = i+1; j <= s.length(); j++)
            {
                string ss=s.substr(i,j-i);
                //<<ss<<endl;
                long double len=0.0;
                for (int r = 0; r < ss.length(); r++)
                {
                    if(ss[r]=='I' || ss[r]=='E' || ss[r]=='A' || ss[r]=='O' || ss[r]=='U' || ss[r]=='Y' )
                        len++;
                }
                //cout<<"len = "<<len<<"\tss= "<<ss<<endl;
                long double len_ss=ss.length();
                sum+=(len/len_ss);
            }
        }
        cout<<fixed;
        cout << std::setprecision(6) << sum<<endl;

    }
return 0;

}


texts:
I wrote this function to be passed as a param in spl_autoload_register(). It autoloads PHP classes from their respective directories using their namespace, named the same as path. I am not sure if there would be any easier way but this is quite simple and does what it needs to.

spl_autoload_register(function($class) {
    $ns = explode('\\', strtolower($class));
    $class = array_pop($ns);
    $ns = implode('\\', $ns) . '\\';
    require_once __DIR__ . '\\' .  $ns . 'class.' . $class . '.php';
});

Thoughts on this? Is there an easier way?


texts: Creating user accounts as an administrative user

texts:
I have a site where user accounts can be created in two ways: by new users (sign up) and by admin users. Since the creation is handled differently in each case, I decided to split the logic into two separate functions. I have a working implementation but I'm pretty new to Rails so I don't know if it is robust and secure. I am looking for feedback on how to improve it.

users_controller.rb

before_action :signed_in_user, only: [:home, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: [:create_by_admin, :destroy]

.
.
.

def new
    if !signed_in?
        @user = User.new
        @user.confirmation_code = User.new_confirmation_code
    elsif signed_in? && current_user.admin?
        @user = User.new
        render 'new_by_admin' # basically a new.html.erb but with a dropdown for the admin setting
    else
        redirect_to root_url
    end
end

def create
    if signed_in? && !current_user.admin?
        redirect_to root_url
    elsif signed_in? && current_user.admin?
        create_by_admin
    else
        create_by_user
    end
end

def create_by_user
    @user = User.new(user_params)
    if @user.save
        UserMailer.confirmation_email(@user).deliver
        flash[:success] = "Great! Now check your email for activation instructions."
        redirect_to root_url
    else
        render 'new'
    end
end

def create_by_admin
    @user = User.new(admin_params)
    if @user.save
        @user.update_attributes(confirmed: true)
        flash[:success] = "User for " + @user.name + " created."
        redirect_to users_path
    else
        render 'new_by_admin'
    end
end

.
.
.

private
    def user_params
        params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end

    def admin_params
        params.require(:user).permit(:name, :email, :password, :password_confirmation, :admin)
    end

Essentially, all create requests are routed to the create action, and from there sent to the appropriate method (depending on whether the requesting user is a new user or an existing user who is an admin). The differences between the methods is that new users receive an email to activate their accounts upon signup and cannot set themselves as admin, whereas admin users create accounts that are already confirmed and can set them as admin.

Is this a silly way to do it? Should I create an admin_controller that handles all administrative requests?


texts:
This is my solution for a Hackerrank problem. The problem was:

  There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube_i is on top of cube_j then sideLength_j >= sideLength_i.

  When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time. Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks.

  Input Format

  The first line contains a single integer T, the number of test cases.
  For each test case, there are 2 lines.
  The first line of each test case contains , the number of cubes.
  The second line contains space separated integers, denoting the sideLengths of each cube in that order.

  Constraints

1 <= T <= 5
1 <= n <= 10**5
1 <= sideLength <= 2**31

  Output Format

  For each test case, output a single line containing either "Yes" or "No" without the quotes.

  Sample Input

2
6
4 3 2 1 3 4
3
1 3 2

  Sample Output

Yes
No

  Explanation

  In the first test case, pick in this order: left - 4, right - 4, left - 3, right - 3, left - 2, right - 1.
  In the second test case, no order gives an appropriate arrangement of vertical cubes. 3 will always come after either 1 or 2.

My code is actually rather short:

if __name__ == '__main__':
    num_tests = int(input().strip())

    for _ in range(num_tests):
        num_cubes = int(input().strip())
        cube_sidelengths = list(map(int, map(str.strip, input().strip().split())))

        i, j = 0, len(cube_sidelengths)-1
        pile = []

        while i != j:
            left, right = cube_sidelengths[i], cube_sidelengths[j]
            # In case there is nothing in the pile just add the bigger one
            if not pile:
                if left > right:
                    pile.append(left)
                    i += 1
                else:
                    pile.append(right)
                    j -= 1
            else:
                # Take the bigger of the left and right element and compare it
                # to the last item on the pile. If it's bigger we can't pile
                # it up, otherwise put it on the pile and continue
                if left > right:
                    if left > pile[-1]:
                        print('No')
                        break
                    else:
                        pile.append(left)
                        i += 1
                else:
                    if right > pile[-1]:
                        print('No')
                        break
                    else:
                        pile.append(right)
                        j -= 1
        else:
            print('Yes')

But I'm actually not very satisfied with the code. It passes all Hackerrank tests but I can't help feeling that it's missing something - but I can't put my finger on it.

An additional thing that has been bugging me was that it was part of the  "Python collections" problems but I haven't used anything from the collections module. It would be possible to use a deque here but that felt like overkill - because pop and popLeft are O(1) but just keeping the indices and accessing a list is also O(1) so it wouldn't even provide better asymptotic behaviour. So as additional question: Is there anything that could be improved by using a deque?

Otherwise I would be very glad about any feedback how I could improve the code.


texts: Git pre-commit hook to check that changes to certain files only happen on the master branch

texts:
As a beginner in Ruby, I am trying to optimize this script that is a client side pre-commit hook for git.

Was hoping I could get a review to ensure I am following all ruby idioms, and to ensure I have the most elegant solution.

#!/usr/bin/env ruby
#
# Pre-commit hook created to help ensure dns changes are being
# committed to the correct branch.
#

# Hash of zone files to look for when a commit is attempted.
zone_files = {
  development: ‘some_zone_file1’,
  prod: ‘some_zone_file2’
}

# Execute git diff to determine files includes as part of commit.
out_data = %x{git diff --cached --name-only}
pri_branch = "master"

# Iterate through the zone files, and check if any are found in the output.
# Only one needs to be found. No need to find all.
zone_files.keys.each do |key|
  if out_data.include?zone_files[key]
    current_branch = %x{git branch}.match(/\* (.+?)\n/m)
    if current_branch[1].include?pri_branch
      break
    else
      puts "Warning: You have triggered a git pre-commit hook."
      puts "Warning: Your current branch is: #{current_branch[1]}."
      puts "Warning: For dns, ensure you commit on branch: #{pri_branch}"
      puts "Warning: Include '-n' to bypass this check."
      puts "Exiting..."
      exit 1
    end
  end
end


texts: Ask for stream of character input and print number of uppercase/lowercase characters

texts:
Does this code look okay?

#include <stdio.h>
#include <ctype.h>

int case_letters();

int main(void)

{
    case_letters();
    return 0;
}

int case_letters()

{
    int ch;
    int numOfUpper = 0;
    int numOfLower = 0;

    printf("please enter a some characters, and ctrl + d to see result\n");

    while ((ch = getchar()) != EOF)
    {
        if (isdigit(ch))
        {
            printf("please enter a valid character\n");
            continue;
        }

        else if (isupper(ch))
        {
            numOfUpper++;
        }

        else if (islower(ch))
        {
            numOfLower++;
        }
    }

    return  printf("There are %d Uppercase letters, and %d Lowercase letters\n", numOfUpper, numOfLower);
}


texts:
I am working on projecteuler # 14, http://projecteuler.net/problem=14 and my code takes too long to run. Any tips, or hints for a beginner?

Code:

////////////////////////
/// ProjectEuler # 14///
////////////////////////

#include <iostream>
#include <tuple>           //New, shaky on tuple
using namespace std;

bool tester(int n)      //Even number tester//It works 100%
{
    bool result = false;
    if (n%2 == 0) result = true;
    return result;
}

int collatz_counter (int collatz_number)    //Collatz sequence counter//It works 100%
{
    int j = collatz_number;
    int total = 0;
    do
    {
        if (tester(j))
        {
            j /=2;
            total ++;
        }
        else
        {
            j = 3*j +1;
            total ++;
        }
    }while (j!=1);
    total +=1;          // To account for the original number itself
    return total;
}

pair <int n, int m> value_finder (int n)
{
    int max = 0;
    int max_number = 0;
    for (int i = n; i>1; i--)
    {
        if(collatz_counter(i) > max)
        {
            max_number = i;
            max = collatz_counter(i);
        }
    }
    max_number++;
    return{max, max_number};
}

int main (void)
{
    int starter;
    int x;
    cout<<"Enter value :"<<endl;
    cin>>starter;
    cout<<endl;
    int Max = 0;
    int Max_Number = 0;
    for (x = starter; x>= starter/2 ; x--)
    {
        int m, n;
        tie(m, n) = value_finder(x);
        if ( m> Max)
        {
            Max_Number = n;
            Max = m;
        }
    }

    cout<<" The maximum numbers in the collatz sequence is "<<m<<endl;
    cout<<" The starting number of the collatz sequence is "<<n<<endl;
    system ("pause");
    return 0;
}


texts: Determining the similarity between two documents

texts:
I've made some code that reads in text files (which hold quite large vectors of word frequencies), which in turn stores each index of a vector within an ArrayList for their specified team (i.e. Arsenal vector to the Arsenal ArrayList, Chelsea vector the Chelsea ArrayList, etc.). It then uses a cosine similarity function to determine similarity between the two documents and writes it to a file.

What I would like is to make the code that reads in the text files (and storing them in their corresponding ArrayList more efficient), rather than me change the parameters of the while loop each time i need to use it.

public static Double cosineSimilarity(ArrayList<Integer> vectorOne, ArrayList<Integer> vectorTwo) {

    Double dotProduct = 0.0;
    Double normVecA = 0.0;
    Double normVecB = 0.0;
    for(int i = 0; i < vectorOne.size(); i++) {
        dotProduct += vectorOne.get(i) * vectorTwo.get(i);
        normVecA += Math.pow(vectorOne.get(i), 2);
        normVecB += Math.pow(vectorTwo.get(i), 2);
    }

    return dotProduct / (Math.sqrt(normVecA) * Math.sqrt(normVecB));

}

public static void main(String[] args) throws IOException {

    ArrayList<Integer> arsenal = new ArrayList<Integer>();
    ArrayList<Integer> chelsea = new ArrayList<Integer>();
    ArrayList<Integer> liverpool = new ArrayList<Integer>();
    ArrayList<Integer> manchesterCity = new ArrayList<Integer>();
    ArrayList<Integer> manchesterUnited = new ArrayList<Integer>();
    ArrayList<Integer> tottenham = new ArrayList<Integer>();

    Scanner textFile = new Scanner(new File("Enter textfile  here"));

    while (textFile.hasNext()) {
        arsenal.add(textFile.nextInt());
   }

    Double output = cosineSimilarity(arsenal, chelsea);

    File fileName;
    FileWriter fw;

    // Create a new textfile for listOfWords
    fileName = new File("arsenalCosineSimilarities.txt");
    fw = new FileWriter(fileName, true);

    fw.write(String.valueOf("Chelsea: " + output + "\n"));

    fw.close();
}


texts: Using Scrapy/Xpath to scrape ESPN for football (soccer) commentaries

texts:
The class takes an input of a game-id from the ESPN soccer website. The code then has to grab the commentary, process that and also grab the player names/ids and create a small dictionary of those.

I understand the premise of OOP when shown in basic examples but I cannot get my head around using it in actual programs/applications. I have tried here, but to me it seems to not achieve anything extra (so I must be doing it wrong).

I end up with a list of lists containing each of the key events (corners, shots etc) and a dictionary of players, so it works.  But it just seems so inelegant and I would love some tips on improving it (however small/focused they are).

import urllib2
from scrapy.selector import HtmlXPathSelector
import re
import codecs
import timeit
start = timeit.default_timer()

class game:
    def __init__(self,game_id):
        self.game_id = game_id
        self.comms_url = 'http://espnfc.com/uk/en/gamecast/%d/gamecast.html?soccernet=true&cc=5739' % self.game_id
        self.data_text = urllib2.urlopen(self.comms_url).read()
        self.corners = []
        self.shots = []
        self.fouls = []
        self.shots_on_target = []
        self.offsides = []
        self.goals = []
        self.extractCommentaries()
        self.extractPlayers()
        self.extractTeams()
        self.findAction('^Corner', self.corners)
        self.findAction('^Foul by', self.fouls)
        self.findAction('^Attempt', self.shots)
        self.findAction('^Attempt saved', self.shots_on_target)
        self.findAction('^Offside', self.offsides)
        self.findAction('^Goal!', self.goals)
    def extractCommentaries(self):
        self.hxs = HtmlXPathSelector(text=self.data_text)
        self.match_comments = self.hxs.select("//div[@id='convo-window']/ul[@id='convo-list']/li/div[@class='comment']/p/text()")
        self.match_timestamps = self.hxs.select("//div[@id='convo-window']/ul[@id='convo-list']/li/div[@class='timestamp']/p/text()")
        self.events = zip(self.match_timestamps.extract(), self.match_comments.extract())
        self.cleanclean = []
        for time,event in self.events:
            time = re.search('\d+', time)
            if time:
                time = time.group()
                time = int(time)
                self.cleanclean.append((time,event))
        self.dumdum = range(len(self.events))
        self.clean_events = {}
        for key, event in enumerate(self.cleanclean):
            self.clean_events[key] = event
    def extractPlayers(self):
        self.player_names = self.hxs.select("//table[@class='stat-table']/tbody//a/text()")
        self.player_urls = self.hxs.select("//table[@class='stat-table']/tbody//a/@href")
        self.player_ids = []
        for url in self.player_urls.extract():
            digit = []
            for s in url:
                if s.isdigit():
                    digit.append(s)
            self.placeholder = ''.join(digit)
            self.placeholder = int(self.placeholder)
            self.player_ids.append(self.placeholder)
        self.players = dict(zip(self.player_ids, self.player_names.extract()))
    def extractTeams(self):
        self.dummy = ['home','away']
        self.zero = [0,0]
        self.team_names = self.hxs.select("//li[@class='country']/h2/text()")
        self.teams = dict(zip(self.dummy,self.team_names.extract()))
    def findAction(self, keyword, storage):
        for key, value in self.clean_events.iteritems():
            action = re.search(keyword, value[1])
            if action:
                for ha, team in self.teams.iteritems():
                    if keyword == '^Goal!':
                        split_up_action = value[1].split('.')
                        found = re.search(team, split_up_action[1])
                    else:
                        found = re.search(team, value[1])
                    if found:
                        temp_holder = [value[0], team, self.game_id]
                        storage.append(temp_holder)

a = game()
stop = timeit.default_timer()

print stop - start


texts: Code for checking several conditions for the below json transformation

texts:
A json i have provided which is actually i am getting by hitting a Rest Service.
To keep it simple I have provided that directly inside the method.
A modal with textarea and accepr/Reject button has been given.

Input Json:{
  "Reference No":"101",
  "Date Of Reporting":"2019/04/29",
  "Status":"",
  "Comments":"",
  "Organization Name":"ABC"
  }

Conditons:
1.Set the data entered in the textarea value to "Comments"  in json.
2.Transform the date format to 2019-04-29 and set it to "Date Of Reporting" by comaparing key name contains "date" .
3.set the status value as A or R based on the onclick button value passed to the method below.
4.Keep all other json data as same.

I have provided the code I have done and it is working fine.

Can anyone help me with some better optimal solutions?

function tansformJson(btn){

var jsonStr={
  "Reference No":"101",
  "Date Of Reporting":"2019/04/29",
  "Status":"",
  "Comments":"",
  "Organization Name":"ABC"
  }

var jsonData = {};
var y=document.getElementsByTagName('textarea');
for (var key in jsonStr) {
    if (jsonStr.hasOwnProperty(key)) {
          if(key=="Comments"){
    jsonData[key] = y[0].value;
     }
     else if(key.toLowerCase().includes("date")){
    var date = new Date(jsonStr[key]);
    var value =date.getFullYear()+ '-' +(date.getMonth() + 1) + '-' + date.getDate();
    jsonData[key]=value;

     }else if(key=='Status'&& btn=='approve'){
      jsonData[key]='A';

     }else if(key=='Status'&&btn=='reject'){
      jsonData[key]='R';

     }else
      jsonData[key]=jsonStr[key];
   }
}

console.log(jsonData);
}

Comments

     <textarea rows="3" cols="50"></textarea>

        <button type="button" class="btn btn-primary" onclick="tansformJson('approve')">Accept</button>
        <button type="button" class="btn btn-primary" onclick="tansformJson('reject')">Reject</button>


texts: Bookmarklet to quickly fill an input with a maximum width string for visual testing purposes

texts:
I'm currently working on a complete overhaul of the CSS of our flagship product with a goal of maintainability and simplification. During the testing, my coworkers and I have found that a lot of pages aren't exactly coping well with extremely long user-defined values, leading to things like long scrollbars, buttons being pushed outside the visible area, text escaping the boundaries of labels,...

In order to quickly enter data like this in an input, I've written a bookmarklet that automatically fills the focused element with w-padded numbers, incrementing by 10, up to the maxLength defined on the element. I chose the letter w because it's the widest letter in the English alphabet, so a value that for up to 80% consists of the letter w should be close to the worst-case scenario for display issues.

The bookmarklet is as follows:

javascript:(function(){var focused=document.activeElement; if(focused&&focused.maxLength){ var focusedMaxLength=focused.maxLength,focusedText="",i=10; for(;focusedMaxLength>=i;i+=10){ focusedText+=("wwwwwwwwwww"+i).slice(-10); } focused.value=focusedText.slice(0,focusedMaxLength); }})()

Version with whitespace:

javascript:(function(){
    var focused=document.activeElement;
    if(focused&&focused.maxLength){
        var focusedMaxLength=focused.maxLength,focusedText="",i=10;
        for(;focusedMaxLength>=i;i+=10){
            focusedText+=("wwwwwwwwwww"+i).slice(-10);
        }
        focused.value=focusedText.slice(0,focusedMaxLength);
     }
 })()

An example of the string this generates: wwwwwwww10wwwwwwww20wwwwwwww30wwwwwwww40wwwwwwww50 in a field that's 50 characters long.

Any remarks on how this bookmarklet could be optimized or potential issues that could arise from using this bookmark are appreciated.


texts: Am I on the right track with this random number array?

texts:
Is this the best way of doing this? I wanted to make sure the grammar is correct when the array is output.

1 car, 2 cars.

The output is correct but is there an easier way generally? I just want to make sure I am doing this in a proper way. I don't have the benefit of the experience of the majority of you guys so I am asking for general guidance.
 Or is it a case of "if the code works then that's all that matters".

<?php
//generates a random number between 1 -10.
function randomnumber(){
    $randomnumber = mt_rand(1, 10);
    return $randomnumber;
}

//Creates array.
//Checks to see if the random number is greater than 1
//Adds an 's' to the entry if greater than one
for ($i = 0; $i < 10; $i++){
        $rannum = randomnumber();
        if ($rannum > 1){
            $adds = "s";
        }else{
            $adds = "";
        }
        $products[$i] = $rannum." car".$adds;
}

//Outputs the final array.
foreach ($products as $current){
    echo $current."<br />";
}
?>


texts: Take previous element from array if condition on current element matches

texts:
Any ideas to simplify this beauty; I would prefer a LinQ expression if possible:

private object[] array;
public abstract bool Condition(object o);
//...
private object FindStuff()
{
    for (int i = 0; i < array.Length; i++)
    {
        if (Condition(array[i]))
        {
            return i == 0 ? null : array[i-1];
        }
    }
    throw new ItemNotFoundException();
}
//...


texts:
I'm creating a version of the classic sequential master file update in java. This is used when you sort two files by the same key for updating one file with the other. In this case, I'm pulling in all available note types and then comparing them against note types configured. The goal is to create two collections, the list of configured note types, and the list of available note types, which do not contain the configured ones.

private void setAvailableAndConfiguredNoteTypes(OptionGroupConfiguration optionConfig,
                                                List<Map<String, String>> noteConfig) {
    //retrieve the collections and sort by ID
    List<ConfigOption> dbConfigured = getConfiguredNoteTypes();
    List<ConfigOption> apiAvailable = getAvailableNoteTypes(noteConfig);

    ConfigOption.CompareById comparator = new ConfigOption.CompareById();
    Collections.sort(dbConfigured, comparator);
    Collections.sort(apiAvailable, comparator);

    //hold the results
    List<ConfigOption> configured = new ArrayList<>();
    List<ConfigOption> available = new ArrayList<>();

    //process both collections
    ListIterator<ConfigOption> configuredIt = dbConfigured.listIterator();
    String configuredId = "";
    ListIterator<ConfigOption> availableIt = apiAvailable.listIterator();
    String availableId = "";

    ConfigOption currentAvailable = null;
    ConfigOption currentConfigured = null;

    while (stillRunning(configuredId, availableId)) {
        int cmp = configuredId.compareTo(availableId);

        if (cmp == 0) {
            //on equal, it goes in configured
            if (currentConfigured != null) {
                configured.add(currentConfigured);
            }

////////////Code Group A
            if (configuredIt.hasNext()) {
                currentConfigured = configuredIt.next();
                configuredId = currentConfigured.getId();
            }
            else {
                currentConfigured = null;
                configuredId = EOF;
            }

////////////Code Group B
            if (availableIt.hasNext()) {
                currentAvailable = availableIt.next();
                availableId = currentAvailable.getId();
            }
            else {
                currentAvailable = null;
                availableId = EOF;
            }
        }
        else if (cmp < 0) {
            //someone disabled the configured option, remove it
            noteTypesConfiguredRepository.delete(configuredId);

////////////Code Group A
            if (configuredIt.hasNext()) {
                currentConfigured = configuredIt.next();
                configuredId = currentConfigured.getId();
            }
            else {
                currentConfigured = null;
                configuredId = EOF;
            }
        }

        else {
            //add to available
            available.add(currentAvailable);

////////////Code Group B
            if (availableIt.hasNext()) {
                currentAvailable = availableIt.next();
                availableId = currentAvailable.getId();
            }
            else {
                currentAvailable = null;
                availableId = EOF;
            }
        }
    }

    Collections.sort(available);
    optionConfig.setAvailableOptions(available);

    Collections.sort(configured);
    optionConfig.setConfiguredOptions(configured);
}

private static boolean stillRunning(String configuredId, String availableId) {
    boolean result = !(configuredId.equals(EOF) && availableId.equals(EOF));
    return result;
}

Some people on my project are looking at this and thinking it's complicated, but I can't for the life of me figure out how to make it any simpler.

Specifically, if you look at the two sections of 8 lines of code marked code group A and code group B, these are identical sections of 8 lines of code and it REALLY bugs me that I can't figure out a way to use the same 8 lines of code.

Does anyone have any suggestions on how to make this code simpler?


texts: Email thousands of customers from a PHP form using a MySQLi query on a MySQL database

texts:
How can a large internet service provider email certain customers to warn them about an impending service interruption? I'm providing what I think is a reasonable solution, but I have not tested it. Please assume that the ISP prefers procedural MySQLi, rather than object-oriented PDO. Please also assume that the ISP is large enough to have their own servers, so there is no hosting company that would prohibit bulk emailing or impose other limitations.

My questions are:

Is this an optimal and efficient way to email to tens- or hundreds-of-thousands of customers, from a database containing several million records?
Can you show me a better way, and explain why it is better?
If this is not optimal for a very large email list, please explain why not.

As an amateur, I do some occasional (rare) programming for small web sites. I don't know anything about the "best practices" for larger companies, and I'm curious to know how they might do it.

Here's the scenario:

Assume the MySQL database has these fields:

customer_id
first_name
last_name
email_address
customer_type

The customer_type field stores the customer category, which indicates whether the customer has cable service or fiber optic service or satellite service, etc. The company employee who is sending the emails would specify which category of customers will receive the emails. He would do so by selecting a customer category within the web form, before clicking the send button.

<?php

$user = "example_user";
$pswd = "example_password";
$host = "localhost";
$database = "example_database";

$db = mysqli_connect($host,$user,$pswd,$database)  // Log in to the database
or die (echo "Could not connect to the database.");

  $customer_type_filter = $_POST['customer_type_filter']; // This value would be set within the form by the ISP employee. It limits the set of customers to whom the email is sent.

  $stmt = mysqli_prepare($db, "SELECT * FROM customers_table WHERE customer_type = ? ORDER BY last_name ASC");
  if (!$stmt) {die('preparation error: '.mysqli_error($db));}

  else {
    mysqli_stmt_bind_param($stmt, "s", $customer_type_filter);
    mysqli_stmt_execute($stmt);
    if (!mysqli_execute($stmt)) {die('stmt error: '.mysqli_stmt_error($stmt) );}
    else {$result = mysqli_stmt_get_result($stmt);

      while($row = mysqli_fetch_assoc($result))
      {
        $email_address = $row['email_address'];
        $first_name = $row['first_name'];

        $message  = "Dear $first_name,\r\n
        Due to scheduled maintenance, your internet service will be interrupted tomorrow between 10 pm and 11 pm. \n
        We regret any inconvenience. \n
        Thank you.\r\n
        YourISP Ltd.\r\n";

        $message=wordwrap($message);
        $to = $email_address;
        $subject = "Interruption of service due to scheduled maintenance.";
        $headers = "From: YourISP Ltd <no_reply@YourISP.com>\r\n";

        mail ($to, $subject, $message, $headers) or print "Error: Unable to send an email message to $email_address.";
      }
    }
  }


texts:
The problem I was trying to solve sounded pretty basic, but turned out to be a bit hairy.

I need to select some lines of arbitrary length from an input stream (file or standard input) and print them to output. In other words, a function that just echos the line would do the job. The input stream is encoded in UTF-8. For reasons that I don't quite understand, the normal <string> mangles the stream, so I couldn't use:

std::string line;
std::readline(line);
std::cout << line;

I did solve it using basic_istream::getline(); however, this function writes to a buffer, and I need to tell it how big the buffer is. To make it deal with lines of arbitrary length, I need to read to a buffer in a loop, checking whether failbit is set (when the end of the line wasn't reached).

Then, the easier solution was to use iterators on the input and the output stream, like this:

template<typename I, typename O, typename T>
I copy_until(I first, I last, O d_first, T delim)
{
    while (first != last && *first != delim) {
        *d_first = *first;
        ++first;
        ++d_first;
    }
    return first;
}

This copies from first up to last at most, and stops if the delimiter is encountered. It returns a pointer to the first character in the input range that was not copied.

It can be used like this to copy all input to output:

int main()
{
    std::istreambuf_iterator<char> first(std::cin);
    std::istreambuf_iterator<char> last;
    std::ostreambuf_iterator<char> d_first(std::cout);

    while (first != last) {
        first = copy_until(first, last, d_first, '\n');
        std::cout.put(*first);
        ++first;
    }
}

The third argument of copy_until could of course be a unary predicate, then instead of while (first != last && *first != delim) it would say while (first != last && !p(*first)).

More important questions:

Is there an algorithm in <algorithm> that I have overlooked? copy_if and partition_point come close, but they don't do exactly that, and partition_point followed by copy_n will not work with forward iterators.
I am not sure how to declare that the two iterators need to point to the same type as the type of the delimiter or the argument to the unary predicate.
Not certain about the return value. This one is the most useful for my particular use case.
Or maybe there is a much, much easier way that avoids this altogether. But copy_until might be useful in other contexts?