texts: Processing an input image using probability

texts:
I have the function below which is used to process an input image using probability predicted by a CNN network model.

def interp_map(prob, zoom, width, height):
    zoom_prob = np.zeros((height, width, prob.shape[2]), dtype=np.float32)
    for c in range(prob.shape[2]):
        for h in range(height):
            for w in range(width):
                r0 = h // zoom
                r1 = r0 + 1
                c0 = w // zoom
                c1 = c0 + 1
                rt = float(h) / zoom - r0
                ct = float(w) / zoom - c0
                v0 = rt * prob[r1, c0, c] + (1 - rt) * prob[r0, c0, c]
                v1 = rt * prob[r1, c1, c] + (1 - rt) * prob[r0, c1, c]
                zoom_prob[h, w, c] = (1 - ct) * v0 + ct * v1
    return zoom_prob

At the moment, the method takes around 26-30 secs execution time. I want to reduce it, if possible. The 3 for loops consumes a lot of time, however, not sure how can I reduce it.

Any suggestions on how to optimize it?

Attributes of the input parameters:

prob.shape
Out[3]: (66, 66, 13)
width
Out[4]: 480
height
Out[5]: 360


texts: Binary Search Tree insert while keeping track of parent for node to be added - iteration 2

texts:
Follow up question to
  Binary Search Tree insert while keeping track of parent for node to be added

I am implementing a red black tree for fun and am wondering how I should modify my basic BST insert. Note: this happens before the red black tree rules are applied, it just finds the correct place within the tree to add the node, places it, sets references, value and defaults the color to RED. I am mainly struggling to see if there may be a better way to tack on the parent reference for the newly added node. The implementation I have here looks ahead one step with a NULL check where a BST insert that does not need to track the parent would not need.

struct node * bstInsert(struct node *n, int x) {

  if (n != NULL) {

    int isGreater = (n->val < x) ? -1 : (n->val > x);

    if (isGreater == -1) {

      if (n->left == NULL) {
        n->left = createAChild(n, n->left, x);
      } else {
        bstInsert(n->left, x);
      }

    } else if (isGreater == 1) {

      if (n->right == NULL) {
        n->right = createAChild(n, n->right, x);
      } else {
        bstInsert(n->right, x);
      }

    }

  } else{

    n = createAChild(NULL, n, x);

  }

  return n;
}

struct node * createAChild(struct node *par, struct node *n, int x) {

  n = malloc(
    sizeof(struct node)
  );
  n->parent = par;
  n->left = n->right = NULL;
  n->val = x;
  n->color = RED;

  return n;

}

Is there a cleaner solution to setting the parent reference for the node to be added?


texts:
So I have some Javascript code that resembles the following:

var mylibrary = new (function ()
{

    this._getLibraryObj = function ()
    {
        var newLibraryObj = {};
        var libraryData = window.specifiedLibraryData;
        // Add head librarian details
        // open library
        // etc. etc. turn into an object from data

        return newLibraryObj ;
    };

    this.item = function (item)
    {

        if (this.obj && item in this.obj)
        {
            return this.obj[item];
        }
        else
        {
            this.obj = this._getLibraryObj();
            if (item in this.obj)
            {
                return this.obj[item];
            }
            return null;
        }
    };

    return this;
})();

What annoys me is that this.item(item) function repeats the item in this.obj[item] and I find it a little hard to read.  I was hoping for it to not have to run _getLibraryObj too often.

Question: How would you rewrite this.item() to be short and sweet (DRY and readable)?

EDIT:- From alex's post I realised I left out one constraint: If the item isn't in the library object then it might need to _getLibraryObj() again as the data may have changed

Solution:- I ended up using @Alex Nolan's fifth example (with || instead of && I find it easier to read.):

this.item = function(item)
{
    if(!this.obj || !item in this.obj)
    {
        this.obj = this._getLibraryObj();
    }

    return this.obj[item] || null;
}


texts:
Is the following procedure good for shuffling data in general (not just for JavaScript)?

function Shuffle(array) {
  var temp = null,
    len = array.length - 1,
    rnd = null;
  for (var i = len; i > 0; i--) {
    // Generate a random number in which does not exceeds the length of array.
    rnd = Math.floor(Math.random() * len);
    // Assign last item in array to "temp" variable.
    temp = array[len];
    // Assign a random number to last item in array.
    array[len] = array[rnd];
    // Assign value of "temp" variable which may we added previously to the array last random item which has been generated previously.
    array[rnd] = temp;
  }
  return array;
}

// Implementation
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
document.getElementById('result').innerHTML = Shuffle(arr);


texts: Comparing equivalent Scala and C# string-manipulation code - with Scala running much slower

texts:
I am very early in my journey of learning Scala, and I was doing challenges on hackerrank.com to get used to the syntax. As I finished one (very trivial) challenge, I noticed that the run times seem to be unusually slow.

Thinking that it might be environment-dependent (as the code runs on the HackerRank servers), I decided to quickly reimplement the same code in C#. Interestingly, the code runs 5x faster...

I know that the environment could affect a lot of things, but surely a 5x speed gain for such a trivial operation is strange? They are using Mono for compiling C# code, so both implementations run on Linux. You can get detailed info on their environment here.

The only other idea I have is that, as I am very new to Scala, it is my code which is the problem. So, please take a look at my two implementations below (first in Scala, second in C#) for this problem.

Scala implementation:

object Solution {
    def main(args: Array[String]) {
        println(if (readLine.toLowerCase.filter(x => x >= 'a' && x <= 'z').distinct.length == 26) "pangram" else "not pangram")
    }
}

C# implementation:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
    static void Main(String[] args) {
        string x = System.Console.ReadLine();
        System.Console.WriteLine((x.ToLowerInvariant().ToCharArray().Where(z => z >= 'a' && z <= 'z').Distinct().Count() == 26) ? "pangram" : "not pangram");
    }
}

and let me know how it is possible that the Scala implementation runs that much slower...

I can post screenshots of the run results if needed, but to give an idea - most C# test cases finish in 0.1s and Scala cases take 0.5s.

Can it be the startup time of the runtime? Or do I surrender to the idea that Scala is really that much slower by nature?

The timings were returned by HackerRank's environment (so I realize, of course, that this is nowhere near a benchmark - but nevertheless 5x is crazy).

Scala results:

C# results:


texts: Personal Project for managing Bookmarks - View Part

texts:
The code is the view part of my bookmarker - project for managing bookmarks by categories. It uses Python 3.4/Django 1.6. I have also included models.py for reference.

The code does the following

Providing relevant autocomplete JSON data
Providing details of categories/bookmarks (both are DB models of my project)
Open website stored in bookmark

I am mainly concerned with the quality of the abstractions. Other reviews are also welcome but I am mainly concerned with the structure of the code.

views.py

from django.http import HttpResponse
from django.shortcuts import render

from BookMarker.models import BookMark, Category

import json
import webbrowser

###########################
##       Auxiliary       ##
###########################
def _get_objects_by_params(request, param_name, object_class):
    ids_string = request.GET.get(param_name, '')
    if ids_string == '':
        return []
    ids = ids_string.split(',')
    return [object_class.objects.get(pk=_id) for _id in ids]

class Autocomplete():
    @staticmethod
    def _get_json(cur_objects, func):
        results = []
        for cur_object in cur_objects:
            results.append(func(cur_object))
        return json.dumps(results)

    @staticmethod
    def autocomplete(request, class_name, attr_name):
        term = request.GET.get('term', '')
        objects = class_name.objects.filter(**{
            attr_name + '__icontains': term
        })

        exclude_value = request.GET.get("excludes", "")
        if exclude_value != "":
            objects = objects.exclude(id__in=[int(i) for i in exclude_value.split(",")])

        data = Autocomplete._get_json(
            objects,
            lambda x: getattr(x, attr_name)
        )
        return HttpResponse(data, 'application/json')

class GetBookMarks:
    @staticmethod
    def get_bookmarks_by_categories(categories):
        bookmarks = set()
        for category in categories:
            bookmarks.update(category.bookmark_set.all())
        return bookmarks

    @staticmethod
    def get_bookmark_by_name(bookmark_name):
        return BookMark.objects.filter(name=bookmark_name)[0]

class GetCategories:
    @staticmethod
    def get_categories_by_bookmark(bookmark):
        return bookmark.category.all()

###########################
##         Services      ##
###########################
def category_autocomplete(request):
    return Autocomplete.autocomplete(request, Category, 'name')

def bookmark_autocomplete(request):
    return Autocomplete.autocomplete(request, BookMark, 'name')

def website_open(request):
    cur_url = _get_objects_by_params(request, 'id', BookMark)[0].url_content
    webbrowser.open(cur_url)
    return HttpResponse('success', 'text/html')

def get_bookmarks(request):
    categories = _get_objects_by_params(request, 'value', Category)
    bookmarks = GetBookMarks.get_bookmarks_by_categories(categories)
    return render(request, 'BookMarker/partials/bookmarks.html', {
        'bookmarks': bookmarks,
    })

#TODO Need to check the name
def get_bookmark_by_name(request):
    bookmark = GetBookMarks.get_bookmark_by_name(request.GET.get("name", ""))
    categories = GetCategories.get_categories_by_bookmark(bookmark)
    result = [category.name for category in categories]
    return HttpResponse(json.dumps(result), 'application/json')

def get_category(request):
    category = Category.objects.get(name=request.GET.get('value', ''))
    return render(request, 'BookMarker/partials/category.html', {
        'category': category,
    })

models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class BookMark(models.Model):
    name = models.CharField(max_length=50)
    url_content = models.CharField(max_length=500)
    category = models.ManyToManyField(Category)

    def __str__(self):
        return self.name


texts:
I am trying to remove file extension of a file with many dots in it:

string a = "asdasdasd.asdas.adas.asdasdasdasd.edasdasd";

string b = a.Substring(a.LastIndexOf('.'), a.Length - a.LastIndexOf('.'));

string c = a.Replace(b, "");

Console.WriteLine(c);

Is there any better way of doing this?


texts:
please let me know if this question doesn't meet community standard for code review (I will delete it)
Hey, I am probably terrible in naming files, functions etc.
We follow atomic design principle. More here
I have a react app where we put small components like button, label etc and call it atoms.
In that I have made loading and Error component responsible for displaying loading bar and Error alert respectively.
Then I created a molecule status which contains both these components
// Reports current status of the application
// For loading display loading bar
// for Error shows, error component
import React from 'react'
import Loading from 'components/atoms/loading'
import Error from 'components/atoms/ErrorAlert'
import { MoleculesStatus } from '@types'
import _ from 'lodash'

export default function Status({ projects }: MoleculesStatus) {
  const loading = _.get(projects, 'loading')
  const error = _.get(projects, 'error')
  return (
    <>
      <Loading loading={loading} />
      <Error error={error} />
    </>
  )
}

In the PR, I have been asked to search about atomic design naming convention and write more understandable naming. Can someone help me in understanding, what's wrong with my naming as per atomic design and what naming would be more appropriate?


