texts:
For Khronos, I've had to develop these utility functions to help me deal with storing the .wav files.  However, they could also be used in a variety of applications.

A description of what the three functions do are given in the header documentation comments.

util.h:

#ifndef UTIL_H
#define UTIL_H

/**
 * @return the temporary file directory for your system
 */
const char* getTmpDir(void);

/**
 * Generates a unique temporary filename given the fileroot, creates and opens the file
 * @return file descriptor to the open file
 */
int createSafeFileDescriptor(const char* fileRoot);

/**
 * Fetches the file path given the file descriptor
 * @return file path
 */
const char* getPathFromDescriptor(int fd);

#endif // UTIL_H

util.c:

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

#ifndef _WIN32
#include <fcntl.h>
#include <unistd.h>
#endif

#include "util.h"

const char* getTmpDir(void)
{
    char *tmpdir = NULL;
    if ((tmpdir = getenv("TEMP"))) return tmpdir;
    else if ((tmpdir = getenv("TMP"))) return tmpdir;
    else if ((tmpdir = getenv("TMPDIR"))) return tmpdir;
    else return "/tmp/";
}

int createSafeFileDescriptor(const char* fileRoot)
{
    // Creates temporary file safely
    char flacFile[FILENAME_MAX] = "";
    snprintf(flacFile, FILENAME_MAX, "%sXXXXXX.wav", fileRoot);

    // the 5 is for the length of the suffix ".wav"
    return mkstemps(flacFile, 4);
}

const char* getPathFromDescriptor(int fd)
{
    char *filename = malloc(FILENAME_MAX);
#ifdef _WIN32
    intptr_t file = _get_osfhandle(fd);
    intptr_t fileMap = CreateFileMapping(file, NULL, PAGE_READONLY, 0, 1, NULL);

    if (hFileMap)
    {
        void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
        if (pMem)
        {
            if (GetMappedFileName(GetCurrentProcess(), pMem, filename, FILENAME_MAX)) return filename;
        }
    }
    return NULL;
#endif

#ifdef __APPLE__
    if (fcntl(fd, F_GETPATH, filename) != -1) return filename;
    return NULL;
#endif

#ifdef __unix__
    char proclnk[PATH_MAX] = {0};
    ssize_t r = -1;
    snprintf(proclnk, sizeof(proclnk), "/proc/self/fd/%d", fd);
    if ((r = readlink(proclnk, filename, FILENAME_MAX)) < 0) return NULL;
    filename[r] = '\0';
    return filename;
#endif
}


texts: String helper functions in NASM Win16 Assembly

texts:
Environment

NASM is required to build this program, and DosBox is required to run it. I'd recommend installing these using the Scoop Package Manager. Feel free to ignore install statements for any programs you have installed already.

iwr -useb get.scoop.sh | iex
scoop install git
scoop install dosbox
scoop install nasm

Building

nasm -f bin -o helper.com helper.asm

Running

Load DosBox, then mount the path where helper.com resides to any available drive. For those unfamiliar, it can be any drive in the A-Z range.

mount H: C:\Users\T145\Desktop\
H:
dir
helper.com

helper.asm

bits 16
org 0x100

section .text

_main:
    lea     di, [prompt]
    call    putstring

    lea     di, [string]
    call    getstring

    lea     di, [hello]
    call    putstring

    lea     di, [string]
    call    putstring

    mov     ah, 0x4c     ; standard exit code
    mov     al, 0
    int     0x21

; no parameters
; returns a char in ax
getchar:
    mov     ah, 0        ; call interrupt x16 sub interrupt 0
    int     0x16
    mov     ah, 0
    ret

; takes a char to print in dx
; no return value
putchar:
    mov     ax, dx       ; call interrupt x10 sub interrupt xE
    mov     ah, 0x0E
    mov     cx, 1
    int     0x10
    ret

; takes an address to write to in di
; writes to address until a newline is encountered
; returns nothing
getstring:
    call    getchar      ; read a character
    cmp     ax, 13       ; dos has two ascii characters for new lines 13 then 10
    je      .done        ; its not a 13, whew...
    cmp     ax, 10       ; check for 10 now
    je      .done        ; its not a 10, whew...
    mov     [di], al     ; write the character to the current byte
    inc     di           ; move to the next address
    mov     dx, ax       ; dos doesn't print as it reads like windows, let's fix that
    call    putchar
    jmp     getstring
.done:
    mov     dx, 13       ; write a newline for sanity
    call    putchar
    mov     dx, 10
    call    putchar
    ret

; takes an address to write to in di
; writes to address until a newline is encountered
; returns nothing
putstring:
    cmp     byte [di], 0 ; see if the current byte is a null terminator
    je      .done        ; nope keep printing
.continue:
    mov     dl, [di]     ; grab the next character of the string
    mov     dh, 0        ; print it
    call    putchar
    inc     di           ; move to the next character
    jmp     putstring
.done:
    ret

section .data

    prompt: db "Please enter your first name: ", 0
    string: times 20 db 0
    hello: db "Hello, ", 0

Output


texts:
Anyone have ideas on how to improve this code at all?

string user = User.Identity.GetUserId();

        IQueryable<Article> t =
            db.Articles.Include(a => a.Categories)
                .Include(b => b.Shared)
                .Where(s => s.Private & s.createdby == User.Identity.Name);
        IQueryable<Article> q = db.Articles.Include(a => a.Shared).Where(s => s.Shared.Any(x => x.User == user));
        IQueryable<Article> art = t.Concat(q);
        IQueryable<Category> cat = db.Categories.Where(x => art.Any(c => c.categoryID == x.Id));

Especially looking to see if anyone has a fun way of putting all this into 1 query.


texts: Find the dominator in an array of integers

texts:
A zero-indexed array A consisting of N integers is given. The
  dominator of array A is the value that occurs in more than half of the
  elements of A.

  For example, consider array A such that

  A[0] = 3    A[1] = 4    A[2] =  3    A[3] = 2    A[4] = 3    A[5] =
  -1    A[6] = 3    A[7] = 3

  The dominator of A is 3 because it occurs in 5 out of 8 elements of A
  (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a
  half of 8.

  Write a function

  int solution(int A[], int N);

  that, given a zero-indexed array A consisting of N integers, returns
  index of any element of array A in which the dominator of A occurs.
  The function should return −1 if array A does not have a dominator.

  Assume that:

  N is an integer within the range [0..100,000]; each element of array A
  is an integer within the range [−2,147,483,648..2,147,483,647].

 int solution(int A[], int N)  {
        int size = 0;
        int value = 0;
        for(int i = 0 ; i < N ; i++)  {
                if(size == 0)  {
                   size++; value = A[i];
                }
                else  {
                   if(value != A[i])
                       size--;
                }
         }
         int candidate = -1;
         if(size > 0) {
            candidate = value;
         }
         int leader = -1;
         int count = 0;
         for(int j = 0 ; j < N ; j++)  {
            if(A[j] == candidate) {
                count++;
            }
         }
         if(count > (N/2)) {
            leader = candidate;
         }
         else {
            return -1;
         }
         int index[count];
         int cnt=0;
         for(int k = 0 ; k < N ; k++) {
            if(A[k] == leader) {
               index[cnt] = k;
               cnt++;
            }
         }
         return index[0];
    }


texts:
I want to iterate a map of map in a java 8 way and get the entry which contains 40 in the value in the inner map.

I have tried the following code in order to do that. But I still don't understand whether there is a better way to do this.

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MapToMapOperation {

    private Map<String, Map<String, Integer>> mapToMap = new HashMap<>();

    MapToMapOperation() {
        Map<String, Integer> dogMap = new HashMap<>();
        dogMap.put("A", 50);
        dogMap.put("B", 35);
        dogMap.put("D", 40);
        dogMap.put("C", 35);
        mapToMap.put("dog", dogMap);

        Map<String, Integer> catMap = new HashMap<>();
        catMap.put("C", 35);
        catMap.put("D", 40);
        catMap.put("M", 40);
        catMap.put("E", 70);
        catMap.put("H", 35);
        mapToMap.put("cat", catMap);

        Map<String, Integer> donkeyMap = new HashMap<>();
        donkeyMap.put("A", 52);
        donkeyMap.put("E", 70);
        donkeyMap.put("F", 80);
        donkeyMap.put("S", 40);
        donkeyMap.put("G", 90);
        mapToMap.put("donkey", donkeyMap);
    }

    public Map<String, Integer> get(String type) {
        return mapToMap.get(type);
    }

    public List<String> get(Map<String, Integer> map, Integer value) {
        if (!map.containsValue(value)) {
            return Collections.emptyList();
        }
        return keys(map, value).collect(Collectors.toList());
    }

    public Map<String, List<String>> getFullMapBasedOnValue(Integer value) {
        Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
        java.util.Iterator<Entry<String, Map<String, Integer>>> iterator =
                mapToMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Map<String, Integer>> entry = iterator.next();
            Map<String, Integer> subMap = entry.getValue();
            if (subMap.containsValue(value)) {
                List<String> list = keys(subMap, value).collect(Collectors.toList());
                resultMap.put(entry.getKey(), list);
            }
        }
        return resultMap;
    }

    public <K, V> Stream<K> keys(Map<K, V> map, V value) {
        return map.entrySet().stream().filter(entry -> value.equals(entry.getValue())).map(Map.Entry::getKey);
    }

    public static void main(String[] args) {
        MapToMapOperation mapOp = new MapToMapOperation();
        mapOp.get("dog").forEach((s, k) -> System.out.println(s + " " + k));

        System.out.println(mapOp.get(mapOp.get("cat"), 35));

        System.out.println(mapOp.getFullMapBasedOnValue(40));
    }

}


texts:
I have a class with a property of grid[][] and each value is either true or false. I need to convert this to a string with letters o and b in place of the boolean.

First way, simple for loops over the array and return the string:

 get rle() {
     let result = "";
     for(let y = 0; y < this.grid.length; y++) {
         for(let x =0; x < this.grid[y].length; x++) {
             result += ( (this.grid[y][x]) ?  "o" : "b" );
         }
     }
     return result;
}

Or a more JS style solution?

get rle() {
    return this.grid.reduce( (total, currentValue, currentIndex, arr) => {
        return total + arr[currentIndex].reduce( (total, currentValue, currentIndex, arr) => {
            return total + ( (arr[currentIndex]) ?  "o" : "b" );
        }, "");
    }, "");
 }

Is this a good JS style solution, and what in your opinion is better? I prefer the first because anyone can instantly understand it. The JS solution makes me frown with 3 nested returns, looks odd.


texts:
Hello I am a beginner in PHP and I need some opinions. How secure is my registration code ? If I launched this on the web would you feel safe signing up with personal info ?

  <?php

    // shows all errors
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    //check if form is submitted
    if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register']))
    {
        // looks like a hack, send to index.php
        header('Location: index.php');
        die();
    }

    include("connect.php");

        $errors = [];
    if (empty($_POST["username"])) {
        $errors[] = "Fill in username to sign up";
    }

    if (empty($_POST["pw"])) {
        $errors[] = "Fill in password to sign up";
    }

    if (empty($_POST["pw2"])) {
        $errors[] = "Confirm password to sign up";
    }
    // and so on...
    if ($_POST['pw'] !== $_POST['pw2']) {
        $errors[] = "The passwords do not match.";
    }

    if (!$errors) {
        $stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
        $stmt->bind_param("s", $_POST['username']);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();

        if ($row && $row['username'] == $_POST['username']) {
            $errors[] = "Username exists";
        }
    }
    if (!$errors) {
        $pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, array('cost' => 14));

        $stmt = $conn->prepare("INSERT INTO users (username, pw) VALUES(?, ?)");
        $stmt->bind_param("ss", $_POST['username'], $pw );
        $stmt->execute();

        echo "Registration successful Login here
