texts: Counting the number of elements in a sorted array

texts:
Suppose I have a sorted array, and each element may appear multiple times.

To make it simple, here is an example:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]

The expected output is the number of each element. In this example, the results are:

number of 1 is 17
number of 2 is 6
number of 3 is 9

I want to find a solution where the algorithm time complexity is lower than \$O(n)\$. My idea is similar to binary search:

When I meet with equal neighbour, I will jump the tail pointer by 1, by 2, by 4, etc. and at the same time, I will make cur pointer move to the tail position
When I meet with unequal case, I will shrink the tail pointer to be in the middle of cur and tail
The diff between cur and last element tail is the count of the current elements

Any advice on algorithm time complexity improvement, code bugs or general code style advice is appreciated.

from collections import defaultdict
import random
def generate_count(numbers):
    last_index = -1
    result = defaultdict(int)
    cur_index = last_index + 1
    tail_index = cur_index + 1
    while cur_index < len(numbers):
        while cur_index < tail_index and cur_index < len(numbers) and tail_index < len(numbers):
            if numbers[cur_index] == numbers[tail_index]:
                pre = cur_index
                cur_index = tail_index
                tail_index += (tail_index - pre)
            else:
                tail_index = (cur_index+tail_index) / 2
        result[numbers[cur_index]] = cur_index - last_index
        last_index = cur_index
        cur_index = last_index + 1
        tail_index = cur_index + 1
    return result
if __name__ == "__main__":
    numbers = []
    for i in range(random.randint(1,20)):
        numbers.append(1)
    print 'number of 1 is', i+1
    for i in range(random.randint(1, 20)):
        numbers.append(2)
    print 'number of 2 is', i+1
    for i in range(random.randint(1, 20)):
        numbers.append(3)
    print 'number of 3 is', i+1
    print numbers
    print generate_count(numbers)


texts: Porting Delphi typed arrays to .NET generics

texts:
Currently I am porting piece of code from some old Delphi  API to C# and smashed into weirdness of type definitions. As its schema fits perfectly with DLL it uses (because it also was made in Delphi and keeps its style) I decided to cover for differences with some generic magic.

Technological constraints forced me to use .NET 2.0 (You expected such API to run on modern system?)

In Delphi (also known is some underground communities as Object Pascal) it is possible to create abominable typed arrays:

TFoo = Array[0..8] of Byte;
TEnum = (rawr, roar, gnar);
TBar = Array[TEnum] of Word;

In said API such little zerglings define most of data and are passed wildly around by pointers so object mimicking array (reference type is good enough) was required:

public class TArray<T>
{
    internal T[] internalArray;

    public TArray(int size)
    {
        internalArray = new T[size];
    }

    public TArray(T[] array)
    {
        internalArray = array;
    }

    public T this[int i]
    {
        get { return internalArray[i]; }
        set { internalArray[i] = value; }
    }

    public static implicit operator T[](TArray<T> tab)
    {
        return tab.internalArray;
    }

    public T[] Array
    {
        get
        {
            return internalArray;
        }
    }
}

And similar monstrosity for arrays indexed by enums (In more civilized days we would use some Dictionary, but since fire nation attacked everything paper became scarce)

public class TEnumArray<T, E> : TArray<T> where E : struct, IConvertible
{
    public TEnumArray()
        : base(Enum.GetValues(typeof(E)).Length)
    {
    }

    public TEnumArray(T[] array)
        : base(array)
    {
    }

    public T this[E i]
    {
        get { return internalArray[(int)(object)i]; }
        set { internalArray[(int)(object)i] = value; }
    }

    public static implicit operator T[](TEnumArray<T, E> tab)
    {
        return tab.internalArray;
    }
}

Usage is quite simple

public class TFoo:TArray<byte>
{
    public TFoo()
        : base(123)
    {
    }
}
public enum TEnum = {rawr=0, roar, gnar};
public class TBar:TEnumArray<ushort, TEnum>
{
    public TBar()
        : base()
    {
    }
}

To mimic pure array I added no exception handling on indexers.

Can it be made cleaner/better/faster?
Is there some obscure Delphi functionality I am missing?


texts: Find the most combinations of two numbers that equal third or get close to it

texts:
My task is to find how many different "tasks" can be done if I have two types of tasks that take specific time and time to complete all of them. I have to find the most tasks that can be done so that the gap between the time and sum of tasks is minimal. For example consider this input:

3 5 55

And output(2x5 + 15x3):

17

Or:

Input: 886 340 6177, Output: 10

Also:

Input: 3 5 54, Output: 18

My code is this:

 import java.util.Scanner;
 public class Protsessor {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt(); //Time of first task
        int n = in.nextInt(); //Time of second task
        int t = in.nextInt(); //Time available

        int tmpgap;
        int gap = t;
        int tasks = 0;
        int t1  = t;

        if( m <= 0|| n <= 0) { //If input is 0 or less
            System.out.println(0);
            System.exit(0);
        }
        if(m > n) { //I rearrange my input as it doesn't work when m is bigger then n
            int tmp = m;
            m = n;
            n = tmp;
        }
        for (int i = 0; i < (t/m+1); i++) {
            int tmptasks = 0;
            t1 -= i*m;
            tmptasks += i;
            for (int j = 0; j < (t/n+1) && t1 >= n; j++) {
                t1 -= n;
                tmptasks++;
            }
            tmpgap = t1;
            if(tmpgap <= gap){
                gap = tmpgap;
                tasks = tmptasks;
            }
            t1 = t;

        }
        System.out.println(tasks);
    }
}

As my code is quite messy, how can I optimize/improve it using dynamic programming?

NOTE: This was a task in competetive programming lesson, I already submitted this code(passed).


texts: Improving a robot's ability to navigate the plane with Karel J. Robot

texts:
I am in my first year of formally learning computer programming in high school (we are using Java). One of the tools we used was Karel J. Robot, which can be downloaded here. Although we finished using Karel after a semester, I felt that there was a lot more I could do with it. I decided to use some of what we are now covering in the class and implement a coordinate system and other improvements. This may also become part of a larger project where I manipulate robot(s) on the plane to perform other tasks as part of an interpreter.

Here is the code I wrote:

//This class creates methods to govern the basic movements of the robot.
//The robot moves on a Cartesian plane with origin (1,1) and turns at 90˚ angles.
//Created 02/08/2016 by Trevor B. (Stack Exchange user Eridan)

import kareltherobot.Robot;

public class Commands extends Robot {
    private int xCoordinate;
    private int yCoordinate;
    private Direction currentDirection;
    private int beeperCount;

    public Commands(int street, int avenue, Direction direction, int beepers) {
        super(street, avenue, direction, beepers);

        xCoordinate = avenue;
        yCoordinate = street;
        currentDirection = direction;
        beeperCount = beepers;
    }

    //MOVEMENT

    public void move(int steps) {
        for(int i = 0; i < steps; i++) {
            super.move();
        }

        if(facingNorth()) {
            yCoordinate += steps;
        }
        else if(facingSouth()) {
            yCoordinate -= steps;
        }
        else if(facingEast()) {
            xCoordinate += steps;
        }
        else if(facingWest()) {
            xCoordinate -= steps;
        }
    }

    public void move() {
        move(1);
    }

    public void turnLeft(int leftTurns) {
        for(int i = 0; i < leftTurns; i++) {
            super.turnLeft();
        }
    }

    public void turnLeft() {
        turnLeft(1);
    }

    public void turnRight() {
        turnLeft(3);
    }

    public void turnAround() {
        turnLeft(2);
    }

    //DIRECTIONS

    public void faceNorth() {
        while(!facingNorth()) {
            turnLeft();
        }
        currentDirection = North;
    }

    public void faceSouth() {
        while(!facingSouth()) {
            turnLeft();
        }
        currentDirection = South;
    }

    public void faceEast() {
        while(!facingEast()) {
            turnLeft();
        }
        currentDirection = East;
    }

    public void faceWest() {
        while(!facingWest()) {
            turnLeft();
        }
        currentDirection = West;
    }

    //COORDINATE CHANGE

    public void coordinateChange(int xDestination, int yDestination) {
        int xDifference = xDestination - xCoordinate;
        int yDifference = yDestination - yCoordinate;

        if(xDifference > 0) {
            faceEast();
        }
        else if(xDifference < 0) {
            faceWest();
        }
        move(xDifference);

        if(yDifference > 0) {
            faceNorth();
        }
        else if(yDifference > 0) {
            faceSouth();
        }
        move(yDifference);
    }

    //BEEPER MANAGEMENT

    public void putBeeper(int drops) {
        for(int i = 0; i < drops; i++) {
            super.putBeeper();
        }
        beeperCount -= drops;
    }

    public void putBeeper() {
        putBeeper(1);
    }

    public void pickBeeper(int picks) {
        for(int i = 0; i < picks; i++) {
            super.pickBeeper();
        }
        beeperCount += picks;
    }

    public void pickBeeper() {
        pickBeeper(1);
    }

    public void putAllBeepers() {
        while(anyBeepersInBeeperBag()) {
            putBeeper();
        }
    }

    public void pickAllBeepers() {
        while(nextToABeeper()) {
            pickBeeper();
        }
    }
}

Is there anything I can do to improve this code? Please keep in mind that I'm a beginner to programming, so I apologize for any glaring failures to follow proper programming conventions.


texts: Using Linq to select the first and last values

texts:
I want to get just the first and last values in a date range. I have the following code:

  using (var myEntities = new dataEntities())
  {
      var myValues = (from values in myEntities.PointValues
                      where values.PointID == dataValue && values.DataTime >= fromDate && values.DataTime <= toDate
                      orderby values.DataTime
                      select new BarChartValue
                      {
                          Time = values.DataTime,
                          Value = values.DataValue
                      }).ToList();
      var myBarChart = new List<BarChartValue> { myValues.First(), myValues.Last() };
      return myBarChart;
  }

This seems inefficient to me as I select the entire date range values initially. I can't seem to find a way to put first and last into the select command. Surely there must be a way to do this?

In response to Svick.

So, if I do this:

      var firstValue = (from values in myEntities.PointValues
                      where values.PointID == dataValue && values.DataTime >= fromDate && values.DataTime <= toDate
                      orderby values.DataTime
                      select new BarChartValue
                      {
                          Time = values.DataTime,
                          Value = values.DataValue
                      }).First();
      var lastValue = (from values in myEntities.PointValues
                        where values.PointID == dataValue && values.DataTime >= fromDate && values.DataTime <= toDate
                        orderby values.DataTime
                        select new BarChartValue
                        {
                            Time = values.DataTime,
                            Value = values.DataValue
                        }).Last();

Is that the best way to do it? I don't have any profiling tools (or if I do, I'm unsure how to use them).

The solution as provided by svick is:

      var myValues = (from values in myEntities.PointValues
                      where values.PointID == dataValue && values.DataTime >= fromDate && values.DataTime <= toDate
                      orderby values.DataTime
                      select new BarChartValue
                          {
                              Time = values.DataTime,
                              Value = values.DataValue
                          });
      var myBarChart = new List<BarChartValue> { myValues.First(), myValues.OrderByDescending(p => p.Time).First() };

A lot of this comes from my lack of understanding of the difference between IQueryable, IEnumerable and List. Here is a good explanation that helped me understand a bit more of what's going on:

https://stackoverflow.com/questions/4844660/differences-between-iqueryable-list-ienumerator


texts: Python generator for "barely obtuse" triangles (Project Euler 224)

texts:
I am trying to solve Project Euler Problem 224:

  Let us call an integer sided triangle with sides a ≤ b ≤ c barely obtuse if the sides satisfy a2 + b2 = c2 - 1.

  How many barely obtuse triangles are there with perimeter ≤ 75,000,000?

For large v_max and v_max_n, the generator below yields very slow when I have 750000000 and 500000000, respectively. Having tried for days, I am still looking for an algorithm that can do this in under a minute.

from itertools import product
import math

n = 15 * 10 ** 8
v_max = math.floor(n / 2 - 1 / (2 * n))
v_max_n = n // 3

(i for i in product(range(2, v_max_n + 1, 2),
                    range(2, v_max + 1, 2),
                    range(3, v_max + 1))
 if i[0] <= i[1] and i[1] <= i[2] and sum(i) <= n and
 i[0] ** 2 + i[1] ** 2 == i[2] ** 2 - 1)

I have tried using it as map(lambda x: x, gen), nested for loops, and have generally been racking my brain to no avail.

I tried re-writing b, c as expressions. This tends to be quick but misses some of the triples.

n = 12
v_max = math.floor(n / 2 - 1 / (2 * n))
v_max_n = n // 3
j = 0  # tested this with low n and compared: 12, 150 to see
for a in range(1, v_max_n + 1, 1):
    b = (n ** 2 - 2 * n * a - 1) / (2 * (n - a))
    c = (a ** 2 + b ** 2 + 1) ** 0.5
    if c % 1 == 0 and b % 1 == 0 and a + int(b) + int(c) <= n:
        # print(a, int(b), int(c))
        j += 1
print(j)


texts: Python/Django Filter with Datetime and extra options

texts:
I'm creating a filter in python/django. I want to make a datetime human-readable.
You have multiple options:
Plain Datetime ("04. Februar 2018, 18:18")

(bools="False,False"),

sentence Datetime ("am 04. Februar 2018 um 18:18")

(bools="True,False"),

onlydate Datetime ("04. Februar 2018")

(bools="False,True"),

sentence and onlyDate ("am 04. Februar 2018")

(bools="True,True")

Here's my filter:

@register.filter
def naturaldaytime(daytime, bools="False,False"):
    if daytime is None:
        return daytime

    sentence = str2bool(bools.split(",")[0])
    onlyDate = str2bool(bools.split(",")[1])

    now = datetime.datetime.now()
    difference = now.day - daytime.replace(tzinfo=None).day
    loc = locale.setlocale(locale.LC_TIME, "de")

    if onlyDate:
        if difference == 0:
            return daytime.strftime(settings.DATE_FORMAT_TODAY) if not sentence else daytime.strftime(settings.DATE_FORMAT_SENTENCE)
        elif difference == 1:
            return daytime.strftime(settings.DATE_FORMAT_YESTERDAY) if not sentence else daytime.strftime(settings.DATE_FORMAT_YESTERDAY)
        elif now.isocalendar()[0] == daytime.isocalendar()[0]:
            if now.isocalendar()[1] == daytime.isocalendar()[1]:
                return daytime.strftime(settings.DATE_FORMAT_THIS_WEEK) if not sentence else daytime.strftime(settings.DATE_FORMAT_THIS_WEEK_SENTENCE)
            return daytime.strftime(settings.DATE_FORMAT_THIS_YEAR) if not sentence else daytime.strftime(settings.DATE_FORMAT_THIS_YEAR_SENTENCE)
        return daytime.strftime(settings.DATE_FORMAT) if not sentence else daytime.strftime(settings.DATE_FORMAT_SENTENCE)
    else:
        pass
        #so what...

def str2bool(v):
    return v.lower() in ("yes", "true", "t", "1")

and my settings vars:

TIME_FORMAT = "%H:%M"

DATE_FORMAT = "%d. %B %Y, {0}".format(TIME_FORMAT)
DATE_FORMAT_THIS_YEAR = "%d. %B, {0}".format(TIME_FORMAT)
DATE_FORMAT_THIS_WEEK = "%A, {0}".format(TIME_FORMAT)
DATE_FORMAT_YESTERDAY = "Gestern, {0}".format(TIME_FORMAT)
DATE_FORMAT_TODAY = "Heute, {0}".format(TIME_FORMAT)

DATE_FORMAT_SENTENCE = "am %d. %B %Y um {0} Uhr".format(TIME_FORMAT)
DATE_FORMAT_THIS_YEAR_SENTENCE = "am %d. %B um {0} Uhr".format(TIME_FORMAT)
DATE_FORMAT_THIS_WEEK_SENTENCE = "diesen %A um {0} Uhr".format(TIME_FORMAT)
DATE_FORMAT_YESTERDAY_SENTENCE = "gestern um {0} Uhr".format(TIME_FORMAT)
DATE_FORMAT_TODAY_SENTENCE = "heute um {0} Uhr".format(TIME_FORMAT)


texts:
I am trying to practice the Observer design pattern in Golang, here is my code. I would be pleased to receive your comments, improvements, etc.

package observer

import (
    "container/list"
    "fmt"
    "math/rand"
)

//interface that receive updates
type Observer interface{
    Update(s *Subject)
}

// interface that manage notifying
type Subject struct{
    observers *list.List
    status int
}

func NewSubject() *Subject {
    //this can be categorized from database etc
    return &Subject{observers:new(list.List)}
}

func (s *Subject) Attach(o Observer){
    s.observers.PushBack(o)
}

func (s *Subject) DeAttach(o Observer){
    for obs := s.observers.Front(); obs != nil; obs = obs.Next() {
        if obs.Value.(Observer) == o {
            s.observers.Remove(obs)
        }
    }
}

func (s *Subject) notify(){
    for obs := s.observers.Front(); obs != nil; obs = obs.Next() {
        observer := obs.Value.(Observer)
        observer.Update(s)
    }
}

// some business logic function to notify
func (s *Subject) ScanData() {

    // just generate random number for status
    // this can be a business logic in real world to calculate or fetch status for a specific source or logic
    s.status = rand.Intn(1000)
    s.notify()
}

//Concrete class A for Observer
type ConcreteNotifierA struct{
}

func NewConcreteNotifierA() *ConcreteNotifierA {
    return &ConcreteNotifierA{
    }
}

func (a *ConcreteNotifierA) Update(s *Subject) {
    if s.status > 500 {
        fmt.Printf("Status is bigger than 500: %v \n", s.status)
    }
}

//Concrete class B for Observer
type ConcreteNotifierB struct{
}

func NewConcreteNotifierB() *ConcreteNotifierB {
    return &ConcreteNotifierB{
    }
}

func (b *ConcreteNotifierB) Update(s *Subject) {
    if s.status < 501 {
        fmt.Printf("Status is less than 500: %v \n", s.status)
    }
}

And here is testing:

subject := observer.NewSubject()
concreteObserverA := observer.NewConcreteNotifierA()
concreteObserverA1 := observer.NewConcreteNotifierA()
concreteObserverB := observer.NewConcreteNotifierB()
concreteObserverB1 := observer.NewConcreteNotifierB()

subject.Attach(concreteObserverA)
subject.Attach(concreteObserverA1)
subject.Attach(concreteObserverB)
subject.Attach(concreteObserverB1)

fmt.Printf("First Scan\n")
subject.ScanData()

subject.DeAttach(concreteObserverB)
subject.DeAttach(concreteObserverA)

fmt.Printf("Second Scan\n")
subject.ScanData()

EDIT: Let's say the goal is on different type of "Status", different type of subscribers will be notified.


texts: Algorithm to add all lucky numbers under [N] to a Vector

texts:
A lucky number is defined as a positive integer whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. I need to check if a given number is evenly divisible by any lucky number or not.
Now, suppose I want to add all Lucky Numbers under a given integer [N] to a vector, without using recursion. For the sake of simplicity, let N = 1000.

I came up with an approach to just check each digit of all the numbers under [N] by making separate loops for 1 digit numbers, 2 digit numbers etc.
for(int number=0;number<10;number++) {if(((number%10==4)||(number%10==7))) {lucky.push_back(number);}} //1 Digit Lucky Numbers
for(int number=10;number<100;number++) {if(((number%10==4)||(number%10==7))&&(((number/10)%10==7)||((number/10)%10==4))) {lucky.push_back(number);}} //2 Digit Lucky Numbers
for(int number=100;number<1000;number++) {if(((number%10==4)||(number%10==7))&&(((number/10)%10==7)||((number/10)%10==4))&&(((number/100)%10==7)||((number/100)%10==4))) {lucky.push_back(number);}} //3 Digit Lucky Numbers
for(int number=10;number<100;number++) {if(((number%10==4)||(number%10==7))&&(((number/10)%10==7)||((number/10)%10==4))&&(((number/100)%10==7)||((number/100)%10==4))&&(((number/1000)%10==7)||((number/1000)%10==4))) {lucky.push_back(number);}} //4 Digit Lucky Numbers

I was thinking that this could roughly be converted to something along these lines but I am not quite able to come up with what exactly to do.
for(number;number<10*itr_counter;number++)
    {
    if(((number%10*itr_counter==4)||(number%10*itr_counter==7))) {lucky.push_back(number);}
    itr_counter*=10;
    }

I basically want to check each digit of all 1 digit numbers by taking modulo 10 and checking if the digits are 4 or 7. Similarly for a number consisting of X digits, I am taking modulo and dividing the number by 10, 100 and so on to check against 4 or 7.
Can someone help me optimise the first block of code into something smaller and more efficient? Something along the lines of the second block of code would work.
The Program
#include <bits/stdc++.h>
using namespace std;

int main()
{
int in_num;
cin>>in_num;

//This Part Needs to be Optimised
vector<int>lucky;
for(int number=0;number<10;number++) {if(((number%10==4)||(number%10==7))) {lucky.push_back(number);}} //1 Digit Lucky Numbers
for(int number=10;number<100;number++) {if(((number%10==4)||(number%10==7))&&(((number/10)%10==7)||((number/10)%10==4))) {lucky.push_back(number);}} //2 Digit Lucky Numbers
for(int number=100;number<1000;number++) {if(((number%10==4)||(number%10==7))&&(((number/10)%10==7)||((number/10)%10==4))&&(((number/100)%10==7)||((number/100)%10==4))) {lucky.push_back(number);}} //3 Digit Lucky Numbers
for(int number=10;number<100;number++) {if(((number%10==4)||(number%10==7))&&(((number/10)%10==7)||((number/10)%10==4))&&(((number/100)%10==7)||((number/100)%10==4))&&(((number/1000)%10==7)||((number/1000)%10==4))) {lucky.push_back(number);}} //4 Digit Lucky Numbers
//This Part Needs to be Optimised

int flag=0;
for(unsigned int index=0;index<lucky.size();index++)
    {
    if(in_num%lucky[index]==0) {flag=1; break;}
    }
if(flag==1) {cout<<"YES";}
else {cout<<"NO";}
return 0;
}


texts:
To start, I am in the wrong language and I think it is time learn some C++ and compile it as an add-on for NodeJS. For now, though, I have a few code snippets that work that may be interesting or may be an abomination of coding.

