texts: Linked list in Python which gets values from keyboard

texts:
What do you think about my implementation of linked list, which gets values from keyboard? I implemented three basic functions: print, insert and size.

class Node:

       def __init__(self):
               self.data = None
               self.next = None

class LinkedList:

       def __init__(self):
               self.head = None

       def insert(self,data):
               data = input("Add an element:")
               node = Node()
               node.data = data
               node.next = self.head
               self.head = node

       def print(self):
               print_list = self.head
               while print_list:
                       print(print_list.data)
                       print_list = print_list.next

       def size(self):
               i=0
               head = self.head
               while head:
                      i+=1
                      head = head.next
               print (i)

  MyList = LinkedList()

  while True:
       print("1. Add an element")
       print("2. Print the list")
       print("3. Size of the list")
       menu = int(input("Choose an action:"))

       if menu == 1:
               MyList.insert(1)
       elif menu == 2:
               MyList.print()
       elif menu == 3:
               MyList.size()


texts:
I've made a small script to compile Go code with Python.

The result is not something I'm happy with, because:

It seems overly complicated
I'm worried the nested if-else with f string are unreadable
Am I using the subprocess module the correct way?

Any review is welcome.

#!/usr/bin/env python3

import argparse
import subprocess
import os

ARCHS = {
    "32": "386",
    "64": "amd64"
}

BUILDTYPES = ["exe", "dll"]

def parse_arguments():
    parser = argparse.ArgumentParser(usage='%(prog)s [options] <buildtype> <architecture>',
                                     description='Go builder',
                                     formatter_class=argparse.RawDescriptionHelpFormatter,
                                     epilog='''
Python program to build go payloads

Examples:
    ./builder exe 32 --stripped
    ./builder dll 64 --upx --stripped
    ./builder dll 32
''')
    parser.add_argument("buildtype", help="The type to build the paylopad with", type=str)
    parser.add_argument("architecture", help="The architecture to build the paylopad with", type=str, default="32")
    parser.add_argument("--stripped", "-s", help="Strip the payload of symbols", action="store_true", default=False)
    parser.add_argument("--upx", "-u", help="Pack the payload with upx", action="store_true", default=False)
    arguments = parser.parse_args()

    if not arguments.buildtype.lower() in BUILDTYPES:
        parser.error(f"{arguments.buildtype} is not a valid buildtype can only be {', '.join(BUILDTYPES)}")

    if not arguments.architecture.lower() in ARCHS:
        parser.error(f"{arguments.architecture} is not a valid architecture can only be {', '.join(ARCHS.keys())}")
    arguments.architecture = ARCHS[arguments.architecture]

    return arguments

def build_go(**kwargs):
    enviroment = {
        **os.environ,
        "GOOS": "windows",
        "GOARCH": f"{kwargs['architecture']}"
    }
    if kwargs['buildtype'].lower() == "dll":
        enviroment["CGO_ENABLED"] = "1"
        enviroment["CC"] = f"{'i686' if kwargs['architecture'] == '386' else 'x86_64'}-w64-mingw32-gcc"

    build_type = f"go build -buildmode=c-shared" if kwargs["buildtype"].lower() == "dll" else "go build -tags exe"
    stripped = "-s -w" if kwargs['stripped'] else ""
    builder = f'''{build_type} -o GOLoader.{kwargs['buildtype']} -ldflags "-H=windowsgui {stripped}"'''
    subprocess.check_output(builder, shell=True, env=enviroment)

    if kwargs["stripped"]:
        stripped = f"strip GOLoader.{kwargs['buildtype']}"
        subprocess.check_output(stripped, shell=True)

    if kwargs["upx"]:
        upx = f"upx -f GOLoader.{kwargs['buildtype']} -9 --ultra-brute -o GOLoader.upx.{kwargs['buildtype']}"
        subprocess.check_output(upx, shell=True)

if __name__ == '__main__':
    args = parse_arguments()
    build_go(**vars(args))


texts:
My Scenario:

#TmpDistinctFolderIds table contains one or many FolderId.
fnGetAllParentFolderIds function receives the input as FolderId and return it's all possible parent folder ids (a parent folder can have N number of sub folders).

I'm using the below block to get each folder's all possible hierarchy parent folder ids. This approach is working as expected. No issues with the approach.

But can I achieve the same with out using WHILE execution or any other better approach?

DECLARE @TmpFolderId INT;
DECLARE @RelatedParentFolderIds TABLE (FolderID INT, ParentFolderID INT);

