texts:
I'm reasonably happy with the execution:

thufir@dur:~/eclipse-workspace/jsr374$
thufir@dur:~/eclipse-workspace/jsr374$ gradle runShadow

> Task :runShadow
Oct 22, 2017 11:59:02 AM net.bounceme.dur.json.JsonOperations tryJsonFromUrl
INFO: https://my-json-server.typicode.com/typicode/demo/db
Oct 22, 2017 11:59:03 AM net.bounceme.dur.json.Main json
INFO: {"posts":[{"id":1,"title":"Post 1"},{"id":2,"title":"Post 2"},{"id":3,"title":"Post 3"}],"comments":[{"id":1,"body":"some comment","postId":1},{"id":2,"body":"some comment","postId":1}],"profile":{"name":"typicode"}}

BUILD SUCCESSFUL in 2s
6 actionable tasks: 1 executed, 5 up-to-date
thufir@dur:~/eclipse-workspace/jsr374$

am less than thrilled with the variable names, error handling, and, specifically, the convertStreamToString method.

package net.bounceme.dur.json;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.logging.Logger;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

public class JsonOperations {

    private static final Logger LOG = Logger.getLogger(JsonOperations.class.getName());

    private JsonObject readJsonFromString(String jsonString) {
        JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
        JsonObject jsonObject = jsonReader.readObject();
        return jsonObject;
    }

    private String convertStreamToString(InputStream is) {
        Scanner scanner = null;
        scanner = new java.util.Scanner(is);
        scanner = scanner.useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    }

    public JsonObject tryJsonFromUrl(String urlString) {
        LOG.info(urlString);
        JsonObject jsonObject = null;
        try {
            jsonObject = jsonFromUrl(urlString);
        } catch (IOException e) {
        //  e.printStackTrace();
            LOG.severe(e.toString());
        }
        return jsonObject;
    }

    private JsonObject jsonFromUrl(String urlString) throws MalformedURLException, IOException {
        LOG.fine(urlString);
        InputStream inputStream = new URL(urlString).openStream();
        String jsonString = convertStreamToString(inputStream);
        inputStream.close();
        LOG.fine(jsonString);
        JsonObject jsonObject = readJsonFromString(jsonString);
        return jsonObject;
    }

}

Open, really, to any input.  It's meant as a generic sort of utility.  Perhaps static methods?  Wasn't sure.

Finally, it's perhaps an erroneous assumption that the JSON will come in via URL...

Basically, just want to make it a bit more robust.  For example, if there's a problem, pretty much anywhere down the line...perhaps throw a custom exception?  Or return a default empty JSON object?  Both?

Finally, if there's a library which handles URL -> JSON seamlessly then all the better.


texts:
This is a Rspec test for pagination in Rails project. I'm not sure if I should write the test in spec/requests or spec/controllers.

And there must be a lot of thing that I had better to do. Which part of code should I refactor?

spec/requests/companies_spec.r

describe "Companies" do
  describe "GET /companies" do
    before(:all) { 50.times { FactoryGirl.create(:company) }}
    describe "index" do
      context "with 50 companies" do
        it "has not second page" do
          visit root_path
          expect(page).to have_no_xpath("//*[@class='pagination']//a[text()='2']")
        end
      end
      context "with 51 companies" do
        before{ FactoryGirl.create(:company) }
        it "has second page" do
          visit root_path
          find("//*[@class='pagination']//a[text()='2']").click
          expect(page.status_code).to eq(200)
        end
      end
    end
  end
end


texts:
I wrote a module to simulate physics of 2D elastic balls and the community helped me to improve it on this post.

Now I implemented a GUI using Tkinter to display the simulation in a window.

I'm a beginner in programming GUI and I don't know if my script can be more efficient and/or simpler.

Indeed, I'm not really satisfied by my display function because it includes definitions of other functions dedicated to the buttons commands.

Moreover, when I push the start button twice, I also need to push the pause button twice to stop the simulation. I don't understand this behaviour !

Import modules

import Tkinter as tk
import solver

You'll find the solver module here. This isn't the object of this post. If you've comments or remarks about it, post them on this post I spoke above.

Surrounding functions

def _create_circle(self, x, y, r, **kwargs):
    """Create a circle

    x the abscissa of centre
    y the ordinate of centre
    r the radius of circle
    **kwargs optional arguments
    return the drawing of a circle
    """
    return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
tk.Canvas.create_circle = _create_circle

def _coords_circle(self, target, x, y, r, **kwargs):
    """Define a circle

    target the circle object
    x the abscissa of centre
    y the ordinate of centre
    r the radius of circle
    **kwargs optional arguments
    return the circle drawing with updated coordinates
    """
    return self.coords(target, x-r, y-r, x+r, y+r, **kwargs)
tk.Canvas.coords_circle = _coords_circle

def create(balls, canvas):
    """Create a drawing item for each solver.Ball object

    balls the list of solver.Ball objects
    canvas the Tkinter.Canvas oject
    return a dictionary with solver.Ball objects as keys and their circle drawings as items
    """
    return {ball: canvas.create_circle(ball.position[0], ball.position[1], ball.radius, fill="white") for ball in balls}

def update(drawing, canvas, step, size):
    """Update the drawing items for a time step

    drawing the dictionary of drawing items
    canvas the Tkinter.Canvas oject
    step the time step
    size the medium size
    """
    balls = drawing.keys()
    solver.solve_step(balls, step, size)
    for ball in balls:
        canvas.coords_circle(drawing[ball], ball.position[0], ball.position[1], ball.radius)
    canvas.update()

display function

def display(balls, step, size):
    """Display the simulation

    balls the list of solver.Ball objects
    step the time step
    size the medium size
    """
    # Instanciate the window, canvas and circle objects
    window = tk.Tk()
    window.poll = True
    canvas = tk.Canvas(window, width=size, height=size, bg="black")
    canvas.pack()
    canvas.focus_set()
    drawing = create(balls, canvas)
    # Define functions to launch and stop the simulation
    def animate():
        """Animate the drawing items"""
        if window.poll:
            update(drawing, canvas, step, size)
            window.after(0, animate)
        else:
            window.poll = True
    def stop():
        """Stop the animation"""
        window.poll = False
    # Define the buttons used to launch and stop the simulation
    start_button = tk.Button(window, text="Start", command=animate)
    stop_button = tk.Button(window, text="Pause", command=stop)
    start_button.pack()
    stop_button.pack()
    # GUI loop
    window.mainloop()

Unit test of display function

# Test this module
if __name__ == "__main__":
    balls = [solver.Ball(20., 20., [40.,40.], [5.,5.]), solver.Ball(10., 10., [480.,480.], [-15.,-15.]), solver.Ball(15., 15., [30.,470.], [10.,-10.])]
    size = 500.
    step = 0.1
    display(balls, step, size)


texts: Node.js pg-pool db connection acquisition, use and release

texts:
I am trying to use pg-pool to connect to my DB and perform queries using a connection pool.

Here is how I do it, but to be sure I'm not doing it wrong, or to see if there is a better way, please review and critique my code.

var Pool = require('pg-pool');

var aggregation_pool = new Pool({
  // your pool configuration options
});

pool.connect().then(client => {
  client.query('your_query (select, update, insert, delete, whatever..)')
    .then((query_result) => {
      client.release();
      return query_result.rows;
    }).catch(err => {
      client.release();
      return err;
    });
}).catch(err => {
  return err;
});


texts: Given a number: find the closest value in a list of unique and sorted numbers with some twists

texts:
I have a method getClosest() in an object, that does the following:

  Given a number: Find the closest number in a list of unique and sorted numeric values.

On top of that it has two additional ptions next|offset:

default: find the closest value, smaller or larger than the submitted value
next: find the next value in the list, that is larger than the submitted one
offset: like default but find the smaller value only, if the distance to it is smaller/equal than a given delta

You can also assume that:

the input value will always be smaller then or equal to the largest value in the set
all parameters have the correct type (integer|boolean)
the list will contain between 10-20 values

This is an example of the list:

this.values = [0, 35, 90, 110, 160, 175, 200];

The function returns an object, holding the position as well as the actual value:

{
    index: 1,
    value: 35
}

class Test {
  constructor() {
    this.values = [0, 35, 90, 110, 160, 175, 200];
    this.delta = 12;
  }

  getClosest(offset, next, value) {
    let closest,
        comparativeValue;

    if (offset === true) {
      for (let i = 0; i < this.values.length; ++i) {
        const current = this.values[i];

        if (value <= current) {
          closest = {
            index: i,
            value: current
          };
          break;
        }

        if (value > current) {
          comparativeValue = {
            index: i,
            value: current
          };
        }
      }

      if (comparativeValue) {
        const offsetA = Math.abs(closest.value - value);
        const offsetB = Math.abs(comparativeValue.value - value);

        if (this.delta < offsetA && this.delta > offsetB) {
          return comparativeValue;
        }
      }
    }

    if (next === true) {
      for (let i = 0; i < this.values.length; ++i) {
        const current = this.values[i];

        if (current > value) {
          closest = {
            index: i,
            value: current
          };
          break;
        }
      }
    }

    if (!offset && !next) {
      for (let i = 0, shortest = null; i < this.values.length; ++i) {
        const current = this.values[i];
        const delta = Math.abs(current - value);

        if (null === shortest || shortest > delta) {
          closest = {
            index: i,
            value: current
          };
          shortest = delta;
        }
      }
    }
    return closest;
  }
}

const test = new Test();

console.log(
  test.getClosest(false, false, 10).value,
  test.getClosest(false, false, 100).value,

  test.getClosest(false, true, 10).value,
  test.getClosest(false, true, 100).value,

  test.getClosest(true, false, 10).value,
  test.getClosest(true, false, 100).value,
);

My concerns are:

overcomplicated
this ain't DRY at all
too many loops and variable declarations
there's a call getClosest(true, true, 40), which might lead to unexpected results

You can ignore the Test-object-wrapper. It's to simplify the example and to make the code easily runnable. Here's a fiddle as well to play around with.


texts:
I want to optimize code in my simple app that I'm writing to learn C#. I feel it's really badly optimized in terms of good coding practises. Could anyone take a look at it and give me a hint to make it look better?