This code works with weather forecast data, specifically the GRIB-2 file format. GRIB-2 compresses weather information into either integers or floating point values depending on the type (this cast is wind gusts). The data has been packed into 8-bit floating point values. I am assuming the GRIB-2 protocol follows floating point arithmetic and we can break our 8-bits into the following sections: 0 000 0000

Code to convert hex: 26 to floating-point: 0.6875:

var bin = makeWhole('100110'); //hex: 26
var fp = nBitFloatPoint(8, bin); //8 is unused but will allow different bit lengths

console.log(fp) // 0.6875

function makeWhole(a){
  var hex = a;
  if(hex.length !== 8){
    hex = prepend(hex);
  }
  return hex;
}

function prepend(hex){
  var diff = 8 - hex.length;
  var str = '';
  for(var i=0; i<diff; i++){
    str += '0';
  }
  return str + hex;
}

function nBitFloatPoint(n, bin){

  var s = bin.charAt(0);
  var e = parseInt(bin.substring(1, 4), 2) - 3;
  var m = '1.' + bin.substring(4, 8);
  var d = shiftDot(m, e);
  var result = convert(s, e, d);

  return result;

}

function convert(s, e, d){

  var strD = d.toString()
  var length, dotIndex, num, frac;
  var values = [];

  length = strD.length;
  dotIndex = strD.indexOf('.');
  num = strD.substring(0, dotIndex).split('');
  frac = strD.substring(dotIndex + 1).split('');

  //console.log(num)
  for(var i=0; i<num.length; i++){
    if(parseInt(num[i])){
      values.push(Math.pow(2, i));
    }
  }

  for(var i=0; i<frac.length; i++){
    console.log(frac)
    if(parseInt(frac[i])){
      //console.log(Math.pow(2, -i))
      values.push(Math.pow(2, -i-1));
    }
  }

  if(values.length){
    return values.reduce(arraySum);
  }
  return 0;
}

function arraySum(prev, curr, index, arr){
  return prev + curr;
}

function shiftDot(m, e){

  var str = '00000000000000000000000000' + m;

  var dot = str.indexOf('.');
  str = str.replace('.', '');

  return parseFloat(str.substring(0, dot + e) + '.' + str.substring(dot + e));
}

Is this a really hack idea that is best left to a language mean to work with binary buffers? Is the function shiftDot a plausible workaround or am I missing something best left to an internal JS function?


texts: Function to test whether the source and destination squares represent a valid knight move