";
    } else {
        foreach ($errors as $error) {
            echo "$error
 \n";
        }
        echo 'Try again
';
    }
    ?>


texts:
In my application there is a "config" object that is accessbile by multiple threads concurrently.
It is a single object (singleton) injected by the DI in the "dependents".
Until now, this (the "config") object was immutable which makes it inherently thread-safe.
However, there is a new requirement that the "config" should be periodically "refreshed/updated".
I wrote a wrapper (decorator) that refreshes itself (from a configProvider), and the refresh happens on the fly, when a method gets called (if the certian amount of time has passed)
The wrapper should be thread safe and non-blocking.

Any (concurrency) issues with the following code?

package xyz;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Implementation of {@link IMyModuleConfig} that periodically refreshes itself from the provided
 * {@link IConfiguration}.
 * The refresh is done on-the-fly when some method is called, it is thread safe.
 *
 * @Threadsafe
 */
public class MyModuleRefreshableConfig implements IMyModuleConfig {

    private IMyModuleConfig configBean; // Decorated object, Immutable, non-final should be properly fenced
    private long lastRefreshTime;  // time when we refreshed the configuration last, non-final should be properly fenced

    private final IConfiguration configProvider; // refresh source
    private final long refreshInterval; // how often we refresh

    private final AtomicBoolean refreshConfigMutex; // if true, a thread is refreshing configuration right now

    public MyModuleRefreshableConfig(IConfiguration configProvider, long refreshInterval) {
        refreshConfigMutex = new AtomicBoolean(false);

        this.configBean = refreshConfig();
        this.lastRefreshTime = System.currentTimeMillis();

        // Do not re-arrange, the assignment to final field latter in the constructor serves as a "store fence"

        this.configProvider = configProvider;
        this.refreshInterval = refreshInterval;
    }

    @Override
    public boolean getMyBoolean() {
        refreshConfigIfNeeded(); // full fence
        return this.configBean.getMyBoolean();
    }

    @Override
    public int getTimeout() {
        refreshConfigIfNeeded(); // full fence
        return this.configBean.getTimeout();
    }

    private void refreshConfigIfNeeded() {
        boolean aquired = refreshConfigMutex.compareAndSet(false, true); // full fence
        if (aquired) { // critical section starts, if some thread is in just continue, no need to wait
            long cTime = System.currentTimeMillis();
            boolean shouldRefresh = (cTime - lastRefreshTime) > refreshInterval;
            if (shouldRefresh) {
                lastRefreshTime = cTime;
                configBean = refreshConfig();
            }
            refreshConfigMutex.set(false); // critical section ends, write fence
        }
    }

    private IMyModuleConfig refreshConfig() {
        // creates new immutable IMyModuleConfig with values provided by configProvider
    }
}


texts: How to use pattern matching within curried function

texts:
I'm learning F# and I'm trying the following exercise (exercise 4.10 of Functional Programming Using F#).

  Declare an F# function prefix: 'a list -> 'a list -> bool when a:equality. The value of the expression prefix[x_0;x_1;...;x_m] [y_0;y_1;...;y_n] is true if m<=n and x_i=y_i for 0<=i<=m, and false otherwise.

I wanted to use pattern matching on the two inputs, but wasn't sure how to do this with a curried function (as opposed to a function taking a 2-tuple). So I wrote:

let rec prefix a b = (function
    | ([], _) -> true
    | (_, []) -> false
    | (x0::xst,y0::yst) -> x0 = y0 && prefix xst yst) (a,b);;

I wasn't very happy with this, because I thought it would be better (clearer and more efficient) if the inner function called itself, so I tried declaring the inner function locally.

let prefix a b =
    let rec prefixt = function
        | ([], _) -> true
        | (_, []) -> false
        | (x0::xst,y0::yst) -> x0 = y0 && prefixt (xst,yst)
    prefixt (a,b);;

Is this the right way to approach such a problem in F#?


texts: Printing Pascal’s triangle for n number of rows in Python

texts:
I have written a program that takes a number n and prints Pascal's triangle having n number of rows.

Here is my code -

n = int(input("Enter number of rows: "))
a = []

for i in range(n):
    a.append([])
    a[i].append(1)

    for j in range(1, i):
        a[i].append(a[i - 1][j - 1] + a[i - 1][j])
    if (n != 0):
        a[i].append(1)

for i in range(n):
    print("   " * (n - i), end = " ", sep = " ")

    for j in range(0, i + 1):
        print('{0:5}'.format(a[i][j]), end = " ", sep = " ")
    print()

Here are some example outputs -

Enter number of rows: 3
              1
           1     1
        1     2     1

Enter number of rows: 6
                       1
                    1     1
                 1     2     1
              1     3     3     1
           1     4     6     4     1
        1     5    10    10     5     1

Enter number of rows: 10
                                   1
                                1     1
                             1     2     1
                          1     3     3     1
                       1     4     6     4     1
                    1     5    10    10     5     1
                 1     6    15    20    15     6     1
              1     7    21    35    35    21     7     1
           1     8    28    56    70    56    28     8     1
        1     9    36    84   126   126    84    36     9     1

Therefore, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts: PHP Validate JSON objects with a JSON schema

texts:
I have a basic JSON API written in PHP. I want to validate incoming JSON data.

I know there are PHP JSON validators out there, here is a quick one I just rolled up.

<?php

$json_payload = json_decode('{
  "data": {
    "a_string": "short",
    "a_number": 7
  }
}');

validateJSONPayload(
  '{
    "data": {
      "a_string": "type=string,min_length=7,max_length=10",
      "a_number": "type=integer,min=8,max=50"
    }
  }',
  $json_payload
);

function validateJSONPayload($json_schema, $json_payload){

  $json_schema = json_decode($json_schema);

  function reCursiveCheck($schema_value, $schema_type, $payload_value, $payload_type){
    if($schema_type === "object" || $schema_type === "array"){
      # KEEP LOOPING
      foreach ($schema_value as $key => $key_val) {
        if(!property_exists($payload_value, $key)) echo "validation failed because the data does not match the schema
";
        reCursiveCheck($key_val, gettype($key_val), $payload_value->{$key}, gettype($payload_value->{$key}));
      }
    } else {
      # VALUE IS A STRING, NUMBER, BOOL, NULL
      $validation_param_strings = explode(",", $schema_value);

      # STORE THE PARAMS TO CALL THE VALIDATION FUNCTION
      $validation_params = array();

      foreach($validation_param_strings as $validation_param) {
        $params = explode("=", $validation_param);
        $validation_params[$params[0]] = $params[1];
      }
      // print_r($validation_params);
      validateProperty($payload_value, $payload_type, $validation_params);
    }
  }

  function validateProperty($payload_value, $payload_type, $validation_rule){
    if($payload_type !== $validation_rule["type"]) {
      echo "types do not match
";
    }
    # STRING VALIDATION
    if($validation_rule["type"] === "string"){
      if(strlen($payload_value) > $validation_rule["max_length"]) echo "string too long
";
      if(strlen($payload_value) < $validation_rule["min_length"]) echo "string too short
";
    }
    # NUMBER VALIDATION
    if($validation_rule["type"] === "integer"){
      if($payload_value > (int)$validation_rule["max"]) echo "number too large
";
      if($payload_value < (int)$validation_rule["min"]) echo "number too small
";
    }
    # NULL VALIDATION
    if($validation_rule["type"] === "null"){
      echo "found a null
";
    }
  }

  foreach($json_schema as $key => $value) {
    if(!property_exists($json_payload, $key)) echo "validation failed because the data does not match the schema
";
    reCursiveCheck($value, gettype($value), $json_payload->{$key}, gettype($json_payload->{$key}));
  }
}

?>


texts:
Please let me know if there is any other optimal way of doing this.

public class StringDistance {

public static void main(String[] args) {
    int i, j, m, n, temp, tracker;

    int[][] d = new int[100][100];

    String s = "kittenede";
    String t = "sitting";

    char u[] = s.toCharArray();
    char v[] = t.toCharArray();

    m = u.length;
    n = v.length;

    for (i = 0; i <= m; i++) {
        d[i][0] = i;
    }
    for (j = 0; j <= n; j++) {
        d[0][j] = j;
    }

    for (j = 1; j <= m; j++) {
        for (i = 1; i <= n; i++) {
            if (u[j - 1] == v[i - 1]) {
                tracker = 0;
            } else {
                tracker = 1;
            }
            temp = Math.min((d[i - 1][j] + 1), (d[i][j - 1] + 1));
            d[i][j] = Math.min(temp, (d[i - 1][j - 1] + tracker));

        }
    }

    System.out.println("The levenstien distance" + " " + d[n][m]);
}
}


texts: Function to find sum of digits in the number a^b where a, b are positive integers

texts:
I was solving Project Euler problem 16, which asks to find the sum of digits of the number 2 raised to the power 1000. Using Python, it can be solved in one line of code:

sum(map(int, list(str(2**1000))))

It felt too easy so I decided to write a function in C to do the same job. Here's my program. In what ways can I improve it?  Please suggest good practices also.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>

int sumdigit(int a, int b);

int main(void) {
    int a = 2;
    int b = 10000;
    printf("%d\n", sumdigit(a, b));
    return 0;
}

int sumdigit(int a, int b) {
    // numlen = number of digit in a^b
    // pcount = power of 'a' after ith iteration
    // dcount = number of digit in a^(pcount)

    int numlen = (int) (b * log10(a)) + 1;
    char *arr = calloc(numlen, sizeof *arr);
    int pcount = 0;
    int dcount = 1;
    arr[numlen - 1] = 1;
    int i, sum, carry;

    while(pcount < b) {
        pcount += 1;

        sum = 0;
        carry = 0;

        for(i = numlen - 1; i >= numlen - dcount; --i) {
            sum = arr[i] * a + carry;
            carry = sum / 10;
            arr[i] = sum % 10;
        }

        while(carry > 0) {
            dcount += 1;
            sum = arr[numlen - dcount] + carry;
            carry = sum / 10;
            arr[numlen - dcount] = sum % 10;
        }
    }

    int result = 0;
    for(i = numlen - dcount; i < numlen; ++i)
        result += arr[i];

    free(arr);
    return result;
}


texts:
I have below route. I am using Laravel 8.
Route::post('/update-crew',
    array(
        'uses' =>  'App\Http\Controllers\Directory\Crew\API\CrewAPIController@Update',
        'as'   =>  'apiUpdateCrew',
    )
);

Is there any way to use namespace instead of writing the path in string. My route contains both uses and as.
can I improve the code by keeping the uses and as and instead of string path, can I use namespace something like below?
use App\Http\Controllers\Directory\Crew\API\CrewAPIController;

Route::post('/update-crew',
    array(
        'uses' =>  ['CrewAPIController', 'Update'],
        'as'   =>  'apiUpdateCrew',
    )
);

Is this possible?


texts: Regex to clean text in preparation for word count in PHP

texts:
EDIT: Here's my totally-revised PHP...

$text = preg_replace("~[^ a-z0-9'-]~"," ",strtolower($INPUT));
for($i=1;$i<strlen($text)-1;$i++) {
    if(preg_match("~['-]~",$text[$i]) && ( !preg_match("~[a-z0-9]~",$text[$i-1]) || !preg_match("~[a-z0-9]~",$text[$i+1])) ){
        $text[$i] = " ";
    }
}
while( preg_match ("~  ~",$text) ) $text = preg_replace( "~  ~", " ", $text);
if(preg_match("~[' -]~",$text[0])) $text = substr($text,1,strlen($text)-1);
if(preg_match("~[' -]~",$text[strlen($text)-1])) $text = substr($text,0,strlen($text)-2);