texts:
I was hacking around this morning and wanting to use automatically generate safe-to-use variables from $_POST. Probably not the best use of extract() and compact(), but extract() allowed me to prefix variable names and compact(explode()) seemed like a neat way to stick everything back into an array after being prefixed.

function sanitizeForm($formVars) {
    // prefix $_POST vars so attacker can't try and guess existing
    extract($_POST, EXTR_PREFIX_ALL, 'form');
    // put the form variables back into an array
    $inputArray = compact(explode(' ', $formVars));
    $cleanInput = array();
    foreach($inputArray as $key => $value) {
        $cleanInput[$key] = htmlspecialchars($value);
    }
    return $cleanInput;
}

The test form I used simply posted firstname, lastname, and comments. Here's the PHP:

if(isset($_POST['submit'])) {
    $test = sanitizeForm('form_firstname form_lastname form_comments');
    echo('<pre>');
    print_r($test);
    echo('</pre>');
}

Submitting 'test' for both firstname and lastname with the script in comments:

Array
(
    [form_firstname] => test
    [form_lastname] => test
    [form_comments] => <script>alert('xss')</script>
)


texts:
I have created a ViewModel for a Product Edit page because it has specific related entities I need to load - the class currently looks like this:

public class ProductEditView
{
    public ProductEditView(Product product)
    {
        this.ID = product.ID;
        this.Code = product.Code;
        this.ProductLanguage = product.ProductLanguages.Where(x => x.LanguageID == Global.Language).FirstOrDefault();
        this.PrimaProduct = product.PrimaProduct;
        this.Multimedias = product.Multimedias;
    }

    public int ID { get; set; }
    public string Code { get; set; }
    public ProductLanguage ProductLanguage { get; set; }
    public PrimaProduct PrimaProduct { get; set; }
    public IEnumerable<Multimedia> Multimedias { get; set; }

}

So then in my controller I can go:

public ActionResult Edit(int? id)
{
    if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    Product product = db.Products.Find(id);
    if (product == null) return HttpNotFound();

    ProductEditView productEditView = new ProductEditView(product);
    return View(productEditView);
}

I've not really seen anybody do it like this though, is it bad practice - and for what reason? What are the better alternatives to accomplish this if this is wrong?


texts: Code to calculate similarity between strings - R

texts:
I have a large datafile with names and I want to create a similarity distance matrix. With this matrix I want to get similar names that could be the same person (or not) and that I could compare these rows and check whether more variables match or not.

However the code I have is quite slow. The dataframe has 58797 rows and some of them are repeated names. I was wondering for other options or a better way to get the information I'm looking for.

This is the code I have so far:

similar <- list()
for (i in 1:dim(data)[1]) {
    ids <- which(levenshteinSim(data$nomeAlt[i], data$nomeAlt) != 1 &
                 levenshteinSim(data$nomeAlt[i], data$nomeAlt) > 0.85)
    # ifelse only returns first element of list, instead use separate if else
    similar[[i]] <- if (length(ids) == 0) NA else ids
    print(i) # to get an update of the progress
}

Basically, the output returns rownames which I can get the names. In a working exemple I got names such as "ABEL MACEDO ALVES" and "ABEL MACHADO ALVES".

Any suggestion would be appreciated. Thank you!


texts:
Note: I wasn't trying to follow the POSIX getdelim signature exactly. I needed to add the consume argument for a project I'm working on.

I am pretty new to writing C. It would be great to get some feedback on whether best practices are being followed.

Some things I learned about while writing this code (which might be areas that need improvement)

Pointer arithmetic
FILE * error handling

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

ssize_t read_until_deliminator(char **buffer, size_t *size, char deliminator,
                               FILE *file, bool consume)
{
        char ch;
        char *buffer_pos;

        if (buffer == NULL || size == NULL || ferror(file)) {
                errno = EINVAL;
                return -1;
        }

        if (buffer == NULL || *size == 0) {
                // Empty buffer supplied
                *size = 128;
                *buffer = malloc(*size);

                if (*buffer == NULL) {
                        errno = ENOMEM;
                        return -1;
                }
        }

        buffer_pos = *buffer;

        for (;;) {
                ch = getc(file);

                if (ch == EOF) {
                        break;
                }

                if ((buffer_pos + 1) == (*buffer + *size)) {
                        // No more room in buffer
                        size_t new_size = *size * 2;
                        char* realloc_buffer = realloc(*buffer, new_size);

                        if (realloc_buffer == NULL) {
                                errno = ENOMEM;
                                return -1;
                        }

                        buffer_pos = realloc_buffer + (buffer_pos - *buffer);
                        *buffer = realloc_buffer;
                        *size = new_size;
                }

                *buffer_pos++ = ch;

                if (ch == deliminator) {
                        if (!consume) {
                                // If not consuming delim roll back buffer
                                buffer_pos--;
                        }

                        break;
                }
        }

        if (ch == EOF && buffer_pos == *buffer) {
                return -1;
        }

        *buffer_pos = '\0';

        return buffer_pos - *buffer;
}

int main(void)
{
        size_t buffer_size = 50;
        char *buffer = malloc(buffer_size);

        ssize_t result = read_until_deliminator(&buffer, &buffer_size, 'c', stdin, false);

        printf("Result: %zd\n", result);
        printf("Buffer Size: %zu\n", buffer_size);
        printf("Buffer: %s\n", buffer);

        free(buffer);
}

Minimal working example: https://repl.it/repls/SlimEarlyField


texts:
Probably, this use of for-loops and lists is horrible. Thus, I describe my procedure below and am thankful for any constructive feedback!

Conjoint analysis is used in marketing to extract preferences from a rated/ranked list of variants. The variants are combinations (e.g. all permutations) of certain attributes/variables. The steps are annotated.

Define the data (9 variants):

data <- data.frame(
  "upper" = c(1,1,1,2,2,2,3,3,3), # var 1
  "country" = c(1,2,3,1,2,3,1,2,3), # var 2
  "price" = c(1,2,3,2,3,1,3,1,2), # var 3
  "rating" = c(9,7,5,6,5,6,5,7,6) # rating of the alternative
)

Set up a list in which the keys are the attributes (upper, country, price) and the values are the unique levels of that attribute (1, 2, 3).

lst <- list()
for (attribute in setdiff(colnames(data), "rating")) {
  lst[[attribute]] = unique(data[[attribute]])
}

Set up a list with dummy-codings. Each level of each attribute will be represented as a tuple of 0s and a single 1. Thus, for three levels 1, 2, 3, we need two dummy variables with coding 00, 01, 10 (for four levels, you would have 000, 001, 010, 100 - NOT 11). The keys are the string  and the values are 1 if the level is present and 0 if not. Since we need n-1 dummy variables for n levels of an attribute, the last one is skipped.

dummy <- list()
for (attribute in colnames(data)) {
  i <- 1
  for (level in lst[[attribute]]) {
    if (length(lst[[attribute]])!=i) {
      dummy[[paste0(attribute, level)]] <- ifelse(
        data[[attribute]]==level,
        1,
        0
      )
    }
    i <- i + 1
  }
}

Copy the rating:

dummy[["rating"]] <- data[["rating"]]
dummy <- as.data.frame(dummy)

Solve the linear model:

model <- lm(rating~.,dummy)

Retrieve coefficients:

coef <- model$coefficients

Transform coefficients to meaningful level-based scores:

pwlst <- list()
for (attribute in setdiff(colnames(data), "rating")) {
  vals <- sapply(lst[[attribute]][1:length(lst[[attribute]])-1],
    function(x) {
      coef[paste0(attribute, x)]
    }
  )
  m <- diag(length(vals)+1)
  m[,ncol(m)] <- -1
  m[nrow(m),] <- 1
  pwlst[[attribute]] <- solve(m, c(unname(vals), 0))
}

Print utility of levels within each attribute:

print(pwlst)

Retrieve part-worths of the attributes:

rpwlst <- list()
tw <- 0
for (x in names(pwlst)) {
  tw <- tw + max(pwlst[[x]]) - min(pwlst[[x]])
}
for (x in names(pwlst)) {
  rpwlst[[x]] <- (max(pwlst[[x]]) - min(pwlst[[x]]))/tw
}

Print results of relative attribute part-worths:

print(rpwlst)


texts:
I've written a script in vba to parse movie names and year from a torrent site. The script is doing just awesome. Although the scraper is leaving no room for complaint, I'm still dubious about how the way I've set the proxy is accurate. Moreover, I've set two proxies in my scraper. Btw, I went through few codes where the proxy has been set using .setProxy 2,"xxxxxxx" whereas I used .setProxy 1 in my below code because the earlier one was throwing errors. Once again, the code is working flawlessly. Thanks in advance.

Here is what I've written:

Sub Torrent_Scraper()
    Dim http As New ServerXMLHTTP60, html As New HTMLDocument
    Dim post As HTMLHtmlElement

    With http
        .Open "GET", "https://yts.ag/browse-movies", False
        .setRequestHeader "Content-Type", "text/html; charset=utf-8"
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
        .setProxy 1, "61.233.25.166:80", "46.101.27.218:8118"
        .send
        html.body.innerHTML = .responseText
    End With

    For Each post In html.getElementsByClassName("browse-movie-bottom")
        With post.getElementsByClassName("browse-movie-title")
            x = x + 1: Cells(x, 1) = .item(0).innerText
        End With
        With post.getElementsByClassName("browse-movie-year")
            If .Length Then Cells(x, 2) = .item(0).innerText
        End With
    Next post
End Sub


texts:
I’ve written an answer for The Grid Search challenge on HackerRank.
Please let me know of any improvements that can be made to my implementation (specifically if there's any way to make the algorithm more efficient. I'd like to make this algorithm optimal).

P.S: My implementation is a brute force algorithm, and I reckon that there's a much better way of solving this problem. But, as the grid is unsorted, I'm not exactly sure what that better method would be.

Problem statement (as written on HackerRank):

  Given a 2D array of digits, try to find the location of a given 2D pattern of digits.