texts:
The following is my solution to a problem. While it works - I want to learn how to optimize this in a much better way (I'm new to C++). My original idea was the use a map to map the r,c pairs and then test those but hoping someone can help optimize this for me.

  Write a function using a grid of string and two row/column pairs (r1, c1), (r2, c2) which returns true if there is a knight at chess board square (r1, c1) who can move to empty square (r2, c2). For your function to return true, there must be a knight at square (r1, c1), and the square at (r2, c2) must store an empty string, and both locations must be within the bounds of the grid.
  A knight makes an "L" shaped move, going 2 squares in one dimension and 1 square in the other. i.e. if the chess board (1, 2) stores "knight", then the call of knightMoves(board, 1, 2, 2, 4) returns true.

Here is my current solution

bool knightMoves(Grid<string>& board, int r1, int c1, int r2, int c2);

int main() {

    //create a fake board
    Grid<string> board(7,7);
    board[1][2] = "knight";
    board[3][1] = "rock";
    board[0][4] = "king";

    //fire the function
    bool result = knightCanMove(board, 1, 2, 2, 4);
    cout << result << endl;

    return 0;
}

bool knightMoves(Grid<string>& board, int r1, int c1, int r2, int c2) {

    bool canMove = false;
    string knight = "knight";

    //within grid bounds
    if(r1 > board.numRows() || c1 > board.numCols()) return false;
    if(r2 > board.numRows() || c2 > board.numCols()) return false;

    //test whether the co-ords match a knight string,
    //if yes, continue
    if (board[r1][c1] == knight) {
        if(board[r1 + 2][c1 + 1] == "" && r1+2 == r2 && c1+1 == c2) {
            canMove = true;
        }
        if(board[r1 + 2][c1 - 1] == "" && r1+2 == r2 && c1-1 == c2) {
            canMove = true;
        }
        if(r1 >= 2 && board[r1 - 2][c1 + 1] == "" && r1-2 == r2 && c1+1 == c2) {
            canMove = true;
        }
        if(r1 >= 2 && board[r1 - 2][c1 - 1] == "" && r1-2 == r2 && c1-1 == c2) {
            canMove = true;
        }
        if(board[r1 + 1][c1 + 2] == "" && r1+1 == r2 && c1+2 == c2) {
            canMove = true;
        }
        if(c1 >= 2 && board[r1 + 1][c1 - 2] == "" && r1+1 == r2 && c1-2 == c2) {
            canMove = true;
        }
        if(board[r1 - 1][c1 + 2] == "" && r1-1 == r2 && c1+2 == c2) {
            canMove = true;
        }
        if(c1 >= 2 && board[r1 - 1][c1 - 2] == "" && r1-1 == r2 && c1-2 == c2) {
            canMove = true;
        }
    }
    return canMove;
}


texts:
I have a piece of code that takes a couple of integers and check if performing an addition on the inputs would result in an overflow.

I was wondering if this code is SOLID:

public static boolean CanAdd(int me, int... args) {
    int total = me;
    for (int arg : args) {
        if (total >= 0) {
            if (java.lang.Integer.MAX_VALUE - total >= arg) { // since total is positive, (MaxValue - total) will never overflow
                total += arg;
            } else {
                return false;
            }
        } else {
            if (java.lang.Integer.MIN_VALUE- total <= arg) { // same logic as above
                total += arg;
            } else {
                return false;
            }
        }
    }
    return true;
}

Does anyone have a better (faster) way to achieve the same thing?


texts:
This is a user login (some session wrapper I managed to put together after a lot of web searching).

It's for a simple CMS I'm trying to build.  It only needs one user and there is no need for multiple user log in at the same time.  It works, the problem being I think it has safety issues.

It works like this:

The user accesses CMS index page, and inserts the user and password.
If one of them does not coincide with the data in the database it does not set the session and triggers a "die" or a error message.
If the info is ok then it sets the session and redirects the user from the index page to an admin.php page as you can see in the code below.

I commented it quite well.  If you see any safety issues please point them out as I can't seem to notice them.

The form is a simple user, password and submit form.

The class:

      <?php
      class Session{

    private static $_user;
    private static $_password;

    private static $_sessionStart = false;

    //here we check if the data inserted by the user in the form coincides with the rows in the db
    //if it does it sets the session for the user
    public static function CheckLog($received_user,$received_password){
        self::$_user            = $received_user;
        self::$_password        = $received_password;

        $db = Database::getInstance();
        $mysqli = $db->getConnection();

        $sql    = 'SELECT * FROM utilizatori ';
        $sql   .= 'WHERE user = "'.self::$_user.'" AND password = "'.self::$_password.'" ';
        $result = $mysqli->query($sql) or die (mysqli_error());
        if($row = $result->fetch_assoc()){
            if(($row['user'] === self::$_user)&&($row['password'] === self::$_password)){
                self::set('user',self::$_user);
                self::set('key',session_id());
            }
        }

      }
    //this method starts the session
    public static function start(){
       if(self::$_sessionStart == false){
         session_start();
         self::$_sessionStart = true;
       }
    }
    //this function sets the session values
    public static function set($key,$value){
        $_SESSION[$key] = $value;
    }
    public static function get($key){
        if(isset($_SESSION[$key])){
            return $_SESSION[$key];
        }
        else{
            return false;
        }
    }
    }

//from here is the handeling of the data in the "index" page:

        include("class_def/database.inc");
        include("class_def/user.inc");

        Session::start(); //here we start the session
        $up = strip_tags($_POST['user']); //post the user name
        $pp = strip_tags($_POST['password']);     //post the password
        //check if the variables are set and access the CheckLog method
       if((isset($up))&&(isset($pp))){
           Session::CheckLog($up,$pp);
       }
       //get the name of the current file
       $current_file = basename($_SERVER["SCRIPT_FILENAME"], '.php');

       //if the current page is index and the key is set redirect to admin.php
       if(isset($_SESSION['key'])){
           if($current_file == 'index')
      { echo '
        <script type="text/javascript">
            <!--
              window.location = "admin.php"
            //-->
            </script>';
      }
       }
       else{ //if the key is not set and the page is any other than index die and display message
           if($current_file != 'index'){
          die('You must log in first');
      }
          else{ // if the page is index echo out an error message
              $error_msj = 'Wrong user or pass';
          }
       }
    ?>


texts: Disallowing repeated characters and space after punctuation

texts:
I'm trying to "sanitize" a textarea input by disallowing repeated characters like "!!!", "???", etc. add spaces after commas, and I would like to optimize the code because I'm not a pro at this.

jsFiddle

$("#post_input").keypress(function() {
        var obj = this;
        setTimeout(function() {
            var text = obj.value;
            var selStart = obj.selectionStart;
            var newText = text.replace(/,{2,}|\.{4,}|\!{4,}|\¡{4,}|\?{4,}|\¿{4,}/, function(match, index) {
                if (index < selStart) {
                    selStart -= (match.length - 4);  // correct the selection location
                }
                return(match.substr(0,1));
            });
            if (newText != text) {
                obj.value = newText;
                obj.selectionStart = obj.selectionEnd = selStart;
            }
        }, 1);
    });

    $("#post_input").blur(function(){
      this.value = this.value.replace( /,\s*/g, ', ' );
    });

I would like to merge all in only one regex and function.

Basically, I want to:

Prevent repeated characters (all kind of characters) to 3. No "aaaaa" or "!!!!!"
Add space after commas (,) or any kind of punctuation (!) (?) (.)


texts:
Very simple requirements here:

connect to web service
check if account number exists
if it exists update it
if it does not exist create the account

I have accomplished this with the code below I am wondering if this is efficient and secondly if there is a better way of doing this.

 protected void Button1_Click(object sender, EventArgs e)
 {
    //authentication header
    com.x.w_1.www.WebService ws = new com.x.w_1.www.WebService();
    com.dat_e_baseonline.w_1.www.AuthenticationHeader header = new com.x.w_1.www.AuthenticationHeader();
    header.UserName = "";
    header.Password = "";
    ws.AuthenticationHeaderValue = header;

    string email = TextBox1.Text.ToString();

    //Are they a subscriber?
    XmlNode result = ws.getAccountIDbyEmail(email, "247");

    Label1.Text = result.OuterXml;

    foreach (XmlNode x in result.FirstChild)
    {
        string m = x.InnerText;
        string account = result.LastChild.InnerText;

        switch (m)
        {

            case "100":
                //update the account
                ws.Subscribe("x", "3", account);
                Label1.Text = "account exists";
                break;
            case "200":
                //create an account
                ws.createAccount("x", "5", email, "x", "x", "x", "01-01-1998", "1", "yes");
                Response.Redirect("/thankyou.aspx");
                break;

        }
    }

For reference here is the XML I get back when I send an email to be updated:

<getAccountID:name xmlns:getAccountID="http://x">
<getAccountIDResultCode xmlns="">100</getAccountIDbyEmailResultCode>
<getAccountIDResultDescr xmlns="">Account found.</getAccountIDResultDescr>
<accountID xmlns="">12345</accountID>
</getAccountIDbyEmail:name>


texts: Parse one table out of CSV with multiple titled tables with the Python CSV module

texts:
I'm looking to parse CSV files containing multiple tables using Python 3's csv module.

These complex CSVs are not unlike the toy example below. My goal is to make an idiom for picking out any one table using a known header row.

Complex CSV file toy.csv:

lists, fruits, books, forks, rope, gum
4, 2, 3, 0, 2, 2

Manhattan Produce Market
id, fruit, color
1, orange, orange
2, apple, red

Books
id, book, pages
1, Webster’s Dictionary, 1000
2, Tony the Towtruck, 20
3, The Twelfth Night, 144

Rope
id, rope, length, diameter, color
1, hemp, 12-feet, .5, green
2, sisal, 50-feet, .125, brown

Kings County Candy
id, flavor, color, big-league
1, grape, purple, yes
2, mega mango, yellow-orange, no

Each table is preceded by a title (except for a garbage table at the start). I save the previous row, and when I match the correct table header, I add the title as a new column.

import csv, re
header = [] #doesn't need to be list, but I'm thinking ahead
table = []

with open('toy.csv', 'r') as blob:
    reader = csv.reader(blob)
    curr = reader.__next__()
    while True:
        prev = curr
        try:
            curr = reader.__next__()
        except StopIteration:
            break
        if not ['id', ' book', ' pages'] == curr:
            continue
        else:
            header.append(prev)
            table.append(['title'] + curr)
            while True:
                try:
                    curr = reader.__next__()
                    if curr == []:
                        break
                    else:
                        table.append(header[0] + curr)
                except StopIteration:
                    break

The first part is to make an idiom which I can simply repeat for each table I want to extract. Later, I will combine the tables into one super-table filling NANs where the table headers don't match.

[['title', 'id', ' book', ' pages'],
 ['Books', '1', ' Webster’s Dictionary', ' 1000'],
 ['Books', '2', ' Tony the Towtruck', ' 20'],
 ['Books', '3', ' The Twelfth Night', ' 144']]

The code is based on this Stack Overflow post.

Happy to hear your suggestions to make the code more compact, idiomatic, and fit for my goals.


texts:
I started learning C++ a few days ago, and this is my first full program. It takes in words until an end-of-file character prompt is given, and then outputs which of those words are palindromes and the longest palindrome of those words.

I want to know if my evaluation for whether each string is a palindrome is acceptable given the little knowledge I have about C++ thus far, and by acceptable I mean like not costly or just not agreeable for good C++ code. I was unsure if it would be better to access characters by position in each string with like a "double iterator" to check if they were the same while the iterators converged, or if just making a reversed string and checking is a better approach like I did.

Also, just if my general program structure looks okay - I'm rather unsure if my desire to have void functions to clean up my main function is really a good thing to do or otherwise.

#include <iostream>
#include <list>
#include <iomanip>

using std::cin;         using std::cout;        using std::string;
using std::istream;     using std::list;        using std::endl;
using std::setw;

istream& read(istream& is, list<string>& word_list)
{
    word_list.clear();
    string word;
    while(is >> word)
        word_list.push_back(word);

    is.clear();
    return is;
}

void evaluate(list<string>& words, string& longest)
{
    longest.clear();
    typedef string::size_type str_sz;

    list<string>::iterator it = words.begin();
    while (it != words.end())
    {
        if (*it == string(it->rbegin(), it->rend()))
        {
            longest = max(longest, *it);
            ++it;
        }
        else
        {
            it = words.erase(it);
        }
    }
}

void output(const list<string>& palindrs, const string& longest)
{
    if (palindrs.empty())
        cout << "No palindromes were given :(" << endl;
    else{
        cout << "The palindrome(s) given are: " << '\n' << endl;
        for (list<string>::const_iterator it = palindrs.begin();
            it != palindrs.end(); ++it)
            cout << setw(5) << "- \"" << *it << "\"" << endl;

        cout << '\n' << "And the longest palindrome is \"" <<
             longest << "\"!";
    }
}

int main()
{
    list<string> words;

    cout << "Please enter some words." << endl;
    read(cin, words);

    string longest;
    evaluate(words, longest);

    output(words, longest);

    return 0;
}


texts: Checking if a random number exist within an interval efficiently

texts:
I have a problem where you have a bunch of probabilities associated with a number.

In this case:

any number between 0 - 0.3 should return 0,
any number between 0.3 - 0.7 should return 1,
any number between 0.7 - 1.0 should return 2

Is there a better way I can achieve this?

import random

class ProbChecker(object):

    def __init__(self, nums, prob):
        self._nums = nums
        self._prob = prob

    def next_val(self):
        if sum(self._prob) != 1.0:
            raise ValueError("Probabilities does not sum up to 1.0")

        accumulate = [sum(self._prob[: idx+1]) for idx in range(len(self._prob))]
        randomVal = random.random()

        for idx, x in enumerate(accumulate):
            if randomVal < x :
                return randomVal, self._nums[idx]

if  __name__ =='__main__':
    random_nums = [0, 1, 2]
    probabilities = [0.3, 0.4, 0.3]
    gen = ProbChecker(random_nums, probabilities)
    for i in xrange(100):
        print gen.next_val()

# EXAMPLE OUTPUT
#(0.9771170760903612, 2)
#(0.738653579103415, 2)
#(0.33448331523062824, 1)
#(0.6458688675258738, 1)
#(0.7062504910283919, 2)
#(0.4159743894291702, 1)
#(0.2636825176117218, 0)


texts: Lazy generator of strings in lexicographical order

texts:
I needed to write a Python generator that lazily generates, in lexicographical order, strings composed of a certain alphabet (e.g. lowercase English letters).
My first thought was to make an infinite generator, but an infinite iterator would be pretty useless because it would just generate strings composed of only the character a. This is because the lexicographical ordering of strings is not a well-order; it can be thought of as composed of an infinite sequence of infinitely nested sequences: (a, (aa, ...), (ab, ...), ...), (b, (ba, ...), (bb, ...), ...), ... The generator would never reach ab since it has an infinite amount of predecessors.
Thus I went for limiting the maximum length of the strings. I.e., the full specification is a generator that lazily generates all strings in a given alphabet of up to a certain length in lexicographical order. E.g., for a maximum length of 3 with ASCII lowercase letters, it should generate, in this order: "", "a", "aa", "aaa", "aab", ..., "aaz", "ab", "aba", ..., "zzz".
The solution I came up with is elegant in the abstract; it uses the intrinsic recursive relationship of lexicographical ordering: if you take the set of all strings—including infinite strings—and remove the first character from each, you're still left with the set of all strings. But it's probably not very efficient in practice, as for each iteration it uses Python's string concatenation operation + \$m\$ times to build a string of length \$m\$ (\$m - 1\$ times in between characters plus the "terminating" empty string, as you'll see below), and strings are immutable so copies are made at every intermediate step, resulting in \$O(m^2)\$ time complexity at each iteration.
Here is my solution:
import string

def lexstrings(max_length: int, alphabet=string.ascii_lowercase):
    yield ""
    if max_length == 0: return
    for first in alphabet:
        for suffix in lexstrings(max_length - 1, alphabet=alphabet):
            yield first + suffix

Example:
>>> g = lexstrings(max_length=3, alphabet="ab")
>>> list(g)
['',
 'a',
 'aa',
 'aaa',
 'aab',
 'ab',
 'aba',
 'abb',
 'b',
 'ba',
 'baa',
 'bab',
 'bb',
 'bba',
 'bbb']

This implementation also "supports" the infinite version by supplying a negative maximum length:
>>> g = lexstrings(-1)
>>> next(g)
''
>>> next(g)
'a'
>>> next(g)
'aa'
>>> next(g)
'aaa'
...

Some benchmarking confirms a single iteration of this is quadratic in terms of the string size. Here is a plot of execution time for generating a string of maximum length (in a single iteration) vs the maximum length:

The code to generate this plot using perfplot follows. (I modified the order of generation so that the first iteration yields a max-length string.)
import string
import perfplot
import sys

import numpy as np

def lexstrings(max_length: int, alphabet=string.ascii_lowercase):
    if max_length == 0:
        return
    for first in alphabet:
        for suffix in lexstrings(max_length - 1, alphabet=alphabet):
            yield first + suffix
    yield ""

n_range = np.linspace(1, sys.getrecursionlimit() - 500)
benchmark = perfplot.bench(
    setup=lambda n: n,
    kernels=[
        lambda n: next(lexstrings(n)),
    ],
    labels=[
        "lexstrings",
    ],
    n_range=n_range,
    xlabel="maximum string length",
    title="Single iteration (max-length string)",
    target_time_per_measurement=0.1,
    equality_check=None,
)

benchmark.show(logx=False, logy=False)


texts: Generating all 6-digit palindrome numbers in C++

texts:
I just finished my first homework for university where I had to create code that would generate all 6 digit palindrome numbers.

Can someone who has more knowledge give me some tips where I can improve my code?

#include <iostream>
#include <algorithm>
#include <sstream>

using namespace std;

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

  for (int iter = 100000; iter <= 1000000; ++iter ) {
    stringstream ss;
    ss << iter;
    palindroms = ss.str();

    string RevStr = palindroms;
    reverse( RevStr.begin(), RevStr.end() );

    if ( RevStr == palindroms ) {
      cout << palindroms << endl;
    }
  }
return 0;
}


texts:
Awhile back, I wrote a quick and dirty webapp to read the remote server's log files, without a user needing to ssh in to view it via command line. It's meant to be a quick and dirty tool since we don't have anything like logstash available.

I am rewriting in Java 8 and have used the Streaming API to remove about 60% of the existing code.

What I need reviewed is the following function:

@RequestMapping(value="logLines")
public void getLog(@RequestParam String logName, @RequestParam Integer logSize, HttpServletResponse response) throws Exception {

    log.debug("Entered getLog(). log: {}, logSize: {}", logName, logSize);

    PrintWriter writer = response.getWriter();
    // stream a line at a time to try to minimize memory usage
    Stream<String> stream = logService.getLogStream(logName, logSize);
    stream.forEach(p -> {
        writer.println(p);
    });

}

The previous version of the logService.getLogStream() method returned a List<String> which would have at least 1000 entries (and likely more). This version is meant to be optimized to avoid the memory overhead of a large List implementation. Also, it is meant so that the garbage collector can clean up used entries.

Am I really getting the benefits here that I want?

Here's the service method being used. There's some rudimentary HTML processing stuff being done to the lines read from the text file, which, if this wasn't quick and dirty code, I'd find a more elegant way to do.

/* JAVA 8 CODE */
@Override
public Stream<String> getLogStream(String logName, int lines) throws Exception {

    log.debug("Entered getLogStream()");

    final String filepath = properties.getProperty(logName);
    Path path = Paths.get(filepath);
    if (Files.exists(path)) {
        long countOfLines = Files.lines(path).count();
        Stream<String> result = Files.lines(path)
                .skip(Math.max(0, countOfLines - lines))
                .map(p -> p.trim())
                .map(p -> HtmlUtils.htmlEscape(p))          // Spring Util to escape the string for HTML since I'm already using Spring
                .map(p -> {
                    if (p.startsWith("at ")) {
                        return "" + p + "
\r\n";
                    } else {
                        return p + "
";
                    }
                });

        return result;
    } else {
        throw new IOException(String.format("Log file %s not found!", logName));
    }
}