WHILE EXISTS (SELECT * FROM #TmpDistinctFolderIds)
BEGIN
    SELECT TOP 1 @TmpFolderId = FolderId FROM #TmpDistinctFolderIds

    -- Get all possible hierarchy level parent folder ids
    INSERT INTO @RelatedParentFolderIds (FolderID, ParentFolderID)
    SELECT FolderID, ParentFolderID
    FROM [dbo].[fnGetAllParentFolderIds] (@TmpFolderId)

    DELETE FROM #TmpDistinctFolderIds WHERE FolderId = @TmpFolderId
END


texts: Seeking ideas for better efficiently deleting an element in a vector

texts:
While experimenting with some algorithm I decided to simulate it in R.
I have a number of chronological elements in an array, and I want to prevent unlimited growth as new samples are added.
So I decided to start removing older samples with a somewhat higher probability than more recent samples.
OK, enough background, here's the function that does the "thinning":
f <- function(v) {
    l <- length(v)
    p  <-  l
    nv <- c(NULL)
    for (i in 1:l) {
        print(c(nv,"|",v[i:l]))
        if (trunc(runif(1, 0, p)) == 0) {
            nv <- c(nv, v[1:l > i])
            break
        }
        if (p > 1)
            --p
        nv <- c(nv, v[i])
    }
    v <- nv
}

Initially I had the line nv <- c(nv, v[i +1:l]), but that didn't work, so I changed it. But I feel this algorithm is highly inefficient for large vectors.
To help understanding what f does, there are some simple test outputs (remove at most one element (also preferably at least one) from the vector C(1,2,3) (v <- f(v) is to allow multiple reductions):
> v<-c(1,2,3)
> print(v <- f(v))
[1] "|" "1" "2" "3"
[1] 2 3
> v<-c(1,2,3)
> print(v <- f(v))
[1] "|" "1" "2" "3"
[1] 2 3
> v<-c(1,2,3)
> print(v <- f(v))
[1] "|" "1" "2" "3"
[1] "1" "|" "2" "3"
[1] "1" "2" "|" "3"
[1] 1 2 3
> v<-c(1,2,3)
> print(v <- f(v))
[1] "|" "1" "2" "3"
[1] "1" "|" "2" "3"
[1] "1" "2" "|" "3"
[1] 1 2
>

Ideally I would compute the index of the element to drop, and then drop it.
In a functional language like R there does not seem to exist a way to avoid copying all but one elements, right?


texts: Checking surrounding pixels inefficiently in pygame

texts:
This checks surrounding pixels to my object's pixel:

self.surr = [None, None, None, None, None, None, None, None]

for i in range(9):
#for x in range(-1, 2):
    #for y in range(-1, 2):
        if i != 5:
            x = i % 3 - 2
            y = int((i % 3) / 3) - 1

        if x == 0 and y == 0:
            pass
        else:
            PAI = allPixels[(self.x + x) % width][(self.y + y) % height] if allPixels[(self.x + x) % width][(self.y + y) % height] != None else None

        self.surr[(y * 3) + x] = (PAI)

return self.surr

This returns a list of length 8 that holds either a Pixel object or None. allPixels is a 2D array that also holds either a Pixel object or None.
I've tried then nested loops that are commented out but they run just a bit slower that the method I'm currently using. This however, is still too slow as if there are 3000 pixels on the screen, which is the lower bounds of the total pixels there will be on the screen in the end, do the maths and you have a LOT going on every frame.

Any help somehow making this run faster/more efficiently would be much appreciated.

If you want to see the whole code, it can be found here.


texts: Duplicate the previous input if zero or not a number

texts:
I have the following code which  duplicates the previous input if any entry is less than zero or NaN, except the first row of a matrix.

Is there any other efficient way to do this without using multiple for loops? The input matrix values may differ in some case and may contain float values or alphabets. The matrix considered here is just an example. The actual table will be 14352 x 42 in shape.

import numpy as np

data = [[0, -1, 2],
        [7, 8.1, -3],
        [-8, 5, -1],
        ['N', 7, -1]]
m, n = np.shape(data)

for i in range(1, m):
    for j in range(n):
        if data[i][j] < 0 or not isinstance(data[i][j], (int, float,long)):
            data[i][j] = data[i-1][j]

The output is:

[[0,-1,2],
 [7,8.1,2],
 [7,5,2],
 [7,7,2]]


texts:
I am learning algorithms by using Java. Here is an implementation of heapsort. Let me know if anything is wrong and and suggestion to improve the algorithm.

public class HeapSort {
    public int arr[];

    public HeapSort(int[] arr) {
        this.arr = arr;
    }

    // to make a heap
    public void makeHeap() {
        for (int i = 0; i < arr.length; i++) {
            // index of child element
            int index = i;
            while (index != 0) {
                int parent = (index - 1) / 2;
                if (arr[index] <= arr[parent]) break;
                // swap child element to its parent one
                int temp = arr[index];
                arr[index] = arr[parent];
                arr[parent] = temp;
                index = parent;
            }
        }
    }

    // to remove item from the top of the binary tree -> arr[0]
    public void removeTopItem(int count) {
        int a = arr[0];
        arr[0] = arr[count];
        arr[count] = a;
        int index = 0;
        count--;
        // to remake binary tree
        while (true) {
            int leftChild = index * 2 + 1;
            int rightChild = index * 2 + 2;

            // check the boundary
            if (rightChild > count) break;
            if (arr[index] > arr[leftChild] && arr[index] > arr[rightChild]) break;

            // to get greater parent
            int parentGreat = arr[rightChild] > arr[leftChild] ? rightChild : leftChild;

            // swap current item to its parent one
            int temp = arr[index];
            arr[index] = arr[parentGreat];
            arr[parentGreat] = temp;
            index = parentGreat;
        }
    }

    // sort using by heap
    public int[] heapSort() {
        // make a heap
        makeHeap();
        // sorting
        for (int i = arr.length - 1; i >= 0; i--) {
            removeTopItem(i);
        }
        return arr;
    }
}


texts: Creating a list of things by looking up multiple sources

texts:
I am trying to write a rspec webmock test for a rails PORO model. What this model does is, query bugzilla with a set of filters for a list of bugs and iterate over it such that:

The bug ids are used to make an xmlprc call to an internal service to get an id
This id is used to call another internal service which returns a url.
The outcome of this iteration is to create a list of hashes that includes the name of the bug, the type of the bug and an url.

The webmocks are getting messy and are forcing me to thing about a rewrite. I would like your advice on how to go about it, if at all.

# frozen_string_literal: true

class BugzillaLookup

  def initialize
    @xmlrpc_client = XMLRPC::Client.new_from_uri('https://foo.com/xmlrpc.cgi')
  end

  def find_url_for(args)
    report = []

    Bicho::Bug.where(query).each do |bug|
      location = get_thing_file(get_service_2_id(bug.id))
      things = create_hash_for_thing(bug['summary'], bug['id'], location)
      report.append(thing)
    end
    osp_sosreport
  end

  private

  def get_service_2_id(bug_id)
    @xmlrpc_client.call('Thing.get_thing_id', 'bug_id' => bug_id)['thing_id']
  rescue XMLRPC::FaultException => msg
    logger.debug msg
  end

  def get_thing_file(thing_id)
    job = HTTParty.get(URL + "thing/#{thing_id}/jobs").last
    return unless valid_response?(job)
    return if last_job_has_no_payloads(job)
    return unless payload_has_no_probe_files(job)
    filename = probe_file(job)
    job_id = job['job_id']
    URL + "reports/#{thing_id}/#{job_id}/probe/#{filename}"
  end

  def valid_response?(response)
    response.to_a.flatten.index('result').nil?
  end

  def last_job_has_no_payloads
    job['result_payloads'].empty?
  end

  def payload_has_no_probe_files(job)
    job['result_payloads'].select { |payload| payload['type'] == 'probe' }.present?
  end

  def probe_file(job)
    job['result_payloads'].select { |payload| payload['type'] == 'probe' }.first['filename']
  end

  def create_hash_for_thing(summary, type, location)
    thing = {}
    thing['name'] = summary
    thing['thing_type'] = type
    thing['file_location'] = location
  end
end


texts:
I recently implemented a dictionary class in TypeScript. I'm still new to JavaScript so I'm curious what people think about it.

class Dictionary {
    public constructor ();
    public constructor (object: Object);
    public constructor (object?) {
        if (object != null) {
            for (let property in object) {
                if (object.hasOwnProperty(property)) {
                    this[property] = object[property];
                }
            }
        }
    }

    public clone(): Dictionary {
        let result = new Dictionary(this);
        return result;
    }

    public getKeys(): string[] {
        let result = [];
        for (let item in this) {
            if (this.hasOwnProperty(item)) {
                result.push(item);
            }
        }
        return result;
    }

    public getValues(): any[] {
        let result = [];
        for (let item in this) {
            if (this.hasOwnProperty(item)) {
                result.push(this[item]);
            }
        }
        return result;
    }

    public tryAddItem(key: string, value: any): boolean {
        let isAddItem = !this.hasOwnProperty(key) && typeof(value) !== 'undefined';
        if (isAddItem) {
            this[key] = value;
        }
        return isAddItem;
    }

    public tryUpdateItem(key: string, value: any): boolean {
        let isUpdateItem = this.hasOwnProperty(key) && typeof(value) !== 'undefined';
        if (isUpdateItem) {
            this[key] = value;
        }
        return isUpdateItem;
    }

    public tryDeleteItem(key: string): boolean {
        let isDeleteItem = this.hasOwnProperty(key);
        if (isDeleteItem) {
            delete this[key];
        }
        return isDeleteItem;
    }
}

I realized that objects in JavaScript act a lot like dictionaries so I'm basically just adding functionality to the object. I'm not sure how I would want to handle sorting. I think I would prefer to create a method that returned a sorted array or object based on some function. Similar to what a JavaScript Linq library would do.


texts: Replacing each letter with the letter that is in the corresponding position from the end of the English alphabet

texts:
I wrote a small program for hyperskill/jetbrains academy to encrypt the message "we found a treasure!" and print only the ciphertext (in lower case) by replacing each letter with the letter that is in the corresponding position from the end of the English alphabet (a→z, b→y, c→x, ... x→c, y →b, z→a) and without replace spaces or the exclamation mark.

I would like code review comments in terms of correct use of java.

package encryptdecrypt;

public class Main {

    final static int lower_case_a = 'a';
    final static int lower_case_z = 'z';

    public static void main(String[] args) {
        String s = "we found a treasure!";

        StringBuffer reverse = new StringBuffer();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if ((int)c >= lower_case_a && (int)c <= lower_case_z)
                reverse.append((char)(lower_case_z - c + lower_case_a));
            else
                reverse.append((char) c);
        }
        System.out.println(reverse.toString());
    }
 }


texts: Implementing multiple Producer Consumer using custom Blocking queue

texts:
I am trying to implement multiple producer multiple consumer problem using a custom blocking queue. The requirement is that:

If the queue is not full, all the producers should be able to produce products independently.
If the queue is full, the producers have to wait.
If the queue is not empty, the consumer can consume products independently.
If the queue is empty, the consumers have to wait.

Here is the code I have implemented. Could you please review my code and let me know if there is any flaw?

Custom Blocking Queue

public class CustomQueue<T> {

private static final Object LOCK = new Object();
private int queueSize = 100; // default size
private List<T> queue;

public CustomQueue(int size){
    this.queueSize = size;
    this.queue = new LinkedList<>();
}

public void produce(T t){
    if(queue.size()==queueSize){ // queue is full. Producer need to wait
        synchronized(LOCK){
            while(queue.size()==queueSize){
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    System.out.println("Exception in produce() while waiting. Reason: "+e.getCause());
                }
            }
        }
    }else{ // queue is not full. Producer can produce items
        queue.add(t);
        LOCK.notifyAll();
    }
}

public T consume(){
    if(queue.size()==0){
        while(queue.size()==0){// queue is empty. Consumer need to wait
            try {
                LOCK.wait();
            } catch (InterruptedException e) {
                System.out.println("Exception in consume() while waiting. Reason: "+e.getCause());
            }
        }
    }else{ // queue is not empty. Consumers can consume item
        T t = queue.get(0);
        return t;
    }
    return null;
}

Producer code

public class Producer<T> implements Runnable{

private CustomQueue<T> sharedQueue;

public Producer(CustomQueue<T> sharedQueue){
    this.sharedQueue = sharedQueue;
}

@Override
public void run() {
    produceItems();
}

private void produceItems() {
    List<T> items = getItems();
    for(T t: items){
        sharedQueue.produce(t);
    }
}

private List<T> getItems() {
    //dummy method to get list of items
    return null;
}

Consumer code

public class Consumer<T> implements Runnable {

private CustomQueue<T> sharedQueue;

public Consumer(CustomQueue<T> sharedQueue){
    this.sharedQueue = sharedQueue;
}

@Override
public void run() {
    T t = consumeItem();
}

private T consumeItem() {
    T t = sharedQueue.consume();
    return t;
}


texts: Abstract Factory + Strategy pattern for parsing log files in multiple formats — improvement suggestions?

texts:
I'm writing a service to parse machine log files as they are written to a central directory and push them to a web service. Each machine generates several log files at a time, with each file encapsulating a particular domain of operational information (e.g. user login sessions, errors, statistics, etc.).

The log files are written by different models of machines from different manufacturers. All the machines generate the same kinds of information, but the structure of the log files differs according to the manufacturer of the machine and the type of information the log file contains. Below is a sketch of a set of factories that will create Log classes for each type of log file and configure them with a Parser appropriate for that manufacturer (Strategy Pattern).

Over time new machines will be added to the logging pool and it should be straightforward to add support for these. The proposed design is arranged around the manufacturer and it makes it simple to add support for new manufacturers. However, I am concerned about a scenario in which a new model from an existing manufacturer does not adhere to that manufacturer's existing log format.

Is there a better design?

public interface ILogFactory
{
    ISessionLog CreateSessionLog();
    ITipLog CreateTipLog();
    IStatisticsLog CreateStatisticsLog();
}

public class SmithsLogFactory : ILogFactory
{
    public ISessionLog CreateSessionLog()
    {
        return new SessionLog() { Parser = new SmithsSessionStrategy(); }
    }

    public ITipLog CreateTipLog()
    {
        return new TipLog() { Parser = new SmithsTipStrategy(); }
    }

    public IStatisticsLog CreateStatisticsLog()
    {
        return new StatisticsLog() { Parser = new SmithsStatsStrategy(); }
    }
}

public class L3LogFactory : ILogFactory
{
    public ISessionLog CreateSessionLog()
    {
        return new SessionLog() { Parser = new L3SessionStrategy(); }
    }

    public ITipLog CreateTipLog()
    {
        return new TipLog() { Parser = new L3TipStrategy(); }
    }

    public IStatisticsLog CreateStatisticsLog()
    {
        return new StatisticsLog() { Parser = new L3StatsStrategy(); }
    }
}

public class VividFactory : ILogFactory
{
    public ISessionLog CreateSessionLog()
    {
        return new SessionLog() { Parser = new VividSessionStrategy(); }
    }

    public ITipLog CreateTipLog()
    {
        return new TipLog() { Parser = new VividTipStrategy(); }
    }

    public IStatisticsLog CreateStatisticsLog()
    {
        return new StatisticsLog() { Parser = new VividStatsStrategy(); }
    }
}


texts:
I create a 2dVector class to use a position coordinates in a pygame application and maybe in the future as part of a physics engine. Does this implementation has any huge downsides? Is the type hinting ok?

import math
import random
from numbers import Real
from typing import Union, Sequence, cast

VectorType = Sequence[Real]

class Vector(VectorType):
    x: Real
    y: Real
    rotation: Real
    magnitude: Real

    def __init__(self, x: Union[VectorType, Real], y: Real = None) -> None:
        if y is None:
            x, y = cast(VectorType, x)
        self.x, self.y = cast(Real, x), y

    def __repr__(self):
        return f"{self.__class__.__name__}{self.x, self.y}"

    def __len__(self) -> int:
        return 2

    def __getitem__(self, i: int) -> Real:
        return (self.x, self.y)[i]

    def __add__(self, other: VectorType):
        return Vector(self.x + other[0], self.y + other[1])

    def __radd__(self, other):
        return Vector(self.x + other[0], self.y + other[1])

    def __iadd__(self, other: VectorType):
        self.x += other[0]
        self.y += other[1]
        return self

    def __sub__(self, other: VectorType):
        return Vector(self.x - other[0], self.y - other[1])

    def __rsub__(self, other: VectorType):
        return Vector(other[0] - self.x, other[1] - self.y)

    def __isub__(self, other: VectorType):
        self.x -= other[0]
        self.y -= other[1]
        return self

    def __mul__(self, other: Real) -> Vector:
        return Vector(self.x * other, self.y * other)

    def __rmul__(self, other: Real):
        return Vector(self.x * other, self.y * other)

    def __matmul__(self, other: VectorType):
        return Vector(self.x * other[0], self.y * other[1])

    def __rmatmul__(self, other):
        return Vector(other[0] * self.x, other[1] * self.y)

    def __truediv__(self, other: Union[VectorType, Real]) -> Vector:
        if isinstance(other, Sequence):
            return Vector(self.x / other[0], self.y / other[1])
        return Vector(self.x / other, self.y / other)

    def __rtruediv__(self, other: VectorType) -> Vector:
        self.x /= other
        self.y /= other
        return self

    def __round__(self, n=None) -> Vector:
        return Vector(round(self.x, n), round(self.x, n))

    def change_rotation(self, rotation: float) -> Vector:
        v = Vector(self.x, self.y)
        v.rotation += rotation
        return v

    @classmethod
    def random(cls, x_range=(0, 1), y_range=(0, 1)):
        return cls(random.uniform(*x_range), random.uniform(*y_range))

    @classmethod
    def from_polar(cls, rotation: Real, magnitude: Real):
        return Vector(math.cos(rotation) * magnitude, math.sin(rotation) * magnitude)

    def normalize(self):
        f = self.magnitude
        self.x *= f
        self.y *= f
        return self

    @property
    def magnitude(self) -> Real:
        return (self.x * self.x + self.y * self.y) ** 0.5

    @magnitude.setter
    def magnitude(self, value: Real):
        f = value / self.magnitude
        self.x *= f
        self.y *= f

    @property
    def rotation(self):
        return math.atan2(self.x, self.y)

    @rotation.setter
    def rotation(self, value):
        m = self.magnitude
        self.x = math.sin(value)
        self.y = math.cos(value)
        self.magnitude = m

    @property
    def rounded(self):
        return round(self.x), round(self.y)

Here is the code on github (with a few additions)


texts: Planned Economy Bakery - Trying to scale a nested loop with a heap

texts:
Let's say you are living in a controlled economy where there is a baker in town, and every day he bakes a random number of loaves of bread (sometimes the oven breaks, or he has less ingredients). The people in the town queue up to buy a loaf of bread (you can only buy one loaf) based on a pre-assigned ticketing system. Your position in the queue is constant every single day.
There are more people in the queue than loaves of bread available. The bread is ready at different times each day, and some people in the queue need to be at work. If the bread isn't ready before they have to leave for work, they leave the queue and the next person in line takes their place. But they still have their original queue ticket. The values in the people list are the number of hours before the person in the queue has to leave for work
I want to know what is the number on the last ticket given to the baker each day before he runs out of loaves of bread.
I can get my existing code to work for relatively small numbers of people, but if there are millions of people, lots of days (planned economies plan for 5 years ahead), you get the picture.
def BakerQueue(loaves, people, bake_time):
    got_some_bread = []
    for b in bake_time:
        counter = 0
        for p in range(len(people)):
            if people[p] >= b:
                counter += 1
                if counter == loaves:
                    got_some_bread.append(p + 1)
                    counter = 0
                    break
                elif p == len(people) - 1:
                    got_some_bread.append(0)
                    break
            elif counter < loaves and p == len(people) - 1:
                got_some_bread.append(0)
                counter = 0
    return got_some_bread

You can use this to run the code:
in this example, there are 3 loaves, 19 people in the queue [list], and different bake times [list] for each of the days in a week, so on the first day, ticket 1, 2, 3 get loaves, on the second day 2,3,4 get loaves because 1 went to work as the bread wasn't ready in time, on the third day, 7, 9 and 15 get loaves because the bread took 5 hours to be ready and those people went to work. I only care about who gets the last loaf on each day which is what the function is returning.
BakerQueue(3, [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],[1, 2, 5, 4, 5, 4, 7])

This will return as expected
[3, 4, 15, 7, 15, 7, 19]

So I thought about implementing a priority queue using the heapq library, however, I need to maintain the original ticket order, so I thought to create a list of tuples with the values and the index and convert to a heap and pop the top person off of the heap if they have gone to work or if they have gotten a loaf of bread and there are still loaves available. This is the point where I begin to fail. I only care which ticket number got the last loaf of bread each day


texts:
I wrote 2 classes in order to implement some basic cryptography algorithm. I tried to use some object-oriented concepts of C++. I'm a beginner, so any comment or suggestion is welcome.

First class: Message

The header:

#ifndef MESSAGE_H
#define MESSAGE_H

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

class Message
{
   public:
       friend class Chiffre;
       typedef std::vector<char> cryptoContainer;
       // constructors
       Message();
        Message(const std::string&);
        Message(const cryptoContainer&);
        Message(const std::string&, const int&);
        // templates for writing original and crypted messages
        template<typename T>
        int writeOriginalMessage(T& stream) const // return original message in an output stream
        {
            for (auto it = m_originalContent.begin(); it != m_originalContent.end(); it++) stream << *it;
            stream.flush();
            return 0;
        }
        template<typename T>
        int writeCryptedMessage(T& stream) const // return crypted message in an output stream
        {
            if (m_cryptedContent.empty()) return 1;
            for (auto it = m_cryptedContent.begin(); it != m_cryptedContent.end(); it++) stream << *it;
            stream.flush();
            return 0;
        }
        // getters
        cryptoContainer getOriginalMessage(void) const;
        cryptoContainer getCryptedMessage(void) const;
        // destructor
        virtual ~Message();
    protected:
        //protected setter
        void setOriginalMessage(cryptoContainer&);
        void setCryptedMessage(cryptoContainer&);
        //attributes
        int m_key;
        cryptoContainer m_originalContent;
        cryptoContainer m_cryptedContent;
};

#endif // MESSAGE_H

The .cpp file:

#include "Message.h"

Message::Message(const std::string& texte):
    m_key(0),
    m_originalContent(texte.begin(),texte.end())
{

}

Message::Message(const Message::cryptoContainer& texte):
    m_key(0), // default key is 0
    m_originalContent(texte)
{

}

Message::Message(const std::string& texte, const int& clef):
    m_key(clef),
    m_originalContent(texte.begin(),texte.end())
{

}

Message::~Message()
{

}

Message::cryptoContainer Message::getOriginalMessage(void) const
{
    return m_originalContent;
}

Message::cryptoContainer Message::getCryptedMessage(void) const
{
    return m_cryptedContent;
}

void Message::setOriginalMessage(Message::cryptoContainer& msg)
{
    m_originalContent = msg;
    return;
}

void Message::setCryptedMessage(Message::cryptoContainer& msg)
{
    m_cryptedContent = msg;
    return;
}

second class: Chiffre (will implement crypto algorithms)

The header:

#ifndef CHIFFRE_H
#define CHIFFRE_H

#include <vector>
#include "Message.h"

class Chiffre
{
public:
        Chiffre();
        virtual ~Chiffre() = 0;

        static void cesar(Message&, const int&);   // décale un caractère à partir d'une clef (algorithme de César)

};

#endif // CHIFFRE_H

The .cpp file:

#include "Chiffre.h"

Chiffre::Chiffre()
{
}

Chiffre::~Chiffre()
{
}

void Chiffre::cesar(Message& msg, const int& clef)
{
    Message::cryptoContainer res;
    Message::cryptoContainer orig = msg.getOriginalMessage();
    for (auto it = orig.begin(); it != orig.end(); it++) res.push_back(*it + clef);
    msg.Message::setCryptedMessage(res);
    return;
}


texts: Three "alias-functions" in my .bashrc file

texts:
These functions work well for me. Can they be improved or made more standard in some way?

Each function has a documentation header block, which contains a description of what it does, along with example usage and reference links where applicable.

:<<COMMENT
    Alias function for recursive deletion, with are-you-sure prompt.
    Example call:
        srf /home/myusername/django_files/rest_tutorial/rest_venv/

    Short description: Stored in SRF_DESC

    With the following setting, this is *not* added to the history:
        export HISTIGNORE="*rm -r*:srf *"
    - http://superuser.com/questions/232885/can-you-share-wisdom-on-using-histignore-in-bash

    See:
    - y/n prompt: http://stackoverflow.com/a/3232082/2736496
    - Alias w/param: http://stackoverflow.com/a/7131683/2736496
COMMENT
#SRF_DESC: For "aliaf" command (with an 'F'). Must end with a newline.
SRF_DESC="srf [path]: Recursive deletion, with y/n prompt\n"
srf()  {
    #Actual line-breaks required in order to expand the variable.
    #- http://stackoverflow.com/a/4296147/2736496
    read -r -p "About to
sudo rm -rf $1
Are you sure? [y/N] " response
    response=${response,,}    # tolower
    if [[ $response =~ ^(yes|y)$ ]]
    then
        echo -e "sudo rm -rf $1"
        sudo rm -rf "$1";
    else
        echo "Cancelled."
    fi
}

:<<COMMENT
    Delete item from history based on its line number. No prompt.

    Short description: Stored in HX_DESC

    Examples
        hx 112
        hx 3

    See:
    - http://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#HX_DESC: For "aliaf" command (with an 'F'). Must end with a newline.
HX_DESC="hx [linenum]: Delete history item at line number\n"
hx()  {
    history -d "$1";
}

:<<COMMENT
    Deletes all lines from the history that match a search string, with a
    prompt. The history file is then reloaded into memory.

    Short description: Stored in HXF_DESC

    Examples
        hxf "rm -rf"
        hxf ^source

    See:
    - http://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#HXF_DESC: For "aliaf" command (with an 'F'). Must end with a newline.
HXF_DESC="hxf [searchterm]: Delete all history items matching search term, with y/n prompt\n"
hxf()  {
    read -r -p "About to delete all items from history that match \"$1\". Are you sure? [y/N] " response
    response=${response,,}    # tolower
    if [[ $response =~ ^(yes|y)$ ]]
    then
        #Delete all matched items from the file, and duplicate it to a temp
        #location.
        echo -e "grep -v \"$1\" \"$HISTFILE\" > /tmp/history"
        grep -v "$1" "$HISTFILE" > /tmp/history

        #Clear all items in the current sessions history (in memory). This
        #empties out $HISTFILE.
        echo "history -c"
        history -c

        #Overwrite the actual history file with the temp one.
        echo -e "mv /tmp/history \"$HISTFILE\""
        mv /tmp/history "$HISTFILE"

        #Now reload it.
        echo -e "history -r \"$HISTFILE\""
        history -r "$HISTFILE"     #Alternative: exec bash
    else
        echo "Cancelled."
    fi
}


texts: Yet another smart pointer implementation for learning

texts:
I based this implementation on CountedPtr in The C++ Standard Library book by Nicolai Josuttis (page 222) and also available online here.

I know that I can use the C++11 smart pointers but this is a learning exercise and also for some projects an earlier compiler must be used.

I didn't understand the need for the actual reference counter to be a pointer so I just used a standard integer.  Maybe that introduces a bug, not sure.

My main concern is about the object lifecycle.  Does the reference counter as a straight integer cause a bug?  Any feedback will be much appreciated.

Here is the smart pointer class:

#ifndef SMARTPOINTER_HPP__
#define SMARTPOINTER_HPP__

#include <iostream>

template<typename T>
class sp {
public:
   sp(T* ptr) : ptr_(ptr), ref_cnt_(1) {
      std::cout << "sp ctor: " << ptr_ << ", ref_cnt_: " << ref_cnt_ << std::endl;
   }

   T& operator*() { return *ptr_; }

   T* operator->() { return ptr_; }

   sp(const sp<T>& rhs) : ptr_(rhs.ptr_), ref_cnt_(rhs.ref_cnt_) {
      ++ref_cnt_;
      std::cout << "sp copy ctor: " << ptr_ << ", ref_cnt_: " << ref_cnt_ << std::endl;
   }

   sp& operator=(const sp& rhs) {
      if(this != &rhs) {
         *this = rhs;
         ++ref_cnt_;
         std::cout << "sp assignment: " << ptr_ << ", ref_cnt_: " << ref_cnt_ << std::endl;
      }
      return *this;
   }

   ~sp() {
     if(ptr_)
       std::cout << "~sp: " << ptr_ << ", ref count: " << ref_cnt_ << std::endl;
       --ref_cnt_;
       if(ref_cnt_ == 0)
         delete ptr_;
   }

   bool operator==(const T& that) const { return ptr_ == that.ptr_; }
   bool operator==(T* that) const { return ptr_ == that; }

   bool operator!=(const sp& that) const { return ptr_ != that.ptr_; }
   bool operator!=(sp* that) const { return ptr_ != that; }

private:
   T* ptr_;
   unsigned ref_cnt_;
};

#endif //SMARTPOINTER_HPP__

Here is my code to exercise:

#include <iostream>
#include <string.h>

#include "smart_pointer.hpp"

class name {
public:
   name(const char* label) : label_(label) {}

   const char* get_name() const { return label_; }
   unsigned length() const { return strlen(label_); }

private:
  const char* label_;
};

int main() {

   {
      std::cout << "Test with ints\n";
      sp<int> myptr1 = new int(3);
      *myptr1 = 4;
      std::cout << "number: " << *myptr1 << std::endl;

      sp<int> myp2(myptr1);

      sp<int> myp3(myptr1);

      sp<int> myp4 = myptr1;
   }

   {
     std::cout << "Test with name object\n";
     sp<name> myname = new name("Andrew");
     std::cout << myname->get_name() << " has length: " << myname->length() << std::endl;
     sp<name> myname2(myname);
   }

   return 0;
}

I get this output:

Test with ints
sp ctor: 004C7A80, ref_cnt_: 1
number: 4
sp copy ctor: 004C7A80, ref_cnt_: 2
sp copy ctor: 004C7A80, ref_cnt_: 2
sp copy ctor: 004C7A80, ref_cnt_: 2
~sp: 004C7A80, ref count: 2
~sp: 004C7A80, ref count: 2
~sp: 004C7A80, ref count: 2
~sp: 004C7A80, ref count: 1
Test with name object
sp ctor: 004C7A80, ref_cnt_: 1
Andrew has length: 6
sp copy ctor: 004C7A80, ref_cnt_: 2
~sp: 004C7A80, ref count: 2
~sp: 004C7A80, ref count: 1


texts: Skipping over failed imports until they are needed (if ever)

texts:
We have a program with many dependencies. Because the user may not want to use all of them, the program should skip over failed imports and only raise an error if absolutely necessary. e.g. if the user tries to call that class.

I have implemented a way of doing this but I'm not sure it is as good as it could be, it certainly seems somewhat inelegant. I presume there are also some overlooked bugs.

The important file structure is:

Program:
  - engines
    - __init__.py
    - base_engine.py
    - ...
    - psi4.py
    - rdkit.py
  - run.py

The base_engine.py contains the base class Engines which all the other engines (PSI4 in psi4.py, RDKit in rdkit.py ... ) inherit from, as well as a Default class.

If any class fails to import, Default is imported instead, but with the name of the class that failed to import (see the __init__.py file).

base_engine.py:

class Engines:
    """
    Engines base class containing core information that all other engines (PSI4, etc) will have.
    """

    def __init__(self, molecule):

        self.molecule = molecule

class Default:
    """
    If there is an import error, this class replaces the class which failed to be imported.
    Then, only if initialised, an import error will be raised notifying the user of a failed call.
    """

    def __init__(self, *args, **kwargs):
        # self.name is set when the failed-to-import class is set to Default.
        raise ImportError(
            f'The class {self.name} you tried to call is not importable; '
            f'this is likely due to it not being installed.')

__init__.py:

try:
    from .psi4 import PSI4
except ImportError:
    from .base_engine import Default as PSI4
    setattr(PSI4, 'name', 'PSI4')

try:
    from .rdkit import RDKit
except ImportError:
    from .base_engine import Default as RDKit
    setattr(RDKit, 'name', 'RDKit')

psi4.py:

from Program.engines.base_engine import Engines

# Example import that would fail
import abcdefg

class PSI4(Engines):
    """
    Writes and executes input files for psi4.
    """

    def __init__(self, molecule):

        super().__init__(molecule)

    def generate_input(self):

        ...

run.py:

from Program.engines import PSI4

PSI4('example_molecule').generate_input()

So now when classes are imported at the top of the run.py file, there is no problem even if there's an import error; if there's a failed import with PSI4 because abcdefg cannot be imported, Default is simply imported as PSI4 and given the name PSI4 via the setattr().

Then, only if that Default class is called the ImportError is raised and the user can see that the issue was with PSI4.

This seems to work quite well, even when there are multiple failed imports. We can also add extended error messages for each different failed import. Is this the best way of doing something like this, though? It gets quite messy since we have so many files in our engines package.

Please let me know if some relevant code has been omitted and I can add it back. Thanks for any help.

EDIT for @jpmc26:

I appreciate the time spent on your post but it's not practical for us. The program still fails fast (when necessary) because the imports are first initialised when configs are set. We have ~12 (large) stages of execution, each with multiple options which are handled by these configs. We handle this by reading the configs and terminal commands and calling whatever the option is e.g. EngineForStageFive = PSI4 is set from the configs, then we just call EngineForStageFive(args).do_something() where do_something() exists for all of the stage five classes available. All of this is nicely handled by our terminal command and config file interpreters.

The PSI4 class for example is called many times and repeatedly calling for its import with some additional logic is not what we want in our run file. We'd end up repeating a lot of code unnecessarily. e.g. every stage would need a long if/elif chain or dictionary to determine how it would be used.


texts: Python - Activity Selection - Greedy Algorithm

texts:
I've done this activity selection piece of code, which is a greedy approach. I need some feedback/suggestions.

# Python 3
import random
import operator
begin = [random.randint(1, 10) for i in range(10)]
end = [x + random.randint(1, 4) for x in begin]
pair = sorted(list(zip(begin, end)), key=operator.itemgetter(1))
ls = list()
ls.append(pair[0])
for i in pair[1:]:
    if i[0] >= ls[-1][1]:
        ls.append(i)
print(ls, '>>>', len(ls), 'out of', len(pair), 'activities.')


texts:
I have written the following class to allow me to uniquely identify classes in C++, and I was wondering if there are any better ways of going about it.

#ifndef _TYPE_IDENTIFIER_H_
#define _TYPE_IDENTIFIER_H_

typedef std::size_t Identifier;

class TypeIdentifier {
public:
    template<class T>
    static Identifier get_identifier() {
        static const Identifier current_identifier = ++next_identifier;

        return current_identifier;
    }

private:
    static Identifier next_identifier;
};

Identifier TypeIdentifier::next_identifier = 0;

#endif

And an example of using it:

class MyFirstClass {};
class MySecondClass {};

printf("%zu", TypeIdentifier::get_identifier<MyFirstClass>()); // 1
printf("%zu", TypeIdentifier::get_identifier<MySecondClass>()); // 2

printf("%zu", TypeIdentifier::get_identifier<MySecondClass>()); // 2
printf("%zu", TypeIdentifier::get_identifier<MyFirstClass>()); // 1

I'm using it in an ECS, where there can only be one instance of a certain component in an Entity. I store a vector of structs containing a void pointer to the component and an Identifier type of the component. Using TypeIdentifier::get_identifier<ComponentType>(), I can check the type of a passed component and check if it's already present in the Entity.


texts:
How to open an input file programmatically (javascript) in a reliably way?

The most modern versions of internet browsers prevent the opening of input files programmatically (javascript) under certain circumstances. For this reason I opened this thread to define a way to open input files so that we have no problems - or at least mitigate that risk - in future versions of internet browsers.

PLUS:

Some statements made in foruns (see references):

1

  Yes, you can programmatically click the input element using jQuery
  (JavaScript), but only if you do it in an event handler belonging to
  an event THAT WAS STARTED BY THE USER.

2

  The function must be part of a user activation such as a click event.
  Attempting to open the file dialog without user activation will fail.

A little example (for illustration only):

Notice the comments in the code.

Apparently the safest way to open an input file is create this element dynamically.

We also have the approach using .trigger("click") (worked) and .click() (did not work). I couldn't understand why trigger worked and click didn't, because apparently they do the same thing.

IMPORTANT: For me there is no guarantee that the "trigger" solution will continue to work in future versions of "Chrome" or even other "browsers" like "Firefox". That is why I think it is important to find a safe way to resolve this issue.

    OPEN FILE DIALOG
    <input type="file"/>

[Refs.: https://stackoverflow.com/a/43174934/3223785 ,
https://stackoverflow.com/a/21583865/3223785 ,
https://mariusschulz.com/blog/programmatically-opening-a-file-dialog-with-javascript ,
https://www.freecodecamp.org/forum/t/jquery-trigger-click-event-not-the-same-as-a-real-click/170745/3 ]


texts: Updating user log in time while he logs in to the web page

texts:
My intention is to store the user's last login date and time when he logs in to the web page. I pass his username and password to the stored procedure to check whether is it correct or not! I believe it'll be fine to store his last login date and time if any record matches.

USE [DBNAME]
GO
/****** Object:  StoredProcedure [dbo].[WP_LogInUser]    Script Date: 27-Apr-15 4:09:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[WP_LogInUser]
    @Username   Nvarchar(100),
    @Password   Nvarchar(100)

as
Begin
    if exists(Select Username from TableName where Username=@Username and UserPassword=@Password)
        Begin
            Update TableName Set UserLastLogin = GETUTCDATE() where Username=@Username and UserPassword=@Password and IsActive = 1
            Select UserID, Username, UserEmail, UserFullName, UserType from TableName where Username=@Username and UserPassword=@Password and IsActive = 1
        End
End

What do you think about it? Is it okay? Or can I make this even better?


texts: Return characters in a string in alphabetical order

texts:
Problem

  Take a string and return all input characters in alphabetical order
  Assume that no numbers or punctuation will be used
  For the same character, uppercase characters should be returned before lowercase characters
  Do not use the sorted helper method
  Do not use any libraries that are not included with Python 3.6.1

For example, alphabetize(HelLo) should return eHLlo

Approach

Create a 26-element list. This list will represent the counts (uppercase
and lowercase) of the different alphabetical characters seen via a dictionary
Iterate through the characters in the input string

Get the index for each character by subtracting the int values
of the lowercase character from the int value of a
Get the existing count for that index & case from the counts
dictionary
Increment the count by 1

Initialize the return string
Iterate through each element in the list

For each dictionary / element, get the character, and get the
uppercase and lowercase counts
Add the uppercase characters to the return string
Add the lowercase characters to the return string

Return the alphabetized string

Implementation Discussion

I know the 'Pythonic' way to accomplish this is something like
''.join(sorted(myString)).

However, as somebody trying to learn Python, I wanted to use this exercise
to learn more about strings and characters in Python (for example)
vs. Googling a one-liner (not that there's anything wrong with that).

Things I'm concerned about:

Should this be a class? Or is it ok as a standalone method? (As
somebody that is more comfortable in Java, things that aren't in classes
make me irrationally uneasy.)
Speaking of which, there's a decent amount of stuff going on in this
method, should I break it up?

If I decide to break it up, what's the right way of 'showing' that
some functions are only going to be used by another function?
I think Python doesn't really have a concept of private vs.
public so do I _(some_method_name) here?

What other 'Pythonic' elements am I missing (again, aside from using
the sorted method)?

Implementation

def alphabetize(value):
    uppercase_key = 'uppercase'
    lowercase_key = 'lowercase'

    character_counts = []
    for i in range(26):
        character_counts.append({uppercase_key: 0, lowercase_key: 0}.copy())

    for character in value:
        index = ord(character.lower()) - ord('a')
        counts = character_counts[index]
        key = uppercase_key if character.isupper() else lowercase_key

        count = counts[key]
        counts[key] = count + 1

    alphabetized = ''
    for index, counts in enumerate(character_counts):
        character = chr(ord('a') + index)
        uppercase_counts = counts[uppercase_key]
        lowercase_counts = counts[lowercase_key]
        for i in range(uppercase_counts):
            alphabetized += character.upper()
        for i in range(lowercase_counts):
            alphabetized += character

    return alphabetized


texts:
I'm new to Groovy but have some experience with Java, C and Python. I'd appreciate your feedback on Groovy style and features in this FizzBuzz code.

Review Checklist

Is it idiomatic Groovy code?
Can anything be taken away?
Can it be more functional?
Could I make use of any Groovy-specific features?

FizzBuzzTest.groovy

import org.fizzbuzz.FizzBuzz
import org.junit.Before
import org.junit.Test

class FizzBuzzTest {

    FizzBuzz fb

    @Before
    void setUp() {
        fb = new FizzBuzz()
    }

    @Test
    void testGiven1Returns1AsString() {
        assert '1' == fb.toString(1)
    }

    @Test
    void testGiven2Returns2AsString() {
        assert '2' == fb.toString(2)
    }

    @Test
    void testGiven3ReturnsFizz() {
        assert 'Fizz' == fb.toString(3)
    }

    @Test
    void testGiven5ReturnsBuzz() {
        assert 'Buzz' == fb.toString(5)
    }

    @Test
    void testGiven15ReturnsFizzBuzz() {
        assert 'FizzBuzz' == fb.toString(15)
    }
}

FizzBuzz.groovy

package org.fizzbuzz

class FizzBuzz {

    String toString(number) {
        if (isMultipleOf3(number) && isMultipleOf5(number))
            return 'FizzBuzz'
        if (isMultipleOf3(number))
            return 'Fizz'
        if (isMultipleOf5(number))
            return 'Buzz'
        number.toString()
    }

    private boolean isMultipleOf5(number) {
        isMultipleOf.curry(5)(number)
    }

    private boolean isMultipleOf3(number) {
        isMultipleOf.curry(3)(number)
    }

    private def isMultipleOf = { int multipleOf, number ->
        number % multipleOf == 0
    }

    static void main(String... args) {
        def fb = new FizzBuzz()
        for (num in 1..100) {
            println fb.toString(num)
        }
    }

}


texts: Changing object attributes by calling getters and setters using reflection

texts:
We have a class with 10 attributes (longs, Strings) the following method should change any attribute to any value of an object specified by the client,

It mimics the SQL update statement Update Users Set username = 'newValue' where id = 5

the user will provide the 4 variables id = 5 to find the object and username = newValue to change its username.

The method :

 public static void usersUpdate( String attributeToBeChanged, String newAttributeValue, String whereKey ,String whereValue) throws Exception{

        Method getter=getDeclaredMethodIgnoreCase(User.class,"get"+whereKey);

        HashMap<String,User> refToUsersCache= usersCache.getUsersCache(); // The objects are stored in this map as <username,User Object>
        User requiredUser = null;

        for(String user: refToUsersCache.keySet()) { // loop through the hashmap and call its getter to check its "ID" or any attribute
            if (getter.invoke(refToUsersCache.get(user)).equals(whereValue))  // getID() == "5" (in our example)
                requiredUser = refToUsersCache.get(user); // this is the required object
        }

        Method setter=getDeclaredMethodIgnoreCase(User.class,"set"+attributeToBeChanged);
        setter.invoke(requiredUser,newAttributeValue); // change the username = "newValue"

);

attributeToBeChanged = username

newAttributeValue= newValue

whereKey= id

whereValue = 5


texts: Using/storing server-side data on the client side

texts:
I've a slot booking script which is as follows:

My Current Algorithm

A calendar is shown to the user
The user clicks on a date
I make an ajax call to determine if at least 1 slot is booked on the
clicked date
I return back a form from the ajax page ("Time To", "Time
From", "Event Name" etc; form along with a hidden input whose value
is "1" if at least 1 slot is booked or "0" if no booking is done for
that day. This hidden input will be used a flag at a later stage)
The user then enters/selects values in the form and clicks "Book"
Upon the click of the "Book" button, I check the value of the hidden
input via javascript
If it is "0", I return true so that the form goes for submission (As there is not even a single slot booked on that day, there is no need to validate if the chosen time slot is booked or not)
If the value is "1", I run another ajax call to validate whether the time slot selected by the user is free, and if not I return false and display message to user stating the slot is already booked

Now this is where my problem arises. Since the value of the hidden input can be easily manipulated through Firebug before the Book button is clicked, I'm wondering what other way can I set the flag which will be tamper proof by the user.

HTML

JavaScript

// executed upon clicking on a date
$("#calendar .day").on("click", function () {
    var clicked_date = $(this).find("input").val();
    $.ajax({
        type: 'post',
        url: 'set-flag.php',
        data: {
            dt: clicked_date
        },
        success: function (data) {
            $("#booking-form").html(data);
        }
    });
});

//executed upon clicking "Book Date"
$("form#booking-form").on("submit", function ()
{
    var flag = $(this).find("input:hidden").val();
    if (flag == 0) // form can be submitted
    {
        return true;
    }
    else
    {
        $.ajax({
            type: 'post',
            url: 'check-slot-availability.php',
            context:this,
            data: {
                // parameters containing date clicked, time from, and time to values
            },
            success: function (data) {
                if($.trim(data) == 0) // slot already booked
                {
                    // show message to user to select another time slot
                }
                else // form can be submitted
                {
                    this.submit();
                }
            }
        });
    }
    return false;
});

set-flag.php

$clicked_date = safe($_POST['dt']);
/* perform db operations
.
.
.
*/
if($db->num_rows() > 0) // at least 1 slot is booked on selected day
{
   $flag = 1;
}
else
{
   flag = 0;
}

$form = '<form id="booking-form.php" action="some-page.php" method="post">';
$form .= 'Time From : <select></select>';
$form .= 'Time To : <select></select>';
$form .= '<input type="hidden" value="'.$flag.'" />';
$form .= '<input type="submit" value="Book" />';
$form .= '</form>';
echo $form;
exit;


texts: Using pandas and sklearn for forecasting stock market return

texts:
I have been using R for stock analysis and machine learning purpose but read somewhere that python is lot faster than R, so I am trying to learn Python for that.

I am using Yhat's rodeo IDE (Python alternative for Rstudio), Pandas as a dataframe, and sklearn for machine learning.

This is the code I wrote for forecasting one day return:

#importing necessary packages
from pandas.io.data import DataReader
from datetime import datetime
from sklearn import svm
from sklearn.metrics import accuracy_score

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

#downloading data from yahoo
ibm = DataReader('IBM',  'yahoo', datetime(2000,1,1), datetime(2012,1,1))
ibm.info()
ibm.dtypes
ibm.describe()
list(ibm)
ibm.shape

df=ibm['Close']

#arithematic return
ret = df.pct_change()

#geomatric return
#gret = np.log(1 + ret)

ret.head()

#lagged return features
X=pd.concat([ret.shift(1),ret.shift(2),ret.shift(3),ret.shift(4)],axis=1)
X.head()

#tomorrows return
Y=ret.shift(-1)
Y.head()

#combining featrues and target
col=pd.concat([X,Y],axis=1)
col.head()

#removing NaN values
col=col.dropna()

#creating separte features and target variable
feat=col.iloc[:, [i for i in range(col.shape[1]) if i != 4]]
target=col.iloc[:,4]

#training features and target for machine learnging
trainfeat=feat[1:2000]
traintrgt=target[1:2000]

#testing features and target for machine learnging
testfeat=feat[2001:]
testtrgt=target[2001:]

#Support vector regression
clf = svm.SVR()

#training
clf.fit(trainfeat, traintrgt)

#prediction
prd=clf.predict(testfeat)

#accuracy_score
#testnp = testtrgt.as_matrix()
#accuracy_score(testnp,prd)


texts:
I read that if an object is made using the init it must be released, but if it's something like this  elementFormula = [[NSMutableString  stringWithString:@""] it is autoreleased. However, there are some other aspects of memory management that confuse me.

For example, something like [[NSMutableString  stringWithString:@""] retain]  If I retain an autoreleased object, do I have to release it myself, or is it still autoreleased? Also, if I declare a pointer to an object in the .h and assign it a value in the .m like so     completeFormula = [self synthesizeFormula]; without going through the init process, do I have to release completeFormula?

Those are my main concerns, but I have posted the entire code below if needed.

@interface EquationTextField : UIView <KeyInput> {

FormulaKeyboard *keyboard;
int consecutiveElementCount;
int subscriptLength;
int chargeIndex;
NSMutableString *elementFormula;
NSString *lastElementPressed;
NSString *charge;
NSString *state;
NSString *completeFormula;
}

init {

      NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:@"FormulaKeyboard"     owner:self options:nil];

    for (id object in bundle) {
        if ([object isKindOfClass:[FormulaKeyboard class]])
            keyboard = (FormulaKeyboard *)object;
    }

    self.inputView = keyboard;
    keyboard.delegate = self;

    elementFormula = [[NSMutableString  stringWithString:@""] retain];
    charge = [[NSString alloc] initWithString:@""];
    state = [[NSString alloc] initWithString:@""];

}

 - (void)addElement:(NSString *)currentElement {

if (![currentElement isEqualToString:lastElementPressed])  {

    // when new element is pressed

    [elementFormula appendString:currentElement];
    lastElementPressed = currentElement;
    consecutiveElementCount = 1;

}

else if ([currentElement isEqualToString:lastElementPressed]) {

    // when element is pressed consecutively

    if (consecutiveElementCount == 1) {

        // since there is no '1' subscript, nothing needs to be deleted

        [elementFormula appendString:@"₂"];
        subscriptLength = 1;

    }

    if (consecutiveElementCount > 1) {

        // deletes last subscript and replaces it with new subscript

        NSArray *subscriptList = [[[NSArray alloc] initWithObjects:@"₂", @"₃", @"₄", @"₅", @"₆", @"₇", @"₈", @"₉", @"₁₀", @"₁₁", @"₁₂", nil] autorelease];

        NSRange range = NSMakeRange (([elementFormula length] - subscriptLength), subscriptLength);

        [elementFormula deleteCharactersInRange:range];

        NSString *tempSubscript = [subscriptList objectAtIndex:consecutiveElementCount - 1];
        [elementFormula appendString:tempSubscript];

        subscriptLength = [tempSubscript length];

    }

    if (consecutiveElementCount < 11)
        consecutiveElementCount ++;

}

completeFormula = [self synthesizeFormula];

 }

- (void)changeCharge:(NSString *)chargeIncrease {

NSArray *chargeList = [[[NSArray alloc] initWithObjects:@"⁴⁻", @"³⁻", @"²⁻", @"⁻", @"", @"⁺", @"²⁺", @"³⁺", @"⁴⁺", nil] autorelease];

if ([chargeIncrease isEqualToString:@"+"]) {

    chargeIndex += 1;
    charge = [chargeList objectAtIndex:chargeIndex];

}

else if ([chargeIncrease isEqualToString:@"-"]) {

    chargeIndex -= 1;
    charge = [chargeList objectAtIndex:chargeIndex];

}

completeFormula = [self synthesizeFormula];

}

- (void) changeState:(NSString *)stateName {

state = stateName;

completeFormula = [self synthesizeFormula];

}

- (NSString *)synthesizeFormula {

NSMutableString *synthesizedFormula = [[[NSMutableString alloc] initWithString:elementFormula] autorelease];
[synthesizedFormula appendString:charge];
[synthesizedFormula appendString:state];

return synthesizedFormula;
}

- (void)dealloc
{
[charge release];
[state release];
self.inputView = nil;
keyboard.delegate = nil;
[keyboard release];
[super dealloc];
}


texts: Dynamic Official Receipt increment algorithm

texts:
I made a function that would automatically generate official receipt for POS. it is able to accept format such as xxx, xxx-xxx, xx-xx.

But my code is really messy and horrible and it needs review. I would really appreciate for corrections, recommendations and critiques to improve this.

The flow would be:

Get the last official receipt number OR, if none use specified system default.
If there is a provided format, use it. and read the last number according to its format
Split it, convert it to int and increment it.
Check it doesn't exist yet.
Return the next official receipt number

I'm using Django/Python. If it needs explanation please comment and I will explain the best way I can.

try:
    user = request.user.id
    official_receipt = {}
    default = {}
    company = get_current_company(request)

    or_from_last_transaction = ""
    or_from_default_company = ""

    try:
        try:
            official_receipt = Pointofsale.objects.filter(company=company,is_or_manual=False).values('official_receipt').order_by('-official_receipt').first()
        except Exception as e:
            or_from_last_transaction = '10000'
        else:
            pass
        finally:
            or_from_last_transaction = official_receipt['official_receipt']
        try:
            POS_settings.objects.filter(company=company).exists()
        except POS_settings.DoesNotExist:
            pass
        else:
            or_from_default_company = '00000'
        finally:
            default_company = POS_settings.objects.filter(company=company).values().first()
            if default_company['is_or_per_company']:
                or_from_default_company = default_company['pos_official_receipt']
            else:
                or_from_default_company = None

    except Exception as e:
        official_receipt = '30000'
    else:
        pass
    finally:
        official_receipt = or_from_default_company if or_from_default_company else or_from_last_transaction

    stop = True
    duplicate_add = 0

    if any(c.isalpha() for c in official_receipt):
        return 'Incorrect OR Format'

    while stop:
        str_group = official_receipt.split("-")
        str_length = len(official_receipt)
        group_length = int(len(str_group))

        for index, group in reversed(list(enumerate(str_group))):
            limit = len(group)
            group = int(group)
            group += 1
            if len(str(group)) > limit:
                if index == 0:
                    str_group[index] = group
                else:
                    str_group[index] = 0
            else:
                str_group[index] = int(str_group[index]) + (1 + duplicate_add)
                str_group[index] = str(str_group[index]).zfill(limit)
                break

        next_official_receipt = ''
        for group in str_group:
            next_official_receipt += str(group)
            next_official_receipt += '-'

        next_official_receipt = next_official_receipt[0:len(next_official_receipt)-1]
        if Pointofsale.objects.filter(official_receipt=next_official_receipt,company=company).exists():
            stop = True
            duplicate_add += 1
        else:
            stop = False
    return next_official_receipt
except Exception as e:
    print(e)
    return e


texts: using (IDisposable) in c# factory pattern

texts:
How will this example affect the using implementation in GetSite?

public abstract class SPSiteBase
{
    protected abstract string Url { get; set; }

    public abstract SPSite GetSite(string url = null);
}

public class SPSiteFactory : SPSiteBase
{
    protected override sealed string Url { get; set; }

    public override SPSite GetSite(string url = null)
    {
        using (SPSite site = new SPSite(string.IsNullOrEmpty(url) ? Url : url))
        {
            return site;
        }
    }

    public SPSiteFactory() { }

    public SPSiteFactory(string url)
    {
        Url = url;
    }
}

I call it like this

SPSiteFactory siteFactory = new SPSiteFactory("http://portalurl/");
SPSite site = siteFactory.GetSite();

I've noticed that the code steps out of the using after I run the siteFactory.GetSite() method but will the site ever be disposed?


texts:
I have written some Assembly code for an assignment, that has me activating the outer bounds of a 7-segment display.
The toggle is every time there is a state change, so both when I flick a switch, and when the switch is returned.
The microcontroller I have programmed is an ATMega32.
How can I make this code more 'crisp'? It looks overly complicated, but I can't seem to figure out how to simplify it. Thanks!

.include "m32def.inc"

init:
.DEF    counter=R19
.DEF    switch=R30

reset:
; setup port B (output)
ldi R16, 255
out DDRB, R16 ; setup PORTB as output
out PORTB, R16

; setup port C (input)
ldi R16, 0x00
out DDRC, R16
com R16
out PORTC, R16

ldi R19, 0

pinsetup:
in  switch, PINC
delay:
nop
dec R20
brne    delay
in  R16, PINC
cp  R16, switch
brne    pinsetup

rjmp    main

main:
in  R16, PINC   ; indlæs pins i r16
ldi R20, 100
delay2:
nop
dec R20
brne    delay2
in  R17, PINC   ; indlæs pins i r17
cp  R16, R17
brne    main
cp  R16, switch
brne    count
rjmp    main

count:
mov switch, R16
cpi counter, 0
breq    outa

cpi counter, 1
breq    outb

cpi counter, 2
breq    outc

cpi counter, 3
breq    outd

cpi counter, 4
breq    oute

cpi counter, 5
breq    outf

outa:
ldi R18, 8; load a's værdi ind i R18
com R18
out PORTB, R18
inc counter
rjmp    main

outb:
ldi R18, 4; load b's værdi ind i R18
com R18
out PORTB, R18
inc counter
rjmp    main

outc:
ldi R18, 2; load c's værdi ind i R18
com R18
out PORTB, R18
inc counter
rjmp    main

outd:
ldi R18, 1; load d's værdi ind i R18
com R18
out PORTB, R18
inc counter
rjmp    main

oute:
ldi R18, 16; load e's værdi ind i R18
com R18
out PORTB, R18
inc counter
rjmp    main

outf:
ldi R18, 64; load f's værdi ind i R18
com R18
out PORTB, R18
dec counter
dec counter
dec counter
dec counter
dec counter
rjmp    main


texts:
Please review my first query project. It achieves the desired result, but am I doing it right?

window.onresize = centreBoxInViewport;

function displayLightBox(obj) {

    // Get the path to the image
    var path = obj.getAttribute("href");

    // Create a new image, and set its source.
    var image = new Image();

    // The onload function must come before we set the image's src, see link for explanation.
    // http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called.

    // Anonymous function set to onload event, to make sure we only proceed if the image has been loaded.
    image.onload = function() {
        $('#image').attr("src", path)
        centreBoxInViewport();
        showOverlay();

        // Bind the hide functions here, as the elements have now been loaded into the DOM.
        $('#overlay').click(hideLightBox);
    };

    // Set the src, and show the image.
    image.src = path;
}

function hideLightBox() {
    fadeBox();
}

function showBox(){
    $('#lightbox').fadeTo(200, 1);
}

function fadeBox(){
    $('#lightbox').fadeTo(200, 0, function() {
        $('#lightbox').hide();
        hideOverlay();
    });
}

function centreBoxInViewport() {
    // Get the dimensions of the viewport.
    height = $(window).height()
    width = $(window).width();

    // Position the box.
    $('#lightbox').css('top', (height/2) - parseInt($('#lightbox').height())/2);
    $('#lightbox').css('left', (width/2) - parseInt($('#lightbox').width())/2);

}

function showOverlay() {
    $('#overlay').fadeTo(200, 0.5, function() { showBox() });
}

function hideOverlay() {
    $('#overlay').fadeTo(200, 0, function() {
        $('#overlay').hide();
    });
}

HTML

CSS

div#overlay { position: fixed; background-color:#000000; top: 0px; left: 0px; width: 100%; height: 100%; z-index: 99; }
div#lightbox { background-color: white; border: 5px solid white; z-index: 100; position: fixed; }


texts: Writing a user's profile image to disk using nested Node.JS closures

texts:
I am writing non-blocking code as it should be in Node.JS. If I want run function A after B I do it using callback.

But I find this style guide:

  Use closures, but don't nest them. Otherwise your code will become a
  mess.

  Right:

setTimeout(function() {
  client.connect(afterConnect);
}, 1000);

function afterConnect() {
  console.log('winning');
}

  Wrong:

setTimeout(function() {
  client.connect(function() {
    console.log('losing');
  });
}, 1000);

How deep should my closures be? Specifically, I'd like to consider this sample:

exports.profileImage = function(req, res) {
    var id = req.params.user_id;
    userProvider.get(id, function(err, user){
        if (err) throw err;
        userProvider.getImageById(user['image_id'], function(err, image) {
            if (err) throw err;
            userProvider.writeImageToDisk(image, function(err, path){
                if (err) throw err;
                res.sendfile(path);
            });
        });
    });
};


texts:
Before implementing a GUI I tried performing it at CLI first and I also tried to implement it by using calling methods to another class.

BinaryConversion class:

import java.io.IOException;
import static java.lang.System.in;
import java.util.InputMismatchException;
import java.util.Scanner;

public class BinaryConversion{

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

        try (Scanner in = new Scanner(System.in)) {

            System.out.print("Enter given: ");
                int givenNum = in.nextInt();
            System.out.println("Binary: " + convert.getBinary(givenNum));
            System.out.println("Octal:  " + convert.getOctal(givenNum));
            System.out.println("Hex:    " + convert.getHex(givenNum));

        } catch(InputMismatchException e) {

            System.out.println("Looks like you entered a non integer value.");

        } finally {

            in.close();

        }
    }
}

Convert class:

public final class convert{

    private convert() {
        // removes the default constructor
    }

    public static String getBinary(int given) {
        char binNumbers[] = {'0','1'};
        String str = "";
        int rem;
            while (given > 0) {
                rem = given % 2;
                str = binNumbers[rem] + str;
                given /= 2;
            }
        return str;
    }

    public static String getOctal(int given) {
       char octalNumbers[] = {'0','1','2','3','4','5','6','7'};
       String str = "";
       int rem;
           while (given > 0) {
               rem = given % 8;
               str = octalNumbers[rem] + str;
               given /= 8;
            }
       return str;
    }

    public static String getHex(int given) {
        char hexNumbers[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        String str = "";
        int rem;
            while(given > 0){
                rem = given % 16;
                str = hexNumbers[rem] + str;
                given /= 16;
            }
        return str;
    }
}

My questions are:

Did I missed something?
Is there a more efficient implementation of this program?


texts:
After realizing that I was spending a lot of time getting the latest version of Chromium, I figured I would throw together a quick script. Over time, I wanted to make the script more efficient, cleaner, and pythonic. Here is what I came up with:

from zipfile import ZipFile
from os import rename, remove, path
from shutil import rmtree, copytree
from httplib2 import Http
from sys import argv, exit
from easygui import indexbox

h = Http('.cache')
saveDir = 'C:\\Program Files\\Chromium\\'

def getLatestVersion():
    verSite = ('http://build.chromium.org/f/chromium/snapshots/' +
            'Win/LATEST')
    re, ver = h.request(verSite)
    ver = str(ver, encoding='utf8')
    return ver

def delCurrent():
    try:
        rmtree(path.join(saveDir, 'Current'))
    except Exception:
        print('Chromium could not be removed.')

def delBackup():
    try:
        rmtree(path.join(saveDir, 'Backup'))
    except Exception:
        print('Backup could not be removed.')

def downloadChromium(ver):
    site = ('http://build.chromium.org/buildbot/snapshots/Win/'
            + ver + '/chrome-win32.zip')
    re, chrome = h.request(site)
    file = open(path.join(saveDir, 'latest.zip'), 'wb')
    file.write(chrome)
    file.close()

def unzip():
    zip = ZipFile(saveDir + 'latest.zip', 'r')
    zip.extractall(saveDir)
    rename(path.join(saveDir, 'chrome-win32'), path.join(saveDir, 'Current'))
    zip.close()
    remove(path.join(saveDir, 'latest.zip'))

def revert():
    delCurrent()
    copytree(path.join(saveDir, 'Backup'), path.join(saveDir, 'Current'))

def backup():
    delBackup()
    copytree(path.join(saveDir, 'Current'), path.join(saveDir, 'Backup'))

def gui():
    ver = getLatestVersion()
    choices = ['Download version %s' % ver, 'Backup', 'Revert', 'Exit']
    choice = indexbox('What do you want to do?',
            'Chromium Downloader', choices)
    if choice == 0:
        delCurrent()
        downloadChromium(ver)
        unzip()
    elif choice == 1:
        backup()
    elif choice == 2:
        revert()
    elif choice == 3:
        exit()
    gui()

def usage():
    print('-h         Display help text\n' +
          '-g         Launches the GUI Program\n' +
          '-v         Only gets the version\n' +
          '-r         Reverts to last backup\n' +
          '-b         Saves a new backup\n' +
          '-o         Specify version to download\n')

def main():
    if '-g' in argv:
        gui()
        exit()
    elif '-h' in argv:
        usage()
        exit(2)
    elif '-r' in argv:
        revert()
        exit()

    if '-o' in argv:
        ver = argv.index('-o') + 1
    else:
        ver = getLatestVersion()
        print('Latest Version: ', ver)
    if '-v' in argv:
        exit()

    delCurrent()
    downloadChromium(ver)
    unzip()

    if '-b' in argv:
        backup()

if __name__ == "__main__":
    main()

Are there any major things that should be changed to make this code better?


texts:
I have created this class to simulate a thread-safe Singleton.

Have I missed anything?

#include <boost/thread/mutex.hpp>

class Singleton
{
public:
  static Singleton& GetInstance()
  {
    boost::mutex::scoped_lock lock(m_mutex);
    static Singleton instance;
    return instance;
  }

private:
  static boost::mutex m_mutex;

  Singleton() {}
  ~Singleton() {}

  Singleton(const Singleton&);
  const Singleton& operator=(const Singleton&);
};


texts:
I am trying to implement the F1 score shown here in Python.

The inputs for my function are a list of predictions and a list of actual correct values.  I thought that the most efficient way of calculating the number of true positive, false negatives and false positives would be to convert the two lists into two sets then use set intersection and differences to find the quantities of interest.  Here is my code

def F1_score(tags,predicted):

    tags=set(tags)
    predicted=set(predicted)

    tp=len(tags.intersection(predicted))
    fp=len(predicted.difference(tags))
    fn=len(tags.difference(predicted))

    if tp>0:
        precision=float(tp)/(tp+fp)
        recall=float(tp)/(tp+fn)

        return 2*((precision*recall)/(precision+recall))
    else:
        return 0


texts: A small api that delays api requests using async/await with Node.js

texts:
I spent a good couple hours troubleshooting a bug where the yelp-fusion api said I was sending too many requests per second, so I finally found a way to delay each api request to make it work. Please take a look at the code and give me any tips you have. I'd like to see how this could be done in a better way if possible.

Here is my server.js where post requests come through:

  //handle post requests for getting yelp data
  app.post('/post', async function(req, res) {
    let yelpInData = []
    let result = null;
    req.body.forEach((item) => {
      yelpInData.push(item);
    });

    result = await handleYelp(yelpInData);
    //send data back to the front end
    res.send(result);

  });

  //handle yelp api
  async function handleYelp(yelpInData) {
    let yelpData = [];

    for (let i = 0, len = yelpInData.length; i < len; i++) {
      let result = await searchPlace(yelpInData[i]);
      yelpData.push(result);
    }
    //  console.log(yelpData);
    return yelpData;

  }

  function searchPlace(city) {
    //console.log(city)
    return new Promise((resolve) => {
      setTimeout(() => {
        let coords = city.coords.lat + "," + city.coords.lng;
        let name = city.name;

        client.search({term: name, location: coords}).then(response => {

          //name, img url, review count, rating, price, location.display address, is closed,phone
          resolve({
            name: response.jsonBody.businesses[0].name,
            img: response.jsonBody.businesses[0].image_url,
            hours: response.jsonBody.businesses[0].is_closed,
            revcount: response.jsonBody.businesses[0].review_count,
            rating: response.jsonBody.businesses[0].rating,
            price: response.jsonBody.businesses[0].price,
            location: response.jsonBody.businesses[0].location.display_address.toString(),
            phone: response.jsonBody.businesses[0].display_phone,
            url: response.jsonBody.businesses[0].url
          });

        }).catch(e => {
          console.log(e);
        });
      }, 100);
    })
  }

Is setTimeout a good idea for delaying the api requests to yelp or is there a different way to delay? Here is the git repo if you want to run the web app: https://github.com/capozzic1/knockout_map


texts:
I tried to code the fizzbuzz program following the functional programming rules in javascript. Please check my code and give feedback. thank you.
const isDivisible = (number, fizz) => number % fizz === 0;
const getSubstitutes = (
  number,
  substitutes,
  { currentIndex = 0, result = "" } = {}
) => {
  if (currentIndex === substitutes.length) return result;
  const { divisor, substitute } = substitutes[currentIndex];
  const newResult = result + (isDivisible(number, divisor) ? substitute : "");
  return getSubstitutes(number, substitutes, {
        currentIndex: currentIndex + 1,
        result: newResult,
  });
};
const fizzBuzz = (number, substitutes, currentIndex = 1) => {
  if (number < currentIndex) return;
  console.log(getSubstitutes(currentIndex, substitutes) || currentIndex);
  fizzBuzz(number, substitutes, ++currentIndex);
};
const substitutes = [
  {
        divisor: 3,
        substitute: "fizz",
  },
  {
        divisor: 5,
        substitute: "buzz",
  },
];
fizzBuzz(100, substitutes);


texts:
My intention is to separate components on a file basis. For example, I want a specific controller to have it's own file (Same goes with services, filters and directives). Of course, files will be group together based on the module they will fall into.

Here's an overview of what I currently have:

Directory

User/
    User/UserModule.js
    User/UserDirective.js
    User/UserService.js
    User/UserFilter.js
    User/UserController.js

UserModules.js

UserModule = angular.module('UserModule', []);

UserModule.controller('userCtrl', ['$scope', 'UserService', UserCtrl])

    .factory('userService', function() {
        return new UserService();
    })

    .filter('userFilter', UserFilter)

    .directive('userDirective', UserDirective);

UserController.js

UserCtrl = function($scope, UserService) {
    // ...
};

UserDirective.js

UserDirective = function() {
    return {
        // ...
    }
};

UserService.js

UserService = function() {
    // ...
};

UserFilter.js

UserFilter = function() {
    return function() {
        // ...
    }
};

Then I'll just push the user module to the app module.

app.requires.push('UserModule');

My concern lies on the registration of the concepts (Such as controllers, services...) to the module. I was wondering if this is the best way to go and if it's correct. Also possible issues on the parameters and the external .js file.

Consider this part:

.controller('userCtrl', ['$scope', 'UserService', UserCtrl])

The UserCtrl above refers to a function defined in a separate file. Will I be able to pass the $scope and UserService dependency as parameters to the UserCtrl?

UserCtrl = function($scope, UserService) { // Pass parameters (UserController.js)

What's the correct way of doing this in terms of Services, Filters and Directives?

Finally, how can I improve the code?


texts:
I want to solve the following for \$x\$ (in Python):

\$x^{101} = 8765 \ (\mod{9691573})\$

I coded this:

n = 8765
power = 101
mod = 9691573

x = 0
while x < mod:
    if (x ** power) % mod == n:
        break
    x += 1

print x

This is basically the "brute force" approach.

What is the most efficient way to solve this problem programmatically?

Note:

  solving the equation \$x^n = a \mod{M}\$ for the unknown \$x\$ in modular arithmetic means to find an integer \$x\$ such that \$x^n - a\$ is a multiple of the modulus \$M\$


texts: How to refactor this complicated html generator in Ruby?

texts:
['content', 'answers', 'comments'].each do |t|
  break if results.length >= MAX_RESULTS
  Question.search_tank('', :conditions => conditions.merge(t => "#{search_term}"), :page => 1, :per_page => 5).each do |q|
    next if matched_qs.include? q.id
    matched_qs << q.id

    r = {:title => q.content, :value => app_question_url(q.app, q.id)}
    if t == 'content'
      r[:label] = highlight_matched(search_regex, q.content)
      r[:label] << "Question"
    else
      r[:label] = q.content
    end

    if t == 'answers'
      r[:label] = "Answer" + [r[:label], get_snippet(search_regex, q.answers)].compact.join('
')
    end

    if t == 'comments'
      r[:label] = "Comment" + [r[:type], r[:label], get_snippet(search_regex, q.answers.map(&:comments).flatten)].compact.join('
')
    end

    results << r
    break if results.length >= MAX_RESULTS
  end

I would like to refactor that part which generates r[:label]


texts: Exception handling for HTTP request timer

texts:
This method is used to check a URL and return the time it takes to check and the HTTP status code:

public static String urlCheck(String url) {
    try {
        URL urlToCheck = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlToCheck.openConnection();
        connection.setRequestMethod("GET");
        Long start = System.currentTimeMillis();
        connection.connect();
        int urlStatus = connection.getResponseCode();
        Long stop = System.currentTimeMillis();
        Long urlCheckTime = stop - start;
        return (connection.getRequestMethod() + " " + urlToCheck + " "
                + urlStatus + " " + urlCheckTime + "ms");
    }
    catch (IOException err){
        logger.log(Level.WARNING,err.getMessage());
        return "Skipping URL";
    }

}

My questions are:

Should my try block contain all the lines that are in it now, or should it only contain the line that can throw an exception (I put them all in since variables were not resolving (e.g. urlToCheck on first line was not passed to the second line if the second line was outside the try block))?
Is using the blanket exception IOException ok, or would it be better to create a catch block for each exception type that the try block can throw?


texts:
I use jQuery and underscore.js, I have title1-2 and I would like to have the action corresponding.

this.items = {
    menuItems: [
        { title: 'title1',
            data: [
                { title: 'title1-1',
                    action: 'action1-1'
                },
                { title: 'title1-2',
                    action: 'action1-2'
                }
                ]
        },
        { title: 'title2',
            data: [
                { title: 'title2-1',
                    action: 'action2-1'
                },
                { title: 'title2-2',
                    action: 'action2-2'
                }
            ]
        }
    ]
};

Currently, I have the following code to do this:

var item = _.find(_.flatten(_.pluck(this.items.menuItems, 'data')), function (item) { return item.title === 'title1-2'; });
console.log(item.action);

Is there a better way to find it?


texts: Parsing of a (Linux) netlink hotplug uevent packet

texts:
The netlink service is used, among other things, to notify userspace about hotplug events (e.g. "a device has been connected"). These events come in the form of packets, which follow the following format, explained here:

  The netlink packet contains a set of null terminated text lines. The
  first line of the netlink packet combines the $ACTION and $DEVPATH
  values, separated by an @ (at sign).  Each line after the first
  contains a KEYWORD=VALUE pair defining a hotplug event variable.

I have made an "SSCCE" of the code I use to parse these kinds of packets, and posted it on Ideone.com.  I'd like a review on potential risks and bad practices.

#include <cstdlib>

#include <vector>
#include <unordered_map>
#include <string>
#include <algorithm>
#include <iostream>

int main (void)
{
    /* Even if a std::string was used, a string literal would not work, because
    the fake packet contains '\0'. */
    const std::vector<char> msg = {
        'a','d','d','@','/','s','y','s','/','d','e','v','i','c','e','s','\0',
        'S','U','B','S','Y','S','T','E','M','=','b','l','o','c','k','\0','D',
        'E','V','T','Y','P','E','=','p','a','r','t','i','t','i','o','n','\0'
    };

    std::unordered_map<std::string , std::string> hotplug_event_variables;

    auto it1 = std::find( msg.begin() , msg.end() , '@' );
    if ( it1 != msg.end() )
    {
        /* As per the kernel documentation, the piece before the '@' token is
        the implicit "ACTION" event variable. */
        hotplug_event_variables.emplace( std::piecewise_construct , std::forward_as_tuple("ACTION") , std::forward_as_tuple(msg.begin(),it1) );

        /* It points to the '@'; increment it. */
        ++it1;

        auto it2 = std::find( it1 , msg.end() , '\0' );
        if ( it2 != msg.end() )
        {
            /* As with the previous event variable, DEVPATH is implicit. */
            hotplug_event_variables.emplace( std::piecewise_construct , std::forward_as_tuple("DEVPATH") , std::forward_as_tuple(it1,it2) );

            /* It points to the '\0'; increment it. */
            ++it2;

            /*
             * An example packet:
             *
             * Pass of the loop
             *                   |$ACTION@$DEVPATH0·····=·····0······=······0|
             *                           ^^       ^^    ^     ^^     ^      ^
             *                          it1      it2    |     ||     |      |
             * #1                                it3   it4   it5     |      |
             * #2                                             it3   it4    it5
            */
            for ( auto it3 = it2 , it4 = std::find( it2 , msg.end() , '=' ) , it5 = std::find( it4+1 , msg.end() , '\0') ; it3 != msg.end() , it4 != msg.end() , it5 != msg.end() ; it3 = it5+1 , it4 = std::find( it3 , msg.end() , '=' ) , it5 = std::find( it4 , msg.end() , '\0' ) )
            {
                /* While playing with the fake packet, I found that empty pairs
                could made it into the map. */
                if ( std::distance(it3,it4) > 0 && std::distance(it4+1,it5) > 0 )
                {
                    hotplug_event_variables.emplace( std::piecewise_construct , std::forward_as_tuple(it3,it4) , std::forward_as_tuple(it4+1,it5) );
                }
            }

            /*
             * Expected output:
             *
             * "ACTION"    = "add"
             * "DEVPATH"   = "/sys/devices"
             * "SUBSYSTEM" = "block"
             * "DEVTYPE"   = "partition"
            */
            for ( const auto & x : hotplug_event_variables )
            {
                std::cout << '"' << x.first << "\" = \"" << x.second << "\"\n";
            }
        }
    }

    return EXIT_SUCCESS;
}

More information about netlink may be found at the netlink(7) man page.


texts: Function to add a node with a unique ID and x,y coordinates

texts:
This here is a function that adds a graph node, with a unique id to an x,y matrix.

The rules are that :

The node id must be unique
Only one node can exist at a given coordinate.

Here's my function that attempts to add a node with given id, at given x y coordinates .

def addNode(self, node_id, x, y):
    if self.node_list[node_id] != None:
        raise exception("This node ID already exists.")
    else:
        if self.spacialMatrix[x][y] != None:
            raise exception("This node position is already populated.")
        else:
            self.spacialMatrix[x][y] = node_id
            self.node_list[node_id] = [x,y]

How else would I do this?

I generally prefer keeping an if/else structure (so that you know that you are capturing all branches of your logic flow, rather than leaving unhandled else conditions).


texts: Thread-safe concurrent FIFO queue in C++

texts:
Is this the correct way to implement a thread-safe concurrent FIFO queue in C++?  It requires passing unsigned char* arrays of binary data.

Thread Safe Concurrent Queue

#include <queue>
#include <pthread.h>

class concurrent_queue
{

private:

    std::queue<unsigned char*> _queue_;
    pthread_mutex_t push_mutex;
    pthread_mutex_t pop_mutex;
    pthread_cond_t cond;

public:

    concurrent_queue()
    {
        pthread_mutex_init(&push_mutex, NULL);
        pthread_mutex_init(&pop_mutex, NULL);
        pthread_cond_init(&cond, NULL);
    }

    void push(unsigned char* data)
    {
        pthread_mutex_lock(&push_mutex);

        _queue_.push(data);

        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&push_mutex);
    }

    void pop(unsigned char** popped_data)
    {
        pthread_mutex_lock(&pop_mutex);

        while (_queue_.empty() == true)
        {
            pthread_cond_wait(&cond, &pop_mutex);
        }

        *popped_data = _queue_.front();
        _queue_.pop();

        pthread_mutex_unlock(&pop_mutex);
    }
};

CONSUMER TEST:

void *consumer_thread(void *arguments)
{
    concurrent_queue *cq = static_cast<concurrent_queue*>(arguments);

    while (true)
    {
        unsigned char* data = NULL;

        cq->pop(&data);

        if (data != NULL)
        {
            // Eureka! Received from the other thread!!!
            // Delete it so memory keeps free.
            // NOTE: In the real scenario for which I need
            // this class, the data received are bitmap pixels
            // and at this point it would be processed

            delete[] data;
        }
    }

    return 0;
}

PRODUCER TEST:

void main()
{
    concurrent_queue cq;

    // Create the consumer
    pthread_t consumer;
    pthread_create(&consumer, NULL, consumer_thread, &cq));

    // Start producing
    while(true)
    {
        // Push data.
        // Expected behaviour: memory should never run out, as the
        // consumer should receive the data and delete it.
        // NOTE: test_data in the real purpose scenario for which I
        // need this class would hold bitmap pixels, so it's meant to
        // hold binary data and not a string

        unsigned char* test_data = new unsigned char [8192];
        cq.push(test_data);
    }

    return 0;
}


texts:
I have written a Python 2.6.6 script in order to make tables by taking the third column of every text file in a particular subgroup (signal and background in this case[particle physics]). However, I used the exec command too often and I think this code can be written more elegantly.

#!/usr/bin/python
import sys
stringpu = ["50PU", "140PU"]
stringsig = ["NM1", "NM2", "NM3", "Scenario4", "Scenario6"]
stringbkg = ["TTbar", "DiBoson", "TopJets", "BosonJets"]

for a in range(len(stringsig)):
    exec("FILESIG"+str(a)+" = open('SummerStd_'+stringpu[1]+'_'+stringsig[a]+'.txt', 'r')")
    exec("LINESIG"+str(a)+" = FILESIG"+str(a)+".readlines()")

for b in range(len(stringbkg)):
    exec("FILEBKG"+str(b)+" = open('SummerStd_'+stringpu[1]+'_'+stringbkg[b]+'.txt', 'r')")
    exec("LINEBKG"+str(b)+" = FILEBKG"+str(b)+".readlines()")

table = open('table.txt', 'w')
table.write("\\begin{table}[h]  \n")
table.write("\\centering \n")
table.write("\\begin{tabular}{|c|c|c|c|c|c|} \n")
table.write("\\hline  & \\textbf{NM1} & \\textbf{NM2} & \\textbf{NM3} & \\textbf{STOC} & \\textbf{STC} \\\\ \n")

n = 0
for line in range(len(LINESIG0)):
    n += 1
    for i in range(len(stringsig)):
        exec("wordsig"+str(i+1)+" = LINESIG"+str(i)+"[line].split()")
    if n > 2:
        table.write("\hline  \n")
        table.write(wordsig2[2]+"  &  "+wordsig1[3]+"  &  "+wordsig2[3]+"  &  "+wordsig3[3]+"  &  "+wordsig4[3]+"  &  "+wordsig5[3]+" \\\\ \n")

table.write("\hline \n")
table.write("\end{tabular} \n")
table.write("\end{table} \n")

table.write("\\begin{table}[h]  \n")
table.write("\\centering \n")
table.write("\\begin{tabular}{|c|c|c|c|c|c|} \n")
table.write("\\hline  & \\textbf{TTbar} & \\textbf{DiBoson} & \\textbf{TopJets} & \\textbf{BosonJets}  \\\\ \n")

n = 0
for line in range(len(LINEBKG0)):
    n += 1
    for i in range(len(stringbkg)):
        exec("wordbkg"+str(i+1)+" = LINEBKG"+str(i)+"[line].split()")
    if n > 2:
        table.write("\hline  \n")
        table.write(wordbkg2[2]+"  &  "+wordbkg1[3]+"  &  "+wordbkg2[3]+"  &  "+wordbkg3[3]+"  &  "+wordbkg4[3]+" \\\\ \n")

table.write("\hline \n")
table.write("\end{tabular} \n")
table.write("\end{table} \n")
table.close()

I took courses on programming in Python before, but I do not remember the concepts of dictionaries and how to assign variables with dynamic names (such as changing inside a for loop).


texts: A PHP function that prints the url based on path

texts:
I'm trying to come up with a smart wordpress inspired PHP function that builds an url for my CMS. It has some different requirements that are almost all fulfilled so far.

Must use correct domain
Must be able to use subfolder (Eg. /blog/index.php)
Must be able to specify protocol (if http or https)
Must accept queries (Eg. ?sort=date)

The purpose is to make it easier to print urls when developing through my site so that I don't have to type the whole url myself. It's also so the CMS can run on as many different websites as possible, both with subfolders and without.

My code so far:

function _url( $path = null, $args = "" ) {

    $protocol = "http";

    if ( isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST']) ) {
        $domain = $_SERVER['HTTP_HOST'];
    } else {
        $domain = $_SERVER['SERVER_NAME'];
    }

    if ( isset($_SERVER['HTTPS']) ) {
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }

    if ( isset($_SERVER['PHP_SELF']) && strlen(dirname($_SERVER['PHP_SELF'])) > 1 ) {
        $subfolder = dirname($_SERVER['PHP_SELF']);
    } else {
        $subfolder = "";
    }

    if ( !$path ) {
        $path = str_replace( $subfolder, "", strtok($_SERVER["REQUEST_URI"],'?') );
    }

    $url = $protocol . "://" . $domain . $subfolder . $path . $args;

    return $url;
}

An example of use:

// A website where the domain is http://domain.com
echo _url( "/about.php" );

// A website where the domain path is https://domain.com/blog/
echo _url( "/users.php", "?sort=date");

Which prints:

http://domain.com/about.php
https://domain.com/blog/users.php?sort=date

I'm pretty satisfied so far with my code. But I'm 100% sure that there is a smarter way. I tried to dig out the functions that wordpress use, but I couldn't figure it out.

Any help or proposals are appreciated. I hope it makes sense.


texts:
I've been trying to get a relatively optimized version of base64 encoding that works against files.  However, I've made several attempts and haven't gotten anything much faster than what I have here.  On the posted implementation, I started from what was posted on http://www.swissdelphicenter.ch/torry/showcode.php?id=1524 .  I have to think there's a way to do it without tossing values around in a, so I tried that by processing three bytes at a time and then processing the rest, but I didn't end up with anything faster.  So, does anyone have any ideas on how to improve it any more from a speed perspective?

(Relevant code below, I slid some global definitions into the first procedure so people could see those.  Codes64 is the string I'm using to encode the data
with, not reproduced here for brevity)

procedure TMyMimeEncoder.Enc64Buffer(inbuf, outbuf: pointer; inbufsize:  longint;
        var outbufsize: longint);
 // run on the buffer read in by the file (inbuf).  Outbuf is the output.
  type
    PByteArray1 = ^TByteArray1;
    TByteArray1 = array[1..buffersize] of Byte;
  var
    a, b: longint;
    inproc: PByteArray1 absolute inbuf;
    outproc: PChar;
    i: longint;
  begin
    outproc := outbuf;
    outbufsize := 0;
    for i := 1 to inbufsize do
      begin
        b := (b shl 8) + inproc^[i];
        a := a + 8;
        if a = 12 then
          begin
            a := a - 6;
            outproc^ := Codes64[(b shr a)];
            b := b and ((1 shl a) - 1);
            inc(outproc, 1);
            inc(outbufsize, 1);
          end;
        a := a - 6;
        outproc^ := Codes64[(b shr a)];
        b := b and ((1 shl a) - 1);
        inc(outproc, 1);
        inc(outbufsize, 1);
      end;
  end;

function TMyMimeEncoder.Enc64Final: String;
  // run at the end of file to finish the encoding.
  begin
    Result := '';
    if a = 4 then
      Result := Codes64[(b shl 2) + 1] + '='
    else
    if a = 2 then
      Result := Codes64[(b shl 4) + 1] + '==';
  end;