Now, what I'd said still applies..

This regex seems to work for me, but I'm curious if anyone can think of a breaking case, or tell me anything I did wrong.

(If it seems the code does what I say I want it do to, say so, then for fun you can help me become more neurotic about what I actually want it to do, which hinges on the question of defining an English "word".)

Desired final form of $text: replace, with spaces, all characters in $INPUT except for letters, digits, and any hyphens or apostrophes that are directly between two letters/digits (and hence "part of a word"). Then collapse all whitespace into single spaces, and if necessary, drop the leading and closing space.

End result should be a lowercase series of words separated by spaces, of which some words may contain (entirely "inside" the word) one or more non-consecutive apostraphes, and/or one or more non-consecutive hyphens.

Does this do that, with no exceptions?

After this step, the next part will be to split (or explode, whichever is better) the string by spaces, then generate a list of words and frequencies. I'm pretty sure how to do that on my own (especially because my teacher actually told us two algorithms). In fact I'll probably hand the assignment in before choosing an answer to this; I'm mostly asking out of curiosity.

My thinking is...

English "words" tend to be case insensitive for distinction (though there is the proper noun issue, which I'll just ignore).
Some "words" are digits (The word 88), or include digits, like 2Pac or se7en.
An apostrophe can also be a single quote, so it shouldn't be considered part of the word in case that's the intention, even though it sometimes might be, as with What is goin' on? (Fortunately, "proper" contractions don't begin or end with an apostrophe.)
Hyphens can occur at the beginning or end of a word, but that doesn't make for a distinct word (An eater asked if I was a fire-juggler or -eater has two *eater*s, not one with the hyphen and one without).
Two or more consecutive hyphens are meant as a dash of some kind, separating words
Two consecutive apostrophes are likewise assumed to separate words, despite typos like don''t
In general, digits, hyphens, and apostrophes are the only relevant "non-letter letters" for word-frequency counting.
Despite all my overthinking here, I don't actually want to be maximally thorough, just "good enough" (and "good enough" is the question I'm ovethinking!).

Old code:

$text = preg_replace( "~((?<![a-z0-9])[-'](?![a-z0-9]))|([^ a-z0-9'-])~", " ", strtolower($INPUT));
while(preg_match("~  ~",$text)) $text = str_replace("  ", " ", $text);
if($text[0] == " ") $text = substr($text,1,strlen($text)-2);
if($text[strlen($text)-1] == " ") $text = substr($text,0,strlen($text)-2);


texts: Packing algorithm of 1-Bit monochrome image data to BYTE buffer

texts:
I have 1-bit monochrome image which I have to put into a BYTE buffer. The monochrome image is kept to a dynamic memory of OLE_COLOR. I have to copy the color data to BYTE buffer. Before moving into trial and error, I would like to share if my algorithm is something that will do as I am expecting worth a review.

    const long stride = 4;
    const long height = 32;
    const gsl::span<const OLE_COLOR> textureColors = {colorParam, gsl::narrow_cast<gsl::span<OLE_COLOR>::index_type>(width * height)};
    std::vector<BYTE> texture;
    texture.resize(gsl::narrow_cast<size_t>(stride * height));
    gsl::span<BYTE> colors = {texture};
    for (long y = 0; y < height; ++y)
    {
        const auto bitmapRow = textureColors.subspan(y, gsl::narrow_cast<gsl::span<OLE_COLOR>::index_type>(width));
        const auto textureRow = colors.subspan(y * stride, stride);
        for (long s = 0; s < stride; ++s)
        {
            auto& destColors = *textureRow.subspan(s, 1).data();
            for (int b = 0; b < 8; ++b)
            {
                const auto srcColor = *bitmapRow.subspan(s * 8 + b, 1).data();
                destColors += gsl::narrow_cast<BYTE>((destColors << b) | srcColor);
            }
        }
    }


texts: Sympy reduction of a multivariate, bounded, under-determined system

texts:
This is bad. I've been hacking away at Sympy for a few hours and the only solution I've come up with to yield the data I want is brute-force:
Code
from sympy import Interval, Naturals0, Q, Symbol, refine, solveset

N = 10
digit_interval = Interval.Ropen(0, N)
digits = digit_interval.intersect(Naturals0)  # equivalent to range(N)

# These don't seem to have any useful impact on solveset
assumptions = {
    'nonnegative': True,
    'noninteger': False,
    'real': True,
}

a = Symbol('a', **assumptions)
b = Symbol('b', **assumptions)
c = Symbol('c', **assumptions)
symbols = (a, b, c)

left = a / (b + c)
right = 3
soln = solveset(left - right, symbols[-1], digits)

# Useless - has no effect
for sym in symbols:
    soln = refine(soln, Q.positive(N - sym))

print(f'Set solution to {left}={right} for {symbols[-1]} is {soln}')

# Number of variables is so small that recursion is fine(ish)
def recurse_determine(inner_soln, vars=(), depth=0):
    if depth == len(symbols) - 1:
        yield from (vars + (v,) for v in inner_soln)
    else:
        for val in digits:
            yield from recurse_determine(
                inner_soln.subs(symbols[depth], val),
                vars + (val,),
                depth+1,
            )

for values in recurse_determine(soln):
    print(', '.join(str(v) for v in values))

The crux of the problem is that it seems difficult (impossible?) to have Sympy find a solution to such a multivariate integer problem and meaningfully constrain it to known bounds, so I'm left doing the brute-force approach: iterate through every possible value of every variable, and only when a (probably invalid) selection of variable values has been substituted can I ask Sympy to tell me that the result is an empty set. It works (for about the worst definition of "works") but there has to be a better way.
I should add that the bounds will remain the same but the equation will be subject to change in the future, so a suggested solution that replaces Sympy with (e.g.) hard-coded Numpy or bare Python will not help me.
Output
Set solution to a/(b + c)=3 for c is Intersection(FiniteSet(a/3 - b), Range(0, 10, 1))
0, 0, 0
3, 0, 1
3, 1, 0
6, 0, 2
6, 1, 1
6, 2, 0
9, 0, 3
9, 1, 2
9, 2, 1
9, 3, 0


texts: Function to return last line's length of a string

texts:
I am completely re-writing the textbox GUI widget.
In order to set the position cursor after the last character in the last line of a text, it is good if you know the exact column of it. So I created a small function that calculates this. It is meant to work sonicly.

int get_last_line_length (char *string)
{
    const int len = strlen(string) - 1;
    int i;

    for(i = len; i != -1 && string[i] != '\n'; i--);

    return (len - i);
}


texts: Dealing with messy JSON API and UTF-8 encoding problems

texts:
I am using an API that returns a JSON object that has "encoded_polyline" fields that tend to result in errors like this one:

  UnicodeEncodeError: 'utf-8' codec can't encode character '\udb6e' in position 2: surrogates not allowed

Since the offending fields don't offer useful data, I decided the best would be to get rid of the fields causing these errors. However, these fields are sometimes stored at the top level of the JSON object but also sometimes stored within an array at either:

jsonobject["points"]["points"]
jsonobject["laps"]["metric"]
jsonobject["laps"]["imperial"]

I think I've finally got something working to hunt down all these fields and delete them, but I have a feeling this could be done much more cleanly.

r = requests.get(url, headers = {'User-Agent':UA})
jsonobject = r.json()
if 'laps' in jsonobject and jsonobject['laps'] is not None:
    if 'imperial' in jsonobject['laps']:
        laps_array = jsonobject['laps']['imperial']
        type = 'imperial'
    if 'metric' in jsonobject['laps']:
        laps_array = jsonobject['laps']['metric']
        type = 'metric'
    if laps_array is not None:
        jsonobject['laps_correct'] = dict()
        jsonobject['laps_correct'][type] = list()
        for document in laps_array:
            #sometimes these document objects turn out to be dicts
            #and sometimes they turn out to be strings
            #even though JSON output is always the same
            #is there a better way to deal with this?
            if document.__class__.__name__ == "dict":
                document2 = document
            else:
                document2 = json.loads(document)
            if 'small_encoded_polyline' in document2 and document2['small_encoded_polyline'] is not None:
                del document2['small_encoded_polyline']
                document = document2
                #I thought this line above would modify the original
                #jsonobject since document is a dictionary so I should
                #be working with a pointer to the original object
                #but inspection of jsonobject reveals this not to be the case
                jsonobject['laps_correct'][type].append(document2)
        del jsonobject['laps']
        jsonobject['laps'] = jsonobject.pop('laps_correct')

# this can't be an elif because sometimes json objects
# have both "points" and "laps"
if 'points' in jsonobject and jsonobject['points'] is not None:
    if 'points' in jsonobject['points']:
        laps_array = jsonobject['points']['points']
        jsonobject['points_correct'] = dict()
        jsonobject['points_correct']['points'] = list()
        if laps_array is not None:
            for document in laps_array:
                if document.__class__.__name__ == "dict":
                    document2 = document
                else:
                    document2 = json.loads(document)
                    if 'small_encoded_polyline' in document2 and document2['small_encoded_polyline'] is not None:
                        del document2['small_encoded_polyline']
                        document = document2
                        jsonobject['points_correct']['points'].append(document2)
        del jsonobject['points']
        jsonobject['points'] = jsonobject.pop('points_correct')

if 'small_encoded_polyline' in jsonobject and jsonobject['small_encoded_polyline'] is not None:
    del jsonobject['small_encoded_polyline']

My two biggest worries/questions are:

How can I deal with variables that are sometimes typed as dicts and sometimes as strings even though the JSON format appears identical in both cases?
Is it really necessary to delete original key and replace it rather than updating dicts from the original key? This seems slow and clunky.


texts:
This is a Follow-up to Simple pay rate calculator

Here is what I came up with.  Hopefully if I have missed something that was said in answers on the previous question, we can still get those things pointed out.  I am hoping that I made the code cleaner.

Main Method

class MainClass
{
    public static void Main (string[] args)
    {
         //var payCheck = new PayRateCalculator("Hart",40,23);
        var payCheck = new PayCalculator();
        Console.Write ("Please provide the Employees Last Name >>");
        payCheck.lastName = Console.ReadLine();
        Console.Write ("How many hours has employee {0} worked? >>", payCheck.lastName);
        payCheck.hours = Convert.ToInt32 (Console.ReadLine());
        Console.Write ("What is employee {0}'s hourly wage? >>", payCheck.lastName);
        payCheck.payrate = Convert.ToInt32 (Console.ReadLine ());
        Console.WriteLine ("{0}'s Gross pay is ${1}", payCheck.lastName, payCheck.GrossTotal());
        Console.WriteLine ("{0}'s Net pay is ${1}", payCheck.lastName, payCheck.NetTotal());
    }
}

PayCalculator Class

class PayCalculator
{
    private const decimal _PayRateDefault = 8.25m;
    private decimal _payrate = _PayRateDefault;
    private decimal _withholdingRate = 0.20m;
    private decimal _hours;

    public decimal hours {
        get {
            if (hours < 1) {
                return 40;
            } else {
                return _hours;
            }
        }
        set {
            _hours = value;
        }
    }
    public decimal grossPay { get;set; }
    public decimal netPay { get; private set; }
    public decimal payrate {
        get {
            return _payrate;
        }
        set {
            if (value < 8.25){
                _payrate = 8.25m;
            } else {
                _payrate = value;
            }
        }
    }
    public decimal WithholdingRate{ get; set; }
    public string lastName { get; set; }

    public decimal GrossTotal ()
    {
        grossPay = hours * payrate;
        return grossPay;
    }

