texts: Determining if f(n) = n^2 + 3n + 5 is ever divisible by 121

texts:
Given the following problem:

  It is conjectured that for any \$n > 0\$, \$n^2 + 3n + 5\$ is never
  divisible by 121. Test this conjecture for \$n = 1,2,...,9999,10000\$.

I wrote the following solution:

(defpackage :one-twenty-one-divisible (:use :cl))
(in-package :one-twenty-one-divisible)

(defun divisible (n) (= (mod n 121) 0))
(defun f_n (n) (+ (expt n 2) (* 3 n) 5))

(let ((divisible-result (loop for n from 1 to 10000 when (divisible (f_n n)) collect n)))
  (format t "The conjecture that for 1 <= n <= 10,000 f(n) = n^2 + 3n + 5 is indivisible by 121 is ~:[false~;true~].~%" (null divisible-result))
  (unless (null divisible-result) (format t "The following items were found to have f(n) that is divisible by 121: ~a ~%" divisible-result)))

What do you think?


texts:
I have a LINQ query that I am having trouble optimizing and takes about 5.5 seconds to run. I am using a view called StaffingResourceData and a table called StaffingForecasts.

Each StaffingResource has a ResourceId, a Division, and a Type. A StaffingForecast has a ResourceId, Project, Date (represents a Monday of a week), Hours. A StaffingResource can have 0-many StaffingForecasts.

For each StaffingResource, I need a list of their total forecasted hours for the next 12 weeks. Here is what I have right now:

// Get list of dates
var dates = new List<DateTime>();
var start = Utilities.GetStartOfWeek(DateTime.Today);
for (var i = 0; i < 12; i++)
{
    dates.Add(start.AddDays(i * 7));
}
var end = dates[11];

// Get resources
var resources = (from r in context.StaffingResourceDatas
                 where r.EmployeeId != null
                     && !exclusionList.Contains(r.ResourceTitleId)
                 join f in context.StaffingForecasts.Where(x => x.Date >= start && x.Date <= end) on r.ResourceId equals f.ResourceId into g1
                 from f in g1.DefaultIfEmpty()
                 group new { f.Date, f.Hours } by r into g2
                 select new ChartResourceModel
                 {
                     ResourceId = g2.Key.ResourceId,
                     Division = g2.Key.ResourceDivision,
                     Type = g2.Key.ResourceType,
                     Dates = dates.Select(d => new ChartDateModel
                     {
                         Date = d,
                         Available = (g2.Where(f => f.Date == d).Any() ? g2.Where(f => f.Date == d).Sum(f => f.Hours) : 0) < 24
                     }).ToList()
                 })
               .ToList();

Any ideas on how I could speed this up?


texts: Program that finds prime numbers in a specific range

texts:
I'm kinda new to programming, and as a solution to an exercise, I made a program to find prime numbers in a range. It runs just right for small ranges of numbers, but for this exercise we are given a high range of nums, and it just takes much time to finish examining. Any suggestions how can I make it faster?

#include <stdio.h>

#define START 190000000
#define END 200000000

int main()
{
    int primenum = 0, i = 0, j = 0, c = 0;
    for (i = START; i <= END; i++)
    {
        printf("EXMINING %d\r\n", i);
        c = 2;
        for (j = 2; j <= i-1; j++)
        {
            if (i%j == 0)
            {   c=1;
                break;
            }
        }
        if (c == 2) primenum = primenum + 1;
        printf("Prime Numbers Found so far: %d\r\n", primenum);
    }
    printf("THE PRIME NUMBERS ARE %d", primenum);
    return 0;
}


texts: Finding a string in a text file and reporting full file name and size

texts:
I have the following script to find files containing a certain string and then report on the location of the file along with the size in bytes.

It works, but I seem to have made heavy weather of finding the string which involves a fair bit of tidying up afterwards to produce some clean output.

Any idea how I could make this more concise?

# Ignore errors
$ErrorActionPreference= 'silentlycontinue'

# Grab user options
$ext = Read-Host -Prompt        "Enter extension   "
$huntString = Read-Host -Prompt "Enter hunt string "

# Find text files (.log, .txt etc) containing the hunt string
$entries = gci -recurse -include *.$ext -ErrorAction SilentlyContinue | select fullname, length | sort -property length

echo ''
foreach ($e in $entries)
{
    # Find files containing the hunt string
    $foundFile = (gci $e.fullname | select-string $huntString | measure-object | findstr Count)

    # Output hit count along with size and name
    $rawOutput = $foundFile.ToString() + $e.Length.ToString().PadRight(10,[char]32) + "`t" + $e.fullname

    # Only output entries with a hit count
    $cleanOutput = echo $rawOutput | select-string ": 1"

    # Remove hit count
    $finalOutput = $cleanOutput -replace "Count","" -replace ": ",""

    # Trim and output
    echo $finalOutput.TrimStart()
}


texts: PHP page to edit a user account information and avatar

texts:
I wanted to ask your opinion about my code created for acccount.php page for editing the data of each logged-in user.

I wanted to have more of an opinion on your right syntax, though maybe it could be improved.

    require('includes/config.php');

//if not logged in redirect to login page
if(!$user->is_logged_in()) {
    redirect('login.php');
}

//define page title
$title = 'Account';

//include header template
require('layout/header.php');

//submit post
if (isset($_POST['location'], $_POST['bio'], $_POST['relationship'], $_POST['interested'], $_POST['work'], $_SESSION['username'])) {
    try {
    //query update
    $stmt = $db->prepare("UPDATE members SET location = ?, bio = ?, relationship = ?, interested = ?, work = ? WHERE username = ?");
    $stmt->execute([$_POST['location'], $_POST['bio'], $_POST['relationship'], $_POST['interested'], $_POST['work'], $_SESSION['username']]);
      $message = $lang['update-profile-success']; //success message
    } catch(PDOException $e) {
    $message = $lang['update-profile-error']; //error message
    }
  }

// ******************  AVATAR  *************************
//choosing the avatar:
    if(isset($_POST['upload']))
    {

        $imgFile = $_FILES['avatar']['name'];
        $tmp_dir = $_FILES['avatar']['tmp_name'];
        $imgSize = $_FILES['avatar']['size'];

        if(empty($imgFile)){
            $message = "Please Select Image File.";
        }
        else
        {
            $upload_dir = 'avatar/'; // upload directory

            $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

            // valid image extensions
            $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

            // rename uploading image
            $userpic = rand(1000,1000000).".".$imgExt;

            // allow valid image file formats
            if(in_array($imgExt, $valid_extensions)){
                // Check file size '5MB'
                if($imgSize < 5000000)              {
                    move_uploaded_file($tmp_dir,$upload_dir.$userpic);
                }
                else{
                    $message = "Sorry, your file is too large.";
                }
            }
            else{
                $message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            }
        }

        // if no error occured, continue ....
        if(!isset($message))
        {

        $edit = $db->prepare("UPDATE members SET user_avatar = :avatar WHERE username ='" . $_SESSION['username'] . "'");
        $edit->bindParam(':avatar', $userpic);
        $row['user_avatar'] = $userpic;

            if($edit->execute())
            {
                $message = "Avatar updated...";
                header("refresh:5;account.php"); // redirects image view page after 5 seconds.
            }
            else
            {
                $message = "Error...";
            }
        }
    }

//run data form
$sql = $db->prepare("SELECT * FROM members WHERE username = ?");
$sql->execute([$_SESSION['username']]);
$row = $sql->fetch();


texts:
I have coded the following C function for multiplying two NxN matrices and using AVX vectors to speed up the calculation. It works but the speedup is not what is to be expected(some scalar code is faster).

What are my major mistakes when trying to use AVX? (I'm new to programming with it so I don't fully understand how the pitfalls when programming for performance)

void version5(int mat1[N][N], int mat2[N][N], int result[N][N])
{
__m256i vec_multi = _mm256_setzero_si256(); //Initialize vector to zero
__m256i vec_mat1 = _mm256_setzero_si256(); //Initialize vector to zero
__m256i vec_mat2 = _mm256_setzero_si256(); //Initialize vector to zero

int i, j, k;
for (i = 0; i < N; i += 8)
{
    for (j = 0; j < N; ++j)
    {
        //The cost heavy storing is done once for each iteration and then use them at all places needed, stores column of matrix2 in chunks of eight, uses setr to have them in the right order
        vec_mat2 = _mm256_setr_epi32(mat2[i][j], mat2[i+1][j],mat2[i+2][j],mat2[i+3][j], mat2[i+4][j],mat2[i+5][j],mat2[i+6][j],mat2[i+7][j]);

        for (k = 0; k < N; ++k)
        {
            vec_mat1 = _mm256_loadu_si256(&mat1[k][i]); //Stores row of first matrix (eight in each iteration)
            vec_multi = _mm256_add_epi32(vec_multi ,_mm256_mullo_epi32(vec_mat1, vec_mat2));//Multiplies the vectors

            result[k][j] += _mm256_extract_epi32(vec_multi, 0) + _mm256_extract_epi32(vec_multi, 1) +_mm256_extract_epi32(vec_multi, 2) +_mm256_extract_epi32(vec_multi, 3) +_mm256_extract_epi32(vec_multi, 4) +_mm256_extract_epi32(vec_multi, 5) +_mm256_extract_epi32(vec_multi, 6) +_mm256_extract_epi32(vec_multi, 7);

            vec_multi = _mm256_setzero_si256();
        }
    }
}
}


texts: Fast bruth force numpy array combination

texts:
I want to extract combinations of numpy arrays in that way:
from itertools import combinations
import numpy as np

X = np.array(np.random.randn(4, 6))
combination = np.array([X[:, [i, j]] for i, j in combinations(range(X.shape[1]), 2)])

Is there a way to speed? My array has a shape of 200x50000.


texts:
I have a function that is called in several subsets of a matrix containing similarities of pathways or genes or clusters of genes, around 200 millions of unique combinations.

To perform that I use outer, but I learned that outer holds everything into memory (it crashes my laptop). Each method is a different algorithm to combine scores some of them are from the literature.

combineScores <- function(scores, method, round = FALSE, t = 0) {
    # Check input
    method <- match.arg(method,
                        c("avg", "max", "rcmax", "rcmax.avg", "BMA",
                          "reciprocal"))

    if (is.list(scores) && length(scores) == 1) {
        scores <- scores[[1]]
    }
    if (!is.matrix(scores)) {
        stop("scores argument should be a matrix")
    }

    if (length(round) != 1 || !is.logical(round)) {
        stop("round argument is not logical")
    }

    if (any(dim(scores) == 0L)) {
        return(NA)
    }

    if (!is.numeric(t) | t < 0 | t > 1) {
        stop("t is for the reciprocal method, and should be between 0 and 1")
    }

    # Remove NA
    if (any(is.na(scores)) && is.matrix(scores)) {
        row.na.idx <- apply(scores, 1, function(i){all(is.na(i))})
        if (any(row.na.idx)) {
            scores <- scores[-which(row.na.idx), ]
        }

    }
    if (any(is.na(scores)) && is.matrix(scores)) {
        col.na.idx <- apply(scores, 2, function(i){all(is.na(i))})
        if (any(col.na.idx)) {
            scores <- scores[, -which(col.na.idx)]
        }
    }

    # Apply the methods
    if (method == "avg") {
        result <- mean(scores, na.rm = TRUE)
    } else if (method == "max") {
        result <- max(scores, na.rm = TRUE)
    } else if (is.matrix(scores)) {
        if (method == "rcmax") {
            result <-  max(rowMeans(scores, na.rm = TRUE),
                           colMeans(scores, na.rm = TRUE))
        } else if (method == "rcmax.avg" || method == "BMA") {
            result <- sum(apply(scores, 1, max, na.rm = TRUE),
                          apply(scores, 2, max, na.rm = TRUE)) / sum(
                              dim(scores))
        } else if (method == "reciprocal") {
            rows <- apply(scores, 2, which.max)
            columns <- apply(scores, 1, which.max)
            reciprocal <- rows[columns[rows] == seq_along(rows)]
            rScores <- sapply(seq_along(reciprocal), function(x) {
                scores[reciprocal[x], names(reciprocal)[x]]
            })

            if (all(rScores <= t)) {
                result <- NA
            } else {
                result <- 2*sum(rScores[rScores >= t])/(sum(dim(scores)))
            }

        }
    } else {
        warning("Using max method because after removing NAs ",
                "there isn't a matrix to use.")
        result <- max(scores, na.rm = TRUE)
    }

    # Return the value
    if (round) {
        return(round(result, digits = 3))
    } else {
        return(result)
    }

}