texts: Determine if one string occurs at the end of another

texts:
Exercise 5-4

  Write the function strend(s,t), which returns one if the string t occurs at the end of the string s, and zero otherwise.

#include <stdio.h>

int str_end(const char *, const char*);

int main(void)
{
    char *s1 = "Man is a rope stretched over an abyss.";
    char *s2 = "an abyss.";

    printf("%s\n", str_end(s1, s2) ? "Yes" : "No");
    return 0;
}

int str_end(const char *s, const char *t)
{
    const char *init = t;       /* Hold the initial position of *t */

    while (*s) {
        while (*s == *t) {
            if (!(*s)) {
                return 1;
            }
            s++;
            t++;
        }
        s++;
        t = init;
    }
    return 0;
}


texts:
I am new to programming and mostly self-taught by following a few MOOCs and doing little projects. I have reached the point where I am trying to develop more complicated programs (numerical models at work and games at home) and I would like to be able to give a structure to my programs to enhance readability.

I am following an Edx course called Systematic Program Design which offers methods on how to design functions, data and world in a consistent manner.

However, I have come to notice that the method seems to work mostly with functional programs rather than the object-oriented(ish) code I tend to write (especially for games). This course made me aware that my code was full of methods with almost exclusively side effects changing attributes. Which makes it hard to follow the method and makes the code look really chunky. I was wondering if anyone knows of a course/book on how to increase readability of OO code. I use Python 2.7.1.

As I said, I am self-taught, so I apologies if the answer seems trivial to some of you who have done CS.

EDIT:

The github link to my game is Far and Away v1

And this is the picture of my  . The idea is that every object in the game has a game attribute linked to the Game() object which I use as a waypoint to access all objects in my game whilst keeping them in separate files.

EDIT END

To give you an example of what my code looks like and why I would like to have a method to improve it, here is one method of a game I've made:

    #Displays the map of planets and handles user interaction with the map
def view_solarsys(self,offset):
        planets_to_blit = []
        #checks for discovered planets and draws lines between them
        #as well as creating a list with them, that will be blitted to the screen
        for p in self.game.all_planets:
            if self.game.player.logbook[p.name].is_discovered == True:
                [pygame.draw.line(self.screen, (0,250,0), p.pos, p2.pos, 5) for p2 in p.planets_in_SOF if self.game.player.logbook[p2.name].is_explored and self.game.player.logbook[p.name].is_explored]
                planets_to_blit.append(p)
                #if mouse is over planet, the hoovered attribute is updated to the planet instance
                if p.rect.collidepoint(pygame.mouse.get_pos()) : self.hoovered = p
        #Blits discovered planets to screen. If they are not explored blits a red halo around them as well. If the player's location is on the planet blits a green halo around it.
        for p in planets_to_blit:
            if self.game.player.logbook[p.name].is_discovered == True:
                if self.game.player.logbook[p.name].is_explored == False:
                    pygame.draw.circle(self.screen, (255,0,0), p.pos, int(p.rect.w*0.6), 0)
                if self.game.player.location == p.name:
                    pygame.draw.circle(self.screen, (0,255,0), p.pos, int(p.rect.w*0.75), 0)
                fn.blitc(self.screen, Data.images_planets[p.img_ref], p.pos)

            '''Mouse interaction'''
            if p.rect.collidepoint(pygame.mouse.get_pos()) and self.game.map_active:
                if pygame.mouse.get_pressed()[0]:
                    if self.game.player.logbook[p.name].is_explored == False:
                        p.explore(self.game.player)
                    else:
                        p.visit(self.game.player)
                elif pygame.mouse.get_pressed()[2] and self.game.pressed_right_clic == True:
                    p.search_in_SOF(self.game.player,True,30)
                    self.game.pressed_right_clic = False

            '''blitting planet info of hoovered planet'''
            self.view_planet()


texts: Trade off in database efficiency versus a nested for loop on client

texts:
I built an app where a user has a recipe box with recipes in it - for the db, there is a user and recipe model, user has "recipeBox" property.  The recipebox is an array of objects like so:

User model....

User.recipeBox = {
["id1", "done": false],
["id1", "done": true],
}

The done property is for a checkbox on the front end.  the recipe models have TONS of information and images. so rather than store the entire recipes in a users recipe box, I stored the recipe IDs in a users recipe box (in order to associate the user with the recipes) and I populate them by id in conjunction with a separate recipe model.  I'm using Angular on the front-end, and when I was trying to use the powers of angular to persist the checkboxes, I found myself with two separate things to loop through, The User's RecipeBox, checking for ids and the "Done" property, and the recipes in the recipe box, which I had already generated with "populate" in mongoose, from the ids in the recipe box.  There was no way to associate the recipe models with the "done" property, the way I had constructed it, so my solution to this on the client was to call a function that put the "done" property on each Recipe (from the User.recipebox).  I'm pretty sure the answer is yes, but what is a more efficient way I could have done this with mongodb/mongoose/or any DB language?

I'm transferring the "done" property from the User.recipeBox over to Recipe manually here, to make it easy to use the "item in items" angular syntax:

 function addDonesToNGModel() {

      if ($scope.userRecipes) {

        var box = $scope.currentUser.recipeBox;
        var recipes = $scope.userRecipes;

        console.log(box, recipes);
        for (i = 0; i < box.length; i++) {
          for (var j = 0; j < recipes.length; j++) {

            if (box[i]._id == recipes[j]._id) {
              recipes[j].done = box[i].done;
            }
          }
        }
      }

    }

Models:

'use strict';

var mongoose = require('mongoose');
var recipeSchema = new mongoose.Schema({
  recipeUrl: String,
  image: String,
  numServings: Number,
  Ingredients: [String],
  NutritionalInformation: [{
    attribute: String,
    description: String,
    unit: {
      name: String,
      plural: String
    },
    value: Number
  }],
  // _id: Number,
  name: String,
  createdAt: { type: Date, default: Date.now },
  totalTime: String
});

var Recipe = module.exports = mongoose.model('Recipe', recipeSchema);

'use strict';

var crypto = require('crypto');
var bcrypt = require('bcryptjs');
var mongoose = require('mongoose');
var recipeSchema = require('./recipe.js').schema;
//need the objectID, see: https://gist.github.com/fwielstra/1025038
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var userSchema = new Schema({
  email: {
    type: String,
    unique: true
  },
  password: String,
  resetPasswordToken: String,
  resetPasswordExpires: Date,
  image: String,
  picture: ObjectId,
  name: String,
  facebook: {
    id: String,
    token: String,
    pictures: String
  },

  // can refactor this with $populate
   recipeBox: [{
    id: ObjectId,
    done: Boolean
  }]
});


texts: Summations zu.mpfr and zstar based on a probability sample

texts:
Here is my code:

library(gtools)
library(Rmpfr)
library(OBsMD)
precBits=1000000
K=9
n=1000
p=mpfr(c(K:1),precBits = precBits);p=mpfr(p,precBits = precBits)/mpfr(sum(p),precBits = precBits)
#p is a vector of probabilities

zu.mpfr <- function(freq, u, precBits){
  sum=mpfr(0,precBits = precBits)
  n=sum(freq)
  for (i in (1:length(freq))){
    prod=mpfr(1,precBits = precBits)
    for (j in (0:(u-1))){
      prod=prod*(mpfr(freq[i]-j,precBits = precBits))/mpfr(n-j,precBits=precBits)
    }
    sum=sum+prod
  }
  return(sum)
}

etastar<-rep(mpfr(0,precBits = precBits),K-1)
etastar=c(etastar)
for (i in 1:(K-1)){
  etastar[i]=sum(p^mpfr(i+1,precBits))
}

In the above codes, p is a vector of probabilities. zu.mpfr is \$z_u =\sum_k \prod_{j=0}^{u-1}\frac{Y_k-j}{n-j},\$ where \$u\$ can be any positive integer (but no more than \$n\$), and \$Y_k\$ is the observed frequency in a random sample for catagory \$k\$. The inputs for zu.mpfr are the sample frequency counts, \$u\$, and precBits (the preset accuracy). For the frequency, for example, if a sample is \$\{1,1,2,3,3,3,4\}\$, then the corresponding frequencies are \$\{2,1,3,1\}\$, since observation "1" appears twice, "2" appears once, "3" appears three times, and "4" appears once. The frequency is directly generated by rmultinom in the next paragraph of codes. etastar is a vector of length \$K-1\$. And the \$i\$-th element, \$\eta^{*}(i)\$, is \$\sum_k p_k ^{i+1}.\$ As a summary, zu.mpfr is a value calculated from a random sample, and etastar is a vector calculated from the probability distribution p.

Following is the part that I need to make it faster:

start.time<-Sys.time()
sample=rmultinom(1,n,asNumeric(p))
zstar<-rep(mpfr(0,precBits = precBits),K-1)
zstar=c(zstar)
for(i in 1:(K-1)){
  zstar[i]=zu.mpfr(sample,i+1,precBits)
}

end_time <- Sys.time()
end_time-start.time

In the latter codes, I used rmultinom to get the sample, which is the frequency counts from a random sample that generated by the probability distribution p. Then I calculated zstar, which is a vector of length \$K-1\$, with the \$i\$-th element zu.mpfr(sample, i+1, precBits). Here comes my problem. It takes too long to calculate the vector zstar. By timing it, "Time difference of 6.207007 secs" on my end. I am wondering if I can make it better. I need it faster because I need to run the simulation with thousands of iterations. I am not sure if the slowness is caused by mpfr but I do need it to enforce accuracy.

Please let me know if any further clarification is needed.


texts:
This code calculates pi via collisions; it asks for a user input of N which determines the mass of the second block. It is fully working, it just takes forever to run when N >= 2. I want to be able have at least N=5 and have a reasonable runtime. The issue is in the velocity and x1, x2 calculation I believe. There are just so many that need to be appended that it takes forever to run and then just as long to append.

My code shows that I have tried to use Numba to speed up the runtime, but that doesn't seem to be helping. I am currently using the RK-4 method to update position, and I previously tried the Verlet method which did not seem to have an affect on the runtime. Any help on this is greatly appreciated.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
from numba import jit
import time

start = time.time()

@jit(nopython=True)
def RK4_1(x, vx):
    return vx

@jit(nopython=True)
def RK4_2(x, vx):
    return 0

