texts:
How can I decrease the time complexity and increase efficiency, without writing a new algorithm. My solution solves the majority of puzzles in a fast time, but for some difficult ones it can take over a minute! I have added some of the difficult puzzles below the code.
import numpy as np
from skimage.util import view_as_blocks  # pip install scikit-image

#input: 9x9 numpy array, empty cell = 0
#output: 9x9 numpy array: if not solution all array entries should be -1
#backtracking depth-first search with constraint propagation

#searches for 0 value in board
def zero_search(sudoku):
    for i in range(len(sudoku)):
        for j in range(len(sudoku[0])):
            if sudoku[i][j] == 0:
                return (i, j)  # row, col

    return False

#parameters: board, num = inserted value, pos = board position(vector/tuple)
def valid(sudoku, num, pos):
    # Check row
    for i in range(len(sudoku[0])):
        if sudoku[pos[0]][i] == num and pos[1] != i:
            return False

    # Check column
    for i in range(len(sudoku)):
        if sudoku[i][pos[1]] == num and pos[0] != i:
            return False

    # Check box
    box_x = pos[1] // 3
    box_y = pos[0] // 3

    #y-axis/columns
    for i in range(box_y*3, box_y*3 + 3):
        #x-axis/rows
        for j in range(box_x * 3, box_x*3 + 3):
            if sudoku[i][j] == num and (i,j) != pos:
                return False

    return True

def solver(sudoku):

    find = zero_search(sudoku)
    if not find:
        return True

    else:
        row, col = find

    #check insertion values 1-9
    for i in range(1,10):
        if valid(sudoku, i, (row, col)):
            sudoku[row][col] = i

            if solver(sudoku):
                return True

            sudoku[row][col] = 0

    return False

def initial_invalid(sudoku):

    # Check row
    for i in range(9):
        dup_lst=[]
        for j in range(9):
            if sudoku[j][i]!=0:
                if sudoku[j][i] in dup_lst:
                    return True

                else:
                    dup_lst.append(sudoku[j][i])

    #check column
    for i in range(9):
        dup_lst=[]
        for j in range(9):
            if sudoku[i][j]!=0:
                if sudoku[i][j] in dup_lst:
                    return True

                else:
                    dup_lst.append(sudoku[i][j])

#not needed
def final_valid (sudoku):

    subgrids = view_as_blocks(sudoku, (3, 3))

    sums = [np.sum(subgrids[i][j]) for j in range(3) for i in range(3)]
    if sum(sums) !=405:
        return False

    else:
        return True

    #row_sum = sudoku.sum(axis=1)
    #if sum(row_sum) != 405:
    #   return False

    #col_sum = sudoku.sum(axis=0)
    #if sum(col_sum) != 405:
    #    return False

def sudoku_solver(sudoku):

    if initial_invalid(sudoku):
        return np.full((9,9),-1)

    if solver(sudoku):
            return sudoku
    else:
        return np.full((9,9),-1)

[[0 8 0 4 3 0 0 0 0]
 [0 0 5 0 0 9 0 0 0]
 [6 0 0 0 8 0 0 7 0]
 [0 0 0 0 9 0 0 0 3]
 [0 0 0 8 0 7 0 0 0]
 [9 0 0 0 0 0 0 5 4]
 [0 6 0 0 0 0 0 0 5]
 [0 0 8 0 0 0 4 0 0]
 [0 4 0 0 0 6 0 1 0]]

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

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


texts:
Could you suggest ways of writing this code better?

bool success = true;

if(x == 0)
{
    if(do_up)
        run_do_up();
    else if(do_a)
        run_do_a();
    else if(do_n)
        run_do_n();
    else
        success = false;
}
else if(x == 1)
{
    if(do_n)
        run_do_n();
    else if(do_a)
        run_do_a();
    else
        success = false;
}
else//x == 2
{
    if(do_a)
        run_do_a();
    else if(do_n)
        run_do_n();
    else
        success = false;
}


texts: Fast insert, fast removal and fast access object pool C++ container

texts:
I just want to gather some feedback about this container, in my view it solves the problem of common data containers which don't have fast access and fast deletion. I want to admit that I have not benchmark this, as I don't understand how to do it and to compare with other containers. I tested it and it works, although it might not be the cleanest or safest code.

map<> has O(log(n)) for access and deletion

vector<> has O(n) for deletion

As you can see, with usual STL containers, you can't have O(1) performance and low memory footprint everywhere.

I heard about object pool some time ago, where instead of deleting objects, you reuse them, but the problem is that you have to resize the vector<>.

Then I've read a suggestion on IRC about swapping the tail of the vector with the item I want to delete. The problem is that the index of the last item is changing.

So I wrote this container with an index mapper.

The index is just two vector<int>, a forward and a backward map, with a queue<int> for available indexes.

The data is a vector<T>.

Each time an item is remove or added, the index is adjusted so that you can still access the item by the same index.

template <typename T>
struct managed_pool {
    queue<size_t> avail;
    vector<T> data;
    vector<int> index, back_index; // forward and backward index
    size_t add(T&&val) {

        // always add to tail since we "swap-pop":
        data.push_back(val);
        size_t data_index = data.size() - 1;
        size_t index_index;

        // if there's no available index
        if (avail.empty()) {
            // add a new index
            index.push_back(data_index);
            index_index = index.size()-1;
        }
        else {
            // reuse one
            index_index = avail.front();
            avail.pop();
        }
        back_index.push_back(index_index);
        index[index_index] = data_index;

        msgm(val, index_index);
        return index_index;
    }
    void rem(size_t translate_index_delete) {
        auto real_index_backup = data.size() - 1; // you want to keep this
        auto real_index_delete = index[translate_index_delete]; // you want to delete this
        auto translate_index_backup = back_index[real_index_backup];

        index[translate_index_delete] = -1; // invalidate
        avail.push(translate_index_delete);

        data[real_index_delete] = data[real_index_backup]; // here we "swap-pop". We move the .back() of the vector to the index of the item we want to remove. This ensures contiguity of the vector, at a minimal performance cost
        data.pop_back(); // remove it

        index[translate_index_backup] = real_index_delete; // we adjust the mapping table to make sure the item is still indexed at the same index.
    }
    T&operator[](size_t & i) {
        if(index[1] != -1)
        return data[index[i]];
    }
};

I just want to have your opinion if this is good, and if there are better methods than this. Remember that a heap is not what I want. I want the fastest container and keep a low memory footprint, be simple enough, have fast insertion, fast removal, and fast access. I'm not sure queue<> is a good choice.


texts: Fetch and append player statistics to an Excel spreadsheet

texts:
I am a new programmer in python, and I need a bit of help to structure my code.

game_schedule = (
    ('Daily Game Schedule', 'daily_game_schedule'),
    ('Full Game Schedule', 'full_game_schedule'),
)

team_standings = (
    ('Overall Team Standings', 'overall_team_standings'),
    ('Playoff Team Standings', 'playoff_team_standings'),
)

worksheets = (
    ('Game Schedule', game_schedule),
    ('Cumulative Player Stats', 'cumulative_player_stats'),
    ('Player Injuries', 'player_injuries'),
    ('Team Standings', team_standings),
)

def create_and_update_worksheets():
    """
    Add 'Player statistics' if the worksheet is not in file_name.
    Otherwise, it will update the worksheet itself.
    """

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    writer = pd.ExcelWriter(file_name, engine='openpyxl')

    for key, value in worksheets:
        start_row = 0
        if isinstance(value, tuple):
            for subkey, subvalue in value:
                response = send_request('2017-2018-regular', subvalue).content
                df1 = pd.DataFrame(['Title'])
                df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

                df1.to_excel(writer, key, startrow=start_row, header=None, \
                             index=False)
                df2.to_excel(writer, key, startrow=start_row+2, index=False)
                start_row += len(df2) + 4
        else:
            response = send_request('2017-2018-regular', value).content
            df1 = pd.DataFrame(['Title'])
            df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

            df1.to_excel(writer, key, startrow=start_row, header=None, \
                         index=False)
            df2.to_excel(writer, key, startrow=start_row+2, index=False)

    for sheet in writer.sheets.values():
        resize_columns(sheet)

    writer.save()
    writer.close()

create_and_update_worksheets()

I think there is repetitive code in the for loop for key, value in worksheets:. How can I change the structure so that it is not repetitive?


texts: UVA 10474 - "Where is the marble?" time limit

texts:
I have a problem from UVA online judge here. I have read it tons of times, and as they said, I have to get the answer really fast.

I have used a binary search and std::sort, but I am still having a time error. I don't know any faster way of searching on an array other than binary search.

Any feedback please?

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

int n,q,vec[100000];
int inicio,final,medio,busca;
int cont;
int busquedabinaria()
{

    //busqueda binaria
    std::sort(vec,vec+n);
    inicio=0;
    final=n-1;
    medio=(inicio+final)/2;

    while(inicio<=final)
    {
        if(vec[inicio]==busca)
            return inicio;
        if(vec[medio]==busca)
            return medio;
        if(vec[final]==busca)
            return final;
        medio = (inicio + final) / 2;
        if (vec[medio] > busca)
            final = medio - 1;
        else if (vec[medio] < busca)
            inicio = medio + 1;
        // found

    }
    return -1;

}

int main()
{

    freopen("in.txt", "rt",stdin);
    freopen("out.txt", "wt",stdout);

    while (scanf("%d %d\n",&n,&q)!=EOF && (n!=0 || q!=0)    )
    {
        for (int i=0;i<n;i++)
        {
            scanf("%d\n",&vec[i]);

        }
        printf("CASE# %d:\n",cont+1);
        cont++;
        while(q--)
        {

        scanf("%d\n",&busca);

            int res=busquedabinaria();
            if(res!=-1)
            {
                while (vec[res-1]==busca && res>0)
                {
                    res--;
                }
                printf("%d found at %d\n",busca,res+1);

        }
            else
                printf("%d not found\n",busca);

        }

    }

    return 0;
}


texts: Building and querying an immutable phone book

texts:
I wanted to get your opinion on this immutable implementation of a Phone Book using recursion to process a stream. I am especially interested in ways to speed up the code execution.

Here is an example of expected input:

8
add 811 Mom1
add 12376213 Mom2
add 1732239 Bob
find 76213
find 910
find 811
del 811
find 811

Now, here is the code

import scala.collection.immutable.HashMap

object phoneBook extends App {
override def main(args: Array[String]): Unit = {
  import scala.io.Source.fromInputStream
  import scala.annotation.tailrec

  val verbose = false

 lazy val rawLines = fromInputStream(System.in).getLines.toStream

val nQueries = (rawLines.head).head.toInt
if(verbose) println(nQueries)

   def parseLine(s:String):(Int,Array[String]) = {
      val a = s.split(" ")
     if(verbose) println(a.mkString(","))
      a(0) match {
        case "add" => {if(verbose) println(0); (0, a)}
        case "find" =>{if(verbose) println(1); (1, a)}
        case "del" => {if(verbose) println(2); (2, a)}
      }
   }
lazy val lines = (rawLines drop 1).map(parseLine)
  @tailrec  def doAction(stream:Stream[(Int,Array[String])],acc:HashMap[Int,String]=HashMap.empty[Int,String]):Unit = {

  if(stream.isEmpty) Unit
  else{
    val nextAction = stream.head
    val actionDetail = nextAction._2

    nextAction._1 match {
      case 0 => doAction(stream.tail,acc.+(actionDetail(1).toInt -> actionDetail(2)) )
      case 1 => {
        println(acc.getOrElse(actionDetail(1).toInt,f"not found"))
        doAction(stream.tail,acc)
         }
      case 2 =>     doAction(stream.tail,acc.-(actionDetail(1).toInt ) )
    }
  }

}

doAction(lines)

  }
}