To use in the matrix with several subsets I wrap it in

combineScoresPrep <- function(x, y, prep, method, ...) {
    if (is.null(x) || is.null(y)) {
        NA
    } else if (all(is.na(x)) || all(is.na(y))) {
        NA
    } else {
        combineScores(prep[x[!is.na(x)], y[!is.na(y)], drop = FALSE],
                      method, ...)
    }
}

And to use it in outer I vectorize it:

vcombineScoresPrep <- Vectorize(combineScoresPrep,
                                vectorize.args = c("x", "y"))

Which is called like:

outer(subss, subss, vcombineScoresPrep, prep = A, method = "max")

A: is a matrix
subss: is a vector.

I would like to improve the following points:

Can combineScores be vectorized (other than with Vectorize)?
How can I reduce the memory usage when I call outer with combineScores?
Another option I was considering using loops or other functions to
avoid outer. See this related question where instead of mean
would be combineScores
Or should I move to Rcpp and write it in c++?


texts:
This is a simple library I just finished writing. The main function is entropy(), which returns the entropy of a file. I'd really appreciate suggestions to improve it.

caos.c:

#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <sys/stat.h>
#include "caos.h"

static unsigned long long int wc(const char * file_to_size);
static int get_times(double table_of_chars[ASCII], const char * file);
static int calc_frequencies(double table_of_chars[ASCII], const char * file);

double entropy(const char * file)
{
  int iter;
  double entropy = (double)INIT;
  double table_of_chars[ASCII] = {INIT};
  if (get_times(table_of_chars, file) == EREAD)
  {
    return EREAD;
  }

  if (calc_frequencies(table_of_chars, file) == EREAD)
  {
    return EREAD;
  }

  for (iter = INIT; iter < ASCII; iter++)
  {
    if (table_of_chars[iter] != INIT)
    {
      entropy -= (table_of_chars[iter] * log2(table_of_chars[iter]));
    }
  }

  return fabs(entropy);
}

static int get_times(double table_of_chars[ASCII], const char * file)
{
  int getch;
  if (access(file, F_OK) != EREAD)
  {
    FILE * fget = fopen(file, READ);
    while ((getch = getc(fget)) != EOF)
    {
      table_of_chars[getch]++;
    }
    fclose(fget);
    return OK;
  }

  return EREAD;
}

static int calc_frequencies(double table_of_chars[ASCII], const char * file)
{
  int iter;
  unsigned long long int file_size = wc(file);
  if (file_size != (unsigned)EREAD)
 {
    for (iter = INIT; iter < ASCII; iter++)
    {
      if (table_of_chars[iter] != INIT)
      table_of_chars[iter] = (double)(table_of_chars[iter] / file_size);
    }

   return OK;
 }

 return EREAD;
}

static unsigned long long int wc(const char * file)
{
  if (access(file, F_OK) != EREAD)
  {
    struct stat st;
    if (stat(file, &st) == OK)
    {
      unsigned long long int bytes = st.st_size;
      return bytes;
    }
  }

  return EREAD;
}

caos.h:

#define   ASCII         256
#define   INIT           0

#define   EREAD         -1
#define   READ          "r"
#define   OK             0

double entropy(const char * path_to_file);


texts:
I'm trying to learn more about counting sort and I just implemented the example given in CLRS,  my question is: How can I improve this code?

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

void counting_sort(int *, int, int);
int find_max(int *, int);

int main(void)
{
    int l_size;
    int i;

    scanf("%d", &l_size);

    int *num_list = calloc(l_size, sizeof(int));

    for (i = 0; i < l_size; i++)
        scanf("%d", &num_list[i]);

    int max = find_max(num_list, l_size);
    counting_sort(num_list, l_size, max);

    puts("Sorted:");
    for (i = 0; i < l_size; i++)
        printf("%d ", num_list[i]);

    printf("\n");

    return 0;

}

void counting_sort(int *num_list, int l_size, int max)
{
    int i, j;

    int *count_list = calloc(max + 1, sizeof(int)); // auxiliary array C
    int *sorted_list = calloc(l_size, sizeof(int));

    for (i = 0; i < l_size; i++)
        count_list[num_list[i]]++;

    for (i = 1; i < max + 1; i++)
        count_list[i] += count_list[i - 1];

   for (i = l_size - 1; i >= 0; i--)
   {
        sorted_list[count_list[num_list[i]] - 1] = num_list[i];
        count_list[num_list[i]]--;
   }

   memcpy(num_list, sorted_list, l_size * sizeof(int));
}

int find_max(int *num_list, int l_size)
{
    int i;
    int max = num_list[0];

    for (i = 1; i < l_size; i++)
    {
        if (num_list[i] > max)
            max = num_list[i];
    }

    return max;
}


texts:
From a deck of 50 need to get sets of 5 as random as possible and as fast as possible.  The thought here is to shuffle to get 10 sets of five at a time with no collisions.

Int1 and Int2 will not change during a run.  If they do other bad stuff would happen.

    public MainWindow()
    {
        InitializeComponent();
        Stopwatch sw = new Stopwatch();
        sw.Start();
        for(int i = 0; i < 100000; i++ )
        {
            //Debug.WriteLine(string.Join(", ", NextFive(11, 12)));
            int count = NextFive(11, 12).Count();
        }
        sw.Stop();
        Debug.WriteLine(sw.ElapsedMilliseconds.ToString("N0"));
    }
    Random rand = new Random();
    private int[] deckBase;
    int nextFiveLastStart = 45;
    private IEnumerable<int> NextFive(int int1, int int2)
    {
        if (int1 == int2)
            throw new IndexOutOfRangeException("int1 == int2");
        if (int1 > 51 || int2 > 51)
            throw new IndexOutOfRangeException("int1 > 51 || int2 > 51");
        if (deckBase == null)
        {
            deckBase = new int[50];
            int j = 0;
            for (int i = 0; i < 52; i++)
            {
                if (i == int1 || i == int2)
                    continue;
                deckBase[j] = i;
                j++;
            }
        }
        if (nextFiveLastStart >= 45)
        {
            nextFiveLastStart = 0;
            // Yates shuffle
            for (int i = 49; i >= 1; i--)
            {
                int j = rand.Next(i + 1);
                if (j != i)
                {   // exchange values
                    int curVal = deckBase[i];
                    deckBase[i] = deckBase[j];
                    deckBase[j] = curVal;
                }
            }
        }
        else
            nextFiveLastStart += 5;
        return deckBase.Skip(nextFiveLastStart).Take(5);
    }


texts: Removing n elements from array starting from index

texts:
This method removes n elements starting from a given index, from an array of a given type. If n is positive it removes elements forwards, if it is negative it removes them backwards (e.g. for an array {1,2,3,4,5} Remove(2,2) results in {1,2,5}; Remove (2,-2) results in {1,4,5})

It there a better way to do it?

public static class ArrayExtensions
{
    public static T[] RemoveAt<T>(this T[] array, int idx, int len)
    {
        T[] newArray;

        if (len > 0)
        {
            if (idx + len > array.Length)
                len = array.Length - idx;

            newArray = new T[array.Length - len];
            if (idx > 0)
                Array.Copy(array, 0, newArray, 0, idx);

            if (idx < array.Length - 1)
                Array.Copy(array, idx + len, newArray, idx, array.Length - idx - len);
        }
        else
        {
            newArray = new T[array.Length + len];
            if (idx > 0)
                Array.Copy(array, 0, newArray, 0, idx + len);

            if (idx < array.Length - 1)
                Array.Copy(array, idx, newArray, idx + len, array.Length - idx);
        }

        return newArray;
    }
}


texts:
I tried to answer the question "How to print a hash in Perl, such that 3 key value pairs are printed on each line?" like this.

As I got an uncommented downvote, I'd like to ask: What's wrong with/How to improve:

use Modern::Perl;

my %h = ();
for (0..7) {
    $h{$_} = chr(65 + $_);
}
print %h, "\n";
my $cols = +$ARGV[0] || 5;
my $n = -$cols;
for my $key (keys %h) {
    print $key, ' => ', $h{$key}, 0 == ++$n % $cols ? "\n" : "\t\t";
}
print $n % $cols ? "\n------" : "------";


texts: Minimum Window Subsequence LeetCode Solution

texts:
Problem statement :
Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.
If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.
Example:
Input:  S = "abcdebdde", T = "bde" Output: "bcde" Explanation:  "bcde" is the answer because it occurs before "bdde" which has the same length. "deb" is not a smaller window because the elements of T in the window must occur in order.
public class MinimumWindowSubsequence {
  public String minWindow(String s, String t) {
    if (t.length() == 1) {
      int index = s.indexOf(t.charAt(0));
      return index == -1 ? "" : s.substring(index, index + 1);
    }
    int minLength = Integer.MAX_VALUE;
    String result = "";
    for (int leftPointer = 0; leftPointer < s.length(); leftPointer++) {
      char currentChar = s.charAt(leftPointer);
      if (currentChar == t.charAt(0)) {
        int counter = 1;
        int rightPointer = leftPointer + 1;
        while (rightPointer < s.length()) {
          if (counter < t.length() && s.charAt(rightPointer) == t.charAt(counter)) {
            counter++;
            if (counter == t.length()) {
              int currentLength = rightPointer - leftPointer;
              if (currentLength < minLength) {
                result = s.substring(leftPointer, rightPointer + 1);
                minLength = currentLength;
              }
              break;
            }
          }
          rightPointer++;
        }
      }
    }
    return result;
  }
}

My code works but it does not pass the tests on LC which is fine with me. Can you please give me feedback on the code and help me cross-check the runtime of this algorithm? I think it is linear run-time.
Thanks,


texts: When a constructor calls a helper function, should the helper mutate the object or return part of the object?

texts:
I have a private method that is called from the constructor to instantiate a bunch of objects.

I can do it two ways.

    private Monster[,] createMonsters()
    {
        Monster[,] myMonsterArray = new Monster[8, 6];

        for (int i = 0; i < 8; i++)
        {
            myMonsterArray[0, i] = new Monster(SpriteFactory.getMonster1Sprite());
            myMonsterArray[1, i] = new Monster(SpriteFactory.getMonster2Sprite());
            myMonsterArray[2, i] = new Monster(SpriteFactory.getMonster3Sprite());
            myMonsterArray[3, i] = new Monster(SpriteFactory.getMonster1Sprite());
            myMonsterArray[4, i] = new Monster(SpriteFactory.getMonster2Sprite());
            myMonsterArray[5, i] = new Monster(SpriteFactory.getMonster3Sprite());
        }

        return myMonsterArray;
    }

