texts:
I've spent my fair share of time criticizing other people's code on this site; but I'm finding out I'm kind of a hypocrite. Almost everything I've written so far has been some program whipped together to do some task for me. I have little experience actually starting out writing maintainable code.

Then today I decided to start a semi-large project. I want to write a sort of custom networked remote manager; a kind of cross-breed between ssh and an all-out remote desktop.

I wrote up the following class while realizing the previous revelations:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

public abstract class Connection implements Runnable {
    private final Socket s;
    private final InputStream is;
    private final OutputStream os;
    private final ArrayList<byte[]> posts;
    private boolean run;
    public Connection(String addr, int port) throws UnknownHostException, IOException {
        s = new Socket(addr, port);
        is = s.getInputStream();
        os = s.getOutputStream();
        posts = new ArrayList<>();
        run = true;
        new Thread(this).start();
    }
    public void post(byte data[]) {
        synchronized (posts) {
            posts.add(data);
        }
    }
    public void stop() {
        run = false;
    }
    public void run() {
        while (run) {
            byte send[] = null;
            synchronized (posts) {
                if (posts.size() > 0) {
                    send = posts.get(0);
                    posts.remove(0);
                }
            }
            if (send != null) {
                try {
                    os.write(send);
                } catch (IOException e) {
                    hasError(e);
                }
            }
            try {
                if (is.available() > 0) {
                    byte data[] = new byte[is.available()];
                    receive(data, is.read(data));
                }
            } catch (IOException e) {
                hasError(e);
            }
        }
    }
    public abstract void receive(byte data[], int len);
    public abstract void hasError(Exception e);
}

It occurred to me I should probably be asking here how maintainable code is actually written. I'm kind of ashamed I haven't done this sort of thing before, but as a self-taught programmer I presume this sort of obstacle is common.

Given the above sample of my idea of how to make maintainable modular code, what sort of pitfalls should I look out for while making the excursion into a legitimate program of larger than two or three files?


texts:
link to original question: Simple media ingest script

As per answers I have refactored my code and would like to get feedback on the current structure.

The purpose of this tool is to allow someone to copy media from cards (SD cards, CFast, etc) using rsync and to also allow someone to complete incomplete transfer that they have initiated.

I've chosen to use prompts because it's more user friendly for the environment the script will be used in. The intended users are not command line tool friendly.

I'm not very familiar with bash and am quite out of practice with code in general so I would like to check behind myself. I received excellent feedback in the previous post and have addressed several of the points raised.

#!/usr/local/bin/bash
set -e
set -u

# prompt user for input
prompt_user(){
        while [[ -z "${!2:-}" ]]
            do
            read -r -p "$1" "$2"
        done
}

# prompt user for additional rsync options
add_rsync_options(){
    while true;
    do
        read -r -p "Add rsync options? [y/n] " add_options
        case $add_options in
            [Yy]* )
                read -r -p $'Enter additional rsync options:\n' rsync_options
                break;;
            [Nn]* )
                break;;
            *) echo "Please enter y or no!"
        esac
 done
}

# make target directory for transfer
make_directory(){
    echo  $'Follow the prompt to create a project directory.\n'

    prompt_user $'Path of target directory?\n' target_directory
    prompt_user $'Brand Prefix?\n' brand_prefix
    prompt_user $'Project Name?\n' project_name
    prompt_user $'Media Type?\n' media_type
    prompt_user $'Location?\n' location
    prompt_user $'Employee?\n' employee

    destination_path=${target_directory}/$(date +'%Y%m%d')_${brand_prefix}_${project_name}_${media_type}_${location}_${employee}

    echo "Creating directory: ${destination_path}"

    mkdir -p "${destination_path}" "${destination_path}/logs"
}

# run rsync command
run_rsync(){
    echo $'Follow the prompt to complete the rsync command.\n'

    prompt_user $'Path to source media?\n' source_path

# if partial ingest indicate pre-existing target directory
    if [[ "$option" == "2" ]]; then
        prompt_user $'Target directory?\n' target_directory
        destination_path=$target_directory
    fi

    add_rsync_options

    echo $'Running rsync command:\n'

    rsync -r --info=progress2 --log-file="${destination_path}/logs/$(date +'%Y%m%d')_transfer_log.txt" ${rsync_options:-} "${source_path}/" "${destination_path}"

}

# clear terminal for readability
clear

# start
while true
do
# read user input and run appropriate functions
        read -r -p $'Enter [1] to start an ingest or [2] to complete a partial ingest.\n' option
        case $option in
            1 )
                make_directory
                run_rsync
                break;;
          2 )
                run_rsync
                break;;
          * )
                echo $'Please enter a valid option!\n';;
        esac
done

Error handling is at a minimum still I believe and I'm not too sure what would even be relevant to handle past what's implemented. I'm not very experienced in that regard so resources are appreciated!

Thanks!


texts:
The following implementation is a bit different form the standard implementations I have read. Is it correct?

#include <malloc.h>
#include <stdio.h>
void heapify(int[],int,int);
void swap(int a[],int i,int j){
    int temp=a[i];
    a[i]=a[j];
    a[j]=temp;
}
void heap_sort(int a[],int l,int r){
    for(int i=l;i<r;i++)
        heapify(a,l,r);
}
void heapify(int a[],int l,int r){//brings largest element to position l
    int size=(r-l+1);
    int i=size-1,larger;
    if(size%2){
        if(a[l+i]<a[l+i/2])
            swap(a,l+i,l+i/2);
        i--;}
    while(i>0){
        if(a[l+i]>a[l+i-1])
            larger=l+i-1;
        else
            larger=l+i;
        if(a[l+(i-1)/2]>a[larger])
            swap(a,larger,l+(i-1)/2);
        i-=2;
    }
}
void printArray(int arr[], int n)
{
   int i;
   for (i=0; i < n; i++)
       printf("%d ", arr[i]);
   printf("\n");
}

/* Driver program to test insertion sort */
int main()
{
   int arr[] = {12, 11, 13, 5, 6, 7};
    int arr_size = sizeof(arr)/sizeof(arr[0]);
    printf("Given array is \n");
    printArray(arr, arr_size);
    heap_sort(arr,0,arr_size-1);
    printf("\nSorted array is \n");
    printArray(arr, arr_size);
    return 0;
    return 0;
}


texts: Calculate rolling mean and std over a pandas dataframe

texts:
I am trying to calculate the rolling mean and std of a pandas dataframe. So far I'm here:
phi = pd.DataFrame(data=phi)

#mean and std ## This could be a function...
#for each window, get the mean and std of previous M frames
#M = 40
p1_mean = phi.iloc[0].rolling(40, min_periods=1).mean()
p2_mean = phi.iloc[1].rolling(40, min_periods=1).mean()
p3_mean = phi.iloc[2].rolling(40, min_periods=1).mean()
p4_mean = phi.iloc[3].rolling(40, min_periods=1).mean()

P_mean = P_mean = [p1_mean, p2_mean, p3_mean, p4_mean]
P_mean = pd.DataFrame(data=P_mean)

p1_std = phi.iloc[0].rolling(40, min_periods=1).std()
p2_std = phi.iloc[1].rolling(40, min_periods=1).std()
p3_std = phi.iloc[2].rolling(40, min_periods=1).std()
p4_std = phi.iloc[3].rolling(40, min_periods=1).std()

P_std = [p1_std, p2_std, p3_std, p4_std]
P_std = pd.DataFrame(data=P_std)

This works, but I'm wondering if there is a more pythonic way to do this?
I tried this something like this:
P = phi.rolling(40, min_periods=1).agg({np.std, np.mean})

print
       0                   1                   2                   3     \
       mean       std      mean       std      mean       std      mean
0  0.084194       NaN  0.329374       NaN  0.353773       NaN  0.345830
1  0.161660  0.109554  0.229725  0.140926  0.290061  0.090103  0.302811
2  0.163631  0.077542  0.286092  0.139506  0.312857  0.074955  0.318717
3  0.138196  0.081217  0.295218  0.115359  0.323390  0.064725  0.325664

which seems close enough, except that I want the std and mean for each column on the same column. In my df of shape (4, 3000) this gives me (4, 6000) and I'm looking for a shape of (8, 3000) Also, I want the rolling window row/-wise not default column wise.
Any ideas?
Thanks!


texts: Fast way of searching for a string in a text file

texts:
I have written this code to search for a string in a .txt file. Is it possible to optimize the code so that it searches for the string in fastest manner possible? Assuming the text file would be a large one (500MB-1GB)

I don't want to use regex.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class StringFinder {

