texts: How can I tidy up this servlet parameter check code?

texts:
One of the servlet in my web app takes parameters in the form www.service.com/servletname/parameter1/parameter2.

The first parameter is required and the second parameter is an integer.
I've made some code to validate the parameters but it looks really really messy. Is there a nicer and cleaner way I can write the following:

Thanks :)

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType(CONTENT_TYPE);
    PrintWriter out = resp.getWriter();
    int maximumResults = defaultMaxResults;

    // check that parameters were provided
    if (req.getPathInfo() == null)
    {
       out.println( JSONHelper.writeStatus(false, Status.TOO_FEW_ARGS.getMessage()));
        return;
    }

    // seperate parameters
    String[] parameters = req.getPathInfo().split(PARAMETER_SEPERATOR);

    if (parameters.length < MIN_NUM_PARAMETERS)
    {
        out.println( JSONHelper.writeStatus(false, Status.TOO_FEW_ARGS.getMessage()));
        return;
    }

    // validate parameters
    if (parameters.length > MIN_NUM_PARAMETERS)
    {
        try
        {
        maximumResults = Integer.parseInt(parameters[2]);
        } catch (NumberFormatException nfe)
        {
        out.println( JSONHelper.writeStatus(false, Status.INVALID_MAX_RESULTS.getMessage()));
        return;
        }
    }


texts: List enrolled users & show checkmark if all activities are complete

texts:
I'm a beginner with rails working on a rails 4 project to use with my students. Users enroll in lessons; on enrollment, four activities are created for each user (expositions, scrambled, dictations, and spellings). Each of these activities has a number of words which are set to false in the db upon creation, and change to true as the user rewrites them correctly. At the bottom of each lesson's view I'm displaying a list of enrolled users. If the user completes all four activities, I'm displaying a font-awesome checkmark icon.

I'm noticing as more students enroll in each lesson that loading times for the lesson show view are increasing--most probably because my setup to find whether each user completed the lessons is inefficient.

In my lessonss controller I wrote helper methods to list the lesson's enrolled users, and to generate arrays with users who completed each of the lessons activities. In the view page, I'm testing whether each of the listed users completed all four activities in order to add the "completed" checkmark to his or her name.

As things are right now the code does what it's supposed to, but I'd love to learn and improve the student-user's experience. Any feedback regarding how I can improve this process will be well received.

In lessons controller:

  helper_method :enrolled_users
  def enrolled_users
    lesson = Lesson.find(params[:id])
    enrollments = lesson.enrollments
    enrolled_users = enrollments.map { |enrollment| enrollment.user }
  end

  helper_method :completed_scram
  def completed_scram
    lesson = Lesson.find(params[:id])
    completed_scram = enrolled_users.map do |user|
      current_enrollment = lesson.enrollment_for(user)
      all_unscramble = current_enrollment.scrambled_words
      user if all_unscramble.all? { |scrambled| scrambled.completed == true }
    end
  end

  helper_method :completed_expos
  def completed_expos
    lesson = Lesson.find(params[:id])
    completed_expos = enrolled_users.map do |user|
      current_enrollment = lesson.enrollment_for(user)
      all_expos = current_enrollment.word_expositions
      user if all_expos.all? { |expos| expos.completed == true }
    end
  end

  helper_method :completed_dicts
  def completed_dicts
    lesson = Lesson.find(params[:id])
    completed_dic = enrolled_users.map do |user|
      current_enrollment = lesson.enrollment_for(user)
      all_dicts = current_enrollment.word_dictations
      user if all_dicts.all? { |dict| dict.completed == true }
    end
  end

  helper_method :completed_spel
  def completed_spel
    lesson = Lesson.find(params[:id])
    completed_sp = enrolled_users.map do |user|
      current_enrollment = lesson.enrollment_for(user)
      all_sp = current_enrollment.image_spellings
      user if all_sp.all? { |spell| spell.completed == true }
    end
  end

In the view:

<% unless enrolled_users.count == 0 %>

Enrolled users:

    <% enrolled_users.uniq.each do |user| %>

          <%= user.username %>

          <% if completed_scram.include?(user) && completed_expos.include?(user) && completed_dicts.include?(user) && completed_spel.include?(user) %>

          <% end %>

    <% end %>

<% end %>


texts:
This is my attempted solution to Question 1.3 from "Cracking the Code Interview", 6th ed.

Question:

  Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the true length of the string.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
// Input:  "Mr John Smith    ", 13
// Output: "Mr%20John%20Smith"

int countSpaces(char* str) {
  int i = 0, j = 0;
  while (str[i] != '\0')
    if ( str[i++] == ' ')
      j++;

  return j;
}

char* replaceChars(char* str, int length) {
  int x = countSpaces(str);
  int stringLength = length + x - x/3;

  char* urlifiedString = malloc((stringLength + 1) * sizeof(char));
  int i = 0, j = 0;
  while (i < stringLength) {
    if (str[j] != ' ') {
      urlifiedString[i++] = str[j];
    } else if (str[j] == ' '){
      urlifiedString[i++] = '%';
      urlifiedString[i++] = '2';
      urlifiedString[i++] = '0';
    }
    j++;
  }
  urlifiedString[stringLength] = '\0';
  return urlifiedString;
}

int main() {
  char* result1 = replaceChars("Mr John Smith    ", 13);
  printf("%s\n", result1);
  printf("%li\n", strlen(result1));
  assert(strcmp("Mr%20John%20Smith", result1) == 0);
  free(result1);

  char* result2 = replaceChars("lol  lol lol      ", 12);
  printf("%s\n", result2);
  assert(strcmp("lol%20%20lol%20lol", result2) == 0);
  free(result2);

  char* result3 = replaceChars("", 0);
  assert(strcmp("", result3) == 0);
  free(result3);

  return 0;
}


texts:
Original code: Getting name from user, and handling any errors in C

I fixed the bugs. Is there anything else to consider?

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

#define BUFFSIZE 10

/*Checks to see if name contains actual characters and not just whitespace*/
bool hasAlpha(unsigned const char * name, size_t buffersize)
{
    for (size_t index = 0; index < buffersize && name[0] != '\0' ; ++index) {
        if (isalpha(name[index]))
            return true;
    }

    return false;
}

/* @param[nlcspan], Used to determine if newline char was in C string or not */
/* @param[incomplete], If true, new line character is still in the buffer i.e. need to clear buffer*/

void retrieveName(unsigned char* name, size_t buffersize)
{
    for (;;) {
        if (fgets(name, buffersize, stdin) != NULL) {
            size_t nlcspn = strcspn(name, "\n");
            bool incomplete = name[nlcspn] == 0;
            name[nlcspn] = 0;
            if (incomplete) {
                int bufferclear;
                while ((bufferclear = getchar()) != '\n' && bufferclear != EOF);
            }
            if (name[0] == '\0' || !hasAlpha(name, buffersize)) {
                printf("Invalid name entered please try again...\n"
                       "USER NOTE: name cannot be empty and must contain at least one char\n");
            }
            else {
                return;
            }
        }
        else
            printf("Memory could not be allocated please try again...\n");
    }
}

int main(void)
{
    size_t len = BUFFSIZE;
    unsigned char name[BUFFSIZE];

    printf("Enter Name: ");
    retrieveName(name, len);
    printf("Your name is: %s\n", name);

    printf("Enter Name: ");
    retrieveName(name, len);
    printf("Your name is: %s\n", name);

    printf("Press enter to continue...\n");
    getchar();

    return 0;
}


texts: Disabling a form button while there's an http request running

texts:
I have a form built with react, formik and yup, and this form has some async validations. Apparently, some users were able to bypass these validations, and to prevent some errors, I wanted to disable the submit button when there's a pending http request.

Many years ago, I used to handle this very easily with jQuery, but now, this is not the case.

I came up with a solution where I used the useEffect hook to set a state in case there's an http request running, and the way I'm detecting this is what I wanted your opinion.

Basically:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Input } from '../../../../components/Formik';

const Form = props => {
  const [disableSubmitBtn, setDisableSubmitBtn] = useState(false);

  useEffect(() => {
    axios.interceptors.request.use(
      configs => {
        console.log('http req running');
        setDisableSubmitBtn(true);
        return configs;
      },
      error => {
        return Promise.reject(error);
      },
    );
    console.log('no http req running');
    setDisableSubmitBtn(false);
  }, [disableSubmitBtn]);

  return (
    <form
      className="form-horizontal"
      onSubmit={e => {
        props.handleSubmit(e);
      }}
    >
      {props.settings.bonuscode && (
        <fieldset>
          <Input
            id="marketing.bonus_code"
            {...props.user.marketing.bonus_code}
            {...props}
            classNameLabel="col-md-5"
            classNameInput="col-md-7"
          />
        </fieldset>
      )}

      <button
        id="wordreg-form-submit"
        type="submit"
        disabled={props.settings.formSubmited || disableSubmitBtn}
      >
        Submit
      </button>
    </form>
  );
};

export default Form;

So what matters is actually the code inside the useEffect hook. Whad do you think about it?
Is it ok to check for pending http requests this way?


texts: "Can you answer these queries I" challenge

texts:
I have tried to solve the following problem on SPOJ.com:

  You are given a sequence

A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1 ≤ N ≤ 50000 )

  A query is defined as follows:

Query(x,y) = Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }

  Given M queries, your program must output the results of these queries.

When I run it, I get a time limit error, but I don't know why.

import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;

 class TestClass {

static int[] dist ;
static int[][][] vis;
static ArrayList<Integer>[] resu;
static char[][] graph;
static int max;
static int min;
static int[] dp;
static int zz;
static int zzz;
static nodes[] som;
static nodes temp;
static boolean fin;

static class nodes{

      int sum ;
      int presum;
      int suffsum;
      int max;

      public nodes(){

      }
      public nodes(int sum , int presum , int suffsum , int max){

            this.sum = sum;
            this.presum = presum;
            this.suffsum = suffsum;
            this.max = max;
      }
}

public static nodes merge(nodes a , nodes b){

    nodes result = new nodes();

    result.sum =  a.sum + b.sum;
    result.presum = Math.max(a.presum, a.sum + b.presum);
    result.suffsum = Math.max(b.suffsum, b.sum+a.suffsum);
    result.max  = Math.max(Math.max(a.sum, b.sum), a.suffsum+b.presum);

    return result;

}

public static void maketree(int current ,int a , int b ,int[] arr){
//  System.out.println(a+" "+b+" "+current);
     if(a>b) return;

     if(a==b)
     {
         int x = arr[a];
         nodes newnode = new nodes(x,x,x,x);
         som[current] = newnode;
         return;
     }

     maketree(2*current, a, (a+b)/2, arr);
     maketree(2*current+1, (a+b)/2+1, b, arr);

     som[current] = merge(som[2*current], som[2*current+1]);

}

public static nodes query(int current , int a, int b, int i , int j){

     if(a==i && b==j) return som[current];

     int mid = (a+b)/2;

     if(j<=mid) return query(2*current, a, (a+b)/2, i, j);
     else if(i>mid) return query(2*current+1, (a+b)/2+1, b, i, j);
     else{

         return merge(query(2*current, a, (a+b)/2, i, j), query(2*current+1, (a+b)/2+1, b, i, j));
     }
}

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

Scanner in = new Scanner(new InputStreamReader(System.in));

int n = in.nextInt();
int[] a = new int[n+1];
som = new nodes[10000000];
for(int i=1;i<=n;i++) a[i]=in.nextInt();

temp = new nodes(Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE);

maketree(1, 1, n, a);

int Q = in.nextInt();

for(int i=0;i<Q;i++){

    int l =in.nextInt();
    int r =in.nextInt();
    System.out.println(query(1, 1, n, l, r).max);
    //System.out.println(som[2].max+ " "+ som[4].max +" "+ som[5].max);
}

}
 }