called with

monsterArray = createMonsters();

or

    private void createMonsters()
    {
        monsterArray = new Monster[8, 6];

        for (int i = 0; i < 8; i++)
        {
            monsterArray[0, i] = new Monster(SpriteFactory.getMonster1Sprite());
            monsterArray[1, i] = new Monster(SpriteFactory.getMonster2Sprite());
            monsterArray[2, i] = new Monster(SpriteFactory.getMonster3Sprite());
            monsterArray[3, i] = new Monster(SpriteFactory.getMonster1Sprite());
            monsterArray[4, i] = new Monster(SpriteFactory.getMonster2Sprite());
            monsterArray[5, i] = new Monster(SpriteFactory.getMonster3Sprite());
        }

    }

called with

createMonsters();

Is either better or worse?


texts:
How can I do the following with less nested loops.
How can I output the Table names above their corresponding tables without having to loop.

Functions for returning the DB Info:

// Return all the Table names in an array
public function getDbTables() {
    $result = $this->query("SHOW TABLES");
    while ($row = $result->fetchAll(PDO::FETCH_COLUMN)) {
        return $row;
    }
}

// Return ALL column names for each Table available
public function getColumnNames($table){
    $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
    try {
        $stmt = $this->dbh->prepare($sql);
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
        $stmt->execute();
        $output = array();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output[] = $row['COLUMN_NAME'];
        }
        return $output;
    }

    catch(PDOException $pe) {
        trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
    }
}

// Populate HTML Table with the DB Table Data
public function populateTable($table) {
    $sql = "SELECT * FROM $table";
    try {
        $stmt = $this->dbh->prepare($sql);
        $stmt->execute();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            return $row;
        }

    }
        catch(PDOException $pe) {
        trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
    }
}

HTML Output:

<?php print_r($phpCore->getDbTables()); ?>

<form>

<?php
foreach($phpCore->getDbTables() as $tablename) {
    echo '
';
    foreach($phpCore->getColumnNames($tablename) as $fieldnames) {
        echo ''.$fieldnames.'	';
    }
    echo '
';

    echo '
';
    foreach($phpCore->populateTable($tablename) as $tabledata) {
        echo '<input type="text" value="'.$tabledata.'"></input>	';
    }
    echo '
';
}
?>

</form>

Visual Output:


texts:
(See the next iteration.)

I have this small template function for convenient dumping a sequence into a string such that there is a delimeter between two consecutive elements, and no such after the last element:

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

using std::cout;
using std::endl;
using std::for_each;
using std::vector;

template<typename T>
std::string join(const T begin,
                 const T end,
                 std::string separator,
                 std::string concluder)
{
    const auto length = std::distance(begin, end);
    std::stringstream ss;
    size_t count = 0;

    for (T iter = begin; iter != end; ++iter, ++count)
    {
        ss << *iter;

        if (count < length - 1)
        {
            ss << separator;
        }
    }

    ss << concluder;
    return ss.str();
}

template<typename T>
std::string join(T begin, T end, std::string separator)
{
    return join(begin, end, separator, "");
}

template<typename T>
std::string join(T begin, T end)
{
    return join(begin, end, ", ");
}

int main() {
    vector<vector<int>> matrix = {
        { 1, 2, 3 },
        { 4, 5 },
        { },
        { 10, 26, 29 }
    };

    for_each(matrix.cbegin(),
             matrix.cend(),
             [](std::vector<int> a) {
                 cout << join(a.cbegin(), a.cend()) << endl;
             });
}

Any idea how to improve this?


texts:
I decided to make a roguelike for fun. Here's the first part, a building generator (in the link at the bottom of the post, each square represents a building):

var mm=millis()
//var mm2=0

var rooms=[]
var S=63 //What's a better name for S?
S+=S%2 //forces S to be even

for(var i=0;i<S;i++){
    rooms[i]=[]
    for(var j=0;j<S;j++){
        rooms[i][j]=Infinity
    }
}

var pick=function(array){

    var queue=[]
    //var mm3=millis()
    for(var i=1;i<S-1;i++){
        for(var j=1;j<S-1;j++){
            if(rooms[i][j]==Infinity){
                var t = min(min(rooms[i-1][j],rooms[i][j-1]),
                            min(rooms[i+1][j],rooms[i][j+1]))
                if(t<Infinity){
                    queue.push([i,j,pow(S,2)])
                }
            }
        }
    }
    //mm2+=millis()-mm3
    return queue[~~(Math.random()*queue.length)]
}

var createRoom=function(pos){
    rooms[pos[0]][pos[1]]=pos[2]
}

var drawRooms=function(){
    pushMatrix()
    //scale(4.0)
    colorMode(HSB)
    background(255, 0, 255)
    noStroke()
    for(var i=0;i<S;i++){
        for(var j=0;j<S;j++){
            if(rooms[i][j]!==Infinity){
                fill(rooms[i][j]*10,255,255)
                rect(i*width/S,j*height/S,ceil(width/S),ceil(height/S))
            }
        }
    }
    popMatrix()
}

var redo=function(x,y,t){
    if(rooms[x][y]!==Infinity&&rooms[x][y]>t){
        rooms[x][y]=t
        t++
        redo(x+1,y,t)
        redo(x,y+1,t)
        redo(x-1,y,t)
        redo(x,y-1,t)
    }
}

createRoom([S/2,S/2,1])
for(var i=0;i<pow(S,2)/10;i++){
    createRoom(pick())
}
redo(S/2,S/2,0)

drawRooms()
fill(0)
var benchmark=millis()-mm
text('Took '+benchmark+' milliseconds to run.',10,10)

I would have done it in processing.py, but I had some trouble with matrices. If anyone knows how to use them in vanilla python, feel free to give me an explanation.

Lastly, here's the link I mentioned if you want to have a look at it:

(The "rainbow" part represents the distance from the center "room" (the reddest square) to the colored room.)

https://www.khanacademy.org/computer-programming/roguelike-room-generator/6424540231008256


texts:
I use Marionette for my JavaScript application (requirejs for module structure). Application has router and controller. When starting, application renders the root view. Controller executes actions on each route and shows a subview.

To show a subview, I transmit a root view in a controller with options. It is a first way I see.

Application code

define([

    'marionette',
    'router',
    'controller',
    'view.application',

], function (

    Marionette,
    Router,
    Controller,
    ViewApplication
) {

    return Marionette.Application.extend({

        onStart: function () {
            this.view = {};
            this.view.application = new ViewApplication();
            this.view.application.render();

            new Router({
                controller: new Controller({
                    view: this.view.application,
                }),
            });

            if (Backbone.history) {
                Backbone.history.start({
                    root:       '/',
                    pushState:  true,
                });
            }
        },
    });
});

Controller code

define([

    'marionette',
    'controller.category',

], function (

    Marionette,
    ControllerCategory
) {

    return Marionette.Object.extend({

        initialize: function (options) {

            this.view = {};
            this.view.application = options.view;
        },
        category: function () {

            new ControllerCategory({
                view: this.view.application,
            });
        },
    });
});

Controller Category code

define([

    'marionette',
    'view.category',

], function (

    Marionette,
    ViewCategory
) {

    return Marionette.Object.extend({

        initialize: function (options) {

            this.view = {};
            this.view.application = options.view;

            this.view.category = new ViewCategory();
            this.view.application.showChildView('main', this.view.category);
        },
    });
});

Another way I see, is to create a global object, store a root view in it and then use it further (e.g. App = { Views: { Root: this.view.application, }}).

Am I right? Is it the best ways to show a subview depending on route? Or does some better way exist?


texts: jQuery autocomplete for all place names in the UK

texts:
I made an autocomplete input box of every town, city and village in the UK. Yes, every single one. The load times are painful so is there a way to reduce that?

Here is a sample:

<input type="text" id="location" name="locations" placeholder="Edinburgh, Belfast, Cardiff, London">
$( function() {
    var availableTags = [
      "Abberton",
      "Abbeytown",
      "Abbots Bromley",
      "Abbots Leigh",
      "Abbotsbury",
      "Abbotskerswell",
      "Abbotsley"
    ];
$("#location").autocomplete({
      source: availableTags
});
});

Here is a JSFiddle with the entire list, which has 7726 items.


texts: Generating parallel random numbers in a thread-safe way and using them in computations implemented by class method

texts:
I have the following code that I managed to make thread-safe but I am not sure if I am using C++ technology optimally.

#include <iostream>
#include <omp.h>
//#include <memory>

class GenNo
{
public:

    int num;

    explicit GenNo(int num_)
    {
        num = num_;
    };

    void create(int incr)
    {
        num += incr;
    }
};

class HelpCrunch{
public:
    HelpCrunch() {

    }

    void helper(int number)
    {
        std::cout << "Seed is " << number << " for thread number: " << omp_get_thread_num() << std::endl;
    }
};

class calculate : public HelpCrunch
{
public:

    int specific_seed;
    bool first_run;

    void CrunchManyNos()
    {
        HelpCrunch solver;

        thread_local static GenNo RanNo(specific_seed);
        //std::unique_ptr<GenNo> GenNo_ptr(nullptr);
        /*
        if(first_run == true)
        {
            GenNo_ptr.reset(new GenNo(specific_seed));
            first_run = false;
        }
         solver.helper(GenNo_ptr->num);
*/
        RanNo.create(1);
        solver.helper(RanNo.num);

        //do actual things that I hope are useful.
    };
};

int main()
{

    calculate MyLargeProb;
    MyLargeProb.first_run = true;

#pragma omp parallel firstprivate(MyLargeProb)
    {
        int thread_specific_seed = omp_get_thread_num();
        MyLargeProb.specific_seed = thread_specific_seed;

        #pragma omp for
        for(int i = 0; i < 10; i++)
        {
            MyLargeProb.CrunchManyNos();
            std::cout << "Current iteration is " << i << std::endl;
        }

    }
    return 0;
}

The code that is commented out can be used as an alternative but the pointer gets destroyed after the method finishes which crashes the programme. Moreover, it was pointed out to me that I could use threadprivate for the static instance of GenNo. The use case equivalent of GenNo is a random number generator that gets seeded once per thread with a known seed and then is left alone, i.e. not reinitialised, but called upon to generate fresh random numbers in each iteration.

I know the whole structure seems a bit contrived but my hands are tied somewhat: the classes and their dependence are dictated to me by the tools I would like to use and I think this scenario is common in the scientific computing community.
It compiles fine and upon manual testing appears to be thread-safe and working but again, I don't think this is particularly good style and a bit cobbled together, so I would love to hear everyone's comments.
Important note: I am using gcc as my compiler and gcc for over ten years now doesn't support threadprivate class instances. Intel's compiler which can be obtained for academics and students on a trial license, does.

The following is an example of code that would not compile in GCC (even the most recent version).

#include "myclass.h"
#include <omp.h>
int main

{
   myclass myinstance;
   #pragma omp parallel threadprivate(my_instance)

    {

      // do parallel things

     }
    return 0;
}

The error message would be my_instance declared threadprivate after first use which is a long-standing bug or rather not a bug but a missing feature, see here, for example.


texts: Loop termination check for multiple types of host reachability tests

