texts: Find the range of index of consecutive integers from a sorted array

texts:
I would like to know how can   improve  my solution.

import java.util.*;
public class prog{

    public   Map<Integer, Integer>  findList(int[] array1)
    {
         Map<Integer, Integer> list= new HashMap<Integer, Integer>();

         int start_index= 0;
         int end_index = 0;
         int length = array1.length;

         for(int i = 1; i < length ; ++i)
         {
             if(array1[i-1] + 1 != array1[i])
             {

                 end_index = i - 1;
                 list.put(start_index, end_index);
                 start_index = i;
             }
         }
         if( array1[length -2]+1 == array1[length -1])
         {
             end_index = length - 1;
             list.put(start_index, end_index);
         }
          return list;
    }

    public static void main(String[] arr)
    {
        int [] array1 = { 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 20, 22, 23, 24, 27,34 };
        prog prg = new prog();
        Map<Integer, Integer> list1= new HashMap<Integer, Integer>();
        list1 = prg.findList(array1);

        for( Map.Entry<Integer,Integer> entry: list1.entrySet())
        {
            System.out.println( entry.getKey()+"--"+ entry.getValue());
        }
    }
}


texts: Processing image blocks using a task runner

texts:
This code works, but I'm sure it isn't written according to "best practices" for closures.  On the other hand, at least it's intuitive to me...

the taskRunner object runs functions on setTimeout, so as not to block the UI for too long.  I'm breaking this function into chunks and running one chunk at a time.  I'm passing i into my function so it will be part of the closure, but I know I've seen this done more elegantly - I just can't wrap my head around how to do it right now.

var tr = new taskRunner();
        //I'm sure there's a better way to do a closure, but works
        for(var i=0;i<blocks;i++){
            var blockFunc = (function(i){
                    var innerFunc = function(){
                    var blockLen=Math.min(32768,len-(i*32768));
                    stream.push(i==(blocks-1)?0x01:0x00);
                    Array.prototype.push.apply(stream, blockLen.bytes16sw() );
                    Array.prototype.push.apply(stream, (~blockLen).bytes16sw() );
                    var id=imageData.slice(i*32768,i*32768+blockLen);
                    Array.prototype.push.apply(stream, id );
                }
            return innerFunc;
            }(i));
            tr.AddTask(blockFunc);
        }


texts: Setting new lines and adding them to a list to be drawn

texts:
I have a method that basically passes in a known drawn line segment in my view and then draws parallel lines n distances away from the passed in original line. This one in particular draws two parallel lines on either side.

It seems to be a lot of repeat code here, so how can I refactor it to a smaller method and avoid redundancy?

public List<Line> DrawTwoParallelLines(Line line)
   {
       List<Line> listOfParallelLines = new List<Line>();

       Line parallelLine1 = new Line();
       Line parallelLine2 = new Line();
       Line parallelLine3 = new Line();
       Line parallelLine4 = new Line();

       parallelLine1.point1.x =(float)(line.point1.x + 50 * Math.Cos(90));
       parallelLine1.point1.y = (float)(line.point1.y + 0 * Math.Cos(90));
       parallelLine1.point2.x = (float)(line.point2.x + 50 * Math.Cos(90));
       parallelLine1.point2.y = (float)(line.point2.y + 0 * Math.Cos(90));

       parallelLine2.point1.x = (float)(line.point1.x + 100 * Math.Cos(90));
       parallelLine2.point1.y = (float)(line.point1.y + 0 * Math.Cos(90));
       parallelLine2.point2.x = (float)(line.point2.x + 100 * Math.Cos(90));
       parallelLine2.point2.y = (float)(line.point2.y + 0 * Math.Cos(90));

       parallelLine3.point1.x = (float)(line.point1.x + -50 * Math.Cos(90));
       parallelLine3.point1.y = (float)(line.point1.y + 0 * Math.Cos(90));
       parallelLine3.point2.x = (float)(line.point2.x + -50 * Math.Cos(90));
       parallelLine3.point2.y = (float)(line.point2.y + 0 * Math.Cos(90));

       parallelLine4.point1.x = (float)(line.point1.x + -100 * Math.Cos(90));
       parallelLine4.point1.y = (float)(line.point1.y + 0 * Math.Cos(90));
       parallelLine4.point2.x = (float)(line.point2.x + -100 * Math.Cos(90));
       parallelLine4.point2.y = (float)(line.point2.y + 0 * Math.Cos(90));

       listOfParallelLines.Add(parallelLine1);
       listOfParallelLines.Add(parallelLine2);
       listOfParallelLines.Add(parallelLine3);
       listOfParallelLines.Add(parallelLine4);

       return listOfParallelLines;

   }


texts: Generating a table of differences between two dictionaries

texts:
for (int i = 0; i < keyList.Count; i++)
{
    if (oldDic.ContainsKey(keyList[i].ToString()))
    {
        if (newDic[keyList[i].ToString()].ToString() == oldDic[keyList[i].ToString()].ToString())
        {
            //ReminderBackupLog("Same");
        }
        else
        {
            isChnagedSectionFields = "Yes";
            string oldValue = oldDic[keyList[i].ToString()].ToString();
            string newValue = newDic[keyList[i].ToString()].ToString();
            table = table + "
" + colNames[keyList[i].ToString()].ToString() + "	" + oldValue + "	" + newValue + "
";
        }
    }
    else
    {
        isChnagedSectionFields = "Yes";
        string newValues = newDic[keyList[i].ToString()].ToString();
        table = table + "
" + colNames[keyList[i].ToString()].ToString() + "	" + " " + "	" + newValues + "
";
    }
}


texts:
You are given a polynomial of degree n. The polynomial is of the form

    P(x) = an · xn + an-1 · xn-1 + … + a0

  where the ai‘s are the coefficients. Given an integer
  x, write a program that will evaluate P(x).

  You are provided with a function named power( ) that takes two
  positive integers x and y and returns xy. If y is
  0, the function returns 1.

  The prototype of this function is

int power(int x, int y);

  INPUT:

  Line 1 contains the integers n and x separated by whitespace.
  Line 2 contains the coefficients an, an-1, …, a0 separated by whitespace.

  OUTPUT:

  A single integer which is P(x).

  CONSTRAINTS:

  The inputs will satisfy the following properties. It is not necessary
  to validate the inputs.

1 <= n <= 10
1 <= x <= 10
0 <= ai <=10

My code

#include<stdio.h>

int power(int x, int y);

int main()
{

int n,x,a[11],i; unsigned long long int sum=1;
scanf("%d%d",&n,&x);
if(n<1 || n>10) return 0;
if(x<1 || x>10) return 0;

for(i=0;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]< 0 || a[i]>10) return 0;
}
for(i=0;i<n;i++)
{

sum+=power(x,n-i)*a[i];
}
printf("%llu",sum);

    return 0;
}

int power(int x, int y)
 {
   int result = x,i;

   if(y == 0) return 1;
   if(x < 0 || y < 0) return 0;

   for(i = 1; i < y; ++i)
   result *= x;

   return result;
}


texts:
binaryToDecimal = lambda binary: sum([[int(2**index) for index in range(len(binary))][-index-1] for index, char in enumerate(binary) if int(char)])

I wrote a simple function that converts binary strings into decimal integers. How can this be improved/simplified?

I know about the int function, I wanted to implement the conversion myself.


texts: Counting which numbers fall in a certain bracket

texts:
I'm taking a text file that looks like this:

77, 66, 80, 81
40,  5, 35, -1
51, 58, 62, 34
 0, -1, 21, 18
61, 69, 58, 49
81, 82, 90, 76
44, 51, 60, -1
64, 63, 60, 66
-1, 38, 41, 50
69, 80, 72, 75

and I'm counting which numbers fall in a certain bracket:

f = open("//path to file", "r")
text = f.read()
split = text.split()

greater70=0
sixtys=0
fiftys=0
fortys=0
nomarks=0

for word in split:
    temp = word.replace(',', '')
    number = int(temp)
    if number > 70:
        greater70+=1
    if number >= 60 and number <= 69:
        sixtys+=1
    if number >= 50 and number <= 59:
        fiftys+=1
    if number >= 40 and number <= 49:
        fortys+=1
    if number == -1:
        nomarks+=1

print greater70
print sixtys
print fiftys
print fortys
print nomarks

Have I done it in an efficient way sensible way or do experienced Python users think it looks a little convoluted?


texts: Put ages within a supplied range into a HashMap

texts:
I'm looking for general considerations to make for the next time I'm writing code. I'm wondering if in this case it's better to have another auxiliary storage (another map?) in this case (and how to do so?). I haven't yet learned about complexity, so I'm not sure if I'm completing that part of the question (running in O(N log N) time).

Write a method byAge that accepts three parameters: 1) a Map where each key is a person's name (a string) and the associated value is that person's age (an integer); 2) an integer for a minimum age; and 3) an integer for a maximum age. Your method should return a new Map with information about people with ages between the min and max, inclusive.

In your result map, each key is an integer age, and the value for that key is a string with the names of all people at that age, separated by "and" if there is more than one person of that age. Your result map's pairs should be sorted in ascending order by age (keys). Include only ages between the min and max inclusive, where there is at least one person of that age in the original map. If the map passed is empty, or if there are no people in the map between the min/max ages, return an empty map.

For example, if a Map named ages stores the following key=value pairs:

{Paul=28, David=20, Janette=18, Marty=35, Stuart=98, Jessica=35, Helene=40,
 Allison=18, Sara=15, Grace=25, Zack=20, Galen=15, Erik=20, Tyler=6, Benson=48}

The call of byAge(ages, 16, 25) should return the following map (the contents can be in any order):

{18=Janette and Allison, 20=David and Zack and Erik, 25=Grace}

For the same map, the call of byAge(ages, 20, 40) should return the following map:

{20=David and Zack and Erik, 25=Grace, 28=Paul, 35=Marty and Jessica, 40=Helene}

Obey the following restrictions in your solution:

You will need to construct a map to store your results, but you may not use any other structures (arrays, lists, etc.) as auxiliary storage. (You can have as many simple variables as you like.)
You should not modify the contents of the map passed to your method.
Your solution should run in no worse than O(N log N) time, where N is the number of pairs in the map.

public Map<Integer, String> byAge(Map<String, Integer> namesAges, int min, int max) {
    Map<Integer, String> range = new HashMap<Integer, String>();
    for (String name : namesAges.keySet()) {
        int age = namesAges.get(name);
        if (range.containsKey(age)) {
            range.put(age, range.get(age) + " and " + name);
        } else if (min <= age && age <= max) {
            range.put(age, name);
        }
    }
    return range;
}


texts:
I recently created a function calculating the sum of an arbitrary range object in \$O(1)\$:

def sum_of_range(range_obj):
    """Calculates the sum of a range object (Python 3) in O(1).

    This function always returns a python integer representing the sum
    without loss of precision (as would happen if it uses intermediate
    floating point values).
    """
    start, stop, step = range_obj.start, range_obj.stop, range_obj.step
    len_ = len(range_obj)
    if step > 0:
        if start >= stop:
            return 0
        # Find the last "really" included number. Subtract one from stop
        # because the stop is not included in ranges.
        upper = (stop - 1 - start) // step * step + start
    else:
        if stop >= start:
            return 0
        # In case the step is negative we need to add one to the difference
        # instead of subtracting one.
        upper = (stop - start + 1) // step * step + start
    sum_first_and_last = upper + start
    return (sum_first_and_last * len_) // 2

I used "random" tests to verify that it works:

import random

for i in range(100000):  # make a lot of random tests
    up = random.randint(-10000, 10000)
    lo = random.randint(-10000, 10000)
    step = random.randint(-25, 25)
    if step == 0:  # steps of zero are not possible
        continue
    rg = range(lo, up, step)
    assert sum_of_range(rg) == sum(rg)

Is there any room for improvement? Especially (but not only):