Answer:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {
    public static void main(String[] args) throws IOException {
        Solution solution = new Solution();
        try(BufferedReader input = new BufferedReader(new InputStreamReader(System.in))){
            int numTestCases = Integer.parseInt(input.readLine());
            assert numTestCases >= 1 && numTestCases <= 5;
            int[][] grid;
            int[][] pattern;

            for(int t = 0; t < numTestCases; t++) {
                grid = solution.buildArray(input);
                pattern = solution.buildArray(input);
                // Gotta STDOUT in HackerRank for problem to be graded.
                System.out.println(solution.findPattern(grid, pattern));
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    /**
     * Determines whether pattern exists in grid.
     *
     * @param grid       2D array of digits
     * @param pattern    the 2D sequence of digits to be found in grid
     * @return "YES" if grid contains pattern. "NO" if not.
     */
    public String findPattern(int[][] grid, int[][] pattern){
        // R, C, r, & c are the same letters used in the problem
        for(int R = 0; R < grid.length - pattern.length + 1; R++){
            for(int C = 0; C < grid[0].length - pattern[0].length + 1; C++){
                outerLoop:
                for(int r = 0; r < pattern.length; r++){
                    for(int c = 0; c < pattern[0].length; c++){
                        if(grid[R + r][C + c] != pattern[r][c]){
                            break outerLoop;
                        }
                    }
                    if(r == pattern.length - 1){
                        return "YES";
                    }
                }
            }
        }
        return "NO";
    }

    /**
     * Builds and returns an array built according to data received from STDIN.
     *
     * @param input    STDIN stream
     * @return a 2D primitive array containing 0-9 digits
     * @throws IOException
     */
    public int[][] buildArray(BufferedReader input) throws IOException {
        String[] sizeParameters = input.readLine().split(" ");
        int rows = Integer.parseInt(sizeParameters[0]);
        int columns = Integer.parseInt(sizeParameters[1]);
        int[][] array = new int[rows][columns];

        for(int i = 0; i < rows; i++){
            String rowOfNumbers = input.readLine();
            for(int j = 0; j < columns; j++){
                array[i][j] = Character.getNumericValue(rowOfNumbers.charAt(j));
            }
        }

        return array;
    }

}


texts:
I have some code to translate some color names, and this is what I did, quick and dirty.
But I'm guessing there might be some function to replace arrays with arrays maybe, like in PHP, where you can have str_replace($array_of_colors, $replace_array_of_colors, $colors);.

var color = colors[c].replace(/sort/i, "Black");
color = color.replace(/brun/i, "Brown");
color = color.replace(/hvit/i, "White");
color = color.replace(/oransje/i, "Orange");
color = color.replace(/gul/i, "Yellow");
color = color.replace(/beige/i, "Beige");
color = color.replace(/Mørk/i, "Dark");
color = color.replace(/Rosa/i, "Pink");
color = color.replace(/rød/i, "Red");
color = color.replace(/Blå/i, "Blue");
color = color.replace(/grå/i, "Gray");
color = color.replace(/Lys/i, "Light");
color = color.replace(/lilla/i, "Purple");


texts:
Is this a good approach or is there some other solution that I am not aware of?

//C++ program to count number of words in text file

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

int main()
{
    ifstream inFile; //Declares a file stream object
    string fileName;
    string word;
    int count = 0;

    cout << "Please enter the file name ";
    getline(cin,fileName);

    inFile.open(fileName.c_str());

    while(!inFile.eof())
    {
        inFile >> word;
        count++;
    }

    cout << "Number of words in file is " << count;
    inFile.close();

    cin.get();
    return 0;
}


texts:
I currently override the sorting methods provided by namedtuple by doing something like this:

class Subtitle(namedtuple('Subtitle', ['index', 'start', 'end', 'content'])):
    def __eq__(self, other): return self.start == other.start
    def __ne__(self, other): return self.start != other.start
    def __lt__(self, other): return self.start <  other.start
    def __le__(self, other): return self.start <= other.start
    def __gt__(self, other): return self.start >  other.start
    def __ge__(self, other): return self.start >= other.start

Typically I would use functools.total_ordering as a decorator to fill in the other sort methods from one, but in this case, collections.namedtuple already defines sort methods, so decorating with it has no effect.

As it is, fleshing out all of these comparisons when they can be deduced from each other seems a waste of code -- something that is much better handled by functools.total_ordering if only I could use it. I suppose I could delete the other sort methods from the object, but that seems quite messy. I'm not interested in reimplementing something like functools.total_ordering from scratch in my code.

Is there a better way to do this?


texts: Switch-Case pattern for non-constant types

texts:
Edit: Following answers, I modified my code, and wrote an other question.

History

Recently, I (stupidly) tried to make a switch on myObj.GetType(). Of course, it didn't work. Then I made an ugly (this is subjective) if ... else if ... else if ... else ... list.
I ask myself if I couldn't make something to keep the switch-case architecture, and then I started experienced things.

Expected

To keep the structure of a real switch-case, I want to use it in this way:

Switch(myInt)
    .Case(1, EqualsOneMethod)
    .Case(2, EqualsTwoMethod)
    .CaseWhen(i => i <= 0, NullOrNegativeMethod)
    .Default(DefaultMethod);

static void EqualsOneMethod() { ... }
static void EqualsTwoMethod() { ... }
static void NullOrNegativeMethod() { ... }
static void DefaultMethod() { ... }

Code

Everything starts with this interface:

public interface ISwitchCase<T>
{
    ISwitchCase<T> Case(T value, Action action);
    ISwitchCase<T> Case(T value, IEqualityComparer<T> comparer, Action action);
    ISwitchCase<T> CaseWhen(Predicate<T> predicate, Action action);
    void Default(Action action);
}

The normal implementation is this one:

internal class SwitchCase<T> : ISwitchCase<T>
{
    private T Value { get; }

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

    public ISwitchCase<T> Case(T value, Action action)
    {
        if (Value is IEquatable<T>)
            return CaseWhen(t => ((IEquatable<T>)t).Equals(value), action);

        if (value is IEquatable<T>)
            return CaseWhen(t => ((IEquatable<T>)value).Equals(t), action);

        return Case(value, EqualityComparer<T>.Default, action);
    }

    public ISwitchCase<T> Case(T value, IEqualityComparer<T> comparer, Action action)
    {
        return CaseWhen(t => comparer.Equals(Value, value), action);
    }

    public ISwitchCase<T> CaseWhen(Predicate<T> predicate, Action action)
    {
        if (predicate(Value))
        {
            action();
            return EmptySwitchCase<T>.Instance;
        }

        return this;
    }

    public void Default(Action action) =>
        action();
}

Whenever a case fullfils its predicate, it returns an EmptySwitchCase, which is the following:

internal class EmptySwitchCase<T> : ISwitchCase<T>
{
    public static EmptySwitchCase<T> Instance { get; }

    static EmptySwitchCase() { Instance = new EmptySwitchCase<T>(); }

    private EmptySwitchCase() { }

    public ISwitchCase<T> Case(T value, Action action) => this;

    public ISwitchCase<T> Case(T value, IEqualityComparer<T> comparer, Action action) => this;

    public ISwitchCase<T> CaseWhen(Predicate<T> predicate, Action action) => this;

    public void Default(Action action) { }
}

Thanks to this EmptySwitchCase, once a case is executed, no other case / default will be triggered.

Finally, as all these classes are internal, a simple static class is used as a facade:

public static class Bar // couldn't find a correct name...
{
    public static ISwitchCase<T> Switch<T>(T value) => new SwitchCase<T>(value);
}


texts:
I have a webpage that shows shorthand code on the left, and its long form on the right. When you hover over code on the left (signified with a space-separated array in the data-from attribute), it uses jQuery to highlight corresponding code on the right (signified with a space-separated array in the data-to attribute), and vice-versa. It's working great, but it feels very long.

Script

function containsAny(haystack, needles) {
    for(needle in needles)
        if (haystack.indexOf(needles[needle]) >= 0)
            return true;
}
$(document).ready(function() {
    /* from to */
    $("[data-from]").each(function(i, e) {
        var $e = $(e),
        froms = $e.data("from").toString().split(/\s+/); // must do toString in case we get an int
        $e.hover(function() {
            $e.addClass("hilighted");
            $("[data-to]").each(function(i2, e2) {
                var $e2 = $(e2),
                tos = $e2.data("to").toString().split(/\s+/);
                if (containsAny(tos, froms))
                    $e2.addClass("hilighted");
            });
        },
        function() {
            $("[data-to]").each(function(i2, e2) {
                $e.removeClass("hilighted");
                var $e2 = $(e2),
                tos = $e2.data("to").toString().split(/\s+/);
                if (containsAny(tos, froms))
                    $e2.removeClass("hilighted");
            });
        });
    });

    /* to from */
    $("[data-to]").each(function(i, e) {
        var $e = $(e),
        tos = $e.data("to").toString().split(/\s+/);
        $e.hover(function() {
            $e.addClass("hilighted");
            $("[data-from]").each(function(i2, e2) {
                var $e2 = $(e2),
                froms = $e2.data("from").toString().split(/\s+/);
                if (containsAny(froms, tos))
                    $e2.addClass("hilighted");
            });
        },
        function() {
            $("[data-from]").each(function(i2, e2) {
                $e.removeClass("hilighted");
                var $e2 = $(e2),
                froms = $e2.data("from").toString().split(/\s+/);
                if (containsAny(froms, tos))
                    $e2.removeClass("hilighted");
            });
        });
    });
});

SSCCE HTML

Before

*:link {
    color: blue;
}

button,
input[type=("button","submit","reset")] {
    color: match(*:link);
}

After

*:link,
button,
input[type="button"],
input[type="submit"],
input[type="reset"] {
    color: blue;
}

Full use case

How can I make the JavaScript shorter (or at least more OO) without sacrificing functionality? I'm sure it can be shorter or more OO because it's so redundant, but I can't figure how.


texts: Design/reiterate or code reuse for linked list

texts:
This is what my class hierarchy looks like. I have an abstract superclass, AbstractLinkedMyList, that contains common operations for both sorted and unsorted linked list.

Here's the declaration for it and the method I have a question about:

public abstract class AbstractLinkedMyList<Type> implements MyList<Type> {
    protected ListNode<Type> front;
     protected ListNode<Type> back;

public void insertAtIndex(int index, Type value) {
        checkOkToInsertAtIndex(index);
        if (size == 0) {
            ListNode<Type> newNode = new ListNode<Type>(value);
             front = back = newNode;
         }
        else {
            if (index == 0) {
                   ListNode<Type> newNode = new ListNode<Type>(value, front);
             front = newNode;
            }
           else {
                  ListNode<Type> current = nodeAt(index - 1);
                  ListNode<Type> newNode = new ListNode<Type>(value, current.next);
                 current.next = newNode;
                 if (index == size) {
                     back = newNode;
                 }
            }
       }
   size++;
    }
     protected ListNode<Type> nodeAt(int index) {
         ListNode<Type> current = front;
         for (int i = 1; i <= index; i++) {
                current = current.next;
          }
         return current;
    }
  protected static class ListNode<Type> {
        public Type data;
        public ListNode<Type> next;
        public ListNode(Type data) {
             this(data, null);
        }
        public ListNode(Type data, ListNode<Type> next) {
             this.data = data;
             this.next = next;
        }
     }
    .....
}

Here is my declaration for the sorted linked list:

public class LinkedListSorted<E extends Comparable<E>> extends AbstractLinkedMyList<E>

My question is about the insertAtIndex method. I chose to put the insertAtIndex method in the abstract superclass because this would be how you insert something at an index, no matter what the subclass is (sorted vs unsorted). I realized that in the sorted linked list class, I will have to extend this method to impose restrictions(to not break sorted property of the list).

This is my insertAtIndex method (what I have so far) in the sorted linked list:

public class LinkedListSorted<E extends Comparable<E>> extends AbstractLinkedMyList<E>
@Override
public void insertAtIndex(int index, E value) {
    if(index == 0 && front != null && value.compareTo(front.data) > 0) {
        throwSortException();
    }
    if(index == size && value.compareTo(back.data) < 0) {
        throwSortException();
    }
    if(index > 0 && index < size) {
        ListNode<E> before = nodeAt(index - 1);
        if(value.compareTo(before.data) < 0 || value.compareTo(before.next.data) > 0) {
            throwSortException();
        }
    }
    super.insertAtIndex(index, value);
}

My logic here is here are all the cases where you cannot insert (would break the sorted property of the list). If you can make it past all these cases, I will allow insertAtIndex, whose implementation is in the abstract superclass (explained is this decision above).

Would this be good code design? One drawback I saw right away was that my check logic involved a lot of iteration. You would need to this iteration again if you actually wanted to insert. But then if you put the insert logic in the check case, you would be rewriting code (not taking advantage of code reuse). How would you weight the two? Is what I have acceptable?


texts: A beginners implementation of Game of Life

texts:
I'm totally new to python and coding in general and I tried for my first project to recreate Conway's game of life. After days of trial and error, I came up with this code:

import numpy as np
import copy
import png
import PIL as PIL
def a(a) :
    if a == "gen" :
        size=int(input("size ? "))
        ratio=float(input("ratio ? "))
        name=input("file name: ")
        matrix=np.random.choice(2,(size,size),p=[1-ratio,ratio])
        i = png.from_array(matrix, mode='L;1')
        i.save(str(name)+'.JPEG')

    if a == "start" :
        name=input("file name: ")
        time=input('number of rounds: ')
        matrix=np.asarray(PIL.Image.open(str(name)+'.jpeg')).astype(int)
        matrix2=copy.deepcopy(matrix)
        taille1,taille2=matrix.shape
        counter=0
        while counter<int(time):
           for x in range(0,taille1-1):
             for y in range(0,taille2-1):
                if matrix[x,y]==0 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]==3:
                   matrix2[x,y]=1
                if matrix[x,y]==1 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]<2:
                   matrix2[x,y]=0
                if matrix[x,y]==1 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]>3:
                   matrix2[x,y]=0
           i = png.from_array(matrix2, mode='L;1')
           i.save(str(name)+'_output_'+str(counter+1)+'.JPEG')
           matrix=copy.deepcopy(matrix2)
           counter+=1