public void mainMenu(BookList b)
        {
            bool repeat = false;
            Console.WriteLine("Welcome to Library.");
            Console.WriteLine("What do you want to do?");
            Console.WriteLine("1. Add a book.");
            Console.WriteLine("2. Delete book.");
            Console.WriteLine("3. Borrow a book.");
            Console.WriteLine("4. Return book.");
            Console.WriteLine("5. See list of available books.");
            Console.WriteLine("6. See list of all books.");
            Console.WriteLine("7. Exit");
            string userChoice = Console.ReadLine();
            switch  (userChoice)
            {
                case "1":
                    do
                    {
                        b.addBook();
                        Console.WriteLine("What do you want to do now?");
                        Console.WriteLine("Add another book? - Press 1.");
                        Console.WriteLine("Go back to main menu? - Press any other button.");
                        ConsoleKeyInfo keyPressed;
                        keyPressed = Console.ReadKey();
                        if (keyPressed.Key == ConsoleKey.D1 || keyPressed.Key == ConsoleKey.NumPad1)
                        {
                            repeat = true;
                            Console.Clear();
                        }
                        else
                        {
                            repeat = false;
                        }
                    }
                    while (repeat == true);
                    Console.Clear();
                    this.mainMenu(b);
                    break;
                case "2":
                    b.deleteBook();
                    break;
                case "3":
                    b.borrowBook();
                    break;
                case "4":
                    b.returnBook();
                    break;
                case "5":
                    b.displayBooks();
                    break;

            }
        }

I wanted to add repeating an action in addbook() function, but mainMenu is method of different class so I figured it out this way.


texts:
Can someone help me make a more elegant solution to this function?

function convertToHHMM(info) {
var suffix='AM';
var hrs = parseInt(Number(info));
var min = Math.round((Number(info)-hrs) * 60);
if (hrs >12) { hrs = hrs - 12; suffix='PM'; }
if (min < 10) {min='0'+min;}
return hrs + ':' + min + ' ' + suffix;
}


texts:
It is a basic calculator where the user inputs two numbers, and an operation and the program makes it into an equation and gets the answer.  For example, if the user enters number 2 number 3 and tells it to multiply, it will display the answer as 6.  I just want to know how this could be improved.

Could I have used loops or more advanced procedures to get the same output?

 namespace Test
 {
    class Program
    {
            static void Main(string[] args)
            {
                int firstNum;
                int secondNum;                   //Variables for equation
                string operation;
                int answer;

                Console.WriteLine("Hello, welcome to Alex's basic calculator!");
                Console.ReadLine();

                Console.Write("Enter the first number in your basic equation: ");
                firstNum = Convert.ToInt32(Console.ReadLine());

                //User input for equation
                Console.Write("Now enter your second number in the basic equation: ");
                secondNum = Convert.ToInt32(Console.ReadLine());
                Console.Write("Ok now enter your operation ( x , / , +, -) ");
                operation = Console.ReadLine();

                if (operation == "x")
                {
                   answer = firstNum * secondNum;
                   Console.WriteLine(firstNum + " x " + secondNum + " = " + answer);
                   Console.ReadLine();
                }
                else if (operation == "/")
                {
                   answer = firstNum / secondNum;
                   Console.WriteLine(firstNum + " / " + secondNum + " = " + answer);
                   Console.ReadLine();
                }
                //Getting answers
                else if (operation == "+")
                {
                   answer = firstNum + secondNum;
                   Console.WriteLine(firstNum + " + " + secondNum + " = " + answer);
                   Console.ReadLine();
                }
                else if (operation == "-")
                {
                   answer = firstNum - secondNum;
                   Console.WriteLine(firstNum + " - " + secondNum + " = " + answer);
                   Console.ReadLine();
                }
                else
                {
                   Console.WriteLine("Sorry that is not correct format! Please restart!");     //Catch
                   Console.ReadLine();
                }
           }
     }
}


texts: Filtering a long list of files through a set of ignore patterns using iterators

texts:
I have a backup job that walks across a huge directory with potentially millions of files. Python's os.walk() works just fine.

Now, I have implemented a feature to ignore files based in a black list of patterns. I just want it to behave like a .gitignore file.

Currently I do this:

import os
from fnmatch import fnmatch

some_dir = '/'
ignore_list = ['*.tmp', 'tmp/', '*.py']
for dirname, _, filenames in os.walk(some_dir):
    for filename in filenames:
        should_ignore = False
        for pattern in ignore_list:
            if fnmatch(filename, pattern):
                should_ignore = True
        if should_ignore:
            print 'Ignore', filename
            continue

It works, but I failed to write it in terms of iterators.

Can this routine be written in terms of python iterators? Can it be improved in terms of iterators or generators?


texts:
Here is a classical attempt to implement a lock-free stack (based on this article). I rewrote it in C++11 and also tried to add memory orders which I would like to confirm to be correct.

template<typename T>
class stack
{
    struct node_t final
    {
        T value;
        node_t *next;
    };

    struct head_t final
    {
        uintptr_t aba;
        node_t *node;
        head_t() noexcept :aba(0),node(nullptr)
        {}
        head_t(node_t* ptr) noexcept :aba(0),node(ptr)
        {}
    };

    static_assert(sizeof(head_t) == 2*sizeof(uintptr_t), "Stack head should be 2 pointers size.");

    typedef typename std::aligned_storage<sizeof(node_t), std::alignment_of<node_t>::value>::type aligned_node_t;

    std::unique_ptr<aligned_node_t[]> buffer_ptr;
    node_t *node_buffer;
    char cache_padding_1_[64 - sizeof(node_t*)];
    std::atomic<head_t> head;
    char cache_padding_2_[64 - sizeof(std::atomic<head_t>)];
    std::atomic<head_t> free_nodes;
    char cache_padding_3_[64 - sizeof(std::atomic<head_t>)];

public:

    stack(size_t capacity)
    {
        head.store( head_t(), std::memory_order_relaxed );
        // preallocate nodes
        buffer_ptr.reset(new aligned_node_t[capacity]);
        node_buffer = reinterpret_cast<node_t*>(buffer_ptr.get());
        for(size_t i = 0; i < capacity - 1; ++i)
        {
            node_buffer[i].next = &node_buffer[i + 1];
        }
        node_buffer[capacity-1].next = nullptr;
        free_nodes.store( head_t(node_buffer), std::memory_order_relaxed );
    }

    template<class U>
    bool push(U && data)
    {
        node_t *node = _pop(free_nodes);
        if (node == nullptr)
            return false;
        node->value = std::forward<U>(data);
        _push(head, node);
        return true;
    }

    bool pop(T& data)
    {
        node_t *node = _pop(head);
        if (node == nullptr)
            return false;
        data = std::move(node->value);
        _push(free_nodes, node);
        return true;
    }

private:
    node_t* _pop(std::atomic<head_t>& h)
    {
        head_t next, orig = h.load(std::memory_order_relaxed);
        do {
            if (orig.node == nullptr)
                return nullptr;
            next.aba = orig.aba + 1;
            next.node = orig.node->next;
        } while (!h.compare_exchange_weak(orig, next,
                                        std::memory_order_acq_rel,
                                        std::memory_order_acquire));
        return orig.node;
    }

    void _push(std::atomic<head_t>& h, node_t* node)
    {
        head_t next, orig = h.load(std::memory_order_relaxed);
        do {
            node->next = orig.node;
            next.aba = orig.aba + 1;
            next.node = node;
        } while (!h.compare_exchange_weak(orig, next,
                                        std::memory_order_acq_rel,
                                        std::memory_order_acquire));
    }
};


texts:
This is the code I made to scan IP addresses. I am new to python and just want to learn how I can optimize it. I know the subprocess is slower than others to IP scanning but if there is a way to make it faster I would like to know how. :)

#!/usr/bin/env python
# coding:utf-8
import subprocess
import datetime
hostname = input("Entrez la gateway de cette manière(example: 192.168.1)")
# Ask for gateway
while True:
    file_name = input("Comment voulez-vous appelez votre dossier?Sans espace ni   caratère spéciaux(example:file_name)")
    # Ask how the user want to name the file where the result of the scan will be

    if " " in file_name:
        print("Réecrire le nom sans espace")
    # check for spaces in the name file(impossible to create name files with spaces or special characters)
    else:
        break
with open(str(file_name) + ".txt", "w")as i:
    i.write("Start time" + str(datetime.datetime.now()))
    # print the start time of the scan process
    for scan in range(1, 255):
        i.write("-" * 100)

        ip_address = str(hostname) + "." + str(scan)
        ping_response = subprocess.Popen(["ping", ip_address, "-n", '1'],   stdout=subprocess.PIPE).stdout.read()
        #Ping the ip address

        ping_response = ping_response.decode()
        # (la réponse du ping est encoder , cette commande la decode)

        print("-"*100)
        print(ping_response)
        i.write(str(ping_response))
        if ip_address == hostname + "." + "254":

            i.write("End time" + str(datetime.datetime.now()))
            # print the end time of the scan process

            i.close()
            quit()


texts:
Following idea:

  You have a LCD-display with 2 rows.

  You write the first line of a "text" to the second row. Then you clean the screen.
  After a delay you write the first line to the first row and a the second line of the text to the second row. Then follows another clean
  and delay.
  Then you write the second line to the first row and the third line to the second row. And so on ...

  When the end of the text is reached the whole process starts again
  from the beginning.

  That way the impression of an "vertical moving" text is accomplished.

The code I have written:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setDisplay(String lineValue, int lineNumber, int waitUntilClear, boolean clearScreen) {
  lcd.setCursor(0, lineNumber),
  lcd.print(lineValue);

  delay(waitUntilClear);

  if (clearScreen == true) {
   lcd.clear();
  }
}

void setup() {
  lcd.begin(16, 2);
}

void loop() {
  const int DELAY = 3000;
  const int COUNT_ELEMENTS = 12;

  String messages[COUNT_ELEMENTS] = {
    "",
    "Furniture Store",
    " MEYER & MILLER",
    "",
    "  Contact us!",
    "",
    " -- Email ----- ",
    "demo@example.com",
    "",
    " -- Phone ----- ",
    " 000 123456",
    ""
  };

  for (int i = 0; i < COUNT_ELEMENTS - 1; i++) {
    setDisplay(messages[i], 0, 0, false);
    setDisplay(messages[i + 1], 1, DELAY, true);
  }
}

It works fine and by using an additional function I could avoid code redundancies mostly. If someone has an idea how to improve my code or even doing it completely different in a better way, then I would appreciate his/her comment or answer.