@jit(nopython=True)
def iterate(x1, x2, vx1, vx2, col):
    k1 = dt*RK4_1(x1, vx1)
    k2 = dt*RK4_1(x1 + k1/2, vx1)
    k3 = dt*RK4_1(x1 + k2/2, vx1)
    k4 = dt*RK4_1(x1 + k3, vx1)
    x1 += (1/6)*(k1 + 2*k2 + 2*k3 + k4)

    k1 = dt*RK4_1(x2, vx2)
    k2 = dt*RK4_1(x2 + k1/2, vx2)
    k3 = dt*RK4_1(x2 + k2/2, vx2)
    k4 = dt*RK4_1(x2 + k3, vx2)
    x2 += (1/6)*(k1 + 2*k2 + 2*k3 + k4)

    k1 = dt*RK4_2(x1, vx1)
    k2 = dt*RK4_2(x1, vx1 + k1/2)
    k3 = dt*RK4_2(x1, vx1 + k2/2)
    k4 = dt*RK4_2(x1, vx1 + k3)
    vx1 += (1/6)*(k1 + 2*k2 + 2*k3 + k4)

    k1 = dt*RK4_2(x2, vx2)
    k2 = dt*RK4_2(x2, vx2 + k1/2)
    k3 = dt*RK4_2(x2, vx2 + k2/2)
    k4 = dt*RK4_2(x2, vx2 + k3)
    vx2 += (1/6)*(k1 + 2*k2 + 2*k3 + k4)

    if x1 < 0:
        x1 = 0
        vx1 = -vx1
        col += 1

    if x2 < x1:
        x2 = x1
        vx1_i = vx1
        vx2_i = vx2
        vx1 = (2*m2*vx2_i + m1*vx1_i - m2*vx1_i)/(m1+m2)
        vx2 = (2*m1*vx1_i + m2*vx2_i - m1*vx2_i)/(m1+m2)
        col += 1

    return x1, x2, vx1, vx2, col

dt = 0.01

m1 = 1
N = int(input("Enter an integer N that will determine the mass of the second block: "))
m2 = 100**N

w1 = 1
w2 = w1*(100**N)**(1/3)
x1 = 1
x2 = 1.15
y1 = 1
y2 = 1
vx1 = 0
vx2 = -1
col = 0

x1arr = np.array([])
x2arr = np.array([])
y1arr = np.array([])
y2arr = np.array([])
vx1arr = np.array([])
vx2arr = np.array([])
colarr = np.array([])

t = 0

while (vx2 < 0) or (abs(vx1) > abs(vx2)):
    x1, x2, vx1, vx2, col = iterate(x1, x2, vx1, vx2, col)
    #print(vx1, vx2)
    t += dt

    x1arr = np.append(x1arr, x1)
    x2arr = np.append(x2arr, x2)
    y1arr = np.append(y1arr, y1)
    y2arr = np.append(y2arr, y2)
    vx1arr = np.append(vx1arr, vx1)
    vx2arr = np.append(vx2arr, vx2)
    colarr = np.append(colarr, col)

print("Number of collisions: %f" % (col))

speed = 1000

def update_plot(i, fig, scat1, scat2, txt):
    last = 0
    if(i>int(len(x1arr)/speed)-2):
        last=1
    s = int(speed*i)
    scat1.set_data(x1arr[s],y1arr[s])
    scat2.set_data(x2arr[s],y2arr[s])
    #scat.set_sizes(lx1=5, lx2=5*N)
    txt.set_text('x1= %.3f   m1=%.0f\nx2= %.3f   m1=%.0f\nCollisions=%.0f\n t=%.3fs' % (x1arr[s],m1,x2arr[s],m2,colarr[s]+last,(s*dt))) #update of legend
    #print("Frame %d Rendered" % (s))
    return scat1, scat2, txt,

size = 5*N
fig =  plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0, 3]) #animation scale
ax.set_ylim([0,5])
ax.grid()
txt = ax.text(0.05, 0.8, '', transform=ax.transAxes)
scat1, = ax.plot([], [],'s', c='r', markersize=5)
scat2, = ax.plot([], [],'s', c='r', markersize=5*(N+1))
anim = FuncAnimation(fig, update_plot, fargs = (fig, scat1, scat2, txt), frames = int(len(x1arr)/speed), interval = 1, blit=True, repeat=False)
anim.save("originalpi.mp4", fps=30, bitrate=-1)

end = time.time()
print("Total runtime in seconds:  ", end-start)

plt.show()


texts: Stopping a thread that runs an action periodically

texts:
I have a class that (among others) needs to run an action at fixed intervals of time. So I created a thread for this:

struct Logger
{
   std::chrono::milliseconds flush_interval_;
   std::thread flush_thread_;

   Logger(...) : flush_thread_{&Logger::flush_thread_function, this}, ... {}

   auto flush_cb() -> void; // this is the action that need to be ran periodically

   auto flush_thread_function() -> void
   {
       while (true)
       {
           std::this_thread::sleep_for(flush_interval_);
           flush_cb();
       }
   }
};

The problem with this is of course stopping this thread when the object is destroyed. I came with a solution involving condition_variable that seems to work, but since I don't have much experience with multi-threading and I am just getting my head around condition_variable I want to make sure the solution is OK.

This is the part of the class that deals only with this:

class Logger
{
private:
    std::chrono::milliseconds flush_interval_;

    bool flush_stop_ = false;
    std::condition_variable flush_stop_cv_{};
    std::mutex flush_stop_mutex_{};

    std::thread flush_thread_;

public:

    Logger(std::chrono::milliseconds flush_interval = 1s)
        : flush_interval_{flush_interval},
          flush_thread_{&Logger::flush_thread_function, this}
    {
    }

    ~Logger()
    {
        {
            std::lock_guard<std::mutex> lock_guard{flush_stop_mutex_};
            flush_stop_ = true;
        }

        flush_stop_cv_.notify_all();
        flush_thread_.join();
    }
private:

    auto flush_cb() -> void;

    auto flush_thread_function() -> void
    {
        auto prev_flush = std::chrono::system_clock::now();

        while (true)
        {
            auto next_flush = prev_flush + flush_interval_;

            std::unique_lock<std::mutex> lock{flush_stop_mutex_};
            auto stop_reason = flush_stop_cv_.wait_until(lock, next_flush);

            if (stop_reason == std::cv_status::timeout)
            {
                flush_cb();
                prev_flush = std::chrono::system_clock::now();
            }
            else if (flush_stop_)
            {
                // could call flush_cb() one last time here,
                // but I have another mechanism that deals with unflushed log entries
                break;
            }
            else
            {
                // this is a spurious wakeup
                // nothing to do here
            }
        }
    }
};

I am interested if my logic is solid and if the implementation is (thread-) safe. I chose wait_until and this overload in particular because the condition won't tell me if it was a timeout or a spurious wakeup. Another part that I am not entirely sure it's ok is the locking/unlocking of flush_stop_mutex_ in ~Logger() and the use of lock in flush_thread_function. As I understand after waking flush_stop_mutex_ is locked protecting flush_stop_ until the end of the current iteration of while, so I reason it is correct.


texts: With 2 sets of strings, find a string that can be constructed from either set

texts:
Given the following sets of strings:

are yo
you u
how nhoware
alan arala
dear de

I need to find a sequence that can be constructed by concatenating the strings in either columnm, and it must use the same number of elements in both cases.

For example, "dearalanhowareyou" can be constructed from both sets of strings, using 5 elements each time.

A invalid choice would be "dearalanhoware" since it would use 4 elements from the left column but only 3 from the right

The problem is taken from here:

https://open.kattis.com/problems/correspondence

I'm using this site to improve for future job interviews and I just can't seem to figure this one out at all.

My only working implementation is a brute force approach taking every possible combination of each set which is not a very good solution due to time complexity.

My code right now:

 list1 = getPermutations("",send1);
            list2 = getPermutations("",send2);

     ArrayList<String> duplicateValues = new ArrayList<String>();
            for (int i = 0; i < list1.size(); i++) {
                if (list2.contains(list1.get(i))) {
                    duplicateValues.add(list1.get(i));
                }

    private static ArrayList<String> getPermutations(String currentResult, ArrayList<String> possibleChars) {
            ArrayList<String> result = new ArrayList<>(possibleChars.size());
            for (String append : possibleChars) {
                String permutation = currentResult + append;

                result.add(permutation);
                if (possibleChars.size() > 0) {

                    ArrayList<String> possibleCharsUpdated = (ArrayList) possibleChars.clone();

                    possibleCharsUpdated.remove(new String(append));

                    result.addAll(getPermutations(permutation, possibleCharsUpdated));
                }
            }
            return result;
        }


texts: Showing a unique result based on options selected

texts:
I created a simple quiz in HTML/CSS and plain Javascript. There are three questions with two options each, so there are eight possible combinations of answers, and therefore results. You can only pick one option per question.

This is how I am currently assigning a result to each combination in Javascript. The input is done through HTML.

function GetResult(){
var result;
var inputs = document.getElementsByTagName('input');
for(var i = 0, i < inputs.length, i++){
if(inputs[i].checked){
result = result + inputs[i].value;
}}

if(result == 'NaturalHistoricalRelaxed'){
//result A
}
if(result == 'NaturalHistoricalFast'){
//result B
}
if(result == 'NaturalModernRelaxed'){
//result C
}
if(result == 'NaturalModernFast'){
//result D
}
if(result == 'UrbanHistoricalRelaxed'){
//result E
}
if(result == 'UrbanHistoricalFast'){
//result F
}
if(result == 'UrbanModernRelaxed'){
//result G
}
if(result == 'UrbanModernFast'){
//result H
}
}

My question is, is there a better way of assigning each result to each combination?

I know that many people would tell me to use a Javascript library, but I don't want to, so please do not write answers like that.


texts:
public sealed class Class1
{
    Class1()
    {

    }
    private static readonly object padlock = new object();
    private static Class1 instance = null;
    public static Class1 Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Class1();
                    }
                }
            }
            return instance;
        }
    }

    public bool EncryptFile(string path)
    {
        string ext = Path.GetExtension(path).Replace(".","");
        string filename = Path.GetFileNameWithoutExtension(path);

        byte[] b= System.Text.ASCIIEncoding.ASCII.GetBytes(ext);
        string encrypted = Convert.ToBase64String(b);
        var newPath = path.Replace(filename+"."+ext, filename+"_"+ encrypted + ".vik");

        try
        {
            string password = @"vik12389"; // Your Key Here
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);

            string cryptFile = newPath;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

            RijndaelManaged RMCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateEncryptor(key, key),
                CryptoStreamMode.Write);

            FileStream fsIn = new FileStream(path, FileMode.Open);

            int data;
            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);
            fsIn.Close();
            cs.Close();
            fsCrypt.Close();
            File.Delete(path);

            return true;

        }
        catch(Exception e)
        {
            return false;
        }
    }

    public bool DecryptFile(string path)
    {
        string ext = Path.GetExtension(path).Replace(".", "");
        string filename = Path.GetFileNameWithoutExtension(path);

        string[] splitFilename = filename.Split('_');

        byte[] b = Convert.FromBase64String(splitFilename[1]);

        string decryptedfileext = System.Text.ASCIIEncoding.ASCII.GetString(b);

        var newPath = path.Replace(filename + ".vik", splitFilename[0] + '.'+ decryptedfileext);
        try
        {
            string password = @"vik12389"; // Your Key Here

            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);

            FileStream fsCrypt = new FileStream(path, FileMode.Open);

            RijndaelManaged RMCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateDecryptor(key, key),
                CryptoStreamMode.Read);

            FileStream fsOut = new FileStream(newPath, FileMode.Create);

            int data;
            while ((data = cs.ReadByte()) != -1)
                fsOut.WriteByte((byte)data);

            fsOut.Close();
            cs.Close();
            fsCrypt.Close();

            return true;

        }
        catch (Exception e)
        {
            return false;
        }

    }

}

My Project Link on GitHub :https://github.com/vivianm94/EncryptFile.
how do I improve my code any suggestion.any features that could be added to the project


texts: Java: Find the smallest integer not in the list - Memory Efficiency