task=input("command : ")
a(task)

It works really fine but I'm afraid it is quite unefficient, so I'd like to hear advice on how to make it faster (especially the triple loop)


texts: Merge Sort implementation with generators and recursion

texts:
Just beating the dead merge-sort horse, this time with generators and recursion!

What do you think?

p.s. Not entirely sure why stack overflow needs me to post more details on a code review. I'm implementing something straight from an undergrad CS class but because it does, here Is the video that inspired me https://www.youtube.com/watch?v=TzeBrDU-JaY

k=[1,2,1,3,4,2]
def merge_sort(lis):
    """this performs merge sort assuming
none of the values in lis are greater than 10**100"""
    if len(lis)<=1:
        return lis
    else:
        over=int(len(lis)/2)
        RL=lis_generator(merge_sort(lis[over:]))
        LL=lis_generator(merge_sort(lis[:over]))
        new_l=list()
        cRL=next(RL)
        cLL=next(LL)
        while len(new_l)<len(lis):
            if cRL<=cLL:
                new_l.append(cRL)
                cRL=next(RL)
            else:
                new_l.append(cLL)
                cLL=next(LL)

        return new_l

def lis_generator(lis):
    """enumerate --> index, value"""
    for i in lis:
        yield i
    yield 10**100


texts:
Function to use several blocks of if:elif:else: that all take slightly different conditional statements.  I'm trying to format integers into a 2 digit string, adding a leading 0 for single digits.  It is working great, but there has to be DRY way of doing the same thing.  Also, the timezone formatting is a bit of a mess.  After struggling to come up with a more elegant solution, I just went with what was obvious and working.

def rfc_3339_str(minutes = 0, year = 1999, month = 1, date = 1, secs = 0, time_zone = 0):
    '''Takes minutes and builds RFC 3339 timeDate string.
        yyyy-mm-ddTHH:MM:ss[.mmm][+/-HH:MM].  Does not support milliseconds.
        All params optional.  Timezone format is number in range
        [-12:12] (hours only).  All numbers expect integers.
        Minutes > 1439 (23 hours 59 minutes) wrap around to zero,.
        Date defaults to 1/1/1999.  Supported years 1000-2035 CE.  Date allows
        range 0-31 inclusive for all months.  Negative times are not supported.
        Incorrect params return error description'''
    plus = '+'
    minus = '-'
    date_time_split = 'T'
    date_split = '-'
    time_split = ':'
    time_zone_mins = ':00'
    MAX_MINUTES = 1440
    yyyy = None
    mm = None
    dd = None
    HH = None
    MM = None
    SS = None
    zone_sign = plus
    zz = None

    #validate inputs
    if 1000 > year > 2035:
        return 'year_out_of_range'
    else:
        yyyy = str(year)

    if month in range(1,10):
        mm = '0' + str(month)
    elif month in range(10,13):
        mm = str(month)
    else:
        return 'month_out_of_range'

    if date in range(1, 10):
        dd = '0' + str(date)
    elif date in range(10, 32):
        dd = str(date)
    else:
        return 'date_out_of_range'

    if minutes < 0:
        return 'minutes_out_of_range'
    while minutes > MAX_MINUTES:
        minutes = minutes - MAX_MINUTES
    hours_int = int(minutes / 60)
    mins_int = int(minutes % 60)

    if hours_int in range(0,10):
        HH = '0' + str(hours_int)
    elif hours_int in range(10, 100):
        HH = str(hours_int)
    else:
        return 'hours_out_of_range'

    if mins_int in range(0,10):
        MM = '0' + str(mins_int)
    elif mins_int in range(10,60):
        MM = str(mins_int)
    else:
        return 'minutes_out_of_range'

    if secs in range(0, 10):
        ss = '0' + str(secs)
    elif secs in range(10,60):
        ss = str(secs)
    else:
        return 'seconds_out_of_range'

    small = False
    positive = False
    if time_zone in range(-9, 10):
        small = True
    if time_zone in range(-12,0):
        positive = False
    if time_zone in range(0, 13):
        positive = True

    if small:
        zz = '0'
    if positive:
        zz = plus + zz + str(time_zone)
    if not positive:
        zz = minus + zz + str(abs(time_zone))
    else:
        zz = plus + '00'

    print(yyyy + date_split + mm + date_split + dd +
        date_time_split + HH + time_split +
        MM + time_split + ss +
        zz + time_zone_mins)


texts:
I have implemented a collection class that stores a single type of value.

At the moment it is immutable.

abstract class Collection implements Iterator
{

    /** @var int */
    protected $position = 0;
    /** @var array */
    private $items = [];

    public function next()
    {
        ++$this->position;
    }

    public function key()
    {
        return $this->position;
    }

    public function valid()
    {
        return isset($this->items[$this->position]);
    }

    public function rewind()
    {
        $this->position = 0;
    }

    protected function add($item)
    {
        return $this->items[] = $item;
    }

    protected function get($index)
    {
        return $this->items[$index];
    }
}

DateTimeIterator guarantees that when iterated over it will only return the specified type.

interface DateTimeIterator extends Iterator
{

    public function current(): DateTimeInterface;
}

The constructor of DateTimeCollection ensures that the collection only stores values that implement DateTimeInterface.

class DateTimeCollection extends Collection implements DateTimeIterator
{

    public function __construct(iterable $values = [])
    {
        foreach ($values as $value) {
            if (!$value instanceof DateTimeInterface) {
                throw new TypeError('DateTimeCollection only accepts ' .
                    'items that implement DateTimeInterface');
            }
            $this->add($value);
        }
    }

    public function current(): DateTimeInterface
    {
        return $this->get($this->key());
    }
}


texts:
Do you have any suggestions about how to make this code faster/better? Maybe suggest new features or better comments/docstrings?

from time import time, ctime, sleep
from random import choice, uniform
from glob import glob
import os

# Gets current working directory
DIRECTORY_NAME = os.getcwd()

def load():
    """Prints loading messages"""
    os.system("clear")
    MESSAGES = ["Deleting hard drive...", "Reticulating Spines...", "Fetching Your Credit Card Number...", "Hacking your computer..."]
    print(choice(MESSAGES))
    sleep(uniform(1, 5))
    os.system("clear")

def print_dir(dirname):
    """Prints the current directory"""
    print("Directory: %s" % dirname)
    print("-"*80)

def number_of_files(dirname):
    """Finds the number of files in the directory using glob"""
    num_of_files = len(glob("*"))
    print(num_of_files, "files")
    print("-"*80)

def last_access(dirname):
    """Prints a ctime representation of the last access to a file"""
    print("Last Access: ")
    print(ctime(os.path.getatime(dirname)))
    print("-"*80)

def last_change(dirname):
    """Prints a ctime representation of the last change to a file"""
    print("Last Change: ")
    print(ctime(os.path.getmtime(dirname)))
    print("-"*80)

def size_of_dir(dirname):
    """Walks through the directory, getting the cumulative size of the directory"""
    sum = 0
    for file in os.listdir(dirname):
        sum += os.path.getsize(file)
    print("Size of directory: ")
    print(sum, "bytes")
    print(sum/1000, "kilobytes")
    print(sum/1000000, "megabytes")
    print(sum/1000000000, "gigabytes")
    print("-"*80)
    input("Press ENTER to view all files and sizes")

def files_in_dir(dirname):
    """Walks through the directory, printing the name of the file as well as its size"""
    print("Files in directory: %s" % dirname)
    for file in os.listdir(dirname):
        print("{0} => {1} bytes".format(file, os.path.getsize(file)))

load()
print_dir(DIRECTORY_NAME)
number_of_files(DIRECTORY_NAME)
last_access(DIRECTORY_NAME)
last_change(DIRECTORY_NAME)
size_of_dir(DIRECTORY_NAME)
files_in_dir(DIRECTORY_NAME)


texts:
I have made my own compression tool for a stack-based language that uses a dictionary compression method. The code for the decompression is the following:

elif current_command == "\u201d":
    temp_string = ""
    temp_string_2 = ""
    temp_index = ""
    temp_position = pointer_position
    while temp_position < len(commands) - 1:
        temp_position += 1
        try:
            current_command = commands[temp_position]
            if dictionary.unicode_index.__contains__(current_command):
                temp_index += str(dictionary.unicode_index.index(current_command))
                temp_position += 1
                pointer_position += 2
                current_command = commands[temp_position]
                temp_index += str(dictionary.unicode_index.index(current_command))
                if temp_string == "":
                    temp_string += dictionary.dictionary[int(temp_index)].title()
                else:
                    temp_string += " " + dictionary.dictionary[int(temp_index)].title()
                temp_index = ""
            elif current_command == "\u201d":
                pointer_position += 1
                break
            elif current_command == "\u00ff":
                temp_string += str(pop_stack(1))
                pointer_position += 1
            else:
                temp_string += current_command
                pointer_position += 1
        except:
            pointer_position += 1
            break
        if debug:print(str(pointer_position) + " with " + str(hex(ord(current_command))))

    stack.append(temp_string)