public static void main(String[] args)
{
    double count = 0,countBuffer=0,countLine=0;
    String lineNumber = "";
    String filePath = "C:\\Users\\allen\\Desktop\\TestText.txt";
    BufferedReader br;
    String inputSearch = "are";
    String line = "";

    try {
        br = new BufferedReader(new FileReader(filePath));
        try {
            while((line = br.readLine()) != null)
            {
                countLine++;
                //System.out.println(line);
                String[] words = line.split(" ");

                for (String word : words) {
                  if (word.equals(inputSearch)) {
                    count++;
                    countBuffer++;
                  }
                }

                if(countBuffer > 0)
                {
                    countBuffer = 0;
                    lineNumber += countLine + ",";
                }

            }
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Times found at--"+count);
    System.out.println("Word found at--"+lineNumber);
}
}


texts: Mixing arbitrary integers and enum values

texts:
I'm writing a text adventure editor that identifies various StoryEntity instances by name, among other means, but the name is the primary way for the user or player to refer to them. The name doesn't have to be unique. For example, there may by many instances of "North" which each refer to a different StoryEntity depending on where the player is, or the context of which container you're referring to. Sometimes I know the name will be ambiguous, but I want to give preference to names of entities that are near the player. Other times, like when the user types Edit North, they may be dealing with a design-mode copy of the data where the player is always in its designed starting location, but I have another way of identifying the "current location". Still other times, I don't want to waste time sorting the results at all because I will handle all of them equally. So I updated the function that retrieves a StoryEntity by name to include a parameter indicating whether and how to sort the results by relevance:

public IEnumerable<StoryEntity> EntitiesNamed(string name,
   RelevantContainer relevantContainer)
{
   if (relevantContainer == RelevantContainer.PlayerAndContainer)
      return byName[name.ToLower()].OrderBy((e) => (e.Container == PLAYER_ENTITYID)
         ? 1 : ((e.Container == Player.Container) ? 2 : 3));
   else if (relevantContainer > 0)
      return byName[name.ToLower()].OrderBy((e) => ((e.Container == relevantContainer)
         ? 2 : 3));
   else
      return byName[name.ToLower()];
}

Now my question is how can I best define RelevantContainer so that it allows pre-defined values as well as arbitrary int (container ID) values? I can imagine implementing it as an enum or a struct:

Struct

public struct RelevantContainer
{
   private int value;
   public static implicit operator RelevantContainer(int containerId)
   {
      return new RelevantContainer() { value = containerId };
   }
   public static implicit operator Int32(RelevantContainer relevantContainer)
   {
      return relevantContainer.value;
   }
   public readonly static RelevantContainer None = 0;
   public readonly static RelevantContainer PlayerAndContainer = -1;
}

Enum

public enum RelevantContainer
{
   None = 0,
   PlayerAndContainer = -1
}

Of course if I implement it as an enum, then I will have to do more casting to persuade the compiler to allow integer values and enum values to be interchanged, but the code for RelevantContainer itself is much simpler. Is there a clear choice for which approach to use here? If it matters, this is a Xamarin Android project.


texts: Checking if the whole number is prime, and if all its digits are too

texts:
That was an easy one to solve but the problem lies in the efficiency since it checks every single digit of the number while converting to integers. I'm receiving TLE (i.e. Time Limit Exceeded) on the site so I have to increase its performance.

So its hard to explain but the exercise asks for the return value to be "Super" when the number is prime and all of its digits are too, return "Primo" when the number is prime but its digits are not, return "Nada" When the whole number is not prime. The test cases end with EOF.

Its worth mentioning that only built-in modules are accepted by the site. I tried using the well known (and much faster) sympy.isprime method, but it's from a 3rd party module so it wasn't accepted, sadly.

Again, I solved it, but I need a bump in the efficiency since there are 1018 numbers in the test cases and more than 200 test cases and I need to solve it in 2 seconds:

def is_prime(n):
    if n in range(0, 2):
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

while True:
    try:
        data = input()
    except EOFError:
        break
    if is_prime(int(data)):
        for j in data:
            if not is_prime(int(j)):
                print("Primo")
                break
        else:
            print("Super")
    else:
        print("Nada")


texts:
How would I implement a data structure that supports the following in constant time? I got this question at a job interview, and the following is my solution. Please check my approach, or suggest a better alternate approach, if you have one.

////////////////////////////////////////////////////////////////
// Implement a container that have the following methods:
// Java:
//     public class Container<E>
//     {
//         // data memebers
//         ...
//         public Container();
//             // constructor
//             // Complexity: Constant
//
//         public int size();
//              // return the total number of elements in the container
//              // Complexity: Constant
//
//         public E get(int index);
//              // get an element from the container by its index
//              // Complexity: Constant
//
//         public void set(int index, E element);
//              // set an element in the container by its index. index >= 0 && index < size()
//              // Complexity: Constant
//
//         public void add_front (E element);
//              // add a new element to the front of the container i.e. its index is 0
//              // Complexity: Constant (amortized time)
//
//         public void remove_front ();
//              // remove the element at the front of the container
//              // Complexity: Constant
//
//         public void add_back (E element);
//              // add a new element to the back of the container i.e. its index is size()
//              // Complexity: Constant (amortized time)
//
//         public void remove_back ();
//              // remove the element at the back of the container
//              // Complexity: Constant
//     }
//
// Examples:
//   at beginning   => []

//   add_front(0)   => [0]
//   add_front(-1)  => [-1, 0]
//   add_back(1)    => [-1, 0, 1]
//   add_back(2)    => [-1, 0, 1, 2]
//   get(0)         => -1
//   get(3)         => 2
//   set(3, 8)      => [-1, 0, 1, 8]
//   remove_front() => [0, 1, 8]
//   remove_back()  => [0, 1]
////////////////////////////////////////////////////////////////

My approach

Use a Hashtable for storing values:

Hashtable<Integer, Integer> storage = new Hashtable<>();

Have two variable called front and back, which signify the start and end of the data structure's storage range.

add_front(E element)

low--;
storage.put(low, element);

add_back(E element)

high++; storage.put(high, element);

public void remove_front ();

low++;

public void remove_back ();

high--;

public E get(int index);

index = index-low; return storage.get(index);

public void set(int index, E element);

index = index-low; storage.put(index, element);

public int size();

return high-low+1;


texts:
I've written a small program that calculates Arithmetic and Geometric Partial Sums. I'd like feedback on anything possible, since I intend on writing a cheatsheet that encapsulates all PreCalculus equations.

partial_sum.py

"""
This is a program that calculates arithmetic and geometric
partial sums

"""

from fractions import Fraction

def find_an(parsed_series):
    """
    Finds an in the passed parsed arithmetic series

    :param parsed_series: The series to be analyzed

    """
    for i, _ in enumerate(parsed_series):
        if parsed_series[i] == ".":
            return int(parsed_series[i + 1])
    return None

def arithmetic_partial_sum(series):
    """
    Returns the partial sum of an arithmetic series

    Formula:
        S = n( (a1 + an) / 2 )

    Find an:
        an = a1 + (n - 1)d

    Find n:
        n = 1 + ( (an - a1) / d )

    :param series: Arithmetic series to solve

    """

    series = series.split("+")

    a1 = int(series[0])
    d = int(series[1]) - a1
    an = find_an(series)
    n = 1 + ((an - a1) / d)
    S = n * ((a1 + an) / 2)

    return S

def geometric_partial_sum(series):
    """
    Returns the partial sum of the geometric series

    :param series: Geometric series to solve

    Formula:
        S = (a1 * (1 - (r ** n))) / (1 - r)

    """

    series = series.split("+")

    a1 = int(series[0])
    r = int(series[1]) / a1
    n = len(series)
    S = (a1 * (1 - (r ** n))) / (1 - r)

    return str(Fraction(S).limit_denominator())

if __name__ == '__main__':
    A_SERIES = "3+7+11+15+.+99"
    G_SERIES = f"3+1+{1/3}+{1/9}+{1/27}+{1/81}"
    print(arithmetic_partial_sum(A_SERIES))
    print(geometric_partial_sum(G_SERIES))


texts:
I'm learning ML/DL and found the process of getting the data and labels quite tedious. There is not much details on how to get JPG files into H5, which is (afaik) the only way to work smoothly later on.
I wrote my own simple script, and would like to hear about modifications, to improve my Python syntax. And maybe there are shortcuts I'm not aware of.
import h5py
import numpy as np
from glob import glob # import "submodule"
from PIL import Image
import matplotlib.pyplot as plt

# img source directory
src = "images/raw/cats/*"

# self explanatory
outfile = "images/clean/cat.hdf5"

listOfImages = glob(src)

# img loaded as JpegImageFile Object
oneImage = Image.open(listOfImages[0])

# open file
f = h5py.File(outfile, "w")
data  =  np.array(oneImage) #this is an array 200x200x3

# save dataset (ndarray but with more features)
dset = f.create_dataset("images", data=data) # array 200x200x3

# Check if files can be read from the h5py file
with h5py.File(outfile, "r") as f:
    image = f['images']
    print(image.shape, image.dtype)
    plt.imshow(image)
    plt.show()


texts:
I'm basically wondering what the optimal method for returning to the top of src/main.rs::main() is?

Maybe something like this:

mod main;

pub fn main() {
    crate::main();
}

Or maybe there's a keyword built in?

I want to handle certain kinds of errors by 'restarting the program'.


texts: Approximating square root (loops and functions exercise)

texts:
Just looking for some feedback on my solution for Tour of Go Exercise 24 - Loops and Functions. Is there anything that looks like a wrong way to do things in go? anything I could have done better?

package main

import (
    "fmt"
    "math"
)

func Approx(x float64, z float64) float64 {

    return z - (((z * z) - x) / (2 * z))

}

func Sqrt(x float64) float64 {

    previous := 0.0
    delta := 1.0
    z := x

    for delta > 0.005 {

        z = Approx(x, z)

        if previous > 0.0 {
            delta = previous - z
        }

        previous = z
    }

    return z

}

func main() {

    for i := 1; i < 11; i++ {

        value := float64(i)

        fmt.Println("Calculating Sqrt for ", value)

        real := math.Sqrt(value)
        approx := Sqrt(value)

        fmt.Println("Real ", real)
        fmt.Println("Approx ", approx)

    }

}


texts:
I was trying to sort a massive file of successive chars in C. I did some research and found a few file sorting algorithms that look the same. Their main idea is to read an amount of data to memory, sort them using one of classic sort algorithms, write them to a new file, then repeat the process and merge the two files and so on. You can find more here

I tried to make a new algorithm that does not require a lot of memory. I ended up with this code that actually works and is inspired from Bubble sort algorithm:

#include<stdio.h>
int main()
{
char a,b;
FILE *f,*aux;

int sorted;//BOOLEAN
do
{
    f = fopen("ltr.txt","r"); //Assuming that the file exists
    aux = fopen("aux.txt","w+");
    a = getc(f);
    sorted = 1;
    while ( (b = getc(f)) != EOF )
    {
        if (b < a)
        {
            fputc(b, aux);
            sorted = 0;
        }
        else
        {
            fputc(a, aux);
            a = b;
        }
    }
    fputc(a, aux);
    fclose(f);
    fclose(aux);
    remove("ltr.txt");
    rename("aux.txt","ltr.txt");
}while(!sorted);
return 0; //EXIT_SUCCESS
}

The algorithm works but is improvable and can be optimized, however I'm asking for help by reviewing complexity, performance, read/write to disk, disk management, memory management and comparison to other sorting algorithms.

I can list some disadvantages:

requires disk space of file_size*2 (can be improved by deleting original char each time we write it to aux.txt)
file will be written to disk several times and the original will be deleted
execution time looks to be too long (yet I didn't measure it)


texts: Creating a list of new areas for patches of conserved land within a watershed

texts:
I'm writing code to create a list of new areas for patches of conserved land within a watershed based on the current size distribution of conserved land patches that are in the watershed now.

I'm generating a new random area based on a normal probability density function fitted to the log-transformed distribution of the sizes of currently conserved land. Then I have a list of the areas of tax parcels in the region, and I want to randomly grab a tax parcel that is within ± 10% of the randomly generated area. The loop will continue until I've generated a total 4,735 hectares of new areas for conservation.

The code works, and runs very quickly if I lower the threshold for total new conserved area to ~500 hectares. However, for my current endpoint (4,735 new hectares), it runs so slowly that I haven't actually ever run it all the way through (waited an hour+). Any ideas on how I can streamline this code to get it to run faster are greatly appreciated!

# Set endpoint of total new area
new_cons_area = 4735.44

# Get new random areas until they total the new_cons_area
sum_rand_area = 0
new_rand_area = []
rand_sizes = []
index_list = []
while sum_rand_area < new_cons_area:
    # Get new random size based on current distribution of sizes of conservation patches
    new_log_size = np.random.normal(param_log[0],param_log[1],1)
    # Transform back to actual area
    new_size = np.e**new_log_size[0]
    # Set buffer boundaries
    min_size = new_size * 0.9
    max_size = new_size * 1.1
    # Get length of new_rand_area list
    current_length = len(new_rand_area)
    # Set up loop to grab sizes from the current list of tax parcels suitable for conservation
    if new_size >= 3.33:
        # Run this loop until a new size is added to the list of new random areas
        while len(new_rand_area) == current_length:
            # Grab a random index from the list of parcel areas
            rand_index = random.randrange(len(parcel_areas)-1)
            # See if the parcel area associated with the random index matches the randomly generated size
            if min_size <= parcel_areas[rand_index] <= max_size:
                # If criteria is met, add the randomly generated size to a list
                rand_sizes.append(int(new_size))
                # Add the randomly generated index to list so you can grab the object ids in the next step
                index_list.append(rand_index)
                # Add the actual tax parcel area to a list
                new_rand_area.append(parcel_areas[rand_index])
                # Add the area to the total area of new land to be conserved
                sum_rand_area += parcel_areas[rand_index]


texts: Possibly mixing prototype and module pattern

texts:
I have either created something beautiful or something monstrous, and I'm not really sure which, and I don't know where else to turn but here. What I've done:

var MyObject = function(opts) {
    //init code, set vals, runs when 'new MyObject()' is called
}

MyObject.prototype = (function() {
    //private helper functions
    //scoping is a pain, but doable
    function myPrivateFunction() {}

    return {
        publicFunc1: function() { /* uses myPrivateFunction() */ }
        , publicFunc2: function() { /* uses myPrivateFunction() */ }
    };
})();

MyObject.prototype.publicFunc3 = function() {}
MyObject.prototype.publicFunc4 = function() {}
MyObject.prototype.publicFuncEtc = function() {}

To my surprise, this works, and takes care of a pretty significant problem of creating reusable private functions for various public functions. Of course, I have to do some scoping for the this object, but I feel it's a small price to pay for being able to use private reusable functions. I left the other functions on the outside to avoid having to deal with scoping.

My question is: is this a code smell? and as a corollary, is there a better way to do this?


texts: Scraping data from tables connected to each dot on a map

texts:
I've written a script in python with selenium to scrape different table data lie within different dots on a map in a certain website. Each table is connected to each dot. The table is activated once either of the dots is clicked. However, my script is able to open that webpage, traverse the map, click each dot to activate each table and finally parse the data of each table available on that map. Any input on this to make it more robust  will be highly appreciated.

Here is what I've written to do the whole thing:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
driver.get("https://acwi.gov/monitoring/vm/programs/vm_map.html")
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.TAG_NAME, 'iframe')))