texts: Asynchronous lookup over HTTP and checking the status

texts:
For some reason declaring ApiResult before checking if the answer is in a correct status doesn't look good. I wonder if there is any better way to check the status and return the result:

public async Task<ApiResult> GetCustomersByOutcode(string outcode)
{
    using (var client = new HttpClient())
    {
        ConfigureHttpClient(client);

        var response = await client.GetAsync(
            $"customer?q={WebUtility.UrlEncode(outcode)}");

        ApiResult result = null;
        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsAsync<ApiResult>();
        }
        return result;
    }
}


texts:
Here is my solution to a series of problems in JS fundamentals. I've made it pass but I know this could be more efficient. I'm not looking for anyone to rewrite the code, but just asking what methods should be used when writing similar code in the future.
The goal is basically to input two parameters, both have to be positive numbers and typeof numbers otherwise return ERROR. Also form an array that adds said two integers and all numbers between them. For example: if you enter 1,4 the answer would compute 1 + 2 + 3 + 4 = 10, and return 10.
const sumAll = function(lowEnd, highEnd) {
    let total = [];
    let sum = 0;
    let first = lowEnd;
    let second = highEnd;
    if (typeof first === 'number' && typeof second === 'number') {
        if (lowEnd >= 0 && highEnd >= 0) {
            if (lowEnd <= highEnd){
                for (let i = lowEnd; i <= highEnd; i++) {
                    total.push(i);
                }
            }
            else {
                for (let i = highEnd; i <= lowEnd; i++) {
                    total.push(i);
                }
            }
            for (let i = 0; i < total.length; i++) {
                sum += total[i];
            };
            return sum;
        }
        else if (lowEnd < 0 || highEnd < 0)
            return 'ERROR';
    }
    else {
        return 'ERROR';
    }
}

and here are the tests,
const sumAll = require('./sumAll')

describe('sumAll', function() {
  it('sums numbers within the range', function() {
    expect(sumAll(1, 4)).toEqual(10);
  });
  it('works with large numbers', function() {
    expect(sumAll(1, 4000)).toEqual(8002000);
  });
  it('works with larger number first', function() {
    expect(sumAll(123, 1)).toEqual(7626);
  });
  it('returns ERROR with negative numbers', function() {
    expect(sumAll(-10, 4)).toEqual('ERROR');
  });
  it('returns ERROR with non-number parameters', function() {
    expect(sumAll(10, "90")).toEqual('ERROR');
  });
  it('returns ERROR with non-number parameters', function() {
    expect(sumAll(10, [90, 1])).toEqual('ERROR');
  });
});


texts:
There are many instances of prime number sieve implementation both here and other places on the web, but I wanted something a little different.  In particular, I wanted to create a static array of the first 1024 prime numbers at compile time as a simple reusable structure.  I also wanted to allow for relatively simple creation of larger or smaller arrays.

I combined the code from this question with a little bit of macro magic from this other question to come up with code that meets my goal.

Questions:

I'd like to be able to use something more elegant than the stack of macros (templates perhaps), and would prefer to have the result be something more like an STL container than a raw array.  Comments on how to do those things, or comments generally to clean up the code would be welcome.

primeconsttest.cpp

#include "primeconst.h"
#include <vector>
#include <iterator>
#include <iostream>

int main() {
    std::vector<int> prime{std::begin(primes), std::end(primes)};
    for (unsigned i=0; i < prime.size(); ++i)
        std::cout << i << '\t' << prime[i] << '\n';
}

primeconst.h

extern const int primes[1024];

primeconst.cpp

constexpr bool isPrimeLoop(int i, int k) {
    return (k*k > i)?true:(i%k == 0)?false:isPrimeLoop(i, k + 1);
}

constexpr bool isPrime(int i) {
    return isPrimeLoop(i, 2);
}

constexpr int nextPrime(int k) {
    return isPrime(k)?k:nextPrime(k + 1);
}

constexpr int getPrimeLoop(int i, int k) {
    return (i == 0)?k:
        (i % 2)?getPrimeLoop(i-1, nextPrime(k + 1)):
        getPrimeLoop(i/2, getPrimeLoop(i/2, k));
}

constexpr int getPrime(int i) {
    return getPrimeLoop(i, 2);
}

static_assert(getPrime(511) == 3671, "computed incorrectly");

#define K(x) J(x) J(x + 512)
#define J(x) I(x) I(x + 256)
#define I(x) H(x) H(x + 128)
#define H(x) G(x) G(x +  64)
#define G(x) F(x) F(x +  32)
#define F(x) E(x) E(x +  16)
#define E(x) D(x) D(x +   8)
#define D(x) C(x) C(x +   4)
#define C(x) B(x) B(x +   2)
#define B(x) A(x) A(x +   1)
#define A(x) getPrime(x) ,

extern constexpr int primes[] = { K(0) };

Output

0   2
1   3
2   5
3   7
4   11
5   13
6   17

...

1017    8093
1018    8101
1019    8111
1020    8117
1021    8123
1022    8147
1023    8161


texts: Finding the number of permutations of an integer array with equaling difference (not in order)

texts:
The array size is <= 16. The difference is defined as:

diff[i] = array[i+1] - array[i];

I need to find the number of permutations of the original array, which have a difference that is a permutation of the difference of the original array.

This is my code:

public class Main {
    Scanner scan = new Scanner(System.in);
    int N;
    int [] array_base;
    int [] first_diff;
    int result;

    public static void main(String[] args) {
        Main main = new Main();
        main.read();
        main.run();
    }

    void read() {
        N = scan.nextInt();
        array_base = new int [N];
        for (int i = 0; i<N; i++) {
            array_base[i] = scan.nextInt();
        }
        first_diff = first_difference();
    }

    int [] first_difference() {
        int [] temp = new int [N-1];
        for (int i=0; i < N-1; i++) {
            temp[i] = array_base[i+1] - array_base[i];
        }
        return temp;
    }

    void run() {
        permute(array_base,0);
        System.out.println(Integer.toString(result));
    }

    public void permute(int[] array, int k)
    {
        for(int i=k; i<array.length; i++)
        {
            int temp;
            temp = array[i];
            array[i] = array[k];
            array[k] = temp;
            permute(array, k+1);
            int temp2;
            temp2 = array[i];
            array[i] = array[k];
            array[k] = temp2;
        }
        if (k == array.length-1)
        {
            calculate(array);
        }
    }

    void calculate(int [] array) {
        int [] diff_values = new int [array.length-1];
        for (int i = 0; i < array.length-1; i++) {
            diff_values[i] = array[i+1] - array[i];
        }
        compare(diff_values);
    }

    void compare(int [] values) {
        boolean [] used_new = new boolean [values.length];
        boolean [] used_first = new boolean [values.length];
        for (int i = 0; i < values.length; i++) {
            used_new[i] = false;
            used_first[i] = false;
        }
        for (int i = 0; i < values.length; i++) {
            for (int j = 0; j < values.length; j++) {
                if (used_new[j]) {
                }
                else if (first_diff[i] == values[j]) {
                        used_new[j] = true;
                        used_first[i] = true;
                        break;
                }
            }
            if (used_first[i] == false) break;
        }
        if (areAllTrue(used_new) && areAllTrue(used_first)) {
            result += 1;
        }
    }

    public boolean areAllTrue(boolean[] array)
    {
        for(boolean b : array) if(!b) return false;
        return true;
    }

}

I do, however, see that this code is not fast as it could be. Could anyone give me some advice on how to speed it up?


texts: Return union and complement of three sets

texts:
I would be especially happy to hear opinions about complement_union.
The rest of the code is just there to test the output.

program test_complement_union
    implicit none(type, external)

    call assert(all([3, 5] == complement_union([1, 2, 3], [1, 2], [5])))
    call assert(all([2, 3, 4] == complement_union([1, 2, 3], [1], [4])))
    call assert(all([1, 3, 5] == complement_union([1, 2, 3], [2], [5])))
contains
    !> Merge C into A and remove values that are in B.
    !> The result can be written with set notation as A ∪ C / B.
    !> Preconditions (not tested!):
    !>      1. B is a subset of A
    !>      2. A and C are disjoint
    !>      3. B and C are disjoint
    !>      4. A, B, and C are sorted.
    pure function complement_union(A, B, C) result(D)
        integer, intent(in) :: A(:), B(:), C(:)
        integer :: D(size(A) + size(C) - size(B))

        ! We will index as A(i), B(j), C(k), D(l)
        integer :: i, j, k, l

        i = 1
        j = 1
        k = 1
        l = 1
        do while(l <= size(D))
            ! Only indices from C have to be added to A
            ! We use assumption that B is a subset of A
            if (i > size(A)) then
                D(l) = C(k)
                k = k + 1
                l = l + 1
            ! Neither indices from B have to be deleted in A
            ! nor indices from C have to be added from C to A.
            else if (j > size(B) .and. k > size(C)) then
                D(l) = A(i)
                i = i + 1
                l = l + 1
            ! No more indices from B have to be deleted in A
            else if (j > size(B)) then
                if (A(i) < C(k)) then
                    D(l) = A(i)
                    i = i + 1
                    l = l + 1
                else if (A(i) > C(k)) then
                    D(l) = C(k)
                    k = k + 1
                    l = l + 1
                end if
            ! No more indices have to be added from C to A
            else if (k > size(C)) then
                if (A(i) /= B(j)) then
                    D(l) = A(i)
                    i = i + 1
                    l = l + 1
                else
                    i = i + 1
                    j = j + 1
                end if
            ! Normal case:
            ! Merge C sorted into A excluding values from B.
            else if (A(i) < C(k)) then
                if (A(i) /= B(j)) then
                    D(l) = A(i)
                    i = i + 1
                    l = l + 1
                else
                    i = i + 1
                    j = j + 1
                end if
            else if (A(i) > C(k)) then
                if (A(i) /= B(j)) then
                    D(l) = C(k)
                    k = k + 1
                    l = l + 1
                else
                    D(l) = C(k)
                    i = i + 1
                    j = j + 1
                    k = k + 1
                    l = l + 1
                end if
            end if
        end do
    end function

    pure subroutine assert(cond)
        logical, intent(in) :: cond
        if (.not. cond) error stop
    end subroutine