The temporary variables are temp_string, temp_string_2, temp_index and temp_position. I know I should not be using names like these, but I didn't know what else to name it. This code just doesn't feel clean, and I don't know if it's just me, but it's not pleasant to look at. The code above can be found here. The dictionary.unicode_index is found here.

The best way to explain this is with an example:

For example, we want to compress the sentence Hello, World!. We first look at the index of the word Hello, which has index 2420. Since the language is 0-indexed, we need to substract 1 from this, leaving 2419. We now slice this into two pieces, 24 and 19. Then we find the corresponding indices, found here.

24 gives Ÿ
19 gives ™

The concatenation of the indices is done at this part:

temp_index += str(dictionary.unicode_index.index(current_command))

After the concatenation, we search up the index in the dictionary, which is done here:

if temp_string == "":
    temp_string += dictionary.dictionary[int(temp_index)].title()
else:
    temp_string += " " + dictionary.dictionary[int(temp_index)].title()

We append a comma, and we repeat the process for the next word, which is World. This has the index 119. Again, substract 1, which gives us the following compressed word: Œ‰. This gives us the following code for my language:

”Ÿ™,Œ‰!

And decompresses to Hello, World!, which can be verified here.

I was wondering how I can make the code look more clean, because right now, it looks like a complete mess.


texts: Using Common Table Expression and Outer queries

texts:
In following query I'm use both Common Table Expression and Outer queries. Apparently both looks same to me.

If I summarize my requirement, I have employees in SalaryTrans table and I want to find out amounts to be recovered from their salaries monthly. Table Rcovery contains all recovery data.  Table Instalment contains all previously paid amounts so I want to sum all paid amounts and then it is deducted from total amount to calculate balance amount.

So what I'm doing here is in CTE, I'm getting two numeric fields called recovered_amount and total_amount. In second query I'm checking whether recovered_amount is not null and if it's not null I'm calculating the balance.

In outer query I have a criteria to filter out less than 0 balances from the result.

WITH CTE (employee_id, RID, instalment, reference, recovered_amount, total_amount) AS
         (SELECT SalaryTrans.employee_id, Recovery.RID, Recovery.amount / Recovery.duration AS instalment,
          SalaryTrans.reference, SUM(Instalment.recovered_amount) AS recovered_amount,       Recovery.amount AS total_amount
          FROM Recovery INNER JOIN
                        SalaryTrans ON Recovery.emp_id = SalaryTrans.employee_id LEFT OUTER JOIN
                        Instalment ON Recovery.RID = Instalment.recovery_id
          GROUP BY SalaryTrans.employee_id, SalaryTrans.reference, Recovery.RID, Recovery.amount / Recovery.duration, Recovery.amount)

SELECT RID, Balance, reference  FROM
      (SELECT RID,
       "Balance" = CASE WHEN recovered_amount !=NULL
                   THEN total_amount-recovered_amount
                   ELSE total_amount END ,
       reference FROM CTE) AS Result
WHERE Balance >0

This query gives intended output. But I want to know Can I do whole thing using CTE or simply should I use outer queries in this case. Also any idea to make it look better?

Could you please review this and give your feedback?


texts: PHP validation class for username, email, and password

texts:
I'm relatively new to PHP OOP, currently I'm practising how to use it, however I am not really certain I'm building my classes correctly, I think perhaps I'm missing something out but I'm not entirely sure what, any advice would be appreciated

Class

class Validation
{
    private
    $password,
    $repeatPassword,
    $username,
    $email;

    private static
    $minPassword = 7,
    $confirmPassword,
    $minUsername = 3,
    $maxUsername = 14,
    $validEmail;

    public static function validateEmail($email)
    {
        return (filter_var($email, FILTER_VALIDATE_EMAIL) != self::$validEmail);
    }
    public static function validatePassword($password)
    {
        return(strlen($password) >= self::$minPassword);
    }

    public static function validatecheckbox($agree)
    {
        return(!empty($terms) >= self::$checked);
    }
    public static function validateRepeatPassword($repeatPassword,$password)
    {
            return $repeatPassword === $password;

    }
    public static function validateUsername($username)
    {
            return strlen($username) >= self::$minUsername
            && (strlen($username)) <= self::$maxUsername
            && (filter_var($username ,  FILTER_VALIDATE_REGEXP,["options"=> [ "regexp" => "/^[\p{L}0-9\s]+$/u"]]) == TRUE);
    }
}

Usage

    $errors = array();

 $fields = array(
  'username' => array(
    'validator' => 'validateUsername',
    'message'   => 'What is your username?'
  ),
  'email' => array(
    'validator' => 'validateEmail',
    'message'   => 'Please enter a valid email',
  ),
  'password' => array(
    'validator' => 'validatePassword',
    'message'   => 'Password must be a minimum of seven characters'
  )
);

if(!Validation::validateRepeatPassword($password, $repassword))
{
    $errors[] = ["name" => "repassword", "error" => "Passwords must match"];
}
foreach($post as $key => $value)
    {
  if(isset($fields[$key]))
    {
            if(!Validation::{$fields[$key]['validator']}($value))
            {
                $errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
            }
    }
}


texts:
In order to learn the basics of Monte Carlo I calculated pi with it.
I also wrote an explanation of the reasoning behind the code.

Down here you can see the circle with random points that I simulated in my code.

"""
        This programme calculates pi with Monte Carlo

Given a square and a circle inside it.
We have

Area_of_the_square = LENGTH ** 2
Area_of_the_circle = radius ** 2 * pi => (LENGTH ** 2) / 4 * pi

The circle is obviously smaller than the square.
We have the equation:

Area_of_the_square * number_less_than_one == Area_of_the_circle

This programme is going to put a big number of points inside the square
(I suggest TIMES_TO_REPEAT = 10**5).

It will then count how many of them are inside the circle,

number_less_than_one = points_inside_the_circle / total_points

After doing some simple math with this formula:

Area_of_the_square * number_less_than_one == Area_of_the_circle

we get that

pi = number_less_than_one * 4

NOTE: This method is deadly slow and quite complicated,
I made this programme just in order to learn.

"""
import random

TIMES_TO_REPEAT = 10**5
LENGTH = 10**5
CENTER = [LENGTH/2,LENGTH/2]

def in_circle(point):
    x = point[0]
    y = point[1]
    center_x = CENTER[0]
    center_y = CENTER[1]
    radius = LENGTH/2
    return (x - center_x)**2 + (y - center_y)**2 < radius**2

count = inside_count = 0
for i in range(TIMES_TO_REPEAT):
    point = random.randint(1,LENGTH),random.randint(1,LENGTH)
    if in_circle(point):
        inside_count += 1
    count += 1

pi = (inside_count / count) * 4

print(pi)


texts: Add the number of descendants for each li node

texts:
A web page has a nested list.  The goal is to insert the number of descendants for each li node (except for leaf nodes).

Here is an example of the expected output:

Animals [9]
    Mammals [4]
        Cows
        Donkeys
        Dogs
        Tigers
    Other [3]
        Snakes
        Birds
        Lizards
Fishes [5]
    Aquarium [2]
        Guppy
        Angelfish
    Sea [1]
        Sea trout

Here is the javascript I wrote:

function isLeaf(elem) {
    if(elem.firstElementChild === null) {
        return true;
    }

    else {
        return false;
    }
}

function countDescendants(elem) {
    if(isLeaf(elem)) return 0;

    else {
        let children = elem.firstElementChild.children;
        let count = 0;

        for(let child of children) {
            if(isLeaf(child)) {
                   count++;
            }

            else {
                count = count + 1 + countDescendants(child);
            }

        }
        return count;
    }
}

function insertCount(elem) {
    let count = countDescendants(elem);
    let text = elem.firstChild.textContent.trim();
    text = text + " [" + count + "]";
    elem.firstChild.textContent = text;
}

function traverseDOM(root) {
    let children = root.children;

    for(let child of children) {
        if(!isLeaf(child)) {
            if(child.tagName === "LI") {
                insertCount(child);
            }
            traverseDOM(child);
        }
    }
}

//traverse DOM tree
//try catch is for debugging only
try {
    if(document.body.firstElementChild !== null) {
        traverseDOM(document.body.firstElementChild);
    }
}  catch (err) {
    console.log(err);
}

The code works.  I get this nagging feeling it could be done better.  For example, is there a way to improve the countDescendants function?


texts:
In the mobile application I have a search page. As user types search keywords I display autocomplete entries.
On each keystroke I initiate autocomplete lookup, and I am using CancellationToken to cancel lookups if user keeps typing.

I am new to using CancellationTokens, so please review my code and recommend changes as needed.

// ViewModel code is below.

// Search service is injected in ctor.
private readonly ISearchService _searchService;
private CancellationTokenSource _cancellationTokenSource;

// From the UI accept user input and get autocomplete search results.
public async Task GetAutocompleteSearchResultsAsync(string searchText)
{
    try
    {
        if (_cancellationTokenSource != null)
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource.Dispose();
            _cancellationTokenSource = new CancellationTokenSource();
        }
        else
        {
            _cancellationTokenSource = new CancellationTokenSource();
        }

        var autocomplete = await _searchService.GetAutocomplete(searchText, _cancellationTokenSource.Token);
        // Assign result to property to display results in UI.
        AutocompleteSearchResults = autocomplete;
    }
    finally
    {
        if (_cancellationTokenSource != null)
        {
            _cancellationTokenSource.Dispose();
            _cancellationTokenSource = null;
        }
    }
}

And inside the ISearchService implementation I have the following code.

public async Task<ObservableCollection<AutocompleteSearchResult>> GetAutocomplete(
string input, CancellationToken cancellationToken)
{
    try
    {
        string endpoint = $"/autocomplete/{input}";
        // _client is HttpClient instance. It's initialized in ctor.
        using (var response = await _client.GetAsync(endpoint, cancellationToken))
        {
            if (cancellationToken.IsCancellationRequested) return null;

            if (response.IsSuccessStatusCode)
            {
                string json = await response.Content.ReadAsStringAsync();
                var data = await Task.Run(() =>
                        JsonConvert.DeserializeObject<IEnumerable<AutocompleteSearchResult>>(json),
                    cancellationToken);
                return data.ToObservableCollection();
            }
        }

        return null;
    }
    catch (Exception)
    {
        return null;
    }
}


texts: Print the length of words as input to a histogram with horizontal bars