texts:
I have 2 booleans: host.isReachableOnLan, and host.isReachableOnWan

I have a listener onItemClick doing work on network on button event

Then I have an anonymous thread than runs a while loop, evaluating the booleans each iteration with the evalFlag method.

This works, but feels hackish and wrong. Is there a more elegant way of accomplishing the same goal? Hopefully one without my evalFlag method.

I would also like to combine the last two if statements at the top of my onItemClick method, because they feel redundant, but they're there for evalFlag.

Host host;

private boolean evalFlag(int type) {
    switch (type) {
    case 0:
        return !host.isReachableOnLan && !host.isReachableOnWan;
    case 1:
        return host.isReachableOnLan;
    case 2:
        return host.isReachableOnWan;
    }
    return false;

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    host = MainActivity.mainActivity.listAdapter.getItem(arg2);
    int tmp = -1;

    if (!host.isReachableOnLan && !host.isReachableOnWan) {
        new WakeOnLan(host, host.wolBroadcast).start();
        new WakeOnLan(host, host.wanHostName).start();
        tmp = 0;
    }

    else if (host.isReachableOnLan) { // want to combine this statement
        new ExecuteSshCommand(host, host.sshShutdownCommand).start();
        tmp = 1;
    }

    else if (host.isReachableOnWan) { // with this one
        new ExecuteSshCommand(host, host.sshShutdownCommand).start();
        tmp = 2;
    }

    final int type = tmp;
    new Thread() {
        @Override
        public void run() {
            MainActivity.mainActivity.swipeRefreshLayout.setRefreshing(true);
            host.isLoading = true;

            MainActivity.mainActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MainActivity.mainActivity.listAdapter.notifyDataSetChanged();
                }
            });
            int timeSum = 0;
            HostCheck checker = new HostCheck(MainActivity.mainActivity, host, false);

            while (evalFlag(type) && timeSum < checker.loopTimeout) {
                final long startTime = System.currentTimeMillis();
                checker.run();
                if(host.isReachable())
                    try {
                        sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                timeSum += (int) (System.currentTimeMillis() - startTime);
            }
            MainActivity.mainActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MainActivity.mainActivity.listAdapter.notifyDataSetChanged();
                }
            });

            MainActivity.mainActivity.swipeRefreshLayout.setRefreshing(false);
            host.isLoading = false;
        }
    }.start();


texts: Seed std::mt19937 from std::random_device

texts:
Many people seed their Mersenne Twister engines like this:

std::mt19937 rng(std::random_device{}());

However, this only provides a single unsigned int, i.e. 32 bits on most systems, of seed randomness, which seems quite tiny when compared to the 19937 bit state space we want to seed. Indeed, if I find out the first number generated, my PC (Intel i7-4790K) only needs about 10 minutes to search through all 32 bit numbers and find the used seed. (I know that MT is not a cryptographic RNG, but I just did that to get a feel for how small 32 bit really is in these days.)

I am trying to build a function to properly seed a mt19937 and came up with this:

#include <algorithm>
#include <iostream>
#include <random>

auto RandomlySeededMersenneTwister () {
    // Magic number 624: The number of unsigned ints the MT uses as state
    std::vector<unsigned int> random_data(624);
    std::random_device source;
    std::generate(begin(random_data), end(random_data), [&](){return source();});
    std::seed_seq seeds(begin(random_data), end(random_data));
    std::mt19937 seededEngine (seeds);
    return seededEngine;
}

int main() {
    auto rng = RandomlySeededMersenneTwister();
    for (int i = 0; i < 10; ++i)
        std::cout << rng() << "\n";
}

This does look like a safe solution to me; however, I have learned that problems with RNG are often times quite subtle.

Provided std::random_device produces good, random data on my system, does the code give me a correctly seeded std::mt19937?


texts: A Public and Private Key generator for RSA

texts:
I made an RSA encryption public and private key generator and I would like some feedback. In particular, as this is cryptography related I want to know if I have done anything that might be considered insecure.

FYI, the Crypto.Random module is from the crypto-api package.

(Disclaimer, I am not using this for anything serious, just to help understand how the process works.)

import System.Random
import Crypto.Random
import Crypto.Random.DRBG
import Control.Monad.CryptoRandom
import Data.Bits
import qualified Data.ByteString as BS

data PublicKey  = PublicKey Integer Integer deriving (Show,Eq)
data PrivateKey = PrivateKey Integer Integer deriving (Show,Eq)

defaultExp = 65537

modExp :: Integer -> Integer -> Integer -> Integer
modExp b 0 m = 1
modExp b e m = t * modExp ((b * b) `mod` m) (shiftR e 1) m `mod` m
  where t = if testBit e 0 then b `mod` m else 1

fermatPrimeTest :: StdGen -> Int -> Integer -> Bool
fermatPrimeTest g k n = all (\a -> modExp a (n-1) n == 1) as
  where
    as = take k $ randomRs (2,n-2) g

totient :: Integer -> Integer -> Integer
totient p q = lcm (p-1) (q-1)

-- Find GCD of two numbers plus the Coefficients of Bezouts Identity.
-- Used to find modular inverse.
euclideanAlg :: Integer -> Integer -> (Integer, Integer, Integer)
euclideanAlg a b
  | b > a     = tripFlip $ euclideanAlg2 b 1 0 a 0 1
  | otherwise = euclideanAlg2 a 1 0 b 0 1
  where
    tripFlip (a,b,c) = (a,c,b)
    euclideanAlg2 rk0 sk0 tk0 0 sk1 tk1 = (rk0,sk0,tk0)
    euclideanAlg2 rk0 sk0 tk0 rk1 sk1 tk1 =
        let qi = rk0 `div` rk1 in
        euclideanAlg2 rk1 sk1 tk1 (rk0 - qi*rk1) (sk0 - qi*sk1) (tk0 - qi*tk1)

-- Modular inverse, d, of a such that a.d = 1 mod m
modMultInv :: Integer -> Integer -> Integer
modMultInv m a = let (r,_,d) = euclideanAlg m a
                 in d `mod` m

-----------------
-- Prime Number Generator using Secure RNG
-----------------

genPrime :: CryptoRandomGen g => g -> Int -> Integer -> Integer -> Integer
genPrime g k minPrime maxPrime = head $ filter (fermatPrimeTest g' k) ns
  where
    Right (i,g'') = crandom g
    g'            = mkStdGen i
    Right (n,_)   = crandomR (minPrime, maxPrime) g''
    ns            = iterate ((+) 2) (n .|. 1)

genPQ :: CryptoRandomGen g => g -> Int -> Integer -> Integer -> (Integer,Integer)
genPQ g k minPrime maxPrime = (p,q)
  where
    Right (g1,g2) = splitGen g
    p = genPrime g1 k minPrime maxPrime
    q = genPrime g2 k minPrime maxPrime

-- genRSAKeys e g k minPrime maxPrime
-- e is public exponent, g is random seed,
-- k is number of iterations to run Rabin-Miller test.
-- minPrime, maxPrime is range to search for primes.
genRSAKeys :: CryptoRandomGen g => Integer -> g
           -> Int -> Integer -> Integer
           -> (PublicKey, PrivateKey)
genRSAKeys e g k minPrime maxPrime = let
                                        (p,q) = genPQ g k minPrime maxPrime
                                        n    = p*q
                                        t    = lcm (p-1) (q-1)
                                        d    = modMultInv t e
                                     in (PublicKey n e, PrivateKey n d)


texts: Summing up students by the topics they studied and the marks they got

texts:
I wrote scripts that sums up the students and their grades. It uses four csv files.

students
marks
tests
courses

.

# main
import pandas
from statistics import mean

if __name__ == "__main__":
    students_df = pandas.read_csv("students.csv")
    marks_df = pandas.read_csv("marks.csv")
    tests_df = pandas.read_csv("tests.csv")
    courses_df = pandas.read_csv("courses.csv")

    marks_tests = pandas.merge(marks_df, tests_df, left_on="test_id", right_on="id")
    student_courses = marks_tests.groupby(by="student_id")['course_id'].apply(set)

    students_dict = students_df.set_index("id").to_dict(orient="index")
    courses_dict = courses_df.set_index("id").to_dict(orient="index")

    for student_id, course_ids in student_courses.iteritems():
        print("Student id: {}, name: {name}".format(student_id, **students_dict[student_id]))
        final_grades = []
        for course_id in course_ids:
            marks = marks_tests.loc[(marks_tests['course_id'] == course_id) & (marks_tests['student_id'] == student_id)]
            final_grades.append(sum(marks['mark']*(marks['weight']/100.0)))

        print("Total Average: {:.2f}%".format(mean(final_grades)))
        for course_id in course_ids:
            print("  Course: {name}, Teacher: {teacher}".format(**courses_dict[course_id]))
            marks = marks_tests.loc[(marks_tests['course_id'] == course_id) & (marks_tests['student_id'] == student_id)]
            final_grade = sum(marks['mark']*(marks['weight']/100.0))
            print("  Final Grade: {:.2f}%".format(final_grade))

It works very well but I don't know if it is optimized. For instance I have two loops that do almost the same thing : the first one to get the total Average which is mean of the final grades for each topic and the second one to get the final grade for each topics.

Furthermore it would have been better if I added some testing to it such has

if the sum of the weights of the tests a student has taken in a topic are equal to 0 (the student took every tests)
or go over 100.


texts:
I decided to take a more general approach while implementing the TicTacToe game in Haskell.

Util

module Data.List.Utils where

import Data.List (intersperse)

surround :: a -> [a] -> [a]
surround x ys = x : intersperse x ys ++ [x]

nth :: Int -> (a -> a) -> [a] -> [a]
nth _ _ [] = []
nth 0 f (x:xs) = f x : xs
nth n f (x:xs) = x : nth (n - 1) f xs

TicTacToe

module TicTacToe where

import Data.List (transpose)
import Data.Foldable (asum)
import Data.List.Utils (surround, nth)

data Tile = O | X | Empty deriving (Eq)

instance Show Tile where
    show Empty = " "
    show O     = "O"
    show X     = "X"

-- ======================
-- Board Helper Functions
-- ======================
type Board = [[ Tile ]]

showBoard :: Board -> String
showBoard xss = unlines
             . surround vtx
             . map (concat . surround mid . map show)
             $ xss

    where mid = "|"
          vtx = surround '+' $ replicate (length xss) '-'

whoWon :: Board -> Maybe Player
whoWon xss = asum
           . map winner
           $ diag : anti : cols ++ xss

    where cols = transpose xss
          diag = zipWith (!!) xss           [0..]
          anti = zipWith (!!) (reverse xss) [0..]

          winner (x:xs) = if all (==x) xs && x /= Empty
                              then Just (toPlayer x)
                              else Nothing

getCoords :: Int -> Board -> (Int, Int)
getCoords n = divMod (n - 1) . length

fillTile :: Board -> Int -> Tile -> Board
fillTile xss n tile = nth row (nth col (const tile)) xss

    where (row, col) = getCoords n xss

isOver :: Board -> Bool
isOver = all (notElem Empty)

-- ========================
-- Player related functions
-- ========================
data Player = Player1 | Player2 deriving (Eq)

instance Show Player where
    show Player1 = "1st Player"
    show Player2 = "2nd Player"

toPlayer :: Tile -> Player
toPlayer X = Player1
toPlayer O = Player2

fromPlayer :: Player -> Tile
fromPlayer Player1 = X
fromPlayer Player2 = O

changePlayer :: Player -> Player
changePlayer Player1 = Player2
changePlayer Player2 = Player1

-- ====================
-- Game logic functions
-- ====================
validateInput :: Board -> String -> Either String Int
validateInput xss s  = case reads s of

    [(n, "")] -> check n
    _         -> Left "Only integers allowed"

    where check n

            | n < 1 || n > length xss ^ 2 = Left "Out of range"
            | xss !! row !! col /= Empty  = Left "Already filled"
            | otherwise                   = Right n

            where (row, col) = getCoords n xss

askInput :: Player -> Board -> IO ()
askInput player board = do

    putStrLn $ showBoard board
    putStrLn $ "Your turn, " ++ show player ++ "!"

    putStr $ "Tile number (1 - " ++ show (length board ^ 2) ++ "): "
    number <- getLine

    case validateInput board number of

        Left s  -> putStrLn ("Invalid input: " ++ s) >> gameStep player board

        Right n -> let tile = fromPlayer player
                       next = changePlayer player

                   in gameStep next (fillTile board n tile)

gameStep :: Player -> Board -> IO ()
gameStep player board = case whoWon board of

    Just winner -> do

        putStrLn $ showBoard board
        putStrLn $ show winner ++ " won!"

    Nothing | isOver board -> putStrLn "Game ended in a draw"
            | otherwise    -> askInput player board

startBoard :: Int -> Board
startBoard x = replicate x (replicate x Empty)

main :: IO ()
main = gameStep Player1 (startBoard 3) -- Change NxN


texts:
This is a script that I use on a Google sheet for parsing data that has been pasted from various other software and getting it into the correct format and columns on another sheet. Data is pasted into the "CL" sheet where it is parsed and formatted via formulas on the sheet.

The data is then sent to either just the "Work Log" sheet or both the "Work Log" sheet and "Represented" sheet if cell D15 is set to "Yes".

The cells that were changed on sheet "CL" are then deleted and/or changed back to the original values so another entry can be pasted.

Is there a more efficient way to setValue on each of the cells that need to be changed? Or do I need to do them one at a time, as I have them here?

function SendToWorkLogCL() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName("CL");
  var sheet2 = ss.getSheetByName("Work Log");
  var repsheet = ss.getSheetByName("Representing");
  var rep = sheet1.getRange("D15");
  var repvalue = rep.getValue();

  if (repvalue == 'Yes') {
  sheet1.getRange("A2:W2").copyTo(repsheet.getRange(repsheet.getLastRow()+1,1,1,7), {contentsOnly:true});
  sheet1.getRange("A2:W2").copyTo(sheet2.getRange(sheet2.getLastRow()+1,1,1,7), {contentsOnly:true});
  SpreadsheetApp.getActiveSheet().getRange('A3:B23').setValue('');
  SpreadsheetApp.getActiveSheet().getRange('A3').setValue('Ctrl+SHIFT+V');
  SpreadsheetApp.getActiveSheet().getRange('D12').setValue('Chargeback');
  SpreadsheetApp.getActiveSheet().getRange('D13').setValue('Yes');
  SpreadsheetApp.getActiveSheet().getRange('D14:D15').setValue('No');
  SpreadsheetApp.getActiveSheet().getRange('D17').setValue('');
  SpreadsheetApp.getActiveSheet().getRange('D18').setValue('0');
  SpreadsheetApp.getActiveSheet().getRange('D20').setValue('');
  SpreadsheetApp.getActiveSheet().getRange('G12:G15').setValue('');
  SpreadsheetApp.getActiveSheet().getRange('D16').setFormula("=IF(A2=\"\",\"\",VLOOKUP(E18,'Data Validation'!C2:E204,3,FALSE))");

  }else{
  sheet1.getRange("A2:W2").copyTo(sheet2.getRange(sheet2.getLastRow()+1,1,1,7), {contentsOnly:true});
  SpreadsheetApp.getActiveSheet().getRange('A3:B23').setValue('');
  SpreadsheetApp.getActiveSheet().getRange('A3').setValue('Ctrl+SHIFT+V');
  SpreadsheetApp.getActiveSheet().getRange('D12').setValue('Chargeback');
  SpreadsheetApp.getActiveSheet().getRange('D13').setValue('Yes');
  SpreadsheetApp.getActiveSheet().getRange('D14:D15').setValue('No');
  SpreadsheetApp.getActiveSheet().getRange('D17').setValue('');
  SpreadsheetApp.getActiveSheet().getRange('D18').setValue('0');
  SpreadsheetApp.getActiveSheet().getRange('D20').setValue('');
  SpreadsheetApp.getActiveSheet().getRange('D16').setFormula("=IF(A2=\"\",\"\",VLOOKUP(E18,'Data Validation'!C2:E204,3,FALSE))");

 }
 }