#Using iframe link to get to the map

driver.get(driver.find_element_by_tag_name("iframe").get_attribute("src"))
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div#mapDiv_zoom_slider")))

#Zooming in for the browser to locate elements properly

driver.find_element_by_css_selector("div#mapDiv_zoom_slider").click()

#Hardcoded time to wait until certain moment to avoid stale element error

time.sleep(5)

#Finding each tag to click to get the table

for item in driver.find_elements_by_tag_name("circle"):
    ActionChains(driver).move_to_element(item).click().perform()

    #Go for the next item to click

    elem = driver.find_element_by_css_selector(".titleButton.next")
    if elem.is_displayed():
        elem.click()
        time.sleep(5)

        #Finding table element

        items = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "table.attrTable")))
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "tr")))
        list_of_data = [[item.text for item in data.find_elements_by_css_selector('td')]
                    for data in items.find_elements_by_css_selector('tr')]
        for tab_data in list_of_data:
            print(tab_data)

driver.quit()

Here is a link to an image to give the clarity of my above description:
https://www.dropbox.com/s/axd66fvozexbefp/Untitled.jpg?dl=0


texts: Calculating and printing a credit card balance

texts:
I am working on a problem that simply calculates and prints the credit card balance. I hope this code can be improved/optimized a lot.

I am from a Java background. If it was Java code, I would have pulled all the code lines inside the for loop and place it at the beginning of the method and inside for loop I would call the method recursively. I tried to do the same in python but it hit me with some error:

  RuntimeError: maximum recursion depth exceeded while calling a Python object

From a quick internet search I found that it is better to go for iteration instead of recursion:

'''
Program to calculate credit card balance after 1 year
'''
def calculateCreditCardBalance(balance, annualInterestRate, monthlyPaymentRate):

    totalPaid = 0

    for thisMonth in range(1,13):
        monthlyInterestRate = annualInterestRate / 12.0
        minimumMonthlyPayment = round(monthlyPaymentRate * balance, 2)
        monthlyUnpaidBalance = balance - minimumMonthlyPayment
        updatedBalanceEachMonth = round(monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) , 2)

        print 'Month: %d' %(thisMonth)
        print 'Minimum monthly payment: ' + str(minimumMonthlyPayment)
        print 'Remaining balance: ' + str(updatedBalanceEachMonth)

        balance = updatedBalanceEachMonth
        totalPaid += minimumMonthlyPayment

    print 'Total paid: ' + str(totalPaid)
    print 'Remaining balance: '+ str(balance)

calculateCreditCardBalance(4842, 0.2, 0.04)


texts: Convert a boxed integer to an nullable integer with potentially different type

texts:
Given a boxed integer (with a boxed short, int, ...) I want to convert it to an unboxed, nullable type instead. It should be possible to convert non-matching types (for example: boxed int to short?) Can you please comment on:

using System;

public class Test
{
    public static void Main()
    {
        int? x = Unbox<int>((short)42);
        short? y = Unbox<short>(42);
    }

    static T? Unbox<T>(object x) where T : struct
    {
        return typeof(T) == x.GetType() ? (T)x : (T)Convert.ChangeType(x, typeof(T));
    }
}


texts: SSRS: code function to sanitise HTML for rendering in RDLC report

texts:
Background

I have an RDLC that among other things displays text coming in that is captured in SharePoint, using a custom control (TinyMCE) that exposes limited formatting options to users.

The SSRS local report renderer supports a subset of HTML (see details here) and has limited configurability. It has some rendering behaviours that need to be worked around (e.g. if there are <p> tags, it adds some vertical padding above and below the text in the report). I am targeting PDF for reports.

Purpose

Below is a function that I have embedded in the RDLC to accept a string (an HTML fragment in most cases), do the following, and return the transformed string for use in a text field within the report:

Convert to ASCII (if I don't do this, sometimes the first line of text appears with no spaces)
Do some replacement of tags as detailed in code comments
Decode HTML character entities

Concerns

Performance is my main concern at this point.
I suspect the regexes are overkill, certainly from a performance perspective. I've read a bit about backtracking issues but not sure if this code is subject to it.
I am not concerned about the suitability of regex to parse HTML in this case, as it will always be well-formed. I'm aware of the normal wise counsel around doing this in general cases.

Public Function HTMLHelper(input As String) As String

Dim r As String = ""

If String.IsNullOrWhiteSpace(input) = False Then
    ' transform string to Ascii encoding (addresses problem where the first line rendered to PDF hasnospacesinitatall)
    r = System.Text.Encoding.ASCII.GetString(
                       System.Text.Encoding.Convert(
                        System.Text.Encoding.UTF8,
                        System.Text.Encoding.GetEncoding(
                            System.Text.Encoding.ASCII.EncodingName,
                            New System.Text.EncoderReplacementFallback(String.Empty),
                            New System.Text.DecoderReplacementFallback()
                            ),
                        System.Text.Encoding.UTF8.GetBytes(input)))

    ' transformations for tags that are troublesome in SSRS
    r = System.Text.RegularExpressions.Regex.Replace(r, "(?i)</?div[^>]*>", "") ' remove DIV tags
    r = System.Text.RegularExpressions.Regex.Replace(r, "(?i)<p[^>]*>", "") ' remove opening P tags
    r = System.Text.RegularExpressions.Regex.Replace(r, "(?i)</p[^>]*>\s*(?=\Z)", "") ' remove final closing P tag
    r = System.Text.RegularExpressions.Regex.Replace(r, "(?i)</p[^>]*>", "<br>") ' replace remaining closing P tags with BR

    ' decode HTML character entities (like "&#58;" resolves to ":")
    r = System.Net.WebUtility.HtmlDecode(r)
End If

Return r

End Function


texts:
I am trying to learn data structures by taking this Udemy Course, Easy to Advanced Data Structures by William Fiset. The course provided an implementation of Dynamic Array in Java. To ensure I fully understood the material, I tried to re-implement it in Python. Have provided the code below. Please let me know if I am doing it right or if there is anything wrong with it. Much thanks for your help!

"""
A generic dynamic array implementation

"""
class DynamicArray:
    def __init__(self, capacity=0):
        self._index = 0
        self.capacity = capacity # actual array size
        self.arr = [None for _ in range(self.capacity)]
        self.size = 0 # length user thinks array is

    def __len__(self):
        return self.size

    def isEmpty(self):
        return self.size == 0

    def __getitem__(self, index):
        return self.arr[index]

    def __setitem__(self, index, elem):
        self.arr[index] = elem

    def clear(self):
        for i in range(self.size): self.arr[i] = None

    def add(self, elem):
        # To resize
        if self.size + 1 >= self.capacity:
            if self.capacity == 0:
                self.capacity = 1
            else:
                self.capacity *= 2
            new_arr = DynamicArray(self.capacity)
            for i in range(self.size):
                new_arr[i] = self.arr[i]
            self.arr = new_arr
        self.arr[self.size] = elem
        self.size += 1

    # Removes an element at the specified index in this array
    def removeAt(self, rm_index):
        if rm_index >= self.size or rm_index < 0:
            raise IndexError
        data = self.arr[rm_index]
        new_arr = DynamicArray(self.size - 1)
        i, j = 0, 0
        while i < self.size: #self.size = 3
            if i == rm_index:
                j -= 1
            else:
                new_arr[j] = self.arr[i]
            i += 1
            j += 1
        self.arr = new_arr
        self.size -= 1
        return data

    def remove(self, elem):
        index = self.indexOf(elem)
        if index == -1: return False
        self.removeAt(index)
        return True

    def indexOf(self, elem):
        for i in range(self.size):
            if elem == self.arr[i]:
                return i
        return -1

    def __contains__(self, elem):
        return self.indexOf(elem) != -1

    def __iter__(self):
        return self

    def __next__(self):
        if self._index > self.size: raise StopIteration
        else:
            data = self.arr[self._index]
            self._index += 1
            return data

    def __str__(self):
        if self.size == 0: return "[]"
        else:
            ans = "["
            for i in range(self.size - 1):
                ans += str(self.arr[i]) + ", "
            ans += str(self.arr[self.size - 1]) + "]"
        return ans


texts: Container for fast deletion and addition of elements

texts:
I need a container that is able to delete and add elements as fast as possible, without the need of reallocation that usually takes place when we push_back elements in an std::vector or when we delete elements.

By looking around on the internet I have found that a good way to achieve this is to use a fixed-size container. The class is supplied with a counter which accounts for the number of "active elements".
Deletion of an element consists just of swapping said element with the last active one of the container and decreasing the counter of active elements by one.

What do you think of this implementation? How can I improved it?

#include <vector>

template <class Element>
class ObjectPool
{

private:
    size_t            activeElements;
    std::vector<Element> elements;

public:
    ObjectPool(size_t maxElements)
    {
        activeElements = 0;
        elements.resize(maxElements);
    }

    size_t size() const
    {
        return activeElements;
    }

    Element& at(size_t index)
    {
        if (index >= activeElements) {
            throw std::out_of_range("System: element requested is not active.");
        }
        return elements.at(index);
    }

    const Element& at(size_t index) const
    {
        if (index >= activeElements) {
            throw std::out_of_range("System: element requested is not active.");
        }
        return elements.at(index);
    }

    Element& back()
    {
        if (activeElements <= 0) {
            throw std::out_of_range("System: number of active elements is zero.");
        }
        return elements.at((size_t)(activeElements - 1));
    }

    const Element& back() const
    {
        if (activeElements <= 0) {
            throw std::out_of_range("System: number of active elements is zero.");
        }
        return elements.at((size_t)(activeElements - 1));
    }

    void addBackElement()
    {
        if (activeElements < elements.size()) {
            activeElements++;
        }
        else
        {
            throw std::out_of_range("System: maximum limit of elements in the system exceeded.");
        }
    }

    void deleteElement(size_t index)
    {
        if (index >= activeElements) {
            throw std::out_of_range("System: element requested is not active.");
        }
        activeElements--;
        swapElements(activeElements, index);
    }

    void resize(size_t maxElements)
    {
        elements.resize(maxElements);
    }

private:
    void swapElements(size_t i, size_t j)
    {
        std::swap(elements.at(i), elements.at(j));
    }
};


texts:
I am new to encryption and recently wanted to learn more about it. I researched how to do AES Encryption in java and assembled my own Java AES encryption class. I don't know if there are any major security holes, though.

Can someone experienced in Java encryption look at my code and tell me if there are any serious security vulnerabilities that I should know about?

import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryption {

    private SecureRandom random = new SecureRandom();
    private Base64.Encoder encoder = Base64.getEncoder();
    private Base64.Decoder decoder = Base64.getDecoder();
    private Cipher cipher = null;
    private ByteArrayOutputStream outputStream;

    /**
     * Initializes AES Encryption and sets Cipher transformation
     */
    public AESEncryption(){
        try{
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * Generates a random salt used to generate a key in encrypt()
     *
     * @return The random salt
     */
    public String generateSalt(){
        byte bytes[] = new byte[16];
        random.nextBytes(bytes);
        return new String(bytes);
    }

    private byte[] generateIv(){
        byte bytes[] = new byte[16];
        random.nextBytes(bytes);
        return bytes;
    }

    /**
     * Encrypt the user supplied word
     *
     * @param word The user supplied word
     * @param salt The salt generated by generateSalt()
     * @return The encrypted word with IV appended encoded
     */
    public String encrypt(String word, String salt) throws Exception{

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec("12345asdqwe".toCharArray(), salt.getBytes("UTF-8"), 65536, 128);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        byte[] ivBytes = this.generateIv();

        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivBytes));

        byte[] encrypted = cipher.doFinal(word.getBytes("UTF-8"));
        outputStream = new ByteArrayOutputStream();
        outputStream.write(ivBytes);
        outputStream.write(encrypted);
        return encoder.encodeToString(outputStream.toByteArray());
    }

    /**
     * Decrypts the encrypted word with the salt and appended IV used to encrypt the word
     *
     * @param encryptedWord The encrypted word returned from encrypt()
     * @param salt The salt used to encrypt the encrypted word
     * @return The decrypted word
     */
    public String decrypt(String encryptedWord, String salt) throws Exception{

        byte[] decodedBytes = decoder.decode(encryptedWord);

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec("12345asdqwe".toCharArray(), salt.getBytes("UTF-8"), 65536, 128);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(decodedBytes, 0, 16));

        return new String(cipher.doFinal(decodedBytes, 16, decodedBytes.length - 16));
    }

}


texts:
I have to run an external program from Python.  The external program makes many temporary files (which conflict with other instance of same program).

My strategy is:

get current directory (native) path
change to temp directory
run external command
copy output to native directory
change back to native directory

Here is my code:

import os, tempfile
current_dir = os.getcwd()
tmp_dir = tempfile.mkdtemp()
input_file, outfile = 'input_file', 'result'
os.system('cp %s %s' %(input_file, tmp_dir))
os.chdir(tmp_dir)
cmd = 'pwd> tmp_01.txt;ls -ltr >>tmp_01.txt' ##system command goes here
os.system(cmd)
os.system('cp tmp_01.txt %s/%s' %(current_dir, outfile))
os.chdir(current_dir)

My questions are:

Is it right or is there a simpler way to do it?
Do I need to remove the tmp directory?
Is it safe to use this code as Python module/class in a web application? Does it make shell injection easy, or can it possible reveal more information than needed?


texts:
I have written this simple DBHelper class to access a MySQL database. I am rethrowing a more generic exception so that the client side can take some action like showing a friendly message on the screen. Is it ok, or can something else be done?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MySql.Data.MySqlClient;

namespace DBLibrary
{
    public class DBHelper
    {
        private MySqlConnection _connection;
        private string _server;
        private string _database;
        private string _uid;
        private string _password;

        private MySqlCommand _command;

        public DBHelper(string server, string database, string uid, string password)
        {
            _connection = new MySqlConnection();

            _server = server;
            _database = database;
            _uid = uid;
            _password = password;

            _connection.ConnectionString = String.Format("server={0};database={1};uid={2};password={3}", _server, _database, _uid, _password);
        }

        public MySqlParameterCollection Parameters
        {
            get { return _command.Parameters; }
            set
            {
                foreach (MySqlParameter param in value)
                    _command.Parameters.Add(param);
            }
        }

        public bool OpenConnection()
        {
            try
            {
                _connection.Open();
                _command = new MySqlCommand() { Connection = _connection };
            }
            catch (MySqlException ex)
            {
                //When handling errors, you can your application's response based on the error number.
                //The two most common error numbers when connecting are as follows:
                //0: Cannot connect to server.
                //1045: Invalid user name and/or password.
                switch (ex.Number)
                {
                    case 0:
                        throw new Exception("Cannot connect to server. Contact administrator !");

                    case 1045:
                        throw new Exception("Invalid username/password. Please check your connection string and try again !");
                }
                return false;
            }
            return true;
        }

        private bool CloseConnection()
        {
            try
            {
                _connection.Close();
                _refreshCommand(null);
                return true;
            }
            catch (MySqlException ex)
            {
                if (ex.InnerException == null)
                    throw new Exception(ex.Message);
                throw new Exception(ex.InnerException.Message);
            }
        }

        public int ExecuteStoredProcedure(string name)
        {
            _command.CommandType = System.Data.CommandType.StoredProcedure;
            _command.CommandText = name;
            int count = _command.ExecuteNonQuery();

            _refreshCommand(_connection);
            return count;
        }

        private void _refreshCommand(MySqlConnection con)
        {
            _command = new MySqlCommand() { Connection = con };
        }
    }
}


texts: implementations of strncmp, strncat, strncpy

texts:
Write versions of the library functions strncpy, strncat and strncmp, which operate on the most n characters of their argument strings. For example, strncpy(s, t, n) copies at most n characters of t to s. Full Description in Appendix B.

Here is my implementation of strncmp:

int custom_strncmp(const char *s, const char *t, size_t n) {
    while(n--) {
        if(*s != *t) {
            return *s - *t;
        }
        else {
            ++s;
            ++t;
        }
    }

    return 0;
}

The while loop will run until n reaches the value 0, or until the characters that s and t point to are not equal. At each iteration I check if the *s and *t are equal; if they are, I increment s and t. If they are not equal, I return their difference.
After the loop stops, the value 0 is returned.

Here is my implementation of strncat:

char *custom_strncat(char *s, const char *t, size_t n, size_t bfsize) {
    size_t slen = strlen(s);
    char *pend = s + slen;

    if(slen + n >= bfsize)
        return NULL;

    while(n--)
        *pend++ = *t++;

    return s;
}

This version of strncat is a secure one. The first if-statement checks if there is enough space in the s buffer to store the contents of t. The while loop will run until n reaches the value 0. At each iteration the value that t points to is copied in to *s.
After the loop stops, is returned a pointer to the result.

Here is my implementation of strncpy:

char *custom_strncpy(char *s, const char *ct, size_t n) {
    char *saver = s;

    while(n--)
        *saver++ = *ct++;
    *saver = '\0';

    return s;
}

The while loop will run until n reaches the value 0, at each iteration the current character that ct points to is copied in *saver. After the loop stops, the '\0' is copied in *saver and a pointer to the result is returned.

The exercise can be found at page 121 in K&R second edition.


texts:
I am still new to VBA. I recorded several actions that I need to perform to ensure that a specific worksheet is formatted properly.

Row 1 contains headers. Other than the headers, there is no data in the sheet when this should be run. I know that the raw code from the recording can be shrunk down, but I would appreciate some assistance in figuring that out.

Sub MasterSheetFormatTest()
'
' MasterSheetFormatTest Macro
'