texts:
It works, but I'm sure there's a lot of improvement I could make here. I didn't try to get it to work for words over 10 characters in length, and I also didn't want to use built in properties like .length to do the work for me (I don't know why, I just wanted to figure out how to do it on my own).

#include <stdio.h>

/* print the length of words as input to a histogram with horizontal bars */
int main() {
  int c, i, j;
  int accum = 0;
  int nchar[10];

  for (i = 0; i < 10; ++i)
    nchar[i] = 0;

  while ((c = getchar()) != EOF && accum < 10) {
    if (c != ' ' && c != '\n' && c != '\t') {
      ++accum;
    }
    else {
      ++nchar[accum];
      accum = 0;
    }
  }

  for (i = 0; i < 10; ++i) {
    printf("%d ", i);
  if (nchar[i] > 0) {
    for (j = 0; j < nchar[i]; ++j) {
      putchar('x');
    }
  }
  putchar('\n');
  }
  return 0;
}


texts:
Is it possible to write this using the stream element? I can get the most of it with stream but it is the add adding string to list which is in the map that I am caught on.

/**
 * Given a list of strings, returns a map where the keys are the unique strings lengths found in the list and the values are the strings matching each length
 * [hello,world,cat,ambulance] would return {5 -> [hello, world], 3 -> [cat] -> 3, 9 -> [ambulance]}
 * @param strings
 * @return
 */
public Map<Integer,List<String>> mapLengthToMatchingStrings(List<String> strings){

    Map<Integer,List<String>> mapILS = new HashMap<Integer, List<String>>();

    for (String str : strings) {
        int length = str.length();

        if (mapILS.containsKey(length)) {
            // Add str to list at key
            //Get list at key
            List<String> rs = mapILS.get(length);
            //Add str to list
            rs.add(str);
            //Update key in map
            mapILS.put(length, rs);
        }else {
            // Add new key list to map
            //Create list
            List<String> rs = new ArrayList<String>();
            //Add string
            rs.add(str);
            //Add key and list to map
            mapILS.put(length, rs);
        }
    }
    return mapILS;
}


texts: Make a given number by adding given numbers

texts:
I have created a code that checks if a number can be made by adding different quantities of given numbers and if so returns the quantities. Is this the best way to do this or is there a more efficient way?

Here is my function:

def sumFinder(quantities, final_num):
    if len(quantities) == 1:
        for i in range(final_num//quantities[0]+1):
            num = quantities[0] * i
            if num == final_num:
                return [i]
        return False
    for i in range(final_num//quantities[0]+1):
        num = quantities[0]*i
        found_nums = sumFinder(quantities[1:], final_num-num)
        if found_nums:
            return [i] + found_nums
    return False

This is an example of it working:

for num in range(100):
    answer = sumFinder([4, 6, 9, 20], num)
    if answer:
        a, b, c, d = answer
        answer = "4({}) + 6({}) + 9({}) + 20({})".format(a, b, c, d)
    print(num, "=", answer)


texts:
I have a substantial music collection, which will not load entirely in any music program.

So I wrote this quick program, to play a random song in a subfolder of my music directory.

I'm just wondering if anyone can improve on this code? It works pretty well, but the subdirectories are not all equal with respect to size, so it neglects some directories. My random mod might also be a problem. This is just to have a useful shuffle.

import java.io.File;
import java.io.IOException;

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

    File f = new File("C:\\MUSIC");
    File random = null;
    try {
        random = goDeeper(f);
    } catch (Exception e) {
    }
    while (random == null) {
        try {
            random = goDeeper(f);
        } catch (Exception e) {
        }
    }

    System.out.println(random.getAbsolutePath());
    Process myProcess = Runtime.getRuntime().exec(
            "\"C:\\Program Files (x86)\\foobar2000\\foobar2000.exe\"   \""
                    + random.getAbsolutePath() + "\"  ");

}

public static File goDeeper(File f) {
    File[] children = f.listFiles();

    int rand = (int) ((Math.random() * 123456) % children.length);
    File random = children[rand];
    if (random.isDirectory()) {
        return goDeeper(new File(f.getAbsolutePath() + "/"
                + random.getName()));
    } else if (random.isFile() && random.getName().endsWith("mp3"))
        return random.getAbsoluteFile();

    return null;
}

}


texts: Is there a proper way to query ExpandoObject?

texts:
I am receiving the JSON from WebService and populating ExpandoObject from this one:

 var converter = new ExpandoObjectConverter();
 var jsonObject = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);

The JSON object is quite complex and in order to find the value I am doing this spaghetti code:

KeyValuePair<string, object> CountPair = new KeyValuePair<string, object>();

var currentCountPair = jsonObject.FirstOrDefault(x => x.Key == "data").Value;

if (currentCountPair != null)
{
    currentCountPair = ((ExpandoObject)currentCountPair).FirstOrDefault(x => x.Key == "children");

    if (currentCountPair != null)
    {
        currentCountPair = ((IList<object>)((KeyValuePair<string, object>)currentCountPair).Value).FirstOrDefault();

        if (currentCountPair != null)
        {
            currentCountPair = ((ExpandoObject)currentCountPair).FirstOrDefault(x => x.Key == "data").Value;

            if (currentCountPair != null)
            {
                CountPair = ((ExpandoObject)currentCountPair).FirstOrDefault(x => x.Key == "score");
                result.Score = CountPair.Value == null ? null : CountPair.Value.ToString();
            }
        }
    }

}

What do you think?  Is there any better way of getting that value from ExpandoObject?
Or at least to reduce the number of if statements and code complexity...


texts:
I have written some code in python in combination with selenium to parse all the names from facebook friend list. It was hard to manage the pop up notification and the process of scrolling to the end of that page. However, my scraper can do that successfully. I tried to do the whole thing very carefully. There are always rooms for improvement, though. here is the working code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)

def Facebook_Crawler(driver):

    driver.get('https://www.facebook.com/login.php?login_attempt=1&lwv=111')
    driver.find_element_by_xpath('//*[@id="email"]').send_keys('SomeEmail')
    driver.find_element_by_xpath('//*[@id="pass"]').send_keys('Password')
    driver.find_element_by_xpath('//*[@id="loginbutton"]').click()
    time.sleep(5)

    driver.find_element_by_xpath("//a[@id='findFriendsNav']").click()
    time.sleep(5)

    num_Of_links = -1
    num = 0

    while num != num_Of_links:

        num_Of_links = num
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(8)

        items = [post.text for post in driver.find_elements_by_xpath("//div[contains(@class,'friendBrowserNameTitle')]/a")]
        num = len(items)

    for item in items:
        print(item)

if __name__ == '__main__':
    driver = webdriver.Chrome(chrome_options = chrome_options)
    try:
        Facebook_Crawler(driver)
    finally:
        driver.quit()


texts:
In my loading scene I want to run multiple functions (IO from the disk) and start the app after they are completed.

This is in my loading class. (Note: This is unity 3d and the public variables to get access to other objects is based on Unity best practices).

public Logger MyLogger;
public Parser MyParser;
// ... more

private int coroutineCount = 0;

void Start()
{
    MyLogger.LogLastMonth(Callback);
    coroutineCount++;

    MyParser.ParseFiles(Callback);
    coroutineCount++;
}

public void Callback()
{
    coroutineCount--;

    if (coroutineCount <= 0)
    {
        SceneManager.LoadScene("GameScene");
    }
}

I do something similar in both Logger and Parser (counting coroutines and decrementing when they finish before invoking the callback received). Is there a better way to do this when I need to expand the number of functions I'm calling?


texts: Framework to define and require JavaScript modules

texts:
I'm working on a webapp that I use gulp to build. It uses useref to gather and concatenate/uglify the assets used in the HTML files.

In this case, as things are getting concatenated, it doesn't make much sense to use a framework like RequireJS to separate out my modules, and I think browserify is overkill as I don't need access to any node equivalents on the client side.

I have seen that some apps use a global App object that they attach things to. I wanted something slightly more robust so that I could "require" and "define" and not have the modules exposed on the App object, and be able to name them like in a require() arguments list instead of using App.component every time I wanted to reference one.

Here is my attempt for simple code that emulates a full on require/define methodology. This allows me to put the <script> tags that get concatenated in any order I want to in the HTML, and name the modules as they get passed in to definitions of other modules that require them.

'use strict';

(function(window) {

    var components = {},
        waiting = {};

    window.App = {};

    App.define = function(name, reqs, func) {
        if (typeof reqs === "function") {
            func = reqs;
            reqs = [];
        }
        App.require(reqs, func, name);
    };

    App.require = function(reqs, func, name) {
        var loaded = 0;

        if (!reqs.length) load(func, reqs, name);

        function callback() {
            if (++loaded === reqs.length) {
                load(func, reqs, name);
            }
        }

        for (var i = 0; i < reqs.length; i++) {
            if (components.hasOwnProperty(reqs[i])) {
                callback();
            } else {
                waitFor(reqs[i], callback);
            }
        }
    };

    function waitFor(name, callback) {
        if (waiting.hasOwnProperty(name)) {
            waiting[name].push(callback);
        } else {
            waiting[name] = [callback];
        }
    }

    function load(func, reqs, name) {
        var result = func.apply(window, orderedReqs(reqs));
        if (name) {
            components[name] = result;

            if (waiting.hasOwnProperty(name)) {
                for (var i = 0; i < waiting[name].length; i++) {
                    waiting[name][i](name);
                }
            }

            delete waiting[name];
        }
    }

    function orderedReqs(reqs) {
        var args = [];

        for (var i = 0; i < reqs.length; i++) {
            args.push(components[reqs[i]]);
        }

        return args;
    }

})(window);

Then I can do this in my module javascript files:

App.define('a', function() {
    console.log('a loaded');
});

App.define('b', ['a'], function(a) {
    // use a to do something if I had made it an object
    console.log('b loaded');
});

This custom solution I think is simple enough for my needs but also lends itself to some nice code with only one global and the module definitions hidden away inside of it.

What do other people do when they want something vanilla? Does this seem like a good solution? Feel free to critique my coding style, as any criticism is good criticism.


texts:
I wasn't satisfied with Simon's alert on the orange alert. I wanted to know if even 1 review item was available, so I made some modifications to the userscript so that it runs on the Review page, and only alerts you when there are reviews that show a positive number.

This is Simon's version, and here is my version:

/** @preserve
// ==UserScript==
// @name Review Queue Notification
// @author Malachi Edited Simon Forsberg Created
// @description Shows a desktop notification when there review items in the queue.
// @namespace https://github.com/Zomis/SE-Scripts
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_notification
// @match *://*.stackexchange.com/review*
// @match *://*.stackoverflow.com/review*
// @match *://*.superuser.com/review*
// @match *://*.serverfault.com/review*
// @match *://*.askubuntu.com/review*
// @match *://*.stackapps.com/review*
// @match *://*.mathoverflow.net/review*
// ==/UserScript==
*/

var KEY_NEXT = 'NextReload';
var DELAY = 60 * 1000; //60,000 milliseconds
var currentTime = Date.now ? Date.now() : new Date().getTime();
var lastTime = GM_getValue(KEY_NEXT, 0);
var nextTime = currentTime + DELAY;
GM_setValue(KEY_NEXT, nextTime);

var timeDiff = Math.abs(lastTime - currentTime);
setTimeout(function(){
    window.location.reload();
}, DELAY);

var title = document.title.split(' - '); // keep the site name
document.title = 'Desktop Notifications - ' + title[1];