texts: Simple password dictionary attack script

texts:
This is my simple Perl script implement password dictionary attacking, encryption algorithm SHA1 with different length.

It takes 2 arguments as input: first argument is password dictionary file path, the second one is a text file contains line-by-line encrypted text. I used 2 common dictionaries for testing: rockyou and phpbb.

Any suggestions to make it more efficient?

#!/usr/bin/perl
use strict;
use warnings;
use Digest::SHA;
use autodie qw(open close);

# command arguments
my $dic = $ARGV[0];
my $pwd = $ARGV[1];

# read input cipher texts and dictionary
open (my $input, '<', $pwd);
my @ciphers = <$input>;
# remove end of line characters
chomp(@ciphers);

print "\n";
print "dictionary attack demo\n";
print "encrypt algorithm: SHA1\n";
print "======================================\n\n";

foreach my $cipher(@ciphers){
    my $password = "*";
    my $count = 0;
    my $factor = 0;

    # calculate factor depends on length of cipher text
    $factor = length($cipher);
    if ($factor == 40) {
        $factor = 1;
    }
    elsif(($factor == 56) ||
          ($factor == 64) ||
          ($factor == 96) ||
          ($factor == 128))
    {
        $factor = $factor * 4;
    }
    else {
        next;
    }

    # create new SHA algorithm object with key length is factor
    my $sha = Digest::SHA->new($factor);
    open (my $dict, '<', $dic);

    while(<$dict>){
        chomp;
        $sha->add($_);
        # encrypt each word with SHA1 algorithm
        my $encrypt_text = $sha->hexdigest;

        # compare with cipher text, if matches
        if($encrypt_text eq $cipher){
            $password = $_;
            last;
        }
        # count number of tested words
        $count++;
    }

    # print out result, "*" if not found
    print "$cipher\:\:$password\t[ATTEMPT\:\:$count words]\n";
    # close dictionary file handle
    close ($dict);
}

# close input file handle
close($input);


texts:
I'm trying to get more familiar with the new Java 8 features, so I am rewriting one of my earlier projects. It includes a class that keeps track of the best entry seen so far:

import java.util.List;

public class Maxinator<T> {

    private final QualityFunction<T> qualityFunction;
    private T best;
    private double bestQuality;

    public Maxinator(QualityFunction<T> qualityFunction) {
        this.qualityFunction = qualityFunction;
        reset();
    }

    public void reset() {
        best = null;
        bestQuality = Double.NEGATIVE_INFINITY;
    }

    public T getBest() {
        return best;
    }

    public void updateBest(List<T> population) {
        population.parallelStream()
                .forEach(i -> {
                    double quality = qualityFunction.computeQuality(i);
                    if (quality > bestQuality) {
                        best = i;
                        bestQuality = quality;
                    }
                });
    }
}

Where QualityFunction is simply the following interface:

public interface QualityFunction<T> {
    public abstract double computeQuality(T individual);
}

My questions:

Are there any concurrency issues with the code in the forEach modifying best and bestQuality? Or are these automatically taken care of by the parallel stream processing?
Is there a more idiomatic way to write this, using the new APIs (collect, reduce, etc.)?

Note: the quality function could be very expensive, so I want to make sure that it is only called once per element.


texts:
I'm looking for a better more efficient way to write some code I have where I"m synchronizing two lists.  Basically, the first list is a list of devices I need to check.  The second list is a list of devices that I have already checked with dates.  I need to synchronize the two lists so I only check devices that are new or out of date based on the date.  I also need to delete any devices that have been removed.

Here is my current code that works fine, it just looks and feels SO clunky.

public IEnumerable<AssetBlob> Synchronize(IEnumerable<AssetBlob> assets, string id) {
      //Get list of devices already checked in lineitemsmap
      List<AssetBlob> items = new List<AssetBlob>();
      IEnumerable<LineItemsMap> lineItems = auditRepo.GetLineItemsMap(id).DeviceResults;
      List<LineItemsMap> deleted = new List<LineItemsMap>();

      //put new items into list
      items.AddRange((from t0 in assets
                      join t1 in lineItems on t0.Id equals t1.BlobId into t1_join
                      from t1 in t1_join.DefaultIfEmpty()
                      where t1 == null
                      select t0).ToList());

      //list of existing items that need updated
      items.AddRange((from t0 in assets
                      join t1 in lineItems on t0.Id equals t1.BlobId
                      where t0.Imported > t1.Created
                      select t0).ToList());

      deleted.AddRange((from t0 in assets
                        join t1 in lineItems on t0.Id equals t1.BlobId
                        where t0.Imported > t1.Created
                        select t1).ToList());

      //Delete items in lineitems that don't exists in assets list
      deleted.AddRange((from t0 in lineItems
                        join t1 in assets on t0.BlobId equals t1.Id into t1_join
                        from t1 in t1_join.DefaultIfEmpty()
                        where t1 == null
                        select t0).ToList());

      if (deleted.Any()) {
        auditRepo.RemoveLineItemMaps(deleted);
      }

      return items;
    }

Any suggestion or improvements would be great.  Thank you.


texts: Shortest way to form a string out of a subsequence of a string

texts:
The task is taken from LeetCode (subscription required) -

From any string, we can form a subsequence of that string by deleting
some number of characters (possibly no deletions).
Given two strings source and target, return the minimum number of
subsequences of source such that their concatenation equals target. If
the task is impossible, return -1.
Example 1:
Input: source = "abc", target = "abcbc"
Output: 2
// Explanation: The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".

Example 2:
Input: source = "abc", target = "acdbc"
Output: -1
// Explanation: The target string cannot be constructed from the subsequences of source string due to the character "d" in target
// string.

Example 3:
Input: source = "xyz", target = "xzyxz"
Output: 3
// Explanation: The target string can be constructed as follows "xz" + "y" + "xz".

Note:
Both the source and target strings consist of only lowercase English
letters from "a"-"z". The lengths of source and target string are
between 1 and 1000.

My solution has space complexity of \$O(n)\$ and time complexity of \$O(n^2)\$ (I think...)
/**
 * @param {string} source
 * @param {string} target
 * @return {number}
 */
var shortestWay = function(source, target) {
    const map = new Map();
    for (let i = 0; i < source.length; i++) {
        if (map.get(source[i])) {
            const arr = map.get(source[i]);
            arr.push(i);
            map.set(source[i], arr);
        } else {
            map.set(source[i], [i]);
        }
    }
    let occurrences = 0;
    for (let i = 0; i < target.length; i++) {
        const indexes = map.get(target[i]);
        if (indexes === void 0) return -1;
        occurrences++;
        let max = 0;
        indexes.forEach(index => {
            let j = 0;
            let ignore = 0;
            while(source[index + j + ignore] !== void 0) {
                if(target[i + j] !== source[index + j + ignore]) {
                    ignore++;
                } else {
                    max = Math.max(max, j++);
                }
            }
        });
        i += max;
    }
    return occurrences;
};