    public decimal NetTotal ()
    {
        grossPay = GrossTotal();
        netPay = grossPay - (grossPay * _withholdingRate);
        return netPay;
    }

    public PayCalculator (string lastName, decimal hours, decimal payRate)
    {
        this.hours = hours;
        this.payrate = payrate;
        this.lastName = lastName;
    }

    public PayCalculator ()
    {
    }
}

I am going to put the beginner tag on this again because I know that my coding skills are still not very good.

This will be the last review for this little bit of code.  I am going to see what else catches my eye in this book while I am working through it.


texts:
My company wants me to build a serverless component (AWS Lambda) that checks every minute for our system components health.

The data model (classes structure) I have devised so far is as pasted below.
The main problem I am trying to address is I wanted to have a collection of all our system metrics. At first I thought of having clsMetric<T> where T would determine the type of Value and Threshold properties. But I can't have a collection of a generic class (at least not a generic collection of generic classes).

So I ended up creating subclasses of clsMetric for each metric value type I have, and left in the parent class a string representation of those properties for accessing them while looping over my collection of clsMetric.

Is this the way to go ? Current C# capabilities offer something else I do not know? Any design pattern suitable to apply here I am not aware of ?

public abstract class clsMetric
{
    public string Name { get; }
    public abstract string ValueAsStr { get; }
    public abstract eLogicalOperator LogicalOperator { get; }
    public abstract string ThresholdAsStr { get; }
    public abstract bool Faulty();
    public clsMetric(string name)
    {
         Name = name ?? string.Empty;
    }

    public override string ToString()
    {
        return Name;
    }
}

public class IntegerMetric : clsMetric
{
    eLogicalOperator _logicalOperator;
    #region Properties
    public int Value { get; private set; }

    public override string ValueAsStr => Value.ToString();

    public override eLogicalOperator LogicalOperator => _logicalOperator;

    public int Threshold { get; private set; }
    public override string ThresholdAsStr => Threshold.ToString();

    #endregion

    #region Constructors
    public IntegerMetric(string name, int value, eLogicalOperator logicalOperator, int threshold) : base(name)
    {
        Value = value;
        _logicalOperator = logicalOperator;
        Threshold = threshold;
    }

    public override bool Faulty()
    {
        if (LogicalOperator == eLogicalOperator.Equal)
            return Value == Threshold;
        else if (LogicalOperator == eLogicalOperator.GreaterOrEqualThan)
            return Value >= Threshold;
        else if (LogicalOperator == eLogicalOperator.GreaterThan)
            return Value > Threshold;
        else if (LogicalOperator == eLogicalOperator.LowerOrEqualThan)
            return Value <= Threshold;
        else if (LogicalOperator == eLogicalOperator.LowerThan)
            return Value < Threshold;

        return false;
    }

    #endregion
}

public class StringMetric : clsMetric
{
    eLogicalOperator _logicalOperator;
    #region Properties
    public string Value { get; private set; }

    public override string ValueAsStr => Value.ToString();
    public override eLogicalOperator LogicalOperator => _logicalOperator;

    public string Threshold { get; private set; }

    public override string ThresholdAsStr => Threshold.ToString();
    #endregion

    #region Constructors
    public StringMetric(string name, string value, eLogicalOperator logicalOperator, string threshold) : base(name)
    {
        Value = value;
        _logicalOperator = logicalOperator;
        Threshold = threshold;
    }

    public override bool Faulty()
    {
        if (LogicalOperator == eLogicalOperator.Equal)
            return string.Equals(Value, Threshold);
        else if (LogicalOperator == eLogicalOperator.Contains)
            return ValueAsStr.Contains(ThresholdAsStr, StringComparison.InvariantCultureIgnoreCase);

        return false;
    }
    #endregion
}


texts:
I have this code that is working as intended. Since I am still learning VBA and coding, I was wondering if anyone could look at this at let me know if there is another way to write this. This is part of an Add-In I created and is used by several other people (meaning that I installed the Add-In onto their PCs).

Sub Ex()
If InStr(LCase$(ActiveWorkbook.name), "extract") > 0 Then
    Exit Sub
Else
     Dim MyDir As String, fn As String
     MyDir = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\Extract Files" ' change this to valid path
     If Len(Dir(MyDir, vbDirectory)) = 0 Then MkDir MyDir
     fn = MyDir & "\Extract - " & Format(Now, "mm-dd-yyyy hh_mm")
     ActiveWorkbook.SaveAs Filename:=fn, FileFormat:=xlOpenXMLWorkbook
End If
End Sub

I had a problem with the code creating a new file each time the custom menu button (which is the trigger for the add-in and has other tools that are used on this workbook) was activated, so I added this to prevent that from occurring:

If InStr(LCase$(ActiveWorkbook.name), "extract") > 0 Then
        Exit Sub
    Else

Please let me know if there is any room for improvement of the way this is constructed.


texts:
The following is a code written in Javascript. It let's me change the appearance of a canvas depending on user input.
The question is, how can I make this code more CPU efficient?
I ask that because this code is just barely snappy enough on the iPad 2 and any improvement in speed would be really great to have.

With speed I am mainly focusing on that loop that iterates thousands of times (right now 3.600).

function repeat(){
//pc, input_mouse_x/y becomes input x/y.
if(device_type==0){
    ix=input_mouse_x;
    iy=input_mouse_y;
    //if pc's left mouse button isn't clicked then this isn't a valid input.
    if(input_mouse_button_left==0)  {ix='-';iy='-';}
    }
//ipad, input_touch becomes x/y.
if(device_type==1){
    ix=input_touch[0][0];
    iy=input_touch[0][1];
    //iy=trigonometry.flip({'number':iy,'around':screen_center});
    iy+=(screen_center-iy)*2;
    }

var pencil_x=ix;
var pencil_y=iy; pencil_y+=(screen_center-pencil_y)*2;
var pencil_width=30;
var pencil_height=30;
var data_quantity=(pencil_width*pencil_height*4);
var pencil_width_half=(pencil_width/2);
var pencil_height_half=(pencil_height/2);
var pencil_begin_x=(pencil_x-pencil_width_half);
var pencil_begin_y=(pencil_y-pencil_height_half);
var image_data=drawing_board_canvas_twod.getImageData(pencil_begin_x,pencil_begin_y,pencil_width,pencil_height);

//everything in this loop must be as cpu efficient as possible.
for(var cdata=3;cdata<3600;cdata+=4){
    //data to pixel, and then to x/y.
    var cpixel=Math.floor(cdata/4);
    var cx=(cpixel%pencil_width);
    var cy=parseInt(cpixel/pencil_width);

    //find distance to center of pencil.
    var to_center_x=Math.abs(pencil_width_half-cx);
    var to_center_y=Math.abs(pencil_height_half-cy);
    var to_center=Math.pow((Math.pow(to_center_x,2)+Math.pow(to_center_y,2)), 0.5);

    if(to_center<17){
        image_data.data[cdata]=0;//the higher the denser.
        }
    }
drawing_board_canvas_twod.putImageData(image_data,pencil_begin_x,pencil_begin_y);
}


texts: Merge hashes that have the same description field, summing the other fields

texts:
I have an array of hashes of form:

{ description: 'string', b: float, c: float }

I need to get an array of merged hashes so that if hashes have same value at key description sum values of b and c, (of course keeping value of a unaltered), otherwise (if value of description is unique) just add hash to array.

Current solution:

array_of_hashes.inject([]) do |lines, line|
  if lines.none? { |l| l[:description] == line[:description] }
    lines << line
  else
    lines
      .find { |l| l[:description] == line[:description] }
      .merge!(line) { |key, old_v, new_v| key == :description ? old_v : old_v + new_v }
    lines
  end
end

I am 100% sure there's a nicer solution.


texts:
My code currently:
import os
import pandas as pd
from selenium import webdriver
from tabulate import tabulate
from datetime import datetime
import time
from bs4 import BeautifulSoup as bs

start = datetime.now()

browser = webdriver.Chrome()

class GameData:

    def __init__(self):
        self.date = []
        self.time = []
        self.game = []
        self.score = []
        self.home_odds = []
        self.draw_odds = []
        self.away_odds = []

def parse_data(url):
    browser.get(url)
    df = pd.read_html(browser.page_source, header=0)[0]
    time.sleep(3)
    html = browser.page_source
    soup = bs(html,"lxml")
    cont = soup.find('div', {'id':'wrap'})
    conti = cont.find('div', {'id':'col-content'})
    content = conti.find('table', {'class':'table-main'}, {'id':'tournamentTable'})
    main = content.find('th', {'class':'first2 tl'})
    count = main.findAll('a')
    country = count[1].text
    league = count[2].text
    game_data = GameData()
    game_date = None
    for row in df.itertuples():
        if not isinstance(row[1], str):
            continue
        elif ':' not in row[1]:
            game_date = row[1].split('-')[0]
            continue
        game_data.date.append(game_date)
        game_data.time.append(row[1])
        game_data.game.append(row[2])
        game_data.score.append(row[3])
        game_data.home_odds.append(row[4])
        game_data.draw_odds.append(row[5])
        game_data.away_odds.append(row[6])
    browser.quit()
    return game_data, country, league

# You can input as many URLs you want
urls = {
"https://www.oddsportal.com/soccer/europe/champions-league/results/"
}

if __name__ == '__main__':

    results = None

    for url in urls:
        game_data, country, competition = parse_data(url)
        result = pd.DataFrame(game_data.__dict__)
        result['country'] = country
        result['competition'] = competition
        if results is None:
            results = result
        else:
            results = results.append(result, ignore_index=True)

results

|    | date        | time   | game                                 | score   |   home_odds |   draw_odds |   away_odds | country   | competition      |
|----|-------------|--------|--------------------------------------|---------|-------------|-------------|-------------|-----------|------------------|
|  0 | 17 Mar 2021 | 20:00  | Bayern Munich - Lazio                | 2:1     |        1.35 |        6.02 |        7.53 | Europe    | Champions League |
|  1 | 17 Mar 2021 | 20:00  | Chelsea - Atl. Madrid                | 2:0     |        2.33 |        3.1  |        3.49 | Europe    | Champions League |
|  2 | 16 Mar 2021 | 20:00  | Manchester City - B. Monchengladbach | 2:0     |        1.28 |        6.25 |       10.17 | Europe    | Champions League |
|  3 | 16 Mar 2021 | 20:00  | Real Madrid - Atalanta               | 3:1     |        2.26 |        3.6  |        3.16 | Europe    | Champions League |
|  4 | 10 Mar 2021 | 20:00  | Liverpool - RB Leipzig               | 2:0     |        2.37 |        3.8  |        2.85 | Europe    | Champions League |

How can I make this code better for readability?
Also, since CR is asking to explain further, (mods can delete this)


texts: Cracking the Coding Interview: "Problem 1.5. One Away"

texts:
I am going one-by-one through problems in the "Cracking the Coding Interview". This question is about problem 1.5. One Away. Since I was never good in "algorithming", any suggestions are highly appreciated.

The very best thing you can do for me is suggest a better approach instead of the "straightforward" fragile code I wrote.

Oh, and since it's pretty much an interview question, performance is important too. The solution I got is O(n) -- bound by the length of the longest string so far (which can be easily fixed by early exit when mismatchCount exceeds 1).

Code

/**
 * Problem:
 *   There are three types of edits that can performed on strings:
 *   insert a character, remove a charachter, or replace a character.
 *   Given two strings, write a function to check if they are one edit (or zero edits) away.
 *
 * Example:
 *   pale, ple   -> true
 *   pales, pale -> true
 *   pale, bale  -> true
 *   pale, bake  -> false
 *
 * Solution:
 *   complexity: O(n)
 */