texts: Laravel Pagination: a new one adapted from an old Dreamweaver extension

texts:
I'm new to Laravel and I'm trying to port the most important old-procedural-code snippets and libraries I collect in some years

I missed a nice Pagination I had in an old Dreamweaver extension and I tried to replicate it: I asked on Stack Overflow but was unsatisfied, so I decided to play around and convert the Dreamweaver extensions code with a lot of patience.

Here is the result and it works very fine (I tried in Laravel 4.2 but it should work everywhere, as long as there is the included Bootstrap Paginator), but, since this is my first Laravel improvement I was wondering if this code can be improved.

<?php namespace Illuminate\Pagination;

class DreamweaverPresenter extends BootstrapPresenter {

    protected $TFM_LimitLinksEndCount = 5; // links' range to show

    // Some useful properties, taken from the old DW extension and adapted to OOP
    // This is the part that maybe can be improved: I had no other ideas to adapt those old procedural variables
    // and put them in a costructor, but is there a better / more elegant way?
    function __construct(Paginator $paginator){
        parent::__construct($paginator);
        $this->TFM_startLink = max(1, $this->currentPage - intval($this->TFM_LimitLinksEndCount/2));
        $this->TFM_temp = $this->TFM_startLink + $this->TFM_LimitLinksEndCount - 1;
        $this->TFM_endLink = min($this->TFM_temp, $this->lastPage);
        if ($this->TFM_endLink != $this->TFM_temp){
            $this->TFM_startLink = max(1, $this->TFM_endLink - $this->TFM_LimitLinksEndCount + 1);
        }
    }

    // The following methods are simply adapted from Laravel Paginator code:
    // I copied/pasted/changed some other existent methods

    /**
     * Render the Pagination contents.
     *
     * @return string
     */
    public function render() // adapted from Presenter/render()
    {
        $content = $this->getPageRange($this->TFM_startLink, $this->TFM_endLink);
        return $this->getFirst().$this->getPrevious('&lsaquo;').$content.$this->getNext('&rsaquo;').$this->getLast();
    }

    /**
     * Get the first page pagination element.
     *
     * @param  string  $text
     * @return string
     */
    public function getFirst($text = '&laquo;') // adapted from Presenter/GetFirst()
    {
        // If the current page is less than or equal to one, it means we can't go any
        // further back in the pages, so we will render a disabled first button
        // when that is the case. Otherwise, we will give it an active "status".
        if ($this->currentPage <= 1)
        {
            return $this->getDisabledTextWrapper($text);
        }

        $url = $this->paginator->getUrl(1);

        return $this->getPageLinkWrapper($url, $text, 'first');
    }

    /**
     * Get the last page pagination element.
     *
     * @param  string  $text
     * @return string
     */
    public function getLast($text = '&raquo;') // adapted from Presenter/GetNext()
    {
        // If the current page is greater than or equal to the last page, it means we
        // can't go any further into the pages, as we're already on this last page
        // that is available, so we will make it the "last" link style disabled.
        if ($this->currentPage >= $this->lastPage)
        {
            return $this->getDisabledTextWrapper($text);
        }

        $url = $this->paginator->getUrl($this->lastPage);

        return $this->getPageLinkWrapper($url, $text, 'last');
    }
}


texts:
I've created a little program that basically does the same thing as psexec. It will connect to a host via computer name, or IP address, run the given command, and log the output into a file (little extra for myself). I would like some critique on what I've done, what can I do better, what did I do well, etc.. Some key points I would like to look at are (of course critique everything):

Logging to a file, is there better ways to do so?
Connecting and executing a shell command quicker

import wmi
import sys
import socket
import subprocess
import logging
import getpass
import os
import time
from colorlog import ColoredFormatter

log_level = logging.INFO
logger_format = "[%(log_color)s%(asctime)s %(levelname)s%(reset)s] %(log_color)s%(message)s%(reset)s"
logging.root.setLevel(log_level)
formatter = ColoredFormatter(logger_format, datefmt="%I:%M:%S")
stream = logging.StreamHandler()
stream.setLevel(log_level)
stream.setFormatter(formatter)
LOGGER = logging.getLogger('pyshellConfig')
LOGGER.setLevel(log_level)
LOGGER.addHandler(stream)

def create_log(dest_ip, host_ip, command, data):
    """
    :param dest_ip: Destination IP address
    :param host_ip: IP address of where the command was run
    :param command: Command that was run
    :param data: Output of the command

    Write the output of the run command to a log file for further analysis
    """
    log_path = "C:\\Users\\{}\\AppData\\pyshell".format(getpass.getuser())
    if not os.path.isdir(log_path):
        os.mkdir(log_path)

    with open("{}\\{}_LOG.LOG".format(log_path, __file__), "a+") as log:
        log.write("![{}][LOG FROM:{} TO:{}]COMMAND RUN: {} OUTPUT:{}\n".format(time.strftime("%m-%d-%Y::%H:%M:%S"),
                                                                               host_ip, dest_ip,
                                                                               command, data))