Code readability
Code performance
Should I replace the random tests with explicit tests or can I neglect explicit tests? Or should I include both?


texts:
Here's how I implemented concat - flattens a list of lists into just a list of elements.

concat' :: [[a]] -> [a]
concat' ys = foldl (\acc x -> acc ++ x) [] ys

Is it a problem that I'm using the ++ function?

What's a better way to write this?


texts:
I am building a bare bones freestanding kernel in ASM and C. My make file is below.

CFLAGS= -ffreestanding -nostdlib -gdwarf-4 -m32 -ggdb3 -Wall -Wextra -Werror -std=c11
ASMCFLAGS= -f elf32 -F dwarf -g -w+all
LDFLAGS= --nmagic -m elf_i386 --script=os.lds

BUILD_DIR=../build/os
BUILD_DIR_IMM=$(BUILD_DIR)/imm
BUILD_DIR_IMM_ASM=$(BUILD_DIR_IMM)/asm
BUILD_DIR_IMM_C=$(BUILD_DIR_IMM)/c
BUILD_OUTPUT=$(BUILD_DIR)/os

OS_C_SRCS := $(wildcard *.c)
OS_C_OBJS := $(patsubst %.c, $(BUILD_DIR_IMM_C)/%.o, $(OS_C_SRCS))

OS_ASM_SRCS := $(wildcard *.asm)
OS_ASM_OBJS := $(patsubst %.asm, $(BUILD_DIR_IMM_ASM)/%.o, $(OS_ASM_SRCS))

OS_SRCS := $(OS_C_SRCS) $(OS_ASM_SRCS)
OS_OBJS := $(OS_ASM_OBJS) $(OS_C_OBJS)

all: $(BUILD_OUTPUT)

prepdir:
    mkdir -p $(BUILD_DIR_IMM_C)
    mkdir -p $(BUILD_DIR_IMM_ASM)

$(OS_C_OBJS): $(OS_C_SRCS) $(OS_ASM_OBJS) prepdir
    $(CC) $(CFLAGS) -c $< -o $@

$(BUILD_DIR_IMM_ASM)/__init.o: __init.asm prepdir
    nasm $(ASMCFLAGS) __init.asm -o $@

$(BUILD_DIR_IMM_ASM)/kinit.o: kinit.asm prepdir
    nasm $(ASMCFLAGS) kinit.asm -o $@

$(BUILD_DIR_IMM_ASM)/keyboard.o: keyboard.asm prepdir
    nasm $(ASMCFLAGS) keyboard.asm -o $@

$(BUILD_DIR_IMM_ASM)/interrupt.o: interrupt.asm prepdir
    nasm $(ASMCFLAGS) interrupt.asm -o $@

$(BUILD_DIR_IMM_ASM)/string.o: string.asm prepdir
    nasm $(ASMCFLAGS) string.asm -o $@

$(BUILD_DIR_IMM_ASM)/vid.o: vid.asm prepdir
    nasm $(ASMCFLAGS) vid.asm -o $@

$(BUILD_OUTPUT): $(OS_C_OBJS) $(OS_ASM_OBJS)
    ld $(LDFLAGS) $(OS_OBJS) -o $@

clean:
    rm -rf $(BUILD_DIR)

This makefile is used as a child makefile.

My primary concern is that I cannot pass multiple files to NASM, so I need a rule for each assembly file I have. My secondary concern is cross dependencies on other files, for instance, my C files should be rebuild if any C header files change.


texts: Create a list of all strings within hamming distance of a reference string with a given alphabet

texts:
For a bioinformatic problem, I found myself wanting to create a list of strings within Hamming distance "k" of a reference sequence. I wanted to do so quickly and pythonically. I've implemented it in pure python and in cython, with and without type declarations. The time performance has been identical. (I also compared the compiled python version with an interpreted version defined in ipython, which also performed identically.)

cfi has been set as shorthand to chain.from_iterable in order to reduce the number of dot operators being used as in the following module-level import and definition:

from itertools import chain
cfi = chain.from_iterable

@cython.returns(list)
def PermuteMotifOnce(cython.str motif, set alphabet={"A", "C", "G", "T"}):
    """
    Gets all strings within hamming distance 1 of motif and returns it as a
    list.
    """
    return list(set(cfi([[
        motif[:pos] + alpha + motif[pos + 1:] for
        alpha in alphabet] for
                         pos in range(len(motif))])))

def PyPermuteMotifOnce(motif, alphabet={"A", "C", "G", "T"}):
    """
    Gets all strings within hamming distance 1 of motif and returns it as a
    list.
    """
    return list(set(cfi([[
        motif[:pos] + alpha + motif[pos + 1:] for
        alpha in alphabet] for
                         pos in range(len(motif))])))

@cython.returns(list)
def PermuteMotifN(cython.str motif, cython.long n=-1):
    assert n > 0
    cdef set workingSet
    cdef cython.long i
    workingSet = {motif}
    for i in range(n):
        workingSet = set(cfi(map(PermuteMotifOnce, workingSet)))
    return list(workingSet)

def PyPermuteMotifN(motif, n=-1):
    assert n > 0
    workingSet = {motif}
    for i in range(n):
        workingSet = set(cfi(map(PermuteMotifOnce, workingSet)))
    return list(workingSet)

Results:

motif = "ACCTACTGAACT"
%timeit -n 5 PermuteMotifN(motif, 6)
5 loops, best of 3: 6.93s per loop
%timeit -n 5 PyPermuteMotifN(motif, 6)
5 loops, best of 3: 6.81s per loop
%timeit -n 5000 PyPermuteMotifN(motif, 2)
5000 loops, best of 3: 589 microseconds per loop
%timeit -n 5000 PermuteMotifN(motif, 2)
5000 loops, best of 3: 645 microseconds per loop

Is it just me, or does the pure Python seem even faster than the Cython? Is there a lot of time lost in extra type checking?


texts:
I finished a program to do connected component analysis using union - find algorithm. Is it true that the complexity of the code is \$O(N logN)\$, where \$N\$ is the total number of pixels (512x512 by example, not 512).

Is there any way to improve the performance?

import cv2
import numpy as np
import random

class QuickUnionUF:

    def __init__(self, N):
        self.id = range(N)
        self.sz = [0] * N

    @classmethod
    def fromimage(self, im):
        self.id = im
        self.sz = [0] * len(im)

    def root(self, i):
        while (i != self.id[i]):
            i = self.id[i]
        return i

    def getresult(self):
        result = [self.root(i) for i in self.id]
        return result

    def connected(self, p, q):
        return self.root(p) == self.root(q)

    def union(self, p, q):
        i = self.root(p)
        j = self.root(q)

        if (i == j):
            return
        if (self.sz[i] < self.sz[j]):
            self.id[i] = j
            self.sz[j] += self.sz[i]
        else:
            self.id[j] = i
            self.sz[j] += self.sz[i]

def bwlabel(im):

    M, N = im.shape[:2]
    qf = QuickUnionUF(M * N)
    for i in range(M - 1):
        for j in range(N - 1):
            if (im[i][j] == im[i][j+1]):
                qf.union(i * N + j, i * N + j + 1)
            if (im[i + 1][j] == im[i][j]):
                qf.union(i * N + j, (i + 1) * N + j)

    mask = np.reshape(np.array(qf.getresult()), (M, N))
    values = np.unique(mask).tolist()

    random.seed()
    colors = [(random.randint(0,255), random.randint(0,255), random.randint(0,255)) for k in range(len(values))]

    out = np.zeros((M, N, 3))
    for i in range(M):
        for j in range(N):
            label = values.index(mask[i][j])
            out[i,j] = colors[label]

    return out

im = cv2.imread("bw.jpg",cv2.IMREAD_GRAYSCALE)
out = bwlabel(im > 100)
cv2.imwrite("result.png", out)


texts: Javascript/Typescript anagram String search

texts:
I've created a random word generator which allows me to create random words/anagrams.

Then I've created Anagram search app to find the angarams when user start typing in inbox.

Could you review this with SOLID principles, Performance, Productions level ready scenarios in mind? Please be critical

// Generate random words to be used
class RandomWordGenerator {

  private wordList = [];

  constructor() {
    this.generate().createAnagrams();
  }
  generate() {
    for (let i = 0; i < 10000; i++) {
      this.wordList.push(Math.random().toString(32).substr(2, Math.floor(Math.random() * 10 + 1)));
    }

    return this;

  }

  createAnagrams() {
    let anagrams = this.wordList.slice(0, this.wordList.length/2).map((str) => {
      return str.substr(2, str.length / 2).split('').reverse().join('')
    })
    this.wordList = [...this.wordList, ...anagrams];

    return this;
  }

  getWordList() {
    return this.wordList;
  }

}

// Create Search index
class SearchIndex {

  private searchResults: Array<String>;
  private indexMap = {};
  private indexMapCharArray = [];

  constructor(private wordService: RandomWordGenerator) {
    this.searchResults = this.wordService.getWordList();
    this.sanitizeList().createIndex();
    console.log(this.searchResults);
  }

  sanitizeList() {
    this.searchResults = this.searchResults.filter((str) => !!str).sort();
    this.searchResults = Array.from(new Set(this.searchResults));

    return this;
  }

  createIndex() {
    this.indexMap = {};
    this.indexMapCharArray = [];

    for (let i = 0; i < this.searchResults.length; i++) {
      let sortedStrArr = this.searchResults[i].split('').sort();
      let sortedStr = sortedStrArr.join('')

      if (!!this.indexMap[sortedStr]) {
        this.indexMap[sortedStr].push(this.searchResults[i]);
      } else {
        this.indexMap[sortedStr] = [this.searchResults[i]];

      }
    }

    console.log(this.indexMap);
  }

  getSearchResults(str) {
    let result = this.indexMap[str];
    console.log('SEARCHING');
    return result;;
  }

}

// App
class App {

  constructor(private resultIndex: SearchIndex) {
  }

  start() {
    this.bindEvents();
  }

  bindEvents() {
    let element = <HTMLInputElement>document.querySelector('.search-field');

    element.addEventListener('keyup', (e) => {
      let target = <HTMLInputElement>e.target;
      console.log(target.value, e);
      console.log(this.resultIndex.getSearchResults(target.value))
    })
  }
}

window.onload = () => {
  var el = document.getElementById('content');
  var generator = new RandomWordGenerator();

  let searchIndex = new SearchIndex(generator);
  let app = new App(searchIndex);

  app.start();

};


texts: From a set of words, output all words that fit a string of random letters (like Scrabble)

texts:
I am in my first year of programming with Python 3 and am wondering if anyone had a better way to program this problem. When the user provides up to 7 random letters as a single string, the program should read the ‘wordlist.txt’ file, list the words from that file that can be constructed using some or all of those letters.

For example, if the user provides three letters, ‘AER’ as a string, the program will suggest the following words from the given file:
'AE', 'AR', 'ARE', 'EA', 'EAR', 'ER', 'ERA', 'RE'

This is what I have for now:

wordlist=list(line.strip('\n') for line in open('wordlist.txt','r'))

def wordFinder():
    words=[]
    letters=str.upper(input('enter up to 7 letters:'))
    for word in wordlist:
        candidate=True
        letterlist=list(letters)
        for letter in word:
            if letter not in letterlist:
                candidate=False
                break
            else:
                letterlist.remove(letter)
        if candidate==True:
            words.append(word)
    return words

>>>options()

enter up to 7 letters:aer
>>>['AE', 'AR', 'ARE', 'EA', 'EAR', 'ER', 'ERA', 'RE']

Even though it works I am looking to see if there is an easier/more efficient way for doing it. I came close with list comprehension, but I couldn't figure out how to avoid input letters matching more than once with the potential words.

def options2():
    words=[]
    letters=set(str.upper(input('Enter up to 7 letters:')))
    words=[w for w in wordlist
        if set(w).issubset(letters)
        and len(w)<=len(letters)]
    return words

>>>options2()