'
    Columns("A:A").ColumnWidth = 7
    Columns("B:B").ColumnWidth = 6
    Columns("C:C").ColumnWidth = 17.14
    Columns("D:D").ColumnWidth = 13.57
    Columns("E:E").ColumnWidth = 2.71
    Columns("F:F").ColumnWidth = 21.43
    Columns("G:G").ColumnWidth = 16.43
    Columns("H:H").ColumnWidth = 7.86
    Columns("I:I").ColumnWidth = 13.43
    Columns("J:J").ColumnWidth = 25.14
    Columns("K:K").ColumnWidth = 39.29
    Columns("L:L").ColumnWidth = 34.14
    Columns("M:M").ColumnWidth = 23.14
    Columns("N:N").ColumnWidth = 5.57
    Columns("O:O").ColumnWidth = 17.14
    Columns("P:P").ColumnWidth = 17.14
    Columns("Q:Q").ColumnWidth = 8.14
    Columns("R:R").ColumnWidth = 17.71
    Columns("S:S").ColumnWidth = 22.57
    Columns("T:T").ColumnWidth = 20.43
    Columns("U:U").ColumnWidth = 15.57
    Columns("V:V").ColumnWidth = 13.43
    Columns("W:W").ColumnWidth = 13.43
    Columns("X:X").ColumnWidth = 10.86
    Columns("Y:Y").ColumnWidth = 8.57
    Columns("Z:Z").ColumnWidth = 7.57
    Columns("AA:AA").ColumnWidth = 7.57
    Columns("AB:AB").ColumnWidth = 15
    Columns("AC:AC").ColumnWidth = 9.29
    Columns("AD:AD").ColumnWidth = 15.86
    Columns("AE:AE").ColumnWidth = 67.29
    Range("A1:AE1").Select
    Range("AE1").Activate
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    ActiveWindow.Zoom = 90
    ActiveWindow.Zoom = 80
    ActiveWindow.Zoom = 70
    Range("A2").Select
    With ActiveWindow
        .SplitColumn = 0
        .SplitRow = 1
    End With
    ActiveWindow.FreezePanes = True
End Sub


texts: Set manipulation (javascript arrays) using lodash

texts:
I'd like a more elegant and readable (if possible using functional programming style) for collection filtering (groupToAdd and groupToDelete collection handling)

Just getting rid of multiple _.findIndex() < 0 or _.indexOf() > -1 would make me happy

const {wrap} = require('co');
const _ = require('lodash');

function* manageUserOrganizations(userId, newOrgs, application, token, logger) {
    logger.debug('retrieving existing user groups');
    const userGroups = yield keycloak.getGroupsByUser(userId, token, logger);

    // determine groups operation to handle
    let groupToAdd;
    let groupToDelete;
    if (newOrgs && newOrgs.length) {
      // if some organizations to assign are provided add every one not already belonging to user
      groupToAdd = _.filter(application.subGroups, (elt) => _.findIndex(userGroups, {name: elt.name}) < 0);
      groupToAdd = _.filter(groupToAdd, (elt) => _.indexOf(newOrgs, elt.name) > -1);
      // and remove every one belonging to user but not provided  (including application itself)
      groupToDelete = _.filter(userGroups, (elt) => _.indexOf(newOrgs, elt.name) < 0);
    } else {
      // otherwise add the application itself except if it already belongs to user
      groupToAdd = _.findIndex(userGroups, {name: application.name}) > -1 ? [] : [application];
      // and remove all other existing groups
      groupToDelete = _.filter(userGroups, (elt) => elt.name !== application.name);
    }

    // handle user group assignation / removal
    yield Promise.all(_.flatten([
      groupToAdd
        .map(wrap(assignUserGroup(userId, token, logger.subProcess()))),
      groupToDelete
        .map(wrap(removeUserGroup(userId, token, logger.subProcess())))
    ]));
  }

organizations or applications are handled as groups in keycloak context

below are an example of variables values:

application.subGroups || userGroups: [{id: 665, name: 'orgName'}, {id: 667, name: 'newOrgName'}]

newOrgs: ['someOrgName', 'anotherOrgName']


texts: A1Notation conversion to row & column index

texts:
This set of Google Apps Script helper functions are published in this gist, along with a bunch of other utilities. Background info is in this SO question. Since no Google services are used, this is pure JavaScript.

What I hope to get from a code review:

General feedback on clarity & maintainability.
Is the regex in cellA1ToIndex() too big a drag on performance? What alternatives would be as-or-more functional, with better performance?

cellA1ToIndex( string cellA1, number index )

Convert a cell reference from A1Notation to 0-based indices (for arrays) or 1-based indices (for Spreadsheet Service methods).

colA1ToIndex( colA1, index )

Return a 0-based array index corresponding to a spreadsheet column label, as in A1 notation.

rowA1ToIndex( string rowA1, number index )

Return a 0-based array index corresponding to a spreadsheet row number, as in A1 notation. Almost pointless, really, but maintains symmetry with colA1ToIndex().

/**
 * Convert a cell reference from A1Notation to 0-based indices (for arrays)
 * or 1-based indices (for Spreadsheet Service methods).
 *
 * @param {String}    cellA1   Cell reference to be converted.
 * @param {Number}    index    (optional, default 0) Indicate 0 or 1 indexing
 *
 * @return {object}            {row,col}, both 0-based array indices.
 *
 * @throws                     Error if invalid parameter
 */
function cellA1ToIndex( cellA1, index ) {
  // Ensure index is (default) 0 or 1, no other values accepted.
  index = index || 0;
  index = (index == 0) ? 0 : 1;

  // Use regex match to find column & row references.
  // Must start with letters, end with numbers.
  // This regex still allows induhviduals to provide illegal strings like "AB.#%123"
  var match = cellA1.match(/(^[A-Z]+)|([0-9]+$)/gm);

  if (match.length != 2) throw new Error( "Invalid cell reference" );

  var colA1 = match[0];
  var rowA1 = match[1];

  return { row: rowA1ToIndex( rowA1, index ),
           col: colA1ToIndex( colA1, index ) };
}

/**
 * Return a 0-based array index corresponding to a spreadsheet column
 * label, as in A1 notation.
 *
 * @param {String}    colA1    Column label to be converted.
 *
 * @return {Number}            0-based array index.
 * @param {Number}    index    (optional, default 0) Indicate 0 or 1 indexing
 *
 * @throws                     Error if invalid parameter
 */
function colA1ToIndex( colA1, index ) {
  if (typeof colA1 !== 'string' || colA1.length > 2)
    throw new Error( "Expected column label." );

  // Ensure index is (default) 0 or 1, no other values accepted.
  index = index || 0;
  index = (index == 0) ? 0 : 1;

  var A = "A".charCodeAt(0);

  var number = colA1.charCodeAt(colA1.length-1) - A;
  if (colA1.length == 2) {
    number += 26 * (colA1.charCodeAt(0) - A + 1);
  }
  return number + index;
}

/**
 * Return a 0-based array index corresponding to a spreadsheet row
 * number, as in A1 notation. Almost pointless, really, but maintains
 * symmetry with colA1ToIndex().
 *
 * @param {Number}    rowA1    Row number to be converted.
 * @param {Number}    index    (optional, default 0) Indicate 0 or 1 indexing
 *
 * @return {Number}            0-based array index.
 */
function rowA1ToIndex( rowA1, index ) {
  // Ensure index is (default) 0 or 1, no other values accepted.
  index = index || 0;
  index = (index == 0) ? 0 : 1;

  return rowA1 - 1 + index;
}


texts:
I'm learning Clojure and am a rank n00b at it, trying to learn from books and online tutorials (but I'm sometimes concerned that I am picking up bad habits or at least not all the good habits). For exercise I did the Breaking the Records problem on Hackerrank.
TL;DR problem description:
For a list of scores (in historic order), count the number of times the previous best score was exceeded as well as the previous worst score was undercut.
In an iterative language it is quite easy to just iterate through the list; but Clojure does not do iteration and I decided to tackle this problem for exercise in constructing a (tail end) recursive solution. To make it easier for myself, I first did a recursive solution in Java, which I then translated. All in all, it's quite a simple recursive function without rocket surgery involved.
Obviously my code works, as shown by the included unit tests. My concerns are however as follows:

When put next to the Java code, the two look fairly similar. Did I follow "idiomatic" Clojure programming, or is it just a clumsy "word-for-word transliteration"?
Are there any areas that could have been more compact and/or easier to understand by using different Clojure constructs?

Your critical input will be highly appreciated - including regarding the unit testing, as that is arguably an important part of programming, which I want to learn and practice in parallel.
Code:
(ns hackerrank.breaking-records
  (:require [clojure.test :refer :all]))

(defrecord Record [min max countworse countbetter])

(defn recalc-record [rec newscore]
  (Record.
    (min newscore (:min rec))
    (max newscore (:max rec))
    (+ (:countworse rec) (if (> (:min rec) newscore) 1  0))
    (+ (:countbetter rec) (if (< (:max rec) newscore) 1  0))))

(defn accumulate [curr-record remaining-scores]
  (if (nil? (second remaining-scores))
    curr-record
    (recur (recalc-record curr-record (second remaining-scores)) (rest remaining-scores)))
)

(defn breaking-records [scores]
  (let [result (accumulate (Record. (first scores) (first scores) 0 0) scores)]
    (list (:countbetter result) (:countworse result))))

(deftest test-records
  (testing "edge cases"
    (is (= '(0 0) (breaking-records '())) "no games played yet")
    (is (= '(0 0) (breaking-records '(5))) "single game"))
  (testing "hackerrank examples"
    (is (= '(2 4) (breaking-records '(10 5 20 20 4 5 2 25 1))))
    (is (= '(4 0) (breaking-records '(3 4 21 36 10 28 35 5 24 42)))))
)


texts:
For a hobby project, My aim is to design and implement a generic system for pooling an arbitrary class of object. I tried implementing it using templates.
This pool should support 4 actions:
"Create a pool"
"Allocate an object from this pool"
"Deallocate an object from this pool"
"Destroy this pool"
For sake of simplicity, there is no multi-threading involved.

If I have to pool classes like this example, how do I do that?

typedef char            ByteType;
typedef void*           PointerType;
typedef char            FixedStringType[256];

// A basic struct
struct Point
{
    int x, y, z;
};

Can someone please provide your thoughts/feedback on bugs and how to improve this code?

//ObjectPool.h
#pragma once
#include <vector>
#include <iostream>

const int g_MaxNumberOfObjectsInPool = 2;

template<typename T>
class DefaultAllocator {
public:
    T* operator()() {
        return new T{};
    }
    void operator()(T* p) {
        delete p;
    }
    void reset() {
        std::cout << "reset function called from default allocator" << std::endl;
    }
};

template<typename T, typename AllocatorT=DefaultAllocator<T>>
class ObjectPool
{
    struct ObjectInfo {
        bool isInUse{};
        T* ptrObject{};
    };
    static inline std::vector<ObjectInfo> poolObjects{};
    static inline AllocatorT allocator{};
public:
    static T* getObject() {
        for (auto& currObj : poolObjects) {
            if (!currObj.isInUse) {
                currObj.isInUse = true;
                std::cout << "Existing Object returned" << std::endl;
                return currObj.ptrObject;
            }
        }

        if (poolObjects.size() == g_MaxNumberOfObjectsInPool) {
            std::cout << "Pool is full " << std::endl;
            return nullptr;
        }

        std::cout << "Creating a new object" << std::endl;
        //auto newObj = new T{};
        auto newObj = allocator();
        poolObjects.push_back({ true, newObj });
        return newObj;
    }

