texts: Improvements on column renaming using a mapping table

texts:
I was wondering whether I could use more data.table functions rather than using for loops in the following piece of code:
library(data.table)

n1 <- data.table(A = c(1:5),
                B = c(1:5),
                C = c(1:5))

n2 <- data.table(D = c(1:5),
                E = c(1:5),
                F = c(1:5))

n3 <- data.table(G = c(10:15),
                H = c(10:15),
                I = c(10:15),
                K = c(10:15))

m <- data.table(name1 = c("A", "B", "C"),
                name2 = c("E", "F", "D"),
                name3 = c("I", "H", "G"))

naming_convention <- function(l, m, index = 1){
  if (index > length(l)){
    stop("Indices cannot exceed the number of dataframes in the list.")
  }

  if (ncol(m) != length(l)){
    stop("Columns in mapping matrix, need to match the number of dataframes in the list.")
  }

  new_names <- m[, eval(index), with = FALSE][[1]]

  if (length(new_names) != ncol(l[[index]])){
    stop("Not all columns are defined of the reference matrix.")
  }

  for(i in c(1:ncol(m))){
    if(i == index){
      next
    }
    temp <- l[[i]]
    setnames(temp, old = m[[i]], new = new_names)
    l[[i]] <- temp[,..new_names]
  }
  return(l)
}

l <- list(n1, n2, n3)
naming_convention(l, m, 1)

Examples:
naming_convention(l, m, 1)
should rename all columns to A, B, C of all the data tables in the list, based on the mapping presented in m matrix. For example, in the second matrix, the E would be mapped to an A, F to be mapped to B and D to be mapped to C. For the third table, I mapped to A, H mapped to B, G mapped to C.
Note that if we change the index to 2, naming_convention(l, m, 2), all column names should be renamed to E, F, D. So for the first table it would rename A to E, B to F and C to D.


texts:
SICP exercise 2.18 asks the following:

  Exercise 2.18.  Define a procedure
  reverse that takes a list as argument
  and returns a list of the same
  elements in reverse order:

(reverse (list 1 4 9 16 25))
(25 16 9 4 1)

I wrote this iterative function:

(define (reverse n)
  (define (iter a b)
    (if (null? a) b
        (iter (cdr a) (cons (car a) b))))
  (iter n null))

I could not think of a way to do this recursively.  Is there a better way to write this function?  Is it possible to do it recursively?


texts:
I have this C++ code that implements a rectangular numerical integration.  It evaluates the \$K\$-dimensional integral

$$\int_{u_K = 0}^{\gamma}\int_{u_{K-1} = 0}^{\gamma-u_K}\cdots\int_{u_2}^{\gamma-u_K-\cdots-u_3}F_U(\gamma-\sum_{k=2}^Ku_k)f_U(u_2)\cdots f_U(u_K)\,du_2\cdots du_K$$
where \$F_U\$ is the cdf and \$f_U\$ is the pdf.

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

float pdf(float u){
     return (1/(pow(1+u, 2)));
}

float cdf(float u){
      return (1 - 1/(u+1));
}
// The main function that implements the numerical integration,
//and it is a recursive function
float integ(float h, int k, float du){
      float res = 0;
      if (k == 1){
         res =  cdf(h);
      }else{
         float u = 0;
      while (u < h){
         res += integ(h - u, k - 1, du)*pdf(u)*du;
         u += du;
     }
}
     return res;
}

int main(){
    float du = 0.0001;
    int K = 3;
    float gamma[4] = {0.31622777, 0.79432823,
                1.99526231, 5.01187234};
    int G = 50;
    int Q = 2;
    for (int i = 0; i < 4; i++){
        if ((G-Q*(K-1)) > 0){
            float gammath = (gamma[i]/Q)*(G-Q*(K-1));
            cout<<1-integ(gammath, K, du)<< endl;
    }

 }

    return 0;
}

I am facing a speed problem, although I switched to C++ from Python and MATLAB, because C++ is faster. The problem is that I need a small step size du to get an  accurate evaluation of the integration.

Basically, I want to evaluate the integral at 4 different points defined by gammath, which is a function of other defined parameters.