// a way to detect that the script is being executed because of an automatic script reload, not by the user.
if (timeDiff <= DELAY * 2) {
    var notifications = [];

    var reviewCount = 0;
    var reviewItems = document.getElementsByClassName('dashboard-num');

    for (var i = 0; i < reviewItems.length; i++){
        reviewCount += parseInt((reviewItems[i].getAttribute("title")).replace(',',''), 10);
        console.log(reviewItems[i]);
    }
    console.log(reviewCount);
    if (reviewCount > 0) {
        notifications.push(reviewCount + ' Review Items');
    }

    if (notifications.length) {
        var details = {
            title: document.title,
            text: notifications.join('\n'),
            timeout: 0
        };
        GM_notification(details, null);
    }
}

This is also available on my GitHub as a userscript.

Follow-up question with new GitHub repo


texts: Highlight strings that match a search term

texts:
I'm writing a ctrl+f function so to speak in React that allows a user to search for a term in a list of words, and if the term matches any of the words in the list then it highlights it. To do this, I'm currently using document.querySelectorAll to retrieve all of the words in the list and manipulate them (highlight) if there is a match. Because this is React I feel very bad about using the querySelector to grab the words and feel I should be using refs perhaps, but not sure how comparable that is or if that works in this particular scenario. Here is my code:

const HighlightSearchTerm = () => {
  const [searchTerm, setSearchTerm] = React.useState("");

  React.useEffect(() => {
    const regex = new RegExp(searchTerm, "gi");
    const labels = document.querySelectorAll(".label"); // use refs??

    labels.forEach(label => {
      label.innerHTML = label.innerText.replace(regex, match =>
        `<span class="highlight">${match}</span>`
      );
    });
  }, [searchTerm]);

  return (
    <div>
      <input
        type="text"
        value={searchTerm}
        placeholder="Search Labels"
        onChange={event => setSearchTerm(event.target.value)}
      />
    </div>
  );
};

As you can see, implementing it this way has to also call document.querySelectorAll each time the user types a letter or makes a change which isn't very efficient and is causing [Violation] 'setTimeout' handler took <N>ms to appear in the console many times when working with large lists. Instead, I would like to

Not use document.querySelectorAll to retrieve the words in the list (use refs if possible?)
Not fetch the list of words each time I type due to the fact the list won't change once the component is rendered (possibly render them when the component mounts, although it seems I can't do this currently when using querySelector)

Any other optimization suggestions would also be very much appreciated.

Current working example: https://codepen.io/andrewgarrison/pen/eYOWjZB


texts: JavaScript - Optimizing a two array.map loop

texts:
I have to iterate two arrays, if the iso propery of the first array is equal to address.country of the second array condition is verified, assign address and slug of the second array (this.concessions) to the first array (this.countries).

at the end, you need to have a new this.countries array that contains theaddress and slug property (in addition to the properties he already had)

this.countries.map((element) => {
  this.concessions.map((value) => {
    if (element.iso === value.address.country) {
      element.address = value.address
      element.slug = value.slug
    }
  })
})

How can I optimize this, and for this case what is the best iterable to use, for ..of for example ?


texts:
I have a function that simply counts the number of files in a directory. To test this function I am using temporary files which are great in the respect that they are deleted upon creating. However, when I want to test my function to count multiple file it can become quite tedious. The below code works but you can probably guess there will be many lines in my test case if i wanted to count say 100 files.

#myfunction

class FileHandler:
    def count_files(output_file_dir):
        return len([f for f in listdir(output_file_dir) if isfile(join(output_file_dir, f))])

#test_myfunction
class FileHandlerTests(unittest.TestCase):
    def test_if_files_exist_return_count_of_those_files(self):
        f= FileHandler
        #test with 1 file
        with tempfile.TemporaryDirectory() as tmpdirname:
            print('created temporary directory\n', tmpdirname)
            with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file:
                print('created temporary file\n', test_file.name)
                self.assertEqual(1,f.count_files(tmpdirname))

        #test with 2 file
        with tempfile.TemporaryDirectory() as tmpdirname:
            print('created temporary directory\n', tmpdirname)
            with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file1:
                print('created temporary file\n', test_file1.name)
                with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file2:
                    print('created temporary file\n', test_file2.name)
                    self.assertEqual(2,f.count_files(tmpdirname))

   #test with 34 file
   with tempfile.TemporaryDirectory() as tmpdirname:
        print('created temporary directory\n', tmpdirname)
        #loop to create 34 temp files?


texts: Traversing and printing complex Dictionary types (Scripting.Dictionary) - Dictionary inside of a Dictionary

texts:
Based on this SO post - also reposted on vba4all.com with a few more details and explanations.

Please notice there currently is no error handling whatsoever as I didn't analyse and consider any traps yet. Although feel free to supply details/code based on your assumptions. For Example - the code fails when you try to load duplicate keys into the dictionary... this can easily be handled with the OERN approach...

So the tree would look like this for example

I have created a simple procedure TraverseDictionary() which traverses any structure of dictionaries.

The simplest version that prints somehow a logical structure to the Immediate Window:

Sub Main()

    Dim dict As New Dictionary
    Dim subDict As New Dictionary
    Dim lvlDict As New Dictionary

    lvlDict.Add "LVL KEY", "LVL ITEM"

    subDict.Add "HELLO", ":)"
    subDict.Add "WORLD", ":("
    subDict.Add "OTHER", lvlDict

    dict.Add "FOO", "BAR"
    dict.Add "BOO", subDict

    TraverseDictionary dict

End Sub

Private Sub TraverseDictionary(d As Dictionary)

    For Each Key In d.Keys
        Debug.Print "KEY: " & Key
        If VarType(d(Key)) = 9 Then
            TraverseDictionary d(Key)
        Else
            Debug.Print "ITEM: " & d(Key)
        End If
    Next
End Sub

with a result:

and w/ a print out to sheet with somehow even more logical view

Private i As Long
Private depth As Long

Sub Main()
Cells.ClearContents

    Dim dict As New Dictionary
    Dim subDict As New Dictionary
    Dim lvlDict As New Dictionary

    lvlDict.Add "LVL KEY", "LVL ITEM"

    subDict.Add "HELLO", ":)"
    subDict.Add "WORLD", ":("
    subDict.Add "OTHER", lvlDict

    dict.Add "FOO", "BAR"
    dict.Add "BOO", subDict

    i = 1
    depth = 0
    TraverseDictionary dict

    Columns.AutoFit

End Sub

Private Sub TraverseDictionary(d As Dictionary)

    For Each Key In d.Keys
        Range("A" & i).Offset(0, depth) = "KEY: " & Key
        If VarType(d(Key)) = 9 Then
            depth = depth + 1
            TraverseDictionary d(Key)
        Else
            Range("B" & i).Offset(0, depth) = "ITEM: " & d(Key)
        End If
        i = i + 1
    Next
End Sub

As mr. Ioannis noticed

  There is a small risk, if an Item of a dictionary is itself an object
  but not a dictionary. Specifically, VarType(d(Key)) = 9 holds true for
  Objects of any kind (I tried it with custom classes and it returned a
  type mismatch error). I would suggest after checking for VarType, also
  checking for dictionary specifically (eg, try to access a property and
  trap the error)

Ok, so currently the code works with the assumption that the Dictionary is actually of VarType = 9 but that breaks because of Objects which also return 9.

If we check TypeName(d(key)) = "Dictionary"  then in theory it should only work with Dictionaries but can you think of any other approaches to actually check & possibly validate the Dictionary.

Side note: In the future I am most likely to create a class wrapper for this and accumulate all the checks in there along with printing at different locations and to different views.


texts:
I've written a simple unconventional calculator application using Python and tkinter. It's unconventional because you use the "modes" (+ - * /) to add to the current sum, instead of entering in a statement and doing that calculation. Because of this, 0 is not included. The main part of my program I would appreciate being reviewed:

Creating The Number Buttons

I absolutely hate large blocks of code that are essentially the same except for one or two things. In this case, it's creating the buttons. I am certain it is possible doing it with a loop, but everything I've attempted has resulted in failure. Everything works as intended, but I'd really appreciate some suggestions pertaining to the number buttons creation. As always, other feedback is welcome and greatly appreciated.

from tkinter import Tk, Label, Button

class Calculator:

    def __init__(self, master: Tk):
        # Initial Setup #
        self.master = master
        self.master.title("Calculator")
        self.master.maxsize(500, 700)

        self.sum = 0
        self.mode = "+"

        # Number Buttons
        self.number_buttons = [
            Button(master, text="1", command=lambda: self.do_math(1)),
            Button(master, text="2", command=lambda: self.do_math(2)),
            Button(master, text="3", command=lambda: self.do_math(3)),
            Button(master, text="4", command=lambda: self.do_math(4)),
            Button(master, text="5", command=lambda: self.do_math(5)),
            Button(master, text="6", command=lambda: self.do_math(6)),
            Button(master, text="7", command=lambda: self.do_math(7)),
            Button(master, text="8", command=lambda: self.do_math(8)),
            Button(master, text="9", command=lambda: self.do_math(9))
        ]

        # Mode Button and Label
        self.mode_label = Label(master, text=f"Mode: {self.mode}")
        self.mode_button = Button(master, text="Change Mode", command=self.change_mode)

        # Sum Label Setup #
        self.sum_label = Label(master, text=str(self.sum))
        self.sum_label.grid(row=1, column=2)

        # Reset Button Setup #
        self.reset_button = Button(master, text="Reset", command=self.reset_sum)

        # Calculate/Set Layout for Buttons #
        r, c = 2, 1
        for number_button in self.number_buttons:
            number_button.configure(width=10, height=10)
            number_button.grid(row=r, column=c)
            if c % 3 == 0:
                r += 1
                c = 0
            c += 1

        # Add Mode Label/Button #
        self.mode_label.grid(row=5, column=2)
        self.mode_button.grid(row=6, column=2)

        # Add Reset Button #
        self.reset_button.grid(row=7, column=2)

    def do_math(self, num: int) -> None:
        """
        Checks the current mode and modifies the sum

        :param num -> int: Button clicked by the user

        :return: None

        """
        modes = {
            "+": self.sum + num,
            "-": self.sum - num,
            "*": self.sum * num,
            "/": self.sum / num
        }
        self.sum = modes[self.mode]
        self.sum_label.configure(text=str(self.sum))

    def change_mode(self) -> None:
        """
        Changes the mode in (+, -, *, /) rotation

        :return: None

        """
        modes = {
            "+": "-",
            "-": "*",
            "*": "/",
            "/": "+"
        }
        self.mode = modes[self.mode]
        self.mode_label.configure(text=f"Mode: {self.mode}")

    def reset_sum(self) -> None:
        """
        Resets the sum

        :return: None

        """
        self.sum = 0
        self.sum_label.configure(text=str(self.sum))

if __name__ == "__main__":
    root = Tk()
    gui = Calculator(root)
    root.resizable(width=False, height=False)
    root.mainloop()


texts: Dropping rows from a PANDAS dataframe where some of the columns have value 0

texts:
I am dropping rows from a PANDAS dataframe when some of its columns have 0 value. I got the output by using the below code, but I hope we can do the same with less code — perhaps in a single line.

df:

    A   B   C
 0  1   2   5
 1  4   4   0
 2  6   8   4
 3  0   4   2