texts:
This code is extremely slow and ideally I would appreciate someone walking me through getting this going on the GPU, but if nobody has time for that which is understandable, any and all optimisations would be most welcome!

Private Sub Picture(source As Image, picturebox As PictureBox)
    Dim r As Double
    Dim g As Double
    Dim b As Double

    Dim bmp As New Bitmap(source)
    Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
    Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.[ReadOnly], bmp.PixelFormat)
    Dim ptr As IntPtr = bmpData.Scan0
    Dim bytes As Integer = bmpData.Stride * bmp.Height
    Dim rgbValues As Byte() = New Byte(bytes - 1) {}
    System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)

    Dim linWhiteMult = 1 / (((LinearWhiteTextBox.Text * ((ShoulderStrengthTextBox.Text * LinearWhiteTextBox.Text) + (LinearAngleTextBox.Text * LinearStrengthTextBox.Text)) + (ToeStrengthTextBox.Text * ToeNumeratorTextBox.Text)) _
    / (LinearWhiteTextBox.Text * ((ShoulderStrengthTextBox.Text * LinearWhiteTextBox.Text) + LinearStrengthTextBox.Text) + ToeStrengthTextBox.Text * ToeDenominatorTextBox.Text) - (ToeNumeratorTextBox.Text / ToeDenominatorTextBox.Text)))

    'precalculations for optimisation

    Dim LaLs = LinearAngleTextBox.Text * LinearStrengthTextBox.Text
    Dim TsTn = ToeStrengthTextBox.Text * ToeNumeratorTextBox.Text
    Dim TsTd = ToeStrengthTextBox.Text * ToeDenominatorTextBox.Text
    Dim Tn_Td = ToeNumeratorTextBox.Text / ToeDenominatorTextBox.Text

    Dim list As New List(Of String)
    For x As Integer = 0 To bmp.Width - 1
        For y As Integer = 0 To bmp.Height - 1
            Dim position As Integer = (y * bmpData.Stride) + (x * Image.GetPixelFormatSize(bmpData.PixelFormat) / 8)
            b = rgbValues(position)
            g = rgbValues(position + 1)
            r = rgbValues(position + 2)

            '^2.2 lookup table (for optimisation) for gamma correction

            b = table.Item(b)
            g = table.Item(g)
            r = table.Item(r)

'the following is the filmic tone map formula, i.e.
'x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F)) - E/F

            r = (((r * ((ShoulderStrengthTextBox.Text * r) + (LaLs)) + (TsTn)) _
                    / (r * ((ShoulderStrengthTextBox.Text * r) + LinearStrengthTextBox.Text) + TsTd) - (Tn_Td))) * linWhiteMult

            g = (((g * ((ShoulderStrengthTextBox.Text * g) + (LaLs)) + (TsTn)) _
                    / (g * ((ShoulderStrengthTextBox.Text * g) + LinearStrengthTextBox.Text) + TsTd) - (Tn_Td))) * linWhiteMult

            b = (((b * ((ShoulderStrengthTextBox.Text * b) + (LaLs)) + (TsTn)) _
                    / (b * ((ShoulderStrengthTextBox.Text * b) + LinearStrengthTextBox.Text) + TsTd) - (Tn_Td))) * linWhiteMult
            If r > 1 Then
                r = 1
            End If
            If g > 1 Then
                g = 1
            End If
            If b > 1 Then
                b = 1
            End If

            rgbValues(position) = Math.Round((b ^ 0.45) * 255)
            rgbValues(position + 1) = Math.Round((g ^ 0.45) * 255)
            rgbValues(position + 2) = Math.Round((r ^ 0.45) * 255)

        Next
    Next

    System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes)

    bmp.UnlockBits(bmpData)

    ' apply the bmp to the avatars and dispose old

    Dim OldImage = picturebox.Image
    picturebox.Image = bmp
    OldImage.Dispose()

End Sub


texts: Print each word of a sentence in a new line

texts:
this is my first F# program, very simple concept but took me a few minutes to get it. I'm new to functional programming so I'd appreciate if you could have a look at and comment the code.
Suggest changes or any code smells?
module FSharpFun.PrintSentenceInLines

open System

let printWord w = printfn "%s" w
let printEveryWord = Array.map printWord
let splitIntoWords (s:String) = s.Split ()

// Read a line and print each word in a new line
[<EntryPoint>]
let main _ =
    Console.ReadLine () |> splitIntoWords |> printEveryWord |> ignore
    0


texts:
I'm trying to replicate Android's GenerateViewId() to assign a unique Tag to dynamically created UIViews in Xamarin.iOS.

internal static class LayoutExtensions
{
    // A tentative to mimmic Java's AtomicInteger used by GenerateViewId()
    // https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/View.java#27291
    private static int nextViewTag = 1;

    internal static int GenerateViewTag(this UIView someView)
    {
        for(;;)
        {
            var result = nextViewTag;
            var newValue = result + 1;
            if (newValue > 0x00FFFFFF)
            {
                newValue = 1; // Roll over to 1, not 0.
            }
            if (nextViewTag == Interlocked.CompareExchange(ref nextViewTag, newValue, result))
            {
                return newValue;
            }
        }
    }
}

What do you think?


texts:
I have three functions for building, applying, and plotting filters:

Build a filter:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate

    if filter_type == 'bandpass':
        try:
            normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
        except Exception as e:
            print("Must provide tuple of frequency ranges for a bandpass filter")
            raise
    else:
        try:
            normal_cutoff = frequency / nyq
        except Exception as e:
            print("Must provide a single frequency value for this filter type")
            raise

    b, a = butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

    return b, a

Apply filter:

def filter(signal, frequency, sample_rate, filter_type, filter_order=2):
    try:
        b, a = filter_build(frequency, sample_rate, filter_type, filter_order)
    except:
        print("Error when creating filter")
        return None

    filtered = filtfilt(b, a, signal)
    return filtered

Plotting the filter response:

def plot_filter_response(frequency, sample_rate, filter_type, filter_order=2):

    try:
        b, a = filter_build(frequency, sample_rate, filter_type, filter_order)
    except:
        print("Error when creating filter")
        return None

    w, h = freqz(b, a, worN=8000)
    plt.subplot(2, 1, 1)
    plt.plot(0.5*sample_rate*w/np.pi, np.abs(h), 'b')
    plt.xlim(0, 0.5*sample_rate)
    plt.title("Filter Frequency Response")
    plt.xlabel('Frequency (Hz)')
    plt.grid()

    if filter_type == 'bandpass':
        for i in range(len(frequency)):
            plt.axvline(frequency[i], color='k')
            plt.plot(frequency[i], 0.5*np.sqrt(2), 'ko')
    else:
        plt.axvline(frequency, color='k')
        plt.plot(frequency, 0.5*np.sqrt(2), 'ko')

    plt.show()

Everything appears to be working, but I dont think I'm handling exceptions correctly/efficiently.

For example, in filter() and plot_filter_response() I have the exact same try block, which feels redundant

The purpose of the try blocks (in all 3 functions) is to provide an easily understood error message if building a filter fails. The primary reason for this happening (that I can foresee) is if someone specifies a bandpass filter and only provides a single frequency cutoff, or if someone wants a lowpass filter but accidentally provides a tuple of 2 frequencies

Is there a way to remove the redundant try blocks, so that if a filter is mis-specified, then filter_build() will raise the error and stop any other lines of code from running?

A related issue is my inclusion of Return None in the latter 2 functions. Is there a way to remove those? If I remove them, then currently if filter_build() fails, the rest of the plotting code (or filtfilt) still gets executed, which runs into more problems. Ideally I want the functions to just exit if filter_build() doesn't return correctly


texts: Implementation of a shift operation for Set in JavaScript that emulates the one for arrays

texts:
I discovered that the JavaScript sets are ordered but don't offer a method to take the first element out of the set. For the arrays this operation exists and it's called shift.

A very basic implementation can be written in this way:

function shiftSet(s) {
    let res;
    for (let v of s) {
        res= v;
        break;
    }
    s.delete(res);
    return res;
}

Do you see a better way to write it?


texts: Achieve a dataframe from a dynamic list of lists

texts:
This code works for me, but I am trying to improve my coding and am looking for advice on how to improve it. Specifically I want to simplify this so that perhaps I can have a dynamically updating dataframe that tracks the "site" that I am on, and the "cutoff" value that I am on, and records the calculations for that site/cutoff value combination. Right now, it's a little clumsy and admittedly very ugly. Through this process, though, I learned about "assign" for creating assigning variables on the fly. I think I just need maybe one or two more concepts before I can really clean this up.

calcs <- function(site, cutoff){} #Returns a 4 item list

cutoffmatrix <- c(0, 0.005, 0.01, 0.015) #matrix that I want to loop through

for(i in 1:length(cutoffmatrix)){ #Loop that uses my function for cutoffmatrix value
  test <- list()
  co <- cutoffmatrix[i]
  assign(paste("TC", i, sep = ""), calcs("TC", co))
}

l_TC <- list(TC1, TC2, TC3, TC4) #combines the loop results into a list for that site

library(plyr)
df_TC <- ldply (l_TC, data.frame) #transform lists of lists into dataframe

for(i in 1:length(cutoffmatrix)){ #same thing, but for next site
  test <- list()
  co <- cutoffmatrix[i]
  assign(paste("DC", i, sep = ""), calcs("DC", co))
}

l_DC <- list(DC1, DC2, DC3, DC4)
df_DC <- ldply(l_DC, data.frame)

final <- rbind (df_TC, df_DC) #combines both site's results into a dataframe
final <- cbind(final, cutoffmatrix) #adds cutoff values to dataframe
namelist <- c("TC", "TC", "TC", "TC", "DC", "DC", "DC", "DC") #adds sites to dataframe
final <- cbind(final, namelist)

Any help is greatly appreciated!


texts:
This opens a file and writes 5120 times a string to it, and if the file doesn't exist it creates a new file. The name of the file and the string are chosen randomly. I would like to know if there is a way to speed up this code. It takes about 10 seconds at the moment. I was wondering if I did a recursion in the escreve() function or if I create some space in memory with malloc() on the main and free it before each cycle. If it will speed the thing up.

#define linhas 1024
#define vezes 5120
char *ficheiros[5]={"SO2014-0.txt","SO2014-1.txt","SO2014-2.txt","SO2014-3.txt","SO2014-4.txt"};
char *cadeias[10]={"aaaaaaaaa\n","bbbbbbbbb\n","ccccccccc\n","ddddddddd\n","eeeeeeeee\n","fffffffff\n","ggggggggg\n","hhhhhhhhh\n","iiiiiiiii\n","jjjjjjjjj\n"};

int random(int range)
{
    int num;
    num = rand() % range;
    return num;
}

void escreve(char *fi,char *cad){
    int l;
    int file = open(fi, O_WRONLY | O_CREAT, S_IRWXU | S_IROTH ) ;
    for(l=0;l<linhas;l++)
        write(file,cad, strlen(cad));
    close(file);
}

int main(){
    int x,y,l,i;
    srand(time(NULL));
for(i=0; i<vezes; i++){
    x= random(5);
        y=random(10);
        escreve(ficheiros[x],cadeias[y]);

}
return 0;
}


texts: Determine whether bitwise-OR of sub-array is odd