enter up to 7 letters:aer
>>>['AA','AE','AR','ARE','EA','EAR','EE','ER','ERA','ERE','ERR','RE','REE']

If any changes could be made for the second function to work that would be awesome.


texts: Calculating difference statistics over a moving window

texts:
I'd like to calculate some statistics of given data (frequencies of difference among elements on various distances in percent multiplied by 10) using moving window within that data. Is it possible to speed up the code below? I noticed that some calculations are repeating. But I was not able to exclude them without additional slowness.

def get_dist_stat(pdata, pwin_length):
    ''' pdata - given data array
        pwin_length - the lenght of window
        the function returns stat table where
            row represents the distance between elements
            col represents the difference for that distance in percent multiplied by 10 (assume that maximum difference can be 20 percent)

    '''

    l_data = len(pdata)
    l_win = pwin_length
    print("l_data=", l_data)
    print("l_win=", l_win)

    # stat table
    stat_table = np.zeros((l_win-1, 20*10), dtype = int)

        # loop over all data
    for k in range(l_data - l_win + 1):

        win = pdata[k : k + l_win]
        print('-' * 10)
        print("k=", k, " kend=", k + l_win )

        print("win=", win)

        # loop over window
        for i  in range(1 , l_win):
            b=win[i:]
            a=win[:-i]
            diff=(abs((b-a)/a*100 ) * 10).astype(int)
            print("i=",i)
            print("b=", b)
            print("a=", a)
            print("diff=",diff)

            # storing found differences into stat table
            apercents, acount = np.unique(diff, return_counts = True)
            l_apercents = len(apercents)
            for j in range(l_apercents):
                stat_table[i-1, apercents[j]] += acount[j]
    return stat_table

adata=np.array([1.1,1.2,1.3,1.4,1.5])
print("adata=", adata)

astat_table=get_dist_stat(adata,3)
print(astat_table)

And that is its output

adata= [1.1 1.2 1.3 1.4 1.5]
l_data= 5
l_win= 3
----------
k= 0  kend= 3
win= [1.1 1.2 1.3]
i= 1
b= [1.2 1.3]
a= [1.1 1.2]
diff= [90 83]
i= 2
b= [1.3]
a= [1.1]
diff= [181]
----------
k= 1  kend= 4
win= [1.2 1.3 1.4]
i= 1
b= [1.3 1.4]
a= [1.2 1.3]
diff= [83 76]
i= 2
b= [1.4]
a= [1.2]
diff= [166]
----------
k= 2  kend= 5
win= [1.3 1.4 1.5]
i= 1
b= [1.4 1.5]
a= [1.3 1.4]
diff= [76 71]
i= 2
b= [1.5]
a= [1.3]
diff= [153]
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
  0 0 0 0 2 0 0 0 0 0 0 2 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]


texts: Finding the count of negative sub-arrays for a given array

texts:
I want to improve my implementation for the following problem:

  You are given an array of n integers. A sub-array is "Negative" if sum of all the integers in that sub-array is negative. Count the number of "Negative sub-arrays" in the input array.

  Note: Subarrays are contiguous chunks of the main array. For example if the array is {1,2,3,5} then some of the subarrays are {1}, {1,2,3}, {2,3,5}, {1,2,3,5} etc. But {1,2,5} is not an subarray as it is not contiguous.

  Input Format:

  The first line consists an integer n. The next line will contain n space seperated integers. Value of n will be at most \$100\$. The numbers in the array will range between \$-10000\$ to \$10000\$.

  Output Format:

  Print the answer to the problem.

I am using two loops. It's clearing the test cases, but can I do it with only one loop?

import java.io.*;
import java.util.*;

   public class Solution {

    public static void main(String[] args)throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        byte T = Byte.parseByte(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        int[] arr = new int[T];
        for(int i = 0; i < T; i++){
            arr[i] = Integer.parseInt(st.nextToken());
        }
        int sum = 0, count = 0;;
        for(int i = 0; i < T; i++){
             sum = 0;
             sum += arr[i];// If the number itself is negative count++
              if(sum < 0){
                    count++;
                }
            for(int j = i + 1; j < T; j++){
                sum += arr[j];
                if(sum < 0){// If the most recent sum is -ve, count++
                    count++;
                }
            }
        }
        System.out.println(count);
    }
}


texts: Comparing products sold by several merchants

texts:
My application is for the use of comparing a product sold by several merchants on a daily basis. A process runs to load the current values of data for each store and enters it into a database along with any previous data. Later I plan to create graphs and such off of the history of data.

SELECT `a`.`part_number`, GROUP_CONCAT(`a`.`seller_id` ORDER BY `price` ASC), GROUP_CONCAT(`b`.`part_id` ORDER BY `price` ASC), GROUP_CONCAT(`b`.`price` ORDER BY `price` ASC)
FROM `parts`
LEFT JOIN (
           SELECT *
           FROM (
                 SELECT *
                 FROM `parts_data` AS `tmp_a`
                 ORDER BY `date_added` DESC
                ) AS `tmp_b`
           GROUP BY `part_id`
          ) AS `b`
ON `a`.`part_id` = `b`.`part_id`
GROUP BY `a`.`part_number`

To explain the query a little, I need to select the most recent price information for several part IDs and group them together with a selected part number for comparison. Also, upon concatenation the grouped items are sorted by price to be highest to lowest.

Each part number also can have any number of item IDs associated with it so there is no implication of how many companies are being watched.

part_number |  column1  |  column2  |  column3
++++++++++++++++++++++++++++++++++++++++++++++++
            | seller:A1 | seller:A3 | seller:A6
  153231    | id:x423   | id:x534   | id:x902
            | cost:23   | cost:34   | cost:57
++++++++++++++++++++++++++++++++++++++++++++++++
            | seller:A3 | seller:A1 | seller:A6
  345123    | id:x313   | id:x631   | id:x652
            | cost:78   | cost:86   | cost:99
++++++++++++++++++++++++++++++++++++++++++++++++
            | seller:A5 | seller:A1 |
  231756    | id:x663   | id:x291   |
            | cost:35   | cost:52   |


texts:
I am trying to optimize the filter method for RecyclerView Adapter in Android. The list is used as an ArrayList. I have seen this post but they are filtering from the original list every time. They are not using old results if a character is added.

Example: if there are 10 results for String 'a' then user type 'm' , 'am' results are subset of 'a' results.

Please suggest code optimizations for this method and any test-case where it fails.

public void filter(String s) {
    if (TextUtils.isEmpty(s)) {
        mList.clear();
        mList.addAll(copyList);
        notifyItemRangeRemoved(0, getItemCount());
        notifyItemRangeInserted(0, mList.size());
    } else {
        boolean isBackDirection = false;
        List<WeekWorkBean> tempList = null;
        if (s.length() < oldFilter.length()) {
            tempList = new ArrayList<>();
            tempList.addAll(mList);
            mList.clear();
            mList.addAll(copyList);
            isBackDirection = true;

        }
        for (int i = 0; i < mList.size(); i++) {
            WeekWorkBean bean = mList.get(i);
            if (!bean.getEmpName().toLowerCase().startsWith(s.toLowerCase())) {
                mList.remove(i);
                if (!isBackDirection) {
                    notifyItemRemoved(i);
                }
                i--;
            } else if (isBackDirection) {
                if (tempList.size() != 0) {
                    for (WeekWorkBean b : tempList) {
                        if (!bean.getEmpId().equals(b.getEmpId())) {
                            notifyItemInserted(i);
                        }
                    }
                } else {
                    notifyItemInserted(i);
                }
            }
        }

        oldFilter = s;
    }
}


texts:
I think there are some confusing and weird indentation problems in this WordPress file (single.php). Any suggestions on improving indentation and readability?

<?php
/**
 * The Template for displaying all single posts.
 *
 * @package WordPress
 * @subpackage Starkers
 * @since Starkers 3.0
 */

get_header(); ?>

<?php get_sidebar(); ?>

    <?php // Set and display custom field
        $intro_image = get_post_meta($post->ID, 'Intro Image', true); ?>

            <img src="<?php echo $intro_image; ?>" alt="" />

 <?php
    ?>

    <?php // Start The Loop
        if ( have_posts() ) while ( have_posts() ) : the_post();
    ?>

            <?php the_content(); ?>

    <?php endwhile; // end of the loop. ?>

    <?php //  Display previous and next posts thumbnails ?>

        <?php // Set and display custom field
            $mainbar_left_title = get_post_meta($post->ID, 'Mainbar Left Title', true);
            $mainbar_left_image = get_post_meta($post->ID, 'Mainbar Left Image', true); ?>

<?php echo $mainbar_left_title; ?>

                <img src="<?php echo $mainbar_left_image ?>" alt="" />

 <?php
        ?>

        <?php // Set and display custom field
            $mainbar_right_title = get_post_meta($post->ID, 'Mainbar Right Title', true);
            $mainbar_right_image = get_post_meta($post->ID, 'Mainbar Right Image', true); ?>

<?php echo $mainbar_right_title; ?>

                <img src="<?php echo $mainbar_right_image ?>" alt="" />

 <?php
        ?>

    <?php // Set and display custom field
        $mainbar_right_title = get_post_meta($post->ID, 'Mainbar Right Title', true);
        $mainbar_right_image = get_post_meta($post->ID, 'Mainbar Right Image', true); ?>

<?php echo $mainbar_right_title; ?>

            <img src="<?php echo $mainbar_right_image ?>" alt="" />

 <?php
    ?>

    <?php // Start The Loop
        if ( have_posts() ) while ( have_posts() ) : the_post();
    ?>

            <?php the_content(); ?>

    <?php endwhile; // end of the loop. ?>

    <?php get_sidebar('secondary'); ?>

<?php get_footer(); ?>


texts: Function to generate all valid parentheses of n*2

texts:
For a leetcode problem to generate the valid parentheses of length 2n, I have written this solution. It is working for smaller inputs but not for larger inputs. Please suggest a way to optimise my code.

I have read the Stack Overflow questions but was unable to implement the same concept in my code.

 //I have writte a bruteforce approch and got all the possible combinations..
//Then filter all the combinations to check if every one of them is a valid combination

public class Solution {

    public ArrayList<String> generateParenthesis(int a) {

        ArrayList<String> allCombinations = getAllPossibleCombinations(2*a,new ArrayList<String>());
        ArrayList<String> prunedCombinations = new ArrayList<String>();

        for(String comb : allCombinations)
        {
            if(isCombinationValid(comb))
            {
                prunedCombinations.add(comb);
            }
        }

        return prunedCombinations;
    }

    //Bruteforce way to get all the combinations...
    public ArrayList<String> getAllPossibleCombinations(int num,ArrayList<String> presentCombinations)
    {
        //templist is used to populate the result and pass the values
        ArrayList<String> tempList = new ArrayList<String>();
        if(num == 0) //num is zero, so return the combinations
        {
            return presentCombinations;
        }
        else
        {
            //In first call, just add ( and )
            if(presentCombinations.isEmpty())
            {
                tempList.add("(");
                tempList.add(")");
            }
            else //From second call, add ( and ) for current values in stack
            {
                for(String presentComb : presentCombinations)
                {
                    tempList.add(presentComb+"(");
                    tempList.add(presentComb+")");
                }
            }
        }
        //To pass the intermediate values and num-1
       return getAllPossibleCombinations(num-1,tempList);
    }

    //Check if an individual combination is valid..
    //Use stack to match the paranthesis
    public boolean isCombinationValid(String comb)
    {
            Stack<Character> st = new Stack<Character>();

            for(int i=0 ; i < comb.length() ; i++)
            {
                char current = comb.charAt(i);
                if(current == '(')
                {
                    st.push('(');
                }
                else
                {
                    if(!st.isEmpty() && st.peek() == '(')
                    {
                        st.pop();
                    }
                    else
                    {
                        st.push(')');
                    }
                }
            }

            if(st.isEmpty())
            {
                return true;
            }
            else
            {
                return false;
            }

    }

}