export function areOneAway(leftWord: string, rightWord: string): boolean {
  let leftIndex = 0;
  let rightIndex = 0;
  let mismatchCount = 0;

  while (leftIndex < leftWord.length && rightIndex < rightWord.length) {
    const leftChar = leftWord[leftIndex];
    const rightChar = rightWord[rightIndex];

    if (leftChar === rightChar) {
      leftIndex++;
      rightIndex++;
    } else {
      const nextLeftChar = leftWord[leftIndex + 1];
      const nextRightChar = rightWord[rightIndex + 1];

      const leftCharEqualsNextRight = leftChar === nextRightChar;
      const rightCharEqualsNextLeft = rightChar === nextLeftChar;
      const nextLeftEqualsNextRight = nextLeftChar === nextRightChar;

      if (nextLeftEqualsNextRight) {
        leftIndex++;
        rightIndex++;
      } else if (
        leftCharEqualsNextRight && rightCharEqualsNextLeft ||
        !leftCharEqualsNextRight && !rightCharEqualsNextLeft
      ) {
        return false;
      } else if (leftCharEqualsNextRight) {
        rightIndex++;
      } else if (rightCharEqualsNextLeft) {
        leftIndex++;
      } else {
        throw new Error('Invariant violated');
      }

      mismatchCount++;
    }
  }

  return ((leftWord.length - leftIndex) + (rightWord.length - rightIndex) + mismatchCount) <= 1;
}

Tests

import { expect } from 'chai';

import { areOneAway } from '../../src/cracking-the-coding-interview/1-5-one-away';

describe(`1-5: OneAway`, () => {
  [
    { string1: 'pale', string2: 'ple', expectedResult: true },
    { string1: 'pales', string2: 'pale', expectedResult: true },
    { string1: 'pale', string2: 'bale', expectedResult: true },
    { string1: 'pale', string2: 'bake', expectedResult: false },

    { string1: '', string2: '', expectedResult: true },
    { string1: '', string2: ' ', expectedResult: true },
    { string1: ' ', string2: '', expectedResult: true },
    { string1: '', string2: '  ', expectedResult: false },
    { string1: '  ', string2: '', expectedResult: false },
    { string1: '', string2: 'x  ', expectedResult: false },
    { string1: 'x  ', string2: '', expectedResult: false },
    { string1: 'a', string2: 'a', expectedResult: true },

    { string1: 'ab', string2: 'a', expectedResult: true },
    { string1: 'abc', string2: 'a', expectedResult: false },
    { string1: 'abc', string2: 'abc', expectedResult: true },
    { string1: 'a', string2: 'ab', expectedResult: true },
    { string1: 'a', string2: 'abc', expectedResult: false },

    { string1: 'xab', string2: 'xa', expectedResult: true },
    { string1: 'xabc', string2: 'xa', expectedResult: false },
    { string1: 'xabc', string2: 'xabc', expectedResult: true },
    { string1: 'xa', string2: 'xab', expectedResult: true },
    { string1: 'xa', string2: 'xabc', expectedResult: false },
  ].forEach(testCase => {
    const { string1, string2, expectedResult } = testCase;

    it(`Should return ${expectedResult} for '${string1}' and '${string2}'`, () => {
      expect(areOneAway(string1, string2)).to.equal(expectedResult);
    });
  });
});


texts:
I'm trying to get my head around asyncronous programming in node.js.
My example is reading all the files from a directory.

I know I can avoid asyncronous programming by using the syncronous methods:

var fs = require('fs');

names = fs.readdirSync(".");
for(i in names) {
  fileinfo = fs.statSync( names[i] );
  if( fileinfo.isFile() ) console.log( names[i] + " has size " + fileinfo.size );
};

I know how to write it in the classic node style:

fs.readdir(".", function (err, names) {
  if (err) throw err;
  names.forEach(function(n){
    fs.stat( n, function(err, fileinfo) {
      if( fileinfo.isFile() ) console.log( n + " has size " + fileinfo.size );
    });
  });
});

But now I'm trying "functional reactive programming" with bacon.js and I'm not sure if I really get it.  This is my first sketch:

var fs = require('fs')
  , Bacon = require("baconjs").Bacon;

fs.readdir(".", function (err,names) {
  if (err) throw err;
  Bacon.fromNodeCallback( fs.stat_with_filename, Bacon.fromArray(names) )
    .filter(".isFile")
    .onValue(function(stat) {
      console.log(stat.filename + " has size " + stat.size);
  });
});

But I had to monkeypatch fs to get the filename inside the stat object to achive this:

fs.stat_with_filename = function( filename, callback ) {
   fs.stat( filename, function (err,stats) {
     stats.filename = filename;
     callback( err, stats );
   });
};

Is there a better way to write this in node + bacon?


texts: Building query params which append to URL in a browser

texts:
I was looking for a similar JavaScript method for http_build_query but did not find but create my own and here I am a bit confused to decide the right approach.

Here is the problem. I have an object of params and need to create query string to append with URL with help of encodeURIComponent:

const params = {
    "name": ["alpha &", "beta"],
    "id": ["one", "&two=2"],
    "from": 1533735971000,
    "to": 1533822371147,
    "status": true
};

Now there are two approaches when there is an array of strings are there. I name them pre-encode and post-encode for now.

pre-encode

Apply encodeURIComponent to individual items and then join all items.

const params = {
  "name": ["alpha &", "beta"],
  "id": ["one", "&two=2"],
  "from": 1533735971000,
  "to": 1533822371147,
  "status": true
};

const output = Object.entries(params).map((pair) => {
  const [key, val] = pair;
  if (val instanceof Array && val.length > 0) {
    let pre_encode = val.map(encodeURIComponent).join(',');
    console.log({pre_encode});
    const pre_qs = `${encodeURIComponent(key)}=${pre_encode}`;
    console.log({pre_qs})
    return pre_qs;
  } else {
    return pair.map(encodeURIComponent).join('=');
  }

}).join('&');

console.log({output});

Output

  "name=alpha%20%26,beta&id=one,%26two%3D2&from=1533735971000&to=1533822371147&status=true"

post-encode

First, join all items then apply encodeURIComponent.

const params = {
  "name": ["alpha &", "beta"],
  "id": ["one", "&two=2"],
  "from": 1533735971000,
  "to": 1533822371147,
  "status": true
};

const output = Object.entries(params).map((pair) => {
  const [key, val] = pair;
  if (val instanceof Array && val.length > 0) {
    let post_encode = encodeURIComponent(val.join(','));
    console.log({post_encode});
    const post_qs = `${encodeURIComponent(key)}=${post_encode}`;
    console.log({post_qs})
    return post_qs;
  } else {
    return pair.map(encodeURIComponent).join('=');
  }

}).join('&');

console.log({output});

Output

  "name=alpha%20%26%2Cbeta&id=one%2C%26two%3D2&from=1533735971000&to=1533822371147&status=true"

Which approach is the more efficient and right and how to handle null and undefined values?


texts: Creating a basic calculator for integers

texts:
Create a simple function that given 3 inputs - number 1, number 2 and operator -  calculates the result. The function supports DMAS operations, and accepts only integers

Is there a better way of solving this problem?

#calculator
def calculate(x , y , op):
    if op == '+' :
        z = x  + y
    elif op == '-' :
        z = x - y
    elif op == '*' :
        z = x * y
    elif op == '//' :
        if y!=0:
            z = x // y
        else:
            z = "undefined"
    return z

print calculate(9 , 9 , '//')
print calculate(11 , 0 , '//')


texts: Separate models for rest API POST and GET

texts:
I'm currently all about separating things where it makes sense. We've come to conclusion that small, slim, only-what-really-need models are the only one accepeatable.

How about this scenario?

public class EmailModel
{
  public int Id {get; set;}
  public string Subject {get; set;}
  public string Body {get; set;}
  public List<AttachmentModel> Attachments {get; set;}
  ...
}

To create a new email, user makes HTTP POST request:

POST api/v1/emails
{
  "subject": "email subject",
  "body": "some email content .. "
}

There is additional api for atttachments ofcourse api/v1/emails/attachments with POST to upload attachment and GET to retrieve email attachments.

GET email returns something like this:

GET api/v1/emails/1
{
  "id": "1",
  "subject": "email subject",
  "body": "some email content .. "
  "attachments": []
}

Is it better to have two models then?

public class CreateEmailModel // for http post
{
  public string Subject {get; set;}
  public string Body {get; set;}
}
public class EmailModel : CreateEmailModel // for http get
{
  public int Id {get; set;}
  public List<AttachmentModel> Attachments {get; set;}
}

Or is this complicating things for no reason, but still when another developer sees the code it's immediately clear what the model does. No model property is unneccessary.


texts: Intersection of subset between two lists of dicts

texts:
I want to find the intersection of two lists of dicts.

Note that equality—i.e.: what is to appear in the intersection—is given by which keys they must have equal. See the obj_equal_on function.

def obj_equal_on(obj0, obj1, keys):
    for key in keys:
        if obj0.get(key, False) != obj1.get(key, None):
            return False
    return True

def l_of_d_intersection(ld0, ld1, keys):
    """ Find intersection between two lists of dicts.
          At best, will return `ld0` in full. At worst: [].

    :param ld0 :type [DictType]
    :param ld1 :type [DictType]
    :param keys :type ListType

    :returns intersection of ld0 and ld1 where key is equal.
    """

    return [obj1 for obj0 in ld1 for obj1 in ld0
            if obj_equal_on(obj0, obj1, keys)]