texts:
Problem:
Given an array A of N integers, you will be asked Q queries. Each query consists of two integers L and R. For each query, find whether bitwise OR of all the array elements between indices L and R is even or odd.
My approach:
Accept the array of N integers. For any query (Qi) scan the array of integers between the given limit. If an odd number is found (x%2==1) then raise a flag and terminate scanning. If flag is found raised tell that the result is odd, else say that it's even.
On thinking further, I find myself at the dead end. I can't optimize the code anymore. Only thing I can think of is instead of doing mod 2 I will check the last digit of each number and see if it is one of [0,2,4,6,8]. Upon trying that, the time limit still expired (in context to competitive programming [1]; Note: the competition has ended a day ago and results declared). Anyways, my question is to find a better method if it exists or optimize the code below.
I assume that the time complexity is O(nQ) where n is the number of elements in the given range.

The code O(nq)
Assume array is 1-indexed.
Input
First line consists of two space-separated integers N and Q.
Next line consists of N space-separated array elements.
Next Q lines consist of two space-separated integers L and R in each line.
#include<stdio.h>
#pragma GCC optimize("O2")

int main()
{
    long int c,d,j,N,Q;
    int fagvar=0;
    scanf("%ld %ld\n",&N,&Q);
    int a[N];
    int i=0;
    while(N--)
    {
        scanf("%ld",&a[i]);
        i++;
    }
    while(Q--)
    {
        scanf("%ld %ld",&c,&d);
        for(j=c-1;j<d;j++)
        {
            if (a[j]%2==1)
            {
                fagvar=1;
                break;
            }
        }
        if (fagvar==1)
        {
            printf("%d\n",0);
            fagvar=0;
        }
        else
        {
            printf("%d\n",1);
        }
    }
    return 0;
}

After 2 answers and a rethinking of algorithm, the final complexity falls at O(n+q). Note: Since this was a competitive problem and I probably won't revisit the same program I haven't added any extra readability. The reader is free to edit my code as required. For the algorithm, visit Toby Speight's comment section.
Visit here for the code. For an amalgamation of spanning over even numbers and Toby's method, visit here.


texts: I made a Python program to calculate price based on Inflation Rate

texts:
I made a program that calculates how much the value of money has decreased due to inflation over a given set of years.
This takes a principal amount, a start and end date, and with the help of the inflation rate, it calculates how much the value of money is at the current year. (compound)

The data from the CSV file is taken from here

Here is the code-

import pandas

startDate = input("Enter the starting year ")
endDate = input("Enter the ending year ")

principal_amt = float(input("Enter the amount "))
startDate = startDate + "-12-" + "31"
endDate = endDate + "-12-" + "31"
final_amt = 0

print(startDate, endDate)

df = pandas.read_csv("india-cpi.csv")
df = df.set_index("date")

inflation_list = list(df.loc[startDate:endDate, " inflation-rate"])
print(inflation_list)

list_for_p = []
for item in inflation_list:
    principal_amt += principal_amt*(item/100)
    list_for_p.append(principal_amt)

print(list_for_p)
final_amt += principal_amt
print(final_amt)

This is how the output looks like:
Enter the starting year 2016
Enter the ending year 2018
Enter the amount 100
2016-12-31 2018-12-31
[4.941, 2.4909, 4.8607]
[104.941, 107.554975369, 112.782900056761]
112.782900056761

I want to ask if my calculation is correct and if you have any other suggestion then please give me. It will be helpful. Thanks!


texts: Accessing the only element of Java ResultSet

texts:
Does this code look OK?

public Map<String, String> getById(long id) {
    String sql = "select * from " + this._TABLE_NAME + " where id = ?";
    PreparedStatement p;
    Map<String, String> result = new HashMap<String, String>();
    try {
        p = conn.prepareStatement(sql);
        p.setLong(1, id);
        ResultSet rs = p.executeQuery();

        ResultSetMetaData rsmd = rs.getMetaData();
        int fieldsCount = rsmd.getColumnCount();
        // is this ok?
        rs.next();

        for (int i=1;i<fieldsCount+1;i++) {
            String cName = rsmd.getColumnName(i);
            result.put(cName, rs.getString(cName));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return result;

}


texts:
In my library for styling the Console I need to be able to add or update two styles: color and background-color.

The use case is very simple. There is a string with styles that I'm building and that I update to change the color if necessary.

I divided this task into three steps:

explode the string into declarations
manipulate the style
reconstruct the style

Example Each of these steps has its own extension:

void Main()
{
    var style = "color: red;";

    style
        .ToDeclarations()
        .AddOrUpdate(
            ("color", "black"),
            ("background-color", "blue")
        )
        .ToStyle()
        .Dump();
}

These extensions are used by higher-level extensions that call them with const string for property names. I just used simple strings in LINQPad.

Code Their implementation is very straightforward. They use only LINQ and tuples.

public static class CssExtensions
{
    public static IEnumerable<(string property, string value)> ToDeclarations(
        this string style)
    {
        const string declarationPattern = @"(?<property>[a-z-]+):\s*(?<value>.+?)(;|$)";

        return
            Regex
                .Matches(style, declarationPattern, RegexOptions.IgnoreCase)
                .Cast<Match>()
                .Select(m => (
                    property: m.Value("property").Trim(),
                    value: m.Value("value").Trim())
                );
    }

    public static IEnumerable<(string property, string value)> AddOrUpdate(
        this IEnumerable<(string property, string value)> declarations,
        params (string property, string value)[] updates)
    {
        return
            declarations
                .Concat(updates)
                .GroupBy(t => t.property)
                .Select(t => t.Last())
                .Skip(t => string.IsNullOrEmpty(t.value));
    }

    public static string ToStyle(
        this IEnumerable<(string property, string value)> declarations)
    {
        return
            declarations
                .Select(t => $"{t.property}: {t.value};")
                .Join(" ");
    }
}

As the use case is very simple and I also don't need to parse any complex styles so are the extensions, just a simple regex with some string manipulation.

I update the style by grouping by the property and pick the last one if there are mutliple ones, if there is none yet, then a new style is added. If the value happens to be null or Empty then it's removed.

There are three more extensions: one that I use to Join declarations, one Value shortcut for regex and a Skip that I use as an inverse of Where to use positive conditions if I want to exclude some cases.

public static class EnumerableExtensions
{
    public static string Join<T>(this IEnumerable<T> values, string separator)
    {
        return string.Join(separator, values);
    }

    public static IEnumerable<T> Skip<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        return source.Where(x => !predicate(x));
    }
}

public static class MatchExtensions
{
    public static string Value(this Match match, string groupName)
    {
        return match.Groups[groupName].Value;
    }
}

Should I still improve it in any way?


texts: Saving an Array to PropertiesService in Google Apps Script

texts:
I have the same array set up as a variable inside of each function - I want to make this easier to manage. The array contains multiple strings of values. I’ve attached code below that I've been working on.
I would like to save this array to PropertiesService making it persistent across all executions. I already tried moving the variable out of the functions to make it global, but since I am iterating through the array, this didn't seem to work. I believe each call resets a global array. PropertiesService is hard to figure out because it only accepts one value, hoping someone can help with a string!
Var artistIdsArray = [“29457”, “28194”, “91424”, “53523”, “64824”];

PropertiesService.getScriptProperties().setProperty('artistNumber', JSON.stringify(artistIdsArray) );

var  artistId1 = JSON.parse(PropertiesService.getScriptProperties().getProperty(artistNumber));

The code I have seems to be working. There are no errors. Just wanted a second set of eyes before I add it across the script.


texts: Find all classes A that implement B and aggregate both A and T to build a map out of them

texts:
In my project I have the following base interfaces used through the application:

interface Node { /* ... */ }
interface NodeService<T> { /* ... */ }

Concrete classes might look as follows:

class User implements Node { /* ... */ }
class UserService implements NodeService<User> { /* ... */ }

class Entity implements Node { /* ... */ }
class EntityService implements NodeService<Entity> { /* ... */ }

In the end I want to have a Map<String, Class<? extends NodeService<Node>>> that in the case above might look as follows:

Map{
    User=UserService.class,
    Entity=EntityService.class
}

My current solution has the following approach:

Using the Reflections library find all classes implementing NodeService
Iterate over all generic interfaces of said classes until we find the NodeService interface
Access its first and single generic type argument
Cast the type to a class and map it to its simple name
Build a tuple (using vavr in this case) containing the simple name and the service class we found in step 1
Flatten the result and collect the tuples into a map

@SuppressWarnings({"unchecked", "rawtypes"})
final Map<String, Class<? extends NodeService<Node>>> nodeServices =
    new Reflections(BackendApplication.class.getPackageName())
        .getSubTypesOf(NodeService.class).stream()
            .map(
                serviceClass ->
                    Stream.of(serviceClass.getGenericInterfaces())
                        .filter(ParameterizedType.class::isInstance)
                        .map(ParameterizedType.class::cast)
                        .filter(type -> type.getRawType().equals(NodeService.class))
                        .map(ParameterizedType::getActualTypeArguments)
                        .map(typeArguments -> typeArguments[0])
                        .filter(Class.class::isInstance)
                        .map(Class.class::cast)
                        .map(Class::getSimpleName)
                        .map(nodeClass -> Tuple.of(nodeClass, (Class) serviceClass))
                        .collect(Collectors.toSet()))
            .flatMap(Collection::stream)
            .collect(Collectors.toMap(Tuple2::_1, Tuple2::_2));

I am surprised that this works in the first place but the code is ridiculously complex and I am looking for suggestions on how to rewrite this. Some of my biggest pain points are the handling of the classes generic interfaces even though in the end I'm only interested in a single one of them making the stream in the middle introduce unnecessary nesting. Furthermore the way I attempt to navigate to the correct type is really bothering me as well.

Thus I am open for your input on how to improve this chunk of code.

The performance of this snippet is surprisingly good. I am mainly looking for input on the readability and refactoring this to make it much more maintainable, even at the cost of performance since this will be only invoked once during the application lifecycle.


texts: turn a dict that may contain a pandas dataframe to several dicts

texts:
I have a dict that may be 'infinitely' nested and contain several pandas DataFrame's (all the DataFrame's have the same amount of rows).

I want to create a new dict for each row in the DataFrame's, with the row being transformed to a dict (the key's are the column names) and the rest of the dictionary staying the same.

Note: I am not making a cartesian product between the rows of the different DataFrame's.

I have an example in my SO question

here is what i came up with:

import pandas as pd
from copy import deepcopy
from functools import partial

def map_keys_by_type(d, typ, path=None):
    for k,v in d.items():
        p = path.copy() if path else []
        p.append(k)
        if isinstance(v, typ):
            yield p
        if isinstance(v, dict):
            yield from map_keys_by_type(v, typ, p)

def nested_get(nested_key, input_dict):
    internal_dict_value = input_dict
    for k in nested_key:
        internal_dict_value = internal_dict_value.get(k, None)
        if internal_dict_value is None:
            return None
    return internal_dict_value

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

def dup_dicts(keys, iter_of_values, init_dict):
    for values in iter_of_values:
        init_dict = deepcopy(init_dict)
        [nested_set(init_dict, key, value) for key, value in zip(keys, values)]
        yield init_dict

if __name__ == '__main__':
    keys = list(map_keys_by_type(d, pd.DataFrame))
    dfs = map(partial(nested_get, input_dict=d), keys)
    dfs_as_dicts = map(partial(pd.DataFrame.to_dict, orient='records'), dfs)
    iter_of_dicts = dup_dicts(keys,zip(*dfs_as_dicts), d)