texts:
I've never had a serious attempt at writing an encryption algorithm before, and haven't read much on the subject. I have tried to write an encryption algorithm (of sorts), I would just like to see if anyone thinks it's any good. (Obviously, it's not going to be comparable to those actually used, given that it's a first attempt)

Without further adieu:

def encode(string, giveUserKey = False, doubleEncode = True):
    encoded = [] #Numbers representing encoded characters
    keys = [] #Key numbers to unlonk code
    fakes = [] #Which items in "encoded" are fake
    #All of these are stored in a file

    if giveUserKey:
        userkey = random.randrange(2 ** 10,  2 ** 16)
        # Key given to the user, entered during decryption for confirmation
        # Could change range for greater security
    else:
        userkey = 1

    for char in string:
        ordChar = ord(char)
        key = random.randrange(sys.maxsize)
        encoded.append(hex((ordChar + key) * userkey))
        keys.append(hex(key))

        if random.randrange(fakeRate) == 0:
            fake = hex(random.randrange(sys.maxsize) * userkey)
            encoded.append(fake)
            fakes.append(fake)

    if doubleEncode:
        encoded = [string.encode() for string in encoded]
        keys = [string.encode() for string in keys]
        fakes = [string.encode() for string in fakes]

    hashValue = hex(hash("".join([str(obj) for obj in encoded + keys + fakes]))).encode()

    return encoded, keys, hashValue, fakes, userkey

def decode(encoded, keys, hashValue, fakes, userkey = 1):
    if hash("".join([str(obj) for obj in encoded + keys + fakes])) != eval(hashValue):
        #File has been tampered with, possibly attempted reverse-engineering
        return "ERROR"

    for fake in fakes:
        encoded.remove(fake)

    decoded = ""

    for i in range(len(keys)):
        j = eval(encoded[i]) / userkey
        decoded += chr(int(j - eval(keys[i])))

    return decoded


texts: Prompting the user to enter Name value pairs and then printing it out using a Name_value class

texts:
I am learning from Bjarne Stroustrup's book for beginners and I on Chapter 6 Exercise 4 as seen below. I am studying it alone and I need some reviews.

Are my comments any good?

Can you recommend me some improvements regarding comments or overusing functions?

The writer of the book has some solutions for his exercise and he doesn't use the put_in function for example.

Are global variables that bad? I used it when declaring vector<Name_value>pairs.

/*
4. Define a class Name_value that holds a string and a value. Rework exercise 19 in Chapter 4 to use a
vector<Name_value> instead of two vectors.

Chapter 4 : 19. Write a program where you first enter a set of name-and-value pairs, such as Joe 17 and Barbara 22. For each pair, add
the name to a vector called names and the number to a vector called scores (in corresponding positions, so that if
names[7]=="Joe" then scores[7]==17). Terminate input with NoName 0. Check that each name is unique and
terminate with an error message if a name is entered twice. Write out all the (name,score) pairs, one per line.
*/

#include "../../std_lib_facilities.h"

const string print_names = "NoName";
const int print_val = 0;

//class of the name and corresponding value
class Name_value {
public:
    string Name;        //the name of the person
    int value;          //their respective score
    Name_value(string Na, int val)
        :Name(Na), value(val) { }
};
vector<Name_value>pairs;        //the list of names and their corresponding values

//put the pairs in the vector
vector<Name_value> put_in(string x, int y) {
    pairs.push_back(Name_value(x,y));
    return pairs;
}

int main()
try
{
    string names;
    int scores;
    cout << "Enter 'NoName' and score '0' when you want to print out the results!\n";
    cout << "Please enter some names and their scores (Ex.: Joe 22 Anne 53): ";
    while (cin) {
        cin >> names >> scores;
        if (!cin) error("You have not entered a string and then a value!\n");
        if (names == print_names && scores == print_val) {
            cout << "The list of pairs entered: \n";
            for (int i = 0; i < pairs.size(); i++) {
                 cout << pairs[i].Name << '\t' << pairs[i].value << '\n';
            }
            break;
        }
        for (int i = 0; i < pairs.size(); i++)
        {
            if (names == pairs[i].Name) error("Duplicates found!\n");
        }
        pairs = put_in(names, scores); //put the values into the vector list
    }
}
catch (exception&e)
{
    cerr << "error: " << e.what() << '\n';
    return 1;
}


texts: Calculation of clustering metric in Python

texts:
When I try to run the following code for arrays with more than 10k elements, it takes hours and I don't know how to make it in the most efficient way.

Any ideas?

from scipy.stats import entropy as KL
import numpy as np

def dis(di,dj):
    di = np.asanyarray(di)
    dj = np.asanyarray(dj)
    m =  0.5 * (di+dj)
    kl1 = KL(di,m)
    kl2 = KL(dj,m)
    return 0.5*(kl1+kl2)

def Intra_Cluster_dist(C):
    C = np.asanyarray(C)
    K = float(C.shape[0])
    factor1 = 1.0/float(K)
    total_sum = 0.0
    for cluster in C:
        cluster = np.asanyarray(cluster)
        below1 = float(cluster.shape[0])
        below2 = float(below1 - 1)
        sub_sum = 0.0
        for di in cluster:
            #others = cluster[:]
            #others.remove(di)
            others = cluster[np.logical_not((cluster == np.array(di)).all(axis=1))]
            #for dj in others:
            #    sub_sum = sub_sum +
                       (2*float(dis(di,dj)))/(float(below1)*float(below2))
            sub_sum = sub_sum + np.fromiter((((2*float(dis(di,dj)))/(float(below1)*float(below2))) for dj in others), dtype=float).sum()
    total_sum = total_sum + sub_sum
    return float(factor1 * total_sum)

def Inter_Cluster_dist(C):
    K = float(len(C))
    factor1 = float((1/(K*(K-1))))
    total_sum = 0.0
    for cluster in C:
        sub_sum = 0.0
        other_clusters = C[:]
        other_clusters.remove(cluster)
        below1= float(len(cluster))
        for other in other_clusters:
            below2= float(len(other))
            for di in cluster:
                for dj in other:
                    sub_sum = sub_sum + (float((dis(di, dj)))/float((below1*below2)))
         total_sum = total_sum + sub_sum
    return float(factor1 * total_sum )

def H_score(C):
    return float(Intra_Cluster_dist(C))/float(Inter_Cluster_dist(C))

Link to example data:

The data file is a xlsx. It has three columns: label (cluster label), feature_1 and feature_2.

The process to get C from the file and get the functions working should be something like this:

import pandas as pd
import numpy as np
df = pd.read_excel('example_data.xlsx')
c1 = np.asanyarray(df[df['labels'] == 0].apply(lambda row: ([row['feature_1'], row['feature_2']]), axis=1))
c2 = np.asanyarray(df[df['labels'] == 1].apply(lambda row: ([row['feature_1'], row['feature_2']]), axis=1))
C = [c1,c2]
H_score(C)


texts:
I have a code for a short Python 2 Pig Latin translator. Is it a good code, or should it be revised?

pyg = 'ay'
original = raw_input('Enter a word:')
# allows user input ^

if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
else:
print 'empty'

# prints the inputted word. If someone typed 'Hello', it will translate into Pig Latin.
print new_word

It works, but a shorter code may or may not be a good thing.


texts: How to simplify code, which adds spaces and commas if field value is not empty?

texts:
var searchDetails = "";
searchDetails += $("#last-name").val();
searchDetails += searchDetails != "" ? " "+$("#first-name").val() : $("#first-name").val();
searchDetails += searchDetails != "" ? " "+$("#middle-name").val() : $("#middle-name").val();
if ($("#dob-dd").val() != "" || $("#dob-mm").val() != "" || $("#dob-yyyy").val() != "") {
    searchDetails += searchDetails != "" ? ", " : "";
    searchDetails += "date of birth: ";
    searchDetails += ($("#dob-dd").val() != "" ? $("#dob-dd").val() : "xx") + ".";
    searchDetails += ($("#dob-mm").val() != "" ? $("#dob-mm").val() : "xx") + ".";
    searchDetails += ($("#dob-yyyy").val() != "" ? $("#dob-yyyy").val() : "xx") + ".";
}
if ($("#passport-id").val() != "") {
    searchDetails += searchDetails != "" ? ", " : "";
    searchDetails += "passport " + $("#passport-id").val();
}

searchDetails should contain values like (depending on what user has input):

lastName firstName middleName, date of birth dd.mm.yyyy, passport 123456789
firstName middleName, date of birth dd.xx.yyyy
lastName firstName, date of birth dd.mm.xxxx
date of birth dd.mm.xxxx, passport 123456789
lastName firstName middleName
passport 123456789


texts: Better way to manipulate this string in sequence?

texts:
I am working on a small custom Markup script in Java that converts a Markdown/Wiki style markup into HTML.

The below works, but as I add more Markup I can see it becoming unwieldy and hard to maintain. Is there is a better, more elegant, way to do something similar?

private String processString(String t) {
    t = setBoldItal(t);
    t = setBold(t);
    t = setItal(t);
    t = setUnderline(t);
    t = setHeadings(t);
    t = setImages(t);
    t = setOutLinks(t);
    t = setLocalLink(t);

    return t;
}

And on top of it, passing in the string itself and setting it back to the same string just doesn't feel right. But, I just don't know of any other way to go about this.


texts:
I have written a double linked list in Scala. The list should be fixed in size and items are always added to the head. if the list reaches max size then the tail is dropped.

This is my code. I want to review this for brevity and functional approach.

sealed trait List {
    var prev : List
    var next : List
}

case object Empty extends List {
    var prev : List = Empty
    var next : List = Empty
}
case class Node(v: Int, p: List, n: List) extends List {
    var prev = p
    var next = n
}

class DoubleLinkedList(maxSize: Int) {
    private var head : List = Empty
    private var tail : List = Empty
    private var currentSize = 0
    def print() : Unit = {
        var temp = head
        while(temp != Empty) {
            temp match {
                case Empty => println("Empty")
                case Node(v, _, _) => println(v)
            }
            temp = temp.next
        }
    }
    def add(i: Int) : List = {
        if (head == Empty || tail == Empty) {
            val n = new Node(i: Int, Empty, Empty)
            head = n
            tail = n
            currentSize += 1
            Empty
        } else {
            val n = new Node(i, null, head)
            head.prev = n
            head = n
            currentSize += 1
            if (currentSize > maxSize) {
                val retVal = tail
                tail = tail.prev
                tail.next = Empty
                currentSize -= 1
                retVal
            } else Empty
        }
    }
}


texts:
I have to print the number of stars that increases on each line from the minimum number until it reaches the maximum number, and then decreases until it goes back to the minimum number. After printing out the lines of stars, it should also print the total number of stars printed.

I have tried using shell scripting and worked. But is there any other simplified and generic way to achieve this. Or to be precise any better code to achieve this

echo "enter the mininum number of stars"
read min
echo "enter the maximum number of stars"
read max
for (( i=$min;i<=$max;i++))
do
   for (( j=$max;j>=i;j-- ))
   do
   echo -n " "
   done
   for (( c=1;c<=i;c++ ))
   do
   echo -n " *"
   sum=`expr $sum + 1`
   done
echo ""
done
d_max=`expr $max - 1`
for (( i=$d_max;i>=$min;i--))
do
   for (( j=i;j<=$d_max;j++ ))
   do
   if [ $j -eq $d_max ]
   then
   echo -n " "
   fi
   echo -n " "
   done
   for (( c=1;c<=i;c++ ))
   do
   echo -n " *"
   sum=`expr $sum + 1`
   done
echo ""
done
echo "Total No. of stars : "  $sum

Output:

      *
     * *
    * * *
   * * * *
  * * * * *
   * * * *
    * * *
     * *
      *


texts:
I don't use constraints or IB to create views so it's easier to create rects this way. Does it wrong totaly?

@interface Client ()