    static void releaseObject(T* ptrSo) {
        for (auto& currObj : poolObjects) {
            if (currObj.ptrObject == ptrSo) {
                currObj.isInUse = false;
                return;
            }
        }
    }

    static void destroy() {
        for (auto& currObj : poolObjects) {
            if (currObj.isInUse) {
                std::cout << "WARNING! this object is still in use" << std::endl;
            }
            allocator(currObj.ptrObject);
        }
        allocator.reset();
        poolObjects.clear();
    }
};

The main file looks like this:
#include "ObjectPool.h"
#include <iostream>

class PrivateClass {
    PrivateClass() {

    }
public:
    void func() {

    }
    friend class PrivateAllocator;
};

class PrivateAllocator {
public:
    PrivateClass* operator()() {
        return new PrivateClass{};
    }
    void operator()(PrivateClass* p) {
        delete p;
    }
    void reset() {
        std::cout << "reset function called" << std::endl;
    }
};

int main() {
    using integer = ObjectPool<int>;
    auto int1 = integer::getObject();
    auto int2 = integer::getObject();
    auto int3 = integer::getObject();

    integer::releaseObject(int1);
    auto int4 = integer::getObject();
    integer::destroy();
    return 0;
}


texts: Convert a double to a string containing rational and surd

texts:
First off, code:

string FracSurd(double value)
{
    //A C# 7 local function
    double GCD(double a, double b)
    {
        while (b > 0)
        {
            var rem = a % b;
            a = b;
            b = rem;
        }
        return a;
    }
    for (int i = 0; i <= 1e6; i++)
    {
        var SubjectToTest = value / Math.Sqrt(i);
        for (var denom = 1.0; denom <= 500; denom++)
        {
            var numer = Math.Round(SubjectToTest * denom);
            if (SubjectToTest - numer / denom == 0)
            {
                int Square = 1, a = i;
                for (int b = 2; a > 1; b++)
                    if (a % b == 0)
                    {
                        int x = 0;
                        while (a % b == 0)
                        {
                            a /= b;
                            x++;
                        }
                        //Console.WriteLine("{0} is a prime factor {1} times!", b, x);
                        for (int j = 2; j <= x; j += 2) Square *= b;
                    }
                var LCM = GCD(numer, denom);
                numer /= LCM;
                denom /= LCM;
                var Builder = new System.Text.StringBuilder(numer.ToString());
                Builder.Append(" / ").Append(denom).Append(" √");
                foreach (var Char in (i / Square).ToString())
                {
#if WINDOWS_UWP
                    Builder.Append("̅");
                    Builder.Append(Char);
#else
                    Builder.Append(Char);
                    Builder.Append("̅");
#endif
                }
                return Builder.ToString();
            }
        }
    }
    throw new ArithmeticException("Cannot find appropiate fraction and surd.");
}

The code contains a lot of loops. How can I increase its performance so I can expand its range of input?


texts: Sort a list of pairs representing an acyclic, partial automorphism

texts:
I have this sample data:

let trips = [
  {
    from: "DEN",
    to: "JFK"
  },
  {
    from: "SEA",
    to: "DEN"
  },
  {
    from: 'JFK',
    to: 'SEA'
  },
];

and my origin is 'JFK', I want to sort the list by how I have traveled. So for instance, this should be the end result:

let trips = [
  {
    from: 'JFK',
    to: 'SEA'
  },
  {
    from: "SEA",
    to: "DEN"
  },
  {
    from: "DEN",
    to: "JFK"
  },
];

My solution works but it's not very well written, but I tried!

function sortByLinked(trips, origin = 'JFK') {
  let sortedArray = [];

  let first = trips.filter(trip => trip.from === origin)[0];
  sortedArray.push(first);

  for(var i = 0; i < trips.length; i++) {
    if(sortedArray[0].to === trips[i].from) {
      sortedArray.push(trips[i]);
    }
  }

  for(var i = 0; i < trips.length; i++) {
    if(sortedArray[1].to === trips[i].from) {
      sortedArray.push(trips[i]);
    }
  }

  return sortedArray;
}

sortByLinked(trips)


texts: http url connection with kotlin on android

texts:
I'm making an http call from an android app and want to have it reviewed for brevity and efficiency. It handles both success and error streams, by contract 200 OK is enforced (not 201 created other codes etc.)
class UserNetwork() {

    fun findAll(): ArrayList<User>? {
        val url = URL("http:///10.0.2.2:8080/employees")
        val connection = url.openConnection() as HttpURLConnection
        connection.setRequestProperty("Accept", "application/json");

        var users: ArrayList<User>? = null

        (if (connection.responseCode == 200) connection.inputStream else connection.errorStream).use { stream ->
            BufferedReader(InputStreamReader(stream)).use { reader ->
                val response = StringBuffer()
                users = arrayListOf()

                @Suppress("ControlFlowWithEmptyBody")
                while ((reader.readLine().also { response.append(it) }) != null) {}

                val body = JSONArray(response.toString())
                for (i in 0 until body.length()) {
                    users?.add(User(body.getJSONObject(i)))
                }
            }
        }

        return users
    }
}

User data object.
data class User(var id: Long? = null, var first: String? = null, var last: String? = null): Parcelable {

    constructor(data: JSONObject) : this() {
        id = data.getLong("id")
        first = data.getString("first")
        last = data.getString("last")
    }
}

Test class (testing method for findAll)
class UserNetworkTest {
    @Test
    fun testFindAll() {
        val users = userProxy.findAll()
        assertEquals(3, users!!.size)
        users.forEach { user ->
            assertNotNull(user.id)
            assertNotNull(user.first)
            assertNotNull(user.last)
        }
    }
}


texts:
I have the following function for turning on some ports on a piece of hardware:

public Boolean SwitchOn(Int32 portNumber)
    {
        HttpCommandBuilder builder = new HttpCommandBuilder(_ipAddress);
        builder.Command = HttpCommandBuilder.CommandType.SetPower;

        String result;

        if (portNumber == 1)
        {
            builder.Port1 = true;
            result = SendCommand(builder.GenerateUrl());

            if (String.IsNullOrEmpty(result))
            {
                return false;
            }
            else if (result.IndexOf("p61=1") == -1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else if (portNumber == 2)
        {
            builder.Port2 = true;
            result = SendCommand(builder.GenerateUrl());

            if (String.IsNullOrEmpty(result))
            {
                return false;
            }
            else if (result.IndexOf("p62=1") == -1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else if (portNumber == 3)
        {
            builder.Port3 = true;
            result = SendCommand(builder.GenerateUrl());

            if (String.IsNullOrEmpty(result))
            {
                return false;
            }
            else if (result.IndexOf("p63=1") == -1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else if (portNumber == 4)
        {
            builder.Port4 = true;
            result = SendCommand(builder.GenerateUrl());

            if (String.IsNullOrEmpty(result))
            {
                return false;
            }
            else if (result.IndexOf("p64=1") == -1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            throw new ArgumentException("Invalid port number: " + portNumber);
        }
    }

It has a low maintainability index and there's a lot of copy and pasting going on and I am doing a similar, repetitive action for each port.

I know it's not a very elegant solution so I am looking for any advice and suggestions on how I could re-factor this function to improve its maintainability score.


texts:
I would make a filter to filter my data using next parameters:

First name
Last name
Language
Profile
A minimum date of registration
A maximum date of registration
Success

All filter options are not required for the user. Here could you find my C# code.

private IEnumerable<Registration> Filter(string voornaam,   // first name
                                         string achternaam, // last name
                                         int? language,
                                         int? profiel,      // profile
                                         DateTime? vanaf,   // min date
                                         DateTime? tot,     // max date
                                         bool? geslaagd)    // success
{
    IEnumerable<Registration> all = All(); // <-- this gets all registrations from
                                           //       the database.

    if (!string.IsNullOrEmpty(voornaam))
    {
        all = (from r in all
               where r.FirstName.ToLower().StartsWith(voornaam.ToLower().Trim())
               select r).ToList();
    }

    if (!string.IsNullOrEmpty(achternaam))
    {
        all = (from r in all
               where r.LastName.ToLower().StartsWith(achternaam.ToLower().Trim())
               select r).ToList();
    }

    if (language != null)
    {
        all = (from r in all
               where r.LanguageId == language.Value
               select r).ToList();
    }

    if (profiel != null)
    {
        all = (from r in all
               where r.ProfileId == profiel.Value
               select r).ToList();
    }

    if (vanaf != null)
    {
        all = (from r in all
               where r.RegistrationDate >= vanaf.Value
               select r).ToList();
    }

    if (tot != null)
    {
        all = (from r in all
               where r.RegistrationDate <= tot.Value
               select r).ToList();
    }

    if (geslaagd != null)
    {
        all = (from r in all
               where r.Success == geslaagd.Value
               select r).ToList();
    }

    return all;
}

The function All() gets all the registrations from the database. Next I check if the attributes are not null (or empty for the strings) and if true I set the variable all equal to the return values of the linq query's. After all I return all and load my view.

This code works for all possibilities and got a low fail percentage. Of course my code is too long and will make this code shorter. How could I do this?


texts: Possible improvements to Risk board game?

texts:
Enter risk!
This program will roll dice for the game of Risk. The initial input is two numbers separated by a space and if the attackers wish to do a blitz they can add one more space and an "!" to get a positive attack modifier but are committed for an all or nothing fight.
package riskdieroll;
import java.awt.Component;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.JOptionPane;
public class RiskDieRoll
{
    private static Component frame;
    public static void main(String[] args)
    {
        int spcCnt, atck1, dfnc1, rollCnt, atck2 = 0, dfnc2 = 0, valHold, atckMod;
        String intInpt, Lsr;
        while(true)
        {
            boolean k = false;
            Lsr = "";
            intInpt = JOptionPane.showInputDialog("Please enter the a"
                    + "mount of attackers then the number of\ndefenders separa"
                    + "ted by a space.", atck2 + " " + dfnc2);
            spcCnt = rollCnt = 0;
            valHold = intInpt.length();
            atckMod = 6;
            if("0 0".equals(intInpt))
            {
                break;
            }
            for(int i = 0; intInpt.charAt(i) != ' '; i++)
            {
                spcCnt++;
            }
            atck2 = atck1 = (int)Double.parseDouble(intInpt.substring(0 , spcCnt));
            if(intInpt.charAt(valHold - 1) == '!')
            {
                k = true;
                atckMod = 7;
                valHold -= 2;
            }
            dfnc2 = dfnc1 = (int)Double.parseDouble(intInpt.substring(spcCnt + 1 , valHold));
            Integer[] z = new Integer[3], y = new Integer[2];
            if(atck1 < 2)
            {
                JOptionPane.showMessageDialog(frame, "INVALID ATTACK! You need"
                        + " at least two armys to make an attack!");
                atck2 = dfnc2 = 0;
            }
            else if(dfnc1 < 1)
            {
                JOptionPane.showMessageDialog(frame, "INVALID INPUT! There must"
                        + " be at least one defending army!");
                atck2 = dfnc2 = 0;
            }
            else
            {
                do
                {
                    rollCnt = 0;
                    for(int i = 0; i < 3; i++)
                    {
                        z[i] = (int)Math.ceil(Math.random() * atckMod);
                    }
                    for(int i = 0; i < 2; i++)
                    {
                        y[i] = (int)Math.ceil(Math.random() * 6);
                    }
                    Arrays.sort(z, Collections.reverseOrder());
                    Arrays.sort(y, Collections.reverseOrder());
                    while(dfnc2 > 0 && rollCnt < 2 && atck2 > 1)
                    {
                        if(y[rollCnt] >= z[rollCnt])
                        {
                            atck2--;
                        }
                        else
                        {
                            dfnc2--;
                        }
                        rollCnt++;
                    }
                }while(k && (dfnc2 > 0 && atck2 > 1));
                if(dfnc2 < 1)
                {
                    Lsr = "\n\nDefenders have lost!!";
                }
                else if(atck2 < 2)
                {
                    Lsr = "\n\nAttackers have been repelled!!!";
                }
                JOptionPane.showMessageDialog(frame, "Attacking force now at "
                        + atck2 + " (Lost " + (atck1 - atck2) + ")" + "\nDefence force now "
                        + "at " + dfnc2 + " (Lost " + (dfnc1 - dfnc2) + ")" + Lsr);
                if(!"".equals(Lsr))
                {
                    atck2 = dfnc2 = 0;
                }
            }
        }
    }
}


texts:
The code snippet is what I want to do. Previously I use a different version of my code. But it is out of joint according to Python coding guidelines because I was assigned my lambda function to a variable. It was an obvious violation. Here is my violator code:

my_dict = {
    'first_name': 'Jimmy Floyd',
    'last_name': 'Hasselbaink'
}

db_data = {}

def create_info(db_data, data):
    split_join = lambda field: '_'.join(data.get(field).split()) if field in data else None
    name = split_join('name')
    first_name = split_join('first_name')
    last_name = split_join('last_name')
    code = '_'.join(filter(None, [name, first_name, last_name])).lower()
    db_data['code'] = code
    return db_data

Then I have extracted my split_join variable to a method. The code is below:

my_dict = {
    'first_name': 'Jimmy Floyd',
    'last_name': 'Hasselbaink'
}

db_data = {}

def split_join(data, field):
    return '_'.join(data.get(field).split()) if field in data else None

def create_info(db_data, data):
    name = split_join(data, 'name')
    first_name = split_join(data, 'first_name')
    last_name = split_join(data, 'last_name')
    code = '_'.join(filter(None, [name, first_name, last_name])).lower()
    db_data['code'] = code
    return db_data

new_db_data = create_info(db_data, my_dict)
print(new_db_data)

I have forced into writing split_join method in three times. Is there any way to prevent this situation?


texts: Project Euler #9: Finding Pythagorean triplets with a given sum

texts:
Problem statement:
A Pythagorean triplet is a set of three natural numbers, A < B < C, for which, A² + B² = C².
Given a number N, check if there exists any Pythagorean triplet for which A + B + C = N.
public class SpecialPythagoreanTriplet {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int t = scan.nextInt();
    int n=0, i=0, j=0, a=0, b=0, c=0;

    while(t!=0) {
        n = scan.nextInt();
        a=0; b=0; c=0;
        for(i=1; i<n; i++)
            for(j=(i+1); j<=n; j++) {
                //These two loops run to take a pair of numbers. j=(i+1) to avoid repetitions in the future.
                if(isSquare((i*i) + (j*j))) //check if a number is a square
                    if(((int)Math.sqrt((i*i)+(j*j)) + i + j) == n) {
                        a = i;
                        b = j;
                        c = (int)Math.sqrt((i*i)+(j*j));
                    }
            }
        if(c==0)
            System.out.println(-1);
        else
            System.out.println(a*b*c);
        t--;
    }
    scan.close();
}

static boolean isSquare(double t) {
    int a = (int)Math.sqrt(t);
    if(a*a == t)
        return true;
    else
        return false;
}
}

I was working on this program in ProjectEuler and Hackerrank consecutively. It ran perfectly for the input of 1000 and got accepted in Project Euler. But it is giving Terminated Due to Timeout error in most of the cases in Hackerrank.
How can I optimize it more to evade this error?


texts:
I'm trying to figure out a better way to structure some of my code so that I don't have a ton of conditionals here. I have a series of checkboxes that someone authors on the backend and if they are checked I set a variable with a specific value. I then use that variable and set options in my jQuery plugin. This works just fine but there's got to be a better way as oppose to having all these conditionals. Is there someway I could create a loop or something similar?

<c:if test="${prop.article}">
  <c:set var="contentArticle" value="blog"/>
</c:if>

<c:if test="${prop.quote}">
  <c:set var="contentQuote" value="cited"/>
</c:if>

<c:if test="${prop.music}">
  <c:set var="contentMusic" value="itunes"/>
</c:if>

<c:if test="${prop.money}">
  <c:set var="contentMoney" value="money"/>
</c:if>

<c:if test="${prop.check}">
  <c:set var="contentCheck" value="check"/>
</c:if>

<c:if test="${prop.charge}">
  <c:set var="contentCharge" value="visa"/>
</c:if>

<script>
$(document).ready(function () {
    $('.gallery').sourcesPlugin({
        media: '${contentArticle},${contentQuote},${contentMusic}',
        payment: '${contentMoney},${contentCheck},${contentCharge}',
    });
});
</script>


texts:
So, I wanted a separate project to act as the data layer for my website project.

Classes in the website should reference the data layer after getting input from the user and should get back information regarding the result of whatever actions are performed and then communicate those results to the user.

The following is an example of how I've got it set out. This example deletes a user record from the database:

// Website/Admin/Users.aspx.cs
protected void btnDelete_Click(object sender, EventArgs e)
{
    User us = new User(Convert.ToInt32(Session["ActionUserID"]));

    if (us.Delete())
    {
        lblResult.Text = "User record was successfully deleted.";
    }
    else
    {
        lblResult.Text = us.errmsg;
    }
}

// Website/App_Code/User.cs
//
// For simplicity sake, I've removed code that isn't needed in this example
public int userid { get; protected set; }
public string errmsg { get; protected set; }

public User(int UserID)
{
    userid = UserID;
}

public bool Delete()
{
    OrtundUser ou = new OrtundUser(userid);
    if (ou.Delete())
    {
        return true;
    }
    else
    {
        errmsg = ou.errmsg;
        return false;
    }
}

// DataProject/OrtundUser.cs
public int userid { get; protected set; }
public string errmsg { get; protected set; }

OrtundData od = new OrtundData(); // instantiate the DbContext

public OrtundUser(int UserID)
{
    userid = UserID;
}

public bool Delete()
{
    try
    {
        var user = (from u in od.users
                    where u.userid == userid
                    select u).FirstOrDefault();

        if (user != null)
        {
            od.Remove(user);
            od.SaveChanges();

            return true;
        }
    }
    catch (Exception ex)
    {
        errmsg = ex.InnerException;
        return false;
    }
}

I feel like there's a lot of repetition of code here. I know this will work as intended, but I don't know if it's as efficient as it could be. (for example, the KISS principle would argue the existence of App_Code/User.cs at all ... why not just reference the DataProject directly?)

If anyone can provide any suggestions for me to improve this (particularly with a look at removing redundant code) - possibly explaining any concepts that I may seem to be misunderstanding - I'd really appreciate it.


texts:
I'm currently working in the math library for a game framework that I'm writing and am working to improve some functionality that was affected during a refactor.

Formerly, my Matrix4.SwapColumns(int, int) function looked like this:

/// Documentation
public void SwapCols(int i, int j)
{
    for(int k = 0; k < 4; k++)
    {
        temp = this[k][i];
        this[k][i] = this[k][j];
        this[k][j] = temp;*/
    }
}

This worked because Matrix4[x][y] was a two-dimensional float array, which could be accessed and changed in one step. Now, since I'm using a new version of the operator as follows:

public Vector4 this[int a]
{
    get
    {
        if (a > 3 || a < 0) return Vector4.Zero;
        return (a == 0 ? row1 : (a == 1 ? row2 : (a == 2 ? row3 : row4)));
    }
    set
    {
        if (a == 0) row1 = value;
        else if (a == 1) row2 = value;
        else if (a == 2) row3 = value;
        else if (a == 3) row4 = value;
    }
}

The original method is no longer possible since the values that are part of the Vector4 are immutable, due to a C# language feature relating to properties (which I usually love having, since it makes sure you don't think you're reassigning the variable in one call to the properties' actual method implementations).

Here's the code review I need. Essentially, the new SwapColumns method looks like this:

/// Documentation
public void SwapCols(int i, int j)
{
    // New arguement checking goes here
    int[] indicies = new int[] { 0, 1, 2, 3 };
    indicies[i] = j;
    indicies[j] = i;

    Vector4 tempRow = Vector4.Zero;

    int[] positions = new int[4];
    for (int row = 0; row < 4; row++)
    {
        tempRow = this[row];
        for (int col = 0; col < 4; col++)
        {
            if (indicies[col] != col)
            {
                tempRow[col] = this[row][indicies[col]];
            }
        }
        this[row] = tempRow;
    }
}

Without changing the fact that my Matrix4[] returns a Vector4, since that API needs to stay the same, how can I improve this SwapCols method?


texts: Identifying the missing number in an array

texts:
This is from LeetCode:

  Missing Number

  Given an array containing n distinct numbers taken from 0, 1, 2, ...,
  n, find the one that is missing from the array.

  Example 1:

  Input: [3,0,1]
  Output: 2

  Example 2:

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

  Note: Your algorithm should run
  in linear runtime complexity. Could you implement it using only
  constant extra space complexity?

Code:

def missing_number(nums)
    nums.empty? ? 0 : nums.inject(:^)^(1..nums.length).inject(:^)
end


texts: Checking which pypi packages are Py3k-only

texts:
I looked at the pypi classifiers and some guide to help me write the following script, and here's me wondering if it can be improved:

import xmlrpc.client

# pypi language version classifiers
PY3 =  ["Programming Language :: Python :: 3"]
PY2 =  ["Programming Language :: Python :: 2"]
PY27 = ["Programming Language :: Python :: 2.7"]
PY26 = ["Programming Language :: Python :: 2.6"]
PY25 = ["Programming Language :: Python :: 2.5"]
PY24 = ["Programming Language :: Python :: 2.4"]
PY23 = ["Programming Language :: Python :: 2.3"]

def main():
    client = xmlrpc.client.ServerProxy('http://pypi.python.org/pypi')

    # get module metadata
    py3names = [name[0] for name in client.browse(PY3)]
    py2names = [name[0] for name in client.browse(PY2)]
    py27names = [name[0] for name in client.browse(PY27)]
    py26names = [name[0] for name in client.browse(PY26)]
    py25names = [name[0] for name in client.browse(PY25)]
    py24names = [name[0] for name in client.browse(PY24)]
    py23names = [name[0] for name in client.browse(PY23)]

    cnt = 0
    for py3name in py3names:
        if py3name not in py27names \
           and py3name not in py26names \
           and py3name not in py25names \
           and py3name not in py24names \
           and py3name not in py23names \
           and py3name not in py2names:
            cnt += 1

    print("Python3-only packages: {}".format(cnt))

main()

Sidenote:

$ time python3 py3k-only.py
Python3-only packages: 259

real    0m17.312s
user    0m0.324s
sys 0m0.012s

In addition, can you spot any functionality bugs in there?  Will it give accurate results, assuming that pypi has correct info?


texts: Unit tests for methods that access the file system

texts:
Basically I have some methods that access the file system and to avoid that in the unit test I have broken those sections out into a protected virtual method. In the Unit Test I then use Moq to setup those protected methods the way I want. I am just curious if I am going about this correctly or is there a better way? Below is an example method I have done this with however I have several places I do this with.

Method that gets unit tested:

public IEnumerable<ConfigProfile> GetSavedProfiles(string product)
    {
        if(string.IsNullOrEmpty(product))
        {
            throw new ArgumentNullException("product");
        }

        string profileDirectory = _factory.GetCustomProfileDirectory(product);
        List<ConfigProfile> profiles = Enumerable.Empty<ConfigProfile>().ToList();

        _logger.Debug("Getting Saved profiles.");

        IList<FileInfo> files = GetProfilesInDirectory(profileDirectory).ToList();

        if (!files.Any())
        {
            _logger.Debug(string.Format("No custom profiles found for {0}.", product));
            return profiles;
        }

        profiles.AddRange(files.Select(LoadProfile));

        return profiles;

    }

Then I have these two protected methods I have taken out and setup in my unit test:

protected virtual IEnumerable<FileInfo> GetProfilesInDirectory(string directory)
    {
        DirectoryInfo files = new DirectoryInfo(directory);

        return files.EnumerateFiles("*.ecu");
    }

protected virtual ConfigProfile LoadProfile(FileInfo file)
    {
        ConfigProfile profile;
        using (FileStream stream = new FileStream(file.FullName, FileMode.Open))
        {
            profile = _serializer.DeserializeFromDisk(stream);
        }
        return profile;
    }


texts:
For experimental and learning purposes. I was trying to create a sorting algorithm from a hash function that gives a value biased on alphabetical sequence of the string, it then would ideally place it in the right place from that hash.

The reasoning is that theoretically if done right this algorithm can achieve O(n) speeds or nearly so.

So here is what I have worked out in python so far:

letters = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,
'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,
's':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25,
'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,
'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,
'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25}

def sortlist(listToSort):
    listLen = len(listToSort)
    newlist = []
    for i in listToSort:
        k = letters[i[0]]
        for j in i[1:]:
            k = (k*26) + letters[j]
        norm = k/pow(26,len(i)) # get a float hash that is normalized(i think thats what     it is called)

        # 2nd part
        idx = int(norm*len(newlist)) # get a general of where it should go
        if newlist: #find the right place from idx
            if norm < newlist[idx][1]:
                while norm < newlist[idx][1] and idx > 0: idx -= 1
                if norm > newlist[idx][1]: idx += 1
            else:
                while norm > newlist[idx][1] and idx < (len(newlist)-1): idx += 1
                if norm > newlist[idx][1]: idx += 1
        newlist.insert(idx,[i,norm])# put it in the right place with the "norm" to ref     later when sorting
    return newlist

I think that the 1st part is good, but the 2nd part needs help. so the Qs would be what would be the best way to do something like this or is it even possible to get O(n) time (or near that) out of this?

The testing I did with an 88,000 word list took prob about 5 min, 10,000 took about 30 sec it got a lot worse as the list count went up.

If this idea actually works out then I would recode it in C to get some real speed and optimizations.

Thank for any advice that you could give.


texts: Callback/Promises implementation for a boolean check

texts:
Currently I have the following callback system:

var saveTask = function(err, result) {
    if (err) return callback(err, result);

    var newid = mongoose.Types.ObjectId();
    var task = new Task({
        _id: newid,
        taskname: req.body.name,
        teamid: req.body.team,
        content: req.body.content,
        creator: req.user.userId
    });

    task.save(function (err) {
        if (!err) {
            log.info("New task created with id: %s", task._id);
            return callback(null, task);
        } else {
            if(err.name === 'ValidationError') {
                return callback('400', 'Validation error');
            } else {
                return callback('500', 'Server error');
            }
            log.error('Internal error(%d): %s', res.statusCode, err.message);
        }
    });
};

if (req.body.team) {
    valTeam.isMember(req.body.team, req.user._id, function (err, done) {
        if (err) {
            saveTask('403', 'Not the owner or member of this team');
        } else {
            saveTask(null, true);
        }
    });
} else {
    saveTask(null, true);
}

valTeam.isMember

exports.isMember = function(teamid, userid, callback) {
    Team.find({'_id':teamid, $or:[{'creator': userid }, {'userlist': { $in : [userid]}}]}, function(err, result) {
            if (err) return err;
            console.log(result);
            if (!result.length)
                return callback('404', false);
            else
                return callback(null, true);
    });
}

In short, if team is sent by POST, I'm checking if the user is member of that ID in valTeam.isMember. Am I using the correct syntax and best method to call back my saveTask function to save the task if the user is part of the team?

This code currently works, but I feel like there should be an easier way to do it? How could I use a promise to achieve the same thing?

Thanks in advance.


texts:
I wrote this Fortran module and I need its subroutines to run as fast as possible. My hope is to get some advice to optimize this code, and after having the serial version running as fast as it can run I will use MPI to make it parallel.

Module smearingmodule
IMPLICIT NONE
contains
subroutine smearing(i, nMCd, nPeriodT, nPeriods, DF, theta, wm) bind(C, name="smearing_")
    use, intrinsic                         :: iso_c_binding, only : c_double, c_int
    integer(c_int), intent(in)                                 :: i, nMCd, nPeriods
    integer(c_int), intent(in), dimension(nPeriods)            :: nPeriodT
    real(c_double), intent(in), dimension(i,5)        :: DF
    real(c_double), intent(in), dimension(i,nMCd)     :: theta
    real(c_double), dimension(nMCd, nPeriods), intent(out)  :: wm
    integer                                             :: d

    do d=1,nMCd
        CALL subsmearing(d, i, nMCd, nPeriodT, nPeriods, DF, theta, wm(d,:))
    end do

end subroutine smearing

subroutine subsmearing(d, i, nMCd, nPeriodT, nPeriods, DF, theta, wm)
    integer, intent(in)                                 :: d, i, nMCd, nPeriods
    integer, intent(in), dimension(nPeriods)            :: nPeriodT
    double precision, intent(in), dimension(i,5)        :: DF
    double precision, intent(in), dimension(i,nMCd)     :: theta
    double precision, dimension(nPeriods), intent(out)  :: wm
    double precision, allocatable, dimension(:,:)       :: out
    double precision, dimension(i,8)                    :: bigDF
    double precision, dimension(i)                      :: epredC, epredT, diff, A1, A2
    double precision, dimension(i,i)                    :: B1, B2
    integer                                             :: j, Period, jj
    double precision                                    :: sumWeights

    diff = 0.0d0
    wm = 0.0d0
    epredC = exp(DF(:,4) + (theta(:,d) * DF(:,1)))
    epredT = exp(DF(:,4) - (theta(:,d) * (1-DF(:,1))))

    do j=1,i
        B1(:,j)=epredT(j)
        B2(:,j)=epredC(j)
    end do

    A1 = matmul(DF(:,5), B1)
    A2 = matmul(DF(:,5), B2)

    diff = (A1-A2)/DBLE(i)

    bigDF(:,1:5) = DF
    bigDF(:,6) = epredC
    bigDF(:,7) = epredT
    bigDF(:,8) = diff

    do jj =1, nPeriods
        ALLOCATE(out(nPeriodT(jj),7))
        CALL subsetPeriod(bigDF, i, 8, nPeriodT(jj), jj, out) !Filters data
        sumWeights = sum(out(:,2))
        do j=1, nPeriodT(jj)
            wm(jj) = wm(jj) + (out(j,7)*out(j,2)/sumWeights)
        end do
        DEALLOCATE(out)
    end do

end subroutine subsmearing

subroutine subsetPeriod(A, rowA, colA, rowB, Period, B)
    integer, intent(in)                                    :: rowA, colA, rowB, Period
    double precision, dimension(rowA, colA), intent(in)    :: A
    double precision, dimension(rowB,colA-1), intent(out)  :: B
    integer                                                :: i, pos

    pos = 1
    do i = 1, size(A,1)
        if(A(i,2)==Period)then
            B(pos,1) = A(i,1)
            B(pos,2:) = A(i,3:)
            pos = pos+1
        end if
    end do
end subroutine subsetPeriod

end module smearingmodule

DF is going to be millions by 5, theta millions by 4000. That is why I want to optimize the code and make it parallel.

Ultimately, I will be calling this code from R.

Link in case you are curious about smearing


texts: How do I simplify the following slice of a Makefile?

texts:
Considering the following Makefile:

%.o: %.cpp
    $(C) $(CF) -c $< -o $@

Audio/%.o: Audio/%.cpp
    $(C) $(CF) -c $< -o $@

Game/%.o: Game/%.cpp
    $(C) $(CF) -c $< -o $@

Generation/%.o: Generation/%.cpp
    $(C) $(CF) -c $< -o $@

Input/%.o: Input/%.cpp
    $(C) $(CF) -c $< -o $@

Particle/%.o: Particle/%.cpp
    $(C) $(CF) -c $< -o $@

Screen/%.o: Screen/%.cpp
    $(C) $(CF) -c $< -o $@

Utility/%.o: Utility/%.cpp
    $(C) $(CF) -c $< -o $@

How can I simplify it so that it only depends on a list of directories, such as:

SUBD = Audio/\
 Game/\
 Generation/\
 Input/\
 Particle/\
 Screen/\
 Utility/