def connect(hostname, command=None):
    """
    :param hostname: Computer name or IP address
    :param command: Shell command to be run on the host

    Connect to the host and run a shell command on their system
    """
    LOGGER.info("Attempting to connect to host: '{}'".format(hostname))
    try:
        connection = wmi.WMI(hostname)  # Attempt to connect to the hostname
        if connection:
            LOGGER.info("Connected successfully, running command: '{}'".format(' '.join(command)))
            call = subprocess.Popen(command,
                                    shell=False,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            output = call.communicate("Running remote command...")  # Start running the command and save output to variable
            create_log(socket.gethostbyname(hostname), socket.gethostbyname(socket.gethostname()),
                       command, output)
            LOGGER.info("Command completed successfully.")
    except Exception, e:  # I don't think there's really anyway of getting the exact error from the shell
        error_message = "Failed to connect due to %s. " % e
        error_message += "\nThis could mean that '%s' is not the correct " % hostname
        error_message += "computer name, or that the host has refused it. "
        error_message += "You can try to connect via IP address, if the "
        error_message += "user is able to get it."
        LOGGER.fatal(error_message)

if __name__ == '__main__':
    help_page = """python shell.py [HOST] [COMMAND]"""
    error_message = ""

    try:
        if not sys.argv[1::]:  # User ARGV for the arguments to more match Psexec
            error_message += "You did not supply a hostname to run against\n{}".format(help_page)
            LOGGER.fatal(error_message)
            exit(1)
        elif not sys.argv[2::]:
            error_message += "You did not supply a command to run\n{}".format(help_page)
            LOGGER.fatal(error_message)
            exit(1)

        connect(sys.argv[1].upper(), command=sys.argv[2::])
    except IndexError:
        pass


texts: Merging trips to the same location with overlapping dates

texts:
I have a SQLite database that only contains the holidays for 1 user.

I have a new Trip object (newTrip) that has a StartDate(long unix time) and an EndDate(long unix time) and the trip Iso3Code(string) for the location.

I need to retrieve from the database all existing Trips that can be merged with the newTrip. A trip can be merged if the dates of the new trip fall at the same time of the existing trips or on the day before or after the existing trips and have the same Iso2Code`.

So far I have this:

public static List<Trip> GetTripsThatCanBeMerged(Trip trip)
{
    //ignore times - just get for that date and get the date before for the start date and the day after for the end data, as the day before and after can be merged.
    DateTime startDate = DateTimeHelper.UnixDateToDateTime(trip.StartDate).Date.AddDays(-1);
    DateTime endDate = DateTimeHelper.UnixDateToDateTime(trip.EndDate).Date.AddDays(1);

    //now convert back to unix
    long startDateUnix = DateTimeHelper.DateTimeToUnixTimestamp(startDate);
    long endDateUnix = DateTimeHelper.DateTimeToUnixTimestamp(endDate);

    List<Trip> trips = null;

    using (SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), _sqliteDatabasePath))
    {
        trips = conn.GetAllWithChildren<Trip>(p =>
            ((p.StartDate >= startDateUnix && p.StartDate <= endDateUnix) ||
            (p.EndDate >= startDateUnix && p.EndDate <= endDateUnix) ||
            (p.StartDate <= startDateUnix && (endDateUnix >= p.StartDate && endDateUnix <= p.EndDate))) &&
            p.Iso3Code == trip.Iso3Code
            , true);
    }

    return trips;
}

I think this is correct but can anyone suggest a less complex way of doing it, or see any errors.


texts: Powershell script to verify Linux-generated md5sum file

texts:
I'm moving some files from a Linux machine to a Windows machine over a low-speed, possibly buggy experimental communications channel that I want to test.  One of the tests is to transfer large numbers of large and small files and verify their cryptographic hashes at the receiving end.  On the Linux side, we're using md5sum to generate file hashes like so:
md5sum * > files.md5

Then the files are transmitted from the Linux machine to the Windows 10 machine.  What I'd like to do next is to verify the hashes on the plain-vanilla Windows machine (no Cygwin installed). So to mimic the default operation of md5sum -c files.md5 which would go through, line by line and verify each md5 checksum, I've written this Powershell script.  I'm a lot more at home in bash than in Powershell, so thought I might benefit from a review.
param (
    [Parameter(Mandatory=$true)][string]$infile
)
$basedir = Split-Path -Parent $infile
$badcount = 0
foreach ($line in [System.IO.File]::ReadLines("$infile")) {
    $sum, $file = $line.split(' ')
    $fullfile = "$basedir\$file"
    $filehash = Get-FileHash -Algorithm MD5 $fullfile
    if ($sum -eq $filehash.Hash) {
        Write-Host $file ": OK"
    } else {
        Write-Host $file ": FAILED"
        $badcount++
    }
}
if ($badcount -gt "0") {
    Write-Host "WARNING:" $badcount "computed checksums did NOT match"
}


texts:
Write a Compress class defines two static methods, gzipFile(), which
  compresses a file using GZIP compression format, and zipDirectory(),
  which compresses the files (but not directories) in a directory using
  the ZIP archive and compression format. gzipFile() uses the
  GZIPOutputStream class, while zipDirectory() uses the ZipOutputStream
  and ZipEntry classes, all from java.util.zip.

I am outputting the compressed file in the same directory as the input file.
For zipDirectory() method I have recursively found out the files present in the directory(including those in the sub directories), stored them in a List<File>, and added them to the zip.
How can I improve this code?

package beg_assignment8;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;

public class Compress {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Scanner sc = new Scanner(System.in);
        int op = sc.nextInt();
        String source = sc.next();
        switch (op) {
        case 1:
            GZIPFile(source);
            break;
        case 2:
            zipDirectory(source);
            break;
        }
    }

    public static void GZIPFile(String sourcePath) throws FileNotFoundException, IOException {
        File file = new File(sourcePath);
        String destPath = sourcePath + ".gz";

        try (
            FileOutputStream fos = new FileOutputStream(destPath);
            GZIPOutputStream gzos = new GZIPOutputStream(fos)
        ) {
            writeFileToOutputStream(file, gzos);
        }
    }

    public static void zipDirectory(String sourcePath) throws FileNotFoundException, IOException {
        File dir = new File(sourcePath);
        List<File> allFiles = getAllFiles(dir);
        String destPath = sourcePath + ".zip";

        try (
            FileOutputStream fos = new FileOutputStream(destPath);
            ZipOutputStream zos = new ZipOutputStream(fos)
        ) {
            for (File file : allFiles) {
                String zipFile =
                    file.getCanonicalPath().substring(dir.getCanonicalPath()
                            .length() + 1);
                ZipEntry ze = new ZipEntry(zipFile);
                zos.putNextEntry(ze);
                writeFileToOutputStream(file, zos);
                zos.closeEntry();
            }
        }
    }

    private static List<File> getAllFiles(File dir) {
        File[] files = dir.listFiles();
        List<File> allFiles = new ArrayList<>();
        for (File file : files) {
            if (file.isDirectory()) {
                List<File> allFilesRecur = getAllFiles(file);
                allFiles.addAll(allFilesRecur);
            } else {
                allFiles.add(file);
            }
        }
        return allFiles;
    }

    private static void writeFileToOutputStream(File file,
            OutputStream os) throws FileNotFoundException, IOException {
        try (
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis)
        ) {
            byte[] buffer = new byte[1024];
            int nBytesRead;
            while ((nBytesRead = bis.read(buffer, 0, buffer.length)) >= 0) {
                os.write(buffer);
            }
        };
    }
}


texts: A class to generate, save and load unique transaction reference numbers for an application

texts:
This code is a class I use in my financial market trading bot (note: I'm a daytrader-come-beginner programmer, not the other way around).

Although I have the application running successfully, it has major design flaws which I intend to now address ASAP.

An API requires that a unique transaction ref is submitted with each new order, otherwise, that order will be rejected. I have very little idea if this is a competent or robust design, I could not find any guidance on the issue elsewhere.

I'm very much open to refactoring or a completely new design.

class UniqueTransactionRef:
    """Transaction reference number iterator

    Loads, generates and saves unique transaction ref data for ``Bot`` orders

    :ivar file: absolute path the the .json transaction ref data file
    :ivar num: an integer representing the last generated transaction ref number
    """

    default_file = r"C:\Bot\Bot\trans_ref.json"

    def __init__(self, file=None):
        """Initialize the UniqueTransactionRef object

        :param file: an absolute path to a .json file containing the transaction
        reference number, as an integer
        """
        self.file = file if file else self.default_file
        self.num = 0
        self.load()

    def __iter__(self):
        return self

    def __next__(self):
        """Increment the self.num attribute. Save the value to the local file.

        :returns: a string formatted version of the self.num class attribute
        """
        self.num += 1
        self.save()
        return str(self.num)

    def get(self):
        """Call the ``next`` function on self """
        return next(self)

    def load(self):
        """Load the transaction ref data from the local file

        :raises errors.UniqueTransactionRefError: Cannot find file
        """
        try:
            with open(self.file) as f:
                self.num = json.load(f)
        except FileNotFoundError:
            raise errors.UniqueTransactionRefError(
                self.file,
                num=self.num,
                message="Cannot find file",
                )

    def save(self):
        """Save self.num to the designated local file

        :raises UniqueTransactionRefError:
        """
        try:
            with open(self.file, "w") as f:
                json.dump(self.num, f)
        except Exception as e:
            raise errors.UniqueTransactionRefError(self.file,
                                                     num=self.num,
                                                     message=e)
unique_trans_ref = UniqueTransactionRef()  # module level variable

Simplified example usage:

class Bot:
    def __init__(self, unique_trans_ref):
        self.unique_trans_ref = unique_trans_ref

    def construct_order():
        trans_ref = next(self.unique_trans_ref)


texts: Substring match within a text for given keywords

texts:
Goal:
Look for a substring match within a text for given Keywords. Keep the substring match if the levenshtein distance is smaller than the length of the Keyword divided by (x=10), else return an empty list.
(First of all my apologies if the code is of lower quality. I am quite good in R but very new to Python.)
Current implementation:
from fuzzywuzzy import process
from fuzzysearch import find_near_matches
import math

def fuzzy_extract(qs, ls, threshold, max_dist):
    ret = []
    for word, _ in process.extractBests(qs, (ls,), score_cutoff = threshold):
        for match in find_near_matches(qs, word, max_l_dist = max_dist):
            word = word[match.start:match.end]
            ret.append({"kw": qs, "word": word, "dist": match.dist})
    return(ret)

def get_match(text, keywords, treshold):
    keywords = [keyword.lower() for keyword in keywords]
    text = text.lower()

    candidates = []
    for li in [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords]:
        if len(li) > 0:
            for di in li:
                if di["dist"] <= math.ceil(len(di["word"])/treshold):
                    candidates.append(di)

    if(len(candidates) == 0):
        return([])

    out = str(candidates[0]["kw"])
    return(out)

keywords = ["apple", "banana", "cherry"]
text = "nana is Looking for an aple."

print(get_match(text, keywords, 10))

For me the part in the middle looks neither efficient and also not very declarative.
With part in the middle i mean the Code following:
for li in [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords]:

I started with something longer but more declarative:
candidates = [fuzzy_extract(query_string, ocr_text, 0, 1) for query_string in keywords_ordering]
lens = [len(candidate) > 0 for candidate in candidates]
candidate_lengths = list(compress(candidates, lens))
filtered = [candidate_length[0]["dist"] < math.ceil(len(candidate_length[0]["word"])/10) for candidate_length in candidate_lengths]
candidate_filtered = list(compress(candidate_lengths, filtered))

In R i would make usage of pipes for These cases to avoid the undeclarative variables in between.
Similar Topics:
Find a best fuzzy match for a string
(Difference is that in this question match candidates are compared to a single word and to a substring of a text).
https://stackoverflow.com/a/36132391/3502164
Custom implementation, rather long.


texts: Spiral a matrix of size NxN filled with integers from 1 up to and including n^2

texts:
I have written a solution in Clojure for the following question:

  When starting from the number 1 and adding three numbers on each row
  a 3x3 matrix is formed as follows:

1 2 3
4 5 6
7 8 9

  Starting from the upper left and spiraling inwards in a clockwise
  direction the following series is obtained: 1 2 3 6 9 8 7 4 5.

  Create a method spiral that finds the spiraling series for a \$n\times n\$ matrix.

I created a long and short solution. They are inspired by the following Stack Overflow answer: ruby - Looping in a spiral outside-in

Version with descriptive names:

(ns spiral.core
  (:require [clojure.core.matrix :as m]))

(defn create-numbers-matrix
  "creates a size x size matrix of numbers from 1 up to and including size."
  [size]
  (let [numbers (range 1 (inc (* size size)))
        partitions (partition size numbers)
        matrix (m/matrix partitions)]
    matrix))

(defn get-first-row [m]
  "gets the first row (index 0) of matrix m."
  (m/get-row m 0))

(defn delete-first-row [m]
  "returns matrix with the first row of the matrix m removed."
  (drop 1 (m/rows m)))

(defn transpose [m]
  "transposes matrix m."
  (m/transpose m))

(defn reverse-rows [m]
  "returns matrix m with rows reversed."
  (m/matrix (reverse m)))

(defn rotate-left [m]
  "rotates the matrix m 90 degrees to the left."
  (-> m
      transpose
      reverse-rows))

(defn rotate-and-chop [m]
  "repeatedly rotates matrix m 90 degrees and cuts off the
   top till matrix is empty."
  (if (empty? m) nil
      (conj (rotate-and-chop (-> m
                                 delete-first-row
                                 rotate-left))
            (get-first-row m))))

(defn spiral [size]
  "creates list of values in spiral from grid of size size"
  (let [numbers-matrix
        (create-numbers-matrix size)]
    (flatten (rotate-and-chop numbers-matrix))))

Short version:

(ns spiral.core
  (:require [clojure.core.matrix :as m]))

(defn spiral-one-liner [size]
  (flatten
   ((fn loop [m]
      (if (empty? m) nil
          (conj (loop (m/matrix (reverse (m/transpose (drop 1 (m/rows m))))))
                (m/get-row m 0))))
    (m/matrix (partition size (range 1 (inc (* size size))))))))

The short version is still longer than the Ruby version from the answer (because tail recursions errors appear the loop and recur syntax can, I believe, not be used).

I would be grateful if someone can take a look and provide some suggestions.


texts: Avoid passing variable from class to class

texts:
For context, I have a SourceControlSystem factory class that detects if a user is using Git, SVN, or another source control system and returns an object to interact with that source control system. The implementation is here, but I don't think it's very relevant.

So, at the start of my library, I have this single line:

@source_control_system = SourceControlSystem.create

Now the problem is that some classes depend on this variable. I have a Churn class that needs this variable, but a Churn class instance is only created inside of a Turbulence class.

So I'm doing stuff like the following:

First, I pass @source_control_system to a Turbulence instance:

Turbulence.new(@source_control_system).data

And then inside the Turbulence class:

class Turbulence
  def initialize(source_control_system)
    @source_control_system = source_control_system
  end

  ...

  # Turbulence doesn't need @source_control_system
  # It merely passes it to Churn
  def churn
    @churn ||= Churn.new(@paths, @source_control_system).churn
  end
end

And then I finally pass it to to the Churn class:

class Churn
  def initialize(paths, source_control_system)
    @paths = paths
    @source_control_system = source_control_system
  end

  # do stuff with @source_control_system here
end

Do you consider this to be a problem or not?

I don't think creating that variable is that expensive so I could just call SourceControlSystem.create twice, once inside the Churn class and another outside of it. Do you see any harm in that? I could do that but it seems... odd.

Or should SourceControlSystem be some sort of global singleton object? That way, every class that needed it could instantly access it and call methods on it. You know, like the Math module. That way, I wouldn't have to keep passing it as an argument to a bunch of classes.

How would you do it?


texts:
Basically, I'm trying to make a Simplifier that can take inputs in the form of a String and print out the solution step-by-step. Now that I've got it working, I think it has some cleanliness issues.

public static void test(String eqn) {
    char[] order = { '^', '*', '/', '+'};   //order of precendece
    int found, i, j;
    eqn = eqn.replace("-", "+-");       //Subtracting = Adding (-)ve number.
    eqn = eqn.replace(" ", "");         //Spaces can cause a lot of trouble.
    String eqnC, left, right;
    System.out.println("=>\t"+eqn);
    for(char op : order) {
        while ((found = eqn.indexOf(op)) > -1) {
            left = eqn.substring(0, found);
            right = eqn.substring(found + 1);
            //keep 'walking' up and down the String till a non-number encoutered.
            for( i = left.length() - 1; i >= 0; i--)
                if(!isPONumber(left.charAt(i)))
                    break;
            for( j = 0; j < right.length(); j++)
                if(!isPONumber(right.charAt(j)))
                    break;
            double lV = Double.parseDouble(left.substring(++i));    //left operand
            double rV = Double.parseDouble(right.substring(0, j));  //right operand
            eqn = left.substring(0, i) + putV(lV, rV, op) + right.substring(j);
            System.out.println("=\t" + eqn);
        }
    }
}

private static String putV(double a, double b, char op) {
    switch(op) {
        case '^':   return Math.pow(a, b) + "";
        case '/':   return (a / b) + "";
        case '*':   return (a * b) + "";
        case '+':   return (a + b) + "";
    }
    return null;
}

/*
 * Limit (for now) : decimal support.
 */
private static boolean isPONumber(char c) {
    return Character.isDigit(c) || c == '.' || c == '-';
}

Here are some outputs:

=>  2*84/6+7^2
=   2*84/6+49.0
=   168.0/6+49.0
=   28.0+49.0
=   77.0

=>  3^3/3^2
=   27.0/3^2
=   27.0/9.0
=   3.0

=>  400^0.5
=   20.0

I'd be grateful if anyone would comment and criticize and help me to clean-up my code. I also invite suggestions for making it better, improvising it and so on.


texts:
I wanted to write a simple Log class for PHP, I use ajax calls with AngularJS and often return the log in an array

Example:

$return['data'] = $returnedDataArray;
$return['log'] = $logDataArray;
$return['status'] = 'success';
echo json_encode($return);

I was hoping to implement a logging system in my other classes, like my DB wrapper, etc.

Example:

Log::put('sql', $sql, 'DB');
Log::put('fields', $fieldsArray, 'DB');

And than pass the log.

Example:

$return['log'] = Log::getLog();

Here is my Log class:

class Log {
    private static $_loggingOn = true, $_log = array();

    public static function put ($key, $value, $className = null, $functionName = null) {
        if ($className) {
            if ($functionName) {
                self::$_log[$className][$functionName][$key] = $value;
            } else {
                self::$_log[$className][$key] = $value;
            }
        } else {
            self::$_log[$key] = $value;
        }
    }

    public static function getLog () {
        if (self::loggingOn()) {
            return self::$_log;
        }
        return array('Logging is turned off.');
    }

    public static function loggingOn () {
        return self::$_loggingOn;
    }
}

I am wondering if using the static class would be a recommended approach?


texts: Find all palindromes in the danish language

texts:
I made a program to attempt to find all palindromes in the danish language. Words.txt contains about 50.000 lines of danish words. Palindromes.txt is empty initially.

Im running the program on a Intel® Core™ m3-7Y30 Processor - which has a base frequency of 1.00 GHz. Seeing as the program - as it currently stands - has to check 50.000 * 50.000 = 2.500.000.000 words, it is really slow. Ive been running it for about 25 minutes now without a result (unsuprisingly). I am fairly new to C++, and so I have no idea how to optimize this.

Thats why im posting here - any tips on how to optimize the speed of the program would be greatly appreciated!

#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <chrono>

std::string read_file(const std::string& path)
{
    std::ifstream file(path);
    if (!file.is_open())
    {
        std::cerr << "Couldent open file!" << std::endl;
    }
    std::string content = std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
    if (content.empty())
    {
        std::cerr << "Couldent read file content" << std::endl;
    }
    return content;
}

std::vector<std::string> split_words(const std::string& words_string)
{
    std::vector<std::string> words;
    words.reserve(50000);
    std::stringstream ss_word(words_string);
    std::string word;
    while (!ss_word.eof())
    {
        ss_word >> word;
        words.push_back(word);
    }
    return words;
}

std::vector<std::string> find_palinedromes(const std::vector<std::string>& words)
{
    std::vector<std::string> palindromes;
    std::string first_word = std::string();
    std::string second_word = std::string();

    for (int i = 0; i < words.size(); ++i)
    {
        for (int j = 0; j < words.size(); ++j)
        {
            first_word = words[i];
            second_word = words[j];
            std::reverse(first_word.begin(), first_word.end());

            if (first_word == second_word)
            {
                if (std::find(palindromes.begin(), palindromes.end(), first_word) == palindromes.end())
                {
                    palindromes.push_back(first_word);
                }
            }
        }
    }

    return palindromes;
}

void write_to_file(const std::string& path, const std::vector<std::string>& words)
{
    std::ofstream file(path);
    if (!file.is_open())
    {
        std::cerr << "Couldent open file!" << std::endl;
    }
    for (const std::string& word : words)
    {
        file << word + "\n";
    }
}

int main()
{
    auto start = std::chrono::high_resolution_clock::now();
    std::string words_string = read_file("C:/Users/A/source/repos/Bresenhams/Bresenhams/src/Words.txt");
    std::vector<std::string> words = split_words(words_string);
    std::vector<std::string> palindromes = find_palinedromes(words);
    write_to_file("C:/Users/A/source/repos/Bresenhams/Bresenhams/src/Palindromes.txt", palindromes);
    auto stop = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);
    std::cout << "Found all palindromes in: " << duration.count() << std::endl;
    return 0;
}


texts: Avoiding race in a sub-millisecond TOD timer

texts:
Part of the project I am working on is to maintain the time-of-day, at the sub-millisecond accuracy, while not overwhelming CPU.
The controller has a pretty standard timer, with two registers, COUNTER and PRELOAD. On each system tick COUNTER is decremented; once it reaches 0, the timer posts an interrupt, and reloads COUNTER with the value from PRELOAD.
The value in PRELOAD is calculated off-line, to let the counter expire (and post the interrupt), say, every 100 milliseconds. COUNTER is readable at any time, which allows for a sum-millisecond precision. Yet another timer register, STATUS, has a TIMER_STATUS_IF bit, which determines the state of the timer interrupt.
The timer's registers are memory mapped. Their definitions (along with the definition of timer) come from the manufacturer's #include file. The actual address map is irrelevant.
Here is the code:
static volatile uint32_t ticks;

void ISR timer_isr() {
    ticks++;
    timer->STATUS &= ~TIMER_STATUS_IF;
}

uint64_t usecs() {
    uint32_t counter1 = timer->COUNTER;
    uint32_t ticks1 = ticks;
    uint32_t counter2 = timer->COUNTER;
    uint32_t ticks2 = ticks;

    if (timer->STATUS & TIMER_STATUS_IF) {
        // The interrupt has been asserted, and the counter has been reloaded,
        // but the ISR has not been run (we are called from the higher priority
        // ISR). Increment ticks manually.
        assert(ticks1 == ticks2);
        ticks2 += 1;
    } else if (counter1 > counter2) {
        // We know that between reading counters the reload did not happen.
        // Trust the first reading of ticks.
        ticks2 = ticks1;
    }
    else { // Nothing happens here. It is purely an explanation.
        // We know that between reading counters the reload did happen.
        // Trust the second reading of ticks.
    }

    return ticks2 * US_PER_TICK + (timer->PRELOAD - counter2) / CLOCKS_PER_USEC;
}

This works fine unless some high priority ISR takes more than 100 ms to complete. I am fine with it. If any ISR takes that long, it is much more serious design problem.
What I don't like here.
I am a strong advocate of a comment-less style. To quote myself, "an explanatory comment means that you fail to express the intention in the code". However, I feel I need a large explanatory comment. Any hint on how to remove it is much appreciated.
TL;DR
For a bit of context, the code I inherited (not for a review)

uint64_t usecs() {
    uint32_t counter = timer->COUNTER;
    uint32_t ticks = ticks;
    return ticks * US_PER_TICK + (timer->PRELOAD - counter) / CLOCKS_PER_USEC;
}

once in a while exhibited time travel for about 100 ms into the future.


texts:
I wrote a method to check if each parenthesis in a string is closed. It should take into account the order in which a parenthesis is presented, e.g. "hello)goodbye(" should return false even though there are an equal number of opening and closing parentheses. My method is as follows:

def balance(chars: List[Char]): Boolean = {
    def findNextParen(chars: List[Char]): List[Char] = {
      return chars.dropWhile(char => char != ')' && char != '(')
    }

    def findClosingParen(chars: List[Char]): List[Char] = {
      val nextParen = findNextParen(chars)
      if(nextParen.isEmpty) {
        nextParen
      } else if(nextParen.head == '(') {
        findClosingParen(findClosingParen(nextParen.tail).tail)
      }
      else {
        nextParen
      }
    }
    val nextParen = findNextParen(chars)

    if(nextParen.isEmpty) {
      true
    } else if(nextParen.head == ')') {
      false
    } else if(findClosingParen(nextParen.tail).isEmpty) {
      false
    } else balance(findClosingParen(nextParen.tail).tail)
  }

is there a way to make this more Scala-y? I pretty much feel like I wrote Java code and compiled it with a Scala compiler.


texts:
I have three divs that change a video link when they are hovered. I have the code working in three different blocks but I am not sure how to combine them since it is very repetitive.

$('#videolink-sd').mouseenter(function(event) {
    //$(this).toggleClass('home-pager-hover');

    $('.top-clock').stop( true, true ).fadeOut();
    $('#'+videoID).stop( true, true ).hide();

    $('#'+videoID).stop( true, true ).get(0).pause();
    $('#'+mp4ID).stop( true, true ).attr('src', sdmp4);
    $('#'+oggID).stop( true, true ).attr('src', sdogg);
    $('#'+videoID).stop( true, true ).get(0).load();
    $('#'+videoID).stop( true, true ).get(0).play();

    $('.top-clock').stop( true, true ).removeClass('top-clock--visible');
    $('.top-clock-sd').stop( true, true ).addClass('top-clock--visible');

    $('#'+videoID).stop( true, true ).delay('500').fadeIn();
    $('.top-clock-sd').stop( true, true ).delay('500').fadeIn();
});

$('#videolink-sk').mouseenter(function(event) {
    //$(this).toggleClass('home-pager-hover');

    $('.top-clock').stop( true, true ).fadeOut();
    $('#'+videoID).stop( true, true ).hide();

    $('#'+videoID).stop( true, true ).get(0).pause();
    $('#'+mp4ID).stop( true, true ).attr('src', skmp4);
    $('#'+oggID).stop( true, true ).attr('src', skogg);
    $('#'+videoID).stop( true, true ).get(0).load();
    $('#'+videoID).stop( true, true ).get(0).play();

    $('.top-clock').stop( true, true ).removeClass('top-clock--visible');
    $('.top-clock-sk').stop( true, true ).addClass('top-clock--visible');

    $('#'+videoID).stop( true, true ).delay('500').fadeIn();
    $('.top-clock-sk').stop( true, true ).delay('500').fadeIn();
});

$('#videolink-rb').mouseenter(function(event) {
    //$(this).toggleClass('home-pager-hover');

    $('.top-clock').stop( true, true ).fadeOut();
    $('#'+videoID).stop( true, true ).hide();

    $('#'+videoID).stop( true, true ).get(0).pause();
    $('#'+mp4ID).stop( true, true ).attr('src', rbmp4);
    $('#'+oggID).stop( true, true ).attr('src', rbogg);
    $('#'+videoID).stop( true, true ).get(0).load();
    $('#'+videoID).stop( true, true ).get(0).play();

    $('.top-clock').stop( true, true ).removeClass('top-clock--visible');
    $('.top-clock-rb').stop( true, true ).addClass('top-clock--visible');

    $('#'+videoID).stop( true, true ).delay('500').fadeIn();
    $('.top-clock-rb').stop( true, true ).delay('500').fadeIn();
});

$('.home-pager li').mouseenter(function(event){
    $('.home-pager li').stop( true, true ).removeClass('home-pager-hover');
    $(this).stop( true, true ).addClass('home-pager-hover');
});


texts: Assembling a user agent descriptor, implemented using StringBuilder vs String

texts:
I think performance won't be a big issue here as the concatenation only happens once (2-3 at worse because of multiple threads). Out of the two methods, which one would you prefer, in terms of readability and performance? Is there any better way to accomplish the task of calculating desired string:uaInfo?

 public static string GetUserAgentInfo()
    {
        if (_uaInfo == null)
        {
            string carrier = DeviceNetworkInformation.CellularMobileOperator ?? "(No Network)";
            var sb = new StringBuilder();
            sb.Append("device-type=mobile");
            sb.Append(";os=Windows Phone");
            sb.Append(";os-version=" + Environment.OSVersion.Version);
            sb.Append(";app-name:" + GetAppName());
            sb.Append(";app-version=" + GetVersion());
            sb.Append(";carrier=" + HttpUtility.UrlEncode(carrier));
            sb.Append(";locale=" + Locale);
            _uaInfo = sb.ToString();
        }
        return _uaInfo;
    }

    public static String GetUserAgentInfoOld()
    {
        if (_uaInfo == null)
        {
            string carrier = DeviceNetworkInformation.CellularMobileOperator ?? "(No Network)";
            string temp = "";
            temp += String.Format("{0}={1};", "device-type", "mobile");
            temp += String.Format("{0}={1};", "os", "Windows Phone");
            temp += String.Format("{0}={1};", "os-version", Environment.OSVersion.Version);
            temp += String.Format("{0}={1};", "app-name", GetAppName());
            temp += String.Format("{0}={1};", "app-version", GetVersion());
            temp += String.Format("{0}={1};", "carrier", HttpUtility.UrlEncode(carrier));
            temp += String.Format("{0}={1}", "locale", Locale);
            _uaInfo = temp;
        }
        return _uaInfo;
    }


texts:
This is what I wrote for insertion sort in python. But somehow I'm feeling that it's between bubble and insertion sort.

def insertionSort(lst):
    for i in range(1, len(lst)):
        if lst[i] < lst[i-1]:
            for j in range(i):
                if lst[i] < lst[j]:
                    lst[i], lst[j] = lst[j], lst[i]
    return lst

if __name__ == '__main__':
    lst = [64, 88, 51, 65, 90, 75, 34, 79, 46, 36]
    print insertionSort(lst)


texts:
I've got this kind of data:

[
  { userId: 1, postId: 1, ... },
  { userId: 1, postId: 2, ... },
  { userId: 2, postId: 3, ... },
  ...
]

And I need to group them by postId and userId like this:

{
  1: { 1: [{ ... }], 2: [{ ... }], ...},
  2: { 3: [{ ... }], ...},
  ...
}

Here is what I've done so far:

var posts = {};
_.forEach(response.posts, function (post) {
    if (!posts[post.userId]) {
        posts[post.userId] = {};
    }
    if (!posts[post.userId][post.postId]) {
        posts[post.userId][post.postId] = [];
    }

    posts[post.userId][post.postId].push(post);
});

Any suggestion is welcome (a functional way of doing it using lodash would be great)!


texts:
I have a code, which dynamically creates an SQL query based on the selected tables and columns. One of the sample query, which is generated is as following:
SELECT
    agr.Name,
    agr.Link,
    comp1.Name as 'Party 1',
    cnt1.Name as 'Party 1 Country',
    comp2.Name as 'Party 2',
    cnt2.Name as 'Party 2 Country'
FROM
    [dbo].[Agreements] agr
    LEFT JOIN [dbo].[Companies] comp1 on agr.Party1CompanyId = comp1.BusinessId
    AND agr.TenantId = comp1.TenantId
    LEFT JOIN [dbo].[Countries] cnt1 on comp1.CountryId = cnt1.BusinessId
    AND comp1.TenantId = cnt1.TenantId
    LEFT JOIN [dbo].[Companies] comp2 on agr.Party2CompanyId = comp2.BusinessId
    AND agr.TenantId = comp2.TenantId
    LEFT JOIN [dbo].[Countries] cnt2 on comp2.CountryId = cnt2.BusinessId
    AND comp2.TenantId = cnt2.TenantId
WHERE
    agr.ValidFrom <= DATETIMEFROMPARTS(2019, 1, 1, 00, 00, 00, 1)
    AND agr.ValidTo >= DATETIMEFROMPARTS (2019, 12, 31, 23, 59, 59, 0)
    AND agr.TenantId = 1
    AND comp1.ValidFrom <= DATETIMEFROMPARTS(2019, 1, 1, 00, 00, 00, 1)
    AND comp1.ValidTo >= DATETIMEFROMPARTS (2019, 12, 31, 23, 59, 59, 0)
    AND comp2.ValidFrom <= DATETIMEFROMPARTS(2019, 1, 1, 00, 00, 00, 1)
    AND comp2.ValidTo >= DATETIMEFROMPARTS (2019, 12, 31, 23, 59, 59, 0)
    AND cnt1.ValidFrom <= DATETIMEFROMPARTS(2019, 1, 1, 00, 00, 00, 1)
    AND cnt1.ValidTo >= DATETIMEFROMPARTS (2019, 12, 31, 23, 59, 59, 0)
    AND cnt2.ValidFrom <= DATETIMEFROMPARTS(2019, 1, 1, 00, 00, 00, 1)
    AND cnt2.ValidTo >= DATETIMEFROMPARTS (2019, 12, 31, 23, 59, 59, 0);

I wanted to ask the community, if there is a room for the optimisation of this query so that they do are not too long and still understandable and as per SQLs best practices. The concerns I have is more on the joins to the same table multiple time or same "WHERE" conditions for almost all tables.
The possible optimisation suggestions to the query above are sufficient for me to rewrite some bits, which eventually should be corrected. Thanks.


texts: Get the tail of a file (the last 10 lines)

texts:
Print the tail of a file, if the file has less than 10 lines, then everything available is printed.

Any suggestions for improvement are welcome.

package je3.io;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Created by IDEA on 29/01/15.
 */
public class Tail {
    public static String[] tailLines(String filename, int nLinesToRead) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile(filename, "r");
        long lengthOfFile = randomAccessFile.length();
        long counterFromEnd = 1L;
        long newlineCounterGoal = nLinesToRead;
        int newlineCounter = 0;
        long tailPosition = 0L; // start of the end ;-)

        // If you want to get the last 10 lines,
        // and the last line ends with a newline, then you need to count back 11 newlines
        // if there is no trailing newline, then you only need to count back 10
        randomAccessFile.seek(lengthOfFile - 1L);
        char currentChar = (char) randomAccessFile.readByte();
        if(currentChar == '\n') {
            newlineCounterGoal++;
        }

        while(counterFromEnd <= lengthOfFile) {
            randomAccessFile.seek(lengthOfFile - counterFromEnd);
            if(randomAccessFile.readByte() == '\n') {
                newlineCounter++;
            }
            if(newlineCounter == newlineCounterGoal) {
                tailPosition = randomAccessFile.getFilePointer();
                break;
            }
            counterFromEnd++;
        }
        randomAccessFile.seek(tailPosition);

        String line;
        String[] lines = new String[nLinesToRead];
        int nLine = 0;
        while((line = randomAccessFile.readLine()) != null) {
            lines[nLine++] = line;
        }
        return lines;
    }

    public static void main(String[] args) throws IOException {
        if(args.length != 1) {
            throw new IllegalArgumentException();
        }
        String[] lines = tailLines(args[0], 10);
        for(String line : lines) {
            if(line != null) {
                System.out.println(line);
            }
        }
    }
}


texts:
To learn some PowerShell I made a tool, I've made before in bash. It pings the subnet for arp values and checks if there is no weird behaviour.

function IPv4toBin ($i){
    $b = $i -split '\.' | ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,'0')}
    return $b -join ""
}

function Get-IPs($subnet)
{
    #Split IP and subnet
    $IP = ($Subnet -split "\/")[0]
    $SubnetBits = ($Subnet -split "\/")[1]
    $IPInBinary = IPv4toBin($IP)

    $HostBits = 32-$SubnetBits
    $NetworkIDInBinary = $IPInBinary.Substring(0, $SubnetBits)
    $HostIDInBinary = $IPInBinary.Substring($SubnetBits, $HostBits)
    $HostIDInBinary = $HostIDInBinary -replace "1","0"

    $imax = [convert]::ToInt32(("1" * $HostBits),2) -1

    $IPs = @()

    For ($i = 1 ; $i -le $imax ; $i++)
    {
        $NextHostIDInDecimal = ([convert]::ToInt32($HostIDInBinary,2) + $i)
        $NextHostIDInBinary = [convert]::ToString($NextHostIDInDecimal,2)
        $NoOfZerosToAdd = $HostIDInBinary.Length - $NextHostIDInBinary.Length
        $NextHostIDInBinary = ("0" * $NoOfZerosToAdd) + $NextHostIDInBinary
        $NextIPInBinary = $NetworkIDInBinary + $NextHostIDInBinary

        $IP = @()
        For ($x = 1 ; $x -le 4 ; $x++)
        {
            $StartCharNumber = ($x-1)*8
            $IPOctetInBinary = $NextIPInBinary.Substring($StartCharNumber,8)
            $IPOctetInDecimal = [convert]::ToInt32($IPOctetInBinary,2)
            $IP += $IPOctetInDecimal
        }
        $IP = $IP -join "."
        $IPs += $IP

    }
    return $IPs
}

function Check-Spoof($iplist)
{
    $gate_ip = ipconfig | Select-String "Default Gateway" | % { $_.ToString().Split(':')[1].Trim() }
    $gate_ip = $gate_ip[0]
    $gate_mac = arp -a $gate_ip | Select-String $gate_ip |  % { $_.ToString() -split "\s+" }
    $gate_mac = $gate_mac[2].ToUpper()

    echo ""
    echo "Gateway with ip: $gate_ip and mac: $gate_mac"
    echo ""

    for ($i = 0; $i -lt $iplist.Count; $i++)
    {
        if ($iplist[$i] -ne $gate_ip)
        {
            $ip = $iplist[$i]
            $arp_call = arp -a $ip | Select-String "$ip"
            if ($arp_call -ne $null)
            {
                  $call = $arp_call -split "\s+"
                  $mac = $call[2].ToUpper()
                  echo "Active IP: $ip with MAC: $mac"

                  if ($mac -eq $gate_mac)
                  {
                     echo ""
                     echo "You are being Spoofed a duplicate ARP value found"
                     return
                  }
            }
        }
    }
    echo ""
    echo "You are Safe, no duplicate ARP values found."
}

$subnet = "192.168.1.1/24"
$IPLIST = Get-IPs($subnet)
Check-Spoof($IPLIST)

I am fairly new to PowerShell, so I'm mostly concerned about the proper syntax.


texts:
The locker problem for 100 lockers is simple:

  A school has 100 lockers and 100 students. All lockers are closed on the first day of school. As the students enter, the first student, denoted S1, opens every locker. Then the second student, S2, begins with the second locker, denoted L2, and closes every other locker. Student S3 begins with the third locker and changes every third locker (closes it if it was open, and opens it if it was closed). Student S4 begins with locker L4 and changes every fourth locker. Student S5 starts with L5 and changes every fifth locker, and so on, until student S100 changes L100.

  Which lockers will remain open?

Now my program in Python uses a trick hidden in this problem which is that all  lockers whose numbers have an odd number of divisors will remain open. In other words, lockers whose numbers are perfect squares. This allowed me to expand my program to solve the problem for any \$x\$ amount of lockers, provided by the user:

# 100 Locker Problem

counter_open = 0
counter_close = 0
open_list = []

def locker(num_lockers):
    global counter_open, counter_close
    num = 1
    while num**2 < num_lockers:
        open_list.append(num**2)
        num += 1
    counter_open = len(open_list)
    counter_close = num_lockers - len(open_list)

def run():
    global open_list, counter_close, counter_open
    open_list = []
    counter_open = 0
    counter_close = 0
    endings = ["st", "nd", "rd", "th"]
    try:
        user_input = int(raw_input("How many lockers will there be: "))
    except ValueError:
        print "Please insert an integer"
    else:
        locker(user_input)
        return_str = "The "
        for index in range(0, len(open_list)):
            if index == (len(open_list) - 1):
                if str(open_list[index])[-1:] == "1":
                    return_str += ("and " + str(open_list[index]) + endings[0])
                elif str(open_list[index])[-1:] == "2":
                    return_str += ("and " + str(open_list[index]) + endings[1])
                elif str(open_list[index])[-1:] == "3":
                    return_str += ("and " + str(open_list[index]) + endings[2])
                else:
                    return_str += ("and " + str(open_list[index]) + endings[3])
            else:
                if str(open_list[index])[-1:] == "1":
                    return_str += (str(open_list[index]) + endings[0] + ", ")
                elif str(open_list[index])[-1:] == "2":
                    return_str += (str(open_list[index]) + endings[1] + ", ")
                elif str(open_list[index])[-1:] == "3":
                    return_str += (str(open_list[index]) + endings[2] + ", ")
                else:
                    return_str += (str(open_list[index]) + endings[3] + ", ")
        return_str += " locker(s) will be open."
        print return_str

while True:
    run()
    print "Open Lockers: " + str(counter_open)
    print "Closed Locker: " + str(counter_close)
    print "----------------------------"

Yes, I do realize that I am using global in my functions and I have 8 if/elif statements for grammar but accuracy in the result (and PEP 8) is key to me (keep that in mind) . How do I improve the efficiency of the code and/or shorten the code?


texts:
This code is to have a dictionary of names and birthdays.

It will ask who's birthday it is that you're looking for. Then if it is in the dictionary, it will print back what that birthday is. If not, it will ask if you want to add it then have you insert the birthday as the value and use the name that you input before as the key. Then finally print the full dictionary.

I am pretty new to coding in Python and feel like there is a better way to type this code. Was thinking I could use return but I'm still not quite sure what the difference between return and print is. Is there a way to make this shorter or more efficient?

birthdays = {'Jon': 'July 17', 'Shauna': 'Jan 27', 'Lynette': 'July 10'}

while True:
    print("Who's birthday is it that you are looking for? To cancel, press enter!")
    name = input()
    if name == '':
        break

    if name in birthdays:
        print(birthdays[name] + ' is the birthday of ' + name)
    else:
        print("I don't have that person's name in my archives. Would you like to add it? Press Y or N")
        answer = input()
        if answer == 'Y':
            new_name = name
            print("Please enter their birthday")
            new_birthday = input()
            birthdays[name] = new_birthday
            print('It has been added')
            print(new_name + "'s birthday has been added as " + new_birthday)
            print('Here is a list of birthdays you have saved...')
            print(birthdays)
        else:
            print('Alrighty Then')


texts: How to flatten the nested try-catch block in F#?

texts:
How to flatten the nested try-catch block in F# for the following code? I am using EF Core with F#. The nested is required because I need to Rollback the transaction if there are errors in saving or committing the transaction!
let createTenant (ctx: AppContext) (tenant: Db.Tenant) (firstUser: Db.User) =
    async {
        try
            let! db = ctx.Aquire()

            use! transaction = db.Database.BeginTransactionAsync(IsolationLevel.Serializable) |> Async.AwaitTask

            db.Tenant.Add tenant |> ignore
            db.User.Add firstUser |> ignore

            let! result =
                async {
                    try
                        let! _ = db.SaveChangesAsync() |> Async.AwaitTask
                        do! transaction.CommitAsync() |> Async.AwaitTask

                        return Ok tenant.Id
                    with
                    | _ ->
                        do! transaction.RollbackAsync() |> Async.AwaitTask
                        return Error "internal error"
                }

            ctx.Release()

            return result

        with
        | _ -> return Error "internal error"
    }

On a side note, is this the clean/idiomatic way to handle exceptions in F#? Is there a better way to do this?


texts: Extracting a sentence containing a specific word from a longer text

texts:
My goal is to return a specific sentence in a story that contains a given word. Returns null if the word is not in the story. I'm ok with returning the first occurrence if there are multiples. Is there a more efficient or cleaner way to do this?

public static String getSentence(String text, String word) {
    String sentence = "";
    if (text.toLowerCase().contains(word)) {
        if (text.contains(".")) {  //Are there sentences terminating in a period?
            int loc = text.toLowerCase().indexOf(word);
            int a = loc;
            while (a >= 0) {
                if (text.charAt(a) == '.' || a == 0) {
                    sentence = text.substring(a,loc);
                    a = 0;
                }
                a--;
            }
            a = loc + word.length();
            while (a <= text.length()) {
                if (text.charAt(a) == '.' || a == text.length()) {
                    sentence += text.substring(loc,a+1);
                    a = text.length()+1;
                }
                a++;
            }
            return sentence;
        } else {
            return text;      //If no period, return full text
        }
    } else {
        return null;
    }
}

FYI - I'm implementing this in Android, so I don't believe I have access to Java 8.


texts:
I recently tried to implement a simple hash table using Javascript. Could anyone help me review my implementation?

//Hash Table Implementation
var HashEntry = function(key, value) {
    this.key = key;
    this.value = value;
    this.nextEntry = undefined;
};
HashEntry.prototype = {
  getKey : function() {
    return this.key;
  },
  getValue : function() {
    return this.value;
  },
  setNext : function(entry) {
    this.nextEntry = entry;
  },
  getNext : function() {
    return this.nextEntry;
  }

};

var HashTable = function(){
  this.tableSize = 100;
  this.table = []; //this will be holding HashEntry(s)
};

HashTable.prototype = {
  hashFunction: function(input) {
    //return an hash
    return input % this.tableSize;
  },
  put : function(key, value) {
    var hash = this.hashFunction(key);
    var table = this.table;
    if(table[hash] === undefined) {
       table[hash] = new HashEntry(key, value);
    } else {
       var curr = table[hash];
       while(curr.getNext()!==undefined) {
         curr = curr.getNext();
       }
       curr.setNext(new HashEntry(key, value));
    }
  },
  get : function(key) {
     var hash = this.hashFunction(key);
     var table = this.table;
     var currEntry = table[hash];
     if(currEntry === undefined) return null;
     if(currEntry.getKey() === key) {
       return currEntry.getValue();
     } else {
       while(currEntry.getNext()!==undefined) {
         currEntry = currEntry.getNext();
         if(currEntry.getKey() === key) {
           return currEntry.getValue();
         }
       }
     }
  }
};

var hashTable = new HashTable();
hashTable.put(123, "thomas");
hashTable.put(12, "luis");
hashTable.put(112,"linda");

console.log(hashTable.get(12));
console.log(hashTable.get(123));
console.log(hashTable.get(112));//linked
console.log(hashTable.get(134));//not exist

In my implementation, my hash function is to get the remainder of the key divided by the size of hash table. Per the solution to collision, I used linked list to store entries which have the collided hashes.


texts: Creating new string with only distinct letters

texts:
Aim: To have only one of each character on the Return string:

Public Shared Function CheckForDuplicates(ByVal vCharCheck As String) As String

    Dim vDeDuplicated As String = ""
    Dim i As Integer

    For i = 1 To vCharCheck.Length ' Count length of string

        'vDeDuplicate is blank to start so will always capture first character
        'vDeDuplicate is then checked against each character in the incoming string to see if it contains this character already
        'thus deduplicting the string

        If vDeDuplicated.Contains(Mid(vCharCheck, i, 1)) Then
            'Check the new string to see if it exists, if it does it is not allowed
        Else
            'The character is not found so we add it
            vDeDuplicated += Mid(vCharCheck, i, 1)
        End If

    Next

    Return vDeDuplicated
End Function


texts:
I'm working on an integration for Magento 2 with a 3rd party. This class will fetch the articledata resource. This resource contains multiple items, with a maximum of 750 per call. The class is designed to be used like do load() while next().

If there are more items than the current 750, there will be a value next_resultset. For example /app/api/v3/articledata/750-1-36/. I only need the last part 750-1-36/ to append it to the resource.

This class works fine, but I'm not happy with how all the logic is being handled. Part of me tells that the API I'm using is not designed so well and another part of me tells that the code could be better regardless.

<?php

class ArticleData
{
    const RESULT_SET_LIMIT = 750;

    /**
     * @var RestClient
     */
    protected $client;

    /**
     * @var ConfigProviderFactory
     */
    protected $configProviderFactory;

    /**
     * @var array
     */
    protected $data = [];

    /**
     * @var \Magento\Framework\Json\Decoder
     */
    protected $jsonDecoder;

    /**
     * ArticleData constructor.
     * @param ConfigProviderFactory $configProviderFactory
     * @param RestClient $client
     * @param \Magento\Framework\Json\Decoder $jsonDecoder
     */
    public function __construct(
        ConfigProviderFactory $configProviderFactory,
        RestClient $client,
        \Magento\Framework\Json\Decoder $jsonDecoder
    ) {
        $this->configProviderFactory = $configProviderFactory;
        $this->client = $client;
        $this->jsonDecoder = $jsonDecoder;
    }

    /**
     * Load first set
     */
    public function load()
    {
        $resultSet = '';
        if ($this->next()) {
            $resultSet = $this->getResultSet();
        }

        $response = $this->client->get('articledata/' . $resultSet);

        $decoded = $this->jsonDecoder->decode($response->getBody());
        $decoded['items'] = $decoded['data'];
        unset($decoded['data']);

        $this->data = $decoded;
    }

    /**
     * @return bool
     */
    public function next(): bool
    {
        return !empty($this->data['results']) && $this->data['results'] >= self::RESULT_SET_LIMIT
            && !empty($this->data['next_resultset']);
    }

    /**
     * @return string
     */
    public function getResultSet(): string
    {
        $matches = [];
        return preg_match('/articledata\/([0-9\-]+\/)/', $this->data['next_resultset'], $matches) ? $matches[1] : '';
    }
}


texts:
Here is a simple webpage that I wrote to test HTML code in real time as typed, what are some ways that I can Improve my code? part of the code is reused from a previous project, I believe that it may now be causing problems. I am still learning about CCS and in places i used both the HTML width tag and the CCS property to set the width of the item.

When searching stackoverflow I found Quite a few questions about how HTML code can be loaded into an iframe, this seems to be a common problem, Am I properly loading a HTML string into an iframe?

<!DOCTYPE html>
<title>Live HTML tester</title>

Live HTML tester

    <input id="browseOpen" type="file" accept=".html"/>
    <textarea
        rows="20"
        id="HTMLdata"
        placeholder="Enter HTML code"
        onKeyPress="edValueKeyPress()
        "onKeyUp="edValueKeyPress()">
    </textarea>

Here is where the page is being hosted LiveHTML.html


texts:
I have two lists with ca. 4000 elements where each each element have two columns. These are being fed into a function. Besides the function they are being fed into, is it possible to speed it up somehow? At this rate, it will take ca. 6-7 days to complete.

results=rep(0, length(as.numeric(unlist(coors))))
for(i in names(coors)){
  print(i)
  for( j in names(pols)){
    results[i]=point.in.polygon(coors[[i]][,1], coors[[i]][,2], pols[[j]][,1], pols[[j]][,2])
}}

EDIT: further description, I have the polygons for each ind in year 1 and the coordinates for year 2. I want to see how many of the locations from year 2 that falls within the polygon from year 1 for each individual.

EDIT 2:   the structure of coors

 str(coors)
 List of 4052
  $ 2225 :'data.frame': 48 obs. of  2 variables:
   ..$ cor.x: num [1:48] 635184 635215 635394 635431 635430 ...
   ..$ cor.y: num [1:48] 7151002 7151201 7151175 7151110 7151118 ...
  $ 2226 :'data.frame': 56 obs. of  2 variables:
   ..$ cor.x: num [1:56] 635945 635936 635944 635969 635947 ...
   ..$ cor.y: num [1:56] 7152813 7152847 7152834 7152785 7152810 ...
  $ 2227 :'data.frame': 56 obs. of  2 variables:
   ..$ cor.x: num [1:56] 636244 636245 636317 636450 636386 ...
   ..$ cor.y: num [1:56] 7151503 7151505 7151628 7151693 7151799 ...
  $ 2228 :'data.frame': 56 obs. of  2 variables:
   ..$ cor.x: num [1:56] 636451 636418 636408 636467 636495 ...
  ..$ cor.y: num [1:56] 7152610 7152605 7152634 7152572 7152537 ...

There are always either 48 or 56 obs per element level. Pols have similar structure, but more variable lengths as the number of observations depends on the shape of the polygon.


texts: Code style: passing a reference to subroutine

texts:
Is the subroutine test1 ugly?/uglier than the others?

#!/usr/bin/env perl
use warnings;
use strict;
use 5.10.1;
use Data::Dumper;

my $ref = { one => 1, two => 2, three => 3 };

sub test1 {
    my ( $ref ) = @_;
    $ref->{three} = 4;
}
test1( $ref );

sub test2 {
    $ref->{three} = 4;
}
test2( $ref );

sub test3 {
    my ( $ref ) = @_;
    $ref->{three} = 4;
    return $ref;
}
$ref = test3( $ref );

say Dumper $ref;


texts:
Here is an update to my previous boggle solver. The new version has an almost instantaneous output, removing the need to limit the length of words being searched for.

Any comments on my general coding implementation or layout would be appreciated.

"""Boggle game solver"""

class Trie:
    """Trie class to speed up programme by stopping exploration of non-existent prefixes"""

    def __init__(self):
        """Initialise the trie"""
        self.child = {}

    def insert(self, word):
        """Insert word into trie"""
        current = self.child
        for char in word:
            if char not in current:
                current[char] = {}
            current = current[char]

    def search(self, word):
        """Search the trie"""
        current = self.child
        for char in word:
            if char not in current:
                return False
            current = current[char]
        return True

def words_from(board, row, column, running_string, list_words):
    """Calculate all possible words from a given starting position [row, column]"""
    if row in (4, -1) or column in (4, -1):
        return
    # Search the Trie
    if not trie.search(running_string):
        return
    if board[row][column] != "-":
        new_string = running_string + board[row][column]
        board[row][column] = "-"
        # Add new word
        if len(new_string) >= 3:
            list_words.append(new_string.lower())
        # Find next word
        next_move = [
            (1, 1),
            (-1, -1),
            (1, -1),
            (-1, 1),
            (1, 0),
            (0, 1),
            (-1, 0),
            (0, -1),
        ]
        for dx, dy in next_move:
            words_from(board, row + dx, column + dy, new_string, list_words)
        board[row][column] = new_string[-1]
        return list_words

def get_permutations(board):
    """Get all permutations """
    set_permutations = set()
    # Build Trie
    global trie
    trie = Trie()
    with open("en-dict.txt", "r", encoding="utf8") as file:
        for line in file:
            trie.insert(line)
    #Search for words from each starting position
    for row in range(4):
        for column in range(4):
            # Search for words
            words = words_from(board, row, column, running_string="", list_words=[])
            if words:
                for word in words:
                    set_permutations.add(word)
            words = None
    return sorted(list(set_permutations))

def dictionary_check(set_permuations):
    """Check set_permutations for valid English words"""
    dictionary = {}
    with open("en-dict.txt", "r", encoding="utf8") as file:
        for line in file:
            dictionary[line.strip()] = 0

    counter = 0
    for word in set_permuations:
        if word.lower() in dictionary:
            counter += 1
            print(word)
    print(f"======\n{counter} words")

def find_words(board):
    """Find words on the boggle board"""
    set_permutations = get_permutations(board)
    print("\nPerforming dictionary check....")
    dictionary_check(set_permutations)

def build_board(string):
    """Build board from string"""
    if len(string) != 16:
        print("Error. Must enter 4*4 grid (16 characters)")
        return
    board = [[*string[0:4]], [*string[4:8]], [*string[8:12]], [*string[12:16]]]
    find_words(board)

if __name__ == "__main__":
    string_board = "playthiswordgame"
    build_board(string_board)


texts: Creating a lightweight strongly-typed parameter infrastructure

texts:
I'm looking for some feedback on some code, designed to allow me to strongly-type parameters, which get passed to functions.

I'm only really looking for comments on making my parameters more strongly typed, as well as the existence of the factory method. The implementation of the FindUser method is not relevant.

At the minute the code base has a number of places where many pieces of data are represented as strings, however in actual fact they may be EmailAddresses, Usernames etc.

This can be awkward, so I am trying to consider a way in which this could be improved.

I have written the below code, as an attempt to address this problem, and allow for the parameters I pass around functions, to be more strongly typed.

Interface used to represent the values

Public Interface IStronglyTypedValue(Of T)
    Property Value As T
    // We could add IsValid, IsCorrectFormat, etc methods in future
End Interface

Base class to provide functionality around construction (and maybe properties in future such as IsValid, or ToString()).

Public MustInherit Class StronglyTypedValueBase(Of T, TTypeOfThing As {New, IStronglyTypedValue(Of T)})
    Implements IStronglyTypedValue(Of T)

    Public Property Value As T Implements IStronglyTypedValue(Of T).Value

    Public Shared Function Make(data As T) As TTypeOfThing
        Return New TTypeOfThing() With {.Value = data}
    End Function
End Class

This will then allow for the definition possible parameters to methods, for example:

Public Class EmailAddress
    Inherits StronglyTypedValueBase(Of String, EmailAddress)
End Class

Public Class UserName
    Inherits StronglyTypedValueBase(Of String, UserName)
End Class

Which could then be used like this

 EmailAddress.Make("my@email.com")
 UserName.Make("user123")

Some example ways BEFORE using this functionality (functions grouped into one class for brevity)

Public Class UserFinder
    Public Function FindUserByEmailAddress(email As String) As IUser
        //Lookup the user
    End Function

    Public Function FindUserByUsername(username As String) As IUser
         //Lookup the user
    End Function

    Public Sub DoWork()
        Dim paul = FindUserByEmailAddress("paul@email.com")
        Dim steve = FindUserByUsername("steve1")
    End Sub
End Class

Instead, we can now do:

Public Class UserFinder
    Public Function FindUser(email As EmailAddress) As IUser
        //Lookup the user
    End Function

    Public Function FindUser(username As UserName) As IUser
         //Lookup the user
    End Function

    Public Sub DoWork()
        Dim paul = FindUser(EmailAddress.Make("paul@email.com"))
        Dim steve = FindUser(Username.Make("steve1"))
    End Sub
End Class

This also means we can now more easily write ExtensionMethods, and refactor some of this functionality into the class.

The main area of concern/review is the Make() method on the StronglyTypeValueBase class.. Is this a dirty approach? Would it be better to have used a Public Constructor than a factory method?

Also, is there a better way of solving the problem of strongly typed parameters to methods, which may not need to have loads of function.

In short, I'm looking to add a compile-time enforcement of type. I want to  not allow using a string representing a Username in a function expecting an email address; whilst at the same time not introducing any anti-patterns.


texts: finished Josephus-Problem in C#, how to make this more efficient?

texts:
using System;
using System.Collections.Generic;

namespace Function_JosephusSurvivor
{
    class Program
    {
        static void Main(string[] args)
        {
            //Debug purposes
            Console.WriteLine(JosSurvivor(7, 3));

            Console.ReadKey();
        }

        //Actual function:
        public static int JosSurvivor(int n, int k)
        {
            // n = amount of people(array size)
            // k = every k'th index will be yeeted

            List<int> list = new List<int>();
            int iCounter = 1; //always count till the size of the list
            int iWatcher = 1; //always count till the size of k
            for (int i = 1; i <= n; i++)
            {
                list.Add(i);
            }

            do
            {

                if (iWatcher+1 == k)
                {
                    list.RemoveAt(iCounter);
                    iWatcher = 0;
                }

                iWatcher++;
                iCounter++;

                if (iCounter == list.Count) // -1 because index
                {
                    iCounter = 0;
                }
                else if (iCounter > list.Count)
                {
                    iCounter = 1; //if one is jumped due to deleteting
                }

            } while (list.Count != 1);

            return list[0]; //winner
        }
    }
}

My question is:

how could you make this more efficient? What could I do better?

I'm trying to submit this as my solution on a practicing page. Unfortunately, it always times out. Therefore I need to make this more efficient I believe.

Thanks in advance :)!

Also feel free to add fitting Tags :)!


texts: Small function for getting character value

texts:
I want to extract some values in i-commas(") from lines like this:

<P k="9,0,1" vt="191" v="100.99936" z="" />

Example:

getCharVal ( cp, char "k=\"", 9)

where cp is a pointer the line above should return "9,0,1"

The function:

#define  ENDTAG   "/>"
#define ICOMMAS   '"'
char * getCharVal ( char *cp, char *att, size_t s)
{
  char * val;
  char * endTagP;
  if (cp == NULL)return NULL;
  cp = strstr(cp, att)+strlen(att);
  if (cp == NULL) return NULL;
  char * endP = strchr(cp, ICOMMAS);
  if (endP == NULL) return NULL;
  endTagP = strstr(cp, ENDTAG);
  if (endTagP == NULL) return NULL;
  if (endP > endTagP) return NULL;
  size_t valsize    = endP - cp ;
  if (valsize > s) return NULL;
  val = malloc(valsize + 1);
  memcpy (val, cp, valsize);
  val[valsize]='\0';
  cp = endTagP;
  return val;

}

This code is ugly.  Could anyone give me hints on how to write it better?


texts: Project Euler # 74 Digit factorial chains in Python

texts:
The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:

1! + 4! + 5! = 1 + 24 + 120 = 145

  Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169;
  it turns out that there are only three such loops that exist:

169 → 363601 → 1454 → 169
871 → 45361 → 871
872 → 45362 → 872

  It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example,

69 → 363600 → 1454 → 169 → 363601 (→ 1454)
78 → 45360 → 871 → 45361 (→ 871)
540 → 145 (→ 145)

  Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms.

  How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?

Here's my implementation in Python.

from math import factorial
from time import time

def get_factorial_sequence_length(number, factorials, lengths):
    """Return length of factorial sequence of number."""
    if number in lengths:
        return lengths[number]
    chain = [number]
    while len(chain) == len(set(chain)):
        if chain[-1] in lengths:
            index = chain.index(chain[-1])
            return lengths[chain[-1]] + len(chain[:index])
        chain_next = sum(factorials[digit] for digit in str(chain[-1]))
        chain.append(chain_next)
    duplicate_index = chain.index(chain[-1])
    for num in chain:
        index = chain.index(num)
        if index <= duplicate_index:
            lengths[num] = len(chain[index:-1])
        if index > duplicate_index:
            lengths[num] = len(chain[duplicate_index:index]) + len(chain[index:-1])
    return lengths[number]

def get_sequence_counts(upper_bound, target_chain_size, lengths={}):
    """Return count of factorial sequences which have length target_chain_size within range upper_bound exclusive."""
    factorials = {str(n): factorial(n) for n in range(10)}
    for number in range(1, upper_bound):
        chain_length = get_factorial_sequence_length(number, factorials, lengths)
        lengths[number] = chain_length
        if chain_length == target_chain_size:
            yield number

if __name__ == '__main__':
    start_time = time()
    print(len(set(get_sequence_counts(1000000, 60))))
    print(f'Time: {time() - start_time} seconds.')


texts: Using Comparator with 3 conditions at the same time

texts:
I am trying to create a class which implements the Comparator class.

The thing is that I have a list with some objects. This object is composed of 3 fields (Strings). My purpose is to sort the list based first on the first field: if the first field is the same on the two objects that I am comparing at the moment, then compare the second item of the 2 objects and finally if both fields are the same, compare the third field of the objects.

This is what I have done but I do not know if this is the correct answer:

public class MyComparator implements Comparator<Object>{

    @Override
    public int compare(final Dto address1, final Dto address2) {
        int result = 0;

        if (dto instanceof Dto) {
            final Dto dto = (Dto) address;
            final Dto dto2 = (Dto) address2;
            if(dto.getName() < dto2.getName()) {
                 result = -1;
            } else if(dto.getName() > dto2.getName()) {
                result = 1;
            } else {
                result = 0;
            }
        }
//if the Names are the same then compare the Number
            if (result == 0) {
                if(dto.Number() < dto2.Number()) {
                    result = -1;
                } else if(dto.Number() > dto2.Number()) {
                    result = 1;
                } else {
                    result = 0;
                }
            }
        //if the Numbers are the same then compare the Other Field

        if (result == 0) {
            if(dto.Other() < dto2.Other()) {
                result = -1;
            } else if(dto.Other() > dto2.Other()) {
                result = 1;
            } else {
                result = 0;
            }
        }

return result

}

Then I will use the following way in my service:

Collections.sort(out,new MyComparator());


texts:
database relations can be found here  http://www.tpc.org/tpc_documents_current_versions/pdf/tpc-h_v2.18.0.pdf

SELECT l_orderkey, sum(l_extendedpriced * (1 - l_discount)) as revenue, o_orderdate, o_shippriority
FROM customer, orders, lineitem
WHERE c_mktsegment = 'BUILDING' -- '[SEGMENT]'
    and c_custkey = o_custkey
    and l_orderkey = o_orderkey
    and o_orderdate < "1995-03-15" -- '[DATE]'
    and l_shipdate > "1995-03-15" -- '[DATE]'
GROUP BY l_orderkey, o_orderdate, o_shippriority
ORDER BY revenue desc, o_orderdate;

I was planning on optimizing this query by using joins like so

SELECT l_orderkey, sum(l_extendedpriced * (1 - l_discount)) as revenue, o_orderdate, o_shippriority
FROM customer
JOIN orders ON c_custkey = o_custkey
JOIN lineitem ON o_orderkey = l_orderkey
WHERE c_mktsegment = 'BUILDING' --'[SEGMENT]'
AND o_orderdate < "1995-03-15" -- '[DATE]'
AND l_shipdate > "1995-03-15" -- '[DATE]'
GROUP BY l_orderkey, o_orderdate, o_shippriority
ORDER BY revenue desc, o_orderdate;

Now all I have to do is create indexes for the tables. For this problem, a maximum of 3 indexes per table can be created with its primary key being 1 of them.

The indexes that I came up with are (these are the columns used in the GROUP BY and ORDER BY clauses)

CREATE INDEX idx_l_orderkey ON lineitem(l_orderkey);
CREATE INDEX idx_o_orderdate_shippriority ON orders(o_orderdate, o_shippriority);

Are there any more indexes that I can put in to further optimize this query? I feel like I need to make another index for the customer table for the c_mktsegment.  Also, if there's any other strategies that I forgot, could you please enlighten me. Thank you.


texts:
I commented on a question and blindly asserted that a Stack based on a linked list was rather elegant (see here)

I haven't ever written a Stack in C# so I thought I should back up my claim:

public class Stack<T> : IEnumerable<T>
{
    protected class StorageNode
    {
        public T Value { get; set; }

        public StorageNode Next { get; set; }

        public StorageNode(T value)
        {
            Value = value;
        }
    }

    public int Count { get; private set; }

    private StorageNode head;

    public void Push(T value)
    {
        var newNode = new StorageNode(value);
        if (head != null)
        {
            newNode.Next = head;
        }
        head = newNode;
        ++Count;
    }

    public T Pop()
    {
        if (head == null)
        {
            throw new InvalidOperationException("Cannot pop an empty stack");
        }
        var result = head.Value;
        head = head.Next;
        --Count;
        return result;
    }

    public IEnumerator<T> GetEnumerator()
    {
        var current = head;
        while (current != null)
        {
            yield return current.Value;
            current = current.Next;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

I didn't use the .Net LinkedList because I thought it was a bit overkill for a singly linked list...

Is there anything I can improve in my code?


texts: Advice on approach to organizing my business logic & data access?

texts:
I've been researching various patterns for structuring my business logic & data access, particular in the context of C# and the Entity Framework. I've come up with a basic idea of how I think I'd like to do it, based on several SO answers:

https://stackoverflow.com/questions/1169188/ef-objectcontext-service-and-repositry-managing-context-lifetime
https://stackoverflow.com/questions/678922/using-transactions-with-business-processes-and-the-repository-pattern

I envision a UnitOfWork that encapsulates an IObjectContext (abstract so I can swap out contexts for testing), and exposes a repository of IQueryable<TEntity>.

interface IUnitOfWork
{
    private IObjectContext _context;

    public void SetupContext(); // Create object context here

    IQueryable<TEntity> Repository<TEntity>()
            where TEntity : class, IEntityWithKey;
}

I intend to write service classes that contain my business logic, and follow this structure:

class MyService : IService
{
    public DoWork()
    {
        // Same as nesting one using within the other
        using( IUnitOfWork unitOfWork = unitOfWorkFactory.Create() )
        using( TransactionScope tScope = new TransactionScope() )
        {
            var repository = unitOfWork.Repository<TEntity>();

            /* Do some work with repository */

            unitOfWork.Commit(); // Save changes
            tScope.Complete(); // End transaction
        }
    }
}

Am I going crazy with design patterns? Is there a better way to do this?


texts: A function to find temperatures closest to zero

texts:
I wrote this function that, given an array, calculates the closest number to zero. The conditions are the following:

if the array is empty, return 0
if the array has two values share the "closeness" to zero, return the positive (for example if -1 and 1)

Here is my code and link to it.

// Write a function that takes an array an finds the closes number to 0.
// Disregard all 0s
// If the array is empty return 0

const tempArray = [-1, 0, 0, 5, -5, 6, -3, 2, 10, 13, 8, 70, -36, 36];

function calculateClosestTo0 (tempArray) {
  let minusTemps = [];
  let plusTemps = [];

  if (!tempArray.length) {
    return 0;
  }

  for (let i = 0; i < tempArray.length - 1; i++) {
    if (tempArray[i] < 0) {
      minusTemps.push(tempArray[i]);
    } else if (tempArray[i] > 0) {
      plusTemps.push(tempArray[i]);
    }
  }

  minusTemps.sort((a, b) => b - a)
  plusTemps.sort((a, b) => a - b)

  if (plusTemps[0] === Math.abs(minusTemps[0])) {
    return(plusTemps[0])
  }

  if (plusTemps[0] < Math.abs(minusTemps[0])) {
    return(plusTemps[0])
  }

  if (plusTemps[0] > Math.abs(minusTemps[0])) {
    return(minusTemps[0])
  }
}

calculateClosestTo0(tempArray)

What I intended to do is separate the array into minus values and positive values. The minus values I ordered by descending (cause I want the first item to be the "biggest" in minus numbers perspective) and the positive in ascending. After that, I compare the first number.

What worries me most is the I try to remove the "0" like that:

for (let i = 0; i < tempArray.length - 1; i++) {
  if (tempArray[i] < 0) {
    minusTemps.push(tempArray[i]);
  } else if (tempArray[i] > 0) {
    plusTemps.push(tempArray[i]);
  }
}

My colleagues usually frowned upon having a condition that has "else if" and nothing else. Why, I don't know.

Another thing that worries me is that ending part, where I have 3 conditions to return the correct value. Is there a smarter way to do that?

And generally: do you think that there is a better approach to such a problem?


texts:
Ok, so I started to build my own CMS. You can see Aleksandar Golubovic's Blog,and I need your help. Please, look at my code, and tell me is that safe? You can download current version from Twitter Bootstrap CMS. If you want to install it, just read instructions.

So, please, tell me if I get some errors, or some of your opinions, instructions... I really need help.

EDIT:

I have many functions like:

function DeletePost()
{
if (isset($_GET['action']))
{
    if ($_GET['action']==='delete-post' && !isset($_GET['id']))
    {
        $qry=mysql_query("SELECT * FROM posts ORDER BY id DESC");
        while ($arr=mysql_fetch_array($qry))
        {
        echo '

'.$arr['post_title'].'
 Delete this post

'.$arr['post_content'].'

';
        }
    }
    if ($_GET['action']==='delete-post' && isset($_GET['id']))
    {

            $del=$_GET['id'];
            $qry=mysql_query("DELETE FROM posts WHERE id='$del'") or die ("ERROR!!!");
            echo "This post has been successfull deleted.";

    }
}
}

And this function is included in some page. So my question is: Is this method safe?
Note: All functions is separeted pages using .htaccess