texts:
This is a fairly popular interview question that I conceptually understand but have never really attempted to implement. In other similar implementations of this in Java I have seen they typically operate on an array of boolean values which kind of irks me.  It turns out that the way the JVM works however is that it will allocate 8 bits for a single boolean primitive.  Granted I believe that an array of booleans actually does allocate a single bit for each value but just as a personal challenge I decided to use an array of byte and through bitwise operations utilizing each bit for a boolean value of N.

This means that the byte array will really be N / 8 or a single bit representing each possible random number that COULD occur in a list of numbers that just happens to be of N length as well.

The strategy is to construct my bytes by scanning each randomly generated number, determining which byte and bit that number correlates to in my byte array, and flipping the appropriate bit when that number is encountered.  When the scan is finished I simply inspect each bit and the first 0 bit I encounter means that bit location in my array represents the smallest integer that is not in the list of randomly generated numbers.

It should consume roughly 1/8th of memory from if I were to use a List and is 1/4 faster than sorting the list of random numbers.

import junit.framework.TestCase;

public class TestSmallestNumberNotInList extends TestCase {

    static final int N = 30000000;
    static int[] numbers = null;
    static {
        numbers = new int[N];
        for (int i = 0; i < numbers.length; i++)
            numbers[i] = Math.abs((int)(Math.round(Math.random() * N)));
    }

    public void testFindSmallestNumberNotInList() throws Exception {

        long startTime = System.currentTimeMillis();

        int byteArrayLength = (int) Math.ceil(N / 8);
        byte[] bitset = new byte[byteArrayLength];

        for (int number : numbers) {
            int byteIndex = (int)Math.floor(number / 8);
            byte b = bitset[byteIndex];
            int bitMod = (int)(number % 8);

            // The bit value will be 1 if we encountered this number before
            int bitVal = b>>>(32-bitMod) & 0x00000001;
            if (bitVal == 1)
                continue;

            //Get a byte mask to OR against the existing byte, flipping just the one bit
            //we are concerned with.
            byte byteMask = (byte)(1<<bitMod);
            b = (byte)(b | byteMask);

            //assign the new byte value for the byte array
            bitset[byteIndex] = b;
        }

        //Scan the byte array for the first 0 bit, this ((index * 8) + bitmodulus) is the smallest
        //integer not in the list.
        int location = 0;
        for (int i = 0; i < bitset.length; i++) {
            byte b = bitset[i];
            if (b == 0xFF) {
                location += 8;
                continue;
            } else {
                for (int j=8; j>=1; j--) {
                    if ((b>>>(j) & 0x00000001) == 1)
                        location++;
                }
                break;
            }
        }

        long duration = System.currentTimeMillis() - startTime;

        System.out.println("Total Memory: " + Runtime.getRuntime().totalMemory());
        System.out.println("Free Memory: " + Runtime.getRuntime().freeMemory());
        System.out.println("Smallest number not in the list is " + location);
        System.out.println("Time to execute in milliseconds: " + duration);
    }

    private static String getBitString(int x) {
        StringBuffer buf = new StringBuffer();
        for (int i=1; i<=32; i++) buf.append(x>>>(32-i) & 0x00000001);
        return buf.toString();
    }
}

I believe the output is correct although I really haven't unit tested the results.  It certainly seems correct.  I was wondering if I am making any glaring mistakes in my arithmetic or code or if you have any other possibilities or suggestions for improvement?


texts: Java function that blocks until a specific file is deleted

texts:
Created for a console application that will be run in the background on a linux system, giving me a nice way to gracefully shut it down by simply deleting a file (which can be done via script/etc.)

public class BlockOnRunFile {
    private File watchedFile;
    private Path path;
    private WatchService watcher;

    public void end() {
        watchedFile.delete();
    }

    public BlockOnRunFile(String runFilePath) throws IOException {
        watcher = FileSystems.getDefault().newWatchService();
        path = FileSystems.getDefault().getPath(
                runFilePath.substring(0, runFilePath.lastIndexOf(FileSystems
                        .getDefault().getSeparator())));
        watchedFile = new File(runFilePath);
        watchedFile.createNewFile();
    }

    public void block() {
        try {
            WatchKey key;
            key = path.register(watcher, StandardWatchEventKinds.ENTRY_DELETE);

            // stall until the game is supposed to end
            // reset key to allow new events to be detected
            while (key.reset()) {

                // key = watcher.take();
                try {
                    for (WatchEvent<?> event : key.pollEvents()) {
                        WatchEvent.Kind<?> kind = event.kind();
                        if (kind == StandardWatchEventKinds.OVERFLOW) {
                            Common.log.logMessage("File watcher overflow",
                                    LogLevel.INFO);
                            if (!watchedFile.exists()) {
                                // do nothing
                                ;
                            }
                            break;
                        }
                        if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                            @SuppressWarnings("unchecked")
                            WatchEvent<Path> ev = (WatchEvent<Path>) event;
                            Path filename = ev.context();
                            if (filename
                                    .toAbsolutePath()
                                    .toString()
                                    .equals(watchedFile.getAbsolutePath()
                                            .toString())) {
                                watcher.close();
                                break;
                            }
                        }
                    }
                    Thread.sleep(1000);   // prevent CPU burn, worst-case: 1 second delay on shutdown
                } catch (Exception e) {
                    watcher.close();
                    Common.log.logMessage(e, LogLevel.INFO);
                    continue;
                }
            }// end while loop
        } catch (IOException e1) {
            Common.log.logMessage(e1, LogLevel.ERROR);
        }
    }
}

It works, and I don't expect there to be any large amount of file operations in the directory where the file exists, but I would still like to know of any possible issues (I intend to automate it via some scripts/crontab and make sure it's robust enough)


texts: Clean way to remove an identical nested object in javascript

texts:
can you give me some feedback about my approach to remove an idential element from following data structure?
const items = {
  'Sun Mar 07 2021': [
     { id: 2 },
     { id: 1 }
  ],
  'Sat Mar 06 2021': [
     { id: 1 } // remove me
  ]
}

const id = 1 // filter by id 1
const newDate = 'Sun Mar 07 2021' // filter by newDate

let oldDate = ''
// Find the duplicate date and
// save it in oldDate to splice it afterwards
Object.keys(items).forEach(date => {
  items[date].forEach(item => {
    const match = item.id === id
    if (match && date !== newDate) {
      oldDate = date
    }
  })
})

const idx = items[oldDate].findIndex(el => el.id === id)
// remove the old item from matched array
if (oldDate) items[oldDate].splice(idx, 1)

I think it can be simplified or solved differently. Unfortunately I can't get any further, do you have any ideas?


texts:
I wrote this package for monitoring the state of a network connection in the terminal because my net connection would go down for a few minutes at a time and come back up. I think it could be used in other applications.

I'm looking for any advice on how to improve or extend this package in any way possible.

Package repo

My concerns are as follows:

Is the package "Pythonic"?
Does the package contain any obvious bugs/errors/flaws?

#!/usr/bin/env python

'''
This module is for checking a networks status.
'''

import socket
from time import sleep as _sleep
from functools import wraps
import errno
import os
import signal

TIMEOUT = 2

class NetworkStatus(object):
    def timeout(seconds=1, error_message=os.strerror(errno.ETIME)):
        def decorator(func):
            def _handle_timeout(signum, frame):
                return
                signal.signal(signal.SIGALRM, _handle_timeout)
                signal.alarm(seconds)
            def wrapper(*args, **kwargs):
                try:
                    result = func(*args, **kwargs)
                finally:
                    signal.alarm(0)
                return result

            return wraps(func)(wrapper)

        return decorator

    def set_timeout(self, t_out):
        '''
        Update the global variable TIMEOUT.
        '''
        global TIMEOUT
        TIMEOUT = t_out

    def sleep(self,delay):
        '''
        Sleep function with cleanup.
        '''
        try:
            _sleep(delay)
        except KeyboardInterrupt:
            exit()

    @timeout(TIMEOUT)
    def check(self, **kw):
        '''
        Check if the network is up.
        '''
        self.sleep(TIMEOUT)
        try:
            socket.gethostbyname(kw.get('remote_server', 'www.google.com'))
            return True
        except Exception:
            return False

    def online(self, **kw):
        '''
        return True is the network is UP.
        '''
        return self.check(**kw) is True

    def offline(self, **kw):
        '''
        return False if the network is DOWN.
        '''
        return self.online(**kw) is False

    def if_online(self, func, *args, **kw):
        if self.online():
            func(*args, **kw)

    def if_offline(self, func, *args, **kw):
        if self.offline():
            func(*args,**kw)

    def mainloop(self):
        '''
        Continuously check if the network is UP or DOWN.
        '''
        while True:
            up = self.check()
            if up:
                print 'Network is up'
            else:
                print 'network is down.'

if __name__ == '__main__':
    NetworkStatus().mainloop()


texts:
I'm looking for critiques to see what I could have done better or different ways I could approach writing a script for finding even or odd numbers. I am new to programming with JavaScript, and programming in general. This is one of the first challenges I wrote for finding even or odd numbers.
    var numList = [];
    while(numList.length < 5){
    numList.push(window.prompt());
    }

    var evenNumbers = [];

    numList.forEach(function(element){
        if (element % 2 === 0){
            evenNumbers.push(element);
        }
    })
    document.write(evenNumbers);


texts: Convert sequence of number into display string

texts:
My requirement is to convert a sequence of numbers into a display string as below.

Example

  Input

  1,2,3,4,5,7,7,8,8,8,10,15,10,11,12,88,87,86

  Output

  1-5,7-8,10-12,15,86-88

void makeDisplayString(std::vector<int>& vector, std::wstring& string)
{
    if(vector.empty()) return; // If empty do nothing

    std::sort(vector.begin(),vector.end()); // Sort vector first

    int& preValue =vector.at(0);
    string.append(std::to_wstring(preValue));

    bool continueFlag = false; // Flag to check if continuation of value

    for(auto const & num : vector)
    {
        if(preValue ==num)  continue; // if same number as previous , Skip it

        if(preValue+1 == num) // If number is one more than privious value
        {
            preValue = num;
            continueFlag=true; // set continuation flag and continue rest part
            continue;
        }

        if(continueFlag)
        {
            // We reach here only if neither number is save as previous nor it is continous of numbering
            // But befor this number there was a continous numbering
            string.push_back(L'-');
            string.append(std::to_wstring(preValue));
            string.push_back(L',');
            preValue=num;

            string.append(std::to_wstring(num));
            continueFlag = false;
            continue;
        }
        // We reach here only if neither number is save as previous nor it is continous of numbering
        // Also befor this number there was no continous numbering
        preValue = num;
        string.push_back(L',');
        string.append(std::to_wstring(num));
    }
    // This is to handle a sequence ending with continous number
    if(continueFlag)
    {
        string.push_back(L'-');
        string.append(std::to_wstring(*vector.rbegin()));
    }
}


texts:
I'm working on a simple little one page website for giving a presentation and I have some working code now, but I'm thinking there has to be a more elegant way of doing this. I would describe myself, at best, as a "dabbler" in JavaScript at this point; I'm much more comfortable with statically-typed languages and am doing this as a learning exercise.

Here's my JSFiddle showing what I am doing.

In my "real" site, the PageContent object is coming from an AJAX POST response (via an instance of node.js). I've included all of that code to make it easier to understand what is going on (any suggestions on how to restructure that server-side code would also be appreciated). If I have the time, I'll probably read these "points" from a config file or something else, but for now, a switch statement fits my needs.