Basic testing (self-contained for SE, usually I'd subclass unittest.TestCase):

def run_example(ld0, ld1, keys, expected_result):
    result = tuple(l_of_d_intersection(ld0, ld1, keys))
    assert result == expected_result, '{0} != {1}'.format(result,expected_result)

def main():
    run_example(
        ld0=[{'foo': 'bar', 'haz': 'more'},
             {'can': 'haz', 'more': 'haz'},
             {'foo': 'jar', 'more': 'fish'}],
        ld1=[{'foo': 'bar'},
             {'can': 'haz'},
             {'foo': 'foo'}],
        keys=('foo',),
        expected_result=({'foo': 'bar', 'haz': 'more'},)
    )

    run_example(
        ld0=[
            {'orange': 'black', 'blue': 'green', 'yellow': 'red'},
            {'blue': 'yellow'},
            {'orange': 'red', 'yellow': 'blue'}
        ],
        ld1=[
            {'orange': 'black', 'yellow': 'red'},
            {'blue': 'yellow'},
            {'orange': 'red', 'yellow': 'blue'}
        ],
        keys=('orange', 'yellow'),
        expected_result=({'orange': 'black', 'blue': 'green', 'yellow': 'red'},
                         {'orange': 'red', 'yellow': 'blue'})
    )

My example works, but my code is rather horribly inefficient.


texts: Is there a cleaner/better way to write this Contact Manager in React?

texts:
I am learning React by doing a Contact Manager, I am trying to write this code more efficiently. Any ideas...good practise, component splitting, formatting tips are accepted too. Thanks in advance
P.S. Sorry for my English...I am from Italy.
First I used a separate function for everything, then I transformed person variable in an object to use the id and to map the array, then I used the person id to remove people by clicking the side button. Is it possible to do something else?
import React, { Component } from "react";
import "./App.css";

export default function App() {
  return (

React Contact Manager

      <Content />

  );
}

class Content extends Component {
  state = {
    people: [],
    name: "",
    age: "",
    telephone: "",
    searchTerm: "",
  };

  id = 1;
  people = [];

  getName = (e) => {
    this.setState({ name: e.target.value });
  };
  getAge = (e) => {
    this.setState({ age: e.target.value });
  };
  getTelephone = (e) => {
    this.setState({ telephone: e.target.value });
  };
  getSearchTerm = (e) => {
    this.setState({ searchTerm: e.target.value });
  };

  AddPerson = () => {
    const newPerson = {
      id: this.id,
      name: this.state.name,
      age: this.state.age,
      telephone: this.state.telephone,
    };
    this.people.push(newPerson);
    this.setState({ people: this.people });
    this.id++;
  };

  RemoveElement = (id) => {
    let newPeople = this.people.filter((person) => person.id !== id);
    this.people = newPeople;
    this.setState({ people: this.people });
  };

  ClearItems = () => {
    this.people = [];
    this.setState({ people: this.people });
  };

  render() {
    return (

          <input
            type="text"
            placeholder="Name"
            className="fname"
            onChange={this.getName}
          />
          <input
            type="number"
            placeholder="Age"
            className="age"
            onChange={this.getAge}
          />
          <input
            type="tel"
            placeholder="Telephone Number"
            className="telephone"
            onChange={this.getTelephone}
          />

          <button className="add" onClick={this.AddPerson}>
            Add
          </button>

          {(this.people || []).map((person) => (

                {person.name + ", " + person.age}
                {person.telephone}

              <button
                className="delete"
                onClick={() => this.RemoveElement(person.id)}
              >
                Remove
              </button>

          ))}

        <button className="clear" onClick={this.ClearItems}>
          Clear
        </button>

    );
  }
}


texts: Finding the weight of the heaviest path in a binary tree

texts:
I'm fairly new to Java, arriving in the "future" from C and returning to type safety from Python. I've programmed an algorithm to return the weight of the heaviest path from the root of a binary tree to one of its leaves.

Each Node in the tree has a weight (its data).  The weight of the path is the sum of all of the Nodes weights from root to leave inclusive. This algorithm finds the heaviest.

I'm looking for your suggestions to improve this code in the following areas:

Terminology - is there a name for this problem? have I used
conventional names for things?
Correctness - are there any bugs?
Java conventions and idioms - can I make better use of the standard
libraries?
Runtime performance.
Repetition - is there any way to avoid writing the field names 4 times each?

package binaryTree;

class Node {
    Integer data;
    Node left;
    Node right;

    public Node(Integer data, Node left, Node right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }

    public Node(Integer data) {
        this(data, null, null);
    }

}

public class BinaryTree {

    /**
     * Finds the heaviest path in the tree from the given @root Node to a leaf Node.
     * @param root
     * @return integer representing the sum weight of the heaviest path.
     */
    public static int getHeaviestPathWeight(Node root) {
        if (root == null)
            return 0;
        else
            return root.data + Math.max(getHeaviestPathWeight(root.left), getHeaviestPathWeight(root.right));
    }

}


texts:
Link to full problem description: https://www.codewars.com/kata/534e01fbbb17187c7e0000c6
My code:
def spiralize(size):
    def get_change_values():
        change_x = 0
        change_y = 0
        if direction == 'right':
            change_x = 1
        elif direction == 'left':
            change_x = -1
        elif direction == 'down':
            change_y = 1
        elif direction == 'up':
            change_y = -1
        return change_x, change_y

    def check_collision():
        if 0 <= y + change_y * 2 < size and 0 <= x + change_x * 2 < size:
            if direction in ('right', 'left'):
                if spiral[y][x + change_x * 2]:
                    return True
            elif direction in ('down', 'up'):
                if spiral[y + change_y * 2][x]:
                    return True
        return False

    spiral = [[0 for _ in range(size)] for _ in range(size)]
    directions = ['right', 'down', 'left', 'up']
    x = y = 0
    change_directions = 0
    while change_directions < size:
        direction = directions[change_directions % 4]
        change_x, change_y = get_change_values()
        while 0 <= y + change_y < size and 0 <= x + change_x < size:
            spiral[y][x] = 1
            if check_collision():
                break
            y += change_y
            x += change_x
        change_directions += 1
    return spiral

The basic idea of what my algortihm is trying to do here:

Initialize a matrix of 0s of the given size
Starting from the top left and heading towards the right, go through each element and change it to '1' until it can no longer move in that direction
Once it can no longer move in a given direction, change the direction based on the order right -> down -> left -> up
Repeat until spiral is complete (until size-1 changes of direction have been made)

The main advice I'm looking for here is how to better structure this code to make it more readable and understandable to the average viewer. Granted, if there are any glaring performance optimizations that can be made to improve this code, I'd be more than willing to hear those out as well. But again, I'm mostly looking for advice on how to make this code cleaner in general. I'm not exactly a new programmer per se, but the concept of 'clean code' is still something I very much struggle with.


texts: VBA function to extract worksheets with numeric names

texts:
I have written some code to extract a list of worksheets in the ActiveWorkbook, but only for sheets that have a numeric name.

This works, but I would like to know the Code Review community's thoughts on my methods used here.

Public Sub listNumberedSheets()

    Dim sheetNumberArray As Variant
    ReDim sheetNumberArray(0)

    Dim x As Long
    x = 0

    Sheets(1).Columns(1).ClearContents

    Dim sht As Worksheet
    For Each sht In ActiveWorkbook.Sheets
        If IsNumeric(sht.Name) Then
            ReDim Preserve sheetNumberArray(x)
            sheetNumberArray(x) = sht.Name
            x = x + 1
        End If

    Next

    Sheets(1).Cells(1, 1).Resize(x, 1).Value = Application.Transpose(sheetNumberArray)

End Sub


texts:
Here is my lock-free queue implementation for single producer with some preallocated memory. T is a simple type with no need for move operations. I don't use bool pop(T& result) in order to avoid double checking. I would love to see your feedback!

template <typename T>
class LockFreeQueue {
public:
    void setup(U8* buffer, U32 size) {
        m_buffer = (T*)buffer;
        m_size = size;
        clear();
    }

    void clear() {
        m_first.store(0, std::memory_order_relaxed);
        m_last.store(0, std::memory_order_relaxed);
    }

    void push(const T& value) {   // only for single producer
        U32 last = m_last.load(std::memory_order_relaxed);
        m_buffer[last] = value;
        U32 next = inc(last);
        ASSERT(next != m_first.load(std::memory_order_relaxed), "Queue overflow");
        m_last.store(next, std::memory_order_release);
    }

    bool isEmpty() {
        return m_first.load(std::memory_order_relaxed) == m_last.load(std::memory_order_relaxed);
    }

    void pop(T& result) {    // for single consumer. check isEmpty() before
        ASSERT(!isEmpty(), "Queue is empty");
        U32 first = m_first.load(std::memory_order_relaxed);
        result = m_buffer[first];
        m_first.store(inc(first), std::memory_order_release);
    }

    bool tryPop(T& result) {    // for multiple consumers. don't use isEmpty()
        while (true) {
            U32 first = m_first.load(std::memory_order_relaxed);
            if (first == m_last.load(std::memory_order_relaxed))
                return false;
            result = m_buffer[first];
            if (m_first.compare_exchange_weak(first, inc(first), std::memory_order_release))
                return true;
        }
    }

private:
    U32 inc(U32 n) { return (n + 1) % m_size; }

    T* m_buffer;
    U32 m_size;
    std::atomic<U32> m_first;
    std::atomic<U32> m_last;
};


texts:
I have written a recursive function that I believe will return the 'maximum' row of the 4x4 matrix it is fed. By 'maximum' I mean that the maximum row of the matrix.

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

is row 4 (on account of the first column's values); the maximum row of the matrix

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

is row 3 (on account of the first and second columns' values); the maximum row of the matrix

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

is row 4 (on account of the first, second, and third columns' values); the maximum row of the matrix

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

is row 4 (on account of the values in every column); and the maximum row of the matrix

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

is row 3 (on account of the values in every column - pick the topmost row).

This function is a lot more involved than I expected when I sat down to write it. Please tell me there's an easier way to express this algorithm in C!

(The function is employed in a program written by a Pascalite; please forgive the fact that the arrays ignore their 0th member!)

Here's the function (together with its helper indexOf(), which is never fed an array in which val fails to appear!) Apologies for variable indentation - bit of a nightmare just getting it to this state!

int indexOf(int a[], int val)
{ /* returns index at which val occurs in a[] */
    int i=1;

    while(a[i] != val)
        i++;

    return i;
}

int maxRow (int a[5][5], int index)
{
  int store [5] = {-1, a[1][index], a[2][index], a[3][index], a[4][index] };
  int store2[5] = {-1, a[1][index], a[2][index], a[3][index], a[4][index] };

  int i, j, k, max, i1=0, i2=0, i3=0, i4=0;
  int arr[5]={-1,-1,store2[2],store2[3],store2[4]};

  if (index==5)
  {
    if(a[1][4]>=0)
        return 1;
    else if(a[2][4]>=0)
        return 2;
    else if(a[3][4]>=0)
        return 3;
    else if(a[4][4]>=0)
        return 4;
  }

  /* order store[] from max -> min: */

  for(i=1; i<=3; i++)
  {
    max=store[i];
    j=i;
    for(k=i+1; k<=4; k++)
        if(store[k]>max)
        {
            max=store[k];
            j=k;
        }
    store[j]=store[i];
    store[i]=max;
  }

  i1 = indexOf(store2, store[1]);

  /* now we must indicate which (if any ) rows to recurse on... */

  if (store[1]==store[2])
  {
    if(i1==1)
        i2 = indexOf(arr,store[1]);
    else if (i1==2)
    {
        arr[2] = -1;
        i2 = indexOf(arr, store[1]);
    }
    else if (i1==3)
        i2 = 4;

    /* note: if i2==4 then can't have store[1] equal to any other members of store[] */

    if(store[1]==store[3])
    {
        /* i2 = 2 or 3 */

        if(store2[4] <= store2[3])
            i3 = 3;
        else i3=4;

        if (store[1]==store[4])
        {
            i4=4;
        }
    }
  }

    if (i2==0)
        return i1;

    else if(i3==0)
    {
          i = indexOf(store2,store[4]);

          for(j=0;j<5;j++)
            a[i][j]=-1;

          i = indexOf(store2,store[3]);

          for(j=0;j<5;j++)
            a[i][j]=-1;

          return maxRow(a, index+1);
    }
    else if (i4==0)
    {
      i = indexOf(store2,store[4]);

      for(j=0;j<5;j++)
            a[i][j]=-1;
      return maxRow(a, index+1);
    }
    else /* all i are non-zero */
      return maxRow(a, index+1);
}


texts:
I've written a Vigenere decypher and I would like to have some opinions before I try to refactor it into more OOP style with classes and such.

#include <bits/stdc++.h>
#define Rep(i,a,n) for(int i = a; i < n; i++)
#define rep(i,n) Rep(i,0,n)
using namespace std;
int main(){
    string key, line, code = "", dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", decoded = "";
    cin >> key;
    int n = dict.length();
    char** key_matrix = new char*[n];
    rep(i,n)
        key_matrix[i] = new char[n];
    rep(i,n)
        rep(j,n)
            key_matrix[i][j] = dict[(i+j)%n];
    fstream file;
    file.open("text.txt");
    while(getline(file, line))
        code += line;
    file.close();
    rep(i,code.length()){
        if(!iswspace(code[i])){
            rep(j,n)
                if(key_matrix[j][0] == key[i%key.length()]){
                    rep(k,n)
                        if(key_matrix[j][k] == code[i]){
                            decoded += key_matrix[0][k];
                            break;
                        }
                }
        }else{
            decoded += " ";
        }
    }
    cout << decoded;
}


texts:
I have the following function to collect quota information for the given user and return the information on a "ready to use" array:

/* Get User Quota Information
 *
 * Prepare and array with the user's account disk space information
 * by ascertaining the amount of space available on its quota,
 * the used space from that quota and free space remaining.
 *
 * @param string $user The system user name
 *
 * @return array
 */
function getUserQuotaInfo($user) {

  $quota = exec("quota -s -u ".$user);            // query server

  $quota = preg_replace("/[\s-]+/", ' ', $quota); // clear spaces

  $arr = explode(' ', $quota);

  $freeSpace = str_replace('M', '', $arr[3]) - str_replace('M', '', $arr[2]);

  return array(
    "total" => $arr[3],
    "used"  => $arr[2],
    "free"  => $freeSpace.'M'
  );
}

The function is working well and giving the expected results, but there's a lot going on to manipulate the information in order to have it ready to present to the user.

Is there any optimization that can be done as to reduce the possibilities of failure on this function as well as simplifying it?


texts: Presidential election predictor using matrix-processing

texts:
I'm currently working on a project where I am trying to predict a presidential election based on the population density and region of a voter. I wrote a few MATLAB functions to parse the data, but it takes about a minute to run, which seems long.  My languages of choice are usually Java or Python and I feel like this calculation would only top a few seconds in those languages.

Quick side note: although this is for a school project, it is a simulation class, not a programming class.  The code works, which is what is required, the efficiency of the code is personal interest.

Main test script

%test metrics
printf("starting test\n");
p0 = parsePopMap("density2010.png"); %not shown because this returns quickly
[vm,rp,dp] = metrics(p0);
printf("republican:%d\ndemocrat:%d\n",rp,dp)

metrics.m

%generate matrix determining republican vote
function [voteMatrix,republicanPixels,democratPixels] = metrics(popGraph)

voteMatrix = zeros(rows(popGraph),columns(popGraph));

republicanPixels=0;
democratPixels=0;
printf("loading regions\n");
%regions is a matrix of size == popGraph, has values from 1-6
%so that any regions(row,column) returns the region of the country
load regions; %based on the printout, this happens within seconds
printf("calculating votes\n");

%suspected bottleneck
for r = [1:rows(popGraph)]
    for c = [1:columns(popGraph)]
        pixelRegion = regions(r,c);
        if (pixelRegion == 6)
            voteMatrix(r,c)=-1; %because it is water
        else
            vote = voteFromLocation(pixelRegion,popGraph(r,c));
            voteMatrix(r,c) = vote;
            if vote>.5
                republicanPixels +=1;
            else
                democratPixels +=1;
            end
        end
    endfor
endfor

voteFromLocation.m

function vote = voteFromLocation(region,popDens)

% array is percent for urban, suburban, rural
% probability area will vote republican
voteAverage = [ [.375,.51,.79];%pacific coast
                [.40,.54,.765];%midwest
                [.30,.47,.48];%Northeast
                [.485,.625,.725];%south
                [.46,.62,.795]];%Mountains/plains
voteDelta = [   [.05,.06,.1];%pacific coast
                [.04,.04,.07];%midwest
                [.12,.06,.10];%northeast
                [.09,.07,.27];%south
                [.12,.08,.21]];%mountains/plains

%represents the max value of that demographic
ruralThresh = 900; %so <=900 is rural
subThresh = 1100; % 900<x<=1100 is suburban
%urban is anything above 1100

demo = -1;
if(popDens<=ruralThresh)
    demo = 3;
elseif(popDens<=subThresh)
    demo = 2;
else
    demo = 1;
end
mean = voteAverage(region,demo);
stdDev = voteDelta(region,demo);
probVoteRep = (mean + stdDev * randn());

vote = probVoteRep;

I believe the source of the bottleneck is the for loops of metrics.m.  Most matrix processing I've seen uses different approaches, which I believe may be faster.


texts:
I have been updating my build tools to optionally us autotools (autoconfig/automake/libtool etc.).

As part of this change I have written a couple of M4 macros. This not being something I have done before, any input appreciated on style or if things can be done better.

AC_DEFUN(
    [AX_FUNC_THOR_BUILD],
    [
        AC_CHECK_PROGS([WGET], [wget], [:])
        if test "$WGET" = :; then
            AC_MSG_ERROR([This package needs wget.])
        fi

        AC_CHECK_PROGS([UNZIP], [unzip], [:])
        if test "$UNZIP" = :; then
            AC_MSG_ERROR([This package needs unzip.])
        fi

        AC_PROG_CXX

        git submodule init
        git submodule update
        pushd build/third
        ./setup "$CXX" || AC_MSG_ERROR([Failed to set up the test utilities], [1])
        popd
    ]
)

Should I pull the setup script into this macro or leave it separate?

#!/bin/bash
set -e
CXX=$1
#
# Change this as required to point at the root of ThorsAnvil code
ROOT=$(pwd)
THORSANVIL_ROOT=$(dirname ${ROOT})
if [[ -e ${THORSANVIL_ROOT}/lib/libgtest.a ]]; then
    exit 0
fi

echo "Un-archiving google test"
GTEST_ARCHIEVE=`ls gtest-*.zip 2>/dev/null | tail -n 1`
if [[ ${GTEST_ARCHIEVE} == "" ]]; then
    echo "Retrieving: gtest-1.7.0"
    wget http://googletest.googlecode.com/files/gtest-1.7.0.zip
    GTEST_ARCHIEVE=`ls gtest-*.zip 2>/dev/null | tail -n 1`
fi

GTEST_ARCHIEVE_DIR=${GTEST_ARCHIEVE%.zip}
if [[ ! -d ${GTEST_ARCHIEVE_DIR} ]]; then
    unzip ${GTEST_ARCHIEVE}
fi

echo "Building google test"
GTEST_DIR=${ROOT}/${GTEST_ARCHIEVE_DIR}
pushd ${GTEST_DIR}
${CXX} -I${GTEST_DIR}/include -I${GTEST_DIR} -c ${GTEST_DIR}/src/gtest-all.cc
${CXX} -I${GTEST_DIR}/include -I${GTEST_DIR} -c ${GTEST_DIR}/src/gtest_main.cc
ar -rv libgtest.a gtest-all.o gtest_main.o
popd

echo "Installing google test"
pushd ${THORSANVIL_ROOT}
mkdir -p bin include include3rd lib
rm -f lib/libgtest.*
cp ${GTEST_DIR}/libgtest.a lib/
rm -f include3rd/gtest
ln -s ${GTEST_DIR}/include/gtest include3rd/gtest
popd


texts:
I have Client and Server classes.

The Server return a ResultWithNestedTask instance.

public class ResultWithNestedTask
{
    public Task<String> NestedTask;
    public string Result;
}

The Client displays the data from Result, then waits for the completion of NestedTask and displays the result from NestedTask.

The Server:

Starts a new Task and waits for the result
Starts a nested task and returns the task to the client
Waits for the nested task to complete before doing some work with result.

Server's method DoWorkAsync:

    static async Task<ResultWithNestedTask> DoWorkAsync()
    {
        // start new Task and wait result
        var resultTask = await Task<String>.Factory.StartNew(() =>
        {
            return "Result task.";
        });

        //start neasted task
        var resultNestedTask = Task<String>.Factory.StartNew(() =>
        {
            Task.Delay(TimeSpan.FromSeconds(5)).Wait(); //wait while return data
            return "Result neasted task.";
        });

        //do some work whith nested task
        Task.Factory.StartNew(() =>
            {
                resultNestedTask.Wait();
                var resultFromNestedTask = resultNestedTask.Result;
                resultFromNestedTask = "Updated string";
                Console.WriteLine(resultFromNestedTask);
            });

        //return result string and neasted task to the client
        return new ResultWithNestedTask()
        {
            NestedTask = resultNestedTask,
            Result = resultTask,
        };
    }

Client:

var taskResult = await DoWorkAsync();

// writeline result string
Console.WriteLine(taskResult.Result);

// client wait NestedTask
var nestedTask = await taskResult.NestedTask;

// writeline result string from nested task
Console.WriteLine(nestedTask);

This code should not block the UI.

The server returns the nested task and doesn't wait for the nested task to finish.

 //do some work with the nested task
 Task.Factory.StartNew(() =>
 {
     resultNestedTask.Wait();
     var resultFromNestedTask = resultNestedTask.Result;
     resultFromNestedTask = "Updated string";
     Console.WriteLine(resultFromNestedTask);
 });

I want to return the result before the task completes.

Client and Server are abstractions, and just one class takes data from another class.

Is this normal code? Do you see any problems?


texts: Determinant calculation of a matrix of any degree

texts:
My program calculates the determinant of a matrix of any degree. If you really can't understand my comments or indentifiers please let me know.

//;;MakeShift make element number 'ind' the head of list:
(defun MakeShift (ind L buf)
    (if (= ind 1) (cons (car L) (append buf (cdr L)))
       (makeReplace (- ind 1) (cdr L) (append buf (list (car L))))
    )
)

//;;Shift call MakeShift:
(defun Shift (ind L) (MakeShift ind L nil))

//;;makeTransp make transposition of two elements list:
(defun makeTransp (L) (cons (cadr L) (cons (car L) nil)))

//;;PushForEach put element elem into a heads of all lists of L:
(defun PushForEach (elem L)
    (if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))
    )
)

//;;MakeTranspositions create a list of all transpositions
//;;using first transposition like '(1 2 3 ...).
//;;transpNum is transpositions  number and numOfElem
//;;is amount of elements in transposition:
(defun MakeTranspositions (transp transpNum numOfElem)
    (cond ((> transpNum numOfElem) nil)
        ((= numOfElem 2) (cons transp (cons (makeTransp transp) nil)))
        (T (append (PushForEach (car transp) (MakeTranspositions (cdr transp) 1 (- numOfElem 1)))
            (MakeTranspositions (Shift (+ transpNum 1) transp) (+ transpNum 1) numOfElem)))
    )
)

//;;MakeFirstTransp make a first transpositiion like '(1 2 3 ... )
//;;which has number of element equal matrix degree:
(defun MakeFirstTransp (matrixDegree transp)
    (if (= matrixDegree 0) transp
        (MakeFirstTransp (- matrixDegree 1) (cons matrixDegree transp))
    )
)

//;;Transpositions make all transpositions of matrix using MakeTranspositions:
(defun Transpositions (matrixDegree)
    (MakeTranspositions (MakeFirstTransp matrixDegree nil) 1 matrixDegree)
)

//;;GetCol return elemnt number col in row (row belong to matrix):
(defun GetCol (col rowVector)
    (if (= col 1) (car rowVector)
        (GetCol (- col 1) (cdr rowVector))
    )
)

//;;GetElem return element a[row][col] which belong to matrix:
(defun GetElem (row col matrix)
    (if (= row 1) (GetCol col (car matrix))
        (GetElem (- row 1) col (cdr matrix))
    )
)

//;;CheckFirst check first element in transposition (cons first transp) for even:
(defun CheckFirst (first transp)
    (cond ((null transp) 1)
        ((< first (car transp)) (CheckFirst first (cdr transp)))
        (T (* -1 (CheckFirst first (cdr transp))))
    )
)

//;;Sign return sign of transposition (1 or -1):
(defun Sign (transp)
    (if (null (cdr transp)) 1
        (* (CheckFirst (car transp) (cdr transp)) (Sign (cdr transp)))
    )
)

//;;Product return product of elements of matrix by transposition transp:
(defun Product (matrix transp) (GetProduct matrix 1 transp))

//;;GetProduct are called by Product:
(defun GetProduct (matrix ind transp)
    (if (null transp) 1
        (* (GetElem ind (car transp) matrix)
            (GetProduct matrix (+ ind 1) (cdr transp))
        )
     )
)

//;;GetSumm return summ of all products by transpositions whith their signs:
(defun GetSumm (matrix transps)
    (if (null transps) 0
        (+ (* (Sign (car transps)) (Product matrix (car transps)))
            (GetSumm matrix (cdr transps))
        )
    )
)

//;;Determinant call GetSumm:
(defun Determinant (matrix matrixDegree)
    (GetSumm matrix (Transpositions matrixDegree))
)

//;;So, programm work fast.


texts: Read and sort 100 numbers from a text file

texts:
The program itself reads 100 values from a text file named input.txt. Then sorts those values in ascending order and writes the values to a new file called output.txt.
I used two try-catches for the Scanner and the PrintWriter since to my very basic knowledge they can throw different exceptions. So if anyone can review the code and let me know if my style is bad/good and what could be better, that would be much appreciated.
    //Create new file in, used for input.
    File in = new File("input.txt");

    /* Used two try-catch blocks to narrow down the potential error.
    * Read online if you use try-catch you want to keep them as
    * narrow as possible to know what to catch.
    * If this is bad style let me know.
    */

    try {
        Scanner input = new Scanner(in);
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
        }
        input.close();
        Arrays.sort(numbers);
    } catch (FileNotFoundException e) {
        /*Assume the file is missing since new Scanner(in);
        * will implicitly check if the input file actually exists.
        */
        System.err.println("File missing. Exiting with code: 1");
        System.exit(1);
    }

    try {
        PrintWriter output = new PrintWriter("output.txt");
        for (int i = 0; i < numbers.length; i++) {
            output.println(numbers[i]);
        }
        output.close();
    } catch (IOException ex) {
            System.err.printf("File name does not denote an existing, writable regular file %n"
                            + "and a new regular file of that name cannot be created%n"
                            + "Or another error occured creating/writing to the specified file.%n"
                            + "Exiting with code: 2");
            System.exit(2);
    }


texts: Continuously execute runnables on the UI thread

texts:
I need to run a sequence of runnables on the main (ui) thread with a given delay between them indefinitely until signalled to stop. Code:

public class UiLoop {

    private Handler h;
    private AtomicBoolean breakLoop;

    @UiThread
    public UiLoop() {

        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new RuntimeException("Not called on ui thread!");
        }

        h = new Handler();
        breakLoop = new AtomicBoolean(false);
    }

    /**
     * Break out of the loop on the next iteration.
     */
    public void breakLoop() {
        this.breakLoop.set(true);
    }

    /**
     * @param workers    A Deque of runnables to execute sequentially.
     * @param delay The delay between executing the runnables. This is excluding the time it
     *              takes for the runnable to complete.
     */
    @UiThread
    public void loop(Deque<Runnable> workers, int delay) {

        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new RuntimeException("Not called on ui thread!");
        }

        if (workers.isEmpty()) return;

        if (breakLoop.get()) return;

        final Runnable first = workers.removeFirst();
        h.post(first);
        workers.addLast(first);
        h.postDelayed(() -> loop(workers, delay), delay);

    }
}