texts:
Is this a good C program for splitting a command line without doing any expansion on it? Don't worry too much about main() and the output -- those are for testing.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
void pullwhitespace(char **input);
int main (int argc, char **argv)
{
        if (argc != 2) {
                fputs("Must have exactly one command line argument\n", stderr);
                return 64;
        }
        char *input = argv[1];
        char *outstring = malloc(strlen(argv[1]) + 1);
        char *outptr = outstring;
        char a;
        pullwhitespace(&input);
NORMAL:
        /* We are in an unquoted part of the input */
        switch ((a = *input++))
        {
        case ' ' :
        case '\t':
                *outptr++ = '\0';
                pullwhitespace(&input);
                goto NORMAL;
        case '\n':
        case '\0':
                goto DONE;
        case '\\':
                if (((a = *input++)) == '\n') {
                        break;
                } else if (a) {
                        *outptr++ = a;
                        goto NORMAL;
                } else {
                        goto FAIL;
                }
        case '\'':
                goto QUOTE;
        case '"':
                goto DQUOTE;
        default:
                *outptr++ = a;
                goto NORMAL;
        }
        assert(0);
QUOTE:
        /* We are in a single quoted string */
        while (((a = *input++)) != '\'') {
                if (a) {
                        *outptr++ = a;
                } else {
                        goto FAIL;
                }
        }
        goto NORMAL;
DQUOTE:
        /* We are in a double quoted string */
        switch ((a = *input++))
        {
        case '\0':
                goto FAIL;
        case '\\':
        {
                char b = *input++;
                switch (b)
                {
                case '\0':
                        goto FAIL;
                default:
                        *outptr++ = a;
                case '"':
                case '\\':
                        *outptr++ = b;
                case '\n':
                        break;
                }
        }
        goto DQUOTE;
        default:
                *outptr++ = a;
                goto DQUOTE;
        case '"':
                goto NORMAL;
        }
        assert(0);
FAIL:
        fprintf(stderr, "%s: Invalid string input\n", argv[0]);
        return 1;
        assert(0);
DONE:
        *outptr++ = '\0';
        *outptr++ = '\0';
        errno = 0;
        fwrite(outstring, 1, (size_t)(outptr - outstring), stdout);
        int error = errno;
        if(ferror(stdout)) {
                fprintf(stderr, "%s: write error: %s\n", argv[0], strerror(error));
                return 1;
        }
        fflush(stdout);
        if ( errno != 0) {
                fprintf(stderr, "%s: write error: %s\n", argv[0], strerror(error));
                return 1;
        }
        return 0;
}
void pullwhitespace (char **inputptr)
{
        char *input = *inputptr;
        char a;
        while (( a = *input)) {
                if (a != ' ' && a != '\t') {
                        return;
                }
                input++;
        }
}

I know that it is FULL of goto statements (more than every other program I have ever made put together) -- is that okay?

The reason for the goto statements is that this is meant as a lightweight state machine. Intended applications include parsing command line arguments or (possibly - this is far fetched) for the parser (not supporting code) to be the basis of a kernel module to parse shebang lines, allowing multiple arguments to be passed to a shebang interpreter.


texts: Reusable function for a validation process

texts:
I previously asked how can I simplify a validation process:
How can I simplify this JQuery validation process?
But in hindsight, what I really meant to ask was how can I turn that process into a reusable function.
I'm going through some old code that I wrote, and I am trying to clean it up so there's not a lot of redundant code.
I have many onClick events that look like this:
$('#addSubmit').on('click', function(){
  var addcriteria = {
    addcity: $('#addcity').val(),
    addregion: $('#addregion').val(),
    addloctype: $('#addloctype').val(),
    // several more values
  }

  if(addcriteria.addcity == "" || addcriteria.addcity == null){
    $('#errorModal').modal('show');
    $('.message').text('You must enter a City.');
    $('#errorModal').on('hidden.bs.modal', function(){
        document.forms["addEquipForm"].addcriteria.addcity.focus();
    });
    return false;
  }
  if(addcriteria.addregion == ""){
    $('#errorModal').modal('show');
    $('.message').text('You must select a Region.');
    $('#errorModal').on('hidden.bs.modal', function(){
        document.forms["addEquipForm"].addcriteria.addregion.focus();
    });
    return false;
  }
  // several more checks
  else{
    $.post('api/updateEquip.php', {addcriteria:addcriteria}, function(data){
        if(data == "Success"){
            $('#successModal').modal('show');
            $('.message').text('New Equipment has been added.');
            $('#successModal').on('hidden.bs.modal', function(){
                location.reload();
            });
        }
        else{
            $('#errorModal').modal('show');
            $('.message').text('The Equipment could not be added.');
            return false;
        }
    });
  }
});

As stated, I have many onClick events that look similar to the above.  I want to get better at creating custom functions, and I think this would be a good start.
This was my attempt at creating a custom reusable function for the above code...
I started by creating the function:
function criteriaCheck(checkCriteria){
  if(checkCriteria == ""){
    $('#errorModal').modal('show');
    $('.message').text('Error message of some sort.');
    $('#errorModal').on('hidden.bs.modal', function(){
        document.forms["addEquipForm"].checkCriteria.focus();
    });
    return false;
  }
  else{
    // not sure what to return here
    // but I can console log a success message
    console.log('Success');
  }
}

Then, inside my onClick event, I can call the function and pass the value into the function:
var checkCriteria = '';

criteriaCheck(checkCriteria = addcriteria.addcity);

However, using these updates, I can only get "Success" in the console, even when I try to leave a blank form value.
With all of this said, how can I build a custom reusable function using the above onClick event?


texts:
Consider the class AB below that is to be used as a simple customized list of A objects for lookup operations.

Can this code be improved to avoid instantiating AB with an empty list [] (i.e., perhaps modify __add__ in some way)?

class A():
    def __init__(self, arg):
        self.arg = arg

class AB():
    def __init__(self, list):
        self.list = list

    def __add__(self, other):
        return AB(self.list + [other])

ab = AB([])
ab += A(1)
ab += A(2)


texts: Better way to write 'bulky' function in jQuery

texts:
I have this function that works fine, but it looks really ugly and repetitive...

Basically I have a featured profile and underneath I have 4 smaller thumbnails, on click I want to populate the large profile. The code works fine it just doesn't look too good...

$('ul.teamProfiles li').click(function () {

    var $name = $(this).find('h4.name').html();
    var $picture = $(this).find('img').data('bigimg');
    var $biography = $(this).find('.biographyParas').html();
    var $jobTitle = $(this).find('p.jobTitle').html();
    var $telephone = $(this).find('p.telephone').html();
    var $linkedin = $(this).find('a.linkedinLink').attr('href');
    var $twitter = $(this).find('a.twitterLink').attr('href');
    var $mailto = $(this).find('a.mailtoLink').attr('href');

    $('.profileDetail .largeImg').attr('src', $picture);
    $('.profileDetail h3.name').html($name);
    $('.profileDetail h4.jobtitle').html($jobTitle);
    $('.profileDetail .biographyContainer').html($biography);
    $('.profileDetail span.telephone').html($telephone);
    $('.profileDetail a.linkedin').attr('href', $linkedin);
    $('.profileDetail a.twitter').attr('href', $twitter);
    $('.profileDetail a.email').attr('href', $mailto);
});


texts: Script to access genealogy API for list of users and attributes

texts:
This is a script to access the Stack Exchange API for the genealogy site and create a list of user dictionaries.  It contains a snippet at end to validate.  The data obtained is stored in YAML format in a file for use by other programs to analyze the data.

'''
This is a script to access the stackexchange api
    for the genealogy site
    and create a list of user dictionaries
'''

# use requests module
#      - see http://docs.python-requests.org/en/latest/user/install/#install
import requests

# use YAML to store output for use by other programs
#     see http://pyyaml.org/wiki/PyYAML
import yaml
OUTFILENAME = "users.yaml"

# use se api and access genealogy site
#   see https://api.stackexchange.com/docs/users for api info
URL ='https://api.stackexchange.com/2.1/users'

url_params = {
    'site'     : 'genealogy',
    'pagesize' : 100,
    'order'    : 'desc',
    'sort'     : 'reputation',
    }

page = 1
not_done = True
user_list = []

# replies are paginated so loop thru until none left
while not_done:
    url_params['page'] = page
    # get next page of users
    api_response = requests.get(URL,params=url_params)
    json_data = api_response.json()

    # pull the list of users out of the json answer
    user_list.extend( json_data['items'] )

    # show progress each time thru loop
    print api_response.url
    #note only so many queries allowed per day
    print '\tquota remaining: %s' % json_data['quota_remaining']
    print "\t%s users after page %s" % (len(user_list),page)

    # prepare for next iteration if needed
    page += 1
    not_done = json_data['has_more']

# output list of users to a file in yaml, a format easily readable by humans and parsed
#   note safe_dump is used for security reasons
#   since dump allows executable python code
#   Sidebenefit of safe_dump is cleaner text
outFile = open(OUTFILENAME,"w")
yaml.safe_dump(user_list, outFile)
outFile.close()

# validate it wrote correctly
#   note this  shows example of how to read
infile = open(OUTFILENAME)
readList = yaml.safe_load(infile)
infile.close()

print 'wrote list of %d users as yaml file %s' % (len(readList),OUTFILENAME)

I wrote this code because I wanted the data it gets from the genealogy site but also:

to learn APIs in general
to learn the Stack Exchange API
to get back into programming which I hadn't done much lately
I thought I'd try YAML

Since it's such a simple script I didn't bother with objects, but I would be interested in how it could be remade in the functional programming paradigm which I'm not as familiar with.


texts:
This code basically finds duplicate strings within a file.

  An example: DUPLICATE_LENGTH set to 6, file contains:

process hash michael honeycomb interrupt system call deadlock scheduling michael

  The output will be michael, as its a duplicate with a length of 6 or
  higher

The following code shows my approach to solving this issue.  If there are completely different ideas how to solve it, I'm open too, but primarily I'd like to get some feedback of the code I wrote.

I'm also searching performance optimizations as it gets kinda slow on large files.

import codecs

# Constants
DUPLICATE_LENGTH = 30;
FILE_NAME = "data.txt"
SHOW_RESULTS_WHILE_PROCESSING = True

def showDuplicate(duplicate):
    print("Duplicate found:{0}".format(duplicate))

fileHandle = codecs.open(FILE_NAME, "r", "utf-8-sig")
fileContent = fileHandle.read()
fileHandle.close()

substringList = []  #contains all possible duplicates.
duplicatesList = [] #contains all duplicates

for i in range(0, len(fileContent) - DUPLICATE_LENGTH):
    end = i + DUPLICATE_LENGTH
    duplicate = fileContent[i:end]
    if duplicate in substringList and '|' not in duplicate:
        duplicatesList.append(duplicate)
    else:
        substringList.append(duplicate)

resultList = []
currentMatch = duplicatesList[0]
currentMatchPos = 1
for i in range(1, len(duplicatesList)):
    if currentMatch[currentMatchPos:] in duplicatesList[i]:
        currentMatch += duplicatesList[i][-1]
        currentMatchPos += 1
    else:
        if SHOW_RESULTS_WHILE_PROCESSING:
            showDuplicate(currentMatch)

        resultList.append(currentMatch) # this match is closed, add it!
        currentMatch = duplicatesList[i]
        currentMatchPos = 1

if not SHOW_RESULTS_WHILE_PROCESSING:
    for duplicate in resultList:
        showDuplicate(duplicate)