@property (nonatomic, strong) UITextField *name;
@property (nonatomic, strong) UITextField *phoneNumber;
@property (nonatomic, strong) UITextField *address;
@property (nonatomic, strong) UIButton *submit;

@end

@implementation ClientAddVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSubviews];
    [self createViewsRects:@[_name, _phoneNumber, _address, _submit]];

}

- (void)createSubviews{

    _name = [Utility textFieldWithPadding:@"Name" frame:[Utility rectForFormFields]];
    _name.delegate = self;
    _phoneNumber = [Utility textFieldWithPadding:@"Phone Number" frame:[Utility rectForFormFields]];
    _phoneNumber.keyboardType = UIKeyboardTypePhonePad;
    _phoneNumber.delegate = self;
    _address = [Utility textFieldWithPadding:@"Address" frame:[Utility rectForFormFields]];
    _address.delegate = self;

    _submit = [UIButton buttonWithType:UIButtonTypeCustom];
    [_submit setTitle:@"Submit" forState:UIControlStateNormal];
    [_submit addTarget:self action:@selector(saveClient) forControlEvents:UIControlEventTouchUpInside];
    _submit.backgroundColor = [[Cache sharedCache]blackColor];
    _submit.frame = [Utility rectForFormFields];

    [self.view addSubview:_name];
    [self.view addSubview:_phoneNumber];
    [self.view addSubview:_address];
    [self.view addSubview:_specialRequest];
    [self.view addSubview:_averageOrderSize];
    [self.view addSubview:_submit];
}

- (void)saveClient{
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    _currentField = textField;
}

- (void)createViewsRects:(NSArray *)views{
    CGFloat padding = 16;
    CGFloat rowPadding = 8;
    CGFloat totalHeight = padding;

    for (UIView *view in views) {
        CGRect viewRect = view.frame;
        viewRect.origin.x = padding;
        viewRect.origin.y = totalHeight;
        view.frame = viewRect;
        totalHeight += (view.frame.size.height + rowPadding);
    }
    self.bgView.contentSize = CGSizeMake(self.view.frame.size.width, totalHeight);
}
@end


texts: Lexer Implementation in Rust - `PhantomData` Awkwardness

texts:
I've been working on a Tokeniser/Lexer in Rust. I would like to have the tokeniser take input from different sources, such as files or in-memory strings. To abstract over this concern i've created a trait Source. This has left me with a wonky situation where I appear to need a PhantomData member in the token iterator. I've created a cut-down example here:

/// Source of Characters
///
/// In this example all that a source can do is be sliced to retrieve
/// a subsection of the overall character buffer.
trait Source<'a> {
    /// Character at Offset
    ///
    /// Gets the character at the given offset in the buffer and
    /// returns it. If no character is available at that offset `None`
    /// is returned.
    fn at(&self, offset: usize) -> Option<(char, usize)>;

    /// Slice the Source Buffer
    fn slice(&self, start: usize, end: usize) -> &'a str;
}

/// Source of Characters from a `str` Slice
struct StringSource<'a> {
    pub buff: &'a str
}

/// Implementation of the Source trait.
impl<'a> Source<'a> for StringSource<'a> {
    fn at(&self, offset: usize) -> Option<(char, usize)> {
        self.buff[offset..].chars().nth(0).map(|ch| { (ch, offset + ch.len_utf8()) })
    }

    fn slice(&self, start: usize, end: usize) -> &'a str {
        &self.buff[start..end]
    }
}

/// Token Iterator Implementation
///
/// This token iterator takes a given source and steps through it returning string slices for each token
struct TokenIter<'a, S>
    where S: Source<'a>,
          S: 'a
{
    source: S,
    idx: usize,
    phantom: ::std::marker::PhantomData<&'a ()>,
}

impl<'a, S> TokenIter<'a, S>
    where S: Source<'a>
{
    /// Create a Token Iterator from a Source
    fn new(source: S) -> Self {
        TokenIter {
            source: source,
            idx: 0,
            phantom: ::std::marker::PhantomData,
        }
    }
}

/// Token Iterators implement `Iterator`
impl<'a, S> Iterator for TokenIter<'a, S>
    where S: Source<'a>
{
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        let ts = self.idx;
        self.source.at(ts).map(|(_ch, next)| {
            self.idx = next;
            // Imagine a regex state machine is run here to produce a token
            // rather than just returning single-character tokens.
            self.source.slice(ts, next)
        })
    }
}

fn main() {
    let source = StringSource{ buff: "hello world" };
    let iter = TokenIter::new(source);
    println!("{:?}", iter.collect::<Vec<_>>());
}

Run it here:
https://is.gd/OCL91u

Is there a nicer way to express the source buffer lifetime 'a so that I don't need a PhantomData member or this bit of funky lifetime constraints:

where S: Source<'a>,
      S: 'a


texts: Plotting many images at once in matplotlib

texts:
I am using numpy and  matplotlib to do a statistical simulation.  The simulation itself is pretty fast thanks to numPy vectorizatio, however the plotting is slow since I still use a for loop.

Here is the result:

Right now, I call matplotlib.pyplot.plt 10000 times - once for each tile in 100 × 100 square which can't possibly be optimal, but I can't think of how to do it better:

N = 100
for x in range(N):
    for y in range(N):
        plt.fill( myPath[x,y,0] ,myPath[x,y,1])

Let's say I stored all the varaibles in an numPy array myPath with shape (N,N,2,4) so that myPath[x,y,0] and myPath[x,y,1] give the x and y coordinates of the path.

How do I reduce the number of calls to plt in my visualization?


texts:
I have tried to solve the problem 607 in Project Euler  using the Gradient Descent Algorithm. While I’m getting the answer right I’m not sure if I have used the gradient algorithm correctly or coded it efficiently in Python. I’ll appreciate any guidance or suggestions to improve.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 11 18:48:41 2018