any improvements?


texts:
I decided to write a simple factorial() function in JavaScript and ask here for opinions. The idea is to further improve my JavaScript style and learn the best practices. Is there something bad with this code? What can be improved? Any suggestions are welcome.

/**
 * Calculates the factorial of a given non-negative finite integer.
 * @param {Number} n
 * @return {Number} factorial
 * @throws TypeError if n is not a Number
 * @throws TypeError if n is a Number but not an integer
 * @throws RangeError if n is a negative integer
 */
function factorial(n) {
    if (typeof n !== "number") {
        throw new TypeError("factorial() expects a number.");
    }
    if (Math.floor(n) !== n) {
        throw new TypeError("factorial() expects an integer.");
    }
    if (n < 0) {
        throw new RangeError("factorial() expects a non-negative number.");
    }

    // 170 is the biggest integer whose factorial does not become Infinity in JavaScript.
    // Therefore, we can improve performance by checking directly.
    // This if statement also handles the important edge case of n === Infinity, which
    // would cause the function to be stuck forever.
    if (n > 170) {
        return Infinity;
    }

    var accumulator = 1;

    for (var i = 2; i <= n; i++) {
        accumulator *= i;
    }

    return accumulator;
}


texts:
I'm currently going over Robert Sedgewick Algorithms book and I'm trying to recreate his Java implementations in Ruby. I would like to know If I'm following best practices. I try to use clean code principles, making the code readable and easy to comprehend. If there are any improvements please share. Constructive feedback is highly appreciated.

class Merge
  attr_accessor :aux

  def sort_public(a)
    @aux = []
    sort(a,0, a.length - 1)
  end

  def merge(a, lo, mid, hi)
    i = lo
    j = mid + 1

    k = lo
    while k <= hi do
      @aux[k] = a[k]
      k += 1
    end

    k = lo
    while k <= hi do
      if i > mid
        a[k] = @aux[j]
        j += 1
      elsif j > hi
        a[k] = @aux[i]
        i += 1
      elsif aux[j] < aux[i]
        a[k] = @aux[j]
        j += 1
      else
        a[k] = @aux[i]
        i += 1
      end

      k += 1
    end

    a
  end

  private

  def sort(a, lo, hi)
    return if hi <= lo
    mid = lo + (hi - lo) / 2
    sort(a,lo, mid) #sort left half
    sort(a,mid + 1, hi) # sort right half
    merge(a,lo, mid, hi)
  end
end

merge = Merge.new

a = ["M", "E", "R", "G", "E", "S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"]

p merge.sort_public(a)


texts:
To summarize from a previous question, the user selected a starting date, an ending date, and a region. From these choices, an array of weeks and regions are created, and users enter values ("points") that correspond to a particular week and region. This is what it looks like right now (some parts are hard-coded for testing purposes):

$date_array = Array("01/01/2012", "01/08/2012", "01/15/2012");
$region_array = Array("NYC", "DC");

<form name="test_form" id="test_form" method="post">

        <?php
            foreach ($date_array as $date)
                {
                echo "".$date."	";
                }
        ?>

    <?php
    foreach ($region_array as $region)
        {
        echo "
";
        echo "".$region."	";
        foreach ($date_array as $date)
            {
            echo '<input type="text" name='.$region."-value1_".$date.'><input type="text" name='.$region."-value2_".$date.'>	';

            }
        echo "
";
        }
    ?>

<input type="submit" name="submit">

And the next part:

if (isset($_POST['submit']))
{
    foreach ($_POST as $k=>$v)
    {
    if ($k != "submit") // use even and odd count to differentiate TRP and CPP
        {
        // split the form input on _
        $input = explode("_", $k);
        echo "
Region: " . $input[0];
        echo "
Date: " . $input[1];
        echo "
Value: " . $v;
        }
    echo "
";
    }
}

So basically, in this example it outputs 12 times:

Region: NYC-value1
Date: 01/01/2012
Value: 500

Region: NYC-value2
Date: 01/01/2012
Value: 5

Region: NYC-value1
Date: 01/08/2012
Value: 600

I want to catch the value1 and value2 while the loop is running, but as it stands it loops through both of them before going onto the next date/region. My idea, as I put in comments, was to have a counter of even and odd numbers and simply tell if it was doing value1 or value2 based on that.

Is this a good idea or am I missing something fundamentally simpler?


texts:
Below is an LLVM pass that I've written to rename all functions in an LLVM bitcode file. I would appreciate tips on what is well done and what is poorly done in the code below. In particular, is there a better way to go about writing LLVM passes. Bear in mind that I'm a novice at programming and so would also appreciate it if you could direct me to any resources that would be useful in improving my C++ code.

#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeFinder.h"
#include "llvm/Transforms/IPO.h"

using namespace llvm;

namespace {

  struct FunctionRenamer : public ModulePass {
    static char ID; // Pass identification
    FunctionRenamer() : ModulePass(ID) {
      initializeFunctionRenamerPass(*PassRegistry::getPassRegistry());
    }

    void getAnalysisUsage(AnalysisUsage &AU) const override {
      AU.addRequired<TargetLibraryInfoWrapperPass>();
      AU.setPreservesAll();
    }

    bool runOnModule(Module &M) override {
      // Rename all functions
      const TargetLibraryInfo &TLI =
        getAnalysis<TargetLibraryInforWrapperPass>().getTLI();
      for (auto &F : M) {
        StringRef Name = F.getName();
        LibFunc Tmp;
        // Leave library functions alone because their presence or absence
        // could affect the behaviour of other passes.
        if (Name.startswith("llvm.") || (!Name.empty() && Name[0] == 1) ||
            TLI.getLibFunc(F, Tmp))
          continue;

        F.setName(Name + "_2");
      }
      return true;
    }
  };
}

char FunctionRenamer::ID = 0;
INITIALIZE_PASS_BEGIN(FunctionRenamer, "functionrenamer",
                      "Rename all functions", false, false);
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass);
INITIALIZE_PASS_END(FunctionRenamer, "functionrenamer",
                    "Rename all functions", false, false);
// ===-------------------------------------------------------==//
//
// Function Renamer - Renames all functions
//
ModulePass *llvm::createFunctionRenamerPass() {
  return new FunctionRenamer();
}


texts:
My problem is the following: I wrote a method, which counts words and returns a hash. There is a Ruby idiom which was found by me in some of the forums discussions, which I don't understand.

Here is the whole code:

text = "bla bla blahh blahh"
def count_words(string)
  inp = string.downcase.scan(/\b[\'a-z]+\b/i).inject(Hash.new 0){|c,w| c[w]+=1;c }
  return inp
end
puts count_words(text)

Here is the idiom: inject(Hash.new 0){|c,w| c[w]+=1;c }

My concrete questions are the following:

1) How it understands when we should add 1 to the particular key?

2) As far as I understand "inject" method, "c" is some sort of counter. So how does it happen that we write c[w]?


texts: Reflecting and counting points on a 2D grid

texts:
First number indicates the number of points, followed by N points
  (x,y). Then the next number indicates Q num_queries,  followed by Q queries:

  Reflect all points between point i and j both including along the
  X axis. This query is represented as "X i j"
  Reflect all points between point i and j both including along the Y axis. This query is
  represented as "Y i j"
  Count how many points between point i and j both including lie in each of the 4 quadrants. This query is
  represented as "C i j"

  Sample Input

4
1 1
-1 1
-1 -1
1 -1
5
C 1 4
X 2 4
C 3 4
Y 1 2
C 1 3

  Sample Output

1 1 1 1
1 1 0 0
0 2 0 1

How can i improve this code for better metrics?

import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author cypronmaya
 */
class Point {

    int x;
    int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Quad_query {

    private ArrayList<Point> arrayList;

    public Quad_query(int capacity) {
        this.arrayList = new ArrayList<Point>(capacity);
    }

    public static void main(String args[]) {

        Scanner scanner = new Scanner(System.in);
        int num_of_points = scanner.nextInt();
        Quad_query quad_query = new Quad_query(num_of_points);
        for (int i = num_of_points; --i >= 0;) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            quad_query.add(x, y);
        }
        int num_of_queries = scanner.nextInt();
        for (int i = num_of_queries; --i >= 0;) {
            char c = scanner.next().charAt(0);
            quad_query.query(c, scanner.nextInt() - 1, scanner.nextInt() - 1);
        }
    }

    public void add(int x, int y) {
        Point point = new Point(x, y);
        arrayList.add(point);
    }

    public void query(char c, int i, int j) {

        switch (c) {
            case 'C':
                queryC(i, j);
                break;
            default:
                queryXY(c, i, j);
                break;
        }
    }

    public void queryC(int i, int j) {

        int quad_1 = 0, quad_2 = 0, quad_3 = 0, quad_4 = 0;
        for (int k = i; k <= j; k++) {
            Point pnt = arrayList.get(k);
            int pnt_x = pnt.x;
            int pnt_y = pnt.y;
            if (pnt_x > 0 && pnt_y > 0) {
                quad_1++;
            } else if (pnt_x < 0 && pnt_y > 0) {
                quad_2++;
            } else if (pnt_x < 0 && pnt_y < 0) {
                quad_3++;
            } else if (pnt_x > 0 && pnt_y < 0) {
                quad_4++;
            }
        }
        System.out.println(quad_1 + " " + quad_2 + " " + quad_3 + " " + quad_4);
    }

    private void queryXY(char c, int i, int j) {

        for (int k = i; k <= j; k++) {
            Point pnt = arrayList.get(k);
            int pnt_x = pnt.x;
            int pnt_y = pnt.y;
            if (c == 'X') {
                pnt = new Point(pnt_x, -pnt_y);
            } else if (c == 'Y') {
                pnt = new Point(-pnt_x, pnt_y);
            }
            arrayList.set(k, pnt);
        }
    }
}


texts:
When you only want a couple styles from a workbook but not all of them it's easier to merge styles then remove those you don't want.

How can I improve the form or the backing code?

Userform with styles listed.

'CustomStyleRemoverForm
Private Sub UserForm_Initialize()
    ListStyles
End Sub

Private Sub ListStyles()
    CustomStylesListBox.Clear

    Dim listStyle As Style
    For Each listStyle In ActiveWorkbook.Styles
        If Not listStyle.BuiltIn Then
            CustomStylesListBox.AddItem listStyle.Name
        End If
    Next
End Sub

Private Sub SelectAllButton_Click()
    CheckAllBoxes True
End Sub

Private Sub UnselectAllButton_Click()
    CheckAllBoxes False
End Sub

Private Sub InvertSelectionButton_Click()
    Dim counter As Long
    For counter = 0 To CustomStylesListBox.ListCount - 1
        CustomStylesListBox.Selected(counter) = Not CustomStylesListBox.Selected(counter)
    Next
End Sub

Private Sub CheckAllBoxes(ByVal updateValue As Boolean)
    Dim counter As Long
    For counter = 0 To CustomStylesListBox.ListCount - 1
        CustomStylesListBox.Selected(counter) = updateValue
    Next
End Sub

Private Sub RemoveSelectedButton_Click()
    Dim counter As Long
    For counter = 0 To CustomStylesListBox.ListCount - 1
        If CustomStylesListBox.Selected(counter) Then
            ActiveWorkbook.Styles(CustomStylesListBox.List(counter)).Delete
        End If
    Next

    ListStyles
End Sub