if not resultList:
    print "Awesome, no duplicates were found!"


texts: How to combine items in List to make new items efficiently

texts:
I have a case where I have the name of an object, and a bunch of file names. I need to match the correct file name with the object. The file name can contain numbers and words, separated by either hyphen(-) or underscore(_). I have no control of either file name or object name. For example:

10-11-12_001_002_003_13001_13002_this_is_an_example.svg

The object name in this case is just a string, representing an number

10001

I need to return true or false if the file name is a match for the object name. The different segments of the file name can match on their own, or combined. In the example above, it should be true for the following cases (not every true case, just examples):

10001
10002
10003
11001
11002
11003
12001
12002
12003
13001
13002

And, we should return false for this case (among others):

13003

What I've come up with so far is this:

public bool IsMatch(string filename, string objectname)
{
    var namesegments = GetNameSegments(filename);
    var match = namesegments.Contains(objectname);
    return match;
}

public static List<string> GetNameSegments(string filename)
{
    var segments = filename.Split('_', '-').ToList();

    var newSegments = new List<string>();
    foreach (var segment in segments)
    {
        foreach (var segment2 in segments)
        {
            if (segment == segment2)
                continue;

            var newSegment = segment + segment2;
            newSegments.Add(newSegment);
        }
    }

    return segments.Concat(newSegments).ToList();
}

This does work so far, but is there a better way to do it, perhaps without nesting foreach loops?


texts:
I needed a Minecraft-like stone texture, instead of creating it using image editing software I decided to generate one using R.

The idea is to create some noise and stretch it horizontally so the texture tends to have some horizontal lines.

Example output (this example is upscaled, the original file is 32x32 pixels):

My questions are: What do you dislike about this code? Are the libraries 'ambient' and 'png' necessary, or does R have appropriate functionality builtin?

The package ambient is used to create the Perlin noise, and the package png is used to create a low resolution PNG image.

library(ambient)
library(png)

size <- 32

# data is in a 1:2 ratio.
data <- noise_perlin(dim=c(size, size / 2), frequency=0.9)

min <- 0.1
max <- 0.6

# data's bound is -1 to 1, transform that into a bound of min to max.
inrange <- min + ((data + 1) / 2) * (max - min)

# turn into 1:1 ratio by repeating columns.
stretched <- inrange[, rep(1:(ncol(inrange)), each=2)]

writePNG(target="stone.png", image=stretched)


texts: Registering endpoints and HTTP method for exemption of authentication

texts:
I have a set of API endpoints where the URL is not standardized, so I could either get "api/auth" or "api/auth/" (may or may not end with "/"). I'm 'registering' the endpoint, plus the HTTP Method that comes in, so I can exclude certain endpoints from having to authenticate.

I've written this piece of code, which has a lot of repetition. Any thoughts?

Private _ExemptEndpoints As New List(Of Tuple(Of String, Method))
Public Sub RegisterAuthExemptEndpoint(endpoint As String, method As Method) Implements IRestAuthenticator.RegisterAuthExemptEndpoint

    Dim endpoints As New List(Of Tuple(Of String, Method))
    Dim allMethods As Boolean = False
    If method = Nothing Then allMethods = True

    Dim ep1
    Dim ep2

    If Not endpoint.EndsWith("/") Then
        ep1 = endpoint
        ep2 = endpoint + "/"
    Else
        ep1 = endpoint.Remove(endpoint.Length - 1, 1)
        ep2 = endpoint
    End If

    If allMethods Then
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.GET))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.POST))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.PUT))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.DELETE))

        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.GET))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.POST))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.PUT))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.DELETE))
    Else
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method))
    End If

End Sub


texts:
I don't understand the concept of autoloaders, other than the bare minimum, which is that to load a class file when the class is being called. Or as the PHP manual cites it, to avoid having to require multiple time.

I get that, but what I don't understand is the complexity behind almost all the autoloaders which I sought to learn some things from. It's almost impossible to understand what goes on behind the scenes.

Just to understand it a bit more with your help, I made a simple autoloader as you can see below:

class Autoloader
{
    private $pathToClass;

    //register the path
    function __construct($pathToClass)
    {
        $this->pathToClass = $pathToClass;
    }

    //load the file
    public function load($class)
    {

        // expload the namespaces ex: foo\bar\tar array(foo, bar, tar)
        $explode = explode('\\', $class);

        //get the last exploaded string and append .php so it becomes tar.php
        $class = $explode[count($explode) - 1].'.php';

        // required tar.php in the path it is found ex:
        // require '/foo/bar/tar.php' in lowecase to avoid windows/unix conflict
        if(file_exists(strtolower($this->pathToClass.$class))){
             require strtolower($this->pathToClass.$class);

            return true;
        }

        return false;
    }

    // autoload
    public function register()
    {
        spl_autoload_register([$this, 'load']);
    }
}

The class explains itself. It does work, and I just would like to know what I am missing?  As you can see, it is the most basic autoloader.  What would be the next most important thing you would add to it?

Here is how it is instantiated:

$myLibLoader = new Autoloader(__DIR__.'/foo/bar/');
$myLibLoader->register();

$foo =  new foo();


texts: C++ Class for optionally constructing arbitrary derived classes

texts:
Here is a class I'm working up to register classes derived from a Module base class. These classes may or may not be instantiated (via the ModuleCreatorBase::create() method) based on some logic which is not yet included in the code.

I wanted to allow constructing Modules which take no arguments and Modules which take any number of arguments, though I'm not sure if my method here is the best approach for that. For some reason it feels kind of clunky to me.

Are there more effective or perhaps other more well established ways to achieve this?

#include <memory>
#include <unordered_map>
#include "Module.hpp"

class ModuleManager
{
public:
  template <typename ModuleClass>
  static void registerModule(const std::string& moduleName);
  template <typename ModuleClass, typename... Args>
  static void registerModule(const std::string& moduleName, Args&&... args);
private:
  struct ModuleCreatorBase
  {
    virtual std::unique_ptr<Module> create() = 0;
  };
  template <typename ModuleClass>
  struct ModuleCreator : public ModuleCreatorBase
  {
    std::unique_ptr<Module> create() override;
  };
  template <typename ModuleClass, typename... Args>
  struct ModuleCreatorArgs : public ModuleCreatorBase
  {
    ModuleCreatorArgs(Args&&... args);
    std::tuple<Args...> args;
    template<std::size_t ...I>
    std::unique_ptr<Module> do_create(std::index_sequence<I...>);
    std::unique_ptr<Module> create() override;
  };
  static std::unordered_map<std::string, ModuleCreatorBase*> registry;
};

template <typename ModuleClass>
std::unique_ptr<Module> ModuleManager::ModuleCreator<ModuleClass>::create()
{
  return std::make_unique<ModuleClass>();
}

template <typename ModuleClass, typename... Args>
ModuleManager::ModuleCreatorArgs<ModuleClass, Args...>::ModuleCreatorArgs(Args&&... args)
: args(std::forward<Args>(args)...) {}

template <typename ModuleClass, typename... Args>
std::unique_ptr<Module> ModuleManager::ModuleCreatorArgs<ModuleClass, Args...>::create()
{
  return do_create(std::index_sequence_for<Args...>{});
}

template <typename ModuleClass, typename... Args>
template <std::size_t ...I>
std::unique_ptr<Module> ModuleManager::ModuleCreatorArgs<ModuleClass, Args...>::do_create(std::index_sequence<I...>)
{
  return std::make_unique<ModuleClass>(std::get<I>(args)...);
}

template <typename ModuleClass>
void ModuleManager::registerModule(const std::string& moduleName)
{
  registry.insert(std::pair<std::string, ModuleCreatorBase*>(moduleName, new ModuleCreator<ModuleClass>()));
}
template <typename ModuleClass, typename... Args>
void ModuleManager::registerModule(const std::string& moduleName, Args&&... args)
{
  registry.insert(std::pair<std::string, ModuleCreatorBase*>(moduleName, new ModuleCreatorArgs<ModuleClass, Args...>(std::forward<Args>(args)...)));
}


texts: Connecting MySQL with connection pool in NodeJS

texts:
I'm trying to connect to a MySQL database in NodeJS. It seems it is creating multiple pool connections from multiple sources, instead of using the old one.

If I try this in MySQL console:

SHOW PROCESSLIST;

It shows many sleep connections.

Here is my connection file:

const mysql = require('mysql2/promise');

require('./env');
const config = require('.')[process.env.NODE_ENV || 'development'];
let pool;

function configDb(config) {
  const dbConfig = {
    host: config.host,
    user: config.username,
    password: config.password,
    database: config.database,
    connectionLimit : 100,
  };

  if (!pool) {
    pool = mysql.createPool(dbConfig);
  }

  return pool;
}

function exec(query, values) {
  const db = configDb(config);

  return db.getConnection().then(conn => {
    console.log('QUERY: ', query, values);
    const res = conn.query(query, values);
    conn.release();
    return res;
  });
}

module.exports = {
  exec,
};

What could be a better approach to this?


texts:
I have a web page containing n pages of paged data, showing 20 records at a time. The front end has a link to another page that opens the same data, but without the paging and calls window.print on document.ready.

On my paged content view I have a link:

Print all items

In printallthisstuff.php I have:

$(document).ready(function(){
    window.print();
});

printaallthisstuff.php can be a very large document, taking several seconds to load. What would be a better way of doing this?


texts: Follow-up: Find sum of number of times that each character of source occurs in the target

texts:
This question is a follow-up of this question. The aim of the questions is to find sum of number of times that each character of source occurs in the target.

In the new code, I've renamed the char array and added the functionality to prevent the following "if a character is duplicated in the source, you will double-count it in the result."

I would like to know if there is still a better solution for it.

It was mentioned in one of the answers of the previous question that I should use HashMap or other data structures for chars more than 100, but I am not sure how and why.

String target = "alex alexander";
String source = "ardx";
Map<Character,Integer> tempMap = new HashMap<>();

char[] tchars = source.toCharArray();

int occur = 0;
int occurrence = 0;

for (int i = 0; i < tchars.length; i++) {
   if(!tempMap.containsKey(tchars[i])){ //if the occurrence of the current char
        String temp = target;           //   has been already calculated
        int index = temp.indexOf(tchars[i]);

        while (index != -1) {
            occur++;
            index = temp.indexOf(tchars[i], index + 1);
        }
        tempMap.put(tchars[i],occur);
        occurrence += occur; //add to the total counter
        occur = 0;           //reset the single counter
   }else{
       occurrence += tempMap.get(tchars[i]);
   }

}
System.out.println(occurrence);

Output

a is added to the map and its associated counter is 3
r is added to the map and its associated counter is 1
d is added to the map and its associated counter is 1
x is added to the map and its associated counter is 2
25