"""

# Gradient Descent Algorithm

import numpy as np
import time
import random

def duration(points): # Duration as the objective function
    speed = [ 10, 9, 8, 7, 6, 5,10 ]
    duration=0
    for i in range(0,len(speed)):
        distance = ((points[i+1,0]-points[i,0])**2 + (points[i+1,1]-points[i,1])**2)**0.5
        duration += distance / speed[i]
    return duration

def gradient_function(points): # Gradient: Partial differential of duration function f(x) wrt x
    speed = [ 10, 9, 8, 7, 6, 5,10 ]
    gradient = 0 #np.zeros((8,2))
    for i in range(0,len(speed)):
        gradient += ((points[i+1,0]-points[i,0])/(speed[i]*((points[i+1,0]-points[i,0])**2 + (points[i+1,1]-points[i,1])**2)**0.5))
    return gradient

# Generate randon number between -1 and +1
def myrand():
    seed = random.random() * 2 - 1
    return seed

# Compute x = x0-delta*gradient
def gradient_descent(points,delta):
    old_Duration = duration(points)
    new_Duration = old_Duration - delta * gradient_function(points)
    if myrand() > 0:
        delta = -delta
    id = int(random.random()*6)+1
    points[id,0] += delta
    new_Duration = old_Duration - (1+ delta)*delta * gradient_function(points)
    if (duration(points) >= old_Duration):
        points[id,0] -= delta
        new_Duration = old_Duration - (1-delta)*delta * gradient_function(points)
    return new_Duration

# Floating Point Range Function
def frange(start, stop, step):
    i = start
    while i >= stop:
        yield i
        i /= step
    return step

# Calculate the Minimum Days
def min_days():
    normal_terrain = ((100 / np.sqrt(2) - 50) / 2)
    marsh = 10.
    ini_xy = [ 0., normal_terrain, marsh, marsh, marsh, marsh, marsh, normal_terrain ]
    y_coords = []
    x_coords = []
    k = 0
    for i in range(0,len(ini_xy)):
        k += ini_xy[i]
        y_coords.append(k)
        x_coords.append(k)
    points = (np.stack((x_coords,y_coords), axis=-1))

    for delta in frange(1e-2, 1e-10, 10):
        for i in range(10000):
            gradient_descent(points,delta)
    min_days = gradient_descent(points,delta)
    return min_days

start = time.time()
answer = min_days()
elapsed = time.time() - start
print("\nThe Minimum Days is %s found in %s seconds" % (answer,elapsed))


texts:
As I mentioned in my bio, I do not code for a living and too old to switch careers but I do enjoy it as a hobby and I am trying to get better. Also trying to get my teenage son more interested. Anyhow, the code below does want I want it to but I am looking for tips to improve it. Any advice would be much appreciated before I add more to it with High Score tables and more functionality.

import random
weapons = ["Sword", "Spell", "Fire"]
shields = ["Armour", "Magic", "Water"]

class Player:
    def __init__(self, name):
        self.name = name
        self.health = 100
        self.weapon = 0
        self.shield = 0

    def damage(self):
        points = random.randint(10, 35)
        self.health -= points

    def selectWeapon(self):
        choice = int(input("Choose your weapon 1-Sword, 2-Spell or 3-Fire:  "))
        self.weapon = choice - 1

    def selectShield(self):
        choice = int(input("Choose your shield 1-Armour, 2-Magic or 3-Water:  "))
        self.shield = choice - 1

# Child class of player with override methods for weapon
# and shield selection
class AiPlayer(Player):
    def __init__(self,name):
        super().__init__(name)

    def selectWeapon(self):
        choice = random.randint(1, 3)
        self.weapon = choice - 1

    def selectShield(self):
        choice = random.randint(1, 3)
        self.shield = choice - 1

class Game:
    def __init__(self):
        self.gameOver = False
        self.round = 0

    def newRound(self):
        self.round += 1
        print("\n***   Round: %d   ***\n" %(self.round))

    # Check if either or both Players is below zero health
    def checkWin(self, player, opponent):
        if player.health < 1 and opponent.health > 0:
            self.gameOver = True
            print("You Lose")
        elif opponent.health < 1 and player.health > 0:
            self.gameOver = True
            print("You Win")
        elif player.health < 1 and ai.health < 1:
            self.gameOver = True
            print("*** Draw ***")

    def displayResult(self, player, opponent):
            print("%s used a %s, %s used a %s Shield\n" %(player.name, weapons[player.weapon], opponent.name, shields[opponent.shield]))
            print("%s caused damage to %s\n" %(player.name, opponent.name))

    def takeTurn(self, player, opponent):

        # Decision Array
        #
        #           Armour|  Magic |  Water
        #           ______|________|_______
        # Sword:    False |  True  |  True
        # Spell:    True  |  False |  True
        # Fire :    True  |  True  |  False

        decisionArray = [[False, True, True], [True, False, True], [True, True, False]]
        if decisionArray[player.weapon][opponent.shield]:
            opponent.damage()
            currentGame.displayResult(player, opponent)
        else:
            print("\n%s used a %s, %s used a %s Shield" %(player.name, weapons[player.weapon], opponent.name, shields[opponent.shield]))
            print("%s blocked %s's attack - No Damage" %(opponent.name, player.name))

# Setup Game Objects
currentGame = Game()
human = Player("Mark")
ai = AiPlayer("Computer")

players = [human, ai]

# Main Game Loop
while not currentGame.gameOver:
    for player in players:
        player.selectWeapon()
        player.selectShield()
    currentGame.newRound()
    currentGame.takeTurn(human, ai)
    currentGame.takeTurn(ai, human)
    print("%s's health = %d" %(human.name, human.health))
    print("%s's health = %d" %(ai.name, ai.health))
    currentGame.checkWin(human, ai)


texts:
Hello this is a Console App(.Net Core) in Visual Studio 2019 and i am trying to split a string into sentences and then add them into a dictionary with Key the first word of the sentence and Value the sentence itself.
I have the following code and i wonder if the way i did it has of course a better way to handle it.

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

namespace StringParse
{
    class Program
    {
        static void Main(string[] args)
        {
            string phrase = @"MHD001|LOCCOD|GRCACS|20191117|133601|CB|trx_grcacs_tsk_20191117133601498|
TSK001|GLS|GRCACS|59144|59144|2|TU|93000161357|TRACE|INF|DE 800|please send us the completely address information-thanks|68481|20191117|133555|
TSA001|X|
TSI001|3655|please send us the completely address information-thanks|66510|
TSI001|5637|80337|61335|
TSI001|5841|DE|61313|
MTR001|5|";
            /////////////////////////////////////////////////////////////////////
            string sentenceSeparator = @"\b[A-Z]{3}\d{3}\b";
            string[] words = phrase.Split('|');

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < words.Length; i++)
            {
                //If current word array matches the regex
                if (words[i].Equals(sentenceSeparator))
                {
                    // If the current array value doesn't match, then continue the current line.
                    sb.Append(words[i]);
                    sb.Append(" ");
                }
                else
                {
                    if (i == 0)
                    {
                        // on the 1st iteration, we don't need a new line before the text value.
                        sb.Append(words[i]);
                        sb.Append(" ");
                    }
                    else
                    {
                        sb.Append(words[i]);
                        sb.Append(" ");
                    }
                }
            }
            string[] sentences = sb.ToString().Split('\r');

            ////////////////////////////////////////////////////////////////////////

            Regex regx = new Regex(sentenceSeparator);

            MatchCollection matches = Regex.
                Matches(phrase, sentenceSeparator,
                RegexOptions.Compiled |
                RegexOptions.CultureInvariant);

            for (int i = 1; i < matches.Count; ++i)
            {
                phrase = phrase
                    .Replace(matches[i].Value,
                    Environment.NewLine + matches[i].Value);
            }
            ///////////////////////////////////////////////////////////////////////////////

            Dictionary<Match, string> dic = matches.Zip(sentences, (x, y)
                 => new { Key = x, Value = y }).ToDictionary(x => x.Key, y => y.Value);

            foreach (KeyValuePair<Match, string> kvp in dic)
            {
                Console.WriteLine("Key = {0}" + Environment.NewLine + "Value = {1}", kvp.Key, kvp.Value);
            }

        }

    }

}

output will be like that:

Key = MHD001
Value = MHD001 LOCCOD GRCACS 20191117 133601 CB trx_grcacs_tsk_20191117133601498
Key = TSK001
Value = TSK001 GLS GRCACS 59144 59144 2 TU 93000161357 TRACE INF DE 800 please send us the completely address information-thanks 68481 20191117 133555
Key = TSA001
Value = TSA001 X
Key = TSI001
Value = TSI001 3655 please send us the completely address information-thanks 66510
Key = TSI001
Value = TSI001 5637 80337 61335
Key = TSI001
Value = TSI001 5841 DE 61313
Key = MTR001
Value = MTR001 5


texts: Rearranging numbers to get the largest number

texts:
Given a Integer, find the maximum number that can be formed from the digits.

Input: 8754365
Output: 8765543

private static int largestNumber(int data) {
    int num = data;
    int[] times = new int[10];
    while (num != 0) {
        if (num == 0) {
            break;
        }
        int val = num % 10;
        times[val]++;
        num /= 10;
    }
    String largestNumber = "";
    for (int i = 9; i >= 0; i--) {
        for (int j = 0; j < times[i]; j++) {
            largestNumber += i;
        }
    }
    return Integer.parseInt(largestNumber);
}

Is there any optimization or anything I can improve here?


texts: Foreach loop to generate HTML table with title in first cell of each row in PHP

texts:
I've used quite a lot of foreach loops to achieve this type of HTML table that has titles in the first cell of each row:

         	Product 1	Product 2

          Width	50mm	90mm
          Material	Plastic	Gold
          Diameter	60 mm	70mm
          Battery Hours	60 hours	50 hours

Is it necessary to use so many foreach loops? Do you have any other better way of getting this output?

  $sql = "SELECT * FROM product WHERE name IN ('Product 1','Product 2') ";
  if ($wpdb->query($sql))
  {
    $rows = $wpdb->last_result;
    $similar_com = "";
    $similar_com .= "

	";

    foreach($rows as $row)
    {
       $similar_com .= "image_url."' alt='".$row->model_no."'>";
    }
    $similar_com .= "

Width	";
    foreach($rows as $row)
    {
       $similar_com .= "$row->width mm	";
    }
    $similar_com .= "
Material	";
    foreach($rows as $row)
    {
       $similar_com .= "$row->material	";
    }
    $similar_com .= "
Case diameter	";
    foreach($rows as $row)
    {
       $similar_com .= "$row->case_diameter (".plus($product->case_diameter - $row->case_diameter)." mm)	";
    }
    $similar_com .= "
Case thickness	";

    foreach($rows as $row)
    {
       $similar_com .= "$row->case_thickness (".plus($product->case_thickness - $row->case_thickness)." mm)	";
    }
    $similar_com .= "
Case Material	";
    foreach($rows as $row)
    {
       $similar_com .= "$row->case_material	";
    }
    $similar_com .= "
Battery Hours	";
    foreach($rows as $row)
    {
       $similar_com .= "$row->battery_hours hours	";
    }
    $similar_com .= "
Special Functions	";
    foreach($rows as $row)
    {
       $similar_com .= "$row->special_functions	";
    }

    $similar_com .= "

";
   }


texts: Updating ActiveRecord with text from a joined table

texts:
I have an Active Record update with the following data model:

TvMenuProfile has one rich_text_special
Bar has zero to many tv_menu_profiles
Special has one bar_id and one description

I want to copy all of the Special.description columns to each TvMenuProfile. The link between the two is tv_menu_profile.bar.specials.first.description.

To my understanding this cannot be accomplished with a single Arel query, but could possibly be done with a complex, raw SQL query.

The following is what I have right now, which works. However it performs an UPDATE for each TvMenuProfile that has a bar that has a special, which is not ideal.

TvMenuProfile.joins(bar: :specials).select("*").each do |profile|
  plain_text_description = profile.bar.specials.first.description
  profile.update_attribute(:rich_text_special, plain_text_description)
end

Any thoughts on improving this?


texts:
So, first time I try PHP. Thought I'd set a goal for myself, divide it up in smaller problems and start googling. So yes I got it to work, very happy.

But, it is rather crude and ugly. So now I would like to know how it should look.
Proper regex, proper formatting in the array, keeping the links as links and any other tips.

Just to be clear, what it does: You place this on a server you have, browse to the url where the file is, it scrapes Pirate Bay, and emails you the names and magnets. It could be used by one person on his web domain as private 'proxy'. No one else can see or use it and it is all in one simple file.

I miss-posted earlier but they did say using cache would be smart.

$data = file_get_contents('http://thepiratebay.se/top/201');
$selected = '/Details.for.(.+?)"|magnet:.+?"/';
preg_match_all($selected,$data,$matches, PREG_OFFSET_CAPTURE);

$to = "me@domain.com";
$subject = "Pirate Mail";

if (mail($to, $subject, print_r($matches, 1), 'From: BlackBeard@piratemail.com')) {
   echo("
Message successfully sent!
");
  } else {
   echo("
Message delivery failed...
");
  }


texts:
The below code is run on a routine rather than say login time but being new to using FETCH NEXT I can't help think maybe there is a trick here to merge at least one of the SET lines.

The end results should give me the total unique users, how many completed a module and how many passed.

Fields are indexed on the table at this time but all additional thoughts welcome.

 USE [DB]
    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[spModuleStatisticsUnique2]
    -- Add the parameters for the stored procedure here
    AS

    DECLARE @i INT = 0;
DECLARE @i INT = 0;
DECLARE @Started   int;
DECLARE @Completed  int;
DECLARE @Passed  int;
DECLARE @ModuleID  int;
    DECLARE merge_cursor CURSOR FAST_FORWARD FOR SELECT [ModuleID] FROM dbo.[TblModules]
    --ORDER BY [ModuleID]
    OPEN merge_cursor

    FETCH NEXT FROM merge_cursor INTO @ModuleID

    WHILE @@FETCH_STATUS = 0
    BEGIN

        SET @Started =  (Select Count(ID) FROM [TblResults] WHERE [ModuleID] = @ModuleID)
        SET @Completed = (Select Count(ID) FROM [TblResults] WHERE [ModuleID] = @ModuleID and ModuleDatecomplete <> '')
        SET @Passed = (Select Count(ID) FROM [TblResults] WHERE [ModuleID] = @ModuleID and Pass = 'Yes')

        UPDATE [TblModules]
        SET
        [Started] = @Started
        ,[Completed] = @Completed
        ,[Passed] = @Passed
        ,[PassedPercent] = ((@Passed * 100.0) / @Started)
        WHERE
        [ModuleID] = @ModuleID

    FETCH NEXT FROM merge_cursor INTO @ModuleID
    END

    CLOSE merge_cursor
    DEALLOCATE merge_cursor


texts:
I've wrote a generic function to add an item to an Array 2D

This is what I have:

Private Sub Add_Item_Array_2D(ByRef Array_2D As String(,), _
                              ByVal Items As String())

    Dim tmp_array(Array_2D.GetUpperBound(0) + 1, Array_2D.GetUpperBound(1)) As String

    For x As Integer = 0 To Array_2D.GetUpperBound(0)
        tmp_array(x, 0) = Array_2D(x, 0)
        tmp_array(x, 1) = Array_2D(x, 1)
    Next

    For x As Integer = 0 To Items.Count - 1
        tmp_array(tmp_array.GetUpperBound(0), x) = Items(x)
    Next

    Array_2D = tmp_array

End Sub

The code works, but I want to know if can be improved using Array.Resize method of LINQ extensions.

This is an usage example:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.shown

    ' Create Array 2D (2,2)
    Dim MyArray As String(,) = _
    {{"Item 0,0", "Item 0,1"}, {"Item 1,0", "Item 1,1"}, {"Item 2,0", "Item 2,1"}}

    ' Add Item
    Add_Item_Array_2D(MyArray, {"Item 3,0", "Item 3,1"})

    ' Loop over the Array 2D
    For x As Integer = 0 To MyArray.GetUpperBound(0)
        MsgBox(String.Format("Array 2D {1},0: {2}{0}Array 2D {1},1: {3}", Environment.NewLine, _
                            x, MyArray(x, 0), MyArray(x, 1)))
    Next

End Sub


texts: Simple example to get started with a browser based game

texts:
Here is a "hello world" simple skeleton I wrote to get started on an HTML5/javascript game. I converted it from a python example provided in Coursera's "An Introduction to Interactive Programming in Python" which demonstrates how to start moving a ball around a canvas using arrow keys.

I did this as a learning exercise to get to grips with javascript. While I've got this code to pass jslint, I was wondering if more experienced javascript coders could suggest better ways of doing this.

var canvas, context, ball_pos, vel, keys = {};

var BALL_RADIUS = 20;

function init() {
    'use strict';
    canvas = document.getElementById('c');
    context = canvas.getContext('2d');
    ball_pos = [canvas.width / 2, canvas.height / 2];
    vel = 4;
}

function draw() {
    'use strict';

    // draw background
    context.fillStyle = 'black';
    context.fillRect(0, 0, canvas.width, canvas.height);

    // draw ball
    context.strokeStyle = 'red';
    context.lineWidth = 2;
    context.fillStyle = 'white';
    context.beginPath();
    context.arc(ball_pos[0], ball_pos[1], BALL_RADIUS, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
    context.stroke();
}

function keydown(evt) {
    'use strict';
    // mozilla based browsers return which and others keyCode
    var keyCode = evt.which || evt.keyCode;
    keys[keyCode] = true;
    // alert(keyCode)
    // 33 up right
    // 34 down right
    // 35 down right
    // 36 up left
    if (keys[37]) { // left
        ball_pos[0] -= vel;
    }
    if (keys[38]) { // up
        ball_pos[1] -= vel;
    }
    if (keys[39]) { // right
        ball_pos[0] += vel;
    }
    if (keys[40]) { // down
        ball_pos[1] += vel;
    }
}

function keyup(evt) {
    'use strict';
    var keyCode = evt.which || evt.keyCode;
    delete keys[keyCode];
}

function animate() {
    'use strict';
    window.requestAnimationFrame(animate);
    draw();
}

// register event handlers
window.onkeydown = keydown;
window.onkeyup = keyup;

init();
animate();
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <canvas id="c" width="600" height="400"></canvas>
</body>
</html>


texts:
The Fizz Buzz challenge is well-known and should not need any explanations, right?
I recently got a bit bored and came up with a solution for Fizz Buzz using LINQ and even asynchronous code and a lot of extension methods. Actually, it's only Extension methods!
So, I thought, let's share it and have a review of my code!

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

namespace FizzBuzzApp
{
    using IntEnum = IEnumerable<int>;
    using Pair = KeyValuePair<int, string>;
    using PairEnum = IEnumerable<KeyValuePair<int, string>>;
    using StringEnum = IEnumerable<string>;

    public static class FizzBuzzClass
    {
        public static T DoThis<T>(this T data, Action<T> action) { action(data); return data; }
        public static T DoThis<T>(this T data, Action action) { action(); return data; }
        public static IEnumerable<T> DoThis<T>(this IEnumerable<T> data, Action<T> action) { foreach (var item in data) { action(item); yield return item; } }

        public static T IfThis<T>(this T data, Func<T, bool> condition, Func<T, T> action) => condition(data) ? action(data) : data;
        public static T IfThis<T>(this T data, Func<T, bool> condition, Func<T, T> onTrue, Func<T, T> onFalse) => condition(data) ? onTrue(data) : onFalse(data);

        public static IntEnum MakeIntArray(this int count, int start = 0) => Enumerable.Range(start, count);

        public static Pair NewPair(this int key) => new Pair(key, string.Empty);
        public static Pair NewPair(this Pair pair, string data) => new Pair(pair.Key, data.Trim());
        public static PairEnum MakePairs(this IntEnum data, bool asynchronous) => asynchronous ? data.AsParallel().Select(NewPair) : data.Select(NewPair);
        public static IOrderedEnumerable<Pair> SortPairs(this IEnumerable<Pair> data) => data.OrderBy(p => p.Key);

        public static bool IsFizz(this Pair data) => data.Key % 3 == 0;
        public static Pair DoFizz(this Pair data) => data.NewPair("Fizz " + data.Value);
        public static Pair Fizz(this Pair data) => data.IfThis(IsFizz, DoFizz);
        public static PairEnum Fizz(this PairEnum data, bool asynchronous) => asynchronous ? data.AsParallel().Select(Fizz) : data.Select(Fizz);

        public static bool IsBuzz(this Pair data) => data.Key % 5 == 0;
        public static Pair DoBuzz(this Pair data) => data.NewPair(data.Value + " Buzz");
        public static Pair Buzz(this Pair data) => data.IfThis(IsBuzz, DoBuzz);
        public static PairEnum Buzz(this PairEnum data, bool asynchronous) => asynchronous ? data.AsParallel().Select(Buzz) : data.Select(Buzz);

        public static bool IsNumber(this Pair data) => string.IsNullOrEmpty(data.Value);
        public static Pair DoNumber(this Pair data) => data.NewPair(data.Key.ToString());
        public static Pair Number(this Pair data) => data.IfThis(IsNumber, DoNumber);
        public static PairEnum Number(this PairEnum data, bool asynchronous) => asynchronous ? data.AsParallel().Select(Number) : data.Select(Number);

        public static StringEnum Values(this PairEnum data) => data.Select(p => p.Value);
        public static string Combine(this StringEnum data) => string.Join(", ", data);

        public static string FizzBuzz(this int count, bool asynchronous = false) =>
            count.MakeIntArray()
                 .MakePairs(asynchronous)
                 .Fizz(asynchronous)
                 .Buzz(asynchronous)
                 .Number(asynchronous)
                 .SortPairs()
                 .Values()
                 .Combine();
}

To use it, just use 100.FizzBuzz(true); for the asynchronous version.
Now, the thing is that it's full one-liner extension methods. It's definitely not something a beginner would write. But is it well-written for experts?


texts: Fluent interface and polymorphism for building a scene with shapes

texts:
I would like to improve the interfaces of some polymorphic classes going from positional to named parameters and I came up with the fluent interface.

The following is the most clean, compact and compilable (-std=c++11 required) example that I have been able to come up with:

#include <iostream>
#include <cmath>
#include <vector>
#include <string>

using namespace std;

struct Figure {
  string _name;
  Figure * name(const string & str) { _name=str; return this; }
  virtual double area() const=0;
};

struct Circle: Figure {
  double _radius;
  Circle * radius(double r) { _radius=r; return this;}
  double area() const override {return M_PI*_radius*_radius;}
};

struct Square: Figure {
  double _side;
  Square * side(double s) { _side=s; return this;}
  double area() const override {return _side*_side;}
};

struct Scene {
  vector<Figure*> v;
  ~Scene() { for (auto & f : v) delete f; }
  Scene & add(Figure * f) {v.push_back(f); return *this;}
  double total_area() const {
    double total=0;
    for (auto f : v) total += f->area();
    return total;
  }
};

int main() {
  Scene scene;
  scene.add((new Circle)->radius(1.)->name("c1"))
       .add((new Square)->  side(1.)->name("s1"));
  cout << "Total area: " << scene.total_area() << endl;
  return 0;
}

I have a couple of issues with this:

That is an ugly place to have a new operator, could it be avoided somehow?
After having called the method name("name") the type is lost so there is still an ordering to respect: add((new Square)->name("s1")->side(1.)) will not compile. You should imagine to have many levels of inheritance and lots of parameters to be setted!

How would you address these issues and improve the code? C++1y is allowed and preferred to Boost?

For further improvements see the related question: Variadic templates and pointers to member functions to achieve a named-parameters interface in C++


texts: Localization manager based on ReactiveCocoa

texts:
I have a localization manager class which can change app language on the fly. It's using ReactiveCocoa and my main concern is that I'm not using some of RAC parts correctly.

First (in - (void)configureSignals):

+ (instancetype)sharedInstance
{
    static i2KRLMLocalizationManagerObject *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[[self class] alloc] init];
        [sharedInstance initialConfiguration];
    });
    return sharedInstance;
}

- (void)initialConfiguration
{
    [self configureSignals];
    [self configureAppLocalizations];
}

- (void)configureSignals
{
    RACReplaySubject *subject = [RACReplaySubject replaySubjectWithCapacity:1];
    self.localeConnection = [subject multicast:subject];
    [self.localeConnection autoconnect];

    RACReplaySubject *languagesSubject = [RACReplaySubject replaySubjectWithCapacity:1];
    self.languageNamesConnection = [languagesSubject multicast:languagesSubject];
    [self.languageNamesConnection autoconnect];

    RACReplaySubject *languageIndexSubject = [RACReplaySubject replaySubjectWithCapacity:1];
    self.languageIndexConnection = [languageIndexSubject multicast:languageIndexSubject];
    [self.languageIndexConnection autoconnect];
}

It feels for me that multicast should be used differently(and is used wrong currently, although it works), although I'm not sure how to use it correctly.

Those signals are used to propagate NSLocale, array of supported languages and current language index in that array. I use multicast so that if there is more then 1 subscriber, signal will be shared and current values will be just replayed. I'm not sure that signal multicasting itself is idiomatic/correct way. Also I'm not completely sure if connection is needed at all or I can just go with ReplaySubject.

Second (like here):

- (void)changeToLocale:(NSLocale *)locale
{
    [self reloadBundleWithLocaleID:[locale localeIdentifier]];
    [(RACSubject *)[self localeSignal] sendNext:locale];
}

Cast has to be made now because in interface it's declared as - (RACSignal *)localeSignal; and is actually

- (RACSignal *)localeSignal
{
    return self.localeConnection.signal;
}

which is defined as RACSignal in ReactiveCocoa as well, but since it's definitely RACSubject(RACReplaySubject is subclass of RACSubject and since sendNext is available on RACSubject and not on RACSignal I need to cast to avoid compiler complaints).

I use that getter instead of self.languageNamesConnection.signal because if I ever change this to something I wouldn't have to go all over and remove traces of that. But the cast looks just wrong.

I don't like this cast at all, although not sure how to improve this(since I'm sending values through multicasted signal; and probably get rid of this sending altogether if possible).

Also general suggestions on improving would be very helpful(I think there should be more FRP way to do this).

Full repo with example is here, class is here.


texts: Calculating average value of points around given point in a wider field

texts:
I need to calculate the average value of points around a given point in a wider field.
For this I have a function:
fn local_average((x,y):(i32,i32),n:i32,(width,height):(i32,i32),space:&[i32]) -> i32 {
    let y_range = cmp::max(y-n,0)..cmp::min(y+n+1,height);
    let x_range = cmp::max(x-n,0)..cmp::min(x+n+1,width);
    println!("y: {:.?}, x: {:.?}",y_range,x_range);

    let size = (x_range.end-x_range.start) * (y_range.end-y_range.start);
    let mut total: i32 = 0;
    for yi in y_range {
        for xi in x_range.clone() {
            let i = yi * width + xi;
            total += space[i as usize];
        }
    }

    println!("{} / {} = {}",total,size,total / size);
    total / size
}

The thing that bothers me here is x_range.clone(), I feel like this is not a good approach.
I could also implement this in a more function manor but I'm unsure if this is  better as I find it to be less readable:
fn local_average_functional((x,y):(i32,i32),n:i32,(width,height):(i32,i32),space:&[i32]) -> i32 {
    let y_range = cmp::max(y-n,0)..cmp::min(y+n+1,height);
    let x_range = cmp::max(x-n,0)..cmp::min(x+n+1,width);
    println!("y: {:.?}, x: {:.?}",y_range,x_range);

    let size = (x_range.end-x_range.start) * (y_range.end-y_range.start);
    let total: i32 = y_range.map(|yl| {
        x_range.clone().map(|xl| {
            let il = yl * width as i32 + xl;
            space[il as usize] as i32
        }).sum::<i32>()
    }).sum();

    println!("{} / {} = {}",total,size,total / size);
    total / size
}

How could I improve this function?
Repl: https://repl.it/@JonathanWoollet/DraftyTautAdware


texts: Split a file into individually allocated lines

texts:
This is part of a larger project that is to run on POSIX systems. My concerns with it are the lack of comments, best practices with the filesystem, and naming things. Of course all feedback is great.

fileio.h:

#ifndef FILEIO_H
#define FILEIO_H

char **readlines(const char *path);
void freelines(char **lines);

#endif

fileio.c:

#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include "fileio.h"

static off_t getsize(int fd);
static char *getfile(int fd, off_t *size);
static long countlines(char *buf, off_t size);
static char *allocline(char *buf, off_t size, char **next);
static char **getlines(char *buf, off_t size);

char **readlines(const char *path)
{
    int fd, ret;
    off_t size;
    char *buf;
    char **tmp, **lns = NULL;

    fd = open(path, O_RDONLY);
    if (fd == -1)
        goto out;

    ret = flock(fd, LOCK_NB | LOCK_EX);
    if (ret == -1)
        goto out;

    size = getsize(fd);
    if (size == -1)
        goto close;

    buf = getfile(fd, &size);
    if (buf == NULL)
        goto close;

    (void)flock(fd, LOCK_UN);

    tmp = getlines(buf, size);
    if (tmp == NULL)
        goto free;

    lns = tmp;

free:
    free(buf);
close:
    close(fd);
out:
    return lns;
}

void freelines(char **lines)
{
    char **ln = lines;
    while (*ln != NULL)
        free(*ln++);
    free(lines);
}

static off_t getsize(int fd)
{
    int ret;
    struct stat sb;

    ret = fstat(fd, &sb);
    if (ret == -1)
        return -1;
    else
        return sb.st_size;
}

static char *getfile(int fd, off_t *size)
{
    ssize_t ret;
    char *tmp, *buf;

    buf = malloc(*size);
    if (buf == NULL)
        return NULL;

    ret = read(fd, buf, *size);
    if (ret != *size)
        goto fail;

    if (buf[*size - 1] != '\n') {
        tmp = realloc(buf, ++*size);
        if (tmp == NULL)
            goto fail;
        buf = tmp;
    }

    return buf;

fail:
    free(buf);
    return NULL;
}

static long countlines(char *buf, off_t size)
{
    long n = 0;
    char *cur = buf;

    #define REMAINING ((buf) + (size) - (cur))

    do {
        cur = memchr(cur, '\n', REMAINING);
        n++; cur++;
    } while (REMAINING > 0);

    #undef REMAINING

    return n;
}

static char *allocline(char *buf, off_t size, char **next)
{
    char *ln, *end;

    end = memchr(buf, '\n', size);
    if (end == NULL)
        return NULL; /* programmer error */

    #define LENGTH ((end) - (buf) + 1)

    ln = malloc(LENGTH + 1);
    if (ln == NULL)
        return NULL;
    ln[LENGTH] = 0;
    (void)memcpy(ln, buf, LENGTH);

    #undef LENGTH

    if (next != NULL)
        *next = end + 1;
    return ln;
}

static char **getlines(char *buf, off_t size)
{
    long i, n;
    char **lns;
    char *cur;

    n = countlines(buf, size);

    lns = calloc(n + 1, sizeof(char *));
    if (lns == NULL)
        return NULL;
    lns[n] = NULL;

    for (i = 0, cur = buf; i < n; i++) {
        lns[i] = allocline(cur, buf + size - cur, &cur);
        if (lns[i] == NULL)
            goto fail;
    }

    return lns;

fail:
    freelines(lns);
    return NULL;
}


texts: How to sort array by divisor sum faster?

texts:
I am sorting an array by divisor sum in ascending order. If two or more numbers have the same sum of divisors they have to be sorted in ascending order. The problem I have is that my version is not fast enough. Here is my code:

int divisorSum( double number )
{
    double sum = number + 1;
    for( int i = 2; i <= number / 2; i++ )
        if(( int )number % i == 0 )
            sum += i;
    return sum;
}
void sortByDivisorSum( double *array, int length )
{
    for( int i = 0; i < length; i++ )
    {
        for( int j = i + 1; j < length; j++ )
        {
            if(( divisorSum( array[ i ]) > divisorSum( array[ j ])) || (( divisorSum( array[ i ] ) == divisorSum( array[ j ])) && ( array[ i ] > array[ j ])))
            {
                array[ i ] += array[ j ];
                array[ j ] = array[ i ] - array[ j ];
                array[ i ] -= array[ j ];
            }
        }
    }
}
void readArrayy(double *array, int length)
{
    for(int index = 0; index < length; index++)
        scanf("%lf", &array[index]);
}
int main( void )
{
    int length, in;
    scanf( "%d", &length );
    double ar[ length ];
    readArrayy( ar, length );
    sortByDivisorSum( ar, length );
    for( in = 0; in < length; in++ )
    {
        printf( "%.0lf ", ar[in]);
    }
    return 0;
}

How to solve this in a faster way?

Input:

10
24 46 11 36 48 35 27 28 49 6

Output:

6 11 27 35 28 49 24 46 36 48


texts: The ListenHear Game - Listen and type the word

texts:
What it does:

Speak a random word chosen from an array and ask the user to type the word in the box for 15 seconds

If right, +1pts, reset the timer and go to next word.
If wrong: do nothing.
After 15 seconds: game over.

    body {background-color: black; color: white;}
    .center {
      width: 50%;
      height: 50%;
      position: absolute;
      top:0;
      bottom: 0;
      left: 0;
      right: 0;

      margin: auto;
    }
    .hidden {
      display: none;
    }

    The ListenHear
Game

<button class="w3-btn w3-green" onclick="play()">Play</button><button class="w3-btn w3-red" onclick="exit()">Exit</button>

<x class="w3-red">There was an error.</x>

For those who are complaining the code is broken, the SpeechSynthesisAPI (the code depends on) doesn't have good browser support.


texts:
I have a block of text where several arrays are printed out, with a name and values:

VAL1=10 20 30 40 50
VAL2=4 8 15 16 23 42

I have a function that looks for the value name, and sets an array of these values:
bool FetchValueArray(char* source, char* name, char* typeFormat, int count, void* destination, size_t destElementSize)
{
    int i;
    char *t;
    t=strstr(source,name);
    if (t)
        if (destination != NULL)
        {
            for (i = 0;i < count;i++)
                sscanf(t, typeFormat, (char*)destination + destElementSize * i);
            return true;
        }
    return false;
}

Called thus:
FetchValueArray(source, "VAL1=", "%d", 5, val1array, sizeof(val1array[0]);
FetchValueArray(source, "VAL2=", "%d", 6, val1array, sizeof(val1array[0]);

This is from a StackOverflow question. As the answerer wrote, it works, but it's not safe. If I call it with a count that is higher than the size of the array, I will corrupt the memory. I'm trying to wrap my head around this one and having a tough time. How can I have a function that will set values to a fixed array and be "safe"?


texts: Convert zip to gzip and upload to S3 bucket

texts:
My code accesses an FTP server, downloads a .zip file, pushes the file contents as .gz to an AWS S3 bucket.

import boto3
import ftplib
import gzip
import io
import zipfile

def _move_to_s3(fname):
    host = 'some_host'
    user = 'some_user'
    passwd = 'some_password'

    tmp_dir = '/tmp/'
    tmp_fname = fname.split('.')[0] + '.gz'

    target_bucket = 'some_bucket'
    s3 = boto3.resource('s3')

    try:
        ftp = ftplib.FTP(host, user, passwd)

        with io.BytesIO() as data, gzip.open(tmp_dir + tmp_fname, 'wb') as gz:
            ftp.retrbinary('RETR ' + fname, data.write)
            gz.write(data.getvalue())

        s3.Object(target_bucket, tmp_fname).put(Body=open(tmp_dir + tmp_fname, 'rb'))
    except Exception as e:
        print e
    finally:
        ftp.quit()

if __name__ == '__main__':
    _move_to_s3('some_file.zip')

I welcome any comments but my main points of interest are:

Assuming the source zip contains only one text file, is it OK to
write to the gzip file from a stream containing the contents of the
downloaded zip file?
I think I should change the code to hold the gzip in memory, without generating temporary files.


texts:
I've create a function that rewrites the key or "path" of an object in s3.

By default, Amazon Web Services Firehose writes to s3 in the format of YYYY/MM/DD/HH/foo.json. We have a AWS Lambda function listening for putObjects on l1/source/event_type/fh/, and when a new file is added to s3, the Lambda is invoked and the key or 'path' to that file is rewritten to a flat structure of l1/source/event_type/daily/dt=YYYY-MM-DD/foo.json - yes, I purposefully left-off the fh and HH paths.

input key: l1/source/event_type/fh/YYYY/MM/DD/HH/foo.json

output key: l1/source/event_type/daily/dt=YYYY-MM-DD/foo.json

def create_date_parition_from_key(key):
    '''creates new date parition prefix
    '''

    try:
        key_split = re.split(r'(/\d{4})', key)
        start_path = (key_split[0].split('/')[0], key_split[0].split('/')[1])
        remove_fh_path = '/'.join(start_path)
        default = key_split[2].split('/')
        year = key_split[1][1:]

        s3_prefix = remove_fh_path + '/'# /l1/foo/bar/baz/
        date_partion = ('daily/dt=' +
                        '-'.join([year, default[1], default[2]]) +
                        '/') # dt=YYYY-MM-DD/
        file_name = default[-1] # foo.json

        new_key = s3_prefix + date_partion + file_name

        print ('New partition key created: {}.'.format(new_key))

        return new_key
    except Exception as ex:
        print(ex)
        print('Error paritioning key {}.'.format(key))
        raise ex

I'm newer to python and am just looking for ways to improve my code as it seems fragile.

EDIT: The input key can vary in its number of paths:

l1/source/event_type/fh/YYYY/MM/DD/HH/foo.json
l1/app/source/event_type/fh/YYYY/MM/DD/HH/foo.json
l1/event_type/fh/YYYY/MM/DD/HH/foo.json


texts: Generate 2D array with set amount entries

texts:
I want to generate an array where each row and column needs to have a random generated amount (between 2 and total size of dimension -1) of true values.

Currently I am running each row then columns and check if it validates. If it does not it regenerates and has to do another full loop to check if all rows and columns validate.

/**
 * Procedurally populates 2D array so that each line and row contains between 1 and .Length true values.
 */
public static boolean[][] generateTargetNumbers(int width, int height) {

    boolean[][] targetNumbers = new boolean[width][height];

    // keep looping trough rows and columns to validate and regenerate if necessary
    boolean finished = false;
    while (!finished) {
        finished = true;

        // check columns
        for (int x = 0; x < width; x++) {
            if (generateTargetColumn(x, width, height, targetNumbers)) {
                finished = false;
            }
        }

        // check rows
        for (int y = 0; y < height; y++) {
            if (generateTargetRow(y, width, height, targetNumbers)) {
                finished = false;
            }
        }
    }
    return targetNumbers;
}

/**
 * Checks if the column has a valid amount of targets and regenerates the column if nececary.
 * @param x
 * @param width
 * @param height
 * @param targetNumbers
 * @return returns true if the column is regenerated.
 */
private static boolean generateTargetColumn(int x, int width, int height, boolean[][] targetNumbers) {
    int minTargetCount = 2;
    int maxTargetCount = height - 1;

    // count targets on this column
    int currentCount = 0;
    for (int y = 0; y < height; y++) {
        if (targetNumbers[x][y]) currentCount++;
    }

    if (currentCount >= minTargetCount && currentCount <= maxTargetCount) return false;

    // Column needs regenerating

    // Reset column to false
    for (int y = 0; y < height; y++) {
        targetNumbers[x][y] = false;
    }

    // Amount of targets for this column.
    int targetCount = Random.nextInt(maxTargetCount - minTargetCount + 1) + minTargetCount;

    while (targetCount > 0) {
        int index = Random.nextInt(height);
        if (!targetNumbers[x][index]) {
            targetNumbers[x][index] = true;
            targetCount--;
        }
    }

    return true;
}

/**
 * Checks if the row has a valid amount of targets and regenerates the column if nececary.
 * @param y
 * @param width
 * @param height
 * @param targetNumbers
 * @return returns true if the row is regenerated.
 */
private static boolean generateTargetRow(int y, int width, int height, boolean[][] targetNumbers) {
    int minTargetCount = 2;
    int maxTargetCount = height - 1;

    // count targets on this row
    int currentCount = 0;
    for (int x = 0; x < width; x++) {
        if (targetNumbers[x][y]) currentCount++;
    }

    if (currentCount >= minTargetCount && currentCount <= maxTargetCount) return false;

    // Row needs regenerating

    // Reset column to false
    for (int x = 0; x < width; x++) {
        targetNumbers[x][y] = false;
    }

    // Amount of targets for this row.
    int targetCount = Random.nextInt(maxTargetCount - minTargetCount + 1) + minTargetCount;

    while (targetCount > 0) {
        int index = Random.nextInt(height);
        if (!targetNumbers[index][y]) {
            targetNumbers[index][y] = true;
            targetCount--;
        }
    }

    return true;
}

For my needs (5x5 to 9x9 arrays) it usually does it in just 2 loops so that is great. But the randomness is biased to a larger amount of true values since it adds additional true values to the rows when it encounters a invalid column. I would like to have more control over the amount/percentage of true values.

Besides that, the near identical bottom 2 methods are tickling my OCD senses. I'm sure someone knows a nice way of combining these and make it look cleaner.