The segment of this that makes me the most uneasy is this:

$('#pageContent').append('
' + mp.main);
    if (mp.subPoints.length > 0){
        $('li#'+i).append('
');
        $.each(mp.subPoints, function(index, sp){
            $('li#'+i+' ul').append('
' + sp + '
');
        });
        $('li#'+i).append('
');
    }
    $('#pageContent').append('
');

I don't like how I am having to add id values to my list items so I can then append my subpoints to the correct parent. Is there a less hacky-feeling way to go about this?

In case it isn't obvious from the fiddle, the page should show a list of main points, and, if they exist, subpoints under each main point. I'm basically trying to mimic PowerPoint.

Any criticisms of this code would be gladly accepted; I know this probably isn't idiomatic JavaScript.


texts:
I have a PR for a bugfix in which the fix is just 4 characters. In this situation we are invited to make some refactoring on the class that we are touching if possible.

Venkat Subramaniam's advice is to make lambda expressions just one line, hence I'm trying to move a block of code in a method.

Now choosing a better name come to the scene, and the challenge is to use For+ParamName or not use it on the method name.

With this advice from Google folks (Code Health: IdentifierNamingPostForWorldWideWebBlog):

  Omit words that are clear from the surrounding context.

I think that a method name getProducts(Category category) is better than getProductsForCategory(Category category), so could we avoid the For+ParamName?

Before

public class ProductProvider {

private final ProductProviderDatabaseHelper databaseHelper;

public ProductProvider(ProductProviderDatabaseHelper databaseHelper) {
    this.databaseHelper = databaseHelper;
}

public Observable<List<Product>> getProductsForCategory(Category category) {
    if (category == null) {
        return Observable.just(Collections.emptyList());
    }

    return Observable.defer(() -> {
        List<Product> result = new ArrayList<>();

        try {
            // DAO code
            result = daoProduct.query(preparedQuery);
        } catch (SQLException e) {
            Timber.e(e, "Error retrieving Products");
        }

        return Observable.just(result);
    }).subscribeOn(Schedulers.io());
}

After

public class ProductProvider {

private final ProductProviderDatabaseHelper databaseHelper;

public ProductProvider(ProductProviderDatabaseHelper databaseHelper) {
    this.databaseHelper = databaseHelper;
}

public Observable<List<Product>> getProductsForCategory(Category category) {
    if (category == null) {
        return Observable.just(Collections.emptyList());
    }

    return Observable.defer(() -> getProducts(category)
    ).subscribeOn(Schedulers.io());
}


texts:
How do you handle AggregateException? It is really useful in many TPL or business scenarios, but handling is a real pain. I defined the following three extensions to help myself a little bit. They can be used this way:

try
{
  throw new AggregateException(
     new ArgumentException(),
     new DivideByZeroException());
}
catch (AggregateException aex)
{
  aex
     .Handle((ArgumentException ex) =>
     {
         Console.WriteLine(ex.Message);
     })
     .Handle((DivideByZeroException ex) =>
     {
         Console.WriteLine(ex.Message);
         throw ex;
     })
     .Throw<DivideByZeroException>()
     .Throw<ArgumentException>()
     .ThrowIfNonEmpty();
}

These methods are defined on AggregateException and return AggregateException so they can be chained.

Handle invokes parameter delegate once per each inner exception instance of a specified type and returns a new copy of AggregateException without those handled exceptions. An optional exception being thrown in the delegate will be added to the resulting AggregateException.

Throw method tries to find a first inner exception instance of specified type and throws it if found. You can chain them to decide on priority.

ThrowIfNonEmpty extends an AggregateException to throw it when InnerExceptions collection is not empty.

public static class AggregateExceptionExtensions
{
    public static AggregateException Handle<TEx>(
        this AggregateException source, Action<TEx> handler)
        where TEx : Exception
    {
        var exceptions = source.Flatten().InnerExceptions.OfType<TEx>();
        var handlerExceptions = new List<Exception>();
        foreach (var exception in exceptions)
            try
            {
                handler(exception);
            }
            catch (Exception ex)
            {
                handlerExceptions.Add(ex);
            }

        return new AggregateException(source.InnerExceptions
            .Except(exceptions)
            .Concat(handlerExceptions));
    }

    public static AggregateException Throw<TEx>(this AggregateException source)
    {
        var ex = source.InnerExceptions.FirstOrDefault(e => e is TEx);
        if (ex != null)
            throw ex;

        return source;
    }

    public static void ThrowIfNonEmpty(this AggregateException source)
    {
        if (source.InnerExceptions.Any())
            throw source;
    }
}

Can you suggest any other tricks which might be useful?


texts: PHP to cast votes on an open-to-public election

texts:
I am creating an online voting platform where users could vote on publicly-held polls. It uses Kreait Firebase library (as Google didn't create a PHP library for Firebase Admin).

I am very new to PHP and am not sure about how I should format my PHP code. It is messy. Please help me improve the code.

<?php

$request = json_decode(file_get_contents("php://input"));

if (!isset($request->pollPath) || !isset($request->votes)) {
  print_r($request);
  echo "pollPath and/or votes have not been sent!";
  exit;
}

require __DIR__.'/../vendor/autoload.php';

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;

$pollPath = $request->pollPath;
$votes = $request->votes;

$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/../service.credentials.json');
$firebase = (new Factory)
  ->withServiceAccount($serviceAccount)
  ->asUser('brokerServer')
  ->create();

$pollsDatabase = $firebase->getDatabase();
$electionRef = $pollsDatabase->getReference('publicPolls/' . $request->pollPath);

$postsRef = $electionRef->getChild('posts');
$postsCount = $postsRef->getSnapshot()->numChildren();

if ($postsCount != count($request->votes)) {
  echo "Array of votes doesn't match the election's position count";
  exit;
}

$votesRef = $electionRef->getChild('votes');
$electionVotes = $votesRef->getValue();

if (!isset($electionVotes))
  $electionVotes = [];

$postsValue = $postsRef->getValue();
for ($i = 0; $i  < $postsCount; $i++) {
  $postValue = &$postsValue[$i];
  $postVotes = &$electionVotes[$i];

  if (!isset($postVotes)) {
    $postVotes = [];
    $postCands = count($postValue['candidates']);

    for ($j = 0; $j < $postCands; $j++)
      $postVotes[$postValue['candidates'][$j]] = 0;
  }

  if (isset($request->votes[$i]))
    $postVotes[$request->votes[$i]] += 1;
}

$votesRef->set($electionVotes);
print_r($electionVotes);
echo "done";

The code basically gets a JSON fetch request from the client with the path of the election (in Firebase) and an array of votes (mapping index of positions in election to the candidates chosen).


texts:
I have an n-tier solution which consist of DAL,BL and a ASP.net WebAPI project. I'm new with Asynchronous Pattern and I'm trying to add it to my Framework. Am I using the asynchronous pattern correctly? I'm not convinced with my implementation of it. Could you give me a recommendation on how to use it correctly or any other improvements I can make on my system?

This is my BL.

 public async Task<DTOUserList> GetUserList(DTOSearch source)
            {
                var result = new DTOUserList();

                try
                {

                    string strQuery;
                    Object[] objValues;
                    string strOrderBy;
                    CommonFunctions.ParseQuery(out strQuery, out objValues, out  strOrderBy, source);
                    //This is my implementation of async/await which im not convinced.
                    result = await Task.Run(() => _RepositoryUser.GetUserList(strQuery, objValues, source.PageNo, source.PageSize, source.OrderBy));

                }
                catch (Exception ex)
                {
                    result.IsSuccessful = false;
                    result.ErrorMsg = "Business Layer Error - " + ex.Message;
                }

                return result;
            }

and this is my DAL.

public DTOUserList GetUserList(String Query, object[] values, Int32 pageNo, Int32 pageSize, String orderby)
        {
            var result = new DTOUserList();

            try
            {

                _Entities = new Entities();

                IQueryable<DTOUser> data = from user in _Entities.mdUsers
                                           where user.Deleted == 0
                                           select new DTOUser
                                           {
                                               UserID = user.UserID,
                                               FirstName = user.FirstName,
                                               MiddleName = user.MiddleName,
                                               LastName = user.LastName,
                                               Email = user.Email,
                                               Telephone = user.Telephone,
                                               Mobile = user.Mobile,
                                               Address = user.Address,
                                               City = user.City,
                                               Country = user.Country,
                                               Active = user.Active,
                                               DateCreated = user.DateCreated

                                           };

                if (!string.IsNullOrWhiteSpace(Query)) data = data.Where(Query, values);

                result.TotalRecords = data.Count();
                result.UserList = data.OrderBy(a => a.FirstName).Skip(((pageNo > 0 ? pageNo : 1) - 1) * (pageSize > 0 ? pageSize : 1000)).Take((pageSize > 0 ? pageSize : 1000)).ToList();
                result.IsSuccessful = true;

            }
            catch (Exception ex)
            {
                result.IsSuccessful = false;
                result.ErrorMsg = "Data Access Layer Error - " + ex.Message;
            }
            return result;

        }


texts: Better way to load Mysql query in PHP Array

texts:
Here is my code:

$sql = <<<END
Select Sum(p)/Sum(w)*100 as present FROM attendance group by month
END;
$query = mysql_query($sql) or die($sql . ' - ' . mysql_error());
$names = array();
while ($row = mysql_fetch_array($query)) {
   $names[] = $row[0];
}


texts: Is this the right way to retrieve all the fields from any Object?

texts:
I have a method that returns a List<Object> from any given Object containing its values. It doesn't get the values of any static or final field in the class.

public List<Object> objectData(Object object) {
    Field[] fields = object.getClass().getDeclaredFields();
    Set<String> realFields = new LinkedHashSet<String>();
    for(Field field : fields) {
        if (!(java.lang.reflect.Modifier.isStatic(field.getModifiers()) ||
              java.lang.reflect.Modifier.isFinal(field.getModifiers()))) {
            realFields.add(field.getName());
        }
    }
    List<Object> row = new ArrayList<Object>();
    for(String realField : realFields) {
        Field currentField = object.getClass().getDeclaredField(realField);
        currentField.setAccessible(true);
        row.add(currentField.get(object));
    }
    return row;
}

Is this the right approach? Isn't something else I can be missing?

EDIT: The method above was adapted from this one. I'm assuming Collection<T> data is a valid non-empty collection.

public List<List<Object>> getData(Collection<T> data) {
    try {
        Field[] fields = data.iterator().next().getClass().getDeclaredFields();
        Set<String> realFields = new LinkedHashSet<String>();
        for(Field field : fields) {
            if (!(java.lang.reflect.Modifier.isStatic(field.getModifiers()) ||
                  java.lang.reflect.Modifier.isFinal(field.getModifiers()))) {
                realFields.add(field.getName());
            }
        }
        List<List<Object>> realData = new ArrayList<List<Object>>();
        for(T element : data) {
            List<Object> row = new ArrayList<Object>();
            for(String realField : realFields) {
                Field currentField = element.getClass().getDeclaredField(realField);
                currentField.setAccessible(true);
                row.add(currentField.get(element));
            }
            realData.add(row);
        }
    } catch (Exception e) {
        //basic error handling, this will be improved;
        throw new RuntimeException(e);
    }
}