texts:
I've written a script to look for coordinates in KMZ files. I've tried to speed execution up using the ProcessPoolExecutor. I'm quite new to Python, so any recommendations are more than welcome.

#!/usr/bin/env python

from zipfile import ZipFile
from lxml import html
import os
import concurrent.futures

def process_file(filename):
    results=[]
    try:
        saved_file=False;
        kmz = ZipFile(filename, 'r')
        for kml_name in kmz.namelist():
            if 'doc.kml' in kml_name:
                continue
            kml = kmz.open(kml_name, 'r').read()
            doc = html.fromstring(kml)
            for pm in doc.cssselect('Document Placemark'):
                tmp = pm.cssselect('track')
                if len(tmp):
                    # Track Placemark
                    tmp = tmp[0]  # always one element by definition
                    for desc in tmp.iterdescendants():
                        content = desc.text_content()
                        if desc.tag == 'coord':
                            lon = float(content.split()[0])
                            lat = float(content.split()[1])
                            search_lon = -47
                            search_lat = 47
                            if (abs(lat - search_lat) <= 1 and abs(lon - search_lon) <= 1):
                                if not saved_file:
                                    results.append('\nFile: ' + filename + '\n')
                                    saved_file=True
                                results.append(content + '\n')
    except:
        pass
    return results

def main():
    # Search all files
    kmz_files = []
    for root, subdirs, files in os.walk('raw/L1B_Catalogue'):
        for file in files:
            if '.kmz' in file:
                filename = os.path.join(root,file)
                kmz_files.append(filename)

    # Parallel execution
    f=open('kmz_search_output.txt', 'wt')
    count = 0
    with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
        for results in executor.map(process_file, kmz_files, chunksize=10):
            print("{} / {}".format(count,len(kmz_files)))
            count = count + 1
            for line in results:
                f.write(line);
            pass
    f.close()
    print('Done')

if __name__ == '__main__':
    main()


texts: Using Python to create a JSON file of recipes from MySQL

texts:
I needed to create a JSON file from a couple of MySQL tables to migrate some recipes from wordpress.
This was my first time writing a script in python and would like to get some feedback on what I could have done better. I come from a Javascript background.

import mysql.connector
import json

cnx = mysql.connector.connect(
    database='somedb', user='root', password='root', host='localhost'
)

cnx1 = mysql.connector.connect(
    database='somedb', user='root', password='root', host='localhost'
)

cursor = cnx.cursor();
cursor1 = cnx1.cursor();

query = "SELECT a.recipe_id, a.recipe_item_type, b.meta_key, b.meta_value, b.recipe_item_id FROM wp_simmer_recipe_items a, wp_simmer_recipe_itemmeta b WHERE a.recipe_item_id = b.recipe_item_id GROUP BY a.recipe_item_id"
query1 = "SELECT * FROM wp_simmer_recipe_itemmeta WHERE recipe_item_id=(%s)"

cursor.execute(query)
rs = cursor.fetchall()

data = {}

for row in rs:
    if row[1] == 'instruction':
        cursor1.execute(query1, (row[4],))
        insD = cursor1.fetchall()
        for instruction in insD:
            if instruction[2] != 'is_heading':
                data.setdefault(row[0], {'instructions':[], 'ingredients': []})['instructions'].append(instruction[3]);
    else:
        cursor1.execute(query1, (row[4],))
        rd = cursor1.fetchall()
        ingredient = {}
        for itemMeta in rd:
            ingredient[itemMeta[2]] = itemMeta[3]
        data.setdefault(row[0], {'ingredients': [], 'instructions': []})['ingredients'].append(ingredient)

with open('data.json', 'w') as outfile:
    json.dump(data, outfile, sort_keys=True, indent=4)

cursor1.close()
cnx1.close()
cursor.close()
cnx.close()


texts:
I'm working on a version of the Unix tail command that works by iterating over a file, pushing line by line into a stack. Finally, the number of desired lines will be popped and printed to the screen. I have used void * (void pointers) as the data field of my stack nodes (the stack is basically a linked list with limitations) and due to that I had to do a bit of work with pointer casting and successive allocations with malloc() (one chunk per line). I wonder if there isn't a better (as in simpler, more readable and less memory intensive) way of accomplishing the same goal.

Main tail.c file

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../utils/type_definitions.h"
#include "../stack/stack_list/stack_list.h"
#define LINE_SIZE 256

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

  int number_of_lines;
  if (argc == 2) {
    number_of_lines = atoi(argv[1]);
  } else {
    printf("%s\n", "Error!");
    exit(1);
  }

  FILE *f;
  if (!(f = fopen("file.txt", "r"))) {
    printf("%s\n", "Error opening file!\n");
    exit(1);
  };

  // pushing lines into stack

  int i = 0;
  char *line, *temp = (char*)malloc(LINE_SIZE);
  Node *stack = stack_new();

  while (fgets(temp, sizeof(line), f) != NULL) {
    line = (char*)malloc(LINE_SIZE);
    strcpy(line, temp);
    stack_push((void*)line, &stack);
  }

  // poping and printing n lines to screen

  for (int i = 0; i < number_of_lines; i++) {
    printf("%s\n",(char*)stack_top(stack));
    stack_pop(&stack);
  }

  return 0;
}

Stack header file

#ifndef __STACK_H__
#define __STACK_H__

#include <stdbool.h>
#include "../../utils/type_definitions.h"

Node *stack_new();
void *stack_top(Node *head);
void stack_pop(Node **head);
bool stack_is_empty(Node *head);
void stack_push(void *x, Node **head);

#endif

Implementation of stack functions

Node *stack_new() {
    return NULL;
}

bool stack_is_empty(Node *head) {
    return head == NULL;
}

void *stack_top(Node *head) {
    return head->data;
}

void stack_pop(Node **head)
{
    if (*head == NULL) return;
    Node *temp = *head;
    *head = (*head)->next;
    free(temp);
}

void stack_push(void *x, Node **head)
{
    Node *new_node = (Node*)malloc(sizeof(Node));
    new_node->data = x;
    new_node->next = *head;
    *head = new_node;
}

Edit - following are the includes missing from the file "implementations of stack functions".

#include "stack_list.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>


texts:
Here is one of my programs that utilized memoization and array to improve performance and memory usage. The performance seems satisfactory but the memory usage is ridiculous and I can't figure out what's wrong:

{-# LANGUAGE BangPatterns #-}
import Data.Functor
import Data.Array (Array)
import qualified Data.Array as Arr
import Control.DeepSeq

genColtzArr n = collatzArr
    where collatzArr = Arr.array (1, n) $ take n $ map (\v -> (v, collatz v 0)) [1..]
          collatz 1 !acc  = 1 + acc
          collatz !m !acc
              | even m    = go (m `div` 2) acc
              | otherwise = go (3 * m + 1) acc
              where go !l !acc
                      | l <= n    = let !v = collatzArr Arr.! l in 1 + acc + v
                      | otherwise = collatz l $ 1 + acc

collatz here means this guy. This function is supposed to receive a number n, and then return an array indexing from 1 to n, and in which each cell contains the length of the link from the index to 1 by applying Collatz formula.

But the memory usage of this method is so high. Here is the profiler result (ghc option -prof -fprof-auto -rtsopts, run time option +RTS -p, n == 500000):

total alloc = 730,636,136 bytes  (excludes profiling overheads)

COST CENTRE              MODULE  %time %alloc

genColtzArr.collatz      Main     40.4   34.7
genColtzArr.collatz.go   Main     25.5   14.4

COST CENTRE                      MODULE                    no.     entries  %time %alloc   %time %alloc

      genColtzArr                Main                      105           1    0.0    0.0    74.7   72.1
       genColtzArr.collatzArr    Main                      106           1    8.0   20.8    74.7   72.1
        genColtzArr.collatzArr.\ Main                      107      500000    0.9    2.2    66.8   51.3
         genColtzArr.collatz     Main                      109     1182582   40.4   34.7    65.9   49.1
          genColtzArr.collatz.go Main                      110     1182581   25.5   14.4    25.5   14.4

Please note that -O2 is not a desired answer. I want to figure out what's the problem in this program and in general, how should I spot time and memory inefficiencies in Haskell code.  Specifically, I have no idea why this code, with tail recursion and bang pattern, can consume so much memory.

UPDATE1:

the same code with -s produces this:

   1,347,869,264 bytes allocated in the heap
     595,901,528 bytes copied during GC
     172,105,056 bytes maximum residency (7 sample(s))
         897,704 bytes maximum slop
             315 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0      2408 colls,     0 par    0.412s   0.427s     0.0002s    0.0075s
  Gen  1         7 colls,     0 par    0.440s   0.531s     0.0759s    0.1835s

  INIT    time    0.000s  (  0.000s elapsed)
  MUT     time    0.828s  (  0.816s elapsed)
  GC      time    0.852s  (  0.958s elapsed)
  RP      time    0.000s  (  0.000s elapsed)
  PROF    time    0.000s  (  0.000s elapsed)
  EXIT    time    0.004s  (  0.017s elapsed)
  Total   time    1.684s  (  1.791s elapsed)

  %GC     time      50.6%  (53.5% elapsed)

  Alloc rate    1,627,861,429 bytes per MUT second

  Productivity  49.4% of total user, 46.4% of total elapsed

so it takes 300 meg. that is still too large.


texts: Case insensitive string to replace custom comparers

texts:
In some solutions I use case-insensitive strings a lot and so far I've been always writing custom collections or using custom comparers to support them. This is usually a lot of work and a lot of testing so I thought what if the string was case-insensitive instead?

The implementation is really simple because the CaseInsensitiveString is just a wrapper for a string that is using the StringComparer.OrdinalIgnoreCase comparer internally. Can you think of any improvements? I use it for hash-sets or dictionaries or anything else that might require case insensitive strings.

public class CaseInsensitiveString : IEquatable<CaseInsensitiveString>, IEquatable<string>
{
    private readonly string value;

    public CaseInsensitiveString() { }

    public CaseInsensitiveString(string value)
    {
        this.value = value;
    }

    private CaseInsensitiveString(CaseInsensitiveString other)
    {
        value = other?.value;
    }

    public static CaseInsensitiveString Empty => new CaseInsensitiveString(string.Empty);

    public override int GetHashCode()
    {
        return StringComparer.OrdinalIgnoreCase.GetHashCode(value);
    }

    public override bool Equals(object obj)
    {
        return
            (obj is CaseInsensitiveString cis && Equals(cis)) ||
            (obj is string s && Equals(s));
    }

    public bool Equals(CaseInsensitiveString other)
    {
        if (ReferenceEquals(other, null)) return false;
        return ReferenceEquals(this, other) || Equals(other.value);
    }

    public bool Equals(string other)
    {
        return StringComparer.OrdinalIgnoreCase.Equals(value, other);
    }

    public static implicit operator string(CaseInsensitiveString obj) => obj.value;

    public static implicit operator CaseInsensitiveString(string value) => new CaseInsensitiveString(value);

    public static bool operator ==(CaseInsensitiveString left, CaseInsensitiveString right) => new CaseInsensitiveString(left).Equals(right);

    public static bool operator !=(CaseInsensitiveString left, CaseInsensitiveString right) => !(left == right);
}

Example usage:

var set = new HashSet<CaseInsensitiveString>();
set.Add("foo").Dump(); // true
set.Add("fOo").Dump(); // false

var s = (CaseInsensitiveString)"foo";
(s == "foo").Dump(); // true
(s == "fOo").Dump(); // true


texts: Prompt user for some numbers, then print the max and min

texts:
The function of this program is repeatedly prompting a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. Suppose all input is proper, so we do not need to check whether the input value is illegal or not.

largest = None
smallest = None

while True :
    num = raw_input("Enter a number: ")
    if num == "done" :
        break
    try :
        num = int(num)
    except :
        print "Invalid input"
        continue
    if largest is None :
        largest = num
    elif largest < num :
        largest = num
    if smallest is None :
        smallest = num
    elif num < smallest :
        smallest = num

print "Maximum is", largest
print "Minimum is", smallest


texts: Simple JS validation for two contact forms

texts:
I'm not a pro in js so, my code is a mess (but it's working!). I would like to ask your help to reduce some redundancies in two cases. Those two are codes are affecting these two forms:

<form action="contact.php" method="post" name="form1" onsubmit="return validateForm1()">
    <input type="text" name="name" id="inputName1" placeholder="Name">
    <input type="text" name="tel" id="inputTel1" placeholder="Telephone Number">
    <input type="text" name="address" id="inputAdr1" placeholder="Address">
    <input type="text" name="topic" id="inputTop1" placeholder="Topic">
    <input type="email" name="email" id="inputMail1" placeholder="E-mail">
    <input type="email" id="inputConfirmMail1" onblur="mailConfirm1()" placeholder="Confirm E-mail">
    <input type="submit" value="Send">
</form>

<form action="contact.php" method="post" name="form2" onsubmit="return validateForm2()">
    <input type="text" name="name" id="inputName2" placeholder="Name">
    <input type="text" name="tel" id="inputTel2" placeholder="Telephone Number">
    <input type="text" name="address" id="inputAdr2" placeholder="Address">
    <input type="text" name="topic" id="inputTop2" placeholder="Topic">
    <input type="email" name="email" id="inputMail2" placeholder="E-mail">
    <input type="email" id="inputConfirmMail2" onblur="mailConfirm2()" placeholder="Confirm E-mail">
    <input type="submit" value="Send">
</form>

FIRST (a function to prevent my two forms to have empty inputs before submission)

function validateForm1() {
    var c = document.forms["form1"]["name"].value;
    var d = document.forms["form1"]["tel"].value;
    var e = document.forms["form1"]["address"].value;
    var f = document.forms["form1"]["topic"].value;
    var g = document.forms["form1"]["email"].value;
    if (c == null || c == "") {
            alert("insert your name");
            return false;
        }
        else if (d == null || d == "") {
            alert("insert your telephone");
            return false;
        }
        else if (e == null || e == "") {
            alert("insert your address");
            return false;
        }
        else if (f == null || f == "") {
            alert("insert a topic");
            return false;
        }
        else if (g == null || g == "") {
            alert("insert your email");
            return false;
        }
    }
    function validateForm2() {
        var c = document.forms["form2"]["name"].value;
        var d = document.forms["form2"]["tel"].value;
        var e = document.forms["form2"]["address"].value;
        var f = document.forms["form2"]["topic"].value;
        var g = document.forms["form2"]["email"].value;
        if (c == null || c == "") {
            alert("insert your name");
            return false;
        }
        else if (d == null || d == "") {
            alert("insert your telephone");
            return false;
        }
        else if (e == null || e == "") {
            alert("insert your address");
            return false;
        }
        else if (f == null || f == "") {
            alert("insert a topic");
            return false;
        }
        else if (g == null || g == "") {
            alert("insert your email");
            return false;
        }
    }

SECOND (I have a "confirm your email" area in my form so I did this function to make sure the user inputs the same value in both areas)

function mailConfirm1() {
    var mail1 = document.getElementById("inputMail1").value;
    var conMail1 = document.getElementById("inputConfirmMail1").value;
    if(mail1 != conMail1) {
        alert('both emails are not the same');
    }
}
function mailConfirm2() {
    var mail2 = document.getElementById("inputMail2").value;
    var conMail2 = document.getElementById("inputConfirmMail2").value;
    if(mail2 != conMail2) {
        alert('both emails are not the same');
    }
}


texts: Mailmerge from Excel to premade template in Word

texts:
I've written the following code to take data from the Excel file "Data" and use it for a mailmerge in a prepare Word template named "Template." I'm new to using VBA in word or Access, so any feedback in these areas is very welcome

Sub AccessTransfer()

Dim strPath As String
Dim objAccess As Access.Application
Dim strExcelPath As String
Dim lastRow As Long
lastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).row
Dim rng As Range
Set rng = Sheets("Data").Range("A" & lastRow, "M" & lastRow)
strPath = "L:\...\MailMergeTEMPDB.accdb"
Set objAccess = CreateObject("Access.Application")
Call objAccess.NewCurrentDatabase(strPath)
objAccess.Visible = False
strExcelPath = Application.ActiveWorkbook.FullName
Set objAccess = New Access.Application
Call objAccess.OpenCurrentDatabase(strPath, False)
objAccess.Visible = False
Call objAccess.DoCmd.TransferSpreadsheet(acImport, _
acSpreadsheetTypeExcel8, "MailMergeTable", strExcelPath, _
True, Range:="Data!")
Access.Application.CloseCurrentDatabase

Dim wdApp As Object, newDoc As Object
    Dim strFile As String
    strFile = "L:\...Template.docm"
    Set wdApp = CreateObject("Word.Application")
    wdApp.Documents.Open strFile, ReadOnly:=False
    wdApp.Visible = True
    wdApp.Run "Project.Module1.WordMailMerge"
    Kill "L:\....MailMergeTEMPDB.accdb"
End Sub

And then Macro called from within Word is:

Sub WordMailMerge()
Dim strFile As String
strFile = "L:\...MailMergeTEMPDB.accdb"
    ActiveDocument.MailMerge.OpenDataSource Name:= _
        strFile _
        , ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
        AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
        WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
        Format:=wdOpenFormatAuto, Connection:= _
        "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=strFile;Mode=Read;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path=""""" _
        , SQLStatement:="SELECT * FROM `MailMergeTable`", SQLStatement1:="", _
        SubType:=wdMergeSubTypeAccess
    With ActiveDocument.MailMerge
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
        .Execute Pause:=False
    End With
    Windows("AH_MacroMailMergeTemplate").Activate
    ActiveDocument.Close
End Sub

I'm also new to using VBA to navigate trough directories, so feedback in this aspect would be appreciated too.


texts:
This is my implementation of a binary tree in Scala. How can this be made better?

abstract class BinaryTreeNode[+A]

case class MyBinaryTreeNode[A](var data: A,var left: BinaryTreeNode[A],var right: BinaryTreeNode[A]) (implicit ordering: Ordering[A]) extends BinaryTreeNode[A] {

    override def toString = data + " " + left.toString + " " + right.toString
}

case object MyNilNode extends BinaryTreeNode[Nothing]

class MyBinaryTree[A](var head: BinaryTreeNode[A]) {

    def isBST(implicit order: Ordering[A]): Boolean = {
        this.isBSTHelper(head)._1
    }

    def isBSTHelper(node: BinaryTreeNode[A])(implicit order: Ordering[A]): (Boolean, A, A) = {
        node match {
            case MyNilNode =>
                return (true, null.asInstanceOf[A], null.asInstanceOf[A])
            case MyBinaryTreeNode(data, lNode, rNode) =>
                if(lNode == MyNilNode && rNode == MyNilNode) {
                    return (true, data, data)
                }

                val leftResult = this.isBSTHelper(lNode)(order)
                val rightResult = this.isBSTHelper(rNode)(order)
                return (leftResult._1 && rightResult._1 && data >= leftResult._3 && data <= rightResult._2,
                        leftResult._2,
                        rightResult._3)
        }
    }
}


texts:
This is one of the (many) utilitarian classes I have that I use with my ASP.NET sites.

The basis of this one is to make gathering certain tokens that I use periodically, to make URL's more friendly.

It's pretty simple, and should be quite obvious. I use it to make URL's a little more friendly. (/Id/SomeKey/SomeValue/OtherKey/OtherValue/) It returns Id and creates a dictionary for the remaining pairs of Key and Value.

public class RouteUtilities
{
    public static Dictionary<string, string> GetRouteKeyValuePairs(RouteValueDictionary dataTokens, int startIndex)
    {
        Dictionary<string, string> routeItems = new Dictionary<string, string>();
        List<string> segments = GetRouteSegments(dataTokens);

        for (int i = startIndex; i < segments.Count; i += 2)
        {
            routeItems.Add(segments[i], segments[i + 1]);
        }

        return routeItems;
    }

    public static List<string> GetRouteSegments(RouteValueDictionary dataTokens) => (List<string>)dataTokens["FriendlyUrlSegments"];

    public static bool GetIdAndKeys(RouteValueDictionary dataTokens, out int id, out Dictionary<string, string> keys)
    {
        if (dataTokens.Count > 0)
        {
            Dictionary<string, string> routeItems = GetRouteKeyValuePairs(dataTokens, 1);
            List<string> routeSegments = GetRouteSegments(dataTokens);

            if (routeSegments.Count > 0)
            {
                id = Convert.ToInt32(routeSegments[0]);
                keys = GetRouteKeyValuePairs(dataTokens, 1);
                return true;
            }
        }

        id = 0;
        keys = null;
        return false;
    }
}


texts:
There is a clear pattern as to what the number values would be. And this has a starting interval and known start and end value. Though the end may change, it seems simpler to set the values and do some magical loop. Any better formats would be appreciated. The sets are what I would have gone with if I could have gotten the loop to work correctly.

<?php
$setStart =5000;
$setEnd = 95000;
$setInterval = 5000;

    //Enter your code here, enjoy!

    foreach($zips as $zipcode) {
    $zip = $zipcode['zip'];
    $zipInt = intval($zipcode['zip']);
    $org_ids = $zipcode['orgs'];
    $org_ids = explode(",",$org_ids);
    if (!empty($org_ids)) {
        if ($zipInt < 5000) {
            $zips00_array[$zip] = $org_ids;
        }
        if ($zipInt >= 5000 && $zipInt < 10000) {
            $zips05_array[$zip] = $org_ids;
        }
        if ($zipInt >= 10000 && $zipInt < 15000) {
            $zips10_array[$zip] = $org_ids;
        }
        if ($zipInt >= 15000 && $zipInt < 20000) {
            $zips15_array[$zip] = $org_ids;
        }
        if ($zipInt >= 20000 && $zipInt < 25000) {
            $zips20_array[$zip] = $org_ids;
        }
        if ($zipInt >= 25000 && $zipInt< 30000) {
            $zips25_array[$zip] = $org_ids;
        }
        if ($zipInt >= 30000 && $zipInt < 35000) {
            $zips30_array[$zip] = $org_ids;
        }
        if ($zipInt >= 35000 && $zipInt < 40000) {
            $zips35_array[$zip] = $org_ids;
        }
        if ($zipInt >= 40000 && $zipInt < 45000) {
            $zips40_array[$zip] = $org_ids;
        }
        if ($zipInt >= 45000 && $zipInt < 50000) {
            $zips45_array[$zip] = $org_ids;
        }
        if ($zipInt >= 50000 && $zipInt < 55000) {
            $zips50_array[$zip] = $org_ids;
        }
        if ($zipInt >= 55000 && $zipInt < 60000) {
            $zips55_array[$zip] = $org_ids;
        }
        if ($zipInt >= 60000 && $zipInt < 65000) {
            $zips60_array[$zip] = $org_ids;
        }
        if ($zipInt >= 65000 && $zipInt < 70000) {
            $zips65_array[$zip] = $org_ids;
        }
        if ($zipInt >= 70000 && $zipInt < 75000) {
            $zips70_array[$zip] = $org_ids;
        }
        if ($zipInt >= 75000 && $zipInt < 80000) {
            $zips75_array[$zip] = $org_ids;
        }
        if ($zipInt >= 80000 && $zipInt < 85000) {
            $zips80_array[$zip] = $org_ids;
        }
        if ($zipInt >= 85000 && $zipInt < 90000) {
            $zips85_array[$zip] = $org_ids;
        }
        if ($zipInt >= 90000 && $zipInt < 95000) {
            $zips90_array[$zip] = $org_ids;
        }
        if ($zipInt >= 95000) {
            $zips95_array[$zip] = $org_ids;
        }
    }
}


texts: Connecting and getting mysql connection object

texts:
I have written this code that connects to a mysql database. The function should be able to be used as a context manager - via with. It is working, but I am not sure if this is a great way of doing it.

conect.py

import os
import mysql.connector
from mysql.connector import errorcode
import contextlib

_CFG = {
  'user': os.getenv("MYSQL_USER"),
  'password': os.getenv("MYSQL_PASSWORD"),
  'host': os.getenv("MYSQL_SERVER"),
  'database': os.getenv("SENSOR_DB"),
  'raise_on_warnings': True
}

@contextlib.contextmanager
def _connect(db=None):
    if db:
        _CFG["database"] = db

    try:
        print("{usr} connecting to {db} on {host}.".format(
            usr=_CFG["user"],
            db=_CFG["database"],
            host=_CFG["host"]
            )
        )
        connection = mysql.connector.connect(**_CFG)
        yield connection
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(err)
        yield None
    else:
        connection.commit()
    finally:
        connection.close()


texts:
Since I didn't find a way to properly transform JavaScript object to JSON with PHP, I wrote a snippet.

Lets assume the following excerpt from Google Fonts JavaScript API:

WebFontConfig = {
    google: { families: [ 'Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic,700italic:latin,latin-ext' ] }
};

This, given straight to PHP's json_decode will null out and JSONLint will say it's invalid.

Since I need this data in JSON after the template has been parsed (working on an exporter), I wrote this snippet (which double-quotes the hell out of this one):

// gather WebFontConfig arrays
$webfonts = preg_match_all('/(WebFontConfig\s*?=\s*?)\{(.+?)(\};)/s', $scriptData, $fontdata, PREG_SET_ORDER);

// kids, dont do this at home
foreach ($fontdata as $founddata)
{
    $original = $founddata[0];

    $WFCVariable = $founddata[1];

    // leave outer braces only
    $usable = str_replace($WFCVariable, '', $original);
    $usable = trim($usable, ';');

    // transform keys into double-quoted keys
    $usable = preg_replace('/(\w+)(:\s*?)(\{|\[)/im', '"$1"$2$3', $usable);

    // prepare to transform array wrapping single quotes to double quotes
    $lookups = array(
        '/(\[)(\s*?)(\')/',
        '/(\')(\s*?)(\])/'
    );

    $replace = array(
        '$1$2"',
        '"$2$3'
    );

    $usable = preg_replace($lookups, $replace, $usable);

    // decode
    $jsoned = json_decode($usable);

    // and check
    var_dump($jsoned);
}

$scriptData essentially is the above JavaScript object trim-extracted out of my template through DOMDocument .. DOMNode->nodeValue.

There is no problem with the snippet, it converts my data into PHP array without problems.

My concern, though, is, whether this is the most optimal way of doing it?


texts: Rails guestbook with new, index, and Kaminari pagination in the same method

texts:
I created a guestbook that on one page displays both the form for a new entry and all of the entries that have been created so far.

I am trying to use Kaminari for pagination for the entries.

Right now this code is working on my local machine, but I just have that feeling that it could be improved/refactored, so I wanted to post it here for people's opinions.

My controller:

class GuestbooksController < ApplicationController
    def index
        @guestbooks = Guestbook.all
    end

    def new
        @guestbook = Guestbook.new
        @guestbooks = Guestbook.all
        @guestbooks = Kaminari.paginate_array(@guestbooks).page(params[:page]).per(5)
    end

    def create
        @guestbook = Guestbook.new(guestbook_params)
        @guestbooks = Guestbook.all
        @guestbooks = Kaminari.paginate_array(@guestbooks).page(params[:page]).per(5)

        if @guestbook.save
            flash.now[:notice] = "Thanks for taking the time to write us! We greatly appreciate it!"
            render :new
        else
            flash.now[:notice] = "Your message failed to post, please try again"
            render :new
        end
    end

    private
    def guestbook_params
        params.require(:guestbook).permit(:name, :email, :message)
    end
end

new.html.erb template:

    <%=paginate @guestbooks%>

    <% @guestbooks.each do |g| %>

<%= g.name %>, <%= g.created_at %>

        <%= g.message %>

-----------------------------------------------------------------------------------------------------------------------

    <% end %>

<%= simple_form_for @guestbook, url: guestbooks_path, method: :post do |f| %>

<%= f.input :name %>

<%= f.input :email %>

<%= f.input :message %>

<%= f.button :submit %>

<% end %>

Routes:

 resources :guestbooks, only: [:new, :create]
  get "/guestbooks/index", to: "guestbooks#index"

Now I know my routes file could look like this

resources :guestbooks, only: [:new, :create, :index]

but then my paths look strange:

        guestbooks GET  /guestbooks(.:format)             guestbooks#index
                   POST /guestbooks(.:format)             guestbooks#create
     new_guestbook GET  /guestbooks/new(.:format)         guestbooks#new


texts: One-dimensional circular Conway's Game of Life

texts:
I have a program that is working, but it takes way too long to get the answer. With input like

15 100000000
111010111001100

The program checks for 15 numbers, and checks if two number beside the numbers in the second row adds up to exactly 1. If it adds up to 1, then the number would stay/change to 1, otherwise it change/stay 0. And this need to happen for 100000000 times (it changes each time). Right now I can get the right answer, but it takes like 1 minute to get it.

import java.util.*;
public class circle {
final Scanner in;
public circle()
{
   in=new Scanner(System.in);
   run();
   in.close();
}
public void run()
{
   String input=in.nextLine();
   //I created two arrays, checks for one array while change the other one so the changed number wouldn't affect other checking
   final int[] list=createarray(input);
   final int totalcells=list[0];
   final int generation=list[1];
   String input1=in.nextLine();
   long[] deadalive=createarray2(input1,totalcells);
   long[] changing=new long[totalcells];
   System.arraycopy(deadalive,0,changing,0,totalcells);
   //It checks for y times and checks all the cells
   for(int y=0;y<generation;y++)
   {
       for(int x=0;x<totalcells;x++)
       {
           if(x==0)
           {
               if(deadalive[x+1]+deadalive[totalcells-1]==1)
               {
                changing[x]=1;
               }
               else
                   changing[x]=0;

           }
           else if(x==totalcells-1)
           {

                   if(deadalive[x-1]+deadalive[0]==1)
                   {
                       changing[x]=1;
                   }
                   else
                       changing[x]=0;
           }
           else
           {
                   if(deadalive[x-1]+deadalive[x+1]==1)
                   {
                       changing[x]=1;
                   }
                   else
                       changing[x]=0;
           }
       }
       //make two arrays the same after each changes
       System. arraycopy(changing, 0, dead alive, 0, changing.length);

   }
   System.out.println(java.util.Arrays.toString(changing));

}
private static int[] createarray(String input)
{
   final String[] args=input.trim().split("\\s+");
    final int aray[]=new int[2];
    for(int i=0;i<2;i++)
    {
        aray[i]=Integer.parseInt(args[i]);
    }
    return aray;
}
private static long[] createarray2(String input1,int totalcells)
{
   final long array[]=new long[totalcells];
    for(int i=0;i<input1.length();i++)
    {
        array[i]=Character.digit(input1. charAt(i),10);
    }
    return array;
}
public static void main(String args[])
{
   new circle();
}
}

This code is supposed to change the second row of numbers like input:

7 1
0000001

Output would be:

1000010

0 changes to 1 if the two "neighbor" adds up to 1 exactly. other wise they are 0, but this one only runs for one time unit, where there are ones that needs to run 10000000 time units. For loop probably isn't efficient enough to do it in a short time period, so I thought maybe there are better ways to do it.


texts: Printing JUnit test results in file by changing and using the 'out' static variable of 'System' class

texts:
I'm building a framework for comparing files (in my own way) using JUnit. All test cases have been packaged in a JAR which is ran independently using a .bat file I wrote. I needed to output the test results in a file instead of the console.

I was just using normal System.out.println() in the TestRunner class and also in the various test case classes for printing the output on the console.

I found a solution that I could use in the project (Method number 3 of this article).  I redirected the output stream to my output file. Following is the relevant code from the TestRunner class:

public class TestRunner {

    public static void main(String[] args) {
        System.out.println("Testing Started...");

        // Save the System.out instance
        PrintStream oldPrintStream = System.out;

        FileOutputStream outFile = null;

        try {

            outFile = new FileOutputStream("result.txt");

            PrintStream newPrintStream = new PrintStream(outFile);
            System.setOut(newPrintStream);

            Result result = JUnitCore.runClasses(TestSuite.class);

            // Print the results in desired format

        } catch (FileNotFoundException ex) {
            Logger.getLogger(TestRunner.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            // Reset the old System.out instance
            System.setOut(oldPrintStream);
            System.out.println("Testing Completed! Check output folder for result.");

            try {
                outFile.close();
            } catch (IOException ex) {
                Logger.getLogger(TestRunner.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

The code is working fine but is it the correct way to do this?


texts:
To learn Rust, I tried to write a function that takes two sorted arrays of integers and interleaves them into one longer sorted array.

Is this approach ok? Have I made any mistakes?

fn main() {
    let a = [1, 3, 4, 4];
    let b = [0, 2, 5, 6];
    println!("{:?}", merge(&a, &b));
}

fn merge(list_a : &[i32; 4], list_b : &[i32; 4]) -> [i32; 8] {
    let mut merged_list: [i32; 8] = [0; 8];

    let mut idx = 0;
    let mut idx_b = 0;
    for a in list_a.iter() {
        while idx_b < list_b.len() && list_b[idx_b] < *a {
            merged_list[idx] = list_b[idx_b];
            idx_b +=1;
            idx += 1;
        }
        merged_list[idx] = *a;
        idx += 1;
    }

    for b in list_b[idx_b..].iter() {
        merged_list[idx] = *b;
        idx += 1;
    }
    println!("{:?}", merged_list);
    merged_list
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_merge() {
        let a = [1, 3, 3, 7];
        let b = [0, 4, 6, 8];
        assert_eq!(merge(&a, &b), [0, 1, 3, 3, 4, 6, 7, 8]);
    }
}


texts: Replace string of class of button by class so that only one button is filled in using bootstrap buttons

texts:
I'm using bootstrap buttons, and in this case I have 5 different buttons with 5 different classes. When one of the buttons is clicked on, I want it to be the only one filled in, and the others to only be the outline. Here is how I currently do it:

$(".canvas_btn").on("click",function(){
  for(var i = 0; i < $(".canvas_btn").length; i++){
    document.getElementById($(".canvas_btn")[i].id).className = document.getElementById($(".canvas_btn")[i].id).className.replace("btn-outline-","btn-");
    document.getElementById($(".canvas_btn")[i].id).className = document.getElementById($(".canvas_btn")[i].id).className.replace("btn-","btn-outline-");
  }
  document.getElementById(this.id).className = document.getElementById(this.id).className.replace("btn-outline","btn");
});
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-outline-info     canvas_btn" align="left"  id="new_text_btn">Text</button>
<button class="btn btn-outline-secondary  canvas_btn" align="left"  id="new_audio_btn">Audio</button>
<button class="btn btn-outline-success   canvas_btn" align="left"  id="new_image_btn">Image</button>
<button class="btn btn-outline-danger   canvas_btn" align="left"  id="new_video_btn">Video</button>
<button class="btn btn-outline-warning   canvas_btn" align="left"  id="new_input_btn">Input</button>

It feels a bit odd the way I've done it - is there a more elegant way to do it? A way to use jQuery to make it tidier would be great!

I'm also not sure how I'm causing the error in the console - I think it's to do with the bootstrap script I call in, so don't know what I can do about that.


texts:
I'm new to front-end development and now I'm learning JavaScript with jQuery.
I couldn't understand JavaScript's classes and objects and jQuery plugins, but after reading some articles and examples I wrote simple notifications system.

(function ($) {
    var notification = function (title, msg, duration) {
        var self = this;

        this.hide = function () {
            self.element.fadeOut(1000, function () {
                self.element.remove();
            })
        }

        this.element = $('

' + title + '

' + msg + '
(double click to hide)

');
        this.element.dblclick(self.hide);

        if (duration !== undefined) {
            setTimeout(function () {
                self.hide();
            }, duration * 1000);
        }

        $('#notifications_bar').prepend(this.element.hide().fadeIn(1000));
    };
    $.extend({
        notify:function (title, msg, duration) {
            return new notification(title, msg, duration);
        }
    });

Example:

$(function() {
    $.notify('Title', 'Message'); // sticky note
    $.notify('Title', 'Message', 2); // 2-seconds notification
});

The most terrible were closures and this keyword. I couldn't understand how to use them, so I want to know if there in my code above 'bad-practice' parts.


texts:
I have code which is matching features within regions. The first thing it does it matches features from one region to an entire database of region features.

I have a mapping from query feature index (qfx) into database feature index (ax).
A database feature index has associated with it a region id (rid), region feature index (fx), feature score (fs), and feature rank (fk).
There is also a flag marking each of those mappings as valid or invalid.

The problem is that I want to go from this mapping of query_feature_index-to-database_feature_index (qfx2_ax) into a mapping from region_index-to-feature_match (rid2_fm, rid2_fs, and rid2_fk)

I have the following code which does this (cleaned up just a little bit for clarity). On the left hand side is the rough percentage of time each step takes. The bulk of the time seems to be eaten up by appending to the lists in the default dictionaries.

  0.0      for qrid in qrid2_nns.iterkeys():
  0.0          (qfx2_ax, _) = qrid2_nns[qrid]
  0.0          (qfx2_fs, qfx2_valid) = qrid2_nnfilt[qrid]
  0.0          nQKpts = len(qfx2_ax)
               # Build feature matches
  0.0          qfx2_nnax = qfx2_ax[:, 0:K]
  0.4          qfx2_rid  = ax2_rid[qfx2_nnax]
  0.5          qfx2_fx   = ax2_fx[qfx2_nnax]
  0.2          qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T
  0.1          qfx2_k   = np.tile(np.arange(K), (nQKpts, 1))
               # Pack valid feature matches into an interator
  0.4          valid_lists = [qfx2_[qfx2_valid] for qfx2_ in (qfx2_qfx, qfx2_rid, qfx2_fx, qfx2_fs, qfx2_k,)]
  0.0          match_iter = izip(*valid_lists)
  0.0          rid2_fm = defaultdict(list)
  0.0          rid2_fs = defaultdict(list)
  0.0          rid2_fk = defaultdict(list)
               # This creates the mapping I want. Can it go faster?
 19.3          for qfx, rid, fx, fs, fk in match_iter:
 17.2              rid2_fm[rid].append((qfx, fx))
 17.0              rid2_fs[rid].append(fs)
 16.2              rid2_fk[rid].append(fk)

My gut feeling is that I could pass over the data twice, first counting the number of entries per region, then allocating lists of that size, and then populating them, but I'm afraid that indexing into python lists might take a comparable amount of time.

Then I was thinking I could do it with list comprehensions and build a list of (qfx, fx, fs, and fk), but then I'd have to unpack them, and I'm unsure about how long that will take.

It seems to me that I can't get much better than this, but maybe someone out there knows something I don't. Maybe there is a numpy routine I'm unaware of?

I'm more looking for guidance and insights than anything else before I start coding up alternatives.


texts: BTC price checker with web scraping, regex and Tkinter GUI

texts:
The purpose of this was to practice web scraping, regex and GUI. I use a popular bitcoin website to scrape the names and prices of the top 16 cryptocurrencies. I then create a data frame and make a GUI to display the information based on the user's selection. I am looking for any and all input on how to improve this code.

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import pandas as pd

my_url = 'https://coinmarketcap.com/'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")

containers = page_soup.find("div", {"class": "container main-section"})
tabes = containers.find("table", {"id": "currencies"})
table_names= tabes.find("tbody")

btc = table_names.find_all("tr")

#Get the names and prices of the first 16 crypto coins
prices = []
names = []

for i in range(16):
    x = btc[i]

    #find the price
    x.find("a", {"class": "price"}).text
    current_price = x.find("a", {"class": "price"}).text.strip()
    prices.append(current_price)

    #find the name of the crypto
    name = x.find("td", {"class": "no-wrap currency-name"})
    q = name.text.strip()
    coin_name = " ".join(q.split("\n"))
    names.append(coin_name)

#Make a dataframe with the information we have gathered
df = pd.DataFrame({'Name': names,
                   'Price': prices,
                   })

#Use regular expressions to create a column with just the symbol
import re

symbols = []

for i in df['Name']:
    symbols.append(re.search(r"[A-Z]{3,5}\s\s", i).group().split()[0])

df['Symbol'] = symbols

#GUI
from tkinter import *

root = Tk()
root.title('BTC Price Check')
root.geometry('{}x{}'.format(950, 550))

frame = Frame(root,relief= GROOVE)
frame.pack(side = BOTTOM)

class CheckBox(Checkbutton):
    boxes = []  # Storage for all buttons
    def __init__(self, master=None, **options):
        Checkbutton.__init__(self, frame, options)
        self.boxes.append(self)
        self.var = IntVar()
        self.configure(variable=self.var)

header = Label(height=1, width=100, text = "Welcome to BTC Price Check")
header.config(font=("Courier", 20))
header.pack(side = TOP, pady = 0)

text = Text(frame)
text.pack(padx = 20, pady = 0, side = RIGHT)

#fucntions for our buttons
def display_price():
    for c, box in enumerate(CheckBox.boxes):
        if box.var.get():
            text.insert(INSERT, "The price of " + names[c] + " is: " + prices[c])
            text.insert(INSERT, "\n")
    text.config(state=DISABLED)

def clearBox():
    text.config(state=NORMAL)
    text.delete("1.0", "end")

#Use the class we created to iterate through the 16 cryptos and create a checkbox for each
a=0
while a<len(df['Name']):
   bouton=CheckBox(text = names[a],bg = 'yellow')
   a=a+1
   bouton.pack(fill = Y, pady = 2, side = TOP)

#Buttons
pricefind = Button(frame, text = 'Search',width= 20, command = display_price)
pricefind.pack()
clearprice = Button(frame, text = 'Clear', width= 20, command = clearBox)
clearprice.pack()

mainloop()


texts: Map with case insensitive get, remove and containsKey

texts:
I am looking for a Map implementation (with String keys and any generic type for values) that would support getting, removing and checking the existence of keys in a case insensitive manner while preserving the original keys for the extraction with keySet() or entrySet(). So running put("Some Text", object) I want to be able to retrieve/remove/test object via get("sOmE tExt"), remove("some text"), containsKey("Some TeXT"), yet running keySet() I want to get {"Some Text"}.

The map will be used in a highly concurrent context, but if you have really great ideas based around a standard HashMap please suggest. The implementation should have no external dependencies, that is use only standard Java.

So far I came up with this fairly straightforward implementation. However, I am not sure what could be potential deficiencies of this implementation in a concurrent setting. So far I can see one: keySet, entrySet and values are no longer views, but one should not iterate over keys extracting values by key in a concurrent setting anyway.

Any other issues with this implementation or can you suggest a better one?

public class Context implements Map<String, String> {

    private final ConcurrentHashMap<String, Entry<String, String>> data = new ConcurrentHashMap<>();

    public Context() {
        this(null);
    }

    public Context(@Nullable Context context) {
        this((Map<String, String>) context);
    }

    public Context(@Nullable Map<String, String> context) {
        if (context != null) {
            putAll(context);
        }
    }

    @Override
    public int size() {
        return data.size();
    }

    @Override
    public boolean isEmpty() {
        return data.isEmpty();
    }

    @Override
    public boolean containsKey(@Nonnull Object key) {
        return data.containsKey(String.valueOf(key).toLowerCase());
    }

    @Override
    public boolean containsValue(@Nonnull Object value) {
        Collection<String> vals = values();
        return vals.contains(String.valueOf(value));
    }

    @Override
    public String get(@Nonnull Object key) {
        Entry<String, String> val = data.get(String.valueOf(key).toLowerCase());
        return val != null ? val.getValue() : null;
    }

    @Override
    public String put(@Nonnull String key, @Nonnull String value) {
        Entry<String, String> val = data.put(key.toLowerCase(), new SimpleEntry<>(key, value));
        return val != null ? val.getValue() : null;
    }

    @Override
    public String remove(@Nonnull Object key) {
        Entry<String, String> val = data.remove(String.valueOf(key).toLowerCase());
        return val != null ? val.getValue() : null;
    }

    @Override
    public void putAll(@Nonnull Map<? extends String, ? extends String> map) {
        Map<String, Entry<String, String>> transformed = new HashMap<>();
        for (Entry<? extends String, ? extends String> entry: map.entrySet()) {
            transformed.put(entry.getKey().toLowerCase(), new SimpleEntry<>(entry.getKey(), entry.getValue()));
        }
        data.putAll(transformed);
    }

    @Override
    public void clear() {
        data.clear();
    }

    @Nonnull
    @Override
    public Set<String> keySet() {
        return data.values().stream().map(Entry::getKey).collect(Collectors.toSet());
    }

    @Nonnull
    @Override
    public Collection<String> values() {
        return data.values().stream().map(Entry::getValue).collect(Collectors.toList());
    }

    @Nonnull
    @Override
    public Set<Entry<String, String>> entrySet() {
        return new HashSet<>(data.values());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Context context = (Context) o;
        return Objects.equals(data, context.data);
    }

    @Override
    public int hashCode() {
        return Objects.hash(data);
    }
}


texts: Passing bitmap from C# to C++ via a struct

texts:
First, I've read the a few questions regarding this issue, the most helpful being:
https://stackoverflow.com/questions/27463876/passing-bitmap-from-c-sharp-to-c

I was unable to get the provided solutions to work as I kept getting an AccessViolationException.

What I'm attempting to do is pass bitmap data to an unmanaged c++ dll. To do this I created a struct which holds a pointer to the image data as well as its length. I'm using a struct as I plan on passing in multiple images (in a single call) to the unmanaged API.

What I implemented works but I have a feeling there is probably some serious drawbacks so I'm curious as to what those drawbacks could be.

My current solution uses a generic pointer to hold the image data. This of course would be a drawback as I lose type safety. Anyway here is the relevant code.

C++ dll

raw_image.h

struct raw_image
{
   void* data;
   int size;
};

alignment.cpp (exports)

ALIGNMENT_API void submit( raw_image& img )
{
    cv::Mat mat = cv::imdecode( cv::_InputArray(
        static_cast<uchar*>( img.data ), img.size ), cv::IMREAD_COLOR );
    cv::imshow( "image", mat );
    cv::waitKey( );
    cv::destroyWindow( "image" );
}

C# dll

RawImage.cs

[StructLayout( LayoutKind.Sequential )]
internal unsafe struct RawImage
{
    internal void* ImageData;
    internal int Size;
}

Aligner.cs (import)

[DllImport( "alignment-vc141-mtd-x64.dll", CallingConvention =
 CallingConvention.Cdecl )]
    static extern void submit( RawImage img );

And this is where I pass the image to the unmanaged API.

using( var bitmap = new Bitmap( "AlignmentCenter.jpg" ) )
using( var stream = new MemoryStream( ) )
{
    bitmap.Save( stream, ImageFormat.Jpeg );
    var source = stream.ToArray( );
    fixed( void* ptr = source )
    {
        var raw = new RawImage
        {
            ImageData = ptr,
            Size = source.Length
        };
        submit( raw );
     }
  }

Is what I'm doing unsafe? Am I copying more than I should?
One last thing, I know about EmguCv and I've used it in the past but I won't be using it here.


texts:
I have this Sundaram's sieve to generate prime numbers up to limit in Common Lisp.

(defun sundaram-sieve (limit)
  (let ((numbers (range 3 (+ limit 1) 2))
        (half (/ limit 2))
        (start 4))
    (dolist (step (range 3 (+ limit 1) 2))
      (dolist (i (range start half step))
        (setf (nth (- i 1) numbers) 0))
      (setq start (+ start (* 2 (+ step 1))))
      (if (> start half)
          (return (cons 2 (remove-if #'zerop numbers)))))))

Here range is defined as:

(defun range (min max step)
   (loop for n from min below max by step
      collect n))

How can i make the code above more functional and idiomatic? The use of setq and setf bothers me, not to mention that it takes 10 seconds to calculate with limit equal 100000, when the equivalent code in Python runs almost instantly.


texts:
I am making a Swing application for light local database management and I have the button Run XAMPP.

When that button is pressed this code is executed:

private void jRunXAMPPButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        String[] paths = {"C:\\xampp\\xampp-control.exe",
            "C:\\Program Files\\xampp\\xampp-control.exe",
            "C:\\Program Files (x86)\\xampp\\xampp-control.exe"};

        for (String path : paths) {
            final File file = new File(path);

            if (file.exists()) {
                try {
                    Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
                } catch (IOException e) {
                    continue;
                }
                return;
            }
        }
        Helper.printErrln("xampp-control.exe was not found or is corrupt!"); // Prints error in red
    }

I basically have the three possible paths that xampp could be at and I go through them and check if the file exists and can be executed. If not then it prints the error that the file could not be found or is corrupt.

Do you have any tips for my code? Any better way of doing this and I'm especially concerned that my error handling is not that great.


texts:
Have you got any suggestions to improve this code?
The idea is to generate a one-line string that is visually symmetric.

Revisions at Github


texts: Generic property with AOP-functionality in Java

texts:
After playing around with Java 8 and Generics for some time, I came across an idea while reading some posts about Apple's new programming language Swift.

Swift has AOP-like methods for properties (willSet and didSet) and I thought of creating something similar in Java with the help of the new functional interfaces of Java 8.

/**
 * Generic wrapper for a property with the possibility to apply functions before, after and instead of getting/setting the value
 *
 * @author Thomas Eizinger
 * @param <T> The type of the wrapped value
 */
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;

public class Property<T> {

    private T value;

    private BiConsumer<T, T> beforeSet = (u, v) -> {};
    private Function<T, T> onSet = (v) -> (v);
    private Consumer<T> afterSet = (v) -> {};

    private Consumer<T> beforeGet = (v) -> {};
    private Function<T, T> onGet = (v) -> (v);
    private Consumer<T> afterGet = (v) -> {};

    public void set(T value) {
        this.beforeSet.accept(this.value, value);
        this.value = this.onSet.apply(value);
        this.afterSet.accept(this.value);
    }

    public T get() {
        this.beforeGet.accept(this.value);
        this.value = this.onGet.apply(this.value);
        this.afterGet.accept(this.value);
        return this.value;
    }

    public void beforeSet(BiConsumer<T, T> beforeSet) {
        this.beforeSet = beforeSet;
    }

    public void onSet(Function<T, T> onSet) {
        this.onSet = onSet;
    }

    public void afterSet(Consumer<T> afterSet) {
        this.afterSet = afterSet;
    }

    public void beforeGet(Consumer<T> beforeGet) {
        this.beforeGet = beforeGet;
    }

    public void onGet(Function<T, T> onGet) {
        this.onGet = onGet;
    }

    public void afterGet(Consumer<T> afterGet) {
        this.afterGet = afterGet;
    }
}

Example usage:

public class Foo {

    private Property<Integer> bar;

    public Foo() {
        bar = new Property<>();
        bar.beforeSet((oldValue, newValue) -> System.out.printf("bar will be set from %d to %d.%n", oldValue, newValue));
    }

    public Integer getBar() {
        return bar.get();
    }

    public void setBar(Integer bar) {
        this.bar.set(bar);
    }
}

Some usecases I could think of would be:

Notifying observers
Constraint checks before setting values
Converting values (e.g. tolowercase for strings)

What do you think of this?  Does this put too much logic into properties?

Edit:

I changed the following things based on the review and published the code on github:

Added null-checks before adding new delegates.
New delegates are appended after the existing one.
Changed onGet to Consumer<T> and removed beforeGet and afterGet.
Changed name to PropertyDecorator


texts:
I started a web project. Now I was wondering if it is secure enough. I followed some tutorials on HTS, but I can't see all holes (if there are any). Can you check my pages and if you can find any hole in it (like XSS or SQL injections). Thanks for helping :)!

My URL is: **

And another security question: is my HTTPS certificate safe enough? (**) And my SMTP/SSH/... services?

You can now login using: user: demo, password: test123

User controller code:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

    public function create() {
        setHTTPS();
        if ($this->form_validation->run() == false) {
            $this->load->view('user/create');
        } else {
            $this->MUser->create();
            $this->load->view('user/email_sent');
        }
    }

    public function login() {
        setHTTPS();
        if ($this->form_validation->run() == false) {
            $this->load->view('user/login');
        } else {
            $this->MUser->createSession();
            $this->MUser->checkLogin();
            $this->load->view('user/dashboard');
        }
    }

    public function logout() {
        setHTTPS();
        if ($this->MUser->login()) {
            $this->MUser->logout();
            $this->load->view('user/logout');
        } else {
            $this->load->view('user/logout_failed');
        }
    }

    public function dashboard($username) {
        setHTTPS();
        $this->MUser->checkLogin();
        $this->load->view('/user/dashboard');
    }

    public function verify($userID, $code) {
        setHTTPS();
        $safeCode = urldecode($code);
        if ($this->MUser->checkVerifyCode($userID, $safeCode)) {
            $this->MUser->cleanVerifyCode($userID);
            $this->MUser->setActive($userID);
            mailSignupComplete($userID);
            $this->load->view('user/signup_complete');
        } else {
            $this->load->view('user/validation_failed');
        }
    }

    public function password($userID = null, $verifier = null) {
        setHTTPS();
        if ($userID !== null) {
            $safeCode = urldecode($verifier);
            if ($this->MUser->checkPasswordCode($userID, $safeCode)) {
                $this->MUser->updatePassword($userID);
                $this->load->view('user/password_succes');
            } else {
                $this->load->view('user/password_failed');
            }
        } else {
            if ($this->form_validation->run() == false) {
                $this->load->view('user/password');
            } else {
                $this->MUser->addRecoverPasswordEntry();
                $this->load->view('user/password_sent');
            }
        }
    }

}

/* End of file user.php */
/* Location: ./application/controllers/user.php */


texts:
I have categories and subcategories in my view. The code looks like this

  <% Category.roots.each do |category| %>

    <%= category.name %>
    <% if !category.children.empty? %>

      <%= category.decorate.draw_tree %>

    <% end %>

  <% end %>

I'm basically using a decorator to make it recursive

class CategoryDecorator < Draper::Decorator

  delegate_all
  decorates :category

  def draw_tree

    children.inject("") do |memo, child|

      memo << "
#{child.name}"
      memo << "
#{child.decorate.draw_tree}
" if not child.children.empty?
      memo << "
"

    end.html_safe

  end

end

It works fine. But I'm writing HTML inside a Ruby class and I don't like the idea, I'de like to keep it in the view. I tried to play with &block to turn it like following

  <% Category.roots.each do |category| %>

    <%= category.name %>
    <% if !category.children.empty? %>

      <% category.decorate.draw_tree do |child| %>

<%= child.name %>
      <% if child.children.any %>

<%= child.decorate.draw_tree %>
"
      <% end %>

"

      <% end %>

    <% end %>

  <% end %>

Sadly, I couldn't make it work so far. I think I lack methodology here. How can I rewrite this code ?


texts:
I wanted to create a FizzBuzz implementation that both showcases the strengths of Scala (Functional paradigm and collections) and is general enough to anticipate the typical interview follow-up questions. i.e. What if fizz was for factors of 4 instead? What if we wanted to replace factors of 7 with "foo"?

object FizzBuzz extends App {

  def fizzbuzz(factors: Map[Int, String])(currentNumber: Int): String = {
    val words = factors.filter(currentNumber % _._1 == 0).values
    if (words.isEmpty) currentNumber.toString else words.mkString("")
  }

  private final val Factors = Map(3 -> "fizz", 5 -> "buzz")
  private final val Range = 1 to 100

  Range.map(fizzbuzz(Factors)).foreach(println)
}

I would appreciate any feedback on how I can make my Scala more idiomatic.


texts: Text-based adventure survival horror game

texts:
This is the first couple lines of my new (will be) 8-bit co-op horror game. This is just the code for the first player text-based adventure storyline for the console game.  Please critique.

//Andrew Tew
/*
First EVER Co-Op Horror Game!
*/

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

int main()
{
//Declared Variables
string Answer;

//Title Screen and Custom Letter Output
system ("title Until Death We Part");
system ("color 0f");
system ("mode 1000");
cout << "\t\t\t\t\t\t'------------------------------'\n";
cout << "\t\t\t\t\t\t|------------------------------|\n";
cout << "\t\t\t\t\t\t|--------The first ever--------|\n";
cout << "\t\t\t\t\t\t|----8-bit Horror Game Co-Op---|\n";
cout << "\t\t\t\t\t\t|--------Survival Game---------|\n";
cout << "\t\t\t\t\t\t|--------By: Andrew Tew--------|\n";
cout << "\t\t\t\t\t\t|\"The Backstory/Text Adventure\"|\n";
cout << "\t\t\t\t\t\t|------------------------------|\n";
cout << "\t\t\t\t\t\t'------------------------------'\n";
cout << "\n\n\t\t\t\tPlay in Full Screen Mode/Maximized Mode for the Best Experience!\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";

/*End Start Screen

Begin Help Screen (Refrain from using Gotos)*/

system ("pause");
system ("cls");

cout << "\tHELP SCREEN:\n";
cout << "\t-----------\n\n\n";
cout << "\tAnswers:\n";
cout << "\tyes (ALWAYS LOWERCASE)\n";
cout << "\tno (ALWAYS LOWERCASE)\n\n";
cout << "\tWHO ARE YOU:\n";
cout << "\tPOSSIBLE ETHNICITIES(ALWAYS LOWERCASE):\n";
cout << "\twhite\n";
cout << "\tblack\n";
cout << "\tasian\n";
cout << "\tlatino\n\n";
cout << "\tPOSSIBLE HAIR COLORS(ALWAYS LOWERCASE):\n";
cout << "\tblond (male)\n";
cout << "\tblonde (female)\n";
cout << "\tbrown\n";
cout << "\tblack\n";
cout << "\twhite\n";
cout << "\tgray\n\n\n\n\n\n";
cout << "Cont. Next Page\n";

system ("pause");//Next Page Help Screen
system ("cls");

cout << "\n\n\tPOSSIBLE GENDERS(ALWAYS LOWERCASE):\n";
cout << "\tmale\n";
cout << "\tfemale\n";
cout << "\tit\n\n";
cout << "\tPOSSIBLE EYE COLORS(ALWAYS LOWERCASE):\n";
cout << "\tblue\n";
cout << "\tbrown\n";
cout << "\tgreen\n";
cout << "\tgray\n\n";
cout << "\tNAME LIMITS AND MINIMUMS:\n";
cout << "\tNames must contain at LEAST 3 letters.\n";
cout << "\tNames must contain at MOST 10 letters.\n";
cout << "\tNames must NOT contain spaces.\n\n\n\n\n\n";

system ("pause");
system ("cls");

cout << "\t\t\t\t\t\tTinyBit Games Presents to you:\n";
cout << "\n\t\t\t\t\t\t           Torn\n";
/*
In the future code a "Load" Option and a "New Game" Option
Also code a "Save" option that can be done at any time
Remember this is a TEXT ADVENTURE not any other game
*/

system ("pause");//Game Begins Here Still Refrain from goto statements
system ("cls");

One:
cout << "\tIt's Dark... Pitch Black. A throbbing headache bursts into the front of your head.\n";
cout << "As you begin to get up from where you are you realize that you are bound by strong\n";
cout << "rope.\n\n";
cin >> Answer;
if (Answer == "wait"){
    cout << "You wait... the time is unknown\n\n";
}else {
    cout << "\n\n\nThat answer is not a usable answer in this situation\n\n\n";
    goto One; //I didn't know what else to use please critique!
}
cout << "\tYou hear footsteps faintly, distant but audible. They are getting louder and they\n";
cout << "suddenly stop. A door creaks open and you hear it touch a wall\n\n\n";

system ("pause");
return 0;
}


texts:
The object is to notify if a plane was found or not.
The aircraft_identifier variable is a must. cpl_id and target_no are optional, only either of them can be applied at time not both, they are used for further identification if aircraft_identifier is not unique.

qo = 'squawk' or 'callsign'  # only these variants are possible
qo_squawk = '12345'
qo_callsign = 'AMAN3'
qo_cplId = '11'
qo_targetNo = '22'

def decision_making(aircraft_identifier, cpl_id=None, target_no=None):
    found_target = False

    if qo == 'callsign' or qo == 'squawk':
        if aircraft_identifier.isdigit():
            found_target = (aircraft_identifier == qo_squawk)
        else:
            found_target = (aircraft_identifier == qo_callsign)

        if found_target:
            if cpl_id:
                found_target = True if qo_cplId == cpl_id else False
            if target_no:
                found_target = True if qo_targetNo == target_no else False

            if found_target:
                print('Found target!')
                return

    print('plane not found in list!')

decision_making('AMAN3', '22')

Can this code be made simpler?


texts: Redirecting all pages under a certain directory to a single file

texts:
I want to redirect all pages under a certain directory to a single file, like so:

/dir/a → /dir/new
/dir/b →  /dir/new
/dir/new →  /dir/new

With the straightforward

RedirectMatch 301 ^/dir/ http://example.com/dir/new

I get a redirect loop, since /dir/new redirects to itself. I replaced it with a regular expression

RedirectMatch 301 ^/dir/($|[^n]|n$|n[^e]|ne$|ne[^w]|new.) http://example.com/dir/new

which matches all URLs except the desired one. This works, but it's obviously the 'wrong' way to do it. What's a better way?


texts: Writing if..else construct without long condition checks to increase maintainability

texts:
Should writing if..else construct in the following manner be flagged for correction in peer code review?

Existing Code

bool userInstanceHasTransactions = userInstance != null && userInstance.Transactions > 0;
if(userInstanceHasTransactions) {
   //Processing logic here
} else {
  //Some other processing here
}

Flagged to change as

if(userInstance != null && userInstance.Transactions > 0) {
   //Processing logic here
} else {
  //Some other processing here
}

I have observed code of this kind in C#, but I believe language really does not mattter for this question.

I noticed there are lot of if..else construct written in this manner. Will too many if..else construct in this manner impact size of the binary file (dll or exe)?

Is it correct to say writing if..else construct in the manner depicted above increases readability?


texts:
Please tell me what you think.  Is my code bad?

Function checking

#-*- coding: utf-8 -*-
import re
import unittest

def email_check(mail): # E-mail as argument func

    compil = re.compile(r"""
        ^([-a-z0-9_]+
            ((?![.][.])|([.]))
            ((["]["])|(["][!:,]+["]))?
        ([-a-z0-9_]+)?)
        @
        [-a-z0-9_]+
        [.]
        ([-a-z0-9_]+
            ([.][-a-z0-9_]+)?
        )$
        """, re.X)

    result = compil.search(mail)

    if result:
        length = mail.split('@')
        if len(length[0]) <= 128 and len(length[1]) <= 256:
            print mail, 'correct' if not '-.' in length[1] and not '.-' in length[1] else 'Incorrect value'
        else:
            print 'Length string is not mathing'
    else:
        print 'Incorrect data'
    return result.group()

And unit-test

class TestCorrectEmail(unittest.TestCase):

    def setUp(self):
        self.mails = ['a@m.m', '01mail_na-me@mail.com.com', '01mailna-me@mail.com', '01mail""na-me@mail.com', '01mail"!,:"na-me@mail.com', '01mail.na-me@mail.com']

    def test_email_check(self):
        for i in self.mails:
            self.assertTrue(i == email_check(i), 'Incorrect value')

    def tearDown(self):
        self.mails = None

if __name__ == '__main__':
    unittest.main()


texts: A variadic C function for concatenating multiple strings

texts:
I have this function that takes a number \$N\$, and \$N\$ C strings, concatenates and returns the result:

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

char* mystrcat(int count, ...)
{
    char** p;
    char* result;
    char* ptr;

    size_t* len_array;
    va_list ap;
    int j;
    size_t total_length;

    if (count < 1)
    {
        return "";
    }

    va_start(ap, count);
    p = malloc(sizeof(char*) * count);
    len_array = calloc(count, sizeof(size_t));
    total_length = 0;

    for (j = 0; j != count; ++j)
    {
        p[j] = va_arg(ap, char*);
        total_length += (len_array[j] = strlen(p[j]));
    }

    result = malloc(sizeof(char) * (total_length + 1));
    ptr = result;

    for (j = 0; j != count; ++j)
    {
        strcpy(ptr, p[j]);
        ptr += len_array[j];
    }

    *ptr = '\0';
    va_end(ap);
    return result;
}

int main(int argc, char* argv[]) {
    puts(mystrcat(5, "Hello", ", ", "world", ", ", "friends!"));
}

As always, please tell me anything that comes to mind.


texts: Dynamic allocation, creating and accessing of structs of same struct

texts:
Trying to learn about structures (and pointers...). As my program works, I assume it is correct but asking here to make sure. As to my understanding, malloc is used to reserve some memory for all the students. In the first for-loop, each iteration of the loop takes some input that is used to create the first student and so on... Once all students are created, these structures are same size as all of them are created using the same structure.
Could someone explaine how +i and +j is used to access each structure and why the first loop use an "&" when accessing age, and not in the second loop?
#include <stdio.h>
#include <stdlib.h>

typedef struct {
char *name;
int age;
}Student;

int main() {
Student *ptr;
int amount, i, j;
printf("Amount to register: ");
scanf("%d", &amount);
ptr = (Student*) malloc(amount * sizeof(Student));
for(i = 0; i < amount; i++) {
    printf("Enter name and age: ");
    scanf("%s %d", &(ptr+i)->name, &(ptr+i)->age);
}
for(j = 0; j < amount; j++) {
    printf("%s %d\n", &(ptr+j)->name, (ptr+j)->age);
}
return 0;

}


texts: Can delegation be used to set these values at declaration time (thus reducing lines)?

texts:
This class represents a single entry in a log file of the Common Log Format. Can this be improved? I think I might be able to use delegation to pluck values from the matcher. Ideally I would be able to set these values at declaration time.

Kotlin code

    data class CommonLogEntry(private val entry: String) {
        companion object {
            private val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
            private fun asDateTime(line: String) = LocalDateTime.parse(line, formatter)
            val pattern: String = "^(\\S+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})] \"(\\S+) (\\S+)\\s*(\\S+)?\\s*\" (\\d{3}) (\\d+) \"(\\S+)\" \"(\\S+)\""
        }

        val clientIp: String
        val rfc1413identity: String
        val identity: String
        val requestTime: LocalDateTime
        val verb: String
        val resource: String
        val httpVersion: String
        val statusCode: Int
        val payloadSize: Long
        val URI: URI
        val userAgent: String

        init {
            val p = Pattern.compile(pattern)
            val m = p.matcher(entry)
            if (!m.matches() || m.groupCount() != 11)
                throw IllegalArgumentException("Log Pattern doesn't match '$pattern'")

            clientIp = m.group(1)
            rfc1413identity = m.group(2)
            identity = m.group(3)
            requestTime = asDateTime(m.group(4))
            verb = m.group(5)
            resource = m.group(6)
            httpVersion = m.group(7)
            statusCode = m.group(8).toInt()
            payloadSize = m.group(9).toLong()
            URI = java.net.URI.create(m.group(10))
            userAgent = m.group(11)
        }
    }


texts: Tokenizing each document in a large document of documents

texts:
I've been working on a project where I am importing a large document of documents and tokenizing each document. I then make a hashset of the tokens I have, and for each of these unique tokens I am looking to find their frequency in each of the documents I have. There are about 130000 documents total.

I've run the code and unfortunately, it's taking 150 hrs to run.  Do you have any suggestions on improving my code?

This is my Tokenizer() function, which surprisingly works okay:

static private IEnumerable<string> Tokenizer(ref StreamReader sr, ref List<string> tokenz, ref List<string> stopwords)//function for tokenizing
{
    string line;
    var comparer = StringComparer.InvariantCultureIgnoreCase;
    var StopWordSet = new HashSet<string>(stopwords, comparer);
    List<string> tokens = new List<string>();//list of strings called tokens
    while ((line = sr.ReadLine()) != null)//as long as the streamreader has something
    {
        foreach (string item in line.Split(' '))//split amongst strings
        {
            if (item.StartsWith("<") & item.EndsWith(">"))
            {
                item.Trim();//trims the item of spaces
                if (item == "</DOC>")
                {
                    //return item;
                    tokenz.Add(item);//adds the doc tags for later separation use
                }
            }
            else
            {
                string newitem;
                item.Trim();//trims the item of spaces
                if (item != "")//ensures item is not blank
                {
                    newitem = Regex.Replace(item, @"[^A-Za-z0-9]+", "", RegexOptions.IgnoreCase);//regex allows us to ignore case and remove any special characters
                    string newitem2 = newitem.ToLower();
                    {
                        if (StopWordSet.Contains(newitem2))
                        {
                        }
                        else
                        {
                            tokenz.Add(newitem2);
                        }
                        //tokens.Add(newitem.ToLower());//makes all lower case
                    }
                }
            }
        }
    }
    return tokens;
}

The real issue is here:

static public void AddToDictionaryAndCount(ref int doccounter2, ref HashSet<string> MyLexicon, ref List<string> tokens, ref Dictionary<int, int> DocFreqCounter, ref Dictionary<string, Dictionary<int, int>> MyDictionary, ref Dictionary<int, int> DocWordCounter)
{
    foreach (string item in MyLexicon)
    {
        int counter = 0;
        int secondcounter = 0;
        int doccounter = 1;
        int termcounter = 0;
        while (counter <= tokens.LastIndexOf("</DOC>"))
        {
            if (tokens[counter] == "</DOC>")
            {
                DocFreqCounter.Add(doccounter, termcounter);
                if (doccounter2 < doccounter)
                {
                    DocWordCounter.Add(doccounter, (counter - secondcounter));
                    doccounter2++;
                }
                termcounter = 0;
                secondcounter = counter;
                doccounter++;
            }
            if (tokens[counter] == item)
            {
                termcounter++;
                //words.termCount = termcounter;
            }
            counter++;
        }
        MyDictionary.Add(item, new Dictionary<int, int>(DocFreqCounter));
        DocFreqCounter.Clear();
    }
}


texts: Correct way to implement a Singleton field

texts:
I have a helper class that does HTTP operations on Android. Every method uses a client field. I think it's a good idea to make this client a singleton since every method in the class uses it.

The problem is that I don't know 100% what's the best way to implement this singleton since it's only a field in my helper class.

public class HttpHelper {
    private static OkHttpClient client;

    private HttpHelper() { }

    private static OkHttpClient getClient() {
        if(client == null) {
            client = new OkHttpClient();
            client.setConnectTimeout(TIMEOUT, TimeUnit.SECONDS);
        }
       return client;
    }

    // method that uses client:
    public static String getHTML(String cookie, String URL) throws IOException {

        Request request = new Request.Builder().url(URL).header("Cookie", cookie).build();
        Response response = getClient().newCall(request).execute(); // using client
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        return readStream(response.body().byteStream());
    }
}

I am using methods like getHTML() (yes, the class has more) all over my project.

Is it OK that I use a lot of static methods like getHTML()?
Should I be implementing the HttpHelper class as singleton and use non static methods like HttpHelper.getInstance().getHTML() (where the client is created in the getInstance() method of the HttpHelper?


texts: Blocking send and receive algorithm in Go

texts:
I'm sending and receiving data over an interface (serial in this case) with the following behaviour:

The receiver sends back an Ack message if a message is delivered successfully.
If an Ack is not received within a timeout, the command should be re-sent limited a number of times.
Multiple clients may request sending at the same time, but no new commands should be sent until an Ack for the last command is received or it times out. Other sending commands shall wait until the channel is unreserved or they time out.

The algorithm to do this is fairly simple. (Feel free to say so if you think it can be improved):

The implementation in Go works as expected. I just feel there might be a smarter way to do it:
package main

import (
    "fmt"
    "math/rand"
    "time"
)

/****** Simulating the receiver behaviour ******/

var receiveChannel = make(chan string, 1)

// Used to read messages from the interface
func Read() string {
    return <-receiveChannel
}

// Used to write messages to the interface
func Write(data string) {
    // Randomly drop 50% of packets
    if n := rand.Intn(100); n < 50 {
        receiveChannel <- "ACK"
    }
}

/*******************************************/

var ackChannel = make(chan bool, 1)
var sendChannel = make(chan string, 1)

func run() {
    for {
        if Read() == "ACK" {
            ackChannel <- true
        }
    }
}

func sendWrapper(data string) error {
    // Reserve the sending channel
    timeoutTimer := time.NewTimer(1 * time.Second)
    select {
    // This should block until sendChannel has a free spot or times out
    case sendChannel <- data:
        timeoutTimer.Stop()
        fmt.Printf("Send chan reserved for command id=%v\n", data)
    case <-timeoutTimer.C:
        return fmt.Errorf("timed out while waiting for send channel to be free. id=%v", data)
    }

    attempts := 2
    err := send(data, attempts)

    // Free up the sending channel
    select {
    case x := <-sendChannel:
        fmt.Printf("Send channel cleared %v\n", x)
    default:
        fmt.Printf("Send channel is empty. This should never happen!\n")
    }

    return err
}

func send(data string, attempts int) error {
    // Send data
    Write(data)

    // Wait for an ACK to be received
    ackTimeoutTimer := time.NewTimer(time.Millisecond * 100)
    select {
    case <-ackChannel:
        ackTimeoutTimer.Stop()
    case <-ackTimeoutTimer.C:
        // Retry again
        if attempts > 1 {
            return send(data, attempts-1)
        }
        return fmt.Errorf("Timed out while waiting for ack. id=%v", data)
    }
    fmt.Printf("Frame sent and acked id=%v\n", data)
    return nil
}

/****** Testing ******/

func main() {
    go run()

    // Multiple goroutines sending data
    for i := 0; i < 7; i++ {
        go func() {
            x := i
            if err := sendWrapper(fmt.Sprint(x)); err != nil {
                fmt.Println(err.Error())
            } else {
                fmt.Printf("Sending successful. i=%v\n", x)
            }
        }()
        time.Sleep(10 * time.Millisecond)
    }
    time.Sleep(4 * time.Second)
}


texts:
In my application I need to perform several SSH commands from Windows to a Linux machine.

Since I need to reduce as much as possible the SSH calls overhead and also limit the number of concurrent SSH commands, I thought to keep some sessions open and create a session pool class to manage this.

The following code seems to work, but I'm not sure is deadlock safe :

// Class keeping a SSH session open
class SSHSession
{
    public SSHSession()
    {
        // create and open the SSH session
    }

    // run an SSH command synchronously
    public string RunCommand(string command, ManualResetEvent handle)
    {
        Thread.Sleep(3000); // simulate an SSH command of 3 seconds
        handle.Set();
        return "Result of " + command;
    }
}

// Class managing multiple concurrent ssh sessions
class SSHSessionPool
{
    private readonly object padLock;
    private readonly SSHSession[] sessions;
    private readonly ManualResetEvent[] waitHandles;

    public SSHSessionPool(int concurrentSessions)
    {
        this.padLock = new object();
        this.sessions = new SSHSession[concurrentSessions];
        this.waitHandles = new ManualResetEvent[concurrentSessions];
        for (int i = 0; i < concurrentSessions; i++)
        {
            this.sessions[i] = new SSHSession();
            this.waitHandles[i] = new ManualResetEvent(true);
        }
    }

    // run an SSH command synchronously
    public string RunCommand(string command)
    {
        SSHSession session;
        ManualResetEvent handle;
        lock (padLock)
        {
            int idx = WaitHandle.WaitAny(waitHandles);
            handle = waitHandles[idx];
            handle.Reset();
            session = sessions[idx];
        }
        return session.RunCommand(command, handle);
    }
}

Oversimplified application example :

class Program
{
    static void Main(string[] args)
    {
        var sw = System.Diagnostics.Stopwatch.StartNew();

        var sshPool = new SSHSessionPool(4);

        Parallel.For(0, 100,
        (i) =>
        {
            var start = DateTime.Now;
            Console.WriteLine("Task {0} started", i);
            sshPool.RunCommand(string.Format("{0}", i));
            Console.WriteLine("Task {0} completed in {1}", i, DateTime.Now - start);

        });

        sw.Stop();
        Console.WriteLine("Total elapsed: {0}", sw.Elapsed);

        Console.ReadLine();
    }
}


texts:
I've just finished implementing a Generic RecyclerView adapter in my Android app, written in Kotlin.
BaseAdapter.kt:
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

abstract class BaseAdapter<T>(
    private var dataList: ArrayList<T>
) : RecyclerView.Adapter<BaseViewHolder<T>>() {

    abstract fun setViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<T>

    fun swapDataList(dataList: ArrayList<T>) {
        this.dataList = dataList
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<T> {
        return setViewHolder(parent)
    }

    override fun onBindViewHolder(holder: BaseViewHolder<T>, position: Int) {
        holder.bind(dataList[position])
    }

    override fun getItemCount(): Int = dataList.size
}

BaseViewHolder.kt:
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer

abstract class BaseViewHolder<T>(override val containerView: View) : RecyclerView.ViewHolder(containerView),
    LayoutContainer {

    abstract fun bind(data: T)

}

All of my RecyclerView adapters extend BaseAdapter and have an inner ViewHolder class, which extends BaseViewHolder. I'm asking for suggestions and constructive criticism. What could I change to improve the overall performance of my class? Is there a better approach?


texts: Follow up Implementation on Monty Hall Simulation

texts:
I have taken your inputs on my original question and formed a new implementation of the Monty Hall Simulation:

Again keep an eye on CleanCode and OOP

The Price to be won:

enum Price {
    GOAT, CAR
}

The Door keeping that price in secret

class Door {

    private final Price price;

    Door(Price price){
        this.price = price;
    }

    Price getPrice() {
        return price;
    }
}

the Player who participates in an Monty Hall Game

class Player {

    private final boolean preferresChange;
    private int winCounter;

    Player(boolean preferresChange){
        this.preferresChange = preferresChange;
    }

    boolean preferresChange(){
        return preferresChange;
    }

    void increaseWinCounter() {
        winCounter = winCounter + 1;
    }

    int getWinCounter(){
        return winCounter;
    }
}

the MontyHall in which the player takes action

class MontyHall {

    private final List<Door> doors;
    private Door selected;
    private Door openOne;
    private final Random random;
    private final int amountOfDoors;

    MontyHall(int seed, int amount) {
        random = new Random(seed);
        amountOfDoors = amount;
        doors = IntStream.range(0, amountOfDoors).
            mapToObj(e -> new Door(Price.GOAT)).
            collect(Collectors.toList());
        doors.set(random.nextInt(amountOfDoors), new Door(Price.CAR));
    }

    void chooseDoor(){
        selected = doors.get(random.nextInt(amountOfDoors));
    }

    void openDoor(){
        openOne = doors.stream().
            filter(d -> !d.equals(selected) && Price.GOAT == d.getPrice()).
            collect(Collectors.toList()).
            get(0);
    }

    void changeDoor(){
        selected = doors.stream().
            filter(d -> !d.equals(openOne) && !d.equals(selected)).
            collect(Collectors.toList()).
            get(0);
    }

    Price getPrice(){
        return selected.getPrice();
    }

}

and the simulator who hosts the games

class Simulator {

    public static void main(String[] args) {
        Simulator simulator = new Simulator();
        simulator.simulate(10000, 3);
    }

    private void simulate(int iterations, int amountDoors) {
        Player changer = new Player(true);
        Player stayer = new Player(false);

        Random random = new Random();
        for (int i = 0; i < iterations; i ++){
            int seed = random.nextInt();
            playOneRound(changer, seed, amountDoors);
            playOneRound(stayer, seed, amountDoors);
        }
        System.out.println("changer: "+changer.getWinCounter());
        System.out.println("stayer : "+stayer.getWinCounter());
    }

    private void playOneRound(Player player, int seed, int amountDoors) {
        playOneRound(player, new MontyHall(seed, amountDoors));
    }

    private void playOneRound(Player player, MontyHall montyHall) {
        montyHall.chooseDoor();
        montyHall.openDoor();
        if (player.preferresChange()){
            montyHall.changeDoor();
        }
        if (Price.CAR == montyHall.getPrice()){
            player.increaseWinCounter();
        }
    }

}


texts:
I have this below Data Structure.

The output will be like

m - n - o - p - q - r - s -t

Please review the below code and let me know if any optimization can be done.

public class Application {

    public static Node root = null;
    public static Node temp = root;
    public static Node anotherTemp;

    public static void main(String[] args) {

        Node m = new Node("m");
        Node n = new Node("n");
        Node o = new Node("o");
        Node p = new Node("p");
        m.setDown(n);
        n.setDown(o);
        o.setDown(p);

        Node q = new Node("q");
        Node r = new Node("r");
        Node s = new Node("s");

        m.setRight(q);
        q.setDown(r);
        r.setDown(s);

        Node t = new Node("t");
        q.setRight(t);
        root = new Node(m.getValue());
        temp = root;

        anotherTemp = m;

        flattern(m);
        // Here is my output
        System.out.println(temp);
    }

    public static void flattern(Node m) {

        if (m.getRight() == null)
            return;

        while (m.getDown() != null) {
            if (!m.getValue().equals("m")) {
                root.setRight(new Node(m.getValue()));
                m = m.getDown();
                root = root.getRight();
            }
            else
                m = m.getDown();
        }
        if (m.getDown() == null) {
            root.setRight(new Node(m.getValue()));
            if (anotherTemp.getRight() != null) {
                anotherTemp = anotherTemp.getRight();
                root.getRight().setRight(new Node(anotherTemp.getValue()));
                root = root.getRight();
            }
        }

        if (m.getDown() == null)
            flattern(anotherTemp);
        System.out.println(temp);
        System.out.println(root);
    }

}

class Node {
    String value;
    Node right;
    Node down;

    Node(String val) {
        this.value = val;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public Node getDown() {
        return down;
    }

    public void setDown(Node down) {
        this.down = down;
    }

}


texts:
I have to calculate the premium from a rate chart based on a person's age and the amount of insurance they request. I started out using if/switch statements, but the code is getting too long and seems pretty redundant.

var premium;
var beneAmt = $('#PrimaryApplicantTTLBenefitAmountInput').val();
var age = $('#PrimaryApplicantAge').val();

if (50000 <= beneAmt < 75000) {

    switch (true) {

        case (age < 30):

            premium = 2.00;
            break;

        case (30 <= age < 40):

            premium = 2.50;
            break;

        case (40 <= age < 50):

            premium = 5.00;
            break;

        case (50 <= age < 60):

            premium = 15.00;
            break;

        case (60 <= age < 65):

            premium = 21.50;
            break;

        case (65 <= age < 70):

            premium = 20.80;
            break;

        case (70 <= age < 75):

            premium = 23.25;
            break;

        case (age >= 75):

            premium = 35.00;
            break;

    }

} else if (75000 <= beneAmt < 100000) {

    switch (true) {

        case (age < 30):

            premium = 3.00;
            break;

        case (30 <= age < 40):

            premium = 3.75;
            break;

        case (40 <= age < 50):

            premium = 7.50;
            break;

        case (50 <= age < 60):

            premium = 22.50;
            break;

        case (60 <= age < 65):

            premium = 32.25;
            break;

        case (65 <= age < 70):

            premium = 31.20;
            break;

        case (70 <= age < 75):

            premium = 34.88;
            break;

        case (age >= 75):

            premium = 52.50;
            break;

    }

} else if (100000 <= beneAmt < 125000) {

    switch (true) {

        case (age < 30):

            premium = 4.00;
            break;

        case (30 <= age < 40):

            premium = 5.00;
            break;

        case (40 <= age < 50):

            premium = 10.00;
            break;

        case (50 <= age < 60):

            premium = 30.00;
            break;

        case (60 <= age < 65):

            premium = 43.00;
            break;

        case (65 <= age < 70):

            premium = 41.60;
            break;

        case (70 <= age < 75):

            premium = 46.50;
            break;

        case (age >= 75):

            premium = 70.00;
            break;

    }

}

How else could I go about this?


texts: List with no sequential repeats (where possible)

texts:
Assume I have the following list (List<string>)

G
G
M
T

I'd like this to be in an order where the same letter will not occur twice, such as

G
M
G
T

(I appreciate other variations would also suffice)

Please note, if I had the following

G
G
G
G
G
M
T

Then of course some values will have to occur concurrently. The position within the List  where this concurrency occurs is not relevant. What I'm after is to stop this repetition where possible to most evenly spread the letters.

The C# console application code I share works

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace resorting
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string> { "G", "G", "G", "G", "M", "M", "T", "T", "T", "T", "T", "T", "T", "T", "G", "G", "G", "G", "M", "M", "T", "T", "T", "T", "T", "T", "T", "T" };

            list.UpdateList();
        }
    }

    public static class extension
    {
        public static void UpdateList(this List<string> list)
        {
            GetList(list);
            list.Reverse(); // DO I HAVE TO REVERSE
            GetList(list);  // AND THEN CALL THE METHOD AGAIN
        }

        private static void GetList(List<string> list)
        {
            int total = list.Count;

            int inc = 2;

            for (int i = 0; i < total; i++)
            {
                if (total <= i + 2)
                    break;

                if (total <= i + inc)
                    continue;

                if (list[i] == list[i + 1])
                {
                    var val = list[i];
                    list.RemoveAt(i);
                    list.Insert(i + inc, val);
                    i = i - 1;
                    inc++;
                    continue;
                }
                inc = 2;
            }
        }
    }
}

As you can see, I have to call this function twice. I reverse the order and then reapply the same logic. Whilst it works, and based upon the amount of data I will be using, I don't need the function to be more efficient  my question is still about efficiency (if worth while against the amount
of work required).

Can I update the code to not need to reverse the list to avoid calling the code twice?


texts: Find "secure file erase" commands on the system

texts:
This code finds which "secure file erase" command exists on the system.  It used to simply test for "shred" and pick "rm" as a default.  Now it is a bit more complex since I've ported the code to operating systems with "srm" and "rm -P".  Is this still cleanly written?  How can I improve it?
var shredPath, shredFlag string // Memoization cache

// shredCmd determines which command to use to securely erase a file. It returns
// the command to run and what flags to use with it. Determining the answer
// can be slow, therefore the answer is memoized and returned to future callers.
func shredCmd() (string, string) {
    // Use the memoized result.
    if shredPath != "" {
        return shredPath, shredFlag
    }

    var path string
    var err error
    if path, err = exec.LookPath("shred"); err == nil {
        shredPath, shredFlag = path, "-u"
    } else if path, err = exec.LookPath("srm"); err == nil {
        shredPath, shredFlag = path, "-f"
    } else if path, err = exec.LookPath("rm"); err == nil {
        shredPath, shredFlag = path, "-f"
        // Does this command support the "-P" flag?
        tmpfile, err := ioutil.TempFile("", "rmtest")
        defer os.Remove(tmpfile.Name()) // clean up
        err = RunBash("rm", "-P", tmpfile.Name())
        if err != nil {
            shredFlag = "-Pf"
        }
    }

    // Single exit, so we don't have to repeat the memoization code.
    return shredPath, shredFlag
}

// RunBash runs a Bash command.
func RunBash(command string, args ...string) error {
    cmd := exec.Command(command, args...)
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err := cmd.Start()
    if err != nil {
        log.Fatal(err)
    }
    err = cmd.Wait()
    if err != nil {
        return fmt.Errorf("RunBash cmd=%q err=%w", command, err)
    }
    return nil
}
```


texts: Find the number of working days between two dates inclusively

texts:
The objective is to find the number of working days (days spanning from Monday to Friday) between two given dates inclusively.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 13; i <= 31; i++)
            {
                DateTime start = new DateTime(2014, 10, i);
                DateTime stop = new DateTime(2014, 10, 31);

                int totalWorkingDays = GetNumberOfWorkingDays(start, stop);

                Console.WriteLine("There are {1} working days from Oct {0}, 2014 to Oct 31, 2014.", i, totalWorkingDays);
            }
        }

        private static int GetNumberOfWorkingDays(DateTime start, DateTime stop)
        {
            TimeSpan interval = stop - start;

            int totalWeek = interval.Days / 7;
            int totalWorkingDays = 5 * totalWeek;

            int remainingDays = interval.Days % 7;

            for (int i = 0; i <= remainingDays; i++)
            {
                DayOfWeek test = (DayOfWeek)(((int)start.DayOfWeek + i) % 7);
                if (test >= DayOfWeek.Monday && test <= DayOfWeek.Friday)
                    totalWorkingDays++;
            }

            return totalWorkingDays;
        }
    }
}

Is there the simpler or better way to do so? Any comment and suggestion is welcome.