Is the above code OK?

PS: I am using retrolambda to convert Anonymous Inner Classes to lambda functions.


texts:
I have been trying to automate a lot of stuff lately. I am looking for feedback about my first gulpfile.js.
From what I learned so far gulp is quite powerful but I'm still learning.

I am looking for ways to improve my current file, are there better ways to do what I have so far?

I am especially looking for help concerning my image task and my build/dev environments. Currently, the only difference between dev and build is the fact that dev runs browser sync and does not compress my images (I don't want to reach my API limit or wait for the long build time). Is this the right way?
My other concern is the image task. Tinypng only accepts PNGs and JGPs so I want to compress them and just copy the not supported formats.
Any help is welcome!

GulpFile:

import del from 'del'
import gulp from 'gulp'
import htmlmin from 'gulp-htmlmin'
import tinypng from 'gulp-tinypng'
import browserSync from 'browser-sync'
import merge from 'merge-stream'

const server = browserSync.create()

const reload = done => {
  server.reload()
  done()
}

const serve = done => {
  server.init({ server: '_dist' })
  done()
}

const paths = {
  html: {
    base: './_src',
    dest: '_dist',
    src: '_src/**/*.html'
  },
  styles: {
    dest: '_dist',
    src: '_src/**/*.html'
  },
  scripts: {
    dest: '_dist/',
    src: '_src/**/*.html'
  },
  images: {
    base: '_src/assets/images',
    dest: '_dist/assets/images',
    src: '_src/assets/images/**/*',
    srcNonOptimizable: [
      '_src/assets/images/**/*',
      '!_src/assets/images/**/*.{jpg,jpeg,png}'
    ],
    srcTinypng: '_src/assets/images/**/*.{jpg,jpeg,png}'
  },
  fonts: {
    dest: '_dist/assets/fonts',
    src: '_src/assets/fonts/*'
  }
}

export const clean = () => del(['_dist'])

export const html = () => {
  return gulp
    .src(paths.html.src, { base: paths.html.base, since: gulp.lastRun(html) })
    .pipe(htmlmin({ collapseWhitespace: true }))
    .pipe(gulp.dest(paths.html.dest))
}

export const styles = () => {
  console.log('Coming soon...')
}

export const scripts = () => {
  console.log('Coming soon...')
}

export const images = () => {
  const optimizeImages = gulp
    .src(paths.images.srcTinypng, { base: paths.images.base })
    .pipe(tinypng('api-key'))
    .pipe(gulp.dest(paths.images.dest))
  const copyImages = gulp
    .src(paths.images.srcNonOptimizable, { base: paths.images.base })
    .pipe(gulp.dest(paths.images.dest))
  return merge(optimizeImages, copyImages)
}

export const copyImages = () => {
  return gulp
    .src(paths.images.src, {
      base: paths.images.base,
      since: gulp.lastRun(copyImages)
    })
    .pipe(gulp.dest(paths.images.dest))
}

export const copyFonts = () => {
  return gulp
    .src(paths.fonts.src, { since: gulp.lastRun(copyFonts) })
    .pipe(gulp.dest(paths.fonts.dest))
}

export const watch = () => {
  gulp.watch(paths.html.src, gulp.series(html, reload))
  gulp.watch(paths.styles.src, gulp.series(styles, reload))
  gulp.watch(paths.scripts.src, gulp.series(scripts, reload))
  gulp.watch(paths.images.src, gulp.series(copyImages, reload))
  gulp.watch(paths.fonts.src, gulp.series(copyFonts, reload))
}

const dev = gulp.series(
  clean,
  gulp.parallel(html, copyImages, copyFonts),
  serve,
  watch
)
const build = gulp.series(clean, gulp.parallel(html, images, copyFonts))

gulp.task('dev', dev)
gulp.task('build', build)
export default dev


texts:
I've found a peace of code I've wrote not long ago. It is used to fetch some dictinary from DB table only once and then return it to requestors. Seems like I tryed to implement double-checked locking here. Is it correct? If not, what are the mistakes?

package a.b.c.service.orders;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import a.b.c.dao.OrderStatusesDao;
import a.b.c.model.OrderStatuses;

@Component
public class OrderStatusesService {
  @Autowired
  private OrderStatusesDao orderStatusesDao;

  private volatile Map<String, String> cached;

  @Transactional(rollbackFor = Exception.class, readOnly = true)
  public Map<String, String> getAllOrderStatuses() {
    if (null == cached) {
      synchronized (OrderStatusesService) {
        if (null == cached) {
          final List<OrderStatuses> orderStatuses = orderStatusesDao.getAll();

          cached = new HashMap<String, String>();
          for (OrderStatuses orderStatus : orderStatuses) {
            cached.put(orderStatus.getCode(), orderStatus.getName());
          }
        }
      }
    }

    return cached;
  }
}


texts:
I have a MySQL database, with a table called articles. There is a column in articles for its id, name, date_created, etc.

I want to create a page for each article, for example:

  example.com/article.php?id=1

  example.com/article.php?id=2

  ...

My code works right now, but is there anything I should do differently? I'm worried about the safety of the code. Is there a better way to validate/sanitize the id?

<?php
        require_once('../mysqli_connect.php');

        if(isset($_GET['id'])){

            // Replace
            $idv = preg_replace("#[^0-9]#","", $_GET['id']);

            $query = "SELECT name, description, date, id, date_created
            FROM articles WHERE id = $idv LIMIT 1";

            $result = mysqli_query($dbc, $query);

            if ($result){

                $row = mysqli_fetch_assoc($result);

                if(!$row)
                {
                    //Row doesnt exist
                    //Redirect user somewhere else
                }
                else
                {
                    // echo blog post, with html
                }
            }

            else
            {
                echo "Couldn't issue database query
";
                echo '
' . mysqli_error($dbc) . '
';
                // Redirect user
            }

        }

        else
        {
            //Redirect user
        }

        mysqli_close($dbc);

    ?>


texts: Script to backup data to specific USB Drive

texts:
I have a script and I was looking to have it reviewed to see where I should improve it.

Our need: We need to backup a folder every day to a specific USB drive. There may be multiple USB drives plugged into the computer. We need to ensure that it is only backing up to a specific drive.

Code:

function ex{exit}

#####################################
### Check PC for backup USB Drive ###
#####################################

$diskdrive = Get-WmiObject win32_diskdrive

foreach($drive in $diskdrive){
  $partitions = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($drive.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"

    foreach($part in $partitions){
        $name=$drive.model
        $vols = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($part.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"

    foreach($vol in $vols){
       If($name -eq "General UDisk USB Device" ){
       $USBDisk=$vol.name
       }
     }
  }
}

if ( $USBDisk -eq $null ) {
[void][System.Windows.Forms.MessageBox]::Show("Custom Backup, Please Plug-In the USB Drive","USB Drive not found")
ex
}

###########################################
### Purge USB for data over 90 days old ###
###########################################

$limit = (Get-Date).AddDays(-90)

Get-ChildItem -Path $USBDisk -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $USBDisk -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

#########################
### Backup Custom DBs ###
#########################

# Import Assemblies
[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

$date = Get-Date -Format MMMM.d.yyyy
$backupFolder = "Backup_" + "$date"

if ( $USBDisk -eq $null ) {
#[void][System.Windows.Forms.MessageBox]::Show("No USB Disk Found, Please Plug-In the USB Drive","USB Drive not found")
}
else {
$Usbfreedisk =  ((Get-WmiObject win32_logicalDisk  | where { $_.DeviceID -eq $USBDisk }).FreeSpace /1gb -as [INT])
$FPBackup= Get-ChildItem -Recurse "C:\Folder" | Measure-Object -property length -sum
[int]$DataFilesize = ($FPBackup.sum / 1GB )

if ( $Usbfreedisk -lt $DataFilesize ) {
    [void][System.Windows.Forms.MessageBox]::Show("Your $USBDisk Drive don't have enough space, for backup we need $DatafileSize GB of free space.","Not Enough space")
    }
else {
    $testfolder = Test-Path "$USBDisk\$backupFolder"
  if ( $testfolder -eq $true ) {
  [void][System.Windows.Forms.MessageBox]::Show("You already have backup folder $USBDisk\$backupFolder Please rename it or delete it before running the backup ","Backup Folder Exists")
  }
 else{
  mkdir "$USBDisk\$backupFolder"
  Robocopy "C:\Folder"  "$USBDisk\$backupFolder\CYA" /mir /r:2 /w:3
    if ($lastexitcode -eq 0){
            write-host "Robocopy succeeded"
            }
            else{
            write-host "Robocopy failed with exit code:" $lastexitcode
            }
        }
    }
}

Please let me know if anyone needs any clarification on anything.

Thanks