texts: Display HTML based on user input (via checkbox selection)

texts:
I currently have this, which works. However, I would prefer to not have the HTML that displays being stored inline in array like this, but in a more flexible / optimal way so I can have more text / HTML without being restricted to having it inline within the quotes.

texts = {
      item1: 'Item Box 1 Content html right here! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
      item2: 'Now its Item Box 2 html content here ! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
      item3: 'This is the example html of Item box 4! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
      item4: 'Item box number 5 html content is here! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    }
    $("#container").css('background', '#fff')

     $('.download-pdf').click(function() {

      notChecked = $("input[type=checkbox]:not(:checked)").parent();
      notChecked.hide();
      yesChecked = $("input[type=checkbox]:checked").parent();

      $.each(yesChecked, function( index, el ) {
        $(el).show().html(texts[$(el).attr('id')]);
      });

full js code for better clarity.

texts = {
      item1: 'Item Box 1 Content html right here! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
      item2: 'Now its Item Box 2 html content here ! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
      item3: 'This is the example html of Item box 4! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
      item4: 'Item box number 5 html content is here! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    }
    $("#container").css('background', '#fff')

     $('.download-pdf').click(function() {

      notChecked = $("input[type=checkbox]:not(:checked)").parent();
      notChecked.hide();
      yesChecked = $("input[type=checkbox]:checked").parent();

      $.each(yesChecked, function( index, el ) {
        $(el).show().html(texts[$(el).attr('id')]);
      });

     var pdf = new jsPDF('p', 'pt', 'a4');

      pdf.addHTML(document.getElementById('records'), function() {

          setTimeout(function(){
           location.reload();
           },3000);

      });

      var file = 'test';
      if (typeof doc !== 'undefined') {
          doc.save(file + '.pdf');
      } else if (typeof pdf !== 'undefined') {
          setTimeout(function() {
              pdf.save(file + '.pdf');
              // $("#item4").hide();

          }, 2000);
      } else {
          alert('Error 0xE001BADF');
      }

  });


texts:
I'm representing DB tables as classes (in this case PHP classes). This has the goal of modeling every section of the web page, where you will get inputs from the user.

My actual base design is:

One class per table and every row is represented by an Object of this class.
The constructors asks for what they need in order to get the table row which they will represent:

info = $this->getRowFromVideos($id);
    }
}

The way I access the DB is not important here.

Every field of the table is stored as an array in an $info variable. And I have a method to access for the whole row or just a field.

    function getInfo($key = false){
        if($key) return $this->info[$key];
        else return $this->info;
    }

For composed tables like Players who needs an User and a Game ID, the query would be like this:

SELECT * FROM players WHERE userID = 'xxxxxx' AND gameID = 'SC2'

And the constructor class asks for an User object and Game object:

class Player extends DB {
    private $info = array();
    private $user;
    private $game;

    public function __construct($user, $game){
        $this->user = $user;
        $this->game = $game;
        $this->info =
              $this->getRowFromPlayers($user->getInfo("userID"),$game->getInfo("gameID"));
    }
}

Of course, these classes are not designed to satisfy CRUD needs, like inserting a new user or deleting a video. Those responsibilities would be encapsulated in other classes.

I cannot see which problems may appear with this design in the future if the web page gets really big.


texts:
Is the implementation clean enough & can be used in production?
I tried to write clean & bug-free code. It looks good to me.

I would appreciate any improvement suggestions.

One question I have is, what are the corner cases one might need to consider while implementing a Queue like this that might be part of a 3rd party library?

  I am aware of the build-in C# Queue type. In production obviously that's what I would use

using System;

internal class Queue
{
    private System.String[] _container;
    private System.Int32 _topHook = 0;
    private System.Int32 _downHook = 0;

    public Queue(System.Int32 capacity = 5)
    {
        _container = new System.String[capacity];
    }

    public bool IsEmpty() => Count == 0;

    public System.Int32 Count { get { return _topHook - _downHook; } }

    public void Enqueue(System.String item)
    {
        if(Count == _container.Length) ReSize(Count * 2);
        _container[_topHook++] = item;
    }

    public System.String Dequeue()
    {
        if(IsEmpty()) throw new Exception("No Element In Queue");
        if(Count == _container.Length / 4) ReSize(Count * 2);

        var dequeuedValue = _container[_downHook++];

        _container[_downHook - 1] = null;

        return dequeuedValue;
    }

    private void ReSize(System.Int32 capacity)
    {
        System.String[] container = new System.String[capacity];
        var j = 0;

        for(var i = 0; i < _container.Length; i++)
            if(_container[i] != null)
                container[j++] = _container[i];

        _container = container;
        _topHook = Count;//_topHook will point to the NEXT element
        _downHook = 0;
    }

}


texts:
I have developed a service to automatically detect whether an app has started. If the user forbid this app to start (could be chosen from a list of apps), a dialog will be shown.

public class AppStartReceiver extends Service {
    private static final int DELAY_IN_MS = 2000;
    private List<String> forbiddenApps = new ArrayList<String>();
    private BroadcastReceiver screenReceiver = null;
    private Timer timer;
    private static boolean screenOn = true;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //register screen on/off receiver
        registerScreenReceiver();

        if (forbiddenApps.isEmpty()) {
            DatabaseHelper db = new DatabaseHelper(this);
            forbiddenApps = db.getAllApps();
        }

        //start listening for app starts
        listenForAppStarts();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(screenReceiver);
        timer.cancel();
        super.onDestroy();
    }

    /**
     * start listening for apps to start
     * only foreground apps are being watched
     */
    private void listenForAppStarts() {
        final ActivityManager actMgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {
                final String foregroundApp = actMgr.getRunningTasks(1).get(0).topActivity.getPackageName();
                if (forbiddenApps.contains(foregroundApp)) {
                    //forbidden app detected => show dialog
                    Intent dialogIntent = new Intent(getBaseContext(), AlertActivity.class);
                    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(dialogIntent);
                }

                // stop if user turns screen off
                if(!screenOn) {
                    timer.cancel();
                }
            }
        }, 0, DELAY_IN_MS);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    /**
     * register screen receiver
     * gets callback from it
     */
    private void registerScreenReceiver() {
        // create new receiver
        screenReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    Log.i("ScreenReceiver", "Screen off");
                    screenOn = false;
                } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    Log.i("ScreenReceiver", "Screen on");
                    listenForAppStarts();
                    screenOn = true;
                }
            }
        };

        //register receiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(screenReceiver, filter);
    }

}

I works perfectly, but I don't know how good it is (does it drain too much battery?). Also, I'd like to know if my programming style is ok.


texts: Find next consecutive prime and find nth prime

texts:
Code review for best practices, optimizations, bug detection etc. Also please verify my complexity as mentioned within the function comments.

/**
 * Util class with 2 functions,
 * 1. find the next consecutive prime
 * 2. find the nth prime.
 */
public class PrimeUtil {

    private PrimeUtil() {}

    private static List<Integer> findAllPrimes(int upperBound) {
        assert upperBound > 0;

        final List<Integer> primeList = new ArrayList<Integer>();
        int squareRoot = (int) Math.sqrt(upperBound);

        boolean[] nonPrime = new boolean[upperBound + 1];

        for (int m = 2; m <= squareRoot; m++) {
            if (!nonPrime[m]) {
                primeList.add(m);
                for (int k = m * m; k <= upperBound; k += m)
                    nonPrime[k] = true;
            }
        }

        for (int m = squareRoot; m <= upperBound; m++) {
            if (!nonPrime[m]) {
                primeList.add(m);
            }
        }

        return primeList;
    }

    /**
     * Returns the next / consecutive prime number of input number.
     *
     * Complexity: O (m * n) where m is number of primes till the input number, n is the difference between (to be found prime - input number)
     *
     * @param number The number whose next prime should be returned
     * @return        The next / consecutive prime number of input prime.
     */
    public static int nextPrime (int number) {
        if (number <= 0) {
            throw new IllegalArgumentException("The value of n is " + number + ". It should be greater than 0");
        }

        int nextNum = number + 1;
        boolean notPrime = true;
        final List<Integer> primes = findAllPrimes(number);

        while (notPrime) {

            notPrime = false;
            for (int i : primes) {
                if (nextNum % i == 0) {
                    notPrime = true;
                }
            }
            if (notPrime) {
                nextNum++;
            }
        }

        return nextNum;
    }

    /**
     * Returns the nth prime number.
     *
     * Complexity: O(n * m) where n is the prime number, and m is number of primes till the n.
     *
     * @param n     the nth prime number to be found.
     * @return      the nth prime number
     */
    public static int nthPrime(int n) {
        if (n <= 0) {
            throw new IllegalArgumentException("The value of n is " + n + ". It should be greater than 0");
        }

        final List<Integer> primes = new ArrayList<Integer>();
        int number = 2;

        while (primes.size() < n) {
            boolean notPrime = false;
            for (int i : primes) {
                if (number % i == 0) {
                    notPrime = true;
                }
            }
            // if you are a prime.
            if (!notPrime) {
                primes.add(number);
            }
            number++;
        }

        return primes.get(primes.size() - 1);
    }

    public static void main(String[] args) {
        System.out.println("Expected 101, Actual: " + nextPrime(100));
        System.out.println("Expected 17, Actual: " + nextPrime(15));

        System.out.println("Expected 7, Actual: " + nthPrime(4));
        System.out.println("Expected 29, Actual: " + nthPrime(10));
    }
}


texts: Is this validation sufficient to ensure that the vals are not empty?

texts:
I'm working on a small winforms app, the goal of which is to capture data and write to xml. I'm still a child where programming is concerned so could you guys please take a look and suggest changes as I'm pretty sure that this is not a good approach.
I'm using a masked-textbox for the invoice number which should only contain numbers. I'm trying not to use a numupdown for obvious reasons.

