texts:
I'm learning racket and did simple code challenge in a literate programming style with org mode

The problem:

  Given a matrix of integers and the top left and bottom right coordinates of a rectangular region within the matrix, find the sum of numbers falling inside the rectangle.

1 2 3 4
5 6 7 8
9 0 1 2

should give 24 for locations (1 1)-(3 2) as that is the sum of the submatrix

6 7 8
0 1 2

Here is my final implementation

(require math/array)

(struct location (column row))

(define (sum-matrix-region matrix start end)
  (define slice-spec (list (:: (location-row start)
                               (add1 (location-row end)))
                           (:: (location-column start)
                               (add1 (location-column end)))))
  (define sliced (array-slice-ref matrix slice-spec))
  (array-all-sum sliced))

(sum-matrix-region (array #[#[1 2 3 4]
                            #[5 6 7 8]
                            #[9 0 1 2]])
                   (location 1 1)
                   (location 3 2))

Is that good? Idiomatic? Anything I could have done better?

I'm aware that for literate programming I can provide variables via tables but the only racket-supporting org plugin I found doesn't support that.


texts: Efficient way of reading in list of string csvs' into lists

texts:
I have a list of strings. Each string is a comma separated list of numbers. I want to quickly convert each of these strings into a list. So far I have done the following:

My Solution So Far

def convertCommaSeperatedStringToList(data):

    s_lists = []

    for s in data:
        s_list =  [int(x) for x in s.split(',')]
        s_lists.append(s_list)

Example Dataset

# Here we have 600 very long lists to process
import numpy as np

data = []

for x in range(0,600):
    a = (np.random.randint(1000,size=100000)).tolist()
    b = ','.join(str(x) for x in a)
    data.append(b)

Just some background if you're wondering why I would have such a wierd list, I am reading this list from a downstream database.


texts:
I have to create an XML body for a web service call. I want to use:

private void createProductBody(Product product, StringBuilder body) {
    body.append(WSConstants.WS_PRODUCT_ID_START_TAG)
            .append(product.getId())
            .append(WSConstants.WS_PRODUCT_ID_END_TAG)
            .append(WSConstants.WS_SIZE_TEXT_START_TAG)
            .append(product.getSize())
            .append(WSConstants.WS_SIZE_TEXT_END_TAG);
}

But some colleagues state that this writing is hard to read and they want us to use this:

private void createProductBody(Product product, StringBuilder body) {
    body.append("<ProductId>").append(product.getId()).append("</ProductId>")
        .append("<Size>").append(product.getSize()).append("</Size>");
}

Which are the pro and cons for using hardcoded values?


texts: Simple blog engine for educational purposes

texts:
I am coding a simple blog engine for educational purposes.

In the PostsController I have two two methods that share some common code namely, Add and Edit:

[HttpPost]
public ActionResult Add(PostInputModel model)
{
    if (!ModelState.IsValid) return View(model);

    // map the input model to an entity model using AutoMapper (extension method).
    var post = model.MapTo<Post>();
    post.Summary = Summarize(post.Content);
    post.PublishedAt = DateTime.Now;
    // convert the post title to a slug (Hello World becomes hello-world for example)
    post.Slug = SlugConverter.Convert(post.Title);
    AttachTags(post);

    // check whether the slug is occupied.
    if (repository.Posts.Any(p => p.Slug == post.Slug))
    {
        ModelState.AddModelError("", "title in use");
        return View(model);
    }

    repository.Posts.Add(post);
    repository.SaveChanges();

    // indicates that a "post published. available here." message should be displayed.
    TempData["newPost"] = true;
    // redirect the user to the edit page
    return RedirectToAction("Edit", new { slug = post.Slug });
}

[HttpPost]
public ActionResult Edit(PostInputModel model)
{
    if (!ModelState.IsValid) return View("Edit", model);

    var post = repository.Posts.SingleOrDefault(p => p.Slug == model.Slug);
    // if the post does not exist return an error
    if (post == null) return HttpNotFound("you cannot edit a post that doesn't exist");
    repository.Posts.Remove(post);
    repository.SaveChanges();

    // map the input model to an entity model using AutoMapper (extension method).
    model.MapPropertiesToInstance(post);
    AttachTags(post);

    // convert the title to a slug (Hello World becomes hello-world for example)
    post.Slug = SlugConverter.Convert(post.Title);
    post.Summary = Summarize(post.Content);

    // check whether the slug is occupied.
    if (repository.Posts.Any(p => p.Slug == post.Slug))
    {
        ModelState.AddModelError("", "title in use");
        return View("Edit", model);
    }

    repository.Posts.Add(post);
    repository.SaveChanges();

    return Edit(post.Slug);
}

private static string Summarize(string content)
{
    if (!content.Contains(Environment.NewLine)) return content;
    return content.Split(new[] { Environment.NewLine }, StringSplitOptions.None)[0];
}

private void AttachTags(Post post)
{
    foreach (var tag in post.Tags)
    {
        if (repository.Tags.Any(x => x.Name == tag.Name))
        {
            repository.Tags.Attach(tag);
        }
    }
}

I have cleaned the code and reduced some duplication, but I am sure this code could be improved further. How can I make this code more DRY?


texts: Counting ways to form an amount using coins

texts:
This is just a fun little exercise I had to do for a homework once (in Java rather than Clojure though). Basically, the goal is to find the number of different coin stacks you can build with the coins 1,2,5 and 10 to form a number N (I believe a closed form solution for this exists, but this isn't what this is about).

My solution here works, but I'm not quite happy with it:

Explicit loop. Not sure how to do away with it though.
A few functions there that I think should be core functions, but I can't find them.
Even if they aren't in core, my functions could probably be written somewhat more concisely

Anyways, here's my code (by the way, the function is called "fast-iterative" because the exercise was about calculating these values recursively. Which I think is insane due to the branching factor, but whatever):

(ns test.coin-stacks)

(def maximum (partial reduce max))

(defn shift-vector
  "Shifts v one to the left, insert shift-val at the right"
  [v shift-val]
  (conj (vec (rest v)) shift-val))

(defn update
  "Updates ks in m with f applied to ks.
  I can't believe I have to write this myself."
  [m ks f]
  (apply assoc m (interleave ks (map (comp f m) ks))))

(defn fast-iterative-coinstacks
  "Returns the number of ways to form a coin stack with a total
  value of n with coins"
  [n coins]
  (let [max-coin (maximum coins)
        initial-stacks (apply conj [1] (repeat max-coin 0))]
    (loop [stacks initial-stacks iteration 0]
      (if-not (< iteration n)
        (first stacks)
        (recur (shift-vector (update stacks coins (partial +' (stacks 0))) 0)
               (inc iteration))))))


texts:
This is a programming exercise from chapter 8 of a C learning book by K N King. The program should prompt a user for a message, and return it after translating it to B1ff speak. e.g A->4, b->8 etc

The program works as asked in the exercise, however how can I create a more efficient declaration of the message[] array? Currently it is initialized to size N which is defined as 100 (large enough for most messages), instead of the size of the message from the user.

#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <ctype.h>

#define N 100

int main(int argc, const char * argv[]) {

    //Initialize
    char message[N] = {' '};
    char ch;
    int i = 0, j = 0, k= 0;

    //Prompt user for message
    printf("Enter a message: ");
    //Get message and put each character into an array
    while((ch = getchar()) != '\n'){
        ch = toupper(ch);
        message[i] = ch;
        i++;
    }
  //Print the B1ff speak converting characters
    printf("In B1FF-speak: ");
    for(k = 0; k<i; k++){
        switch(message[k]){
            case 's':
                printf("5");
                break;
            case 'O':
                printf("0");
                break;
            case 'I':
                printf("1");
                break;
            case 'E':
                printf("3");
                break;
            case 'B':
                printf("8");
                break;
            case 'A':
                printf("4");
                break;
            default:
                printf("%c", message[k]);
                break;
        }
    }

    //Print 10 or so exclamation marks and be a citizen
    printf("!!!!!!!!!!!!!!\n");
    return 0;
}


texts: Check if a numpy array contains numerical data

texts:
This function serves me as a testing-utility to check if the result is really numeric and sometimes as input-validation if there are a lot of operations before I would find out (with an Exception) if it's not-numerical.

But I feel like the .dtype.kind in ... is too complex. I've written this function a while back and tried using some better approach but I couldn't find any solution that works for python 2.7 and 3.x and different numpy version 1.7+.

The code:

import numpy as np

def is_numeric_array(array):
    """Checks if the dtype of the array is numeric.

    Booleans, unsigned integer, signed integer, floats and complex are
    considered numeric.

    Parameters
    ----------
    array : `numpy.ndarray`-like
        The array to check.

    Returns
    -------
    is_numeric : `bool`
        True if it is a recognized numerical and False if object or
        string.
    """
    numerical_dtype_kinds = {'b', # boolean
                             'u', # unsigned integer
                             'i', # signed integer
                             'f', # floats
                             'c'} # complex
    try:
        return array.dtype.kind in numerical_dtype_kinds
    except AttributeError:
        # in case it's not a numpy array it will probably have no dtype.
        return np.asarray(array).dtype.kind in numerical_dtype_kinds

and I have the following tests:

def test_not_array():
    assert is_numeric_array(1)
    assert is_numeric_array(1.)
    assert is_numeric_array(1+1j)
    assert not is_numeric_array('a')
    assert not is_numeric_array(None)
    assert is_numeric_array([1, 2, 3])

def test_array():
    assert is_numeric_array(np.array(1))
    assert is_numeric_array(np.array(1.))
    assert is_numeric_array(np.array(1+1j))
    assert is_numeric_array(np.array([1]))
    assert is_numeric_array(np.array([1.]))
    assert is_numeric_array(np.array([1+1j]))
    assert not is_numeric_array(np.array('a'))
    assert not is_numeric_array(np.array(['a']))

test_not_array()
test_array()


texts: Enigma questions from "ANSI Common Lisp"

texts:
I'm working through Paul Graham's ANSI Common Lisp and in Exercise 2.5, I'm stumped. My specific question (I wasn't sure whether this type of question is suitable for stack overflow, code review, or neither) is:

How to even begin working on an answer to this question.

What's interesting is that I simply don't know how to proceed, analytically. Hopefully, it isn't a question which involves simply knowing the answer due to existing familiarity. So, my question is subtle, and it's not simply to ask 'what is the answer', but 'how could you go about finding the answer', if you were really stumped. So I'm asking about method.

The Question: What do these functions do?

(defun enigma (x)
  (and (not (null x))
       (or  (null (car x))
            (enigma (cdr x)))))

(defun mystery (x y)
  (if (null y)
      nil
      (if (eql (car y) x)
          0
          (let ((z (mystery x (cdr y))))
            (and z (+ z 1))))))

I've realised in typing this in that one approach would be simply to run the functions. Perhaps we could call that the "what does this button do?" approach. :)

Update: before posting this, I've found I just solved the first one.
The method I used (I won't reveal the answer completely here, but the following will certainly make it much easier to guess): just run the function with various inputs. First I discovered it errors unless the argument is not a list (we see it calls car on the arg). So, the first arg to and looks like a base case. While it's clear to me now what it does (easy to say), the only way I was able to discover it was by playing with various inputs. It seemed always to return nil on any input I gave it. That seemed strange. Then I just looked at the line (or  (null (car x)), and it's easy to see how to make that evaluate to true: put a nil as an element of the list. And then the secret was revealed... This seems an interesting function, worth plenty of attention. I do love recursion :)

The second remains mystery for now. Please remember, I'd appreciate discussion to be around method and/or techniques, if anyone would care to chip in. Obviously there's much less value in just revealing the answer.


texts: Express middleware to validate URL and tags

texts:
I am building an API where the client can send a url and some comma-delimited tags:

{
   "url": "https://www.youtube.com/watch?v=pquxHIBx8ks",
   "tags": "JavaScript, Sequelize"
}

Before processing this data, I want to validate the input. To do that, I wrote a middleware function called validateSubmitScreencastReq:

import config from 'config'
import youtubeUrl from 'youtube-url'
import db from 'sequelize-connect'
import * as youtubeClient from '../../source/util/youtubeClient'

async function validateUrl (url) {
  if (!url) {
    return 'url cannot be undefined'
  }

  if (!youtubeUrl.valid(url)) {
    return 'url must be a valid YouTube URL'
  }

  const client = youtubeClient.create(config.youtubeApiKey)
  if (!await client.videoExists(url)) {
    return 'url must link to an existent, public YouTube video'
  }

  const foundScreencast = await db.models.screencast.findOne({
    where: {
      url: url
    }
  })
  if (foundScreencast !== null) {
    return 'url has already been submitted'
  }

  return undefined
}

function validateTags (tags) {
  if (!tags) {
    return 'tags cannot be undefined'
  }

  if (typeof tags !== 'string') {
    return 'tags must be a string'
  }

  return undefined
}

export async function validateSubmitScreencastReq (req, res, next) {
  try {
    const urlError = await validateUrl(req.body.url)
    const tagError = validateTags(req.body.tags)
    const errors = []
    if (urlError) {
      errors.push({
        field: 'url',
        message: urlError
      })
    }
    if (tagError) {
      errors.push({
        field: 'tags',
        message: tagError
      })
    }
    if (errors.length !== 0) {
      res.status(400).json({errors})
    } else {
      next()
    }
  } catch (error) {
    next(error)
  }
}

I'm not too happy with this code.

The function essentially aggregates error messages, which makes me think of using reduce but I can't see how to make it work elegantly.

What's more, I don't think I'm expressing that the function aggregates errors very clearly.

How can I improve the readability the above code, preferably using functional concepts?

(If it's at all useful, here is the validateSubmitScreencastReq function on GitHub and here are the corresponding unit tests.)


texts: Phoenix Ecto schema for internal mailbox

texts:
I am building an application messaging system. I am planning on using channels for real-time notifications but I was wondering if this schema makes sense. I am looking for any constructive criticism and problems that might arise.

message.ex

defmodule Trophus.Message do
  use Trophus.Web, :model

  schema "messages" do
    belongs_to :conversation, Trophus.Conversation
    field :body, :string
    timestamps
  end

  @required_fields ~w(body conversation)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.

  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

conversation.ex

defmodule Trophus.Conversation do
  use Trophus.Web, :model

  schema "conversations" do
    has_many :messages, Message
    belongs_to :initiator, User, foreign_key: :user_id
    belongs_to :receiver, User, foreign_key: :user_id
    timestamps
  end

  @required_fields ~w(initiator receiver)
  @optional_fields ~w(messages)

  @doc """
  Creates a changeset based on the `model` and `params`.

  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end


texts: Vectorizing Two Sample Kolmogorov-Smirnov test

texts:
I'm implementing the Two-sample Kolmogorov-Smirnov test in MATLAB. I must admit I know very little of formal statistics and was simply trying to implement the description in wikipedia's page.

Right now I take as input the two vectors to be compared x1 and x2, and optionally the p-value that the check will run on. It outputs 1 if the vectors pass the test and 0 if they do not.

A couple of questions I have:

  Is there a better way to compute the empirical distribution functions?

Right now I evaluate the empirical distribution function at the points defined in the vector t. In my naive approximation, I made it go from the smallest value of the vectors to the largest, using twice as many points as the vector with the most points. I have no idea is this is the best way to compute it, and suspect the vector doesn't have to be nearly as dense.

  Can I vectorize the search through the t vector?

Right now I have a for loop that goes through every value of tand computes the empirical distribution function in that way. It seems that there might be a way to vectorize this operation further and get rid of the for loop. Haven't figured out a good way to do it however.

And of course, any other suggestions are welcome!

My code is below:

function [OUT] = k_stest(x1,x2,p)

% Set default p-value
    if nargin == 2
        p = 0.05;
    end

% Compute lenghts
    N1 = length(x1);
    N2 = length(x2);

% Set vector t over which the empirical distribution function will be computed.
    t = linspace(min(min([x1 x2])),max(max([x1 x2])),2*max([N1 N2]));

% Initialize the statistic, negative values guarantees it will be overwritten by first call.
    D = -1;

% Set c from tabulated values
    if p == 0.10
        c = 1.22;
    elseif p == 0.05
        c = 1.36;
    elseif p == 0.025
        c = 1.48;
    elseif p == 0.01
        c = 1.63;
    elseif p == 0.005
        c = 1.73;
    elseif p == 0.001
        c = 1.95;
    else
        disp('Invalid p-value. Only p = 0.10 0.05 0.025 0.01 0.005 0.001 are supported')
        return
    end

% Search though the vector t, computing the empirical distribution function for each t,
% and overwriting the statistic if a higher value is found.
    for i = 1:length(t)
        F1 = sum(x1<=t(i))/N1;
        F2 = sum(x2<=t(i))/N2;
        if abs(F2-F1) > D
            D = abs(F2-F1);
        end
    end

% Compare the statistic to determine if the samples pass or fail.
    if D == -1;
       disp('Error, invalid input vectors')
       return
    elseif D > c*sqrt((N1+N2)/(N1*N2));
        OUT = 0;
    else
        OUT = 1;
    end

end


texts: Iterating string characters and passing them to a BIOS API

texts:
Which style of printing strings from the SI registry in NASM is more correct?

I'm learning assembly and x86 architecture, but I'm rather new in it, so I've prepared two styles (in NASM) of printing a string, which is held in the SI register.

For a clear text, the samples are at the bottom of the question content.  I also want you to provide me with some information about the correctness of the code style in ASM. The most significant place in both code for me is the loop for printing a char from the whole string, so I want you to tell me which variant is more correct (or maybe both variants are bad and you can provide me a much better sample).

Both samples don't need an OS and could be run as *.img (floopy image) in virtual machine or with the mkisofs (or similar software) be prepared as *.iso (CD image). In these code samples - I'm working with the BIOS to print the string.

Also, about code style. I don't know which style is more correct in ASM, for e.g. in the 1st variant I'm using the name of the functions like: print_string, but as for the 2nd variant, I'm using the style, which is closer to C# name style PrintCharacter, so which variant of naming is more suitable in ASM language?

To compile in NASM, just use this syntax:

nasm -f bin -o file.img file.asm

The first one (http://pastebin.com/32mDPump):

[BITS 16]

start:
    mov ax, 07C0h
    add ax, 288
    mov ss, ax
    mov sp, 4096
    mov ax, 07C0h
    mov ds, ax
    mov si, text_string
    call print_string
    jmp $

text_string db 'Hello World!', 0

print_string:
    mov ah, 0Eh

.repeat:
    lodsb
    cmp al, 0
    je .done
    int 10h
    jmp .repeat

.done:
    ret

times 510-($-$$) db 0
dw 0xAA55

The second one (http://pastebin.com/FnP0NGTY):

[BITS 16]

mov si, HelloString
call PrintString
jmp $

PrintCharacter:
    mov ah, 0x0E
    mov bh, 0x00
    mov bl, 0x07
    int 0x10
    ret

PrintString:
    next_character:
        mov al, [si]
        inc si
        or al, al
        jz exit_function
        call PrintCharacter
        jmp next_character
    exit_function:
        ret

HelloString db 'Hello World', 0

times 510-($-$$) db 0
dw 0xAA55


texts: Long-term archiving + encrypting shell script

texts:
Yesterday, I very quickly, in an hour, wrote the very first version of my long-term archiving + encrypting shell script.

I am aware it may have too many flaws, but none of them really prevent it from normal operation, so before I take another step and restructure it with printf and better error reporting, structure, exit codes, etc. I would like you to have a look first.

What it does:

It archives a given directory into a tarball.
It compresses (with maximum effort) that tarball using xz.
It encrypts that xz archive using openssl and AES-256.
It creates and checks the created SHA-512 sum file.
It then decrypts the created file to a temporary file.
Finally, it compares the decrypted file with the original xz archive.

I am prepared to waste time and effort in order to be 100% sure before burning my precious data to Blu-ray M-disc.

I know I should not have to do steps 5 and 6 just because there is almost a 0% chance for the data to get corrupted in the process. But since I have a rather large NVMe SSD drive, and relatively fast CPU, it should not be so shocking that I wrote it with motto better safe than sorry.

#!/bin/sh

[ -z "$1" ] && echo "You need to give me one directory!" && exit 1

[ ! -d "$1" ] && echo "This is not a directory!" && exit 1

[ ! -w "$PWD" ] && echo "The current directory is not writable by you!" && exit 1

dir=$(basename "$1")
today=$(date +%Y-%m-%d)

backupdir="${dir}_${today}"
# backupdir="${dir}"

backupfile="${backupdir}.tar"

bold=$(tput bold)
red=$(tput setaf 1)
yellow=$(tput setaf 3)
nocolor=$(tput sgr0)
bold_red="$bold$red"
bold_yellow="$bold$yellow"

echo
echo "${bold_yellow}1/6: TAR is archiving your directory '${bold_red}$dir${bold_yellow}' into '${bold_red}$backupfile${bold_yellow}'${nocolor}"
echo

if ! tar -cf "$backupfile" "$1" --totals
then
    echo "TAR failed to archive your directory"
    exit 1
fi

echo
echo "${bold_yellow}2/6: XZ is compressing your '${bold_red}$backupfile${bold_yellow}' into '${bold_red}$backupfile.xz${bold_yellow}'${nocolor}"
echo

if ! xz --format=xz --check=sha256 -9 --threads=8 --keep --verbose --verbose --extreme "$backupfile"
then
    echo "XZ failed to compress your backup file"
    exit 1
fi

echo
echo "${bold_yellow}3/6: OpenSSL is encrypting your '${bold_red}$backupfile.xz${bold_yellow}' into '${bold_red}$backupfile.xz.enc${bold_yellow}'${nocolor}"
echo

if ! pv -W "$backupfile.xz" | openssl enc -aes-256-cbc -md sha256 -salt -out "$backupfile.xz.enc" -pass file:/home/vlastimil/.blablablabla 2> /dev/null
then
    echo "OpenSSL failed to encrypt your compressed file"
    exit 1
fi

echo
echo "${bold_yellow}4/6: sha512sum is creating hash file '${bold_red}$backupfile.xz.enc.SHA512SUM${bold_yellow}'${nocolor}"
echo

if ! sha512sum -b "$backupfile.xz.enc" > "$backupfile.xz.enc.SHA512SUM"
then
    echo "sha512sum failed to compute hashsum file"
    exit 1
fi

sha512sum -c "$backupfile.xz.enc.SHA512SUM"

echo
echo "${bold_yellow}5/6: Decrypting your '${bold_red}$backupfile.xz.enc${bold_yellow}' into a temporary file '${bold_red}$backupfile.xz.dec${bold_yellow}'${nocolor}"
echo

if ! pv -W "$backupfile.xz.enc" | openssl enc -aes-256-cbc -md sha256 -salt -out "$backupfile.xz.dec" -d -pass file:/home/vlastimil/.blablablabla 2> /dev/null
then
    echo "OpenSSL failed to decrypt your encrypted file"
    exit 1
fi

echo
echo "${bold_yellow}6/6: Comparing your un-encrypted, compressed, archived, directory file '${bold_red}$backupfile.xz${bold_yellow}' with a temporary file '${bold_red}$backupfile.xz.dec${bold_yellow}'${nocolor}"
echo

if ! cmp "$backupfile.xz" "$backupfile.xz.dec"
then
    echo "Failed to compare files"
    exit 1
else
    echo "Your directory '${bold_red}$dir${nocolor}' has been successfully stored as '${bold_red}$backupfile.xz.enc${nocolor}'"
    rm "$backupfile.xz.dec"
    rm "$backupfile.xz"
    rm "$backupfile"
fi


texts:
I have been learning firebase with react js lately and I have stumbled upon a situation where I think my code is somewhat not okay.
  const handleFormSubmit = (e) => {
        e.preventDefault();
        if(props.addOrEdit(values).path.pieces_[0] === "Contacts"){
            setValues(initialFieldValues);
        } else {

        }
  };

The aim here is to validate if I am inserting the data into the right database, and then insert but there are a couple of anomalies here. Please note that I am not calling addOrEdit method anywhere else except for this part.

In the if/else block the code is getting inserted while it should be comparing.
I think what I have written is a patchwork.

The code works as it should but the quality of it merely good enough.
Kindly add your comments on it, how can it be improved in the aspect of validating and inserting the data.


texts: Having two abstract (static inner) classes within the interface they implement

texts:
Is it wrong? Should I have these 2 classes in separate files?

public interface InternetDependentFlow {
    void onInternetIsAvailable();
    void onInternetIsNotAvailable();

    public static abstract class InternetIsAvailable implements InternetDependentFlow {
        @Override
        public final void onInternetIsNotAvailable() {
            // do nothing
        }
    }

    public static abstract class InternetIsNotAvailable implements InternetDependentFlow {
        @Override
        public final void onInternetIsAvailable() {
            // do nothing
        }
    }
}

Where I use this interface and the classes:

public class InternetDependentFlowTask extends AsyncTask<InternetDependentFlow,Void,Boolean> {

    private final Context context;
    private InternetDependentFlow[] internetDependentFlows;

    public static void run(Context context, InternetDependentFlow... internetDependentFlows) {
        InternetDependentFlowTask internetDependentFlowTask = new InternetDependentFlowTask(context);
        internetDependentFlowTask.execute(internetDependentFlows);
    }

    public InternetDependentFlowTask(Context context) {
        this.context = context;
    }

    @Override
    protected Boolean doInBackground(InternetDependentFlow... internetDependentFlows) {
        this.internetDependentFlows = internetDependentFlows;
        return NetworkUtils.isInternetAvailable(context);
    }

    @Override
    protected void onPostExecute(Boolean internetIsAvailable) {
        super.onPostExecute(internetIsAvailable);
        InternetDependentFlowChooser flowChooser = (internetIsAvailable == Boolean.TRUE)
                ? INTERNET_IS_AVAILABLE_FLOW_CHOOSER : INTERNET_IS_NOT_AVAILABLE_FLOW_CHOOSER;
        for (InternetDependentFlow internetDependentFlow : internetDependentFlows) {
            if (internetDependentFlow != null) {
                flowChooser.choose(internetDependentFlow);
            }
        }
    }

    private static interface InternetDependentFlowChooser {
        void choose(InternetDependentFlow internetDependentFlow);
    }

    private static final InternetDependentFlowChooser INTERNET_IS_AVAILABLE_FLOW_CHOOSER = new InternetDependentFlowChooser() {
        @Override
        public void choose(InternetDependentFlow internetDependentFlow) {
            internetDependentFlow.onInternetIsAvailable();
        }
    };

    private static final InternetDependentFlowChooser INTERNET_IS_NOT_AVAILABLE_FLOW_CHOOSER = new InternetDependentFlowChooser() {
        @Override
        public void choose(InternetDependentFlow internetDependentFlow) {
            internetDependentFlow.onInternetIsNotAvailable();
        }
    };
}

And how InternetDependentFlowTask is using:

playButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        MusicManager.playClickBig();
        InternetDependentFlowTask.run(WelcomeActivity.this, new InternetDependentFlow() {
            @Override
            public void onInternetIsAvailable() {
                startGameActivity();
                finish();
            }
            @Override
            public void onInternetIsNotAvailable() {
                notifyUserInternetIsNotAvailable();
            }
        });
    }
});


texts: Diving into PHP's MVC - the application's core

texts:
I recently started programming in php using the mvc-pattern, which resulted in one of best choices, I did so far, but I read through many articles showing "easy" examples and some of them were quite advanced (based on my opinion).

I started learning the pattern by looking up some code and I ended up here: "php-mvc"-repository by panique

I changed some lines of code and my best approach up to this point is this:

<?php

define( 'DEFAULT_CONTROLLER', 'controller' );
define( 'DEFAULT_METHOD', 'index' );

define( 'CONTROLLERS_DIR', './application/controllers/' );

/**
 * Gets $_GET['url'], while assuming it will be used in the sense of MVC,
 * it returns information for the controller.
 *
 * @returns string Returns $_GET['url']
 */
function getUrl()
{
    $url = filter_input( INPUT_GET, 'url', FILTER_SANITIZE_URL );
    return ( isset( $url ) && !empty( $url ) ? $url : ( defined( 'DEFAULT_CONTROLLER' ) ? DEFAULT_CONTROLLER : null ) );
}

class Application
{

    const CONTROLLER_INDEX = 0;
    const METHOD_INDEX = 1;
    const DEFAULT_CONTROLLER = DEFAULT_CONTROLLER;
    const DEFAULT_METHOD = DEFAULT_METHOD;

    public $url;
    public $controller, $method, $params;

    public function __construct()
    {
        $this->getUrl();
        $this->splitUrl();

        $this->getController();
        $this->getMethod();
        $this->getParams();

        $this->loadController();
        $this->callMethod();
    }

    /**
     * Retrieves the controller url
     */
    private function getUrl()
    {
        $this->url = getUrl();
    }

    /**
     * Splits the url for better access
     */
    private function splitUrl()
    {
        $this->url = explode( '/', rtrim( $this->url, '/' ) );
    }

    /**
     * Gets the controller from $this->url
     */
    private function getController()
    {
        $this->controller = $this->url[self::CONTROLLER_INDEX];
        unset( $this->url[self::CONTROLLER_INDEX] );
    }

    /**
     * Gets the method from $this->url
     */
    private function getMethod()
    {
        $this->method = ( isset( $this->url[self::METHOD_INDEX] ) ? $this->url[self::METHOD_INDEX] : self::DEFAULT_METHOD );
        unset( $this->url[self::METHOD_INDEX] );
    }

    /**
     * Gets the parameters from $this->url
     */
    private function getParams()
    {
        $this->params = array_values( $this->url );
        if ( empty( $this->params ) )
        {
            $this->params = NULL;
        }
        unset( $this->url );
    }

    /**
     * Loads the controller
     */
    private function loadController()
    {
        if ( !file_exists( CONTROLLERS_DIR . $this->controller . '.php' ) )
        {
            $this->controller = self::DEFAULT_CONTROLLER;
        }
        $this->controller = new $this->controller();
    }

    /**
     * Calls the method
     */
    private function callMethod()
    {
        if ( !method_exists( $this->controller, $this->method ) )
        {
            $this->method = self::DEFAULT_METHOD;
        }
        $this->controller->{$this->method}( $this->params );
    }

}

Basically, what I wanted to do, is making the code clearer and easily readable, but now I am facing a point, where I got stuck.

I really wanted to share my approach, because I wanted you to share some thoughts about it.
Secondly, when I start a project, I always try writing my own little framework, which I require by using spl_autoload_register and the namespace, and I wanted to implement namespaces in the whole project (as it is possible?).
Are there any advices, you would like to share (based on experience, ...)? For example: references using the mvc-pattern, things definitely worth reading


texts:
In call of Duty warzone, there is a Duos mode (Teams of two). As the game progresses and people are eliminated some teams might have just one player left and some still with two. The game tells you the number of players left and the number of teams. For example, 5 players left, 3 teams left. In this case we can know that this will be two teams of 2, and one team of 1.
Anyway I worked out a formula for calculating the number of teams with 1 or 2 players. below is a short code and some test cases I would appreciate any review / feedback on.
source code
from typing import Tuple

def team_counts(players: int, teams: int) -> Tuple[int, int]:
    if players <= 0 or teams <= 0:
        raise ValueError(f"{players=}, {teams=} - Players and teams must be a positive value")
    if teams > players or teams < players / 2:
        raise ValueError(f"{players=}, {teams=} - Teams must be less than players and greater than or equal to half of players")
    twos = players - teams
    ones = teams - twos
    return ones, twos

Test code
from teams_of_two import team_counts
import pytest

def test_players_teams_positive():
    assert team_counts(players=1, teams=1) == (1, 0)

def test_players_negative_teams_positive():
    with pytest.raises(ValueError):
        team_counts(players=-1, teams=1)

def test_players_positive_teams_negative():
    with pytest.raises(ValueError):
        team_counts(players=1, teams=-1)

def test_players_zero_teams_positive():
    with pytest.raises(ValueError):
        team_counts(players=0, teams=1)

def test_players_positive_teams_zero():
    with pytest.raises(ValueError):
        team_counts(players=1, teams=0)

def test_to_many_teams():
    with pytest.raises(ValueError):
        team_counts(players=1, teams=2)


texts: Incremental Sieve of Eratosthenes using unstable generators

texts:
I am in the process of learning Rust and am still having some issues with borrowing and ownership. I find myself trying to borrow mutable references that are already borrowed as immutable references etc...

I noticed that when I try to iterate over the primes without owning them, I encounter issues trying to modify the composites hash map. I was able to get around this by calling to_owned on the vector. Is this the right way to handle this?

This uses the unstable generator feature.

cargo -V
cargo 1.35.0-nightly (0e35bd8af 2019-03-13)

#![feature(generators, generator_trait)]

use std::collections::HashMap;
use std::ops::{Generator, GeneratorState};

let mut sieve = || {
    let mut x: u32 = 2;
    let mut composites: HashMap<u32, Vec<u32>> = HashMap::new();

    loop {
        match composites.get(&x) {
            Some(primes) => {
                for _prime in primes.to_owned() {
                    composites
                        .entry(x + _prime)
                        .and_modify(|v| v.push(_prime))
                        .or_insert(vec![_prime]);
                    composites.remove(&x);
                }
            }
            None => {
                yield x;
                composites.insert(x * x, vec![x]);
            }
        }

        x = x + 1;
    }
};


texts: Interactive dictionary with inexact lookups (step 1)

texts:
I'm currently building an interactive dictionary. I'm using a sample JSON file (i.e. data.json) as a template. But that's not it. My aim is to build an app where I can store the knowledge that I acquire during my learning process.

And I'd like you to take a look at my code to see if there are areas where I can improve the performance of my program.

Code

import json
from difflib import get_close_matches

data = json.load(open('data.json', 'r'))

def newdict(word, definition):
    data.update({word: [definition]})
    with open('data.json', 'w') as file:
        json.dump(data, file)

def tr(word):
    gcm = get_close_matches(word, data, 1, 0.8)
    if word in data:
        print('· ' + word + ':')
        for index, definition in enumerate(data[word]):
            print(str(index+1) + '.', definition)
    elif word.title() in data:
        print('· ' + word.title() + ':')
        for index, definition in enumerate(data[word.title()]):
            print(str(index + 1) + '.', definition)
    elif word.upper() in data:
        print('· ' + word.upper() + ':')
        for index, definition in enumerate(data[word.upper()]):
            print(str(index + 1) + '.', definition)
    elif len(gcm) > 0:
        print('· ' + gcm[0].capitalize() + ':')
        for index, definition in enumerate(data[gcm[0]]):
                print(str(index+1) + '.', definition)
    else:
        print("'%s' definition isn't available at the moment." % word.capitalize())
        x = input('Would you like to add "%s" to the dictionary? ' % word.capitalize())
        x = x.lower()
        if x == 'yes':
            y = input('Type in the meaning of %s: ' % word)
            newdict(word, y)
        else:
            print('Ok, as you wish!')

w = input('Enter a word: ')
w = w.lower()
while w != '0':
    tr(w)
    w = input('\nEnter a word: ')
    w = w.lower()

Is there room for improvement?


texts:
I decided to write a very simple web-game:

function write_at(x, y, text, color, font) {
  ctx.fillStyle = color || "black";
  ctx.font = font || "50px Arial";
  ctx.fillText(text, x + 50, y + 50);
}

function write_at_random(text, color, font) {
  write_at(random_choice(range(0, canvas.width - 250)),
    random_choice(range(200, canvas.height - 250)),
    text, color, font);
}

function random_choice(array) {
  index = Math.random() * array.length
  return array[Math.floor(index)]
}

function range(start, end) {
  return Array.apply(0, Array(end))
    .map(function(element, index) {
      return index + start;
    });
}

function gen_math_expression() {
  start = random_choice(range(0, 20));
  operator = random_choice(['+', '-', '*']);
  end = random_choice(range(0, 20));
  return start + operator + end;
}

function single_digit(expr) {
  return eval(expr) <= 9 && eval(expr) >= 1
}

function gen_single_digit_expression() {
  expr = gen_math_expression();
  while (!single_digit(expr)) {
    expr = gen_math_expression();
  }
  return expr;
}

function number_from_keycode(keycode) {
  return keycode.which - 48;
}

function draw_welcome_and_score() {
  write_at(0, 0, "Single Digit Math Quiz");
  write_at(600, 0, points);
}

function lose_sound() {
  var snd = new Audio("http://www.soundjay.com/misc/sounds/fail-buzzer-02.mp3");
  snd.play();
}

function win_sound() {
  var snd = new Audio("http://www.soundjay.com/misc/bell-ringing-05.mp3");
  snd.play();
}

function main() {
  canvas = document.getElementById("canvas")
  ctx = canvas.getContext('2d');
  points = 0
  draw_welcome_and_score()
  write_at(0, 100, "Press the result of the operation on your keyboard.", 0, "20px Arial");

  expr = gen_single_digit_expression()
  write_at_random(expr);

  function check_expr_and_go_next(e) {
    if (number_from_keycode(e) == eval(expr)) {
      points++;
      color = '#7CFC00'; // light green
      win_sound()
    } else {
      points--;
      color = 'red';
      lose_sound()
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    canvas.style.background = color;
    draw_welcome_and_score()
    expr = gen_single_digit_expression()
    write_at_random(expr);
  }

  window.addEventListener("keydown", check_expr_and_go_next, true);

}

main()
<html>
<canvas id="canvas" width="800" height="600" style="border:1px solid #000000;">
</canvas>
</html>


texts: Count wins and losses for each team in a league

texts:
Here is the problem.
Repeatedly ask the user to enter game scores in a format like team1 score1 - team2 score2. Store this information in a dictionary where the keys are the team names and the values are tuples of the form (wins, losses).
Here is my Solution, what can I change for the better in it?
number_of_games = int(input("Enter the total number of Games: "))
team_wins_and_loses = {}
for _ in range(number_of_games):
  team1, score1, __, team2, score2 = input("Enter the game results(Note that the name of the team must be a single word, without spaces):").split()
  team1_result, team2_result = ((1, 0), (0, 1)) if int(score1) > int(score2) else ((0, 1), (1, 0))
  if team1 not in team_wins_and_loses:
    team_wins_and_loses[team1] = team1_result
  else:
    updated_result = (team_wins_and_loses[team1][0] + team1_result[0], team_wins_and_loses[team1][1] + team1_result[1])
    team_wins_and_loses[team1] = updated_result

  if team2 not in team_wins_and_loses:
    team_wins_and_loses[team2] = team2_result
  else:
    updated_result = (team_wins_and_loses[team2][0] + team2_result[0], team_wins_and_loses[team2][1] + team2_result[1])
    team_wins_and_loses[team2] = updated_result
  print(team_wins_and_loses)


texts: VBA - If value in sheet1 found in sheet2, then delete data from sheet2

texts:
I have 2 sheets setup: Exclusions and Issues

Issues has a list of CASE ID's and Columns that list the "Issue"

Exclusions will be populated with CASE ID's that are to be excluded (and removed) from the Issues sheet.

My question is 2 fold:

Is my current code handling this correctly? Are there any ways to improve this?
Is there a way to have the code cycle through all columns dynamically? Or is it just easier to copy the FOR/NEXT loop for each column on the "Issues" sheet?

Code below:

Sub Exclusions()

'find exclusions and remove from issues sheet. once done delete any completely blank row

Dim i As Long
Dim k As Long
Dim lastrow As Long
Dim lastrowex As Long
Dim DeleteRow As Long
Dim rng As Range

On Error Resume Next
    Sheets("Issues").ShowAllData
    Sheets("Exclusions").ShowAllData
On Error GoTo 0

Application.ScreenUpdating = False

lastrowex = Sheets("Exclusions").Cells(Rows.Count, "J").End(xlUp).Row

    With ThisWorkbook

        lastrow = Sheets("Issues").Cells(Rows.Count, "A").End(xlUp).Row

    For k = 2 To lastrowex
        For i = 2 To lastrow
            If Sheets("Exclusions").Cells(k, 10).Value <> "" Then
                If Sheets("Exclusions").Cells(k, 10).Value = Sheets("Issues").Cells(i, 1).Value Then
                    Sheets("Issues").Cells(i, 11).ClearContents
                End If
            End If
        Next i
    Next k

    End With

On Error Resume Next
Sheets("Issues").Activate
For Each rng In Range("B2:P" & lastrow).Columns
    rng.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Next rng

Application.ScreenUpdating = True

End Sub

Data Format:

"Issues" sheet

CASE ID      Issue 1     Issue 2    Issue 3
ABC123       No address  No Name    No Number

"Exclusions" sheet

Issue 1    Issue 2    Issue 3
ABC123     DEF123     ABC123


texts:
I think this code looks ugly, especially with the multiple try-catch blocks, but I don't know how to rewrite it:

public String handleFileUpload(@RequestParam String url,@RequestParam String fileName, RedirectAttributes redirectAttributes, HttpServletResponse response) {
        InputStream inputStream;
        try {
             inputStream =  new URL(url).openStream();
        } catch (IOException e) {
            LOG.error("Cannot open stream by url=[{}]", url);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot open stream by url=" + url);
            } catch (IOException e1) {
                LOG.error("Cannot send error");
            }
            return null;
        }
        try {
            File file = File.createTempFile("tmp", ".txt", new File(System.getProperty("user.dir")));
            byte[] binary = IOUtils.toByteArray(inputStream);
            FileUtils.writeByteArrayToFile(file, binary);
            UploadedMultipartFile multipartFile = new UploadedMultipartFile(file, file.length(), "jpg",
                    "formParameter", fileName);
            MultipartFileWrapper multipartFileWrapper = new MultipartFileWrapper();
            multipartFileWrapper.setMultipartFile(multipartFile);
            redirectAttributes.addFlashAttribute(multipartFileWrapper);
        } catch (IOException e) {
            LOG.error("Cannot save file [{}] from [{}]",fileName, url);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot save file " + fileName);
            } catch (IOException e1) {
                LOG.error("Cannot send error");
            }
            return null;
        }
        return "redirect:/member/uploadImage";
    }


texts:
I wanted to get some stats on who has done the most edits on Code Review, so I wrote the following query on SE Data Explorer. All improvement suggestions are welcome.

Note that I used a cursor to partition top users by year because at first there was a fundamental flaw in my logic trying to get the top users overall and then grouping them by years, which gave incorrect results.

The execution plan doesn't look too bad, considering the cursor only iterates a total of 6 times (2011-2016), but if it can be improved without degrading readability too much, I'd like to know.

/*
  Aggregate the top 10 users with the most post edits
  for each year, along with relevant statistics.
*/

/* Filter for Edit events: */
declare @EditPostHistoryTypes table (Id int);
insert into @EditPostHistoryTypes
    select Id
    from PostHistoryTypes
    where Name like 'Edit%';

/* All edits on record: */
declare @CountAllEdits int = (
    select count(Id)
    from PostHistory
    where
      PostHistoryTypeId in (select Id from @EditPostHistoryTypes)
      and PostId in (
          select Id from Posts
          where DeletionDate is null
      )
);
/* Hold top editors per year for main query: */
declare @TopEditorsPerYear table (
    [Year] int,
    UserId int,
    CountByYear int,
    TotalCount int
);
/* Get all years with edit activity: */
declare _years cursor for
    select distinct datepart(year, CreationDate)
    from PostHistory
    where PostHistoryTypeId in (
        select Id
        from PostHistoryTypes
        where Name like 'Edit%'
    );
declare @currentYear int;
/* Cursor to split top editors into yearly partitions: */
open _years;
fetch next from _years into @currentYear;
while @@fetch_status = 0
begin;
    insert into @TopEditorsPerYear ([Year], UserId, CountByYear, TotalCount)
        select top 10
            datepart(year, ph.CreationDate) as [Year],
            ph.UserId,
            count(ph.Id),
            (select count(Id) from PostHistory as phInline where phInline.UserId = ph.UserId)
        from PostHistory as ph
        where PostHistoryTypeId in (
            select Id
            from PostHistoryTypes
            where Name like 'Edit%'
        )
        and datepart(year, CreationDate) = @currentYear
        and UserId is not null
        group by
            datepart(year, CreationDate),
            UserId
        order by count(Id) desc;
    fetch next from _years into @currentYear;
end;
/* Cleanup cursor: */
close _years;
deallocate _years;

/* Main query: */
select
    [Year Rank] = row_number() over (
        partition by tops.[Year]
        order by tops.CountByYear desc
    ),
    [Year] = tops.[Year],
    [User Link] = hist.UserId,
    [Annual Total] = tops.CountByYear,
    [% Year/User] = cast((cast(tops.CountByYear as decimal(10,2)) / tops.TotalCount) * 100 as decimal(5,2)),
    [% Year/Site] = cast((cast(tops.CountByYear as decimal(10,2)) / @CountAllEdits) * 100 as decimal(5,2)),
    [% Total/Site] = cast((cast(tops.TotalCount as decimal(10,2)) / @CountAllEdits) * 100 as decimal(5,2)),
    [Grand Total] = tops.TotalCount
from
    PostHistory as hist
    join @TopEditorsPerYear as tops on hist.UserId = tops.UserId
where
    PostHistoryTypeId in (select Id from @EditPostHistoryTypes)
    and PostId in (select Id from Posts where DeletionDate is null)
group by
    hist.UserId,
    tops.[Year],
    tops.CountByYear,
    tops.TotalCount
order by
    [Year Rank] asc,
    [Year] asc;


texts: My own getline function for reading strings from files

texts:
I am a newbie to C++ and I want to do some cool stuff with it. Here I have implemented my own getline function which reads from a file. so what do you think of this getline function?

#include <iostream>
#include <fstream>
using namespace std;

class Foo {
private:
    char ch;
public:
    void getline(fstream& in, string& word, char delimeter ='\n'){
        word = "";
        while(in.get(ch)){
            word += ch;
            if(ch==delimeter)
                break;
        }
    }
};
int main(){
    Foo one;
    string temp;
    fstream obj("file.txt", ios::in | ios::out | ios::trunc );

    obj<<"this is our$ world";
    obj.seekg(0);
    one.getline(obj, temp,'$');
    cout<<temp<<endl;
}


texts: Aggregate prescriptions per drug in a CSV file

texts:
I have a question that is similar in spirit to this previously asked question. Nonetheless, I can't seem to figure out a suitable solution.

Input: I have CSV data that looks like  (FICTIONAL PATIENT DATA)

id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost
1000000001,Smith,James,AMBIEN,100
1000000002,Garcia,Maria,AMBIEN,200
1000000003,Johnson,James,CHLORPROMAZINE,1000
1000000004,Rodriguez,Maria,CHLORPROMAZINE,2000
1000000005,Smith,David,BENZTROPINE MESYLATE,1500

Output: from this I simply need to output each drug, the total cost which is summed over all prescriptions and I need to get a count of the unique number of prescribers.

drug_name,num_prescriber,total_cost
AMBIEN,2,300.0
CHLORPROMAZINE,2,3000.0
BENZTROPINE MESYLATE,1,1500.0

I was able to accomplish this pretty easily with Python. However, when I try to run my code with a much larger (1gb) input, my code does not terminate in a reasonable amount of time.

import sys, csv

def duplicate_id(id, id_list):
    if id in id_list:
        return True
    else:
        return False

def write_file(d, output):
    path = output
    # path = './output/top_cost_drug.txt'
    with open(path, 'w', newline='') as csvfile:
        fieldnames = ['drug_name', 'num_prescriber', 'total_cost']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for key, value in d.items():
            print(key, value)
            writer.writerow({'drug_name': key, 'num_prescriber': len(value[0]), 'total_cost': sum(value[1])})

def read_file(data):
    # TODO: https://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3
    drug_info = {}
    with open(data) as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        next(readCSV)
        for row in readCSV:
            prescriber_id = row[0]
            prescribed_drug = row[3]
            prescribed_drug_cost = float(row[4])

            if prescribed_drug not in drug_info:
                drug_info[prescribed_drug] = ([prescriber_id], [prescribed_drug_cost])
            else:
                if not duplicate_id(prescriber_id, drug_info[prescribed_drug][0]):
                    drug_info[prescribed_drug][0].append(prescriber_id)
                    drug_info[prescribed_drug][1].append(prescribed_drug_cost)
                else:
                    drug_info[prescribed_drug][1].append(prescribed_drug_cost)
    return(drug_info)

def main():
    data = sys.argv[1]
    output = sys.argv[2]
    drug_info = read_file(data)
    write_file(drug_info, output)

if __name__ == "__main__":
    main()

I am having trouble figuring out how to refactor this to handle the larger input and was hoping someone on CodeReview could take a look and provide me some suggestions for how to solve this problem. Additionally, if you happen to see any other issues, I'd love the feedback.


texts: Is this home page well organized and what can I do to improve performance here?

texts:
My page has been loading a bit slower than I want it to.

The website is www.digitechlab.com

I segregated so many files because they were pretty big and I wanted to be able to work on just one section of that page at a time without running the risk of breaking the entire page. This way I could work on, say, the header on its own.

Here is what I have

<!DOCTYPE html>

  <title>DigiTech Dental Lab - Dental Lab Services- Digital Dental Restorations</title>
  <meta name="keywords" content="dental lab, dentist laboratory, dental restorations, digital dental, dental implants, dental bridges, implant system, implant abutments, Bruxzir, IPS.emax, Prismatik, cad/cam technology" />
  <meta name="description" content="DigiTech dental lab offers CAD/CAM technology and digital dentistry to provide quality dental restorations, crowns and bridges at a competitive price." />
  <meta name="google-site-verification" content="" />
  <meta name="y_key" content="" />
  <meta name="msvalidate.01" content="" />

  <link rel="stylesheet" href="/css/header.css" type="text/css" charset="utf-8" />
  <link rel="stylesheet" href="/css/font-museo500.css" type="text/css" charset="utf-8" />

CAD/CAM Digital Dental Restorations

At DigiTech Dental Restorations, we take great pride in offering you quality products at a competitive price. Our dedicated team uses state-of-the-art CAD/CAM processes and equipment to fabricate each restoration, ensuring each crown or bridge is created with an unsurpassed degree of precision. The DigiTech staff is specially trained in monolithic BruxZir material, and our experience is evident in every BruxZir case you prescribe. From crowns &amp; bridges to Inclusive&reg; Implant Abutments, DigiTech is committed to both dentist and patient satisfaction.

            Schedule a pickup

            888-336-1301


texts: "Spinning wheels" - Animated spinner with SVG and Sass-CSS

texts:
I've made this little animation using SVG, CSS-keyframes and a bit of Sass.

html,
body,
.wrap {
  height: 100%;
}
body {
  background-color: #efefef;
}
svg {
  max-width: 500px;
  width: 100%;
  height: 400px;
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
circle {
  position: absolute;
  fill: transparent;
  stroke-width: 50px;
  stroke-dasharray: 31.5;
  transform-origin: 50% 50%;
}
circle:nth-of-type(1) {
  stroke: #00aadd;
  z-index: 0;
  animation: turn-circle 5s linear infinite;
}
circle:nth-of-type(2) {
  stroke: #00ab02;
  z-index: 1;
  animation: turn-circle 4s linear infinite;
}
circle:nth-of-type(3) {
  stroke: #0053FF;
  z-index: 2;
  animation: turn-circle 3s linear infinite;
}
@keyframes turn-circle {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<div class="wrap">
  <?xml version="1.0" encoding="utf-8" ?>
  <svg version="1.1">
    <circle cx="150" cy="150" r="100" />
    <circle cx="330" cy="150" r="100" />
    <circle cx="240" cy="220" r="100" />
  </svg>
</div>

Here's the uncompiled Sass-code:

$backgroundColor:#efefef;
 $blue:#0053FF;
 $green:#00ab02;
 $cyan:#00aadd;
@mixin setCircle ($i:1,
$color:blue,
$zIndex:0,
$animationDuration:3s) {
  circle: nth-of-type(# {
    $i
  }
  ) {
    stroke: $color;
    z-index: $zIndex;
    animation: turn-circle # {
      $animationDuration
    }
    s linear infinite;
  }
}
html,
body,
.wrap {
  height: 100%;
}
body {
  background-color: $backgroundColor;
}
svg {
  max-width: 500px;
  width: 100%;
  height: 400px;
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
circle {
  position: absolute;
  fill: transparent;
  stroke-width: 50px;
  stroke-dasharray: 31.5;
  transform-origin: 50% 50%;
}
@include setCircle (1,
$cyan,
0,
5);
@include setCircle (2,
$green,
1,
4);
@include setCircle (3,
$blue,
2,
3);
@keyframes turn-circle {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

It works and looks alright but could surely be improved.

Therefore my questions:

Could one improve the movement of the wheels in a way that it looks better? More natural?
How could the responsiveness be improved? Currently my main issue.
Suggestions concerning the design? I'm an amateur in that field.


texts: Best way to toggle a property in an array

texts:
I am runing this function that finds an object in an array and toggles the boolean lead property.
I am actually doing this in react so in there I do change the data via state and in the end if I run it again it would toggle Gary true/false, so it works fine.
My question is regarding the JavaScript code itself, it feels a bit convoluted, is there a better way?

const people = [
  {
    "name": "Olivia",
    "lead": true
  },
  {
    "name": "Gary",
    "lead": false
  },
  {
    "name": "Adam",
    "lead": false
  }
]

const toggleLead = (name) => {

  const values = [...people].map(person =>
    person.name === name
      ? {
          ...person,
          lead: !person.lead
        }
      : { ...person }
  )

  return values
}

console.log(toggleLead('Gary'))
.as-console-wrapper { max-height: 100% !important; top: 0; }


texts:
I'm new to C++ and I'm writting some kind of chat server and client who talk to each other through commands for learning purposes. I serialize and deserialize these commands using a JSON library. My first approach has been to create a base class called Command and have a derived class for each command.

The use case would be to be able to directly create objects of the derived classes on the client and to call a deserialize function that will return an object of the derived class on the server. I have something like this.

enum class Commands {
    NAME = 0,
    QUIT,
    WHISPER,
    JOIN,
    CREATE,
    UNKNOWN
};

class Command {
    protected:
        Commands command;
    public:
        Commands getCommandType();
        virtual Message serialize();
        static Command* deserialize(Message message);
};

I thought it would be better to leave command private and make the Command constructor initialize that value and then for every derived class, have it call the "super" constructor. But I don't know if this is a good approach in C++.
I serialize the enum too because each command will have a different number of fields when serialized. For the implementation of deserialize I have this:

Command* Command::deserialize(Message message) {
    auto parsed_message = json::parse(message);
    if (parsed_message["type"] != "command") {
        throw "Unexpected message";
    }

    //Insert every command.
    if (parsed_message["command"] == Commands::QUIT) {
        return QuitCommand::deserialize(message);
    }
    if (parsed_message["command"] == Commands::NAME) {
        return NameCommand::deserialize(message);
    }
    if (parsed_message["command"] == Commands::WHISPER) {
        return WhisperCommand::deserialize(message);
    }

    throw "Unknown command";
}

And then as an example for a deserialize method:

NameCommand* NameCommand::deserialize(Message message) {
    auto parsed_message = json::parse(message);

    if (parsed_message["type"] == "command" && parsed_message["command"] == Commands::NAME) {
        return new NameCommand(parsed_message["name"]);
    } else {
        throw "NAME command not valid";
    }
}

Now, the code right now works (or at least it seems like it does), but I don't see how it is maintainable or well structued. Could anyone please give me their opinion of the code?


texts: Using a Generic Value Object in a DDD application

texts:
I am writing this question in the context of a DDD application.  I found this code online on a number of blogs etc e.g. here  and here.

public abstract class ValueObject<T>
         where T : ValueObject<T>
     {
        protected abstract IEnumerable<object> GetEqualityComponents();

         public override bool Equals(object obj)
       {
            var valueObject = obj as T;

             if (ReferenceEquals(valueObject, null))
                return false;

            return EqualsCore(valueObject);
       }

         private bool EqualsCore(ValueObject<T> other)
         {
             return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
         }

         public override int GetHashCode()
         {
             return GetEqualityComponents()
                 .Aggregate(1, (current, obj) => current * 23 + (obj?.GetHashCode() ?? 0));
         }

         public static bool operator ==(ValueObject<T> a, ValueObject<T> b)
        {
             if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
                 return true;

             if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
                 return false;

             return a.Equals(b);
         }

         public static bool operator !=(ValueObject<T> a, ValueObject<T> b)
         {
             return !(a == b);
         }
     }
 }

Every Value Object in my application inherits from it.  It means the methods like: Equals and GetHashCode are dealt with implicitly.  The main problem I see arises if I want to add a collection e.g. array as a member of a Value Object - in this scenario the generic value object .Equals will not behave as expected as it cannot deal with collections.

Therefore:

Can this class be tweaked to deal with collections?
Are there any other downfalls with this approach?
Is it advisable not to use a generic value class when developing a DDD application?


texts: Find consecutive numbers and turn them into ranges

texts:
I have array

int[] arr = { -2, 0, 1, 2, 3, 4, 5, 8, 9, 11, 13, 15, 18, 22, 25, 28, 29, 30 };

I need to write function that shows it as string and if numbers are near, for example 1,2,3,4,5 - I need to show them 1-5.

I wrote this function in repository

public string[] GetArray()
{
    int[] arr = { -2, 0, 1, 2, 3, 4, 5, 8, 9, 11, 13, 15, 18, 22, 25, 28, 29, 30 };

    int? lastValue = arr.FirstOrDefault();

    var groupDataIntoAdjacentBlocks = arr.Segment(i =>
    {
        var result = lastValue != null && (lastValue != (i - 1));
        lastValue = i;
        return result;
    }
    );

    var convertSetsIntoRanges = groupDataIntoAdjacentBlocks.Select(z =>
    {
        var data = z.ToList();
        if (data.Count() == 1)
            return data.First().ToString();

        return data.First().ToString() + "-" + data.Last().ToString();
    });

    var finalresult = (string.Join(",", convertSetsIntoRanges));
    return new[] { finalresult };

}

And call it like this in controller

public JsonResult GetArray()
{
    var arrayresult = _arrayrepo.GetArray();
    return Json(arrayresult, JsonRequestBehavior.AllowGet);
}

Any suggestions how I can improve my code?


texts: JSON flattening with object duplication on array property for CSV generation

texts:
I am looking for a way to transform JSON data into a flat "csv-like" data object.  In some way, I am looking to "sqlirize" a mongodb collection. I have already check some json flat libraries in NPM but non of them quite solve my problem. I have solved it in my own way but wanted to know if there is a more efficient way.

I have a collection that presents the data through an API in the following way:

[{
    "data": {
        "name": "John",
        "age": 23,
        "friends": [{
            "name": "Arya",
            "age": 18,
            "gender": "female"
        }, {
            "name": "Sansa",
            "age": 20,
            "gender": "female"
        }, {
            "name": "Bran",
            "age": 17,
            "gender": "male"
        }]
    }
}, {
    "data": {
        "name": "Daenerys",
        "age": 24,
        "friends": [{
            "name": "Grey Worm",
            "age": 20,
            "gender": "male"
        }, {
            "name": "Missandei",
            "age": 17,
            "gender": "female"
        }]
    }
}]

This is the function that I have created to reflat a safe-flattened json (e.i.: everything is flattened except arrays)

const { cloneDeep } = require('lodash')
const flatten = require('flat')

const reflatten = (items) => {
  const reflatted = []

  items.forEach(item => {
    let array = false

    for (const key of Object.keys(item)) {
      if (Array.isArray(item[key])) {
        array = true

        const children = Array(item[key].length).fill().map(() => cloneDeep(item))

        for (let i = 0; i < children.length; i++) {
          const keys = Object.keys(children[i][key][i])

          keys.forEach(k => {
            children[i][`${key}.${k}`] = children[i][key][i][k]
          })
          delete children[i][key]
          reflatted.push(children[i])
        }
        break
      }
    }
    if (!array) {
      reflatted.push(item)
    }
  })

  return reflatted.length === items.length
    ? reflatted
    : reflatten(reflatted)
}

const rows = []

for (const item of items) {
  const flat = [flatten(item)]

  rows.push(...reflatten(flat)]
}

console.log(rows)

The expected (and current) output is the following:

[{
    "data.name": "John",
    "data.age": 23,
    "data.friends.name": "Arya",
    "data.friends.age": 18,
    "data.friends.gender": "female"
}, {
    "data.name": "John",
    "data.age": 23,
    "data.friends.name": "Sansa",
    "data.friends.age": 20,
    "data.friends.gender": "female"
}, {
    "data.name": "John",
    "data.age": 23,
    "data.friends.name": "Bran",
    "data.friends.age": 17,
    "data.friends.gender": "male"
}, {
    "data.name": "Daenerys",
    "data.age": 24,
    "data.friends.name": "Grey Worm",
    "data.friends.age": 20,
    "data.friends.gender": "male"
}, {
    "data.name": "Daenerys",
    "data.age": 24,
    "data.friends.name": "Missandei",
    "data.friends.age": 17,
    "data.friends.gender": "female"
}]

Although I achieved the expected output, I keep wondering if there are other libraries there or if there is a more efficient way of doing it.


texts:
I am doing this Codility problem

  You are given N counters, initially set to 0, and you have two possible operations on them:

  increase(X) − counter X is increased by 1,
  max counter − all counters are set to the maximum value of any counter.

  A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:

  if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
  if A[K] = N + 1 then operation K is max counter.

I have ended up with this code -

def solution(N, array):
    counters = [0]*N
    maximum = 0
    for a in array: # O(m) as array has m integers
        if a >=1 and a <= N:
            counters[a-1] += 1
            maximum = max(counters[a-1], maximum)
        if a == N+1:
            counters = [maximum]*N
    return counters

I am failing two test cases because of timeout errors. I timed the function with array as [10]*100000 and \$N\$ as 9. It took 0.175681062359 seconds which is clearly not desirable. I do not understand where the time complexity increases. The for loop has \$O(M)\$ complexity because array has \$M\$ elements and even though max() has \$O(n)\$ complexity, that doesn't matter since I'm comparing just two elements. I looked at a solution by Andrei Simionescu and it looks awfully similar to mine -

def solution(n, arr):
    out = [0] * n
    m = 0
    last = 0
    for op in arr:
        op -= 1
        if op == n:
            last = m
            continue
        out[op] = max(out[op], last) + 1
        m = max(m, out[op])
    for i in xrange(n):
        out[i] = max(out[i], last)
    return out

I timed the above code and it took just 0.0276817503901 seconds on the same input. What is it that I'm doing wrong?


texts:
I was annoyed to manually start new projects each time so I made a Node CLI that automate the process. I'm really not comfortable yet with node, so I wanted some advice. It works but I don't know if I did it the node way or not.

Basically the code under here is my whole application. The file structure is like so:

- app.js
- seed

It's not really complicated. What I do in the app is copy the seed and change the project name in package.json. The seed is a template project, with nothing in it beside a starter-repo. I could have upload it to git but this is more fun.

#!/usr/bin/env node

const spawn = require('child_process').spawn;
const fs = require("fs");
const path = require('path');
const through2 = require('through2');
const copydir = require('copy-dir');

const name = process.argv[2] || "unnamed project";
const projPath = path.join(process.cwd(), name);
// path to my seed project
const seed = path.join(__dirname, "seed");

if (!fs.existsSync(name)) {
    fs.mkdirSync(name);
} else {
    throw new Error(`directory ${name} already exist`);
}

copydir(seed, path.join(process.cwd(), name), function(err) {
    if (err) {
        console.log(err);
        process.exit(1);
    }
    const package = path.join(projPath, "package.json");
    // in my seed project package.json, I have name: "-your-app-name-here-"
    replaceInFile(package, "-your-app-name-here-", name, onCopyDone);
});

function onCopyDone(err) {
    if (!err)
        install(projPath)
    else
        console.log(err)
}

function replaceInFile(someFile, rep, by, cb) {
    fs.readFile(someFile, 'utf8', function(err, data) {
        if (err) {
            return console.log(err);
        }
        let result = data.replace(rep, by);

        fs.writeFile(someFile, result, 'utf8', cb);
    });
}

function install(where) {
    console.log('installing dependencies...')
    const i = spawn('npm', ['install', '--prefix', where]);

    i.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });
}

Primarily what I'd like to know is how I can do it more the Node way, if that makes sense.


texts: Make the tree from a database into a tree of Java

texts:
There is a task to get the data from the database (tree) and translate them into Java. They must maintain their properties (each entry has parent and descendants).

I'm taking data from database using Statement and ResultSet. The output is an arraylist of RowNode:

public class RawNode {
    int id;
    int parentId;
    String text;
//getters&setters here
}

Now we need to convert this array into the likeness of a tree.

How I do it:

public  List<Node> makeNewTree(ArrayList<RawNode> _rawNode) {
    List<Node> nodes = new ArrayList<>(_rawNode.size());
    Map<Node, RawNode> rawNodesByNodes = new HashMap<>(_rawNode.size()+10, 0.98f);
    Map<Integer, Node> nodesById = new HashMap<>(_rawNode.size()+10, 0.98f);

    try {
        for (RawNode rawNode : _rawNode) {
            Node node = new Node();
            node.setId(rawNode.getId());
            node.setText(rawNode.getText());
            rawNodesByNodes.put(node, rawNode);
            nodesById.put(rawNode.getId(), node);
            nodes.add(node);
        }

        for (Node node : nodes) {
            RawNode rawNode = rawNodesByNodes.get(node);
            Integer parentId = rawNode.getParentId();

            if (parentId == null) {
                node.setParent(null);
            } else {
                Node parent = nodesById.get(parentId);
                node.setParent(parent);
            }
        }

        for (Node node : nodes) {
            Node parentNode = node.getParent();
            if (parentNode == null) {
                continue;
            }
            parentNode.addChild(node);
        }
    } catch (Exception ex) {...}
    return nodes;
}

Where Node is:

  public class Node {
    private int id;
    private Node parent;
    private String text;
    private List<Node> children = new ArrayList<>();
}

Isn't that code redundant? Is there a more elegant solution?


texts:
I'm in the process of reviewing some old code released by an old colleague.
We have a cronjob that executes once in an hour to download some thumbnails: the paths to the thumbnails are stored in a plain array.
// $totalThumbs is usually less than 2000 (each about 3kb)
while ($i < $totalThumbs) {

  $imgName = basename($thumbs_array[$i]);

  $fgc = file_get_contents($thumbs_array[$i]);

  $currentFile = __DIR__ . "/" . $imgName;

  // if file_get_contents doesn't return false
  if ($fgc !== false) {

    // if the file is not in that directory, write the file
    if (!file_exists($currentFile)) {

      file_put_contents($currentFile, $fgc);
      clearstatcache(true, $currentFile);

    }

  }

  $i++;

  sleep(1);
}

This code works but, for example, we can't use CURL multi_exec because of the limited resources of our server.
Is there a way to improve it (more efficient and/or more secure), considering our hardware limits? We don't need speed, but eventually less memory consumption because the same server is at the same time busy with many other 'jobs'.
Thanks
EDIT (for Mast): one important thing to say is the current idea is to remove this part and use a cronjob to directly store an array in a file, so that the file we are talking about has only to read that array
$dir = "https://mylocaldir";
$thumbs_array = [];

// this one returns JSONP
$raw_json = 'https://endpoint';
$json = file_get_contents($raw_json);

// JSONP removal
$json = str_replace("jsonOutreachFeed(", "", $json);
$json = substr($json, 0, -1);

$decoded_json = json_decode($json);

$itm = $decoded_json->items;

$totalThumbs = count($itm);

for ($i = 0; $i < $totalThumbs; $i++) {
  $thumbs_array[] = $itm[$i]->media->m;
}


texts:
I have been refactoring a lot of my old code lately, and with that I have been switching from sqlite3 to mysql using PDO - sqlite3 has something called "querysingle" that allows you to return single responses (as a row or a single value) from a database table.

Anyways, I really liked the simplicity of this and that it all fits in 1 line of code and (IMO) doesn't harm the readability of the code.

I wrote a function in PHP that does a similar thing, but I wanted to make sure that I wasn't missing any edge cases, or see if I could improve the function in any way.

Here is my function:

function pdoQuerySingle($con, $query, $values = array(), $single = false) {
    if($values) {
        $stmt = $con->prepare($query);
        $stmt->execute($values);
    } else {
        $stmt = $con->query($query);
    }
    if($single) return $stmt->fetch()[$single];
    return $stmt->fetch();
}

You use it as follows:

$variable = pdoQuerySingle($pdo, "SELECT * FROM table WHERE id=?", [$id]);

As you can see this query works with prepared statements for security against SQL injection, though you can leave the 3rd param empty if you aren't passing any values to the query. The 4th parameter can be used to return only a specific entry from the query return as a string so if you wanted $variable to be set to a string from a column in the database, let's say, "name" you would do

$variable = pdoQuerySingle($pdo, "SELECT name FROM table WHERE id=?", [$id], "name");


texts: Given a set of points and pairs of lines, count the number of points that are between the pairs of lines

texts:
This is a contest problem. The entire description is here.
In resume:
The question gives a point simulating a light explosion that always has a negative x coordinate, a set of pairs line segments on the y axis are given simulating walls and a set of points with positive x coordinate representing possible positions for a soldier.
The walls block  the light forming a cone with low profile. So, in how many of the given points its possible for the soldier stay in low profile? (A point that stays exactly in the cone line is not valid)
Here is a image describing what I want to say:
The points g3 and g1 are not valid.

The input description:

The first line contains an integer T (T = 100) indicating the number of test cases.
In the first line of each case there will be the coordinate (x, y) of the explosion epicenter. The next line will contain an integer P (1 ≤ P), indicating the number of walls. The next P lines there will be pairs of integers indicating the position of the walls, the start and end of a wall (remember that they stay in the Y axis, it is, X = 0). Then there will be an integer G (G ≤ 10^4) indicating the points that are candidates to a hide place. Then G lines will follow with pairs of coordinates (x, y) indicating their coordinates.
All the coordinates will be between -10^4 and 10^4 and will be integers. The epicenter of the explosion will have X < 0 and the hides positions X > 0. The initial Y of a wall will be strictly less than its end. The walls will not be sorted. The walls won't overlap each other, nor share endpoints. There might be some repeated Goemon positions.

My solution test for each point if it is inside of the cone formed by a wall (if the point is above one line and below other line).
The problem is that this solution is too slow, resulting in time limit exceeded. How can I optimize it?
#include <stdio.h>
#include <algorithm>
using namespace std;

typedef struct _point{
    int x,y;
    _point():x(0),y(0){}
    _point(int _x,int _y):x(_x),y(_y){}
}point_t;

typedef struct _line{
    point_t p1,p2;
    _line() : p1(0,0),p2(0,0){}
    _line(int y1,int y2) : p1(0,y1),p2(0,y2){}
}line_t;

inline int cross(point_t &a, point_t &b,point_t &c){
    return (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x);
}

inline bool hasSameSign(int a,int b){
    return (a<0) == (b<0);
}

int main(void){
    int t;
    scanf("%d",&t);

    for (int i = 0,p,g,valid; i < t; ++i) {
        //read explosion coords
        int x,y;
        scanf("%d %d",&x,&y);
        point_t exps(x,y);

        //read initial and end points for each wall
        scanf("%d",&p);
        line_t *wall = new line_t[p];
        for (int j = 0; j < p; ++j)
            scanf("%d %d",&wall[j].p1.y,&wall[j].p2.y);

        //read all possible positions
        scanf("%d",&g);
        point_t *pos = new point_t[g];
        for (int j = 0; j < g; ++j)
           scanf("%d %d",&pos[j].x,&pos[j].y);

        //for each possible position and walls
        valid = 0;
        for (int k = 0; k < g; ++k) {
            for (int j = 0,signal1,signal2; j < p; ++j) {
                signal1 = cross(exps,wall[j].p1,pos[k]);
                signal2 = cross(exps,wall[j].p2,pos[k]);

                if(!hasSameSign(signal1, signal2)){
                    ++valid;
                    break;
                }

                //printf("%d %d\n",sinal1,sinal2);
            }
        }

        printf("%d\n",valid);
        delete [] wall;
        delete [] pos;
    }
}


texts: Need Loops for PHP Username/Pass Encryption Script

texts:
I've created this PHP script to print a batch of usernames with encrypted passwords locally on my computer because the user/pass format is always the same.

username = username
password = username + "admin"
example = homer / homeradmin

Then paste them into two different .htpasswd file and upload to an public Apache server to password-protect a directory and a directory within it.
Is there a better way to write the code below?
<?php
// Password to be encrypted for a .htpasswd file
$user1 = 'admin';
$user2 = 'g';
$user3 = 'homer';
$user4 = 'marge';
$user5 = 'bart';
$user6 = 'lisa';
$user7 = 'maggie';
$user8 = 'dog';

//Admin
$admin1 = 'admin';
$admin2 = '23!bseEsF@';
$admin3 = 'homeradmin';
$admin4 = 'margeadmin';
$admin5 = 'bartadmin';
$admin6 = 'lisaadmin';
$admin7 = 'maggieadmin';
$admin8 = 'dogadmin';

// Encrypt password
$pass1 = crypt($user1, base64_encode($user1));
$pass2 = crypt($user2, base64_encode($user2));
$pass3 = crypt($user3, base64_encode($user3));
$pass4 = crypt($user4, base64_encode($user4));
$pass5 = crypt($user5, base64_encode($user5));
$pass6 = crypt($user6, base64_encode($user6));
$pass7 = crypt($user7, base64_encode($user7));
$pass8 = crypt($user8, base64_encode($user8));

$adminpass1 = crypt($admin1, base64_encode($admin1));
$adminpass2 = crypt($admin2, base64_encode($admin2));
$adminpass3 = crypt($admin3, base64_encode($admin3));
$adminpass4 = crypt($admin4, base64_encode($admin4));
$adminpass5 = crypt($admin5, base64_encode($admin5));
$adminpass6 = crypt($admin6, base64_encode($admin6));
$adminpass7 = crypt($admin7, base64_encode($admin7));
$adminpass8 = crypt($admin8, base64_encode($admin8));
?>

<!doctype html>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Encrypt</title>
  <meta name="viewport" content="width=device-width">

<?php
// Print encrypted password
echo $user1 . ":" . $pass1 . "
";
echo $user2 . ":" . $pass2 . "
";
echo $user3 . ":" . $pass3 . "
";
echo $user4 . ":" . $pass4 . "
";
echo $user5 . ":" . $pass5 . "
";
echo $user6 . ":" . $pass6 . "
";
echo $user7 . ":" . $pass7 . "
";
echo $user8 . ":" . $pass8 . "
";
?>

<?php
echo $admin1 . ":" . $adminpass1 . "
";
echo $admin2 . ":" . $adminpass2 . "
";
echo $admin3 . ":" . $adminpass3 . "
";
echo $admin4 . ":" . $adminpass4 . "
";
echo $admin5 . ":" . $adminpass5 . "
";
echo $admin6 . ":" . $adminpass6 . "
";
echo $admin7 . ":" . $adminpass7 . "
";
echo $admin8 . ":" . $adminpass8 . "
";
?>


texts:
I just started learning recursion and memoization, so I decided to give a simple implementation a shot. Works with some simple test cases I came up with. Is there anything I can add to make this more interesting? I'm not sure if I can update the return type with generics somehow depending on the input "n" for long, BigInteger, etc.

public static int fibonacci(int n) {
    if (n < 0) throw new IllegalArgumentException("n must be non-negative.");
    if (n == 0) return 0;
    if (n == 1) return 1;
    // if n >= 2
    Map<Integer, Integer> hm = new HashMap<Integer, Integer>(); // cache
    hm.put(0, 0);
    hm.put(1, 1);
    return fibHelper(n-1, hm) + fibHelper(n-2, hm);
}

static int fibHelper(int n, Map<Integer, Integer> hm) {
    if (hm.containsKey(n)) return hm.get(n);
    int fn = fibHelper(n-1, hm) + fibHelper(n-2, hm); // fn = fib of n
    hm.put(n, fn);
    return fn;
}


texts: Clumsy PHP5 code reading from an SQLite3 database

texts:
Some time ago I wrote myself a simple blog. The index page is generated
with PHP5, using an SQLite3 database via the variable id handed to it via
the URL.

The SQLite database contains a table called pages. The id refers of course
to the id intergers in this table. Other columns are title, body, time and
timezone.

The title and body are text as you'd expect, the timezone is usually
"Asia/Tokyo", and the time is seconds from the epoch (I just use date +%s,
when I add an entry, nothing fancy).

I use the following code to get these variables from a table, and fill in
a generic page with them.

<?php
    // Open the database.
    $db = new PDO("sqlite:pagesdatabase.db");
    // Is id set? If not get id of last page and put it in $id.
    if (!isset($_GET["id"])) {
        foreach ($db->query("select max(id) from pages") as $lastid) {
            $id = $lastid[0];
        }
    }
    // If id is set, get the value and put it in $id.
    else {
        $id = $_GET['id'];
    }
    // Using the id number, grab the title, body, time and timezone of post.
    foreach ($db->query("select * from pages where id = $id") as $page) {
        $title = $page['title'];
        $body = $page['body'];
        $time = $page['time'];
        date_default_timezone_set($page['timezone']);
    }
?>

This code works, but seems rather clumsy to me. For example, foreach
appears twice, but shouldn't be necessary. To be honest, it's been a while
since I wrote this code, and for some reason I had trouble using sqlite_open
and other more obvious functions. Can someone help me write the above in a more
terse way?


texts:
Follow-up from this question using @Toby Speight's answer:

The primary concern is jq improvement/optimization, but please detail any others.
#!/bin/sh

set -eu

sources=$(mktemp)
trap 'rm "$sources"' EXIT

curl -s -o "$sources" https://raw.githubusercontent.com/T145/packages/master/net/adblock/files/adblock.sources

for key in $(jq -r 'keys[]' "$sources")
do
    case $key in
        gaming | oisd_basic )
        # Ignore these lists
        ;;
        * )
            url=$(jq -r ".$key.url" "$sources")
            rule=$(jq -r ".$key.rule" "$sources")

            curl -s "$url" |
                case $url in
                    *.tar.gz) tar -xOzf - ;;
                    *) cat ;;
                esac |
                gawk --sandbox -- "$rule"
    esac
done |
    sed -e 's/\r//g' -e 's/^/0.0.0.0 /' | sort -u > the_blacklist.txt
# use sort over gawk to merge sort multiple temp files instead of using up limited memory


texts:
I have a string that contains a random order of parenthesis {[()]}. I want to check if for any given parenthesis is there a matching closing one.

Example:

 }}}{{{ //true
 {[]    //false
 {[()]} //true

private static bool checkIfWellFormatted(string inputString)
{

    if (string.IsNullOrEmpty(inputString))
        throw new ArgumentException("String is empty");
    if ((inputString.Length % 2) != 0)
        return false;

    Dictionary<char, int> _inputDictionary = new Dictionary<char, int>();

    foreach (Char c in inputString)
    {
        if (!_inputDictionary.ContainsKey(c))
            _inputDictionary.Add(c, 0);
        else
            _inputDictionary[c] += 1;

    }

    foreach (var item in _inputDictionary)
    {
        char oppKey = '\0';
        if (item.Key == '{')
            oppKey = '}';
        if (item.Key == '}')
            oppKey = '{';

        if (item.Key == '(')
            oppKey = ')';
        if (item.Key == ')')
            oppKey = '(';

        if (item.Key == '[')
            oppKey = ']';
        if (item.Key == ']')
            oppKey = '[';

        if (_inputDictionary.ContainsKey(oppKey))
        {
            var value = _inputDictionary[oppKey];
            if (value != item.Value)
                return false;

        }
        else
            return false;

    }

    return true;
}

Here, the second iteration over the dictionary has \$O(n)\$ complexity. Can I improve its time complexity?


texts: Design for C++ class methods taking input from different sources

texts:
I have a class foo that needs to get input from different sources, namely input streams,
arrays and iterators. The code that actually does the work in the end takes iterators as
input, and all the other methods end up calling it behind the scenes:

void from_stream(std::istream& in); // Read from stream and insert at end
void from_stream(std::istream& in, iterator it); // Read from stream and insert at it

template<typename T>
void from_buffer(T* buffer, size_t len); // Read from a buffer and insert at end
template<typename T>
void from_buffer(T* buffer, size_t len, iterator it); // Read from a buffer and insert at it

// The work is done here
template<typename InputIterator>
void decode(InputIterator first, InputIterator last); // Decode range and insert at end
template<typename InputIterator>
void decode(InputIterator first, InputIterator last, iterator it); // Decode range and insert at it

I want users to be able to make calls like these (assume foo class is initially empty):

Foo foo;
foo.from_stream(my_stream, foo.begin()); // or without foo.begin()
foo.from_buffer(my_buffer, buflen, foo.begin() + 4); // same...

and internally the code will call specialized std::inserter, std::front_inserter
or std::back_inserter functions as appropriate and pass them to foo::decode. I could just use
std::inserter all the time, but I would think it is more efficient to use std::back_inserter
when foo.end() is passed and so on.

I could change the iterator argument to a template parameter and let the user decide
what kind of iterator to use similar to the STL (which is actually what I am trying to aim for). This would also allow the user to pass a foo::iterator and overwrite content instead of inserting data. This would change the calls above to:

foo.from_stream(my_stream, std::back_inserter(foo));
foo.from_buffer(my_buffer, buflen, std::inserter(foo, foo.begin() + 4));

I could use some design advice about what approach, or another one entirely, is "best".


texts: Ajax request URL with the Google Maps API

texts:
I am making an HTTP request with the Google Maps API and I have to pass in parameters (adresses/coordinates):

 $.ajax({
        url : 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + $("#origin").val() + '&destinations=' + $("#destinations").val() +'&mode=driving&key=AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0',
        type: 'GET',
        success : function(data){
        //My code
        }
    });

I was wondering if there was any better cleaner way to do this. I know string concatenation is an option, but I want to know if I have any other options. I just feel like I'm doing this wrong.


texts: Angular directive to fetch resources to fill a table

texts:
I created a directive that solves my immediate problem, but I'm trying to find ways to make it more reusable.

My immediate problem was, I have a table and needed to fill in one of the columns with data from an http request. I passed an object (dir.provider.resource) and a string (attr) into the directive, made a GET request with its href, and then displayed the value gotten from resource[attr].

HTML:

  <get-resource-property passedResource="dir.provider.resource" attr="status"></get-resource-property>

Directive:

angular.module('myApp')
  .directive('getResourceProperty', function ($http) {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        passedResource: '=',
        attr: '='
      },
      template: '{{result}}	',
      link: function postLink(scope, element) {
        var resource = scope.passedResource;
        var attr = scope.attr;

        if (resource) {
          http.get(resource.href)
           .then(function (resource) {
              setScope(resource);
          });
        }

        function setScope(resource) {
          scope.result = resource[attr];
          if (attr === 'status') {
             //do specific stuff with the status here
             var color = resource[attr] === 'ON' : 'green' ? 'red';
             element.css("color", color);
          }
        };
      }
    }
  });

It would be really useful to make this more reusable, as I have to work with a lot of nested resources in my project. Take the example below:

{
  href: "httsp://site.com/resource/12345",
  otherResource: {
     href: "https://site.com/other-resource/678910"
  },
  relatedResource: {
     href: "https://site.com/resource/12345/related-resource/"
  },
  ...
}

If I want to access a property in relatedResource, I have to make a GET request before I can do so. Sometimes I just need to get one value (like in the above example, I just need to get a nested resource's status), so I can see this being useful in these types of cases..

Am I thinking about this right, or am I missing something obvious? Does anything stand out from the code that looks off? (I am new to angular, so any tips would be great!)


texts: Resizing table widths and making input fields

texts:
I am trying to simplify my code, which will do several things:

Give the same width to every columns no matter how many columns the table has.
Add input field if there is no text inside a td
Make sure the input field is no wider than its table cell
Make sure, if the input field has size attribute, the input field size will increase based on the size attribute
If the table width is too narrow, increase if necessary

My HTML structure:

          cell 1

          <input size='18'/>

          cell 3

          cell 4

          <input size='15'/>

          <input size='15'/>

jQuery:

$(".test td").each(function(){
        columns = $(this).parent().find('td').length;
        inputField= $(this).find('input')
        tdWidth= $(this).width() - 35;
        inputSize = $(this).find('input').attr('size');
        span = $(this).find('span');
        oldTableWdith = $(this).closest('table').attr('width');

        if($.trim($(span).html()) == '&nbsp;'){
            $(span).html("<input type='text' style='width:" + tdWidth + "px;'></input>");
        }

        inputWidth = inputSize * 11;
        inputField.css('width',inputWidth);

        if(tableWidth < (columns * inputWidth + 50)){
            tableWidth = columns * inputWidth + 50;
        }
        if(tableWidth===0){
            tableWidth = oldTableWdith
        }
        $(this).closest('table').width(tableWidth);
    })

The code works, but I feel like I can greatly reduce it and achieve what I need.
I also need the span tag because I need them to do some other functions. Can anyone help me simplify the code?


texts:
I have created a simple function to determine if a container contains a value. It allows for certain conditions to be set as well: where to to start searching for value, which way to search, whether to find the first or the last occurrence of the value, and whether or not to include the starting point. I want its return value to be either the index of the matching element, or -1 if no matches were found.

template<class Container, class T>
int Vec_Find(const Container& c, int size, const T& val, int pivot_idx = 0,
             bool find_first = true, bool ltr = true, bool include_pivot = true)
{
    if (find_first && ltr)
    {
        if (include_pivot) pivot_idx++;
        int i = std::distance(std::begin(c),
                    std::find(std::begin(c) + pivot_idx, std::end(c), val));
        if (i != size) return i;
    }
    else if (find_first && !ltr)
    {
        if (!include_pivot) pivot_idx--;
        int i = std::distance(std::find(std::rbegin(c) + (size - pivot_idx - 1),
                                        std::rend(c), val), std::rend(c) - 1);
        if (i != -1) return i;
    }
    else if (!find_first && ltr)
    {
        if (include_pivot && (c[pivot_idx] == val)) return pivot_idx;
        int i = std::distance(std::find(std::rbegin(c),
                            std::rend(c) - (pivot_idx + 1), val), std::rend(c) - 1);
        if (i != pivot_idx) return i;
    }
    else
    {
        if (include_pivot) pivot_idx++;
        int i = std::distance(std::begin(c),
                    std::find(std::begin(c), std::begin(c) + pivot_idx, val));
        if (i != pivot_idx) return i;
    }
    return -1;
}

I am a student to C++ and am looking for ways to code better, I appreciate all suggestions.

To Editors: I wasn't sure if I should leave my long lines on one line or fit to screen, please let me know if they should be on one line, and I will update it.


texts:
I am implementing a mutable trie. I tested and it produces correct results. However, it is very slow. I benchmark it against plain old Data.Map, which is more than twice as fast.

Full source

So what am I doing wrong? I am expecting a fundamental flaw in the way I write mutable code here and not some micro performance tricks. I assume STVector is fast enough.

module Trie(Trie, empty, insert, member) where

import Data.Char (ord, toUpper)
import Data.Maybe (isJust)
import Control.Monad.ST
import qualified Data.Vector.Mutable as V

-- In a real world scenario, we would probably want to our mutable trie to base
-- on PrimMonad and PrimState so that it can work within both IO and ST. Also,
-- our trie only accepts String keys composed of capitalized English alphabets
-- ([A-Z]+). Values, though, can be of any type. Finally, there should have
-- been a function to retrieve the value given a key, but we omitted it because
-- of laziness (pun intended).
data Trie s a = Trie {
    trieValue :: Maybe a ,
    trieChildren :: V.STVector s (Maybe (Trie s a))
}

toIndex :: Char -> Int
toIndex c = (ord (toUpper c) - ord 'A') `mod` 26

empty :: ST s (Trie s a)
empty = emptyWith Nothing

newChildren :: ST s (V.STVector s (Maybe (Trie s a)))
newChildren = V.replicate 26 Nothing

emptyWith :: Maybe a -> ST s (Trie s a)
emptyWith x = newChildren >>= return . Trie x

insert :: Trie s a -> String -> a -> ST s (Trie s a)
insert = insert' . Just

insert' :: Maybe (Trie s a) -> String -> a -> ST s (Trie s a)
insert' Nothing cs z = do
    node <- empty
    insert node cs z
insert' (Just root@(Trie _ ys)) [c] z = do
    node <- emptyWith (Just z)
    V.write ys (toIndex c) (Just node)
    return root
insert' (Just root@(Trie _ ys)) (c:cs) z = do
    let i = toIndex c
    y <- V.read ys i
    insert' y cs z >>= V.write ys i . Just
    return root

member :: Trie s a -> String -> ST s Bool
member = member' . Just

member' :: Maybe (Trie s a) -> String -> ST s Bool
member' Nothing _ = return False
member' (Just (Trie x _)) [] = return (isJust x)
member' (Just (Trie _ ys)) (c:cs) =
    V.read ys (toIndex c) >>= flip member' cs