Is there anyway I can speed up this program? I already have 25x+ speed factor over the same code in Python, but still the code takes too long (I ran it all night, and it wasn't finished in the morning). And this is only for K=3, and G=50. In other cases I want to test K = 10, and G = 100 or 300.


texts: Spreadsheet to calculate how to cut pipes

texts:
I have written a piece of code that calculates how to cut pipes based on an order and fixed raw pipe length (in this case 288 feet), but I am not 100% happy with my current code as it counts the pipe pieces that have been created for each length in column C (see comment in code) and clears column C at the end. Is there an way to store the values without having to create a variable for each pipe length?

This is what my input sheet looks like:

Here is my code:

Sub CalcPipe()

Dim StartPipeLng As Long, LastLng As Long, TotalLng As Long, PipeName As Long

StartPipeLng = Cells(2, 4).Value

LastLng = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row

TotalLng = Application.WorksheetFunction.SumProduct(Range("A2:A" & LastLng), Range("B2:B" & LastLng))
TotalLng = Application.WorksheetFunction.RoundUp(TotalLng / StartPipeLng, 0)

Cells(5, 4).Value = TotalLng

PipeName = 1

    For y = 6 To TotalLng + 5

        Cells(1, y).Value = "Pipe " & PipeName
        PipeName = PipeName + 1
        StartPipeLng = Cells(2, 4).Value

        For x = 2 To LastLng
            If StartPipeLng - Cells(x, 1).Value >= 0 And Cells(x, 2).Value <> Cells(x, 3).Value Then
                StartPipeLng = StartPipeLng - Cells(x, 1).Value
                Cells(x, 3).Value = Cells(x, 3).Value + 1 ' Here is the issue: Rather than write the values in column C, I would like to store them rather then write them in a cell
                Cells(x, y).Value = Cells(x, y).Value + 1
                x = x - 1
            End If
        Next x
    Next y

Columns(3).Clear

End Sub

And this is what my output looks like:


texts: Loop through range, selecting grouped data?

texts:
I have some info. that looks like this:

Header  Debit   Credit

aaaa    20  0

bbbb    0   60

cccc    30  0

xxxx    10  0
xxxx    0   40
xxxx    40  0
xxxx    0   10

oooo    500 0
oooo    0   52
oooo    0   500

pppp    10
pppp    0   10

(Note this starts in col. H)

The idea is that I want to go through this range, and where there are "blocks" of data (see the "xxxx" group), check for offsetting amounts.

I was able to put this together, to loop through the groups, but I'm not sure if it's the best way to do so.  I'm afraid there will be a time it skips a line which is unintended - any ideas/tips on improving it?

Sub strike_out_Matching_Debit_and_Credits()
Dim debitCol&, credCol&, lastRow&, startRow&, endRow&, i&
Dim rng As Range, cel As Range
Dim myWS As Worksheet

Set myWS = Sheets("Raw - edited")
With myWS
    debitCol = .Rows(1).Find(what:="Debit").column
    credCol = .Rows(1).Find(what:="Credit").column
    lastRow = .Cells(.Rows.Count, credCol).End(xlUp).row

startRow = 2
    For i = 2 To lastRow
        endRow = .Cells(i, debitCol).End(xlDown).row
        Set rng = .Range(.Cells(startRow, debitCol), .Cells(endRow, debitCol))

        rng.Select

        If rng.Cells.Count - WorksheetFunction.CountA(rng) = 0 And rng.Cells.Count > 1 Then
            ' We now have a block to work through
            check_Values rng, rng.Offset(0, 1)
            check_for_Offset_Values rng, rng.Offset(0, 1)
        End If
        startRow = .Cells(endRow, debitCol).End(xlDown).row
    Next i

End With
End Sub

Thanks for any ideas/advice/tips!

Edit: I appreciate the help so far! I've made notes on the naming conventions, etc.  Does anyone have any tips for tightening up the actual function of the code loop? That's what I'm mainly interested in.


texts:
The problem:

Treat an array as if it is circular; out-of-bounds indices "wrap around" the array to become in-bounds.

Current solution:

// roudedArray.cpp
#include <iostream>

template <typename T, int N>
int wrapAroundArray(int i, T(&ThisArray)[N])
{
  // "wrap" i around ThisArray, landing on a valid index
  while (i < 0) { i += N; }
  while (i >= N) { i -= N; }
  return i;
}

std::string words[] = { "this", "and", "that" };

int main()
{
  for (int i = -9; i < 10; i++)
  {
    int adj = wrapAroundArray(i, words);
    std::cout << "i: " << i;
    std::cout << ", adjusted index: " << adj;
    std::cout << ", word: " << words[adj] << std::endl;
  }
}

Output (compile with g++ roundedArray.cpp):

i: -9, adjusted index: 0, word: this
i: -8, adjusted index: 1, word: and
i: -7, adjusted index: 2, word: that
i: -6, adjusted index: 0, word: this
i: -5, adjusted index: 1, word: and
i: -4, adjusted index: 2, word: that
i: -3, adjusted index: 0, word: this
i: -2, adjusted index: 1, word: and
i: -1, adjusted index: 2, word: that
i: 0, adjusted index: 0, word: this
i: 1, adjusted index: 1, word: and
i: 2, adjusted index: 2, word: that
i: 3, adjusted index: 0, word: this
i: 4, adjusted index: 1, word: and
i: 5, adjusted index: 2, word: that
i: 6, adjusted index: 0, word: this
i: 7, adjusted index: 1, word: and
i: 8, adjusted index: 2, word: that
i: 9, adjusted index: 0, word: this

I'd prefer an arithmetic (constant-time) solution that produces the same results. Any suggestions?


texts:
I am very new to functional programming. I wrote this program where the user can enter an integer and it will print the factorial. If the user enters a negative integer or not an integer at all, it'll give the user a second chance.

This doesn't feel very functional to me. How can I make this code more functional (esp. the main function)? Or is this just fine?

module Main where
import Data.Char

factorial :: Integer -> Integer
factorial 0 = 1
factorial n = product [1..n]

isIntegral :: String -> Bool
isIntegral [] = False
isIntegral st = all isDigit st

main :: IO ()
main = do
  putStrLn "Enter a non-negative integer:"
  numberStr <- getLine
  if isIntegral numberStr
    then do
      let number = read numberStr :: Integer
      if number < 0
        then do
          main
        else do
          putStrLn $ show $ factorial number
    else do
      main


texts: Speed up weighted average for Leela Chess Zero

texts:
Problem: Given a vector of about 40 values m with normal error sd compute the weighted average of the values weighted by the chance that they are the maximum.

I have come up with 2 different approaches to solve this. The first is numerical integration, the second is monte-carlo sampling.

import numpy as np
from scipy import integrate
from scipy.stats import norm

m = np.arange(-1,1,.03)
sd = np.ones(len(m))*.12

def integ():
    n = len(m)
    dx = .05
    ts = np.arange(-2, 2, dx)
    cdfs = np.ones(len(ts))
    for i in range(n):
        cdfs *= norm.cdf(ts, m[i], sd[i])

    def func(i, x):
        return norm.pdf(x, m[i], sd[i]) / norm.cdf(x, m[i] , sd[i]) * cdfs

    ans = np.zeros(n)
    for i in range(n):
        ys = func(i, ts)
        ans[i] = integrate.simps(ys, dx=dx)
    ans *= m
    return ans

def monte():
    nn=10000
    a = np.random.normal(size=(len(m),nn))*sd[:,None]+m[:,None]
    vals = (a==a.max(axis=0)).sum(axis=1)/nn
    vals *= m
    return vals

Both of these solutions work, but they are in the range of 1/1_000 of a second rather than the 1/1_000_000 of a second I am looking for.

This code is a prototype that I will eventually be writing in c++, but I want to make sure that this function is possible to calculate quickly enough for the change to be worth it, so I really don't care about formatting or readability, just performance.


texts:
Program written in TI-Basic that works on TI-83/84/+/SE calculators. Automatically detects whether input is a number of a Roman numeral, and converts to the opposite. Please try to optimize for size, if possible.

DelVar IDelVar VDelVar XDelVar LDelVar CDelVar DDelVar MClrHome
Input Str1
expr(Str1->A
If A
Then
A->B
"?->Str2
For(I,1,iPart(A/|E3
Str2+"M->Str2
B-|E3->B
End
If B>899
Then
Str2+"CM->Str2
B-900->B
End
If B>499
Then
Str2+"D->Str2
B-500->B
End
If B>399
Then
Str2+"CD->Str2
B-400->B
End
B->A
For(I,1,iPart(A.01
Str2+"C->Str2
B-|E2->B
End
If B>89
Then
Str2+"XC->Str2
B-90->B
End
If B>49
Then
Str2+"L->Str2
B-50->B
End
If B>39
Then
Str2+"XL->Str2
B-40->B
End
B->A
For(I,1,iPart(A.1
Str2+"X->Str2
B-10->B
End
If B=9
Then
DelVar BStr2+"IX->Str2
End
If B>4
Then
Str2+"V->Str2
B-5->B
End
If B=4
Then
DelVar BStr2+"IV->Str2
End
For(I,1,B
Str2+"I->Str2
End
sub(Str2,2,length(Str2)-1
Else
"?"+Str1+"?->Str1
For(I,0,5
inString(Str1,sub("IVIXXLXCCDCM",2I+1,2
If Ans
Then
sub(Str1,1,Ans-1)+sub(Str1,Ans+2,length(Str1)-Ans-1->Str1
C+(4+10fPart(I/2))10^(iPart(I/2->C
End
End
For(I,1,length(Str1
inString("IVXLCDM",sub(Str1,I,1
If Ans
C+(5-8fPart(Ans/2))10^(iPart(.5(Ans-1->C
End
C
End
Ans


texts:
I wrote an OCaml program that displays a scrolling marquee in the terminal:

Code:

(* Displays moving text in the terminal.
 * Uses VT100 escape sequences.
 * Usage:
 *     ocaml <this-file>
 * *)
#load "unix.cma"

let rec loop max_col curr_col =
    print_string "\x1B[2J";  (* Clear screen. *)
    print_string ("\x1B[1;" ^ (string_of_int curr_col) ^ "H");
    print_string "Hello world!";
    flush stdout;
    Unix.sleepf 0.2;
    if curr_col >= max_col then  (* Start from the beginning. *)
        loop max_col 0
    else
        loop max_col (curr_col + 1)

let () =
    (* Raise Sys.Break on Ctrl-C (SIGINT). *)
    Sys.catch_break true;
    print_string "\x1B[?25l";  (* Hide cursor. *)
    try
        loop 20 0
    with
        Sys.Break -> print_string "\x1B[?25h";  (* Show cursor. *)

The code appears to work well, as you can see in the GIF above. I need some advice:

Did I write the program correctly? I am targeting terminal emulators that support VT100 escape sequences, and I want to make sure that this is portable across terminal emulators.


texts: Refractoring OOP vs. Functional Programming Approach

texts:
I am writing a python script that will call mandrills export activity api for every blog on a worpress mu install except for the main site. The script is designed to be called from a cron job on a regular schedule. The code I have is here.

__author__ = 'Taylor'

import datetime
import mandrill
import phpserialize
import mysql.connector

class BlogReporter(object):
    blog_id = None
    table_name = 'wp_%s_options'
    notify_email = None
    sender_email = None
    date_to = None
    date_from = None

    def __init__(self, blog_id_, database_config_, mandrill_client_):
        self.blog_id = blog_id_
        self.mandrill_client = mandrill_client_
        self.table_name = 'wp_' + str(blog_id_) + '_options'
        try:
            cnx_ = mysql.connector.connect(**database_config_)
        except mysql.connector.Error as err:
            print(err)
        else:
            query_ = "SELECT option_value FROM " + self.table_name + " WHERE option_name=%s"
            try:
                cursor_ = cnx_.cursor()
                cursor_.execute(query_, ('admin_email',))
                result = cursor_.fetchone()
            except Exception as err:
                print(err)
            else:
                # set notify email from cursor
                self.notify_email = result
                cursor_.close()
            try:
                cursor_ = cnx_.cursor()
                cursor_.execute(query_, ('wysija',))
                encoded_result = cursor_.fetchone()[0]
            except Exception as err:
                print(err)
            else:
                decoded_result = phpserialize.unserialize(encoded_result.decode('base64', 'strict'))
                self.sender_email = decoded_result['from_email']
                cursor_.close()
            cnx_.close()
        self.date_to = datetime.datetime.now()
        # if it monday lets get activity since saturday
        if self.date_to.weekday() is 0:
            self.date_from = self.date_to - datetime.timedelta(days=2)
        # else just get the activity from the past day
        else:
            self.date_from = self.date_to - datetime.timedelta(days=1)

    def export_activity(self):
        self.mandrill_client.exports.activity(self.notify_email, self.date_from, self.date_to, None,
 self.sender_email,'Sent')

# database name and credentials
# these should eventually be parsed from command line arguments
database_config = {
    'user': 'root',
    'password': 'password',
    'database': 'wpmudb'
}
# Mandrill API Key
# this should also be parsed from command line
mandrill_api_key = 'xxxxx_xxxxxxxxxxxxxxxx'
mandrill_client = mandrill.Mandrill(mandrill_api_key)

try:
    cnx = mysql.connector.connect(**database_config)
except mysql.connector.Error as err:
    print(err)
else:
    try:
        cursor = cnx.cursor()
        # Get all blogs but blog_id 1 since the main site needs no report
        query = "SELECT blog_id FROM wp_blogs WHERE blog_id != '1'"
        cursor.execute(query)
    except Exception as err:
        print(err)
    else:
        for blog_id in cursor:
            blog = BlogReporter(blog_id[0], database_config, mandrill_client)
            blog.export_activity()
            del blog
        cursor.close()
    cnx.close()

I wrote it like this because it is the first program I have written in python and I was unsure of how to structure it and wanted to learn more about classes in python. However, recognizing that in the programs current state Class BlogReporter's constructer and method export_activity could be refactored into one function that accepts the arguments of class BlogReporter's constructor and is simply the class's constructor plus the method export_activity; I was curious if doing so would be beneficial to the program in any way.

I would also like to welcome comments as to whether the mandrill client should be reinstantiated for each instance of BlogReporter or whether it is better to pass the same client to each instance.


texts: Java 8 streams - restructure entity classes for UI Grid

texts:
I have the following domain model:

class Holding
------------
Account account;
DataSourceProduct dataSourceProduct;

class Account
-------------
String name;

class DataSourceProduct
-------------
DataSource dataSource;
Product product;
// other product data specific to the data source

class Product
--------------
String id;

class DataSource
----------------
String name;

I get a list of Holding data from three different data sources. I need to show the data in a grid. Each row in the grid has the same product and account and will have columns to show the product data as provided by the three different data sources. Note: One of the data sources may have a holding with a product id of null.

To accomplish this, I currently break up the list of holdings into several lists where each list contains only holdings with the same product id and account. Also, I key each list by data source. So, in the end, I have the following:

List<Map<DataSource,Holding>>

So, we have something like this:

index 0 in the list
    Map:Key       Map:Value
    datasource1   holding1AccordingToDs1  ----|
    datasource2   holding1AccordingToDs2  ----|---> all three holdings have same product and account
    datasource3   holding2AccordingToDs3  ----|
index 1 in the list
    Map:Key       Map:Value
    datasource1   holding2AccordingToDs1  ----|
    datasource2   holding2AccordingToDs2  ----|---> all three holdings have same product and account
index 2 in the list
    Map:Key       Map:Value
    datasource1   holding3AccordingToDs1  ----|
    datasource3   holding3AccordingToDs3  ----|---> all three holdings have

To get from List<Holding> to List<Map<DataSource,Holding>> I do the following:

    // these holdings could have an null instrument id
    // and this data is returned from a different db than other
    // holdings
    List<Holding> aSourceHoldings = holdingService.getHoldings(date);

    List<Holding> unMatchedHoldings = aSourceHoldings .stream()
            .filter(h -> h.getDataSourceProduct().getProduct().getId() == null)
            .collect(Collectors.toList());

    // if null product id, no way to match to other instruments
    aSourceHoldings.removeAll(unMatchedHoldings);

    // get other data source holdings
    List<Holding> toBeMatchedHoldings = holdingRepository.getHoldings(date);
    toBeMatchedHoldings.addAll(aSourceHoldings);

    // grouping by account and product
    Map<Account, Map<Product, List<Holding>>> matchedHoldings =
            toBeMatchedHoldings.stream()
            .collect(Collectors.groupingBy(Holding::getAccount,
                    Collectors.groupingBy(h -> h.getDataSourceProduct().getProduct())));

List<Map<DataSource, Holding>> unifiedHoldings = new ArrayList<Map<DataSource, Holding>>();
    Map<DataSource, Holding> tmp = new HashMap<DataSource, Holding>();
    for (Map<Product, List<Holding>> productHoldings : matchedHoldings.values()) {
        for (List<Holding> holdings : productHoldings.values()) {
            for (Holding holding : holdings) {
                tempMap.put(holding.getDataSourceProduct.getDataSource(), holding);
             }
            unifiedHoldings.add(tempMap);
        }
    }
    return unifiedHoldings;

Like data sources, the number of accounts is small (4-5) and will remain fairly static over the years. Is it possible to reduce the number of manipulations to group and get the data that I need for the UI grid?


texts:
Title:
Identifying equivalent lists

I am using lists as keys, and therefore want to identify equivalent ones.

For example,

[0, 2, 2, 1, 1, 2]
[4, 0, 0, 1, 1, 0]

are 'equivalent' in my book. I 'equivalify' the list by checking the list value with the highest count, and set that to 0, then the next highest count to 1, and so on and so forth. It's done with this code below, which does the job properly but is fairly slow - and I am wondering if there is a way of doing the same job yet I haven't seen it yet.

for key in preliminary_key_list:
    key = list(key) # convert from immutable tuple to mutable list

    i = 0
    translation = {}
    counts = [[j, key.count(j)] for j in set(key)]
    counts_right = [j[1] for j in counts]
    for count in set(key):
        translation[counts[counts_right.index(max(counts_right))][0]] = i
        counts_right[counts_right.index(max(counts_right))] = 0
        i += 1

    for i in range(len(key)):
        key[i] = translation[key[i]]


texts: Find Pythagorean Triple with Perimeter == 24

texts:
Learn You a Haskell gives this exercise:

  Here's a problem that combines tuples and list comprehensions: which
  right triangle that has integers for all sides and all sides equal to
  or smaller than 10 has a perimeter of 24? First, let's try generating
  all triangles with sides equal to or smaller than 10:

Here's my solution in Scala. Note that I'm ignoring the right triangle part.

val a = List.range(1,11)
val b = List.range(1,11)
val c = List.range(1,11)

def sumsEqualsTo24(x: Int, y: Int, z: Int): Option[(Int, Int, Int)] =
                           if(x + y + z == 24) Some( (x,y,z) ) else None

def pythagTriple(x: Int, y: Int, z: Int): Option[(Int, Int, Int)] = {
                             if( Math.pow(x, 2) + Math.pow(y, 2) == Math.pow(z, 2) )
                                  Some( (x,y,z) )
                             else None
}

Using flatMap

val xs: List[(Int, Int, Int)] = a.flatMap(x =>
                                 b.flatMap(y =>
                                  c.flatMap(z => sumsEqualsTo24(x, y, z) ) ) )

val ys: List[(Int, Int, Int)] = xs.flatMap{a => pythagTriple(a._1, a._2, a._3)}

Using for-comprehension

for {
  a <- List.range(1, 11)
  b <- List.range(1, 11)
  c <- List.range(1, 11)
  xs <- sumsEqualsTo24(a,b,c)
  _ <- pythagTriplebar(xs._1, xs._2, xs._3)
} yield (a,b,c)

Could you please critique my code?


texts: Generate a sequence of coin flips until pattern is hit

texts:
A book on probability says that a sequence of heads and tails is generated by a fair coin asking what is the probability that the pattern T, H, H, H occurs before the pattern H, H, H, H. I have made a generator of such strings. Is it right (I have heard that return statement is not appreciated in Scala)?

def l(s: String): Boolean = {
    if (s.endsWith("hhhh")) return true;
    if (s.endsWith("thhh")) return false;
    l(s + (if (Math.random > .5) "h" else "t"))
}


texts: Trim files by removing bytes from the beginning in bash

texts:
I have files in a store folder, which I want to trim to a particular length by removing bytes from the beginning. My app uses a temp folder for the files manipulation. All files from the previous operations must be taken out form temp, so I use the folder for temporary storing the trimmed files. I also log the errors.
#!/bin/bash

set -euo pipefail

data_service='/path/to/data-service'
store="${data_service}/data/store"
temp="${data_service}/data/temp"
log="${data_service}/logs/log.txt"
max_size=$(( 200000 * 24 ))

{

# Checks if there are any files in 'temp'. It should be empty.
if [ "$( ls -A "${temp}" )" ]
then
    echo "$( date +"%Y-%m-%d %H:%M:%S" ) [ERROR] Temp folder is not empty!" 1>&2
    exit 1
fi

# Loops over all the files in 'store'
for file_path in "${store}/"*
do

    # Trim bigger then 'max_size' files from 'store' to 'temp'
    if [ "$( wc -c < "${file_path}" )" -gt "${max_size}" ]
    then
        file_name="$( basename "${file_path}" )"
        tail -c "${max_size}" "${file_path}" > "${temp}/${file_name}"
    fi

done

# Move all the truncated files back to 'store'
if [ "$( ls -A "${temp}" )" ]
then
    mv "${temp}/"* "${store}/"
fi

} 2>> "${log}"

Any potential problems or ways to improve the code?
Because these are my first steps in writing in bash, the specific things I googled for this code were:

Multiplication and assigning the result to a variable:
max_size=$(( 200000 * 24 ))

Check if there are files in a folder:
if [ "$( ls -A "$temp" )" ]; then .... fi

Get the date and time in a formatted string
$( date +"%Y-%m-%d %H:%M:%S" )

Get the byte size of a file:
"$( wc -c < "$file_path" )"

Copy the last N bytes of a file
tail -c "$max_size" "$file_path" > "$temp/$file_name"

Group commands and redirect STDERR to a log file
{ ... } 2>> log-file

Echo to STDERR of the group
echo 'Error message' 1>&2


texts:
I understand that because of JavaScript's single-threaded execution, long loops or recursive calls could make the browser unresponsive while they execute.

I thought about simulating recursion using setTimeout with a delay of 0, so as to queue the next call to execute as soon as possible.

Here's an example comparing a standard recursive factorial function with an attempt to do the same thing but using setTimeout:

function rFactorial(num)
{
    if (num === 0) return 1;
    else return num * rFactorial( num - 1 );
}

function tFactorial(num, callback, acc) {
    acc = acc || 1;
    if (num === 0) {
        callback(acc);
    }
    else {
        setTimeout(function() {
            tFactorial(num-1, callback, acc*num);
        }, 0);
    }
}

I tested this using the following test:

for (var x = 1; x < 20; x += 1) {
    tFactorial(x, (function(n) {
        return function(result) {
            console.log(rFactorial(n) === result)
        };
    })(x));
}

This worked for that range of numbers, although for higher numbers the two functions seem to give different results. for example, for 100, sFactorial gives 9.332621544394418e+157, while rFactorial gives 9.33262154439441e+157.

I have two questions:

Is this a good approach? Can anyone suggest any improvements etc?
Can anyone shed any light on why the two functions give the same results for lower numbers but different results for higher numbers?


texts: Function that takes a positive integer number and returns the next bigger number formed by the same digits

texts:
I am taking on this challenge on CodeWars. You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:

next_bigger(12)==21
next_bigger(513)==531
next_bigger(2017)==2071

This is my solution:

 def next_bigger(s)
      s.to_s.split("").permutation.to_a.map {|a| a.join("").to_i }.reject { |n| n <= s }.inject do |memo, p|
      (memo-s) < (p-s) ? memo : p
  end
 end

That passes these tests:

Test.assert_equals(next_bigger(12),21)
Test.assert_equals(next_bigger(513),531)
Test.assert_equals(next_bigger(2017),2071)
Test.assert_equals(next_bigger(414),441)
Test.assert_equals(next_bigger(144),414)

But I am being told my code is too inefficient. I am doing a few of these challenges each day to improve my ruby (I am a beginner). Could someone recommend how this could be made more efficient?


texts: Returning IQueryable from my repository in Repository pattern design pattern

texts:
I am developing an application based on Repository design pattern. What should be the return type from the Repository?

This is my UserRepository class:

public class UserRepository : Repository<UserMaster>, IUserRepository
{
    public UserRepository(DbContext context)
        : base(context)
    {

    }
    public UserMaster GetById(int id)
    {
        return FindBy(x => x.Userid == id).FirstOrDefault();
    }

}

The base Repository class:

public abstract class Repository<T> : IRepository<T>
  where T : class
{
    protected DbContext _entities;
    protected readonly IDbSet<T> _dbset;

    public Repository(DbContext context)
    {
        _entities = context;
        _dbset = context.Set<T>();
    }

    public virtual IQueryable<T> GetAll()
    {

        return _dbset.AsQueryable<T>();
    }

    public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {

        IQueryable<T> query = _dbset.Where(predicate).AsQueryable();
        return query;
    }

    public virtual T Add(T entity)
    {
        return _dbset.Add(entity);
    }

    public virtual T Delete(T entity)
    {
        return _dbset.Remove(entity);
    }

    public virtual void Edit(T entity)
    {
        _entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
    }

    public virtual void Save()
    {
        _entities.SaveChanges();
    }
}

Is this the right way to return IQueryable from the repository? If I want to join two tables, where should I implement the join logic? Inside or outside the repository?

Currently my return type is IQueryable from the Repository and I am doing join on the Business layer after calling GetAll() function (returns IQueryable) of the required tables. Is this the right approach?


texts: Searching for a word in a list of tuple extracted from a db via SQL

texts:
Python 3.6 and Sqlite3.

I have a database with something like 300K entries, each entry has several fields (date, username, etc) and a "text" one.  I have a list of 200 words and for each word i have to return the number of entry in the database with the word in the "text" field.
Currently, it takes around 1 second per word to do that. It's fine for 200 words but the list and the db will grow up in the future so i would like to optimize the speed.
Here is how i proceed for now (I won't paste the entire code which is a bit too long but important part but if you need more i'll do it !).

I extract the data from the db with this line and i obtain a list of tuple, each tuple is a row in the db :

db = cursor.execute("select * from mydata").fetchall()

Then I loop on the list of word and i'm looking for the word in the db list like this (row[6] is my "text" field):

for word in wordList:
    for row in db:
        hasFound = re.compile(r"\b"+word.lower()+"\\b")
        if hasFound.search(row[6]):
            compteur += 1
    dicoVolume[word] = compteur

Is there a way to search faster ?


texts:
I just wanted to mess with my friend a little and wanted to text him in Brainfuck. Being a coder like me, I decided, why not just write a quick script to translate it for me?

Considering that most characters that I will be using in a regular English chat will be between 0-127, the algorithm will take the nearest factor of ten. Then it will add the result of the char number modulus that factor. Then I will translate that into Brainfuck.

I am ready to take all criticism so please give your opinion. Also, please test in and find any case where my algorithm will fail.

def letter_to_brainfuck(letter):
    num = ord(letter)
    return '+'*int(num / 10) + '[>++++++++++<-]>' + '+'*(num % 10)

def brainfuck_print(letter_list):
    return ''.join([i +'.>\n' for i in letter_list])

print(brainfuck_print([letter_to_brainfuck(i) for i in list(input())]))


texts:
I was wondering if this implementation of merge sort could be improved. Are there any things that I have done wrong?

void merge(int *a, int *l, int leftCount, int *r, int rightCount) {
int i = 0, j = 0, k = 0;

// Compare l and r and add it to a
while (i < leftCount && j < rightCount) {
    if (l[i] < r[j]) {
        a[k++] = l[i++];
    }
    else {
        a[k++] = r[j++];
    }
}

// Add the leftovers
while (i < leftCount) {
    a[k++] = l[i++];
}
while (j < rightCount) {
    a[k++] = r[j++];
}}

void mergeSort(int *a, int n) {
if (n >= 2) {
    int mid, i, *l, *r;
    mid = n / 2;

    /* Create left and right subarrays */
    // Mid elements from index 0 till mid - 1
    l = (int*)malloc(mid * sizeof(int));
    // From n - mid till n - 1
    r = (int*)malloc((n - mid) * sizeof(int));

    // Fill left subarray
    for (i = 0; i < mid; i++) {
        l[i] = a[i];
    }
    // Fill right subarray
    for (i = mid; i < n; i++) {
        r[i - mid] = a[i];
    }

    // Sort left subarray
    mergeSort(l, mid);
    // Sort right subarray
    mergeSort(r, n - mid);

    // Merge l and r in a
    merge(a, l, mid, r, n-mid);

    // Free the memory
    free(l);
    free(r);
}}


texts: Python code to encrypt and email PDF file using PyPDF2

texts:
This is my first programming project with real world application.  It's purpose is to take a file from a directory, encrypt it with a predetermined password, and email to appropriate recipient.
ID Email and Password are found in a CSV file that I created EmailDict from.
ID and Filename are parsed and dropped into FileDict.  Any feedback is valued and appreciated.

import os
import re
import csv
import PyPDF2
import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart

# Create a dictionary with the csv values for ID, Email and Password
EmailDict = dict()
with open('commissionrepemaillist.csv', 'r') as infile:
    reader = csv.reader(infile)
    for row in reader :
        REP = row[0]
        EMAIL = row[1]
        PASSWORD = row[2]
        EmailDict[REP] = EMAIL, PASSWORD

# create dictionary of IDs and Pdf Files
FileDict = dict()
path = "C:\\Apps\\CorVu\\DATA\\Reports\\Monthly Commission Reports\\Output\\pdcom1"
for FILE in os.listdir(path):
    split = re.split("[_.]", FILE)
    ID = split[1]
    FileDict[ID] = FILE

# encrypt PDF files in FileDict based on ID and Password from EmailDict
for ID in FileDict:
    if ID in EmailDict:
        path = "C:\\Apps\\CorVu\\DATA\\Reports\\Monthly Commission Reports\\Output\\pdcom1\\"
        file = os.path.join(path + FileDict[ID])

        inputStream = PyPDF2.PdfFileReader(file)
        output = PyPDF2.PdfFileWriter()
        output.appendPagesFromReader(inputStream)
        output.encrypt(EmailDict[ID][1])

        with open(file, 'wb') as outputStream:
            output.write(outputStream)

    else : continue

# email encrypted pdf file to appropriate rep

for ID in FileDict:
    path = "C:\\Apps\\CorVu\\DATA\\Reports\\Monthly Commission Reports\\Output\\pdcom1\\"
    file = os.path.join(path + FileDict[ID])
    with open(file, 'rb') as pdf :
        pdfAttachment = MIMEApplication(pdf.read(), _subtype = 'pdf')
        pdfAttachment.add_header('content-disposition', 'attachment', filename=('MonthlyPaidCommission_%s.pdf' % ID))
        text = MIMEText(
        """For Rep Number : %s
        Please use the password previously emailed to open attached file.
        If you have any questions or need assistance please contact  me.
        Thank you""" % ID)
    msg = MIMEMultipart(_subparts = (text, pdfAttachment))
    msg['SUBJECT'] = "Commission Report"
    msg['FROM'] = "me@gmail.com"
    msg['TO'] = EMAIL

    s = smtplib.SMTP("LOCALHOST:587")
    s.starttls()
    s.login('user', 'pwd')
    s.sendmail('me@123.com', EMAIL, msg.as_string())
    s.quit()


texts: Finding number of solutions nqueens 14 by 14 chessboard

texts:
I have written a code to solve the N-Queen problem for a 14 by 14 chessboard. There are preplaced queens (see below for the sample input and output). The lines of sample input (after the 3) represent the positions of the preplaced queens. For example, "1 1 2 9 3 6 4 10" refers to the 4 preplaced queens are at (1st row 1st column), (2nd row, 9th column), (3rd row 6th column), (4th row, 10th column).
I am hoping that it will return me the number of solutions. But when I tried running the code, I got time limit exceeded, even for the sample input.
I will try the list of tuples method, but let me know if there is a more efficient implementation. Thanks in advance
[![Question screenshot][1]][1]
Sample Input
3
1 1 2 9 3 6 4 10
1 9 12 8 8 5 2 7
2 10 10 3

Sample Output
39
32
2414

import sys

def nQueens(n, pre_placed_rows, pre_placed_cols, N, state=[], col=1):
    if col > n: return [state]
    res = []

    for i in range(1, n+1):
        if invalid(state, i): continue
        for sol in nQueens(n, pre_placed_rows, pre_placed_cols, N, state + [i], col+1):
            if N == 2: # 2 preplaced queens
                if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1]:
                    res.append(sol) #[sol]
            elif N == 3:  # 3 preplaced queens
                if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1] and sol[pre_placed_cols[2]-1] == pre_placed_rows[2]:
                    res.append(sol)
            else: # 4 preplaced queens
                if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1] and sol[pre_placed_cols[2]-1] == pre_placed_rows[2] and sol[pre_placed_cols[3]-1] == pre_placed_rows[3]:
                    res.append(sol)
    return res

def invalid(s, r2): # is it safe to put the queen
    if not s:
        return False
    if r2 in s:
        return True
    c2 = len(s) + 1
    return any(abs(c1-c2) == abs(r1-r2) for c1, r1 in enumerate(s, 1))

num_case = int(sys.stdin.readline())
for _ in range(num_case):
    s = sys.stdin.readline().split()
    N = len(s) // 2
    pre_placed_rows = []
    pre_placed_cols = []
    n = 14
    for i in range(N):
        pre_placed_rows.append(int(s[2*i]))
        pre_placed_cols.append(int(s[2*i+1]))

    print(len(nQueens(n, pre_placed_rows, pre_placed_cols, N)))


texts: Removing duplicate hashes in an array while keeping count of the times the hash was present

texts:
I have an array of hashes (price_params['items']) where each item has a key called quantity what I'm trying to do is to clean every duplicate of each item but keeping the count of the times the item was found in the array in the unique one that I'm leaving (using the quantity key to keep that value)

This is my code so far:

def clean_duplicated_offers
  price_params['items'].each do |item|
    max_count = price_params['items'].count(item)
    next unless max_count > 1
    price_params['items'].delete(item)
    item['quantity'] = max_count
    price_params['items'] << item
  end
end

It works well, but it feels weird to delete every occurrence of the item in the array just to add it back to it.

Is there any better way to achieve this?


texts: Implement a generic Fibonacci sequence in Rust without using Copy trait

texts:
I'm trying to learn Rust and am a beginner. How does one go about implementing a generic version of the Fibonacci sequence without using Copy trait in Rust? My code is given below.

I had to use Copy trait, otherwise the compiler would complain

  cannot move out of borrowed content [E0507]

in the method next() (everywhere I have borrowed from self). I understand the error, but I'm not sure how this could be done without copying. Also, other comments and observations are welcome!

lib.rs

pub mod fib_trait;

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}

fib_trait.rs

extern crate num;

pub mod fib_trait {

    use fib_trait::num::traits::*;
    use std::ops::Add;

    #[derive(Clone, Copy)]
    pub struct Fibonacci<T> where
    T : Zero + One + Add + Copy {
        curr : T,
        next : T,
    }

    impl<T> Fibonacci<T> where
    T : Zero + One + Add  + Copy{
        pub fn new() -> Fibonacci<T> {
            Fibonacci {
                curr : T::zero(),
                next : T::one(),
            }
        }
    }

    impl<T> Iterator for Fibonacci<T> where
    T : Zero + One + Add + Copy {
        type Item = T;

        fn next(&mut self) -> Option<T> {
            let c : T = self.next;
            self.next = self.next + self.curr;
            self.curr = c;
            let n : T = self.next;
            Some(n)
        }
    }

    #[test]
    pub fn fib_test() {
        let mut f : Fibonacci<u32> = Fibonacci::new();
        assert_eq!(f.next(), Some(1));

        let mut next_val = 1;
        let mut curr_val = 0;
        for i in Fibonacci::<u32>::new().take(4) {
            let c = next_val;
            next_val = curr_val + next_val;
            curr_val = c;
            assert_eq!(i, next_val);
        }
    }
}


texts: Dependency injection for a bus with a stop-request display application

texts:
I have been told that my implementation below doesn't need dependency injection, however Jeffrey Way uses DI in two similar examples in this tutorial: https://laracasts.com/lessons/tell-dont-ask and that is confusing me. Testing is an important aspect in my application, if that makes any difference.

This is the code I implemented so far.

Is my code incorrect?

Model Bus.php

namespace App\Models;

class Bus {

    private $screen;
    private $isStopped;

    function __construct(Screen $screen)
    {
        $this->screen = $screen;
    }

    public function stops()
    {
        $this->isStopped = true;
        $this->screen->hideRequestedSign();
    }

    public function starts()
    {
        $this->isStopped = false;
    }
}

Model Screen.php

namespace App\Models;

class Screen {

    private $buttons;
    private $isSignDisplayed;

    public function displayRequestedSign()
    {
        $this->isSignDisplayed = true;
    }

    public function hideRequestedSign()
    {
        $this->isSignDisplayed = false;
    }

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

Model Button.php

namespace App\Models;

class Button {

    private $screen;
    private $pressed = false;

    function __construct(Screen $screen)
    {
        $this->screen = $screen;
    }

    public function press()
    {
        $this->pressed = true;
        $this->screen->displayRequestedSign();
    }

    public function isPressed()
    {
        return $this->pressed;
    }

}

Test BusStopRequestTest.php

class BusStopRequestTest extends TestCase {

    public function test_press_button()
    {
        $button = new Button(new Screen);

        $button->press();

        $this->assertTrue($button->isPressed());

    }

    public function test_screen_display_requested_stop_sign()
    {
        $screen = new Screen();
        $button1 = new Button($screen);
        $button2 = new Button($screen);
        $button3 = new Button($screen);

        $button1->press();

        $this->assertTrue($screen->isSignDisplayed());

    }

    public function test_bus_stops_and_resets_sign()
    {
        $screen = new Screen();
        $button1 = new Button($screen);
        $button2 = new Button($screen);
        $button3 = new Button($screen);

        $bus = new Bus($screen);

        $button1->press();
        $bus->stops();
        $bus->starts();
        $button2->press();

        $this->assertTrue($screen->isSignDisplayed());

    }
}


texts: Indenting a function to recursively find filenames

texts:
I wrote this function that recursively traverses a given directory resolves
the relative file-names to absolute file-names and yields the resolved file-name if it matches a given pattern. You can specify a callback function as well.

The first issue I have with this function is that it is a bit hard to comprehend, I think this problem can be reduced with proper indentation of the generator expressions.

The second thing I would like help with is, How do i reduce the repeated block of code?

import fnmatch
import os
import sys

def find(root, pattern, *callback):
    if not callback:
        for _, _, files in  ((root, _, (os.path.join(root, filename)
        for filename in files if fnmatch.fnmatch(filename, pattern)))
        for (root, _, files) in os.walk(root)):
            for filename in files:
                yield filename

    callback = callback[0]
    for _, _, files in  ((root, _, (os.path.join(root, filename)
    for filename in files if fnmatch.fnmatch(filename, pattern)))
    for (root, _, files) in os.walk(root)):
        for filename in files:
            yield callback(filename)

def cb(filename):
    print filename

for filename in find('/home/dwilson', '*.py', cb):
    pass


texts: Best way to pass parameters to Factory class?

texts:
So I have a series of objects, which I will call Impl1, Impl2, and Impl3.  They each implement an interface, called IImpl.  I have a Factory class who's task is to retrieve the ImplX which is appropriate for a given circumstance, and pass it on to its callers.  So the code in the factory looks like:

public IImpl GetInstance(params object[] args)
{
    if (args[0]=="Some Value")
         return new IImpl1();
    else if (args[0]=="Other Value")
         return new IImpl2(args[1]);
    else
         return new IImpl3(args[1]);
}

So depending on the arguments passed in, different instances are selected.  All well and good and works ok.  The problem now is, that I have a class which needs to call this factory method.  It has no references to IImplX, which is good, but it winds up having to know exactly how to construct the input array to GetInstance, in order to ensure it receives the correct kind of instance.  Code winds up looking like:

switch (_selectedInputEnum)
{
    case InputType.A:
        myIImplInst = Factory.GetInstance("Some Value");
    case InputType.B:
        myIImplInst = Factory.GetInstance("Other Value",this.CollectionB);
    case InputType.C:
        myIImplInst = Factory.GetInstance("Third Value",this.CollectionC);
}

This feels very redundant, and off somehow.  What would be the best way to abstract the actual parameters of the factory?  I feel like with the above switch statement, I am strongly coupled to the implemenations of IImplx, even if I don't have a direct reference.


texts: Simultaneous search with Google and Bing, remember the last engine

texts:
A proof of concept app to run the same query on both Google and Bing. For instance, if one of the engines takes too long on a slow connection or the results are not satisfactory, the same query can be run on the other engine with single button click.

The whole app is small single file with < 200 loc. Can be saved and loaded locally with the file:// protocol in the browser.

Flexbox is used to display all labels, forms and buttons with equal gutters inbetween. Perhaps can be improved.

Can be tested here:
https://dmitriz.github.io/search-app/

I am interested in any advice on improving the code and/or layout or any other suggestions.

init();
function init () {
  window.engine = 'bing';
  window.engine_display = document.getElementById('engine');
  window.search_form = document.getElementById('search_form');
  window.results_elm = document.getElementById('results');
  window.notice_elm = document.getElementById('notice');

  set_engine(window.engine);
}
function set_engine (engine) {
  console.log('Change search engine to ', engine);

  window.engine = engine;
  window.engine_display.textContent = capitalize(engine);
  window.search_form.action = engine_url(engine);

  set_notice(window.notice_elm, engine);
}
function set_notice (element, engine) {
  element.textContent = 'bing' === engine
    ? 'Search results will appear here...'
    : 'Search results will appear in another tab as Google refuses to run in a frame...'
}
function search () {
  var isGoogle = 'google' === window.engine;

  window.notice_elm.style.display  = isGoogle ? 'block'  : 'none';
  window.results_elm.style.display = isGoogle ? 'none'   : 'block';
  window.search_form.target        = isGoogle ? '_blank' : 'iframe';

  return window.search_form.submit();
}
function capitalize (string) {
  return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
function engine_url (engine) {
  return 'https://www.' + engine + '.com/search';
}
body, html, main {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0
}
html {
 height: 100%;
}
iframe {
 width: 100%;
 border: none;
 border-top: solid thin;
 border-top-style: groove;
}
input, button {
  font-size: .6em;
}
.margin-left, .items-ml > * ~ * {
 margin-left: 1em;
}
.margin-left-0 {
 margin-left: .2em;
}
.margin-top, .items-mt > * + * {
 margin-top: .6em;
}
.margin-adjust {
 margin-top: -.2em;
 /*display: block;*/
}
.padding-box {
 padding: .5em;
}
.flexbox {
 display: flex;
}
.in-block {
}
.column {
 flex-flow: column;
}
.flex-item-grow {
 flex: 1;
}
.ai-stretch {
 align-items: stretch;
}
.bold {
 font-weight: bold;
}

 <form
  id="search_form"
  class="flexbox items-ml"
  onsubmit="search()"
 >

   Web Search:

  <input
   class="flex-item-grow"
   type="search"
   name="q"
   placeholder="Type some text here"
   autofocus=""
  >
 </form>

   <button
    onclick="set_engine('google'); search()"
   >
    Google!
   </button>

   <button
    onclick="set_engine('bing'); search()"
   >
    Bing!
   </button>

    Default:

    Google

  There would be Bing Search here but your browser does not support inline frames.


texts: More efficient loops to generate unpronounceable words

texts:
I wanted to write a function to generate only unpronounceable words. I realised afterwards that the same thing could probably be achieved by just taking out the vowels. Regardless, I feel that there is probably a better way to iterate through the syllable checking.

function unpronouncable(length) {
    var twoLetters = ['aa','ae','ag','ai','ar','ao','as','aw','ay','ba','da','de','ed','ef','eh','ei','em','en','er','et','ex','fa','fe','fu','gi','go','hm','ho','so','id','ie','jo','ka','ki','ku','lo','mi','mm','mu','na','ne','nu','od','oe','oi','om','op','os','os','oy','pe','pi','qi','re','se','ta','ti','ut','wo','xi','xi','ya','yu','za','zo','co','my','qu','ge','ro','ra','xa','wa'];
    var threeLetters = ['thm','css','dvd','buh','bad','rue','cun','pub','puk','pul'];

    var letters = "abcdefghijklmnopqrstuvwxyz";
    var string = "";
    for (var i = 0; i < length; i += 1) {
        string += letters[Math.floor(Math.random() * letters.length)];
    }

    function generate() {
        for (var j = 0; j < string.length; j += 1) {
            var test = string.slice(j,j+2);
            for (var k = 0; k < twoLetters.length; k += 1) {
                if (twoLetters[k] === test) {
                    console.log('Has two letter syllable');
                    return unpronouncable(length);
                }
            }
        }
        for (var j = 0; j < string.length; j += 1) {
            var test = string.slice(j,j+3);
            for (var k = 0; k < twoLetters.length; k += 1) {
                if (threeLetters[k] === test) {
                    console.log('Has three letter syllable');
                    return unpronouncable(length);
                }
            }
        }

        return string;
    }
    return generate();
}

console.log(unpronouncable(8));


texts:
Could use some help with my presentation in Software Development. I'm presenting how I reworked a game's parser (SpaceTaxi). Basically we take in a .txt file with ASCII characters and convert them into entities that can be rendered in our game.

Input, Output

In between the input and output I've written a parser. I've tried to follow the Facade Design Pattern with the SOLID principles in mind.

I'm not sure how much code I should show here as I don't want to flood you, so I am going to upload some of it but tell me if it's sufficient.

What my code is intended to do

The parser should be a single instance and when called (Parser.StartParse(string txtFile)) the parser should go through a txt file comparing ascii characters with image files.
The image files are given to our project.

IParse.cs

public interface IParse {
    void Parse(string[] txtFile);
    void Add(List<char> map);
}

public class ParseObstacles : IParse {

        public Dictionary<char, string> Dict;
        public List<Entity> Entities;

        public ParseObstacles() {
            Dict = new Dictionary<char, string>();
            Entities = new List<Entity>();
        }

        /// <summary>
        ///     Extracts the txt information about what each character represents.
        ///     Example from the-beach.txt: "A) aspargus-edge-left.png"
        ///     Here we split ')' to first get the character, A, and it's
        ///     correspondent filename, 'aspargus-edge-left.png'.
        /// </summary>
        public void Parse(string[] txtFile) {
            foreach (var i in txtFile) {
                if (i.Contains(")")) {
                    var tile = i.Split(')')[0].ToCharArray()[0];
                    var name = i.Split(')')[1].Trim();
                    Dict.Add(tile, name);
                }
            }
        }

        public void Add(List<char> map) {
            ParseHelper.AddEntities(map, Dict, Entities);
        }
    }

I intended for the parser to follow the facade pattern.
Does this code in fact implement the facade pattern?


texts:
I need a version of the mvc RouteValueDictionary that I can chain Add calls to, ie:

new RouteValueDictionaryExtended()
        .AddValue("controller", "Home")
        .AddValue("action", "Index")
        .AddValue("id", 3)

Is there a more description name I can use for this instead of just "Extended"?

   public class RouteValueDictionaryExtended : System.Web.Routing.RouteValueDictionary
    {
        public RouteValueDictionaryExtended() : base() { }
        public RouteValueDictionaryExtended(object values) : base(values) { }
        public RouteValueDictionaryExtended(System.Collections.Generic.IDictionary<string,object> dict) : base(dict) { }
        public RouteValueDictionaryExtended AddValue(string key, object obj)
        {
            var newDict = new RouteValueDictionaryExtended(this);
            newDict.Add(key, obj);
            return newDict;
        }
    }


texts: Autotools detect C++ language standard support

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

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

A macro for detecting what version of C++ is available and defining the correct flags:

AC_DEFUN(
    [AX_FUNC_THOR_LANG_FLAG],
    [
        minLangFeature=$1
        AS_IF([test "$2" = ""], [maxLangFeature=17], [maxLangFeature=$2])
        AS_IF([test $minLangFeature -gt $maxLangFeature], AC_MSG_ERROR([Invalid Language Value],[1]))

        AC_LANG(C++)
        CXXMaxLanguage=03
        CXXExpLanguage=03
        AX_CHECK_COMPILE_FLAG([-std=c++11], [AC_SUBST([CXXMaxLanguage],11) AC_SUBST([StdFlag11],[-std=c++11])])
        AX_CHECK_COMPILE_FLAG([-std=c++14], [AC_SUBST([CXXMaxLanguage],14) AC_SUBST([StdFlag14],[-std=c++14])])
        AX_CHECK_COMPILE_FLAG([-std=c++17], [AC_SUBST([CXXMaxLanguage],17) AC_SUBST([StdFlag17],[-std=c++17])])
        AX_CHECK_COMPILE_FLAG([-std=c++1x], [AC_SUBST([CXXExpLanguage],11) AC_SUBST([ExpFlag11],[-std=c++1x])])
        AX_CHECK_COMPILE_FLAG([-std=c++1y], [AC_SUBST([CXXExpLanguage],14) AC_SUBST([ExpFlag14],[-std=c++1y])])
        AX_CHECK_COMPILE_FLAG([-std=c++1z], [AC_SUBST([CXXExpLanguage],17) AC_SUBST([ExpFlag17],[-std=c++1z])])

        #CXX_STD_FLAG
        #CXXSTDVER

        AS_IF(
            [test $minLangFeature -le $CXXMaxLanguage],
            [
                AS_IF(
                    [test $maxLangFeature -le $CXXMaxLanguage],
                    [AC_SUBST([CXXSTDVER], [$maxLangFeature])],
                    [AC_SUBST([CXXSTDVER], [$CXXMaxLanguage])]
                )
                AC_SUBST([CXX_STD_FLAG], [$(eval echo "\${StdFlag${CXXSTDVER}}")])
                ],
                [AS_IF(
                    [test $minLangFeature -le $CXXExpLanguage],
                    [
                        AS_IF(
                            [test $maxLangFeature -le $CXXExpLanguage],
                            [AC_SUBST([CXXSTDVER], [$maxLangFeature])],
                            [AC_SUBST([CXXSTDVER], [$CXXExpLanguage])]
                        )
                        AC_SUBST([CXX_STD_FLAG], [$(eval echo "\${ExpFlag${CXXSTDVER}}")])
                ],
                [AC_MSG_ERROR([

Error: Need C++${minLangFeature} but the compiler only supports ${CXXMaxLanguage} (Experimental ${CXXExpLanguage})

                    ], [1])]
            )]
        )
    ]
)

Usage:

AX_FUNC_THOR_LANG_FLAG(<min acceptable C++> [, <max acceptable C++>])

If you don't specify a max then 17 is used as the default. It works out what flags are available to modify the behavior of the C++ compiler to a different version of the standard and then defines the two macros:

CXXSTDVER      /* Will hold 03 11 14 or 17 */
CXX_STD_FLAG   /* Will hold the flag needed be the C++ compiler */

It considers -std=c++1[147] as standard version and will use these if they satisfy the minimum requirements. It considers -std=c++1[xyz] as experimental versions and will only use these if the minimum requirements cannot be achieved by using the standard version flags.


texts: Discrete slide mechanism (with average rating display) for liking posts on a social network app

texts:
I'm thinking about implementing a "liking" mechanism for a social network app (using Parse) whereby users select a value from a discrete slider beneath each post. The slide would range from 0-5 and reflect the post's value to users. An example of the slider is below:

https://material.io/guidelines/components/sliders.html#sliders-discrete-slider

Each "Post" ParseObject would have a column (Number) called "likeCount". This column should be updated for each "like". A change listener would wait for a user to release their finger from the slider and then store that value in the Post ParseObject, i.e. first by storing the user's objectId in a column (Array) that stores unique objectIds:

Sting currentUserObjectId = ParseUser.getCurrentUser().getObjectId();
postObject.addAllUnique("likedBy", Collections.singletonList(currentUserObjectId))

Updating the likeCount on the postObject would work as follows (using something like https://github.com/sonyckovoor/Discrete-Slider/blob/master/sample/src/main/java/in/sc9/samples/discreteslider/MainActivity.java):

@Override
public void onProgressChanged(DiscreteSlider seekBar, int value, boolean fromUser) {

 int likeCountInc = value;
 postObject.increment("likeCount", likeCountInc)

}

Lastly, I'd set the likeCount TextView in the post itself:

int likeCount_int = yeet.getInt("likeCount").size();
int likedByList_int = yeet.getList("likedBy").size();
int averageLikeValue_int = likeCount_int / likedByList_int;
String averageLikeValue_string = Integer.toString(averageLikeValue_int);
holder.averageLikeValue.setText(averageLikeValue_string);

Would Integer division be a problem here? Is there a more effective implementation for this design?


texts: C String Processing -- magnet link example

texts:
I'm trying to get my head around C-string processing. I've decided to try my hand at making a dirt-simple magnet link generator.  The format that a magnet link needs is

magnet:?xt=<hash>&tr=tracker1url&tr=tracker2url&....&tr=trackerNurl

This program takes a hash as an argument on the command line, and takes lines on standard input which are either empty lines or the URLs of trackers.

Am I doing this in a sane way? What can I do better? Please note that I'm fairly new to C, so if you see anything weird or dangerous, let me know about that as well.

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

#define SIZE 4096

/*
 * Exit with the given code, and print an error
 * message if ec != 0
 */
void die(int ec, char *message) {
    if (ec) {
        fprintf(stderr, "ERROR: %s\n", message);
    }

    exit(ec);
}

/*
 * takes one input argument -- the hash code
 * of the thing you're looking to generate a
 * magnet link for, on the command line, and
 * then a list of trackers on the stdin stream.
 */
int main(int argc, char **argv) {
    // If there is no
    if (argc < 2)
        die(1, "No hash code given!");

    // buf is the internal buffer. bufEnd is supposed
    // to be a pointer to the very end of the string
    // to prevent linear time string concatenation.
    char buf[SIZE];
    char *bufEnd;

    // line is a buffer for each line of standard in
    char line[SIZE];

    // 20 is the number of chars in "magnet:?xt=..."
    // magic number is bad but i don't know a better way
    if (20 + strlen(argv[1]) >= SIZE)
        die(1, "buffer overflow detected");

    // Here we initialize buffer
    bufEnd = buf + snprintf(buf, SIZE, "magnet:?xt=urn:btih:%s", argv[1]);

    // keep reading input lines, adding "&tr=..." params
    // to the magnet link for non-empty lines
    while (fgets(line, SIZE, stdin)) {
        int len = strlen(line); // find out how big this line is

        // check for empty line. skip it if it's empty
        if (!(strcmp(line, "\n"))) continue;

        // check to see if there's room left in the array
        // and if so, then add the next arg.
        if (SIZE - (bufEnd - buf + len + 4) > 0) {
            bufEnd += sprintf(bufEnd, "&tr=%s", line) - 1;
        }
        else die(1, "buffer overflow detected");
    }

    // change the trailing newline into a nul byte
    if (bufEnd - buf < SIZE) {
       *bufEnd = '\0';
    }
    else die(2, "crazy buffer overflow detected");

    // output it with backwards brackets (to show whitespace...
    // debugging purposes)
    fprintf(stdout, ">%s<\n", buf);
    fflush(stdout);
    return EXIT_SUCCESS;
}


texts:
I've always been used to write my own CSS but I decided to give a go to twitter-bootstrap and I want to make sure I'm not using more HTML containers that I need to:

This is my code for a single element of a list:

     <input type="email" class="form-control" placeholder="Enter email" value="vitor.monteiro@ubs.com">

My main issue with this is to have two
 wrapping single elements, in the first case it's an <input> and then a . If this was normal HTML I would condemn the DOM code as being inefficient and cluttered as the
 would not be necessary.

Is this a proper usage of twitter-boostrap if I want to create a form group element where the left side is an input and the right side the - icon?


texts: can this php function be written to perform better?

texts:
I have this function takes a long time to complete. Is there a way i can improve it to quicken the procedure

function do_updatebonus() {
    global $site_config;

    $res200 = SQL_Query_exec("SELECT DISTINCT userid FROM peers WHERE seeder = 'yes'");

    while ($row200 = mysql_fetch_assoc($res200)) {
        $userid = $row200["userid"];
        $res201 = SQL_Query_exec("SELECT COUNT(torrent) FROM peers WHERE seeder = 'yes' AND userid = $userid");

        $c = mysql_result($res201, 0);
        if ($c >= 5) {
            SQL_Query_exec("UPDATE users SET seedbonus = seedbonus + '" . $site_config["bonuspertime"] . "' WHERE id = $userid");
        }
    }
}


texts: using method missing to reduce the code in ruby

texts:
I have a set of Class methods which is :

class << self
def increment_value
  self.first.increment_value
end

def max_work_hours_per_day
  self.first.max_work_hours_per_day
end

def fast_completion_day
  self.first.fast_completion_day
end

def super_fast_completion_day
  self.first.super_fast_completion_day
end

def ludicrous_completion_day
  self.first.ludicrous_completion_day
end

def budget_completion_day
  self.first.budget_completion_day
end
end

Since all the methods call self.first.atttibute where attribute is the same name as function name. I think we can reduce this to a single method. Something like method_missing is there in Ruby , but since I am not very good at meta programming , I am seeking advise here.


texts: Running a MySQL query with an admin class

texts:
This is my admin class, DB class and how I use OOP.

I am looking for ways to improve my code to make better use of OOP. Please help me if you think I can improve my code in some way.

db.class.php

class database
{
    private $conn;
    private $db_name = 'profil_penduduk';
    private $db_user = 'root';
    private $db_pass = '';
    private $db_host = 'localhost';

    public function connect()
    {

        $this->conn = null;
        try
        {
            $this->conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $exception)
        {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}

admin.class.php

class admin
{
    private $conn;

    function __construct()
    {
        # code...
        $database = new database();
        $db = $database->connect();
        $this->conn = $db;
    }

    public function runQuery($sql)
    {
        # code...
        $stmt = $this->conn->prepare($sql);
        return $stmt;
    }
}

This is how I fetch the data:

index.php

$auth_admin = new admin();

$admin_id = $_SESSION['admin_session'];

$stmt = $auth_admin->runQuery("SELECT * FROM admin WHERE admin_id=:admin_id");
$stmt->execute(array(":admin_id"=>$admin_id));

$adminRow=$stmt->fetch(PDO::FETCH_ASSOC);

Is there a better way for me to do this? Should I use CRUD? Or should I make a function with this query:

"SELECT * FROM admin WHERE admin_id=:admin_id"

inside the admin class?

Should I also use interface in my class? I don't understand much about interfaces, either.


texts: R Function to Generate Predictions from Ratings and Save Results

texts:
I am trying to generate predictions using the function below in combination with sapply. My actual datasets are very large, I am attempting to make 1.5 million predictions with this function and it is currently taking about 10 seconds per prediction which is... prohibitive to say the least.

mean_rating <- function(df){
  #mean_rating <- function(query_user,query_movie){
  user<-df$user
  movie<-df$movie
  u_row<-which(U_lookup == user)[1]
  m_row<-which(M_lookup==movie)

  knn_match<- knn_txt[u_row,]

  knn_match<-as.numeric(unlist(knn_match))

  dfm_mov<- dfm[,m_row]

  dfm_test<- dfm_mov[knn_match]

  c<-mean(dfm_test[dfm_test!=0])
  c1<-mean(dfm_mov[dfm_mov!=0])
  ifelse(c!="NaN",c,c1)
}
test<-sapply(1:nrow(probe),
             function(x) mean_rating(probe[x,]))

The inputs to this function include the following.
Sparse matrix dfm

library(Matrix)
    dput(dfm)
new("dgTMatrix"
    , i = c(0L, 1L, 2L, 4L, 5L, 6L, 8L, 0L, 1L, 2L, 3L, 4L, 6L, 7L, 8L,
0L, 2L, 3L, 6L, 7L, 8L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 0L, 1L, 3L, 4L, 6L, 7L, 8L, 9L, 0L, 2L, 3L, 5L, 6L, 7L, 9L,
0L, 1L, 2L, 3L, 4L, 5L, 6L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 9L)
    , j = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L)
    , Dim = c(10L, 10L)
    , Dimnames = list(NULL, NULL)
    , x = c(4, 3, 1, 2, 3, 1, 2, 1, 3, 3, 2, 3, 3, 3, 4, 2, 1, 2, 3, 2,
1, 4, 1, 2, 2, 3, 2, 3, 4, 1, 4, 1, 3, 4, 3, 2, 2, 2, 4, 1, 2,
2, 1, 2, 3, 1, 1, 1, 4, 1, 1, 2, 1, 1, 1, 4, 3, 3, 2, 1, 2, 2,
1, 1, 3, 3, 4, 1, 2, 4, 2, 4, 1, 2, 2, 3, 4, 2, 1, 2, 4)
    , factors = list()
)

My probe dataset, these are the user movie combinations I am trying to predict for.

dput(probe)
structure(list(X = c(1145185L, 951920L, 1137277L, 180365L, 353195L
), movie = c(1L, 100L, 10000L, 10002L, 10004L), user = c(10L,
1000004L, 1000033L, 1000035L, 1000053L), Rating = c(4L, 4L, 3L,
5L, 4L)), .Names = c("X", "movie", "user", "Rating"), row.names = c("1145185",
"951920", "1137277", "180365", "353195"), class = "data.frame")

My U_lookup table, this is where I convert from the actual id of a user to the row number of the matrix they are in.

dput(U_lookup[1:10,])
c(10L, 100000L, 1000004L, 1000027L, 1000033L, 1000035L, 1000038L,
1000051L, 1000053L, 1000057L)

My M_lookup table, this is where I convert from the actual id of a movie to the row number of the matrix they are in.

dput(M_lookup[1:10,])
c(1L, 10L, 100L, 1000L, 10000L, 10001L, 10002L, 10003L, 10004L,
10005L)

knn_txt is where I'm storing all the users nearest neighbors. Dfm and knn_text would have the same user in every row. I.e., row 1 in dfm would equate to the same user that is in row 1 of knn_text.

dput(knn_txt)
structure(list(V1 = c(1, 2, 1, 7, 5, 3, 2, 9, 1, 3), V2 = c(7,
9, 5, 5, 3, 4, 2, 7, 4, 9), V3 = c(2, 9, 6, 3, 8, 9, 4, 7, 1,
6)), .Names = c("V1", "V2", "V3"), row.names = c(NA, -10L), class = "data.frame")

Edit: As I have done some more testing myself it does seem like a lot of the time savings could come from more efficiently subsetting my large sparse matrix, dfm. I am planning on trying some different formats of the matrix, in addition to maybe looking at looping rather than using sapply (just because then I could say for user i, if user i=i-1 then I don't need to re-subset the matrix).


texts: F# function to concatenate some DSL scripts with indentation

texts:
I'm rather new to F# and functional programming. I wrote the following method to concatenate some custom dsl scripts. The function works are expected without errors. I wanted to know if there was a better way to rewrite this function.

let foldScript (storeAppScripts : seq<string * string * string>) =
    storeAppScripts
       |> Seq.choose( fun (store, app, script) ->
                            match script with
                                | "" -> None
                                | _ -> Some (store, app, script) )
       |> Seq.groupBy(fun (store, app, script) -> store)
       |> Seq.map(fun (store, group) -> store, (group
                                                    |> Seq.groupBy(fun (_, app, _)-> app)
                                                    |> Seq.map(fun (app, group) -> app , (group |>  Seq.fold(fun accum (_,_, script) -> sprintf "%s\r\n%s" accum script) ""))
                                                    |> Seq.map(fun (app, script) -> sprintf "\r\n\tuse Application = %s  %s"  app (script.ToString()))))
        |> Seq.map(fun (store, script) ->
                                    sprintf "use Store=%s%s" store (script |> Seq.fold( fun accum appScript -> sprintf "%s%s" accum appScript) ""))
        |> Seq.fold(fun acc script -> sprintf "%s\r\n%s" acc script) ""

let s = [("s1", "a1", "script1"); ("s1", "a2", "script2");  ("s2", "a3", "script4")]
let r = foldScript s

//Expected result
// use Store=s1
//    use Application = a1
//      script1
//    use Application = a2
//      script2
// use Store=s2
//    use Application = a3
//      script1


texts: Null check when enabling Up navigation in Android

texts:
This upvoted SO answer and this upvoted SO answer both check for null in a similar way: they call a function in the if or assert statement and "throw away" the result and then call the same method again in the success clause and operate on the result.

I am new to Android development and have limited knowledge of Java, but my experience in other languages (and every bone in my body) tells me it would be better to store the result of the function in a local variable, test that in the if statement and then use that local variable value in the success clause like this:

ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
    actionBar.setDisplayHomeAsUpEnabled(true);
}

Am I missing something (because the answers on SO are upvoted and no-one has suggested this alternative); is my suggestion above flawed in Java?


texts:
I have this loop that iterates and assigns a variable to true depending on the different conditions

for (const element of actionsReferences) {
  if (element === 'accept') {
    this.showAcceptButton = true
  } else if (element === 'reject') {
    this.showRejectButton = true
  } else if (element === 'transfer') {
    this.showTransferButton = true
  }
}

How can i get the same result by avoiding if () ?


texts: Pythonic sieve of Erasthotones that saves results to file

texts:
I'd like to have some feedback on this sieve of erasthotones that I've wrote. It outputs all prime numbers up to n correctly (I've tested with the first 10k prime numbers).

Is this well written? Does it look good for python programmers?

I've made the math up to the sqrt of n + 1, which improved the performance a lot.

import time
import sys
from math import sqrt

def notMarkedValue(n):
    """
    Returns True if parameter is a possible prime number, False otherwise
    """
    return n != -1

def sieve(val):
    """
    Sieve of Eratosthenes implementation. Finds all prime numbers up to n
    """
    primes = [x for x in range(2, val)]
    for n in range(2, int(sqrt(val)+1)):
        if notMarkedValue(n):
            for i in range(2, val):
                index = (i*n) - 2 # shift index down -2 because 0 and 1 are not in the list
                if index < len(primes):
                    primes[index] = -1
    return filter(notMarkedValue, primes)

def saveToFile(primes):
    """
    Saves the input to a file
    """
    with open('output', 'w+') as f:
        for n in primes:
            f.write(str(n) + ' ')

def getMaxNumber():
    """
    Gets, from passed arguments if provided or input otherwise, the number in which all prime numbers up to it will be calculated
    """
    return int(sys.argv[1]) if len(sys.argv) > 1 else int(input('Find all primes up to: '))

def main():
    n = getMaxNumber()
    print("-- counting primes...")
    start = time.clock()
    primes = sieve(n)
    end = time.clock()
    print("-- calculated all prime numbers up to {0} in {1} seconds".format(n, (end - start)))
    print("-- saving to file \"output\"...")
    saveToFile(primes)

if __name__ == '__main__':
    main()

One thing that I've thought was about making def sieve() return a list(filter(notMarkedValue, primes)), so that I'd have a list that could be enumerated later, but I didn't as I thought it'd be a bit overkill.

Edit: Now that I'm thinking of it, I should have added to its docstring that it returns a filter object. :-)


texts: Contains all elements and duplicates are taken into account

texts:
The idea is to have a function which checks if all elements in a list are contained in another list. But not just the containedness has to be true, but also the times of containedness.
One could say the function has to be an extended version of containsAll , which checks only the containedness.
Here's my implementation of such a function:
fun main(args: Array<String>) {
    val toCheck = listOf(1, 2, 3, 4, 5, 6, 1, 1, 3)
    val expected = listOf(1, 1, 1, 3, 3, 4)

    val result = containsAllSameCount(toCheck, expected)
    println("Result => $result")

    val expected2 = listOf(1, 1, 3, 3, 4) // One 1 is missing!
    val result2 = containsAllSameCount(toCheck, expected2)
    println("Result 2 => $result2")
    /*
        Result => true
        Result 2 => false
     */
}

fun containsAllSameCount(toCheck: List<Int>, expected: List<Int>): Boolean {
    for (current in expected) {
        var currentInExpected = expected.filter { it == current }
        var currentInToCheck = toCheck.filter { it == current }

        if (currentInExpected.size != currentInToCheck.size) {
            return false
        }
    }

    return true
}

It's clear to me, that the filter-methods are used multiple times, when the same element is contained multiple times. Therefore I suppose that my implementation isn't the most efficient way to solve the task.
What do you think about my implementation?
What's a better way to solve the way?


texts:
I recently wrote a program that reads a plain text file, and compares every line and alerts you if any are similar, based on a float value that you pass in to a function.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class DuplicateLineFinder {

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

        final float SIMILARITY_RATE = 0.75f;

        String fileLocation = System.getProperty("user.home") + "/Desktop/";
        String fileName = "lines.txt";
        BufferedReader file = new BufferedReader(new FileReader(fileLocation + fileName));

        List<String> lines = new ArrayList<String>();
        String line;
        while((line = file.readLine()) != null) {
            lines.add(line);
        }

        for (int i = 0; i < lines.size()-2; i++) {
            for (int j = i+1; j < lines.size()-1; j++) {

                if (IsSimilar(lines.get(i), lines.get(j), SIMILARITY_RATE))
                    System.out.println("WARNING!\n " + lines.get(i) + "\n and \n" + lines.get(j) + "\n might be the same");
            }
        }

        file.close();
    }

    public static boolean IsSimilar(String line1, String line2, float percentSimilar) {
        int duplicateWordCount = 0;
        List<String> words1 = new LinkedList<String>(Arrays.asList(line1.split(" ")));
        List<String> words2 = new LinkedList<String>(Arrays.asList(line2.split(" ")));

        if (words1.size() >= words2.size()) {
            for (String word : words2) {
                if (words1.remove(word)) {
                    duplicateWordCount++;
                }
            }

            if (duplicateWordCount > (words2.size() * percentSimilar)) return true;
        }

        else if (words2.size() > words1.size()) {
            for (String word : words1) {
                if (words2.remove(word)) {
                    duplicateWordCount++;
                }
            }

            if (duplicateWordCount > (words1.size() * percentSimilar)) return true;
        }

        return false;
    }

}

It works well, and is customisable in case you want to make it more/less strict. I am wondering if there is a better way to do my if statements in the IsSimilar function, as without them it doesn't work as well.


texts:
How can I improve this code?

template<class T>
class Queue {
public:
    Queue(const std::initializer_list<T>& i) :elem{i} {}
    int size() const {
        return elem.size();
    }
    bool empty() const {
        return elem.empty();
    }
    void enqueue(T&&);
    void dequeue();
    T peek();
    T& operator[](std::size_t);
    typename std::vector <T>::iterator begin() {
        return elem.begin();
    }
    typename std::vector <T>::iterator end() {
        return elem.end();
    }

private:
    std::vector<T> elem;
};

template<class T>
void Queue<T>::enqueue(T&& t) {
    elem.push_back(t);
}

template<class T>
void Queue<T>::dequeue() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    elem.erase(elem.begin());
}

template<class T>
T Queue<T>::peek() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    return elem.front();
}

template<class T>
T& Queue<T>::operator[](std::size_t i) {
    if (empty() || i < 0 || i >= size()) {
        throw std::out_of_range("underflow");
    }
    return elem[i];
}


texts: Separating the even and odd numbers in an array in C

texts:
I wrote a working program in C that takes an array with size 2ⁿ, and separates all the even numbers from the odd numbers.
For example: Input: {1,2,3,4,5,6,7,8}, Output: {8,2,6,4,5,3,7,1}
I want my program to be as efficient as possible and to have space complexity O(log n) and time complexity of O(n log n).
This is the code in C:
#include <stdio.h>

void swap(int*, int*);
void arrange(int arr[], int n);

int main() {
    int arr[] = {1,2,3,4,5,6,7,8};
    int size = sizeof(arr)/sizeof(arr[0]);
    arrange(arr,size);

    return 0;
}

void arrange(int arr[], int n) {

    if (n==1) return;

    int istart = 0, iend = n-1;
    while (istart <= iend) {
    if (arr[istart] % 2 == 0) {
        istart++;
        return arrange(arr+istart,n-1);
    }
    else if (arr[iend] % 2 == 1) {
        iend--;
        return arrange(arr,n-1);
    }
    else {
        swap(&arr[istart++],&arr[iend--]);
        return arrange(arr+istart,n-1);
    }
    }
}

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

How can I improve my code? Maybe make it run faster with a better complexity?


texts: Locate enteries to the nearest date selected

texts:
This code loops through a given range of dates and for every 5 minute iteration pulls up the last known records of the users in the database relative to that timestamp.

I'm trying to find a way to optimize this query. Right now it seems to be slow, perhaps because it loops over the entire db each time it runs. Any ideas?

// cleaning / sort

db.Data.createIndex({"_created_at": -1});

// help : hackhands.com/vibhor

var start = new Date(2013, 2, 13, 0, 0, 0);
var end = new Date(2013, 2, 13, 23, 0, 0);

while (start < end) {
    var newDate = start.setMinutes(start.getMinutes() + 5);
    start = new Date(newDate);

    db.getCollection("_User").find().forEach(function (myDoc) {
        var a = db.Data.find({user: myDoc.username, "_created_at": {$lt: start}}).sort({" _created_at": -1}).limit(1);
        if (a.length() > 0) {
            print(a[0]["battery"])
        }
    });

    print(start)
}


texts:
When git runs my post-receive hook, I'd like it to run all the scripts in the subdirectory post-receive.d.

My script is as follows

#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
DIR="$( dirname "$SOURCE" )"

for SCRIPT in $DIR/post-receive.d/*
do
  if [ -f "$SCRIPT" -a -x "$SCRIPT" ]
  then
    "$SCRIPT"
  fi
done

Source: https://github.com/alexchamberlain/githooks/blob/master/post-receive

Is this secure? Reliable?

I can foresee one problem. The hook supplies data using stdin, which should be copied to each subscript. I'm pretty sure this isn't happening at the moment. Any ideas?


texts: Storing the API endpoints in a Pythonic way

texts:
I am currently trying to create an API-wrapper. For that, I connect to the endpoint (for example https://host.example.com/api/accounts/open) with the request module. Since there are a bunch of endpoints, I need a way to sort them. Currently I have a constants file, where most of the endpoints are created like this:

HOST = 'https://wallet.shiftnrg.org'
START = ''.join([HOST, '/api'])

ACCOUNTS = ''.join([START, '/accounts'])
ACCOUNTS_OPEN = ''.join([ACCOUNTS, '/open'])
...
LOADER = ''.join([START, '/loader'])
LOADER_GET_STATUS = ''.join([LOADER, '/status'])

And I access them like this (one example):

def accounts_get_balance(address):
    payload = {'address': address}

response = requests.get(constants.ACCOUNTS_GET_BALANCE,
                        params=payload,
                        timeout=constants.TIMEOUT
)

While this is working, I was wondering if there is a more efficient, pythonic way of doing this, since I am just a beginner (especially the constants.py, but if you find anything else, feel free to tell me as well!)


texts: Return from the parent process code or common code

texts:
In this program, the parent process creates a child process, then the child executes ls -l. The parent process waits for the child process to complete and then returns using return 0;.

/*child's output redirected to file*/
/*sps, 6262015*/

/*Headers*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>

/*Start*/
int main(void)
{
    //Create a child process
    int ret = fork();
    if(ret<0)
            exit(1);
    /*Child code*/
    else if(ret==0)
    {
            char *argv[] = {"ls", "-l", NULL};

            //Execute 'ls -l'
            execvp(argv[0], argv);
    }
    /*Parent code*/
    else if(ret>0)
    {
            int status;
            int w = waitpid(ret, &status, WUNTRACED | WCONTINUED);
    }
    /*Where to place this ???*/
    return 0;
}

Although above code works correctly, I am not sure where to place the return 0; statement. For instance, in the above code it is at the end so it is common to both the parent and child processes.

But in this program, the child process calls execvp, so it will never reach the last line of the code which has return 0;. So, taking this into account, can I place the return 0; inside the parent code as below?

 /*Parent code*/
 else if(ret>0)
 {
         int status;
         int w = waitpid(ret, &status, WUNTRACED | WCONTINUED);
         return 0;
 }

Is there any advantage or disadvantage to putting the return 0; statement inside the parent process code?


texts: Console.log challenge change all of the links on a search results page so that they do not go anywhere?

texts:
I am reading a book call Front end Web Development "The big nerd ranch guide", in which I came across a silver challenge:

Go to your favorite search engine and search for "anything".
Open the DevTools to the console.
With the functions you wrote in this chapter as a reference, attach event listeners to all of the links and disable their default click functionality.

Here's what I wrote:
function selectLink() {
    'use strict'
    var links = document.querySelectorAll('a');
    var linksArray = [].slice.call(links);
    return linksArray;
}

function disableClick (dis) {
    'user strict';
    dis.addEventListener('click', function (event) {
        event.preventDefault();
    });
}

function click() {
    'use strict';
    var link = selectLink();
    link.forEach(disableClick);
}

click();

I don't know whether this is the correct method to do it, since there is no solution on the book for it.
Can I do better?


texts:
I am a java developer and I am trying to learn Go.
I tried to make a simple code that take numbers from a .txt file and make print them in a prettier format.
That is:

0613228745     -> 06 13 22 87 45
06.13.22.87.45 -> 06 13 22 87 45
06-13-22-87-45 -> 06 13 22 87 45
06 13 228 745  -> 06 13 22 87 45
0 613 228 745  -> 06 13 22 87 45

Can you review, give me some advices about my code ?
Here it is:

package main

import (
    "bufio"
    "fmt"
    "os"
    "unicode"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {

    file, err := os.Open("./phonenumbers.txt")
    check(err)

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        basicPhoneNumberArray, prettyPhoneNumber := make([]rune, 0), ""
        // get only digit numbers
        for _, r := range []rune(scanner.Text()) {
            if unicode.IsDigit(r) {
                basicPhoneNumberArray = append(basicPhoneNumberArray, r)
            }
        }
        // put spaces every two digits
        for i, r := range basicPhoneNumberArray {
            prettyPhoneNumber += string(r)
            if i%2 != 0 && i != len(basicPhoneNumberArray)-1 { // no space at the end
                prettyPhoneNumber += " "
            }
        }
        fmt.Println(prettyPhoneNumber)
    }
}

Also I am very fond of functional programming, I think there should be a way to use some filter and map here but after few searches I didn't find a way. If you could give me some advices about that too that would be great :D.


texts:
A threading.Thread subclass intended for running an asyncio loop that has the ability to be stopped gracefully from another thread.
I spent a lot of time doing trial and error until it finally worked, but probably it still needs a lot of refinement. Warning to asyncio noobs like me: asyncio is very thread-unsafe in general. Don't assume otherwise.
Example:
import time

# This is a placeholder for an arbitrary async entry point
async def my_async_main():
    ...

async_thread = StoppableAsyncioThread(target=my_async_main)
time.sleep(5)
async_thread.stop()
async_thread.join()

Code:
import asyncio
import logging
import threading
from typing import ClassVar, Optional

class StoppableAsyncioThread(threading.Thread):
    """
    Stoppable asyncio thread.

    The target callable must be a coroutine function that can be executed with
    ``asyncio.run(target())``.
    """

    logger: ClassVar[logging.Logger] = logging.getLogger("threading")

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        # These are threading.Thread internals; equivalent to passing in the
        # corresponding keyword arguments to __init__. A bit lazy, but it guarantees
        # that the arguments and their defaults get handled correctly because
        # we delegate everything (*args, **kwargs) to threading.Thread.__init__
        self._args = (self._target_wrapper(self._target),)
        self._kwargs = {"debug": self.logger.getEffectiveLevel() <= logging.DEBUG}
        self._target = asyncio.run

        self.loop: Optional[asyncio.AbstractEventLoop] = None
        self._target_task = None

    def stop(self):
        if self.loop is None:
            raise RuntimeError("This asyncio thread is not running")
        self.logger.debug("Trying to stop %s", self)
        # cancelling the root task will be enough for the loop to close, because
        # we started it with asyncio.run, which only waits until the given task is done;
        # asyncio takes care of cancelling any other tasks
        self.loop.call_soon_threadsafe(self._target_task.cancel)

    async def _target_wrapper(self, target):
        self._target_task = asyncio.current_task()
        self.loop = asyncio.get_running_loop()
        try:
            await target()
        except asyncio.CancelledError:
            return


texts:
I use the following code which works ok!
The code is installing helm charts in loop in k8s cluster, and I want to verify that I'm writing it ok.
tmpfile, err := ioutil.TempFile(kp, kcp)
if err != nil {
    log.Error(err, "error")
}

defer os.Remove(tmpfile.Name())

if _, err := tmpfile.Write(cfg); err != nil {
    return err
}
if err := tmpfile.Close(); err != nil {
    return err
}

kcfgFilePath := tmpfile.Name()
settings := cli.New()
ac := new(action.Configuration)
clientGetter := genericclioptions.NewConfigFlags(false)
clientGetter.KubeConfig = &kcfgFilePath

for _, chartInstallation := range charts {
    chart, err := loader.Load(chartInstallation.Path)
    if err != nil {
        return err
    }

    releaseName := releaseName + "-" + chartInstallation.Name
    if err := ac.Init(clientGetter, settings.Namespace(), os.Getenv("HELM_DRIVER"), func(format string, v ...interface{}) {

    }); err != nil {
        return err
    }
    releasePresent := true
    statusAction := action.NewStatus(ac)
    status, err := statusAction.Run(releaseName)
    if err != nil {
        if strings.Contains(err.Error(), driver.ErrReleaseNotFound.Error()) {
            releasePresent = false
        } else {
            return err
        }
    }

    if !releasePresent {
        // install chart
        installAction := action.NewInstall(ac)
        installAction.CreateNamespace = true
        installAction.Namespace = chartInstallation.Namespace
        installAction.ReleaseName = releaseName

        _, err := installAction.Run(chart, nil)
        if err != nil {
            return err
        }
        log.Info("chart installed: ", "releaseName", releaseName)
    }

    if status != nil {
        if releasePresent && status.Info.Status.String() == release.StatusFailed.String() {
            upgradeAction := action.NewUpgrade(ac)
            upgradeAction.Wait = true
            upgradeAction.ReuseValues = false
            upgradeAction.Recreate = false
            _, err := upgradeAction.Run(releaseName, chart, nil)
            if err != nil {
                return err
            }
        }
    }


texts: IKM C++ assessment asks about std::unordered_set, part #1

texts:
Recently I had to do an IKM C++ assessment to qualify for a job. Some of the questions seemed strange to me, so I'll be doing a few posts here to discuss.
The first one is related to use of std::unordered_set. From what I remember it went something like:

A programmer is using a struct to contain some data. The struct must be stored in a std::unordered_set. True or false: The structure has to overload the method operator==() in order for the structure to be supported by std::unordered_set?

I wrote a test program to demonstrate:
#include <iostream>
#include <random>
#include <unordered_set>

struct ikm_test_struct {

   size_t m1;

   std::size_t operator()(ikm_test_struct const& s) const noexcept;

   constexpr bool operator==(const ikm_test_struct &rhs) const;
};

// Method operator() must return a size_t so use its limits in our distribution.

std::uniform_int_distribution<> distrib(
   std::numeric_limits<std::size_t>::min(),
   std::numeric_limits<std::size_t>::max()
);

std::size_t ikm_test_struct::operator()(ikm_test_struct const& s) const noexcept {

   // Seed a random number generator using the value in the parameter struct.

   std::mt19937 gen(s.m1);

   // Exercise the random number generator so that it is well away from any less random starting values.

   for (size_t i = 0; i < 100; ++i) distrib(gen);

   // Generate a random number in the required range.

   return distrib(gen);
}

constexpr bool ikm_test_struct::operator==(const ikm_test_struct &rhs) const {
   return m1 == rhs.m1;
}

typedef std::unordered_set<ikm_test_struct, ikm_test_struct> ikm_test_unordered_set;

int main()
{
   ikm_test_unordered_set x;

   for (size_t i = 0; i < 100; ++i) {

      ikm_test_struct y;
      y.m1 = i;

      x.insert(y);
   }

   size_t j = 0;
   for (const auto& k: x) {
      std::cout << "x[" << j << "] = " << k.m1 << std::endl;
      ++j;
   }
}

So it is possible to write a structure that implements operator==() and is then used in a std::unordered_set. Given this demonstration how should we answer the original question:

The demo code proves that it is possible to do this but the question says "has to overload the method operator==()". There are other ways to implement an equality test. Like creating a separate class or struct and using that class as the third parameter on the std::unordered_set template. So do you answer the question yes because it is possible or no because you don't have to do it that way?
The question says "has to overload". But the demo code implements operator==() only once, so there is no "overloading" of this method. If there is no overloading should the question be answered false? That seems to miss the point of asking the question to test your C++ knowledge.
The question says "in order for the structure to be supported". "Supported" is kind of ambiguous. Supported how, with what specialization of std::unordered_set, with what other helper classes?

Given the above it seems that the question is one that has no correct answer. Therefore, it is stupid to include it in a test that is supposed to evaluate someones C++ skills.
What do you think?


texts: Getting items with overlapping DateTime using Linq

texts:
I have a live chat database and I am trying to get an idea of how many concurrent chats staff are taking. I'm not sure of the best way to report it so I have decided to get a list of chats for a given period then for each one display a count of chats that overlapped that one in some way.

I am querying 2 tables across a join but this is just to get the Operators name. The fields that have the relevant dates are:

DateTime? ChatRequests.Answered
DateTime? ChatRequests.Closed

I think I have everything covered. I just want to see if anyone can tell me if I'm missing anything, or if there is a better approach to it.

ChatRequests
.Where (cr => (cr.Created.AddHours (10).Date == DateTime.Now.AddDays (-1).Date))
.Where (cr => cr.OperatorID.HasValue)
.Join (
    Operators,
    chat => chat.OperatorID.Value,
    op => op.ID,
    (chat, op) =>
        new
        {
            chat = chat,
            op = op
        }
)
.Select (
    g =>
        new
        {
            Operator = g.op.FullName,
            Answered = g.chat.Answered.Value.AddHours (10),
            Closed = g.chat.Closed.Value.AddHours (10),
            Duration = (Decimal)((g.chat.Closed.Value - g.chat.Answered.Value).TotalMinutes),
            Company = g.chat.AccountName,
            Contact = g.chat.ContactName,
            OtherChatsInSamePeriod = ChatRequests
                        .Where (cr => (cr.OperatorID == g.chat.OperatorID))
                        .Where (cr => (cr.ID != g.chat.ID))
                        .Where (
                           cr =>    (cr.Answered.Value >= g.chat.Answered.Value && cr.Answered.Value <= g.chat.Closed.Value)
                                     || (cr.Closed.Value >= g.chat.Answered.Value && cr.Closed.Value <= g.chat.Closed.Value)
                                     || (cr.Answered.Value < g.chat.Answered.Value && cr.Closed.Value > g.chat.Closed.Value)
            )
            .Count ()
        }
)


texts: Implement a string in reverse using pointers and recursion

texts:
I'm trying to reverse a string using pointers and recursion, and I send it a char array. Is this the best way, or is there a better one?

int display_string_reversep(char* astring)
{
  char* achar = astring;
  if((*achar) != '\0')
    {
      char* x= achar;
      x++;
      display_string_reversep(x);
      cout<<(*achar);
    }
    return 0;
}

I'm also trying to do the same using smart pointers and that is proving to be more of a problem.

int display_string_reverseup(shared_ptr<char> astring)
{
  cout<<"\nEntering revup";
  shared_ptr<char> achar(astring);
  cout<<"\nAssigned achar";
  //if((*achar) != '\0')
  if(achar != nullptr)
    {
      cout<<"Forward String ";
      cout<<achar<<endl;
      if(*(achar.get()+1) != '\0')
    {
      shared_ptr<char> x(achar.get()+1);
      //x++;
      cout<<"Forward + 1 String ";
      cout<<x<<endl;
      //if ((*x) != '\0')
      display_string_reverseup(x);
    }
      cout<<(achar);
    }
    return 0;
}