end program
```


texts: Picking a random point along the edge of an area

texts:
I'm writing a Diffusion-limited aggregation simulation, and need to pick a random point along the edge of an area defined by a dimension pair of [width, height]. The point shouldn't be deep within the area; it should always be on the border of one of the sides. This is the intended behavior:

(let [rand-gen (Random.)
      dims [21 11]]

  (dotimes [_ 25]
    ; I'm casting to int so the output is legible
    ;  I actually need doubles
    (println
      (mapv int (random-edge-coord dims rand-gen)))))

[13 0]
[0 8]
[15 10]
[8 10]
[20 0]
[0 6]
[20 2]
[0 5]
[7 10]
[0 7]
[0 10]
[20 1]
[6 0]
[20 0]
[0 2]
[20 10]
[15 0]
[14 0]
[7 0]
[0 7]
[12 0]
[20 7]
[20 4]
[20 8]
[20 4]

This is the mess I came up with:

; These two functions are just for the sake of a MCVE
(defn- random-boolean [^Random rand-gen]
  (.nextBoolean rand-gen))

(defn- random-double [min, max, ^Random rand-gen]
  (let [r (.nextDouble rand-gen)
        spread (- max min)
        rand (* spread r)]
    (+ rand min)))

(defn random-edge-coord [dimensions, ^Random rand-gen]
  (let [[w h] dimensions
        vertical? (random-boolean rand-gen)
        start? (random-boolean rand-gen)

        x (if vertical?
            ; Pick either the left or right edge
            (if start?
              0
              (dec w))

            ; Else, pick a random point along the top/bottom egde
            (random-double 0 w rand-gen))

        y (if vertical?
            (random-double 0 h rand-gen)

            (if start?
              0
              (dec h)))]

    [x y]))

The redundancy is killing me though. I can't think of how to clean it up. I feel like this should be fairly straightforward to generalize, but I'm stuck. I figured I could clean it up introducing some anonymous functions:

(defn random-edge-coord [dimensions rand-gen]
  (let [[w h] dimensions
        vertical? (g/random-boolean rand-gen)
        start? (g/random-boolean rand-gen)

        edge #(if start? 0 (dec %))
        rand-edge #(g/random-double 0 % rand-gen)

        x (if vertical?
            (edge w)
            (rand-edge w))

        y (if vertical?
            (rand-edge h)
            (edge h))]

    [x y]))

But that's not a huge gain.

Any input here would be appreciated.


texts: count all array[index] == index occurrences

texts:
The method foo gets a sorted list with different numbers as a parameter and returns the count of all the occurrences such that: i == list[i] (where i is the index 0 <= i <= len(list)).

def foo_helper(lst, start, end):

    if start > end:
        # end of recursion
        return 0

    if lst[end] < end or lst[start] > start:
        # no point checking this part of the list
        return 0

    # all indexes must be equal to their values
    if abs(end - start) == lst[end] - lst[start]:
        return end - start + 1

    middle = (end + start) // 2

    print(lst[start:end+1], start, middle, end)

    if lst[middle] == middle:
        #print("lst[" , middle , "]=", lst[middle])
        return 1 + foo_helper(lst, middle+1, end) + \
    foo_helper(lst, start, middle-1)

    elif lst[middle] < middle:
        return foo_helper(lst, middle+1, end)
    else:
        return foo_helper(lst, start, middle-1)

def foo(lst):
    return foo_helper(lst, 0, len(lst)-1)

My question is: is this code's worst-case complexity log(n)?  If not, what should I do differently?


texts: Check equality of an objects array property and a nested object property

texts:
On my app I'm checking the equality between an objects array property and a nested object property - based on the results I return a new objects array.
The items objects array:
[{name: 'test', value: 1, category: 'a'},{name: 'test2', value: 2, category: 'b'},{name: 'test3', value: 3, category: 'c'}]

The itemList object:
{testnum1: {name: 'test123', category: 'a'}, testnum2: {name: 'test234', category: 'b'}

I need to check the equality between the category properties and return the following objects array:
[{name: 'test', itemCategory: 'testnum1'},{name: 'test2', itemCategory: 'testnum2'}]

This is what I did, any idea on how to make it more readable?
const getCategorizedItems = items => {
  const itemListCategories = Object.keys(itemList)
  const categorizedItems= items.map(item=> {
    const itemCategory = itemListCategories.find(category =>
      item.category === itemList[category].category
    )
    if (itemCategory ) return {name: item.name, category: itemCategory }
  })
  .filter(f => f)
  return categorizedItems
}


texts: Extension method to retrieve a sample from a collection

texts:
I wrote a little extension method to retrieve a random sample of items from a collection. I've tried to write clean code. What do you think?

is it clean?
does it work as you would expect?

I'll be glad to hear your comments.

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

namespace Extensions
{
    public static class IEnumerableExtensions
    {
        private static Random _rnd = new Random();

        public static T Sample<T>(this IEnumerable<T> values)
        {
            return Sample(values, 1).First();
        }

        public static IEnumerable<T> Sample<T>(this IEnumerable<T> values, int size)
        {
            if(!values.Any())
            {
                throw new InvalidOperationException("Collection empty.");
            }

            if (size < 1)
            {
                return new List<T>();
            }

            if (size >= values.Count())
            {
                return values;
            }

            return GetSamples(values, size);
        }
        private static IEnumerable<T> GetSamples<T>(IEnumerable<T> values, int size)
        {
            var samples = new List<T>();
            var source = new List<T>(values);
            while (samples.Count != size)
            {
                var index = _rnd.Next(source.Count());
                var value = source[index];
                samples.Add(value);
                source.Remove(value);
            }
            return samples;
        }
    }
}


texts:
I have a vector of points that form blobs inside a 2d region. This 2d region represents an image. I need to find the center point of the largest blob very quickly. My algorithm that I use takes ~1 minute for a 50x50 image and it took so long that I canceled it for a 2560x1440 image. I want to be able to calculate a 2560x1440 image in just a couple seconds. Is this possible? I don't mind if the center is just an approximation. It doesn't have to be exact.

Here is an image I created from the points:

The white points are the ones that I am interested in. I need the center of the largest blob. The points that are identified could look wildly different, so take this image with a grain of salt.

I took the code from here and adapted it for my purpose. The point.h file contains an iteration value. I create a 2d array where every point outside the blobs has an iteration value of -1 and the rest have a value greater than or equal to 0 and passed that into the method.

Point.h

class Point
{
private:
    int x, y, iteration;
public:
    Point(int Xin, int Yin) : x(Xin), y(Yin), iteration(-1) {}
    Point(int Xin, int Yin, int Iterationin) : x(Xin), y(Yin), iteration(Iterationin) {}
    int getX() { return x; };
    int getY() { return y; };
    int getIteration() { return iteration; };
};

Center Point

int calculateFramePerturbation2::fill(vector<vector<int>> arr, int r, int c, vector<Point>& points) {
    int count = 0;
    if (r < arr.size() && arr[r][c] >= 0) {
        for (int i = c; i >= 0 && arr[r][i] >= 0; i--) {
            Point pt(r, i, arr[r][i]);
            points.push_back(pt);

            arr[r][i] = -1;
            count += fill(arr, r + 1, i, points) + 1;
        }
        for (int i = c + 1; i < arr[r].size() && arr[r][i] >= 0; i++) {
            Point pt(r, i, arr[r][i]);
            points.push_back(pt);

            arr[r][i] = -1;
            count += fill(arr, r + 1, i, points) + 1;
        }
    }
    return count;
}

Point calculateFramePerturbation2::print_components(vector<vector<int>> arr) {
    vector<int> pointAreas;
    vector<vector<Point>> allPoints;

    for (int r = 0; r < arr.size(); ++r) {
        for (int c = 0; c < arr[r].size(); ++c) {
            if (arr[r][c] >= 0) {
                vector<Point> points;

                fill(arr, r, c, points);
                //cout << fill(arr, r, c, points) << " ";
                //cout << points.size() << endl;
                allPoints.push_back(points);
                pointAreas.push_back(points.size());
            }
        }
    }

    //Identify the blob with the highest area.
    int max = -1;
    int index2 = 0;
    for (int i = 0; i < pointAreas.size(); i++) {
        if (pointAreas[i] > max) {
            max = pointAreas[i];
            index2 = i;
        }
    }

    cout << endl;
    cout << max << " " << index2 << endl;

    //Find the center point
    int totalX = 0;
    int totalY = 0;
    for (int i = 0; i < allPoints[index2].size(); i++) {
        totalX += allPoints[index2][i].getX();
        totalY += allPoints[index2][i].getY();
    }

    Point finalPoint(totalX / allPoints[index2].size(), totalY / allPoints[index2].size(), -1);
    return finalPoint;
}
void run(vector<Point> pointsRemaining) {
    //I'd prefer a solution where I could just take the points remaining array (it defines the blobs instead of converting it into a 2d array.

    vector<vector<int>> glitch2DArray;

    glitch2DArray.resize(WIDTH, vector<int>(HEIGHT, -1));
    for (int i = 0; i < pointsRemaining.size(); i++) {
        glitch2DArray[pointsRemaining[i].getX()][pointsRemaining[i].getY()] = pointsRemaining[i].getIteration();
    }

    Point finalPoint = print_components(glitch2DArray);
}


texts: find if one string is a valid anagram of another , in scala

texts:
Question is taken from leet code.

Problem

Given two strings s and t , write a function to determine if t is an anagram of s.

Examples

Input: s = "anagram", t = "nagaram"
Output: true

Input: s = "rat", t = "car"
Output: false

Here is my implementation in scala

import scala.collection.immutable.HashMap

object ValidAnagram extends App {
  def validAnagram(s1: String, s2: String): Boolean = {
    if (s1 == s2) true
    else if (s1.length != s2.length) false
    else {
      val lookupTable = s1.foldLeft(HashMap[Char,Int]()) ((m,c) => m ++ HashMap(c -> (if (m contains c) m(c) + 1 else 1)))
      println(lookupTable)
      (s2.foldLeft(lookupTable) {(m,c) =>
        if (m contains c) {
          val count = m(c)
          if (count > 1) {m + (c -> (count-1))} else m - c
        } else m  // we can return here if not functional
      }).isEmpty
    }
  }
    println(validAnagram(args(0), args(1)))
  }


texts: Validate User By Comparing against SQL Data

texts:
I'm currently building a Windows Form Application using Visual Studio 2015 and the Visual Basic.NET programming language.

On the main form there is a Tab Control and an ActiveX PDf viewer control. The Tab Control has 4 tabs they are labled "Find", "ECO View", "ECO Edit" & "User Admin". ECO = Engineering Change Order

Tab "Find" uses a List Box and a Textbox. This tab is used to search thru a directory and open a component or assembly drawing from a directory location on one of our file servers.

Tab "ECO View" has many labels that display text. The USer can search for an ECO Number and view the information thru all the labels which get its information from a MS SQL database 2012.

Tab ECO Edit has Textboxes, Labels, Comboboxes and buttons. The purpose of the ECO Edit tab is for creating and updating ECO data.

Tab "User Admin" has a Data Grid View, TextBox and button controls. This tab is used to add and remove Admin Users.

The end users of this application are split into two catagories Standard and Admin. The way I have the application coded is that if your not in the admin list you are a standard user. Standard users have only two tabs visible to them, the "Find" & "ECO View" tabs. The other two are invisible. Most end users are only going to use the view portion of the application. The admins are the engineers who maintain all the drawings and ECO's that others view.

Originally I verified users with this code:

Private Sub AdminOnly()
    Dim this_username As String
    lblCurUseName.Text = _UserName
    this_username = _UserName
    Select Case this_username
        Case "SteveW", "miked", "harryg", "JimV"
            lblAccessLvl.Text = "Admin"
            tcOAP.TabPages.Remove(tpECOedit)
            tcOAP.TabPages.Remove(tpUserAdmin)
            tcOAP.TabPages.Add(tpECOedit)
            tcOAP.TabPages.Add(tpUserAdmin)
            Exit Sub
        Case Else
            lblAccessLvl.Text = "User Only"
            tcOAP.TabPages.Remove(tpECOedit)
            tcOAP.TabPages.Remove(tpUserAdmin)
            tsmiArchive.Enabled = False
            tsmiFolders.Enabled = False
    End Select
 End Sub

But then I realized I would need to recompile the project everytime I add or remove a new user So I created the "User Admin" Tab to add and remove the users. this data is stored in a MS SQL database.

My question is: How do I approach the code in order to pull the admins from the sql database and impliment the code I have above?

Using windows authentication is not an option so I will not discuss using that as an alternative.

Here are the add user button click event code and the remove user button click event code.

Private Sub btnAddUserUA_Click(sender As Object, e As EventArgs) Handles btnAddUserUA.Click
    Dim Sqlstr As String = "INSERT INTO dbo.tblUserAdmin(UserName, ClockNo) VALUES (@UserName, @ClockNo)"
    Dim cn As New SqlConnection()
    cn = DBConnect()
    cn.Open()
    Dim cmdInsert As New SqlCommand(Sqlstr, cn)
    cmdInsert.Parameters.Add("@UserName", Data.SqlDbType.NVarChar).Value = txtUserNameUA.Text()
    cmdInsert.Parameters.Add("@ClockNo", Data.SqlDbType.NVarChar).Value = txtClockNoUA.Text
    cmdInsert.ExecuteNonQuery()
    cn.Close()
    TblUserAdminBindingSource.DataSource = TblUserAdminTableAdapter.GetData()
    TblUserAdminBindingSource.ResetBindings(False)
    txtUserNameUA.Text = Nothing
    txtClockNoUA.Text = Nothing
End Sub

Private Sub btnRemUserUA_Click(sender As Object, e As EventArgs) Handles btnRemUserUA.Click
    Dim cn As New SqlConnection()
    cn = DBConnect()
    cn.Open()
    Dim cmd As New SqlCommand()
    cmd.Connection = cn
    cmd.CommandText = "DELETE FROM dbo.tblUserAdmin where Id='" & dgvUA.CurrentRow.Cells(0).Value & "'"
    cmd.ExecuteNonQuery()
    cn.Close()
    dgvUA.Rows.Remove(dgvUA.CurrentRow)
End Sub

Any help on this would be greatly appreciated.


texts: Implementation of the FNV-1a hash algorithm for 32- and 64-bit

texts:
Are there any improvements to these two classes which implement FNV-1a for hashing? Particularly, I'm looking for any reuse opportunities (possibly via a common abstract superclass derived from HashAlgorithm?).

GitHub

public sealed class Fnv1a32 : HashAlgorithm
{
    private const uint FnvPrime = unchecked(16777619);

    private const uint FnvOffsetBasis = unchecked(2166136261);

    private uint hash;

    public Fnv1a32()
    {
        this.Reset();
    }

    public override void Initialize()
    {
        this.Reset();
    }

    protected override void HashCore(byte[] array, int ibStart, int cbSize)
    {
        for (var i = ibStart; i < cbSize; i++)
        {
            unchecked
            {
                this.hash ^= array[i];
                this.hash *= FnvPrime;
            }
        }
    }

    protected override byte[] HashFinal()
    {
        return BitConverter.GetBytes(this.hash);
    }

    private void Reset()
    {
        this.hash = FnvOffsetBasis;
    }
}

and

public sealed class Fnv1a64 : HashAlgorithm
{
    private const ulong FnvPrime = unchecked(1099511628211);

    private const ulong FnvOffsetBasis = unchecked(14695981039346656037);

    private ulong hash;

    public Fnv1a64()
    {
        this.Reset();
    }

    public override void Initialize()
    {
        this.Reset();
    }

    protected override void HashCore(byte[] array, int ibStart, int cbSize)
    {
        for (var i = ibStart; i < cbSize; i++)
        {
            unchecked
            {
                this.hash ^= array[i];
                this.hash *= FnvPrime;
            }
        }
    }

    protected override byte[] HashFinal()
    {
        return BitConverter.GetBytes(this.hash);
    }

    private void Reset()
    {
        this.hash = FnvOffsetBasis;
    }
}


texts: Basic/beginner interactive program in Python

texts:
I bring this code review plea over from suggestions from SO. I've made the suggested edits from that thread, except I kept one sys.exit() call because I was having trouble exiting otherwise. Overall, the code works as desired, and I'm looking for advice on how I can make it even cleaner.

import time
import sys

done = "I'm tired of you. Goodbye."
rainedOut = "Sorry, rain foiled your plans :("
dontUnderstand = "I'm sorry, I don't understand."

def good_weather():
    """Imagine a world where every 5 seconds it rains (good_weather = False),
    then is sunny again (good_weather = True). This function should return
    whether good_weather is True or False at the time it's called.
    """
    return (time.time() % 10) <= 5

def start():
    entries = 0

    while entries < 4:
        choice = raw_input("Hello! What do you want to do right now? Options: 1) Sleep, 2) Work, 3) Enjoy the great outdoors: ")

        if choice == "1":
            print "We are such stuff as dreams are made on, and our little life is rounded with a sleep. - Shakespeare, The Tempest"
        elif choice == "2":
            work()
        elif choice == "3":
            outdoors()
        else:
            print dontUnderstand
            entries += 1
    print done

def work():
    entries = 0
    entries2 = 0

    while entries < 4:
        choice = raw_input("Would you prefer sedentary office work or manual labor in the elements?: ")

        if "office" in choice:
            print "The brain is a wonderful organ; it starts working the moment you get up in the morning and does not stop until you get into the office. -Robert Frost"
            start()
        elif "manual" in choice:
            sunny = good_weather()
            if sunny == True:
                print "A hand that's dirty with honest labor is fit to shake with any neighbor. -Proverb"
                start()
            else:
                if entries2 < 3:
                    print rainedOut
                    entries2 += 1
                    continue #restart loop
                else:
                    print "You should probably just give up now."
                    start()
        else:
            print dontUnderstand
            entries += 1
    print done
    sys.exit()

def outdoors():
    sunny = good_weather()
    if sunny == True:
        print "Adopt the pose of nature; her secret is patience. -Ralph Waldo Emerson"
        start()
    else:
        print rainedOut
        start()

start()


texts: Filter out unwanted substrings while generating all possible relevant substrings

texts:
Write a Program that determines where to add periods to a decimal string so that
  the resulting string is a valid IP address. There may be more than one valid IP address
  corresponding to a string, in which case you should print all possibilities. For example, if the mangled string is "19216811" then some of the corresponding IP addresses are 192.168.1.1 and 19.216.81.1

Elements of Programming Interviews Section 6.9 See Bottom of Page 82, asks the following as a variant to the above problem:

Now suppose we need to solve the analogous problem when the number of periods is a parameter k and the
string length s is unbounded.

See attempt below, I am generating all permutations, see permute(s), of the string and then filtering later hence I end up doing unnecessary work. Can I do better?

def period_partition(s, k):
    slen = len(s)

    def is_valid_octet(s):
        # section ranges 0 - 255 and `00` or `000`, `01` are not valid but 0 is
        return slen == 1 or (s[0] != "0" and 0 <= int(s) <= 255)

    def permute(s):
        if len(s) > 0:
            for i in range(1, slen + 1):
                first, rest = s[:i], s[i:]
                for p in permute(rest):
                    yield [first] + p
        else:
            yield []

    results = set()

    for s in filter(
        lambda x: len(x) == k + 1 and all(is_valid_octet(i) for i in x), permute(s),
    ):
        results.add(".".join(s))

    return list(results)

if __name__ == "__main__":
    for args in [
        ("", 1),
        ("1234", 2),
        ("19216811", 3),
        ("192168111234", 3),
        ("192168111234", 4),
    ]:
        print(period_partition(*args))
        print()

Output:

[]

['1.23.4', '12.3.4', '1.2.34']

['1.92.168.11', '192.16.81.1', '19.216.81.1', '192.1.68.11', '192.16.8.11', '19.216.8.11', '19.2.168.11', '19.21.68.11', '192.168.1.1']

['192.168.111.234']

['192.16.81.11.234', '19.21.68.111.234', '19.2.168.111.234', '192.168.1.112.34', '192.168.11.12.34', '192.168.11.1.234', '192.168.111.23.4', '192.168.1.11.234', '192.1.68.111.234', '192.168.111.2.34', '19.216.81.112.34', '192.16.81.112.34', '19.216.81.11.234', '192.168.11.123.4', '192.16.8.111.234', '19.216.8.111.234', '1.92.168.111.234']

NB:
This is just a toy problem and its connection to valid IP addresses, IPv4 and IPv6, I think, is just to provide constraints on valid octets as periods are assigned. So 1.23.4 is an unbounded string s, "1234", after being partitioned with periods k=2


texts:
This is the batch file i have created which copy the specific folders which I want. I use the specific server folder name of which I want to copy. Please suggest any improvements.

@echo off
:: variables
echo This script takes the backup of file SwiftALM Important folders
set /P source=Enter source folder Example D:\jboss6.1\server\swift:
set /P destination=Enter Destination folder:
set /P Folder=Enter Folder name:
@echo folder=%folder%
mkdir %destination%\%folder%
set xcopy=xcopy /E/V/Q/F/H/I
echo echo conf folder will be copied
%xcopy% %source%\conf %destination%\%folder%\conf
echo conf folder is copied
echo lib folder will be copied
%xcopy% %source%\lib %destination%\%folder%\lib
echo lib folder is copied
echo deploy folder will be copied
%xcopy% %source%\deploy %destination%\%folder%\deploy
echo deploy folder is copied
echo deployers folder will be copied
%xcopy% %source%\deployers %destination%\%folder%\deployers
echo deplyers folder is copied
echo files will be copy press enter to proceed
pause


texts: Implementing the "Thinking in React" example from React documentation without using Refs

texts:
I'm quite new to React and was working through the "Thinking in React" example,
I noticed they used refs for updating state, but I also read on SO that using refs isn't that good in the long run, so I tried to redo this without using refs:

JSFiddle

var SearchBar = React.createClass({
    handleChange: function(event) {
        if (event.target.type ==='text') {
            this.props.onUserInput(
                event.target.value,
                this.props.inStockOnly
            );
        } else {
            this.props.onUserInput(
                this.props.filterText,
                event.target.checked
            );
        }
    },

    render: function() {
        return (
            <form>
                <input
                    type="text"
                    placeholder="Search..."
                    value={this.props.filterText}
                    onChange={this.handleChange}
                />
                <p>
                    <input
                        type="checkbox"
                        checked={this.props.inStockOnly}
                        onChange={this.handleChange}
                    />
                    {' '}
                    Only show products in stock
                </p>
            </form>
        );
    }
});

It works but it seems repetitive, how would someone comfortable with React do this without refs?


texts:
import random, os

HIGHSCORE_DATA = []
NUM_DIGITS = 1
MAX_GUESS = 10

if os.path.isfile('./highscore.txt'):
    f = open("highscore.txt", "r")
    highscore_data = f.readline().split(',')
    HIGHSCORE_DATA = highscore_data[0], highscore_data[1]

def increment_difficulty(difficulty = 1):
    global NUM_DIGITS
    NUM_DIGITS += difficulty

def get_secret_num():
    numbers = list(range(10))
    random.shuffle(numbers)
    secretNum = ''
    for i in range(NUM_DIGITS):
        secretNum += str(numbers[i])
    return secretNum

def get_clues(guess, secretNum):
    global NUM_DIGITS
    if len(guess) > NUM_DIGITS:
        return 'ERROR_LENGTH_TOO_LONG'

    if guess == secretNum:
        increment_difficulty()
        return 'You got it!'

    clues = []
    for i in range(len(guess)):
        if guess[i] == secretNum[i]:
            clues.append('Fermi')
        elif guess[i] in secretNum:
            clues.append('pico')
    if len(clues) == 0:
        return 'Bagels'

    clues.sort()
    return ' ' . join(clues)

def is_only_digits(num):
    # Returns True if num is a string of only digits. Otherwise, returns False
    if num == '':
        return False

        for i in num:
            if i not in '0 1 2 3 4 5 6 7 8 9'.split():
                return False

        return True

def disp_intro():
    global HIGHSCORE
    print('[Highscore] Name: {name} | Level: {level}\n'.format(name=HIGHSCORE_DATA[0], level=HIGHSCORE_DATA[1]));
    print('I am thinking of a of a %s-digit number. Try to guess what ' % (NUM_DIGITS))
    print('The clues I give are . . .')
    print('When I say:    That means: ')
    print('Bagels         None of the digits is correct.')
    print('Pico        One digit is correct but in the wrong position.')
    print('Fermi          One digit is correct and in the right position.')

while True:
    NUM_DIGITS = 1
    num_guesses = 1
    while num_guesses <= MAX_GUESS:
        secret_num = get_secret_num()

        # Debugging Purposes - print(secret_num)

        print('I have thought up a number. You have %s guesses to get it.' % (MAX_GUESS))
        guess = ''
        disp_intro()

        while len(guess) != NUM_DIGITS or not is_only_digits(guess):
            print("Guess #%s: " % (num_guesses))
            guess = input()

            clue = get_clues(guess, secret_num)
            print(clue)
            if clue == 'You got it!':
                num_guesses = 1;
                print("============================\n")
                break;
            elif clue == 'ERROR_LENGTH_TOO_LONG':
                num_guesses -= 1

            num_guesses += 1

            #if guess == secret_num:
            #    break;
            if num_guesses > MAX_GUESS:
                print('You ran out of guesses. The answer was %s.' % (secret_num))
                print("Please enter your name (FOR HIGHSCORE): ")
                highscore_name = input()

                f = open('./highscore.txt', 'w')
                f.write(highscore_name + "," + str(NUM_DIGITS))
                f.close()
                break;

    print('Do you want to play again? (yes or no)')
    if not input().lower().startswith('y'):
        break

As the disp_intro says. It will give clues depending on the input given.

  Bagels - None of the digits is correct.
  Pico - One digit is correct but in the wrong position.
  Fermi - One digit is correct and in the right position.

So, basically I just want to see the most concise way this can be written as I'm pretty sure most of the code I wrote is redundant and can be improved by a lot.

Features

[X] Generates random SECRET_NUM to guess.
[X] Shows current High Score.
[X] Read/Writes the High Score file.
[X] If length is too long: Do not count tries, and ask again.
[X] If it's not a number: Do not count tries, and ask again.
[X] If guess >=  MAX_GUESS: Ask for player's name, and then ask to terminate.

There might be more, but I think those are the most important ones.


texts:
The below script is one I made to check the disk space on mounted partitions under Debian Wheezy. I tried adding a -d switch to force printing out the used data, but its main purpose is to run as a cron job, and email the administrator if any disks are below a certain threshold.

What I'm looking for is to make sure it's POSIX compliant (in case it needs to be called by another script/application), and that it's rock solid. It works on my servers as is, with and without the -d. It requires that if an argument is given, it's a mount point. I am trying to get the proper coding practices done properly, as well.

#!/bin/sh

MOUNTPOINTS="/ /var /home" #The mount points to always check; the user can
                           #specify more via the command line, or changing this.
THRESHOLD=85    #The amount of disk space used before printing the warning.
DEBUG=false     #If TRUE when running (-d switch) lists all mount points, even if
                #the threshold has not been met.

while getopts ":dh" opt; do
        case $opt in
                d)
                        DEBUG=true
                        ;;
                h)
                        echo USAGE: $0 \[-d\] \[\/mount\/point\/1 ...\]
                        exit 0
                        ;;
                \?)
                        echo Incorrect syntax
                        ;;
        esac
        shift $((OPTIND - 1))
done

if [ "$#" -gt 0 ]; then
        for var in $@; do
                MOUNTPOINTS="${MOUNTPOINTS} ${var} "
        done
fi

for MOUNT in ${MOUNTPOINTS}; do
  CURRENT=$(df ${MOUNT} | grep / | awk '{ print $5}' | sed 's/%//g')
  if ($DEBUG); then
    printf "%20s\t%s\n" ${MOUNT} ${CURRENT}%
  fi
  if [ "${CURRENT}" -gt "${THRESHOLD}" ] ; then
      echo "Your ${MOUNT} partition\'s remaining space is critically low. Used: ${CURRENT}%"
    fi

done


texts: Calling a function from a dynamically loaded DLL

texts:
I need to implement some functionality of the otherwise monolithic application via DLL that is loaded at runtime. (Think about a customized DLL -- different for each customer.)

The Visual C++ from VS 2013 is used.

The application gets the full name name of the DLL. The function to be called has a fixed name (convert in my case) and fixed number and type of the arguments (a reference to a constant vector of strings -- see the cref_vs below). This means the function is implemented in C++.

I have modified the example from the MSDN doc, and it seems to work. However, I must be sure I did not overlooked something important. Here is the code (simplified) to load the DLL and call the function:

typedef const std::vector<std::string> & cref_vs;
typedef int(*CONVERTPROC)(cref_vs vs);

Notice that unlike in the official example that mixes calling a C code in DLL from a C++ function, I do not use __cdecl. I guess that this way I can reliably pass a C++ object (like a vector of strings). Is it correct?

int call_convert_from_dll(const std::string & dllname,
                          const std::vector<std::string> & vs)
{
    HINSTANCE hinstLib;
    CONVERTPROC convert;
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

    // Get a handle to the DLL module.
    hinstLib = LoadLibrary(dllname.c_str());

    // If the handle is valid, try to get the function address.
    if (hinstLib != nullptr) {
        convert = (CONVERTPROC)GetProcAddress(hinstLib, "convert");

        // If the function address is valid, call the function.
        if (convert != nullptr) {
            (convert)(vs);
        }

        // Free the DLL module.
        fFreeResult = FreeLibrary(hinstLib);
    }

    if (!fRunTimeLinkSuccess)
        return 1;

    return 0;
}

Now, because I want the unmangled name of the function inside the DLL, I need to use extern "C", and it must be exported via __declspec(dllexport). However, I do not want to use __cdecl calling convention:

#include <windows.h>
#include <iostream>

using namespace std;

extern "C" {

__declspec(dllexport) int convert(const std::vector<std::string> & vs)
{
    cout << "my.dll -- convert called with arguments:\n";
    for (int i = 0; i < argc; ++i)
         cout << argv[i] << endl;
    return 0;
}

} // extern "C"

Can you confirm that I am doing it correctly?


texts: Will this code get cleaned up by the garbage collector?

texts:
I have been working on a Backbone.js application, and I am starting to think I am making a huge mistake.

I never fully understand garbage collecting, and how exactly some closures prevent it. I just try to keep as organized as possible.

I just read an article that states that JavaScript variables that are not declared using the var keyword will not be removed from memory.

Now in my application I create everything inside an object called once. I clean this object every time I move to another page. I clean out the whole object, and remove all the elements and events associated to it.

Note: I am talking here about a single page backbone.js application. With changing pages I mean changing from one route to another using Backbone.History.navigate.

Am I making good use of the once Object inside the App object?  Will all be gone when I change routes?

////////////////////////////////////
//
// Main Object for my application
//  - once : One time models/views/etc
//  - move : Called before I move to a
//           new route
//  - clean: Called after I moved to
//           the new route
//  - close: Used internal by `clean`
//
/////////////////////////////////////
App = {
    once: {},

    move: function(){
        this.olds = this.once;
        this.once = {};
    },
    clean: function(){
        for(var Obj in this.olds){
            if(this.olds[Obj].models){
                this.olds[Obj].forEach(function(model){
                    this.close(model);
                }, this);
            }
            this.close(this.olds[Obj]);
        }

        delete this.olds;
    },
    close: function(Obj){
        if(typeof(Obj.onClose) !== 'undefined'){
            Obj.onClose();
        }
        if(typeof(Obj.off) !== 'undefined'){
            Obj.off();
        }
        if(typeof(Obj.remove) !== 'undefined'){
            Obj.remove();
        }
    }
}

///////////////////////////////////////////////
//
// My model, collection, and 2 views
//
// Note that I left out some basic steps
//
//////////////////////////////////////////////
window.User = Backbone.Model.extend({});
window.Users = Backbone.Collection.extend({
    model: User
});

window.UserView = Backbone.View.extend({
    // Init, events,  etc ...
    render: function(){
        this.collection.forEach(function(user){
            App.once.userSubView = new UserSubView({
                model: user
            });
            this.$el.append(App.once.userSubView.el);
        })
    }
});
window.UserSubView = Backbone.View.extend({});

///////////////////////////////////////////////
//
// One of the routes of my router.
//
// All my routs begin with move() and end
// with clean().
//
//////////////////////////////////////////////

App.move();

App.once.users = new Users();

// Create the views
App.once.users.fetch({
    success: function(){
        App.once.userView = new UserView({
            collection: App.once.users
        })
        $('body').append(App.once.userView.el);
    }
})

App.clean();


texts:
Can my code from this question be improved? I am thiking of validating inputs, portability issues, etc

Please note that we must declare our strings at compile time. We code embedded systems and are not allowed to malloc().

[Update]

I forgot to state that our enums are non-contiguous and have a wide range, which can make a difference.

Here's some test data:

// +=+=+=+=+=+=+=+=+=+=+=+=+=+=
typedef enum
{
    north,
    south,
    east,
    west
} E_directions;

struct direction_datum
{
    E_directions direction;
    char         direction_name[6];
};

struct direction_datum direction_data[] =
{
    {north, "north"},
    {south, "south"},
    {east,  "east"},
    {west,  "west"},
};

// +=+=+=+=+=+=+=+=+=+=+=+=+=+=
typedef enum
{
    hearts,
    spades,
    diamonds,
    clubs,
} E_suits;

struct suit_datum
{
    E_suits suit;
    char    suit_name[9];
};

struct suit_datum suit_data[] =
{
    {hearts,   "hearts"},
    {spades,   "spades"},
    {diamonds, "diamonds",},
    {clubs,    "clubs"},
};

and, here's the code, which should  get text from an enum, as defined by a struct of enum/string, where different structs can have different length arrays.:

#define ARRAY_LENGTH(A) sizeof(A) / sizeof(*A)

char *Get_text_from_enum(int enum_value,
                         void *array,
                         unsigned int array_length,
                         unsigned int size_of_array_entry)
{
    unsigned int i;
    unsigned int offset;

    for (i = 0; i < array_length; i++)
    {
        offset = i * size_of_array_entry;

        if ((int) * ((int *) (array+ offset)) == enum_value)
            return (char *)  (array + offset + sizeof(int));
    }

    return NULL;
}

printf("Expect south,    got %s\n",
          Get_text_from_enum(south,
                             direction_data,
                             ARRAY_LENGTH(direction_data),
                             sizeof(direction_data[0])));

printf("Expect diamonds, got %s\n",
          Get_text_from_enum(diamonds,
                             suit_data,
                             ARRAY_LENGTH(suit_data),
                             sizeof(suit_data[0])));


texts:
I'm working on a program that will (hopefully) eventually allow me to perform frame rate analysis like Digital Foundry does.  The code below works (as far as I know), but before I iterate on it, I'd like some feedback as I'm new to both C++ and OpenCV.  I say "as far as I know" because I'm not sure how "lossless" my lossless capture is or of the correctness of the program.  Is this code a good start?

#include "opencv2\opencv.hpp"
#include <fstream>

using namespace cv;
using namespace std;

int main(int argv, char** argc) {
    Mat curFrame;
    Mat pastFrame;
    VideoCapture vid("E:\\videos\\video.mkv");
    ofstream textFile("diffs.txt");
    int numDiff = 0;
    int numFrames = 0;

    if (!textFile.is_open()) {
        return -1;
    }

    if (!vid.isOpened()) {
        return -2;
    }

    vid.read(pastFrame);
    while (vid.read(curFrame)) {
        for (int i = 0; i < curFrame.rows; i += 1) {
            cv::Vec3b* curPixel = curFrame.ptr<cv::Vec3b>(i);
            cv::Vec3b* pastPixel = pastFrame.ptr<cv::Vec3b>(i);
            for (int j = 0; j < curFrame.cols; j += 1) {
                bool found = false;
                if (curPixel[j][0] != pastPixel[j][0]) {
                    numDiff += 1;
                    found = true;
                } else if (!found && curPixel[j][1] != pastPixel[j][1]) {
                    numDiff += 1;
                    found = true;
                } else if (!found && curPixel[j][2] != pastPixel[j][2]) {
                    numDiff += 1;
                }
            }
        }
        numFrames += 1;
        //cout << "Frame " << numFrames << endl;
        double size = curFrame.rows * curFrame.cols;
        textFile << numFrames << "," << fixed << setprecision(2) << numDiff / size * 100 << "\n";
        pastFrame = curFrame.clone();
        numDiff = 0;
    }

    textFile.close();
    vid.release();
    return 0;
}


texts: Reading a user credentials from file concurrently

texts:
I came across the following code snippet:

static private volatile ConfigUserCredentails maintenanceUserCred = null;
static private Object maintenanceUserLock = new Object();

/**
 * This method is slower.  Recommend use the one from cache.
 *
 * @return The username/password credentials of the maintenance user.
 * @throws IOException
 */
public static ConfigUserCredentails getMaintenanceUserCredentials() throws IOException {
    return readCredentialsFromFile(MAINTENANCE_CREDENTIALS_PROPS, Crypt.getDefaultCrypt());
}

/**
 *
 * @return The username/password credentials of the maintenance user.
 * @throws IOException
 */
public static ConfigUserCredentails getMaintenanceUserCredentialsFromCache() throws IOException {
    if (maintenanceUserCred != null) {
        return maintenanceUserCred;
    }
    synchronized(maintenanceUserLock) {
        if (maintenanceUserCred == null) {
            maintenanceUserCred = getMaintenanceUserCredentials();
        }
    }
    return maintenanceUserCred;
}

'getMaintenanceUserCredentials()' just reads the user credentials from file and
creates new user object.

My questions are:

What is the purpose of 'volatile'?
Why would one need the 'synchronized' block?

Thanks,
Rafik


texts: Draw element border according to scroll amount

texts:
I needed to draw border element according to scroll amount.
I made it work but I am not sure about optimization and performance.
There may have a better way? I am open to suggestion

you can see it in action here: enter link description here

here my js:

Thanks

var el = document.querySelectorAll(".animateBorder");

document.addEventListener("scroll", (event) => {
    for (var i = 0; i < el.length; i++) {
        var mHeight = window.innerHeight / 2 || document.documentElement.clientHeight / 2;
        var currentPos = document.documentElement.scrollTop + mHeight;

        var elTop = el[i].offsetTop;
        var elHeight = el[i].offsetHeight;
        var count = el[i].dataset.count;

        var partLenght = elHeight / count;

        var elEnd = elTop + elHeight;

        var spans = el[i].getElementsByTagName("span");

        for (var s = 0; s < spans.length; s++) {
            var offset = s * partLenght;
            var _0 = elTop + offset;
            var _100 = _0 + partLenght;
            var direction = spans[s].dataset.direction;
            // console.log("s", s);
            // console.log("partLenght", partLenght);
            // console.log("elTop", elTop);
            // console.log("offset", offset);
            // console.log("currentPos", currentPos);
            // console.log("_0", _0);
            // console.log("_100", _100);
            if (_0 <= currentPos && currentPos <= _100) {
                console.log("spans[s]", s);
                console.log("direction", direction);
                if (direction == "horizontal") {
                    spans[s].style.width = Math.round(((currentPos - _0) * 100) / partLenght) + "%";
                }
                if (direction == "vertical") {
                    spans[s].style.height = Math.round(((currentPos - _0) * 100) / partLenght) + "%";
                }
            }
            if (currentPos >= _100) {
                if (direction == "horizontal") {
                    spans[s].style.width = "100%";
                }
                if (direction == "vertical") {
                    spans[s].style.height = "100%";
                }
            }

            if (currentPos <= _0) {
                if (direction == "horizontal") {
                    spans[s].style.width = "0%";
                }
                if (direction == "vertical") {
                    spans[s].style.height = "0%";
                }
            }
        }
    }
});


texts: Rearrange elements in two-dimensional array spiral order

texts:
Recently I was asked to write algorithm to rearrange elements in two-dimensional array in spiral order.

Input array:                    Output array:

[  1,  2,  3,  4]           [  1,  2,  3,  4 ]
[  5,  6,  7,  8]    = >    [  8, 12, 11, 10 ]
[  9, 10, 11, 12]           [  9,  5,  6,  7 ]

I came up with the following solution using JavaScript:

(function(){
var Spiralify = function(matrix){
    function isArray(obj){
        return Object.prototype.toString.call(obj) === '[object Array]'
    }

    //Matrix is not specified or not an array
    if( !matrix || !isArray(matrix) ) { console.log('Matrix is not an array'); return; }

    var rows = matrix.length;
    if( rows <= 1 ) return matrix;
    //If first element of matrix is not an array, we cant define amount of columns in matrix, so just wrap it in array and return
    if(!isArray(matrix[0])) return [matrix];

    var cols = matrix[0].length;
    //If rows of the matrix are empty arrays, return null
    if( cols == 0 ) return matrix;

    //If arrays, corresponding to rows, have different amount of elements, return null
    if(matrix.some(function(el){ return el.length != cols; })) { console.log('All rows must have equal amount of columns'); return; }

    //If we have only one column, just transpond the array and wrap it into another array
    if( cols == 1) return [matrix.map(function(i){ return i[0]; })];

    function getUpperCorner(r1,c1,r2,c2)
    {
        for(var i=c1;i<=c2;i++)
            tmpArray.push(matrix[r1][i]);

        for(var j=r1+1;j<=r2;j++)
            tmpArray.push(matrix[j][c2]);

        if(r2-r1 > 0)
            getLowerCorner(r1+1,c1,r2,c2-1);
    }

    function getLowerCorner(r1,c1,r2,c2)
    {
        for(var i=c2;i>=c1;i--)
            tmpArray.push(matrix[r2][i]);

        for(var j=r2-1;j>=r1;j--)
            tmpArray.push(matrix[j][c1]);

        if(r2-r1 > 0)
            getUpperCorner(r1,c1+1,r2-1,c2);
    }

    var tmpArray = [];
    getUpperCorner(0,0,rows-1,cols-1);

    var result = new Array(rows);
    for(var i=0;i<rows;i++)
        result[i] = tmpArray.splice(0,cols);

    return result;
}

var matrix1 = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]];
var matrix2 = [[1,2,3,4,5],[6,7,8],[11,12,13,14,15]];
var matrix3 = [[1,2,3,4]];
var matrix4 = [[1],[2],[3],[4],[5],[6]];
var matrix5 = null;
var matrix6 = 1234;
var matrix7 = [];
var matrix8 = [[],[],[]];
var matrix9 = [1,2,3,4];
var matrix10 = 'Hello';

console.log (Spiralify(matrix1));
console.log (Spiralify(matrix2));
console.log (Spiralify(matrix3));
console.log (Spiralify(matrix4));
console.log (Spiralify(matrix5));
console.log (Spiralify(matrix6));
console.log (Spiralify(matrix7));
console.log (Spiralify(matrix8));
console.log (Spiralify(matrix9));
console.log (Spiralify(matrix10));
})(window);

But this solution was a show-stopper. I'm trying to learn from the defeat and would really appreciate some feedback on why this code is unappropriate.


texts: Implementing division without addition, multiplication, division or subtraction - follow-up

texts:
This is a follow-up to this question:

Division without using addition, multiplication or division

Could you please tell me if there is better way of performing division without +,-, * or /?

I've tested this code for different values of a and b.  I've also tested working for:

divide(8,3)
divide(5,10)
divide(9,6)
divide(42,6)

Could you please tell me if there is a cleaner solution?

private static int divide(int a , int b){

    boolean isNeg=false;
    boolean sign=true;
    boolean bothNegative=false;
    int quotient=1;

    if(a<0 && b<0){
        bothNegative=true;
    }
    else if(a<0 || b<0) {

        isNeg=true;
        sign=true;

    }

    a=Math.abs(a);
    b=Math.abs(b);

    if(a<b) return 0;
    else{

        int s=add(a,-b);
        int divisor =b;

        while(Math.abs(s)>=Math.abs(divisor)){
            b=add(b,divisor);
            s=add(a,-b);
            quotient=add(quotient,1);
             if(isNeg){
                sign=!sign;
            }
        }

        if(bothNegative){
            return quotient;

        }else if(isNeg && !sign){
            quotient=add(0,-quotient);
         }

        return quotient;
    }

}

private static int add(int a , int b){

    do{

        a^=b;
        b&=(a^b);
        b<<=1;

     }while(Math.abs(b)!=0);

    return a;
}


texts:
I gave this one a shot, and the code works. Am I on the right track? How can the code be improved? Also, I am unaware of how to determine if this would be linear time or not. Could someone maybe break that determination down for me?

'''
Problem statement: Find pairs in an integer array whose sum is equal to n (bonus: do it in linear time)

@author: Anonymous3.1415
'''

def pair_sum_to_n(integer_list, n):
    pairs = []
    #checks for the occurence of halfs
    if not n % 2:
        if integer_list.count(n/2) > 1:
            pairs.append((n/2, n/2))
        integer_set = set(integer_list) - {n/2}
    #finds pairs of integers where x + (n - x) = n
    for x in integer_set:
        if (n - x) in integer_set:
            if (n - x, x) not in pairs:
                pairs.append((x, n - x))
    return pairs

integer_list = list(map(int, raw_input().strip().split(" ")))
pairs = pair_sum_to_n(integer_list, 10)
print(pairs)


texts: Optimization for histogram computation algorithm in C

texts:
Next is an algorithm to calculate the histogram for a given YUV420sp image.  The YUV data is given by the hardware camera as an unsigned char*.

The algorithms works correctly, but I'm looking to optimize it for speed.

void calculateHistogram(const unsigned char* yuv420sp, const int yuvWidth, const int yuvHeight,
                        const int canvasHeight, int* histogramBins)
{
    const int BINS = 256;

    // Clear the output

    memset(histogramBins, 0, BINS * sizeof(int));

    // Get the bin values

    const unsigned int totalPixels = yuvWidth * yuvHeight;

    for (int index = 0; index < totalPixels; index++)
    {
        histogramBins[yuv420sp[index]]++;
    }

    // Resolve the maximum count in bins

    int maxBinValue = 0;

    for (int index = 0; index < BINS; index++)
    {
        if (histogramBins[index] > maxBinValue)
        {
            maxBinValue = histogramBins[index];
        }
    }

    maxBinValue = maxBinValue == 0 ? 1 : maxBinValue;

    // Normalize to fit into the histogram UI canvas height

    for (int index = 0; index < BINS; index++)
    {
        histogramBins[index] = histogramBins[index] * canvasHeight / maxBinValue;
    }
}


texts:
I recently got started with Elixir.  I'm used to F#'s pipes, and Seq.map and LINQ's .Select statements.  Things are different in Elixir, and the code I have seems very ugly.  Anon functions in anon functions.

defrecord FileData, name: "", date: nil
  def filedetails() do
    files = File.ls!
    datestr = fn {{year, month, day}, _time} -> "#{day}/#{month}/#{year}" end
    filedates = files |> (Stream.map &(File.stat!(&1)))
                      |> (Stream.map &(&1.ctime))
                      |> Stream.map &(datestr.(&1))

    Enum.zip(files,filedates)
      |> Enum.map fn {n,d}->FileData[name: n, date: d] end

  end

How should this be done?


texts: My implementation of a memmem() like function

texts:
Since memmem() isn't cross-platform, I'm trying to rewrite it from scratch. How does this look?
#define MemContainsStr(Str, StrLen, Substr) MemContainsMem(Str, StrLen, SubStr, sizeof(SubStr))
void *MemContainsMem(const void *StrStart, register unsigned long StrLen, const char *Substr, register const unsigned char SubstrLen) {
    if (StrLen < SubstrLen) {
        return 0;
    }
    register const unsigned char *Str = memchr(StrStart, *Substr, StrLen);
    do {
        if (!Str || StrLen < SubstrLen) {
            return 0;
        }
        if (!memcmp(Str, Substr, SubstrLen)) {
            return Str;
        }
        register void *NewStr = memchr(Str+1, *Substr, StrLen);
        StrLen -= NewStr-Str;
        Str = NewStr;
    } while (Str);
    return 0;
}

Are there register variables that shouldn't be, how can I further optimize this code?


texts:
From SICP:

  Exercise 2.2

  Consider the problem of
  representing line segments in a plane.
  Each segment is represented as a pair
  of points: a starting point and an
  ending point. Define a constructor
  make-segment and selectors
  start-segment and end-segment that
  define the representation of segments
  in terms of points. Furthermore, a
  point can be represented as a pair of
  numbers: the x coordinate and the y
  coordinate. Accordingly, specify a
  constructor make-point and selectors
  x-point and y-point that define this
  representation. Finally, using your
  selectors and constructors, define a
  procedure midpoint-segment that takes
  a line segment as argument and returns
  its midpoint (the point whose
  coordinates are the average of the
  coordinates of the endpoints). To try
  your procedures, you'll need a way to
  print points:

(define (print-point p)
  (newline)
  (display "(")
  (display (x-point p))
  (display ",")
  (display (y-point p))
  (display ")"))

I wrote the following solution:

(define (make-segment a b) (cons a b))
(define (start-segment l) (car l))
(define (end-segment l) (cdr l))

(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))

(define (sum . l) (if (zero? (length l)) 0 (+ (car l) (apply sum (cdr l)))))
(define (average . l) (/ (apply sum l) (length l)))

(define (midpoint seg)
  (make-point (average (x-point (start-segment seg))
                       (x-point (end-segment seg)))
              (average (y-point (start-segment seg))
                       (y-point (end-segment seg)))))

(define (print-point p)
  (newline)
  (display "(")
  (display (x-point p))
  (display ",")
  (display (y-point p))
  (display ")"))

(define seg-1 (make-segment (make-point 3 4)
                            (make-point 8 10)))
(print-point (midpoint seg-1))

What do you think?


texts: Simple neural-network simulation in C++ (Round 4)

texts:
You may want to take a look at Rounds 1, 2, and 3, though that isn't necessary for understanding what's below.

The major change since Round 3 is that my code is much cleaner and I'm including profiling information here.

Here's my script:

#include "hansel.h"
#include <deque>

int main()
{

  // Parameters.
  const double tau = 10;
  const double g_l = 0.1;
  const double I_0 = 2.3;
  const double theta = -40;
  const double V_l = -60;
  const double c = 0.5;
  const double N = 128;
  const double I_syn_bar = 0;
  const double tau_1 = 3;
  const double tau_2 = 1;
  const double C = 1;
  const double Delta_t = 0.25;

  // Simulation.
  std::deque<double> spike_times;
  double V = set_initial_V(tau, g_l, I_0, theta, V_l, c, N);
  for (double t = 0; t < 10000; t += Delta_t)
    {
      double I_syn = get_I_syn(I_syn_bar, N, tau_1, tau_2, t, spike_times);
      double dV_dt = get_dV_dt(g_l, V, V_l, I_syn, I_0, C);
      V += Delta_t * dV_dt;
      if (V > theta)
        {
          V = V_l;
          spike_times.push_back(t + Delta_t);
        }
    }

}

Here's the header file it includes:

#include <math.h>
#include <deque>

const double get_T(const double tau, const double g_l, const double I_0,
                   const double theta, const double V_l)
{
  return -tau * log(1 - g_l / I_0 * (theta - V_l));
}

double set_initial_V(const double tau, const double g_l, const double I_0,
                     const double theta, const double V_l, const double c,
                     const double N)
{
  const double T = get_T(tau, g_l, I_0, theta, V_l);
  const double i = 1;
  return V_l + I_0 / g_l * (1 - exp(-c * (i - 1) / N * T / tau));
}

double get_dV_dt(const double g_l, const double V, const double V_l,
                 const double I_syn, const double I_0, const double C)
{
  return (-g_l * (V - V_l) + I_syn + I_0) / C;
}

double get_f(const double tau_1, const double tau_2, const double t)
{
  return 1 / (tau_1 - tau_2) * (exp(-t / tau_1) - exp(-t / tau_2));
}

double get_I_syn(const double I_syn_bar, const double N, const double tau_1,
                 const double tau_2, const double t,
                 const std::deque<double> & spike_times)
{
  double sum_f = 0;
  const int n_spikes = spike_times.size();
  for (int i = 0; i < n_spikes; i += 1)
    {
      sum_f += get_f(tau_1, tau_2, t - spike_times[i]);
    }
  return I_syn_bar / N * sum_f;
}

Profiling the script, I see that ~100% of the time is spent in calls to get_I_syn.  Within that, time is split between calls to get_f (50.1%) and use of the deque [] operator (45.4%).

I'm hoping to speed up this script by a factor of ~10.

My questions are

1) Is there a way to refactor this line to increase speed:

return 1 / (tau_1 - tau_2) * (exp(-t / tau_1) - exp(-t / tau_2));

2) Is there a way to vectorize (or otherwise speed up) this loop:

for (int i = 0; i < n_spikes; i += 1)
  {
     sum_f += get_f(tau_1, tau_2, t - spike_times[i]);
  }

3) Is it likely to be faster to use an array or a vector instead of the deque object?


texts: Multi-threaded Winforms Conventions for Main()

texts:
I'm trying to find a good pattern for new applications (and for refactoring old ones).

Maybe it's just me, but I dislike spawning my main logic thread from inside my main form thread (so far I always have 2+ threads in my apps and beefy hardware, also .NET 4.5).  I feel it conflicts with the separation of concerns principle.

So is this a good pattern?

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace MyApp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                // Prevent multiple instances of the application from opening
                using (new SingleGlobalInstance(1000))
                {
                    // Run Main Logic/Sequence Task
                    Task.Factory.StartNew(() =>
                        {
                            new MainTask()
                                .Run();
                        });

                    // Display GUI
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());    // Blocks until Form Closes
                }
            }
            catch (TimeoutException)
            {
                MessageBox.Show("An instance of the application is already open.");
            }
            catch (Exception ex)
            {
                // Log Error
                // ... log to file...

                // Display Error to User
                MessageBox.Show(ex.Message);
            }
        }
    }
}

MainTask.cs

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

namespace MyApp
{
    public class MainTask
    {
        // Do Work
        public void Run()
        {
            Console.WriteLine("MainTask - Running");
            Thread.Sleep(10000);
        }

        // Constructor
        public MainTask()
        {
            Console.WriteLine("MainTask - Constructed");
        }

        //// Destructor
        //~MainTask()
        //{
        //    // Destructor defined for purposes of debugging
        //    Console.WriteLine("MainTask - Destructed");
        //}
    }
}

MainForm

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyApp
{
    public partial class MainForm : Form
    {
        // Constructor
        public MainForm()
        {
            InitializeComponent();
        }
    }
}


texts:
I have a service to Insert TagName , I dont want to insert duplicate tags
I used this :

   public void Insert(string tagName)
    {
        tagName = tagName.Trim();

        if (IsExists(tagName))
            throw new ArgumentException("tagName is Exists");
        Tag model = new Tag { Name=tagName};

        _uow.MarkAsAdded(model);

    }

    public bool IsExists(string tagName)
    {
        return _tags.Any(row=>row.Name==tagName.Trim());
    }

and another way is change If statement like below :

  public void Insert(string tagName)
    {
        tagName = tagName.Trim();

        if (!IsExists(tagName))
        {
            Tag model = new Tag { Name = tagName };
            _uow.MarkAsAdded(model);
        }
    }

I decided to use second one because I add another method Like this :

  public void Insert(string[] tags)
    {
        foreach (var item in tags)
        {
            Insert(item);
        }
    }

If I throw exception , Insert(string[] tags) will not completed .

Updated:

 private readonly IDbSet<Tag> _tags;

      #region ctor

    public TagService(IUnitOfWork uow)
    {
        _uow = uow;
        _tags = _uow.Set<Tag>();

    }

    #endregion


texts:
I have two files of dip.md and tp.md, which copied respectively from Think Python and Dive Into Python 3

By comparing them, I retrieved the shared words by the following procedures:

Read contents from files

def read(filename):
    with open(filename) as file:
        content = file.read()
    return content
dip = read('dip.md')
tp = read('tp.md')

In [49]: dip
Out[49]: '- -  \n\n    You are here:  •\n\n    # Dive Into Python 3\n\n    Dive Into Python 3 covers Python 3 and its differences from Python 2. Compared to [Dive Into Python](http://diveintopython.net/), it’s about 20% revised and 80% new material. The book is now complete, but [feedback is always welcome](http://www.diveintopython3.net/about.html).\n\n
...
In [50]: tp
Out[50]: 'Think Python: How to Think Like a Computer Scientist\n\nAllen B. Downey\n\n2nd Edition, Version 2.2.23\n\nPreface\nThe strange history of this book\nAcknowledgments\nContributor List\nThe way of the program\nWhat is a program?\nRunning Python\nThe first program\nArithmetic operators\nValues and types\nFormal and natural languages\nDebugging\nGlossary\nExercises\nVariables, expressions and statements\nAssignment statements\nVariable names\nExpressions and statements\nScript mode\nOrder of operations\nString operations\nComments\nDebugging\nGlossary\nExercises\nFunctions\nFunction calls

Clear data using string.punctuation

def clear_data(cont):
    for data in cont:
        if data in punctuation:
            cont = cont.replace(data, ' ')
    cont = cont.replace('\n', ' ')
    cont = cont.lower()
    return cont
dip_cont = clear_data(dip)
tp_cont = clear_data(tip)

Retrieve the qualified list

def get_qualified_list(cont):
    cont_list = cont.split(' ')
    qualified_list = [i for i in cont_list if i.isalpha()]
    return qualified_list
dip_list = get_qualified_list(dip_cont)
tp_list = get_qualified_list(tp_cont)

Get their intersection

In [51]:  print(set(dip_list) & set(tp_list))
{'is', 'study', 'Refactoring', 'with', 'and', 'the', 'first', 'Expressions', 'book', 'as', 'comprehensions', 'of', 'Strings', 'program', 'names', 'expressions', 'Case', 'to', 'Files', 'Classes', 'Objects', 'method', 'are', 'Python', 'The', 'in', 'new', 'strings'}

This solution is a bit too much for such a task which can be easily handled on 'MS Word'.

How can such a task be accomplished in an easy way?


texts:
I've written the below code to validate user input but I feel it's quite excessive for what seems to be a simple operation. I want to only accept non-negative integers or doubles as an input. This block of code is required three times in my program so I will need to put it into a method or something but in the mean time is there a simpler way to validate user input?

    Scanner input = new Scanner(System.in);

    boolean validWidth = false;
    double width = 0.0;;

    do // do while runs until the input is validated
    {
        System.out.print("Enter width: ");
        if (input.hasNextInt()) // we accept an int
        {
            width = input.nextInt();
            if (width > 0) // we accept a non-negative
            {
                validWidth = true;
            }
            else // refuse a negative
            {
                System.out.println("Input error. Try again.");
                validWidth = false;
            }
        }
        else if (input.hasNextDouble())// accept a double
        {
            width = input.nextDouble();
            if (width > 0) // we accept a non-negative
            {
                validWidth = true;
            }
            else // and refuse a negative
            {
                System.out.println("Input error. Try again.");
                validWidth = false;
            }
        }
        else
        {
            System.out.println("Input error. Try again.");
            validInput = false;
            input.next();
        }
    } while (!(validWidth));


texts: Spotify Bestbefore Coding Challenge in Python

texts:
I'm trying to solve the Spotify bestbefore programming challenge found here http://www.spotify.com/us/jobs/tech/best-before/

I have written the code in Python but when I send it in, it says "Wrong Answer". I have checked my code for bugs many times but unable to find out what is wrong. I know the answers to other's people's code is on the web but I do not want to look at theirs. I'm a firm believer in self-integrity and I really want to solve this myself. I'm just trying to found out some test cases where my code below does not work. Thanks

import sys

def values(year,month,day):
    valid = True
    #print "Debug: " + str(a) + " " + str(b) + " " + str(c)
    #Year
    fullYear = year
    if year < 2000:
        fullYear = year + 2000

    #Month
    if month > 12:
        valid = False

    #Day
    if month in (4,6,9,11):
        if day > 30:
            valid = False
    elif month == 2:
        is_leapyear = detectLeapyear(int(fullYear))
        if (is_leapyear):
            if day > 29:
                valid = False
        else:
            if day > 28:
                valid = False
    else:
        if day > 31:
            valid = False

    if not valid:
        return 0
    else:
        return 1

def detectLeapyear(in_year):
    rem4 = in_year % 4
    if not rem4:
        rem100 = in_year % 100
        if not rem100:
            rem400 = in_year % 400
            if not rem400:
                return 1
            else:
                return 0
        else:
            return 1
    else:
        return 0

if __name__ == '__main__':
    for line in sys.stdin:
        #date = sys.argv[1]
        date = line.strip()
        sArray = date.split('/')
        validArray = []

        x = int(sArray[0])
        y = int(sArray[1])
        z = int(sArray[2])

        #year-month-day
        if values(x,y,z):
            validArray.append([x,y,z])

        if values(x,z,y):
            validArray.append([x,z,y])

        if values(y,x,z):
            validArray.append([y,x,z])

        if values(y,z,x):
            validArray.append([y,z,x])

        if values(z,x,y):
            validArray.append([z,x,y])

        if values(z,y,x):
            validArray.append([z,y,x])

        if validArray:
            validArray = sorted(validArray, reverse=False)
            #Zero Padding of Numbers
            if validArray[0][0] < 2000:
                fyear = str(validArray[0][0] + 2000)

            if validArray[0][1] < 10:
                fmonth = "0" + str(validArray[0][1])
            else:
                fmonth = str(validArray[0][1])

            if validArray[0][2] < 10:
                fday = "0" + str(validArray[0][2])
            else:
                fday = str(validArray[0][2])
            #print "=>" + str(validArray[0][0]) + "-" + str(validArray[0][1]) + "-" + str(validArray[0][2])
            print fyear + "-" + fmonth + "-" + fday

            #print validArray
        else:
            print date + " is illegal"

These are the Test cases I have and they all seem to work:

12/11/10
02/4/67
31/9/73
31/12/2999
2000/6/12
2000/06/12
2000/12/6
2000/12/06
13/12/67
02/4/67
31/9/73
99/99/99

Program output:

2010-11-12
2067-02-04
31/9/73 is illegal
2067-12-31
2067-06-12
2067-06-12
2067-06-12
2067-06-12
2067-12-13
2067-02-04
31/9/73 is illegal
99/99/99 is illegal


texts: String Operation to Split on Punctuation

texts:
I've a function to split text on punctuation and leave the rest of the string (including whitespace in other items of the list):

import unicodedata

def split_on_punc(text):
    chars = list(text)
    i = 0
    start_new_word = True
    output = []
    while i < len(chars):
        char = chars[i]
        if is_punctuation(char):
            output.append([char])
            start_new_word = True
        else:
            if start_new_word:
                output.append([])
            start_new_word = False
            output[-1].append(char)
        i += 1
    ##print(output)
    return ["".join(x) for x in output]

def is_punctuation(char):
    return True if unicodedata.category(char).startswith("P") else False

E.g.

split_on_punctuation("This, this a sentence. with lotsa' puncts!?@ hahaha looo world")

[out]:

['This',
 ',',
 ' this a sentence',
 '.',
 ' with lotsa',
 "'",
 ' puncts',
 '!',
 '?',
 '@',
 ' hahaha looo world']

It looks like a very complicated way to check through each character and then keep track of whether it's a start of a new word or not.

I'm looking for improvements in speed and simplicity.


texts: Using jQuery and AJAX process a form with PHP

texts:
I'm looking to collect form input and pass it to a file called processing.php with AJAX

JS:

$(document).ready(function () {

    var serializedSubmission;
    var responseObj;

    $('#myForm').on('submit', function (e) {
        e.preventDefault();
        serializedSubmission = $('#myForm').serialize(); // get input
        if (checkInput()) { // validate
            process();  // append 'action' and process data
        }

    });

    /* data processing functions */
    // verify all parameters have values
    function checkInput() {
        var temp = decodeURIComponent(serializedSubmission);
        if (temp.search('=&') > 0 || temp.slice(-1) == '=') {
            console.log('Form is missing parameters!');
            return false;
        } else {
            return true;
        }
    }

    // append 'action' and pass data to php
    function process() {
        var data = {'action': 'demo'}; // set action to correspond with processing.php
        data = serializedSubmission + "&" + $.param(data);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'php/processing.php',
            data: data,
            success: function (data) {
                responseObj = JSON.parse(data['json']);
                console.log('ajax success:');
                console.log(responseObj);
            },
            error: function (xhr, desc, err) {
                console.log(xhr);
                console.log('Details: ' + desc + '\nError: ' + err);
            }
        });
    }
});

PHP:

<?php
if(isAjax()) {
    if(isset($_POST['action']) && !empty($_POST['action'])) { // check if action value exists
        $action = $_POST['action'];
        switch($action) {
            case 'demo':
                demo();
                break;
        }
    }
}

// check if ajax request
function isAjax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(
        $_SERVER['HTTP_X_REQUESTED_WITH']
    ) == 'xmlhttprequest';
}

// action = 'demo'
function demo() {
    $return = $_POST;
    $return['json'] = json_encode($return);
    echo json_encode($return);
}

// action = 'widget'
function widget() {
    // do stuff
    echo json_encode($return);
}

How's it look?


texts: Simple application in Python using OpenCV for face

texts:
I have been working on a simple Python application for face recognition with OpenCV. My code does its work and gets the job done, but I'm wondering if there's a 'better' way to do this. I hope I can get some tips on how to structure or approach this task.

See my full code 1 and 2.

while True:
    (_, im) = webcam.read()
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

    persons = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in persons:

        cv2.rectangle(im,(x,y),(x + w,y + h),(0, 255, 255),2)
        face = gray[y:y + h, x:x + w]
        rescaling_the_face = cv2.resize(face, (width, height))

        prophecy = model.predict(rescaling_the_face)
        cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 255), 2)

        if prophecy[1]<400:
           cv2.putText(im,'%s' % (names[prophecy[0]]),(x + 10, (y + 22) + h), cv2.FONT_HERSHEY_PLAIN,1.5,(20,205,20), 2)

        else:
          cv2.putText(im,'STRANGE_PERSON',(x + 10, (y + 22) + h), cv2.FONT_HERSHEY_PLAIN,1.5,(65,65, 255), 2)

    cv2.imshow('OpenCV Face Recognition -  esc to close', im)
    key = cv2.waitKey(10)

if key == 27:


texts: Randomly pick a host from a list, subject to an uptime requirement

texts:
I have a POJO as shown below which will have hostname and other attributes.

public class MachineInfo {

    private String hostname;

    // getters and setters here
}

I have my below method from which I need to randomly pick a hostname which is up for more than 10 minutes from machines list. The checkHostUptime method will return true if a particular machine is up for more than 10 minutes.

public static String pickRandomMachine(List<MachineInfo> machines) {
    String hostname = null;
    Collections.shuffle(machines, new Random(System.nanoTime()));
    for (MachineInfo info : machines) {
        if (!checkHostUptime(info.getHostName())) {
            continue;
        }

        hostname = info.getHostName();
        break;
    }

    return hostname;

}

I want to keep on trying finding the hostname until I find the hostname which is up for more than 10 minutes from machines list. If I am not able to find anything, then I would simply return null.

Is there any better way of doing the same thing?