InputVars is a public class with empty string properties (string value {get;set;})

    private bool TestVal(string testedVal)
    {
        if (!String.IsNullOrEmpty(testedVal))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private InputVars SetSemVars()
    {
        InputVars inVars = new InputVars();
        if (TestVal(txtCapt.Text))
        {
            inVars.captured = txtCapt.Text;
        }
        else
        {
            MessageBox.Show("Please insert your name here");
            txtCapt.Focus();
        }
        if (TestVal(mtxtInvoiceNumber.Text))
        {
            inVars.invoice = mtxtInvoiceNumber.Text;
        }
        else
        {
            MessageBox.Show("Please insert the invoice number here");
            mtxtInvoiceNumber.Focus();
        }
        if(TestVal(cmbNetwork.SelectedIndex.ToString()))
        {
            inVars.network = cmbNetwork.SelectedIndex.ToString();
        }
        else
        {
            MessageBox.Show("Please select the network ");
            cmbNetwork.Focus();
        }
        if(TestVal(cmbRegion.SelectedIndex.ToString()))
        {
            inVars.region = cmbRegion.SelectedIndex.ToString();
        }
        else
        {
            MessageBox.Show("Please select your office code here");
            cmbRegion.Focus();
        }
        if(TestVal(cmbSupplier.SelectedIndex.ToString()))
        {
            inVars.supplier = cmbRegion.SelectedIndex.ToString();
        }
        else
        {
            MessageBox.Show("Please select the supplier here");
            cmbSupplier.Focus();
        }
        return inVars;
    }

I was playing around earlier and got this to work , just thought I'd share

        foreach (TextBox box in this.panel1.Controls.OfType<TextBox>())
        {
            if (String.IsNullOrWhiteSpace(box.Text))
            {
                box.Text = "Enter value here";
                //or do a messagebox etc.
                box.Focus();
                return;
            }

        }

that`s loads and loads shorter and easier to read and makes sure that I don't forget a value... me gusta


texts:
This is a partial code of my JavaScript app.

The openDoc function's task is:
call newDoc if use uploads a file through fileInput.
Or, when user drag and drop a file in the document.

I want to review my logic and code.

      function stopDefault(event) {
        event.stopPropagation();
        event.preventDefault();
      }

      function openDoc(event) {
        var files = event.target.files || event.dataTransfer.files,
          file = files[0],
          reader = new FileReader();
        if (file) { // prevent TypeError
          stopDefault(event); // prevent default file drop behavior
          reader.readAsText(file);
        }
        reader.addEventListener("load", function(event) {
          newDoc(event.target.result, file.name);
        });
      }

  fileInput.addEventListener("change", openDoc);
  document.addEventListener("dragover", stopDefault);
  document.addEventListener("drop", openDoc);

If you're interested, checkout the full code - https://dl.dropboxusercontent.com/u/92126558/app.js


texts: Project Euler Smallest Multiple w/ JavaScript

texts:
Question 5 for Project Euler is finding the smallest multiple of 1 - 20. My solution is not even close to most of the solutions I've researched. Any feedback, good or bad, is greatly appreciated as I've been self teaching how to code on and off the past year and a half.

function smallestMultiple()
{
  var smallest = 0;
  var found = false;
  var i = 0;
  while(!found)
    {
      i++
      if(i % 11 === 0 && i % 12 === 0 && i % 13 === 0 && i % 14 === 0 && i % 15 === 0 && i % 16 === 0 && i % 17 === 0 && i % 18 === 0 && i % 19 === 0 && i % 20 === 0)
        {
          smallest = i;
          found = true;
        }
    }
  return smallest;
}


texts: Thread await and execute different methods based on some event or value

texts:
Use case:

I am writing a proactive session updater; The use case is for parallel API calls or sequential API calls intercept the API call and check whether token is valid.

If token is valid continue with call
If token is invalid first update the token then continue with API call.

This is a cakewalk for sequential calls however for parallel calls I want to avoid DDOSing my server for repeated token calls.

Instead I have the following flow:

Suppose a burst of five parallel calls is intercepted by my token updater
The first call (Thread) goes to update the token, all the other four will await till token is updated by the first call. Once the token is updated, other threads continue with normal execution hence skipping the token updation.

Another point here is that requests might appear in bursts 5 API calls at T=1 and 10 API calls at some T=2 so I am also interested in resetting values
(as in executionLatch)

Now the code I have for implementing this is loaded with frameworks and Jargon, instead for simplicity sake I have come up with a below skeleton of exceution:

class SingleUpdater {

    private val lock = ReentrantLock()
    private val executionLatch = AtomicBoolean(false)

    // Say valueToBeUpdated is my session token
    private val valueToBeUpdated = AtomicInteger(0)

    private val awaitingThreadsCounter = AtomicInteger(0)

    fun start() {
        for (i in 0 until 100) {
            Thread(this::execute).start()
            Thread(this::execute).start()
            Thread(this::execute).start()
        }

        Thread.sleep(3000)

        for (i in 0 until 1) {
            Thread(this::execute).start()
            Thread(this::execute).start()
            Thread(this::execute).start()
        }

    }

    private fun execute() {

        println("Trying to acquire lock ${Thread.currentThread().name}")
        try {
            awaitingThreadsCounter.set(awaitingThreadsCounter.get() + 1)
            println("============================= awaitingThreadsCounter = ${awaitingThreadsCounter.get()} ============================= ")
            lock.lock()
            println("I am Thread ${Thread.currentThread().name} I have acquired lock")
            if (executionLatch.get()) {
                continueWithRestOfExecution()
            } else {
                doUpdate()
                continueWithRestOfExecution()
            }

        } catch (e: Exception) {
            e.printStackTrace()

        } finally {
            println("Released by ${Thread.currentThread().name}")
            lock.unlock()

        }

    }

    private fun continueWithRestOfExecution() {
        if (awaitingThreadsCounter.get() >= 0) awaitingThreadsCounter.set(awaitingThreadsCounter.get() - 1)
        println("I am Thread: ${Thread.currentThread().name} and I am executing continueWithRestOfExecution")
        if (awaitingThreadsCounter.get() == 0) {
            println(" =============================  BALANCED  ============================= ")
            executionLatch.set(false)
        }
    }

    private fun doUpdate() {
        try {
            Thread.sleep(3000)
            valueToBeUpdated.set(valueToBeUpdated.get() + 1)
            println("=============================== Value is: $valueToBeUpdated ${Thread.currentThread().name} ===============================")
            executionLatch.set(true)
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }

}

Please help in analysing edge cases here.


texts:
I created the most simple though still quite flexible jQuery slider ever! Or at least, I hope so.

var slider = $(".slider-ul");

slider.each(function () {

    var e = $(this),
        images = e.find("li"),
        current = null;

    slide();

    function slide() {

        images.each(function() {

            var li = $(this),
                next,
                pDone = false,
                sDone = false;

            if (li.hasClass("primary")) {
                li.removeClass("primary");
                pDone = true;
            } else if (li.hasClass("secondary")) {
                li.removeClass("secondary").addClass("primary");

                next = li.next();

                console.log(next);
                if (next.size()) {
                    next.addClass("secondary");
                    sDone = true;
                } else {
                    images.filter(":first").addClass("secondary");
                    sDone = true;
                }
            }

            if (sDone && pDone) {
                return false;
            }
        });

        setTimeout(slide, 5000);

    }
});

How does this look?


texts:
I think I've done a decent job keeping this query simple and understandable, but I'd like to know if you have some more advice.

My relevant entities are defined like this:

public class Task
{
    [ForeignKey("Employee")]
    public string EmployeeId { get; set; }
    public Employee Employee { get; set; }

    [Required]
    [ForeignKey("Status")]
    public int StatusId { get; set; }
    public TaskStatus Status { get; set; }

    [...]
}

public class Employee
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Required]
    [MaxLength(10)]
    [Index(IsUnique=true)]
    public string EmployeeId { get; set; }

    [Required]
    [StringLength(100)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100)]
    [DisplayName("Last name")]
    public string LastName { get; set; }

    [...]
}

public class TaskStatus
{
    [Key]
    public int Id { get; set; }

    [Required]
    [MaxLength(50)]
    public string Name { get; set; }

    [...]
}

I've stripped off what I believe are irrelevant parts of the entities.

The query itself is following:

// Retrieves all tasks from the database. We filter the tasks on 3 different criteria. Since all 3 criteria
// must be fulfilled for the task to be displayed, we use logical and to concatenate them.
//
// The first criteria is the search term. If the search term is empty, we don't filter out any tasks, so
// that is the first check we make. Also, we test if the FistName, LastName or the EmployeeId contain the
// search term.
//
// Next criteria is the status filter. We keep the tasks that have the right status, or all tasks if the
// given status is null.
//
// The last criteria is employee filter, and the logic is the same as for the status filter.
var tasks = db.Tasks
    .Include(t => t.Employee)
    .Include(t => t.Status)
    .Where(t =>
        (
            search == null
            || t.Employee.FirstName.Contains(search)
            || t.Employee.LastName.Contains(search)
            || t.Employee.EmployeeId.Contains(search)
        )
        && ((statusFilter == null) || (t.StatusId == statusFilter.Value))
        && ((employeeFilter == null) || (t.EmployeeId == employeeFilter))
    );

The query does what it is supposed to do, it filters the task list properly on all 3 parameters. I'm just worried that it is a little too unreadable (too tricky), especially since my colleagues are mostly young and inexperienced.


texts:
I just want to confirm that I am versioning my "versionable" fields correctly, and that there isn't another, better way to do this.

I have a table event, a record of an event in time. It has some fields that I want to be invariant, like it's ID and event series it is associated with. It also has some fields that I want to be editable, like the date or the description. The other issue is that I have foreign keys on the auto_increment ids of both tables, which is why I think I need two tables and not just one, or?  But I also want to keep the history of the variant fields, So I created two tables:

invariant

id int
series int
active boolean

and

variant

eventID int //foreign key to the invariant ID field
id int //this table needs its own id which serves as a foreign key on another table
date Date
description varchar(255)
active boolean

When an edit is made to the variant fields, I am switching the active Boolean on existing rows with the same eventID to false. then when I insert my new version, I can get the just latest version on the invariant - variant join by specifying where active=true.

If/when I want to delete the event entirely, I am setting active to false in the invariant table.

As I said at the top, I just want to confirm that this is an optimal solution for the specified requirements, or if there are better ways or things I am not understanding


texts: Writing my first binary search by myself

texts:
Is there any way in which I can improve my code?  I don't know if it is 100% right, and if it can be tweaked in order to be more efficient. That's why I'm posting here.
I'm open to any suggestions :)
#include <iostream>

using namespace std;

int binarySearch(int arr[], int low, int high, int n)
{
    if (low <= high)
    {
        int i = (high + low) / 2;
        if (arr[i] == n)
        {
            return i;
        }
        else
        {
            if (arr[i] > n)
            {
                return binarySearch(arr, low, i - 1, n);
            }
            if (arr[i] < n)
            {
                return binarySearch(arr, i + 1, high, n);
            }
        }
    }
    return -1;
}

int main()
{
    int arr[10]{ 1, 2, 3, 4, 5, 6, 8 }, n = 7;
    cout<<binarySearch(arr, 0, 6, 9);
    return 0;
}

Thanks.


texts: Javascript + php system for reusable HTML templates

texts:
I have many pieces of HTML code that are used in many parts of the website (controlled by javascript), like edit forms and dialogs. Instead of include-ing the html files using php, I made a system for storing these elements in a javascript variable array such that I can choose which files to include in each page and which files will be downloaded via ajax (and cached) only in the case they are needed.

Is this generally a good approach or should this kinda stuff be handled differently?

javascript file

var templates = [];

// convenience method for getting a copy of a template
async function copyTemplate(filename){
   return await getTemplate(filename, true);
}

// get a template from cache, or if not found download it via ajax
async function getTemplate(filename, returnClone = false){
   let template = templates[filename];
   if(template == undefined){
      template = templates[filename] = await getElementAjax('templates/' + filename);
   }
   return returnClone ? template.cloneNode(true) : template;
}

// called from code echoed by php to include some
// templates without additional http requests
function saveTemplate(template){
   const templateElem = template.content.firstElementChild;

   const buttons = templateElem.querySelectorAll('button');
   for(let i = 0; i < buttons.length; i++){
      preventAutoSubmit(buttons[i]);
   }
   templates[template.getAttribute('data-file')] = templateElem;
}

// gets an element from a file via ajax, I excluded the
// implementation of functions called by this function for brevity.
async function getElementAjax(url) {
   const response = await ajax(url, 'GET', null, 'document');
   const mainElem = response.getElementsByTagName('body')[0].firstElementChild;
   const buttons = mainElem.querySelectorAll('button');
   for(let i = 0; i < buttons.length; i++){
      preventAutoSubmit(buttons[i]);
   }
   return mainElem;
}

php file

function includeTemplates(){
   $args = func_get_args();
   foreach($args as $url){
      $code = file_get_contents('templates/' . $url);
      echo "<template data-file='$url'>$code</template>";
   }
?>
<script>
   {
      const templates = document.getElementsByTagName('template');
      for(let i = templates.length - 1; i >= 0; i--){
         if(templates[i].hasAttribute('data-file')){
            saveTemplate(templates[i]);
            templates[i].remove();
         }
      }
   }
   document.currentScript.remove();
</script>
<?php
}

Usage example

<?php includeTemplates('logs/logEntry.html',
                       'logs/logEntryEditForm.html',
                       'foo/bar.html'
                      ); ?>
<script>
   async function populateLog(){
      const logEntries = await getLogEntries();
      const logContainer = document.getElementById('logContainer');

      for(entry of logEntries){
         const entryElem = await copyTemplate('logs/logEntry.html');
         //
         // ... set textContent and other properties for elements in entryElem ...
         //
         logContainer.appendChild(entryElem);
      }
   }
</script>


texts: Evaluating RPG-formatted dice rolls with repeats in Clojure

texts:
My target was to write a function that takes a String as input, interprets it as a series of dice rolls, evaluates it and returns a series of integers.

The input is in a form that is typical in table top RPGs, slightly extended:

1d20; d20; 20 - Roll a single twenty sided die, result would be e.g. 12
2d6 + 4 - Roll two six sided dice and add 4 to the sum, result would be e.g. 12 (5 [d6] + 3 [d6] + 4)
d20, d20; 20, (note the comma) - Roll two twenty sided dice and display the results separately, result would be e.g. 6 // 14

I handled the parsing with instaparse. The function I am interested in feedback for, which you'll find below, is the one that then transforms a single "roll".

According to my specifications, I can add any number of commas (,) to a roll (a series of dice and constant modifiers). I opted to have those additional trailing commas parsed as being part of the preceding roll, syntactically, being added as :repeat flags to the end of the syntax tree. Because these rolls can be repeated, I had to pass functions instead of values, so the repeated rolls would actually yield different results. That means example arguments to this function can look like this:

[#(d 4 12) #(+ 5) :repeat :repeat] - which would correspond to "4d12 + 5,,", where d is defined as follows:

(defn d
    ([count faces]
     (reduce + (map d (repeat count faces))))
    ([faces] (inc (rand-int faces))))

Without further ado:

(defn roll [& dice-info]
    (let [until-repeat (complement {:repeat true})
          [dice repeat] (split-with until-repeat dice-info)
          eval #(%)
          eval-dice #(map eval dice)
          eval-roll (fn [_] (apply + (eval-dice)))]
        (map eval-roll (cons :repeat repeat))))

I am particularly interested in how idiomatic this is, and whether the approach I've chosen is reasonable, but of course any input is welcome.

Here is the grammar text:

Series = Roll ( <','> Roll )*

Roll = <S?> ( QuickDie | ( Die ( <S?> Modifier)* ) ) <S?> Repeat*
Repeat = <',' S?>

Die = Integer? <'d'> Integer
QuickDie = Integer
Integer = #"([1-9][0-9]*|0)"

<Modifier> = ( Plus | Minus )
Plus = <'+'> <S?> Addend
Minus = <'-'> <S?> Addend
<Addend> = ( Integer | Die )

S = #"\s+"

And for completeness' sake, the whole code: DiceRoll.clj and DiceRoll.eval.clj.


texts: Computing six dot products involving one common input vector

texts:
I have created a Matlab Simulink model with a series of dot products.

Embedded Coder generates a for loop for each dot product, as evidenced by this excerpt of the generated output:

/* DotProduct: '<S3>/Dot Product1' incorporates:
 *  Inport: '<Root>/LngPwr'
 */
EPAR_SPAF_dot_B.DotProduct1 = 0.0F;
for (temp_ = 0; temp_ < 24; temp_++) {
  EPAR_SPAF_dot_B.DotProduct1 += temp_DataTypeConversion[temp_] *
  LngPwr[temp_];
}
/* End of DotProduct: '<S3>/Dot Product1' */

/* DotProduct: '<S3>/Dot Product2' incorporates:
 *  Inport: '<Root>/ShrtPwr'
 */
EPAR_SPAF_dot_B.DotProduct2 = 0.0F;
for (temp_ = 0; temp_ < 24; temp_++) {
  EPAR_SPAF_dot_B.DotProduct2 += temp_DataTypeConversion[temp_] *
  ShrtPwr[temp_];
 }
/* End of DotProduct: '<S3>/Dot Product2' */

Can I improve the Simulink model such that it will compile to better code?

I want to avoid using embedded matlab or a S-function for the purposes of maintainability.


texts:
I have wrote a small project for Android. It's an app which lets you to take a photo (or find one with Flickr) and save it in the cloud (Cloudinary).

Link to the GitHub repository.

Should MVP layers be completely separated?

In the repository layer I have two DbPhoto classes (one for local database [SQLite] and one for cloud database [Firebase]), that are converted to Photo class in model. Photo class is used also in View. Should View has its own class?

DbPhoto for local database:

package org.chyla.photoapp.Repository.LocalDatabase.GreenDao.detail;

import org.greenrobot.greendao.DaoException;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Index;
import org.greenrobot.greendao.annotation.NotNull;
import org.greenrobot.greendao.annotation.ToOne;

@Entity(
        indexes = {
                @Index(value = "dbUserId,title,description,url", unique = true)
        }
)
public class DbPhoto {

    @Id
    private Long id;

    @NotNull
    private Long dbUserId;

    @ToOne(joinProperty = "dbUserId")
    private DbUser dbUser;

    @NotNull
    private String title;

    @NotNull
    private String description;

    @NotNull
    private String url;

/** Used to resolve relations */
@Generated(hash = 2040040024)
private transient DaoSession daoSession;

/** Used for active entity operations. */
@Generated(hash = 1256174471)
private transient DbPhotoDao myDao;

@Generated(hash = 1342142122)
public DbPhoto(Long id, @NotNull Long dbUserId, @NotNull String title,
        @NotNull String description, @NotNull String url) {
    this.id = id;
    this.dbUserId = dbUserId;
    this.title = title;
    this.description = description;
    this.url = url;
}

@Generated(hash = 95134667)
public DbPhoto() {
}

public Long getId() {
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}

public String getTitle() {
    return this.title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return this.description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getUrl() {
    return this.url;
}

public void setUrl(String url) {
    this.url = url;
}

// ... (generated functions)

DbPhoto for cloud database:

package org.chyla.photoapp.Repository.CloudDatabase.Firebase.detail;

public class DbPhoto {

    public String title;
    public String description;
    public String url;

    public DbPhoto() {
    }

    public DbPhoto(String title, String description, String url) {
        this.title = title;
        this.description = description;
        this.url = url;
    }

}

Photo class for model and view:

package org.chyla.photoapp.Main.Model.objects;

import android.support.annotation.Nullable;

import java.net.URL;

public class Photo {

    private final String title;
    private final String description;
    private final URL url;

    public Photo(String title, @Nullable String description, URL url) {
        this.title = title;
        this.description = description;
        this.url = url;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        if (description == null) {
            return "";
        }
        else {
            return description;
        }
    }

    public URL getUrl() {
        return url;
    }

}

I'm open to every suggestion improvements for my project.


texts:
I have a quick script I came up with and I was wondering if this is a bad idea.

First let me explain what I want to do. I want to create a dynamic script which will add custom AJAX calls for whatever tab element I need it to. For instance, if the user clicks on Profile, then I want to load profile.php from my files.

This is simple enough, however, I have a lot of calls, and I came up with a quick fix. I am creating an array with all the scripts I need to call in PHP, and when the page loads PHP it creates AJAX call functions from the array list:

<?php
$tab_options = array('home', 'profile', 'news', 'api');
foreach ($tab_options as $option)
{
    ?>
    $(<?php echo $option; ?>).click(function() {
        $.ajax({
            type: "POST",
            url: "_template/<?php echo $option; ?>.php",
            dataType: "html",
            success: function(response){
                window.top.document.title = '<?php echo ucwords($option); ?>';
                window.history.pushState("string", "<?php echo ucwords($option); ?>", "?tab=<?php echo $option; ?>");
                $("#<?php echo $option; ?>").html(response);
            },
            error: function(){
                console.log("Problem found!");
            }
        });
    });
    <?php
}
?>

So in this case I would have PHP loop 4 times over the code, and create the 4 functions for me. It works well, and I am able to switch between tabs smoothly. However, I am not sure if this is good practice, or if it should be avoided.


texts: Find minimum count of items where sum of them is X from an array

texts:
I recently faced an interview question where you have to find minimum needed items from an array that can added together to generate X value.
For example giving:
[1, 9, 2, 5, 3, 10] and the goal is: 13, => it should be [10, 3]

You can't use any number out side of array.

I have tried to sort items and take from the head one by one and some other stuff, but no lucks. Although, I have solved this by a not really performant solution and I will post it as an answer. I am looking for a more performant solution.
Solution:
First we have to find all subsets of the array:
extension Array {
    var allSubsets: [[Element]] {
        guard count > 0 else { return [[]] }

        let tail = Array(self[1..<endIndex])
        let head = self[0]
        let withoutHead = tail.allSubsets

        let withHead = withoutHead.map { $0 + [head] }

        return withHead + withoutHead
    }
}

Then we can filter all subsets that their sum is equal to the goal like:
subsets.filter { $0.reduce(0) { $0 + $1 } == goal }

And lastly, find the smallest subset by its count:
func minimumElements(in array: [Int], goal: Int) -> [Int] {
    let subsets = array.allSubsets

    let validSubsets = subsets.filter { subset in
        subset.reduce(0) { $0 + $1 } == goal
    }

    return validSubsets.reduce(array) { $0.count < $1.count ? $0 : $1 }
}

This question was originally asked and answered in StackOverflow but moved here as suggestion.


texts:
I am very new in Python, I would like to know if the style presented below attends a good implementation in Python.

import numpy as np
from collections import deque

def BFS(theGraph,source):
    n=len(theGraph)
    explored=np.empty(n,bool)
    for i in range(0,n):
        explored[i]=False
    explored[source]=True
    queue = deque([source])
    while len(queue)!=0:
        v=queue.popleft()
        print "theNode: ", v
        for i in theGraph[v]:
            if(not explored[i]):
                explored[i]=True
                queue.append(i)
    return explored

def DFS(theGraph,source):
    n=len(theGraph)
    explored=np.empty(n,bool)
    for i in range(0,n):
        explored[i]=False
    explored[source]=True
    stack = [source]
    while len(stack)!=0:
        v=stack.pop()
        print "theNode: ", v
        for i in theGraph[v]:
            if(not explored[i]):
                explored[i]=True
                stack.append(i)
    return explored

def DFSrec(theGraph,explored,source):
    explored[source]=True
    print "theNode: ",source
    for i in theGraph[source]:
        if(not explored[i]):
            DFSrec(theGraph,explored,i)
    return explored

n=6 #number of nodes

theGraph=[set() for i in range(n)]

theGraph[0].add(1)
theGraph[0].add(2)
theGraph[1].add(0)
theGraph[1].add(3)
theGraph[2].add(0)
theGraph[2].add(4)
theGraph[3].add(1)
theGraph[3].add(5)
theGraph[4].add(2)
theGraph[4].add(5)
theGraph[5].add(3)
theGraph[5].add(4)
print theGraph

print "DFS: "
print DFS(theGraph,0)

explored=np.empty(n,bool)
for i in range(0,n):
    explored[i]=False

print "DFSrec: "
print DFSrec(theGraph,explored,0)

print "BFS: "
print BFS(theGraph,0)


texts: Easy to use code preparation script for CodeReview questions

texts:
We all face questions that forget to include their code. Sometimes all of it, sometimes only parts, that make the rest of the question unfortunately incomplete and therefore off-topic.

What if it was possible to remedy that behavior with a simple script? What if said script fits in a single comment, at least in a less featured variant?

Goals

A POSIX compatible script that prints all files in the current directory in the following format:

## File: <path-to-file>

     source code line 1
     source code line 2
     source code line 3
     ...

Therefore, no bashism (like variable arrays), GNU extensions to find or similar.

The script must only depend on POSIX variants of sh, find and sed. Shellcheck must pass without errors or warnings.

By default, it should print only C/C++ related files and skip the .git and build folders that are often found in those projects. Both options should be configurable via environment variables.

The complete script

#!/bin/sh
FILE_HEADING="## File: %s\n\n"
IGNORED_DIRS="${IGNORED_DIRS:-build .git}"
EXTENSIONS="${EXTENSIONS:-c cc cpp h hpp}"

PRUNE_RULES=""
for dir in ${IGNORED_DIRS}; do
  PRUNE_RULES="${PRUNE_RULES} -name ${dir} -prune"
done

RULE_GLUE=""
if [ -n "${PRUNE_RULES}" ]; then
  RULE_GLUE="-o"
fi

NAME_RULES=""
for ext in ${EXTENSIONS}; do
  if [ -z "${NAME_RULES}" ]; then
    NAME_RULES="-name '*.${ext}'"
  else
    NAME_RULES="${NAME_RULES} -o -name '*.${ext}'"
  fi
done

if [ -n "${NAME_RULES}" ]; then
  NAME_RULES="\\( ${NAME_RULES} \\)"
fi

sh << EOF
    find . ${PRUNE_RULES} ${RULE_GLUE} ${NAME_RULES} \
           -exec sh -c "printf '${FILE_HEADING}' {} && sed 's/^/    /' {}" \\;
EOF

Usage:

cd repository
EXTENSIONS=rb IGNORED_DIRS="gem .git" path/to/script.sh

The second sh call is necessary as find doesn't work with multiple-options in a single argument. Every option for find needs to be in its own argument (e.g. find . '-name' '*' is fine, find . '-name *' is not).

Wait, I was promised a command that fits in a single comment!

For a comment, we can make some adjustements. First of all, we don't need to prune, as .git folders don't contain source code (not counting hooks). However multiple spaces in comments will get replaced by a single one, even in code, so you have to use a tabulator instead:

find . -name '*.hs' -exec sh -c 'printf "## File: %s\n\n" {} && sed "s/^/\t/" {}' \;

You should adjust the file type to the users question, of course. If you're sure that they have GNU find installed, it gets a little bit easier:

find . -o -name '*.rb' -printf "## File: %P\n\n" -exec  sed "s/^/\t/" {} \;

That being said, for some languages like Rust or JavaScript, you really should ignore their additional directories, or at least tell the user to check their post.

Those two variants are also eligible for review, although the latter doesn't follow the POSIX and the settings goals anymore


texts:
I am building a backend to a mobile application that will be hosted on a Django site connected to a PostgreSQL database.

I have never built anything to accomplish this before and this is my first go at it. I have not studied this type of application before so please let me know if the below code follows best practices for this task, is secure, and doesn't have any obvious problems.  If there is an industry standard for this that is very different, please let me know what it is and why it is preferred.

My client connects via the view readJSON:

@csrf_exempt
def readJSON(request):
    if request.method == 'POST':
        try:
            c = connections['postgres_db'].cursor()
            json_data = json.loads(request.body)
            if json_data['tag'] == 'register':
                return HttpResponse(cc().register(c, json_data))
            elif json_data['tag'] == 'syncprofile':
                return HttpResponse(cc().syncProfile(c, json_data))
################ A long list of other possible tags
            else:
                raise Http404
        finally:
            c.close()
    else:
        raise Http404

I have a separate class that holds all the code to handle the incoming JSON requests. This is one such function.

    def register(self, c, json_data):
    import bcrypt as bc
    salt = bc.gensalt()
    pwrd = json_data['data']['password']
    hash = bc.hashpw(pwrd, salt)
    try:
        c.execute("INSERT INTO profiles VALUES (DEFAULT, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
            (json_data['data']['email'], hash, salt, json_data['data']['date_created'],
            json_data['data']['state_lvl'], True,
            json_data['data']['first_name'], json_data['data']['last_name'],
            json_data['data']['sex'], json_data['data']['age'],
            json_data['data']['state'], json_data['data']['country'],
            json_data['data']['language'], json_data['data']['device_type'],
            json_data['data']['device'], json_data['data']['device_width'],
            json_data['data']['device_height'], json_data['data']['device_screen_density']
        ))
        json_response = json.dumps({"success": 1, "errors": 0})
        return HttpResponse(json_response, mimetype="application/json")
    except Exception,e:
        json_response = json.dumps({"success": 0, "errors": 1, "msg": str(e)})
        return HttpResponse(json_response, mimetype="application/json")

And here is the JSON structure for the above function.

    {
   "tag":"register",
   "data":{
      "email":"email@email.com",
      "password":"app123",
      "date_created":"07/10/1967",
      "state_lvl":"1",
      "first_name":"John",
      "last_name":"Smith",
      "sex":"m",
      "age":23,
      "state":"CA",
      "country":"USA",
      "language":"english",
      "device_type":"phone",
      "device":"Nexus-5",
      "device_width":400,
      "device_height":800,
      "device_screen_density":331
   }
}


texts: Upsert query using CTE in PostgreSQL 9.4

texts:
I have a generic pipeline in SnapLogic that logs the start time of the executions of a group of incremental jobs. Suppose, the log table is as follows.

CREATE TABLE sl_control.interface_parameters_values (
    interface_id varchar NOT NULL,
    parameter_name varchar NOT NULL,
    parameter_value varchar NULL
);

A few points to remember:

There may or may not be an entry for a particular job (interface)
This generic pipeline only updates the IncrementalTimestamp parameter of the interface. So, there will be only one entry to insert/update per interface.
The individual values (for example, 'TEST0001', 'IncrementalTimestamp', 0) are being generated by a script and are being passed in batches of 150 to the query. So, VALUES part of the query will have at most 150 entries for each execution.
Although I'm setting the batch as 150, the average number of interfaces I'm expecting is ~30.

Following is my upsert query:

WITH
/* write the new values */
v (
    interface_id,
    parameter_name,
    parameter_value
) AS (
    VALUES ('TEST0001', 'IncrementalTimestamp', 0),
           ('TEST0002', 'IncrementalTimestamp', 0),
           ('TEST0003', 'IncrementalTimestamp', 0),
           ('TEST0004', 'IncrementalTimestamp', 0),
           ('TEST0005', 'IncrementalTimestamp', 0)
),
/* update existing rows */
upsert AS (
    UPDATE sl_control.interface_parameters_values ipv
    SET
        interface_id    = v.interface_id,
        parameter_name  = v.parameter_name,
        parameter_value = v.parameter_value
    FROM v
    WHERE (
            ipv.interface_id   = v.interface_id
        AND ipv.parameter_name = v.parameter_name
    )
    RETURNING ipv.interface_id
)
/* insert missing rows */
INSERT INTO sl_control.interface_parameters_values (
    interface_id,
    parameter_name,
    parameter_value
)
SELECT interface_id
     , parameter_name
     , parameter_value
FROM v
WHERE v.interface_id NOT IN (
    SELECT interface_id FROM upsert
)

I had to take this approach because this particular PostgreSQL instance is version 9.4 and it does not support the ON CONFLICT syntax.

This query is working fine but is there any way this can be optimized further? Or is there any unseen pitfall to this approach. If this approach is good then I'll use this in one of our integration pipelines.


texts:
I am building a cypher program which uses a matrix of numbers and letters. A message is encoded according to the row and column each letter of the message is found in the matrix.

I am trying to find a nice way of iterating over the 2D matrix (6*6).

 for char in range (0, len(message), 1):
  for i in range(0, len(rows), 1):
    for y in range(0, len(cols), 1):
      if matrix[i][y] == message[char]:
         cyphermessage.append(i)
         cyphermessage.append(y)
         cyphermessage.append(" ")

But this method uses a 3-tier for loop which makes it \$\mathcal{O}((N)*3)\$, plus the the cypher append messages are quite ugly.