My code:

 drop_A=df.index[df["A"] == 0].tolist()
 drop_B=df.index[df["C"] == 0].tolist()
 c=drop_A+drop_B
 df=df.drop(df.index[c])

[out]

    A   B   C
 0  1   2   5
 2  6   8   4


texts:
Please take a review of my simple bit manipulator:
#ifndef BIT_STREAM_H
#define BIT_STREAM_H

#include <cstdint>

class BitStream {
public:
    explicit BitStream(uint8_t* buffer, size_t buffer_size) : m_Buffer(buffer), m_BufferSize(buffer_size) {

    }

    virtual ~BitStream() = default;

public:
    inline uint64_t Mask(uint64_t offset, size_t size) const {
        return ((1 << size) - 1) << offset;
    }

public:
    inline size_t GetBufferSize() const {
        return m_BufferSize;
    }

    inline size_t GetOffset() const {
        return m_Offset;
    }

    inline bool GetErrorState() const {
        return m_ErrorState;
    }

protected:
    uint8_t* m_Buffer = nullptr;
    size_t m_BufferSize = 0;
    size_t m_Offset = 0;
    bool m_ErrorState = false;
};

class BitReader : public BitStream {
public:
    explicit BitReader(uint8_t* buffer, size_t buffer_size) : BitStream(buffer, buffer_size) {

    }

    template <size_t buffer_size>
    explicit BitReader(uint8_t(&buffer)[buffer_size]) : BitStream(buffer, buffer_size) {

    }

public:
    template<const size_t bit_size, typename value_t = uint64_t>
    inline value_t Read(value_t df = 0) {
        const size_t bpb = 8;
        const size_t byte_offset = m_Offset / bpb;
        const size_t relative_offset = m_Offset - (byte_offset * bpb);

        if (m_ErrorState) {
            return df;
        }

        if (((m_Offset + bit_size) / bpb) >= m_BufferSize) {
            m_ErrorState = true;
            return df;
        }

        m_Offset += bit_size;

        return (*(value_t*)&m_Buffer[byte_offset] & Mask(relative_offset, bit_size)) >> relative_offset;
    }
};

class BitWriter : public BitStream {
public:
    explicit BitWriter(uint8_t* buffer, size_t buffer_size) : BitStream(buffer, buffer_size) {

    }

    template <size_t buffer_size>
    explicit BitWriter(uint8_t(&buffer)[buffer_size]) : BitStream(buffer, buffer_size) {

    }

public:
    template<const size_t bit_size, typename value_t = uint64_t>
    inline void Write(value_t value) {
        const size_t bpb = 8;
        const size_t byte_offset = m_Offset / bpb;
        const size_t relative_offset = m_Offset - (byte_offset * bpb);

        if (m_ErrorState) {
            return;
        }

        if (((m_Offset + bit_size) / bpb) >= m_BufferSize) {
            m_ErrorState = true;
            return;
        }

        m_Offset += bit_size;

        *(value_t*)&m_Buffer[byte_offset] = (*(value_t*)&m_Buffer[byte_offset] & ~Mask(relative_offset, bit_size)) | (value << relative_offset);
    }
};

#endif // BIT_STREAM_H

Example of usage:
#include "BitStream.h"

#include <iostream>
#include <cassert>

int main() {
    uint8_t buffer[2];
    memset(buffer, 0, sizeof(buffer));

    BitWriter writer(buffer);

    writer.Write<4>(15);
    writer.Write<2>(0);
    writer.Write<6>(63);

    assert(!writer.GetErrorState());

    BitReader reader(buffer);

    std::cout << reader.Read<4>() << std::endl;
    std::cout << reader.Read<2>() << std::endl;
    std::cout << reader.Read<6>() << std::endl;

    assert(!reader.GetErrorState());

    std::cin.ignore();
}

Later in plan add exceptions, to string converter method.


texts:
Got this design for getting rid of checking network availability and informing user of errors. Is it good at all? Please, help.

Overall point is to fire server call as short as possible:

new DefaultServerCallTask<LoginResponse>(){

    @Override
    protected void onSuccess(LoginResponse response){
       //go to nextActivity}
    }

    @Override void callServer() throws ConnectionException, InternalServerException, JSONException {
        return ServerApi.login(/*enclosed params from outer variables */);
    }
}.execute();

AsyncResult is a wrapper class, it's main purpose to be returned from AsyncTask.doInBackground.

CheckableResult is an inteface for POJOs, returned from server.

class AsyncResult<T>{

    T mResponse;
    boolean mOk;
    String mErrorMessage;

    T getResponse(){
        return mResponse;
    }

    boolean isOk(){
    return mOk;
}

String getErrorMessage(){
    return mErrorMessage;
}

public AsyncResult (T response){
    mErrorMessage = "";
    mOk = true;
    mResponse = response;
}

public AsyncResult (String errorMessage){
    mErrorMessage = errorMessage;
    mOk = false;
}

}

AbstractServerCallTask handles connection and server-side exceptions^

abstract class AbstractServerCallTask<Result extends CheckableResponse> extends AsyncTask<Void, Void, AsyncResult<Result>>{

@Override
protected AsyncResult<Result> doInBackground(Void... arg0) {
    if (!AppUtils.isNetworkAvailable())
                return new AsyncResult("No network available. Please, check your connection");
    try {
        return new AsyncResult<Result>(callServerMethod());
    } catch (ConnectionException e) {
        return new AsyncResult<Result>("Can't connect to server, chek your network state");
    } catch (InternalServerException e) {
        return new AsyncResult<Result>("Server-side fault. Please, try again later");
    } catch (JSONException e) {
        return new AsyncResult<Result>("Wrong data format. Please try again later");
    }
}

abstract Result callServerMethod() throws ConnectionException, InternalServerException, JSONException ;

@Override
protected void onPostExecute(AsyncResult<Result> asyncResult){
    if (asyncResult.isOk()){
        Result r = asyncResult.getResponse();
        if (r.isOk())
            onSuccess(r);
        else
            onRequestFailed(r); // we got to server, but somehing is wrong
    }
    else
        onError(asyncResult.getErrorMessage());
}
protected abstract void onError(String errorMessage);
protected abstract void onRequestFailed(Result r) ;
protected abstract void onSuccess(Result r);
}

DefaultServerCallTask leaves onSuccess for derived innerclasses to override:

abstract class DefaultServerCallTask<Result extends CheckableResponse> extends AbstractServerCallTask<Result>{

@Override
protected void onError(String errorMessage) {
    AppUtils.showToast(errorMessage);

}

@Override
protected void onRequestFailed(Result r) {
    AppUtils.showToast(r.getErrorMessage()); // show server-side generated message
}
}


texts: Mechanism for providing timeout notifications when traffic ceases

texts:
I'm trying to build a nicely encapsulated mechanism for providing timeouts that wait for a signalling channel to go quiet for a duration. As a fun study of System.Reactive, I decided to base this mechanism on the Observable.Throttle extension method.

Where possible, I hope to avoid using Subjects in my reactive code but I am unfamiliar with which other toys may help me generate this throttled sequence. I often read that Subjects should only be used for example code because they introduce issues where mutable state is exposed and they are a 'lazy', 'non-Reactive' way of generating sequences. I believe I avoid this in an acceptable way. I am unsure if:

this is appropriate or generally acceptable use of subjects
the lifetime management is done correctly
there is a more concise way of achieving all of this

using System;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;

/// <summary>
/// Provides a timeout mechanism that will not timeout if it is signalled often enough
/// </summary>
internal class TrafficTimeout
{
    private readonly Action onTimeout;
    private object signalLock = new object();
    private IObserver<Unit> signals;

    /// <summary>
    /// Initialises a new instance of the <see cref="TrafficTimeout"/> class.
    /// </summary>
    /// <param name="timeout">The duration to wait after receiving signals before timing out.</param>
    /// <param name="onTimeout">The <see cref="Action"/> to perform when the the timeout duration expires.</param>
    public TrafficTimeout(TimeSpan timeout, Action onTimeout)
    {
        // Subscribe to a throttled observable to trigger the expirey
        var messageQueue = new BehaviorSubject<Unit>(Unit.Default);
        IDisposable subscription = null;
        subscription = messageQueue.Throttle(timeout).Subscribe(
        p =>
        {
            messageQueue.OnCompleted();
            messageQueue.Dispose();
            onTimeout();
        });

        this.signals = messageQueue.AsObserver();
        this.onTimeout = onTimeout;
    }

    /// <summary>
    /// Signals that traffic has been received.
    /// </summary>
    public void Signal()
    {
        lock (this.signalLock)
        {
            this.signals.OnNext(Unit.Default);
        }
    }
}

Since creating this question, I've found a bug with this code where calling OnCompleted from within the subcribe callback results in two Unit values being emmited. I am assuming that this is the same signal.


texts: Use given digits and operators to generate an expression that yields a requested value

texts:
The exercise is as follows:

  Given K digits, show all the arithmetic expressions that yield a requested value (N), using four basic arithmetic operations. Each number should be used exactly one time, and the order of the digits may be changed. Don't use parenthesis.

  Example:

    K = 1, 6, 7, 9

    N = 10

    One possible solution: 1 * 7 + 9 - 6

    Another one: 9 + 7 - 6 / 1

My code:

import itertools
from typing import (Sequence, Iterable, Iterator,
                    Union, Optional,
                    List, NamedTuple)

ALLOWED_OPERATORS = ('*', '/', '+', '-')  # , '**)
REPEAT_NUMBERS = False
DigitsSequence = Union[str, Sequence[Union[str, int]]]

class Answer(NamedTuple):
    solution: Optional[int]
    expression: str

def normalize_input(digits: DigitsSequence) -> List[str]:
    try:
        new_digits = list(map(str, digits))  # type: ignore
        if not all(map(str.isdecimal, new_digits)):
            raise TypeError
    except TypeError:
        print("Digits must be an iterable containing strings.")
        return []
    return new_digits

def any_order(items: Sequence, length: int=None, allow_repeats: bool=True) \
              -> Iterable:
    if length is None:
        length = len(items)

    if allow_repeats:
        yield from itertools.product(items, repeat=length)
    else:
        yield from itertools.permutations(items, r=length)

def zip_to_str(expression: Iterable) -> str:
    return ''.join(''.join(i) for i in expression)

def get_answer(digits: List[str], operators: Sequence) -> Answer:
    expression = zip_to_str(zip(digits, operators)) + digits[-1]
    try:
        return Answer(solution=eval(expression), expression=expression)
    except ZeroDivisionError:
        return Answer(solution=None, expression=expression)

def solver(digits: DigitsSequence, solution: int) -> Iterator[str]:
    assert isinstance(solution, int), "Solution must be a number."
    all_digits = normalize_input(digits)

    for operators in any_order(ALLOWED_OPERATORS, length=len(all_digits)-1):
        for digits_option in any_order(all_digits, allow_repeats=REPEAT_NUMBERS):
                answer = get_answer(digits_option, operators)
                if answer.solution == solution:
                    yield answer.expression

if __name__ == '__main__':
    for solution in solver('1679', solution=27):
        print(solution)