texts:
I build phone apps and I use JSON a lot in my APIs. The problem is sometimes I don't know how to format the JSON data.

For example, an iOS UITableView takes NSArray as datasource.

{
    "contact_id": [
        "455",
        "464"
    ],
    "contact_name": [
        "Administrator",
        "Main contact"
    ]
}

For me it makes sense since I don't have to loop through anything, but I was told it is not safe to rely on the indices matching the position.

I remember, while asking questions, people bringing to my attention to be careful not to separate records into different arrays, and instead I should return array of objects:

[
    {
        "contact_id": "455",
        "contact_name": "Administrator"
    },
    {
        "contact_id": "464",
        "contact_name": "Main contact"
    }
]

I would like to know the best practice to formatting JSON.


texts: Get mod date to attach a version number to JS src script

texts:
Instead of the browser checking if the file was modified before serving the JS script (adds a few seconds to ping the server), or waiting for an arbitrary amount of time until the JS script expires, I have the PHP script instead attach a version number (e.g. script.js?v=123) to the JS script based off of the last modification date.

/**
 * Creates a new version once the file has been modified ensuring the user always receives the most updated file while still utilizing the browser cache
 *
 * @param $path string|array root: "/js/master/example.js" | local: "script.js"
 *
 * @return string
 */
function js($path){
    if(!empty($path)){
        if(is_array($path)){
            $return = '';
            foreach($path as $value){
                $return .= js($value);
            }
            return $return;
        } else {
            if (substr($path, 0, 1) <> '/') {
                $version = dechex(filemtime(getcwd().'/'.$path));
            } else {
                $version = dechex(filemtime(__DIR__.$path));
            }
            return "<script src='$path?v=$version'></script>\r\n";
        }
    }
    return false;
}


texts:
I've hacked together what feels like a mess for an authorize attribute to secure web api methods. The code appears to be functionally correct; passing the unit tests in place. The code has me worried because it will be executing with every call to any web api method and there is a lot going on, including string allocations and database access. I'm sure that a lot of my misgivings are due to premature optimization.

I am looking for a general review of the code; looking for obvious problems, possible performance bottlenecks etc.

The use of this attribute provides for three different scenarios. First, specifying the attribute with no users or roles means that the attribute should simply validate that the supplied user/password authenticate properly. Second, the attribute supports a comma separated list of usernames... so in addition to authenticating the user, it should also verify the user is in the permitted list. Finally, the attribute allows a comma separated list to denote allowed roles... this requires the user to authenticate and to be a member of one of the provided roles. The semantics are such with regard to user or role lists, passing either condition in additional to authenticating successfully should return a true result.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;

using WebMatrix.WebData;

using Appsomniacs.Web.Filters;

namespace Appsomniacs.Web.Handlers
{
    public class BasicAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var identity = Thread.CurrentPrincipal.Identity;

            if (identity == null &&
                HttpContext.Current != null)
            {
                identity = HttpContext.Current.User.Identity;
            }

            if (identity != null &&
                identity.IsAuthenticated)
            {
                var basicAuth = identity as BasicAuthenticationIdentity;

                if (basicAuth != null)
                {
                    if (WebSecurity.Login(basicAuth.Name, basicAuth.Password))
                    {
                        if (this.Users.Length > 0)
                        {
                            var allowedUsers = this.Users.ToUpperInvariant()
                                .Split(',');

                            if (allowedUsers.Contains(basicAuth.Name.ToUpperInvariant()))
                            {
                                return true;
                            }
                        }

                        if (this.Roles.Length > 0)
                        {
                            var allowedRoles = Roles.Split(',');

                            var userRoles = System.Web.Security.Roles.GetRolesForUser(basicAuth.Name);

                            var matches = userRoles.Intersect(allowedRoles).ToArray();

                            if (matches.Length > 0)
                            {
                                return true;
                            }
                        }
                        else
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
    }
}


texts: Basic game engine: timer, FPS and logic loop

texts:
I'm creating a simple Java game engine (just for fun). The idea is to create a basic framework for developing any kind of 2D game, an abstract engine that does the hard work. Would you like to review the core of it and give me some tips?

GameTimer class:

public class GameTimer {

    public static final double ONE_SECOND = java.util.concurrent.TimeUnit.SECONDS.toNanos(1);

    private long start;
    private long[] ticks = new long[1000];
    private int first, last;
    private int fps;

    public GameTimer(){}

    public void start(){
        this.start = System.nanoTime();
    }

    public void tick(){
        ticks[last] = System.nanoTime();
        while (ticks[last] - ticks[first] > ONE_SECOND){
            first = circular(first + 1);
            fps--;
        }
        last = circular(last + 1);
        fps++;
    }

    public long tock(){
        return System.nanoTime() - ticks[circular(last-1)];
    }

    public long getElapsedNanoTime(){
        long prev = ticks[circular(last-2)];
        return (prev == 0) ? 0 : ticks[circular(last-1)] - prev;
    }

    public double getElapsedTime(){
        return this.getElapsedNanoTime() / ONE_SECOND;
    }

    public long getNanoTime(){
        return System.nanoTime() - this.start;
    }

    public double getTime(){
        return this.getNanoTime() / ONE_SECOND;
    }

    public int getFPS(){
        return this.fps;
    }

    private int circular(int n){
        return Math.floorMod(n, ticks.length);
    }
}

Game loop:

double desiredFPS = 60d;
long sleep = (long) (GameTimer.ONE_SECOND / desiredFPS);
GameTimer timer = new GameTimer();
timer.start();

try {
    while(true){

        // tick and print fps
        timer.tick();
        System.out.println(timer.getFPS());

        // input, update and draw (abstract methods of my engine class)
        input();
        update();
        draw();

        // sleep
        long wake = System.nanoTime() + sleep - timer.tock();
        do {Thread.sleep(0);}
        while (System.nanoTime() < wake);
    }
} catch (InterruptedException e) {
    // oh someone paused the game
}

Notes:

For more precision, I'm using nanoseconds and a busy-waiting loop instead of just calling the Thread.sleep() method (it is incredibly inaccurate). My tests show that the engine can keep the desired frequency quite precisely.
I'm using a circular buffer to count the frames per second, I don't like that loop to count late ticks but I couldn't find a better way to do it.
The start variable and related get methods in the GameTimer it's just for game logic use, it isn't important for fps counting or tick/tock operations.


texts: Seeking the seeds for writing tidy event handlers in JS

texts:
I'm seeking a critique of the simple program below, which displays two counters and increments them through a button, using D3.js. In real life of course no one has a need for displaying buttons that increment counters. It's a stand-in to talk about how to craft the code over the scaffold of a trivial problem.

I would like to remain within function invocations, and to generally fit in seamlessly with D3. In particular, I do not wish to use constructor invocation or prototypal patterns. More concretely, I would like to use neither class nor new.

I would also like to avoid constantly asking myself "what is this in this instant?" by initializing that, as you see in the code (let's leave arguing that this is sometimes entirely compelling for another occasion).

function Incrementer(name, value) {
    let that = {};

    that.init = function() {
        that.name = name;
        that.span = d3.select('body')
                      .append('span')
                      .attr('id', '#num' + name)
                      .text(value);
    }
    that.init();

    that.increment = function() {
        let i = parseInt(that.span.text()) + 1;
        that.span
            .text(i);
    }
    return that;
}
var incrementer1 = Incrementer('one', 10);
var incrementer2 = Incrementer('two', 20);

function double_increment() {
    incrementer1.increment();
    incrementer2.increment();
}

d3.select('#inc')
  .on('click', double_increment);

// d3.select('#inc')
//   .on('click', incrementer1.increment);
// d3.select('#inc')
//   .on('click', incrementer2.increment);
span { margin-left: 40px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<button id="inc">Increment</button><br />

At this point I'm lacking a nice way to avoid the function double_increment. Of course without that function—were we to use the commented out pair of on-click handlers instead—we would have a bug. Only one on-click handler can be set. We have no mechanism for adding multiple addEventListeners.

So to summarize:

We define that.init as our initializer. That seems tidier than letting the initialization code loose in the body of the function. But defining it then immediately calling it seems odd. Can you improve on this?
How would you avoid the ugly double_increment function within a D3 program?

that.span.text() should probably be replaced by that.span.datum, if I can find the datum in there. But we'd like to avoid duplicating the counter within Incrementer. This way we do not need to worry about the counter and its view going out of sync. The datum itself, once located, is already a bit of a (necessary) duplication.


texts: How to speed up window leveling (brightness, contrast)?

texts:
I have to apply window leveling on Canvas Medical Image (CR).  I have to get a pixel array from C# Component.lutArr, which is a lookup table array coming as a C# component and which I use in JavaScript. On click of the button, I have to call the function ApplyWLCust().  In this function, all process done getting result perfect. For window leveling, use bit shifting, which takes around 585ms. I have to reduce this time.  What should I do?

var imagewc = document.getElementById("text1").value;
                var imageww = document.getElementById("text2").value;
pixelArr = [11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11..]
        if (pixelArr != null)
                {
                    for (var i = 0, n = pixelArr.length; i < n; i++)
                    {
                        pix = pixelArr[i];
                        pix = ApplyWL(pix, imagewc, imageww);
                        pix = lutArr[pix];

                    // var red = (pix & 0x00ff0000) >> 16;
                    v = i * 4;
                    imagedata[v] = pix & 0xff;
                    imagedata[v + 1] = (pix >>> 8) & 0xff;
                    imagedata[v + 2] = (pix >>> 16) & 0xff;
                    imagedata[v + 3] = 255;
                }
                //  offscreenCtx.imageSmoothingEnabled = true;
                offscreenCtx.putImageData(g, 0, 0);
            }
function ApplyWL(value, _valwindowCenter, _valwindowWidth)
        {
            Recalculate(_valwindowCenter, _valwindowWidth);
            if (value <= _windowStart)
                value = _minimumOutputValue;
            else if (value > _windowEnd)
                value = _maximumOutputValue;
            else
            {
                value = Math.round((((value - _windowCenterMin05) / _windowWidthMin1) + 0.5) * 255.0);
            }
            return value;
        }

        var _minimumOutputValue = 0;
        var _maximumOutputValue = 255;
        function Recalculate(_valwindowCenter, _valwindowWidth)
        {
            if (!_valid)
            {
                _windowCenterMin05 = _valwindowCenter - 0.5;
                _windowWidthMin1 = _valwindowWidth - 1;
                _windowWidthDiv2 = _windowWidthMin1 / 2;
                _windowStart = (_windowCenterMin05 - _windowWidthDiv2);
                _windowEnd = (_windowCenterMin05 + _windowWidthDiv2);
                _valid = true;
            }
        }

Width<input id="text1" type="text" />
    center<input id="text2" type="text" />
    <input id="Button1" type="button" value="Apply" onclick="ApplyWLCust();" />
    </br> time required<input id="text3" type="text" />
    <canvas style="height: 500px; width: 500px; display1: none; background-color: black;
                border: 1px solid red;" id="offscreenCanvas">


texts:
Assume we are given \$ n \$ natural numbers, \$a_{1}, a_{2}, \dots, a_{n} \$ and we are supposed to calculate the following summation:
\$ \sum_{i = 1}^{n}\sum_{j = 1}^{n} \left\lfloor \dfrac{a_{i}}{a_{j}} \right\rfloor\$.
This is a question from a challenge and in only one test, I get time-limit exceeded error.
Can my code become faster?
Here's the question and my code is as follows:
from collections import Counter

numbers = sorted(Counter(int(i) for i in input().split()).items())

sigma = 0
for i in range(len(numbers)):
    for j in range(i, len(numbers)):
        sigma += (numbers[j][0] // numbers[i][0]) * numbers[j][1] * numbers[i][1]

print(sigma)


texts: Changing images when hovering over links

texts:
I wrote a script to change a static image by hovering over navigation links. It works great, however, the script is very long and I'm guessing there is a much more efficient way to write this code. Can anyone give me tips on a better way to do this?

HTML

Link 1

Link 2

Link 3

JQuery

$(document).ready(function() {
$('#navigation li a#1').hover(
    function(){
        $(this).addClass('hover');
        $('.box img').attr('src', 'image1.jpg');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);
$('#navigation li a#2').hover(
    function(){
        $(this).addClass('hover');
        $('.box img').attr('src', 'image2.jpg');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);
$('#navigation li a#3').hover(
    function(){
        $(this).addClass('hover');
        $('.box img').attr('src', 'image3.jpg');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);
});


texts:
Using a java servlet, I've been doing the same approach to building or updating HTML.  I create the basic table on the HTML page, then call for the body from the servlet with ajax.

As an example:
HTML

                    Clinic
                    Location
                    Clinic
                    Location

javascript

function updateLocationTable() {
    $.ajax({
        url: 'TCAUServlet',
        type: 'POST',
        data: {formType: "getLocationTable"},
        dataType: 'html',
        success: function (responseText) {
            $('#tbodyAdminLocation').html('');
            $('#tbodyAdminLocation').html(responseText);
        },
        error: function (request, status, error) {
            alert("An error occurred.  Error:  " + status + ", " + error);
        }
    });
}

Servlet

private String getLocationTable() throws ClassNotFoundException, SQLException {
    List<Location> locList = TCAUDatabaseUtil.getLocations();
    Collections.sort(locList, new LocationComparator());
    String htmlString = "";
    for (int x = 0; x < locList.size(); x++) {
        Location loc = locList.get(x);
        htmlString += "
\n"
                + "                                        " + loc.getLocationClinic() + "	\n"
                + "                                        " + loc.getLocationName() + "	\n";
        if (x < locList.size() - 1) {
            loc = locList.get(++x);
            htmlString += "                                    " + loc.getLocationClinic() + "	\n"
                    + "                                        " + loc.getLocationName() + "	\n";
        }
        htmlString += "
\n";
    }
    return htmlString;
}

It works well, but I can't help but wonder if there isn't a better/easier/more efficient way, especially when I'm dealing with objects with quite a few fields in them.


texts: Split a string into chunks of the same length

texts:
Inspired by this question in chat

  Is there an easy way in .NET to split a string into an array by pulling chunks of the text in. I.e. I have an 18 character string I would like in 3 6-character pieces.

I thought that ain't be that hard. I would like to get any thoughts and improvements you can think of.

public static string[] Split(this string value, int desiredLength, bool strict = false)
{

    EnsureValid(value, desiredLength, strict);

    if (value.Length == 0) { return new string[0]; }

    int numberOfItems = value.Length / desiredLength;

    int remaining = (value.Length > numberOfItems * desiredLength) ? 1 : 0;

    IList<string> splitted = new List<string>(numberOfItems + remaining);

    for (int i = 0; i < numberOfItems; i++)
    {
        splitted.Add(value.Substring(i * desiredLength, desiredLength));
    }

    if (remaining != 0)
    {
        splitted.Add(value.Substring(numberOfItems * desiredLength));
    }

    return splitted.ToArray();
}

private static void EnsureValid(string value, int desiredLength, bool strict)
{
    if (value == null) { throw new ArgumentNullException(nameof(value)); }

    if (value.Length == 0 && desiredLength != 0)
    {
        throw new ArgumentException($"The passed {nameof(value)} may not be empty if the {nameof(desiredLength)} <> 0");
    }

    if (value.Length != 0 && desiredLength < 1) { throw new ArgumentException($"The value of {nameof(desiredLength)} needs to be > 0"); }

    if (strict && (value.Length % desiredLength != 0))
    {
        throw new ArgumentException($"The passed {nameof(value)}'s length can't be split by the {nameof(desiredLength)}");
    }
}

I know the tests aren't complete and the naming could be better, like the missing of a test if the passed in value == null, but here they are for review as well

[TestMethod()]
public void SplitTest()
{
    string input = "123456";
    string[] expected = new string[] { "123", "456" };
    string[] actual = input.Split(3);

    CollectionAssert.AreEqual(expected, actual);
}

[TestMethod()]
public void SplitTestNotEqual()
{
    string input = "12345";
    string[] expected = new string[] { "123", "45" };
    string[] actual = input.Split(3);

    CollectionAssert.AreEqual(expected, actual);
}

[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void SplitTestDesiredlengthIsZero()
{
    string input = "12345";
    string[] actual = input.Split(0);
}

[TestMethod()]
public void SplitTestDesiredlengthIsZeroWithEmptyString()
{
    string input = "";
    string[] expected = new string[0];
    string[] actual = input.Split(0);

    CollectionAssert.AreEqual(expected, actual);
}

[TestMethod()][ExpectedException(typeof(ArgumentException))]
public void SplitTestWillThrowBecauseOfStrict()
{
    string input = "12345";
    string[] actual = input.Split(3,true);
}


texts: Is this a valid and correct skeleton class/struct

texts:
I have been watching Alexander Stepanov programming C++ with components and he, as usual, has some strong opinions. I did like one of his assertions that we use regular, semi-regular and fully ordered types. So I decided to pull together a skeleton class (pair in this case) and wonder if there are any valid reasons for using this skeleton or something different. I realise there is no silver bullet and am not looking for one, but I am interested in the basics being programmatically consistent and correct. Alex seemed to loosely suggest that such a start position would be valid.

I hope this is a valid question, I think some of the areas of concern are:

Is it valid to refer to class as regular/semiregular/fullyordered?
(It's hard to find examples.)
Are there strong reasons for non-member friend/non-friend member functions? (I'm thinking here of the Dr.
Dobbs article showing non-member (non-friend) functions improving encapsulation.)
Should friend requirements define member/non member functions?
Is it a good rule that each of these groups are implemented fully if at least one member of that group is? I.e. == must also be implemented with != etc. Sort of as an extension to the big 4 or 5 or 6 construction or regular methods :-)

This is C++11 that MSVC 2012 can handle. Clang, gcc etc. can improve this loads, but for now I am using MSVC 2012 as the baseline. friend is not required in these functions. I have included it to try and cover a normal "template" (if I create a template/snippet) for use where there are private data members. My intent is not to use this as a snippet, though.

#ifndef MY_CLASS_H
#define MY_CLASS_H

#include <tuple>
#include <utility>

template <typename T, typename U>
struct MyClass {
    T first;
    U second;

    // semiregular

    MyClass(const MyClass& other)
        : first(other.first),
          second(other.second)
    {}

    MyClass(MyClass&& other)
        : first(std::move(other.first)),
          second(std::move(other.second))
    {}

    MyClass()
        : first(),
          second()
    {}

    ~MyClass()
    {}

    MyClass& operator=(MyClass other) {
        swap(*this, other);
        return *this;
    }

    // regular
    friend
    bool operator==(const MyClass& lhs, const MyClass& rhs) {
        return std::tie(lhs.first, lhs.second)
                   == std::tie(rhs.first, rhs.second);
    }

    friend
    bool operator!=(const MyClass& lhs, const MyClass& rhs) {
        return !operator==(lhs, rhs);
    }

    // fully ordered
    friend
    bool operator<(const MyClass& lhs, const MyClass& rhs) {
        return std::tie(lhs.first, lhs.second)
                   < std::tie(rhs.first, rhs.second);
    }

    friend
    bool operator>(const MyClass& lhs, const MyClass& rhs) {
        return operator<(rhs, lhs);
    }

    friend
    bool operator<=(const MyClass& lhs, const MyClass& rhs) {
        return !operator>(lhs, rhs);
    }

    friend
    bool operator>=(const MyClass& lhs, const MyClass& rhs) {
        return !operator<(lhs, rhs);
    }
};

// swap
void swap(MyClass& lhs, MyClass& rhs) /* noexcept */ {
    using std::swap;
    swap(lhs.first, rhs.first);
    swap(lhs.second, rhs.second);
}

#endif // MY_CLASS_H


texts:
I know that sort in R uses radix sort, and I played around in implementing it (mainly to be sure I understood the algorithm properly). However, my implementation is an order of magnitude slower than the native implementation in R.

I'm curious: is there a way to implement radix sort in R so that it wouldn't be so slow?

My code:

get_digit <- function(x, d) {
    # digits from the right
    # i.e.: first digit is the ones, second is the tens, etc.
    (x %% 10^d) %/% (10^(d-1))
}

radix_sort <- function(x) {
    # k is maximum number of digits
    k <- max(nchar(x))
    for(i in 1:k) {
        x_digit_i <- get_digit(x, i)
        # split numbers based on their i digit
        x_by_bucket <- split(x, x_digit_i)
        # recombine the vectors, now sorted to the i'th digit
        x <- unlist(x_by_bucket, use.names = FALSE)
    }
    # since each iteration is a stable sort, the final result
    # is a sorted array, yay!
    x
}

Checking the running time:

> library(microbenchmark)
> x <- sample(100)
> microbenchmark(radix_sort(x), sort(x))
Unit: microseconds
          expr     min      lq      mean   median      uq     max neval cld
 radix_sort(x) 459.378 465.895 485.58322 480.4835 496.779 649.956   100   b
       sort(x)  27.314  29.487  33.05064  31.9710  33.212  73.563   100  a
> x <- sample(10000)
> microbenchmark(radix_sort(x), sort(x))
Unit: microseconds
          expr       min         lq       mean     median        uq       max
 radix_sort(x) 44317.123 44777.8965 46062.3446 45204.3715 45714.807 63838.148
       sort(x)   158.609   165.7485   198.3083   186.6995   206.099   750.832


texts:
I am trying out for the first time knockoutjs and babeljs and have a question on how to do computed observables properly. Both fullName and fullNameComp properties are updated whenever firstName and lastName changes so not sure about pros/cons:

employee

<input type="text" data-bind="value: firstName, valueUpdate: 'keyup'" />
<input type="text" data-bind="value: lastName, valueUpdate: 'keyup'" />

Full name getter: <spane data-bind='text: fullName'>

Full name pure computed:

import ko from 'knockout';
import templateMarkup from 'text!./employee.html';

class Employee {
constructor(params) {
    this.firstName = ko.observable('John');
    this.lastName = ko.observable('Smith');
    this.fullNameComp = ko.pureComputed(function() {
        return this.firstName() + " " + this.lastName();
      }, this);
}

get fullName() {
    return this.firstName() + ' ' + this.lastName();
}

dispose() {
    // This runs when the component is torn down. Put here any logic necessary to clean up,
    // for example cancelling setTimeouts or disposing Knockout subscriptions/computeds.
}
}

export default { viewModel: Employee, template: templateMarkup };


texts: A thread-safe WebDriver pool to submit browsing jobs to

texts:
For a project, I need to make use of Selenium WebDrivers, and since they're so expensive to start, I decided to write a pool to manage them.
with driver_pool.FirefoxWebDriverPool(5) as d_pool:
    # Sequentially visit a page 1000 times
    for _ in range(1000):
        # Don't actually run this. I accidentally go myself rate-limited by SO for doing this.
        d_pool.run_job(lambda driver: driver.get("http://www.stackoverflow.com"))

I realized after writing this that really, it could be generalized to handle arbitrary objects, but for the sake of keeping it simple, I'm going to keep it as is. I could also generalize it to handle all WebDrivers, but drivers have slightly different interfaces, and I wanted to allow going into headless mode, so again, to keep it simple, I'm sticking with Firefox.
I've never written an object pool before, and I haven't written thread-safe code meant for a multi-threaded environment in awhile. I'd like tips on how this can be cleaned up. I'm making use of multiple primitives, so if I'd like to know if it can be simplified. _pending_lock and _n_pending are being used because I realized while writing terminate that I had no way of knowing if there are any jobs outstanding that may cause a driver to get missed while terminating.
The solution I went for is to count how many threads are currently stuck waiting inside the method. If a job finishes and it was the last job, it signals an Event (_can_terminate) that it's safe to terminate. If another job is submitted, the event is cleared to indicate that it's no longer safe. When terminate is called, it will prevent any new jobs from being submitted, wait for the all-clear, then pop drivers while calling quit on them. My main concern is preventing resource leakage because of their potential to bog down my system if leaked repeatedly.
Any tips at all would be appreciated.
from __future__ import annotations
from typing import Callable, Optional, TypeVar
from threading import Lock, Event
import queue

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options

T = TypeVar("T")

class FirefoxWebDriverPool:
    def __init__(self, max_drivers: int, headless: bool = True):
        self._available_drivers = queue.Queue(maxsize=max_drivers)
        self._terminating = False
        self._can_terminate = Event()

        self._pending_lock = Lock()  # TODO: Find a clean way of using Queue.qsize instead
        self._n_pending = 0

        options = Options()
        options.headless = headless

        for _ in range(max_drivers):
            self._available_drivers.put(Firefox(options=options))

    def run_job(self, job: Callable[[Firefox], T]) -> Optional[T]:
        """Runs a job in a browser pool.
        Will return the result of the job if the job succeeded, or None if the job failed
        due to termination of the pool being in progress."""
        driver = None
        try:
            with self._pending_lock:
                if self._terminating:
                    return None
                else:
                    self._n_pending += 1
                    self._can_terminate.clear()

            driver = self._available_drivers.get()
            return job(driver)
        finally:
            # Should never be None, but could theoretically be if a lock throws due to a bug in our logic.
            if driver is not None:
                self._available_drivers.put(driver)  # Should not be possible to be full.
            with self._pending_lock:
                self._n_pending -= 1
                if self._n_pending == 0:
                    self._can_terminate.set()

    def terminate(self) -> None:
        self._terminating = True
        self._can_terminate.wait()

        while self._available_drivers.qsize() > 0:
            driver: Firefox = self._available_drivers.get()
            driver.quit()

    def __enter__(self) -> FirefoxWebDriverPool:
        return self

    def __exit__(self, *_) -> None:
        self.terminate()


texts:
AFAIK Octave still does not support enumerations, so I've done my best to write a workaround. The question is if there is something missing in code below, or maybe something can be improved?

The reason for the enumConstructor method is that with Octave 4.2.0 I had errors when overloading the constructor.

classdef Enum < handle
    methods (Static = true)
        function [out] = test ()
            out = Enum.enumConstructor("test");
        endfunction
    endmethods

    # implementation

    properties (Access = private)
        value
    endproperties

    properties (Dependent = true)
        Value
    endproperties

    methods (Access = private, Static = true)
        function [this] = enumConstructor (in_val)
            this = Enum();
            this.value = in_val;
        endfunction
    endmethods

    methods
        function [out] = get.Value (this)
            out = this.value;
        endfunction

        function [out] = getValue (this)
            out = this.value;
        endfunction

        function [out] = eq (this, in_obj)
            out = false;
            if isa(in_obj, "Enum")
                out = strcmp(this.value, in_obj.value);
            endif
        endfunction
    endmethods
endclassdef

Edit:
I was a bit inspired with Java enumerations, rather than MATLAB.


texts: Query WordPress database, returning an array of rows

texts:
This is one of my first attempts at querying the WordPress database for data, and some my first PHP code ever, so please bear that in mind when commenting.
It is supposed find data between two dates, and show it as HTML in a for each loop. How can this be made better? What is the correct way to query a WordPress database?
<?php
require_once('wp-load.php');
$sd = date('Y-m-d', strtotime(($startdate = filter_input(INPUT_GET, 'startdate'))));
$ed = date('Y-m-d', strtotime(($enddate = filter_input(INPUT_GET, 'enddate'))));
$query = $wpdb->prepare("SELECT FirstName, LastName, FROM WHEN HireDate BETWEEN '%s' and '%s'" $sd, $ed);
echo $query;
$results = $wpdb->get_results( $query );
?>


texts:
Lets say we need to write an algorithm for giving money to the bank. We need to know interest rate, money which we put every year on our account, and amount of money we want to get. F.e int. rate is 1%, money we put every year is 1000 (or whatever) and we want to get 10000 (not more). It'd look like this:

MoneyOnAcc=1000*1.01
MoneyOnAcc=(MoneyOnAcc+1000)*1.01
Until MoneyOnAcc reaches 10000 (we want to print amount what was before
10000 - 9462.21)

and so on. Here is my code in Pascal.

program whilel;

var interestRate:real;
    moneyEveryYear:real;
    accMoneyOut:real;
    totalAmount:real;
    accMoneyControl:real;
begin
readln(moneyEveryYear);
readln(interestRate);
readln(totalAmount);

while accMoneyOut<totalAmount do begin
    accMoneyControl:=(accMoneyOut+moneyEveryYear)*((interestRate/100)+1);

    if accMoneyControl>totalAmount then break;

    accMoneyOut:=(accMoneyOut+moneyEveryYear)*((interestRate/100)+1);

end;
writeln(accMoneyOut:6:2);
readln();
end.

How can I improve this algorithm? Maybe some better logic will help.


texts: Basic structure of commandline applications

texts:
I am new to Elixir and experimenting a bit with my knowledge so far.
I wrote a skeleton for a basic commandline application and I am looking for feedback (e.g. whether the code is ideomatic). The code is a bit abstract, but I try to explain, what I wanted to accomplish so far:

The usage of the app is $name $command $options. Only exception when the user calls it with the  --help flag. There are two commands command and other with options opt1 and opt2 / opt3. The use of opt2 is optional.
Valid usages would be:
./playground --help
./playground --opt1 blah

defmodule Playground do
  @moduledoc """
  Documentation for Playground.
  """

  @doc """
  Hello world.

  ## Examples

      iex> Playground.hello
      :world

  """

  @command "command"
  @othercommand "other"
  @helpcommand "--help"

  def main([]) do
    app(:usage)
  end

  def main([@helpcommand]) do
    app(:help)
  end

  def main(args) do
    args
    |> parse_args
    |> app
  end

  def parse_args(args) do
    [command|options] = args
    parsed = OptionParser.parse(options, strict: [opt1: :string, opt2: :string, opt3: :string])
    case {command, parsed} do
      {@command, {[opt1: opt1], [], []}} -> {:command, %{:opt1=>opt1, :opt2=> "default"}}
      {@command, {[opt1: opt1, opt2: opt2], [], []}} -> {:command, %{:opt1=>opt1, :opt2=>opt2}}
      {@othercommand, {[opt3: otheroptions], [], []}} -> {:other, otheroptions}
      _-> :usage
    end
  end

  def app(:help) do
    IO.puts("Helptext")
  end

  def app(:usage) do
    IO.puts("Usage")
  end

  def app({:other, options}) do
    IO.puts("Other #{options}")
  end

  def app({:command, options}) do
    IO.puts("Command #{options[:opt1]} #{options[:opt2]}")
  end
end

I am mainly interested in:

Is it okay/best practice to have "multiple" main entries (depending on the number of arguments given)? In an earlier version, I had one main but an additional case statement, which I found annoying.

Is it good practice to have a Map containing options for the function called after option parsing, or would it be better to separate each parameter. The latter makes it unnecessary to "unpack" options in the function via options[:option].

Is my way of patern matching to parse different commands/options a good way to do it, or is there a better way?


texts: Calculating user efficiency on a time period with Linq

texts:
I have this expression:

    public static readonly Expression<Func<ApplicationUser, decimal>> EfficiencyPercentExpr = e =>
        (e.ExecutorOrders.Where(x => x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30)).Count(x => x.Status != Order.OrderStatus.Deleted) > 0)
        ?
        (
        e.ExecutorOrders.Where(x => x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30)).Count(x => x.Status != Order.OrderStatus.Deleted)
        /
        e.ExecutorOrders.Where(x => x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30)).Count()
        )
        :
        0
    ;

This expression calculates the user's efficiency by calculating the percentage of successful orders from a total of the last 30 days.

How can I make it more clear?

Update:

There is a second approach of writing the expression, but it generates more expensive SQL query.

    private static readonly Expression<Func<ApplicationUser, decimal>> efficiencyPercentExpr = e =>
        e.ExecutorOrders.Where(x => !x.IsNotConsidered && x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30))
        .GroupBy(x => 1, (k, g) => new { Count = g.Count(), CountUndeleted = g.Count(x => x.Status != Order.OrderStatus.Deleted) })
        .Select(x => x.CountUndeleted > 0 ? (decimal)x.CountUndeleted / (decimal)x.Count : 0).FirstOrDefault();


texts: Ruby command-line app that outputs from JSON file

texts:
I made this application that runs fine, but I feel the code is sloppy as there are many if statements. I'm a beginner so I'm not sure how to improve it, at least not without messing everything up. Any suggestions?

#!/usr/bin/ruby

require 'thor'
require 'json'

class ListTrends < Thor

  desc "list_trends json", "list out trends from JSON file"
  option :api_key, :aliases => "--api-key", :type => :string, :required => true
  option :format, :type => :string, :desc => "one line format"
  option :no_country_code, :aliases => "--no-country-code", :desc => "remove country code", :type => :boolean
  def list_trends(keyword=nil)

    json = File.read('trends_available.json')
    trends_hash = JSON.parse(json)
    re = /^(?=.*[a-zA-Z])(?=.*[0-9]).{8,}$/
    keyword = keyword.to_s.downcase

    if re.match(options[:api_key])

      trends_hash.each do |trend|
        if trend["country"].downcase.include?(keyword)
          if options[:format]
            output = trend.values[0..2]
            output.delete_at(1) if options[:no_country_code]
            puts output.join(" ")
          else
            # Complete output
            trend.each do |k, v|
              if v.is_a?(Hash)
                v.each do |i, j| puts "Trend location type #{i}: #{j}" end
              else
                puts "Trend #{k}: #{v}"
              end
            end # trend.each do
            puts ""
          end # if options[:format]
        end # if trend["country"]
      end # trends_hash.each

    else
      puts "Invalid API Key, operation abort..."
    end # if re.match

  end # list_trends
end

ListTrends.start(ARGV)


texts: Rebol Function to Categorize Items in a Block

texts:
I have a function that iterates through a block, tests each value against a given function and is placed in a block associated with the product of that function.

CATEGORIZE items test

An example:

categorize [
    "Aardvark" "Bison"
    "Antelope" "Baboon"
    "Anaconda" "Basking Shark"
] [first item]

Results in:

[
    #"A" [
        "Aardvark"
        "Antelope"
        "Anaconda"
    ]
    #"B" [
        "Bison"
        "Baboon"
        "Basking Shark"
    ]
]

For its test argument, a function! or a block! is accepted—a block! is transformed into a function with a single argument item.

NB. applying new-line before returning the block neatens the resultant block—for aesthetic purposes only.

Review questions I have are:

Is there a more efficient way to evaluate each iteration step?
Are there any potential optimization possibilities for common comparisons? e.g. by first letter, etc.
This is supposed to be a general-purpose function—are there any glaring cases this function fails? Any enhancement suggestions?

The Code

Rebol [
    Title: "Categorize"
    Date: 11-Mar-2014
    Author: "Christopher Ross-Gill"
    Type: 'module
    Exports: [categorize]
]

categorize: func [items [block!] test [any-function! block!] /local out value target][
    out: copy []
    if block? :test [test: func [item] :test]
    foreach item items [
        value: test item
        unless target: select out value [
            repend out [value target: copy []]
        ]
        append/only target item
    ]
    foreach [value items] out [new-line/all items true]
    new-line/all/skip out true 2
]


texts: Implementing widgets within a main window

texts:
I am learning PySide and am trying to implement widgets within a main window. My goal right now is very simple: I want to place a QLabel, with independently defined event handling, inside a main window that has its own event handling:

# -*- coding: utf-8 -*-
from PySide import QtGui, QtCore

class MainWindow(QtGui.QWidget):
    '''Main window lets user know when window was clicked on non-widget space'''
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.initUI()
    def initUI(self):
        self.myLabel=TalkingQLabel("Don't mess with Breakfast!", self)
        self.myLabel.setGeometry(50, 50, 200, 120)
        self.setGeometry(300,200,300,250)
        self.show()
    def mousePressEvent(self, event):
        print "Well, you pressed in main window!"

class TalkingQLabel(QtGui.QLabel):
    '''QLab el that indicates when it was pressed'''
    def __init__(self, txt, parent):
        QtGui.QLabel.__init__(self, txt, parent)
        self.initUI()
    def initUI(self):
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.setStyleSheet("QLabel { color: rgb(255, 255, 0); font-size: 15px; background-color: rgb(0,0,0)}")
    def mousePressEvent(self, event):
        print "This time you pressed in a label"

def main():
    import sys
    qtApp=QtGui.QApplication(sys.argv)
    myTalker=MainWindow()
    sys.exit(qtApp.exec_())

if __name__=="__main__":
    main()

Was it good practice to have two separate classes like this for Qt programming, or should I have defined TalkingQLabel within MainWindow because they are in a parent-child relationship, and always will be in this application? Is there a standard within the Qt community I should know about, especially in cases when one widget is a child of another?

Related pages:

https://stackoverflow.com/questions/330/should-i-use-nested-classes-in-this-case
Nested class or two separate classes?
https://stackoverflow.com/questions/1581931/should-i-refactor-static-nested-classes-in-java-into-separate-classes
https://softwareengineering.stackexchange.com/questions/171790/are-nested-classes-under-rated


texts: Facebook Login with JS and validate with PHP - Secure?

texts:
I am using Facebook's Javascript SDK for the login, and I am validating it with PHP Graph SDK v5.x
Here is the JS:
logInWithFacebook = function() {
    FB.login(function(response) {
        if (response.authResponse) {

            console.log (response.authResponse);

            $.ajax({
                type: 'POST',
                url: 'facebook-validate-php-sdk.php',
                data: response.authResponse,
                success: function(response){

                    console.log (response);
                    //Success

                }
            });

        } else {

            alert('User canceled login or did not fully authorize.');

        }
    }, {scope: 'user_link, email'});

    return false;
};

window.fbAsyncInit = function() {
    FB.init({
        appId: 'xxx',
        cookie: false,
        version: 'v9.0'
    });
};

Here is the PHP that validates:
require_once 'php-graph-sdk-5.x/autoload.php';

$fb = new Facebook\Facebook([
    'app_id' => 'xxx',
    'app_secret' => 'xxx',
    'default_graph_version' => 'v9.0',
]);

//$helper = $fb->getJavaScriptHelper();

try {
    //$accessToken = $helper->getAccessToken();
    $accessToken = $_POST['accessToken'];
}catch(Facebook\Exception\ResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exception\SDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

if (! isset($accessToken)) {
    echo 'No OAuth data could be obtained.';
    exit;
}

// User is logged in!
//Get Data

try {
    // Returns a `Facebook\Response` object
    $response = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,picture.type(large),birthday', $accessToken);
} catch(Facebook\Exception\ResponseException $e) {
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exception\SDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

$user = $response->getGraphUser();

var_dump ($user);

As you can see, I opted to pass the access token with POST instead of a cookie. Since I am not going to be establishing a session on my project I figured that would be best. Would that be a correct assumption? Is this code secure? Any tips or thoughts?


texts: Refactoring 3 level depth for loops in JavaScript

texts:
I'm trying to get rid of some of the horrible nested loops in the following code.
Essentially is moving TDs to top rows based on whether the current row has the current cell. You can see the execution here:
http://jsfiddle.net/Jq8sk/

How can I clean it up and avoid this level of depth. Any help is appreciated.

var trs = $('.trs');
var arr = ['n0', 'n1', 'n2'];
for (var i = 0; i < trs.length; i++) {
    for (var j = 0; j < arr.length; j++) {
        var tds = trs[i].getElementsByClassName('tds ' + arr[j]);
        if (tds.length == 0) {
           for (var x = i + 1; x < trs.length; x++) {
               var tds_offset = trs[x].getElementsByClassName('tds ' + arr[j]);
               if (tds_offset.length > 0) {
                  trs[i].appendChild(tds_offset[0]);
                  break;
               }
           }
        }
    }
}


texts: How to make DRY logger class with debug, info, warn and error methods that extends private method

texts:
I am trying to make logger class with debug, info, warn and error methods that "extends" basic log method.
However it is not written using DRY principle, how can I make it DRY, not WET?
Code snippet

const logLevels = {
  0: 'debug',
  1: 'info',
  2: 'warn',
  3: 'error',
  'debug': 0,
  'info': 1,
  'warn': 2,
  'error': 3,
}

class Logger {
  logLevel = logLevels.debug

  log(logLevel, ...messages) {
    if (logLevel >= this.logLevel) {
      const logType = logLevels[logLevel]
      messages.unshift(logType)

      console.log(...messages)
    }
  }

  debug(...messages) {
    this.log(logLevels.debug, ...messages)
  }

  info(...messages) {
    this.log(logLevels.info, ...messages)
  }

  warn(...messages) {
    this.log(logLevels.warn, ...messages)
  }

  error(...messages) {
    this.log(logLevels.error, ...messages)
  }
}

const myLogger = new Logger()
const dateNowHex = () => Date.now().toString(16)

myLogger.debug('this is a test', dateNowHex())
myLogger.info('this is a test', dateNowHex())
myLogger.warn('this is a test', dateNowHex())
myLogger.error('this is a test', dateNowHex())

Should I make better class composition? Can you provide examples?


texts:
Here is my code for this problem. Any bugs, performance in terms of algorithm time complexity, code style advice are appreciated.

This is a continued discussion from (Find smallest subset prefixes) and since it is new code, I post a new thread.

Problem:

  Given a set of strings, return the smallest subset that contains the longest possible
  prefixes for every string.

  If the list is ['foo', 'foog', 'food', 'asdf'] return ['foo', 'asdf']

The return is foo since foo is prefix for foo (itself), prefix for foog and prefix for food (in other words, foo could "represent" longer string like foog and food). Output also contains asdf because it is not prefix for any other words in the input list, so output itself.

The empty set is not a correct answer because it does not contain the longest possible prefixes.

Source code:

from collections import defaultdict
class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.isEnd = False
    def insert(self, word):
        node = self
        for w in word:
            node = node.children[w]
        node.isEnd = True
    def find_prefix(self, prefix, result):
        if self.isEnd:
            result.append(''.join(prefix[:]))
            return
        for w, child_node in self.children.items():
            prefix.append(w)
            child_node.find_prefix(prefix, result)
            prefix.pop(-1)

if __name__ == "__main__":
    words = ['foo', 'foog', 'food', 'asdf']
    root = TrieNode()
    for w in words:
        root.insert(w)
    result = []
    root.find_prefix([], result)
    print result


texts: Position update loop and checking collision

texts:
I'm writing a laser connection game. This is my first game on Windows Phone, and I've never used C# and XNA before.

The part of my code that could be improved is Update() (where I make my sprites move).

public void Update(GameTime gameTime)
{
    TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities();
    if (touchCap.IsConnected)
    {
        TouchCollection touches = TouchPanel.GetState();
        if (touches.Count >= 1)
        {
            Vector2 PositionTouch = touches[0].Position;

            for (int i = 0; i < ListDragObj.Count(); i++)
            {
                if (ListDragObj[i].Shape.Contains((int)PositionTouch.X, (int)PositionTouch.Y))
                {
                    //Permit to avoid several Obj to moove in the same time
                    if (!OnlyOneSelected(ListDragObj))
                    {
                        ListDragObj[i].selected = true;
                        TamponPosition = ListDragObj[i].Position;
                    }
                }
                else
                {
                    ListDragObj[i].selected = false;
                }

                if (touches[touches.Count - 1].State == TouchLocationState.Released)
                {
                    if (gm.Check_Tile((int)(PositionTouch.X / 10), (int)(PositionTouch.Y / 10)))
                    {
                        ListDragObj[i].Update(PositionTouch);
                    }
                    else
                    {
                        ListDragObj[i].Update(TamponPosition);
                    }
                }
            }
        }
    }
}

I'm looking for the selected Sprite (in the List ListDragobj), and then I move it.
The last couple if/else is where I check collisions.

I was wondering how I could improve that position Update() method.


texts:
The task:

  Given a string of words delimited by spaces, reverse the words in
  string. For example, given "hello world here", return "here world
  hello"

  Follow-up: given a mutable string representation, can you perform this
  operation in-place?

My solution:

const reverseStr = s => s.split(' ').reverse().join(' ');

console.log(reverseStr("hello world here"));

My "in-place" solution:

const reverseStrInPlace = s => {
  let exp = `\\w+$`;
  const startLen = s.lastIndexOf(s.match(/\w+$/)[0]);
  const strLen = s.length;
  const len = (s.match(/\s/g) || []).length;
  for (let i = 0; i < len; i++) {
    exp = `(\\w+)\\s${exp}`;
    s += ` ${s.match(new RegExp(exp), 'g')[1]}`;
    exp = `(\\w+)\\s${exp}`;
  }
  return s.substring(startLen, startLen + strLen);
}

console.log(reverseStrInPlace('hello world here'));

"In-place" algorithms are defined as:

  An in-place algorithm transforms the input without using any extra
  memory. As the algorithm executes, the input is usually overwritten by
  the output and no additional space is needed for this operation.

Not sure whether this is the right approach for the in-place solution, because, even though I didn't create for the string a new datastructure, i.e. during the operation I overwrite the input and return the overwritten input as the output, but I created other variables, e.g. exp, len, i, etc. i.e. additional space is created for the operation.


texts:
I've written a class for loading a template file and replacing the variables with actual data. Please review my code and suggest improvements.

<?php
/**
 * This class will helpful for variable replacement from a loaded file
 *
 * @author V V R
 * @version 1.0
 */
class Parser {
    public $dir = "";
    public $text = "";

    /**
     * To get directory location
     * @param $dir
     */
    function __construct($dir = "home/template") {
        $this->dir = $dir;
    }

    /**
     * To load the specified file from directory
     * @param $file
     */
    function loadFile($file) {
        try {
            if (file_exists ( $this->dir . "/" . $file )) {
                $this->text = file_get_contents ( $this->dir . "/" . $file );
            } else {
                throw new Exception ( $this->dir . "/" . $file . " does not exist" );
            }
        } catch ( Exception $e ) {
            error_log ( $e->getMessage () );
            die ();
        }
    }
    /**
     * To get the text from a file
     * @return text
     */
    function getText() {
        return $this->text;
    }

    /**
     * To replace the variables
     * @param unknown_type $var
     * @param unknown_type $text
     */
    function replace($var, $text) {
        $this->text = str_replace ( "{\$$var}", $text, $this->text );
    }
}

?>


texts: Binary Heap module in Typescript/Javascript supporting min-heap and max-heap

texts:
About binary heaps: https://en.wikipedia.org/wiki/Binary_heap

The purpose of this module is to allow quick and efficient priority queue management, compared to linked list.
Efficiency: insert: \$O(\log(n))\$, pop: \$O(\log(n))\$.

export enum BinaryHeapType {
    min = 1,
    max = 2,
}

export default class BinaryHeap {
    public heap: number[] = [];
    private check: (parent: number, current: number) => boolean;
    private type: BinaryHeapType;

    constructor(_heap: number[], _type?: BinaryHeapType) {
        this.heap = _heap;
        this.type = _type || BinaryHeapType.max;
        if (this.type == BinaryHeapType.max) {
            this.check = (parent, current) => parent >= current;
        } else if (this.type == BinaryHeapType.min) {
            this.check = (parent, current) => parent <= current;
        } else {
            throw "Unsupported heap type";
        }

        this.heap = this.heap.sort((a, b)=> {
            if (a > b) return this.type == BinaryHeapType.max ? -1 : 1;
            if (a < b) return this.type == BinaryHeapType.max ? 1 : -1;
            return 0;
        });
    }

    public insert(val: number) {
        if (this.type == BinaryHeapType.max) {
            this.heap.push(val);
            this.bubbleUp();
        } else if (this.type == BinaryHeapType.min) {
            this.heap.unshift(val);
            this.sinkDown(0)
        }
    }

    public extractTop() {
        const max = this.heap[0];
        this.heap[0]= this.heap.pop()
        this.sinkDown(0)
        return max
    }

    public peakTop() {
        return this.heap[0];
    }

    private bubbleUp() {
        let index = this.heap.length - 1;

        while (index > 0) {
            let element = this.heap[index];
            let parentIndex = Math.floor((index - 1) / 2);
            let parent = this.heap[parentIndex];

            if (this.check(parent, element)) break
            this.heap[index] = parent;
            this.heap[parentIndex] = element;
            index = parentIndex;
        }
    }

    private sinkDown(index) {
        let left = 2 * index + 1,
            right = 2 * index + 2,
            largest = index;
        const length = this.heap.length

        // if left child is greater than parent
        if (left <= length && this.check(this.heap[left], this.heap[largest])) {
            largest = left
        }
        // if right child is greater than parent
        if (right <= length && this.check(this.heap[right], this.heap[largest])) {
            largest = right
        }
        // swap
        if (largest !== index) {
            [this.heap[largest], this.heap[index]] =
                [this.heap[index], this.heap[largest]]
            this.sinkDown(largest)
        }
    }
}

Code: https://github.com/Livshitz/libx.js/blob/master/compiled/modules/BinaryHeap.ts

Unit tests:
https://github.com/Livshitz/libx.js/blob/master/tests/libx.binaryHeap.test.ts

Extra: How would you suggest implement a generic object support for this heap? So we could insert an object (that implements a interface, lets say IPrioritized, that has a numeric value which will determine its position)?


texts: Determining if a C-style string is alphabetic

texts:
I'm looking for the fastest way to determine if a C-style string contains only alphabetic characters.

For this question, there are a few assumptions:

strlen(c) > 0
Strings are null-terminated
Continuous character encoding from a-z and A-Z is not guaranteed, but likely.
The string is not a null pointer, nor is the pointer its "default value".

#include <stdbool.h>
#include <ctype.h>

bool stralpha(const char *c)
{
    bool alphabetic = true;

    while(*c)
        alphabetic &= !!isalpha(*c++);

    return alphabetic;
}

/* so gcc does not complain */
int main(void){}

To be clear: I know that any performance difference in such a function will be minimal at best. This is just for fun.

In my case, I was having issues with the function returning false even when c was purely alphabetic. That is why I use double negation !! on isalpha(), because it is not guaranteed to return consistently 0 or 1 per the standard.


texts:
private static byte[] GenerateData(long size)
{
    var result = new byte[size];
    new Random().NextBytes(result);

    return result;
}

Is it good, robust and efficient solution?

I use my method like this

[TestMethod]
public void WriteAndRead16MBbyZeroOffsetTest()
{
     var length = 1024 * 1024 * 16; // 16mb
     WriteAndReadTest(length);
}

private void WriteAndReadTest(long length, long offset = 0L)
{
    byte[] generatedData = GenerateData(length);
    byte[] expectedData = null;

    StorageException resultException = null;
    try
    {
         _blobReaderWriterLazy.Value.Write(offset, generatedData);
         _blobReaderWriterLazy.Value.Read(offset, length, out expectedData);
    }
    catch (StorageException exception)
    {
        resultException = exception;
    }

    Assert.IsNull(resultException);
    Assert.IsTrue(generatedData.Length == expectedData.Length);
    Assert.IsTrue(generatedData.SequenceEqual(expectedData));
}


texts: How to simplify the record syntax with pattern matching?

texts:
I've just finished reading Learn You a Haskell and I've started to experiment on my own. I just wanted to create a very simple game system where player A can attack player B.

Now I have 2 questions:

My autoAttack function was very daunting to write. How could I improve it?
How would I format my autoAttack function correctly? I don't find it very pleasing to read.

main = print $ createActor `autoAttack` createActor
type Vector2= (Float,Float)
type Vector3 = (Float,Float,Float)
data StatsSystem = StatsSystem {physicalDamage :: Float,
                                spellPower     :: Float,
                                health         :: Float,
                                mana           :: Float,
                                attackRange    :: Float,
                                castRange      :: Float,
                                attackSpeed    :: Float
                               } deriving(Show)

data MovementSystem = MovementSystem {direction :: Vector2,
                                      speed     :: Float,
                                      position  :: Vector3
                                     } deriving(Show)
data Actor = Actor {stats :: StatsSystem,
                    ms    :: MovementSystem
                   } deriving(Show)
createActor :: Actor
createActor = Actor {stats = StatsSystem {physicalDamage = 1.0,
                                          spellPower = 1.0,
                                          health = 10.0,
                                          mana = 1.0,
                                          attackRange = 1.0,
                                          castRange = 1.0,
                                          attackSpeed = 1.0
                                         },
                     ms = MovementSystem{direction = (1.0,1.0),
                                         speed = 50.0,
                                         position = (0,0,0)
                                        }
                    }
autoAttack :: Actor -> Actor -> Actor
autoAttack Actor {stats = StatsSystem {physicalDamage = p,
                                       spellPower = _,
                                       health = _,
                                       mana = _,
                                       attackRange = _,
                                       castRange = _,
                                       attackSpeed = _
                                      },
                   ms = m
                 }
           Actor {stats = s2,
                   ms = m2
                 }
           = Actor {stats = StatsSystem {physicalDamage = physicalDamage s2,
                                         spellPower = spellPower s2,
                                         health = health s2 - p,
                                         mana = mana s2,
                                         attackRange = attackRange s2,
                                         castRange = castRange s2,
                                         attackSpeed = attackSpeed s2
                                        },
                    ms = m2
                   }


texts:
I’ve multiple yaml files which need to be parsed and have exactly the same structure

schema: "1.0.0"
id: test
version: "1.2.3"

dependency :
 - name: ui
    type: runner
    cwd: /ui
    install:
       - name: api
         group: test
         properties:
             name: app
             url: appUrl

 - name: backend
    type: mongoDb
    path: be
    install:
       - name: db
         type: mongo
    provides:
       - name: api
         properties:
            url: url

The schema section is mandatory for all the yaml which the app should
get always
The dependency tag can contain 1..n entries with mandatory fields such as
,name, type, cwd
The dependency tag can (or not) contain install section with name and
properties which is mandatory
The dependency tag can (or not) contain provides section with name
which is mandatory

The install can have properties and the provides also can have properties

I am using a yaml parser to parse the files but my question is how in Golang I can build struct that when I parse the doc it will automatically fill the main struct and will include the sub structs (such as dependency/ install sections )

The code which done the parse and working is the following:

package main

import (
    "fmt"
    "io/ioutil"
    "log"

    "gopkg.in/yaml.v2"
)

var data = `
schema: "1.0.0"
id: test
version: "1.2.3"

dependency :
  - name: ui
    type: runner
    cwd: /ui
    install:
       - name: api
         group: test
         properties:
             name: app
             url: appUrl

  - name: backend
    type: mongoDb
    cwd: be
    install:
       - name: db
         type: mongo
    provides:
       - name: api
         properties:
             url: url
`

type Yaml struct {
    Schema     string
    ID         string
    Version    string
    Dependency []Dependency
}

type Dependency struct {
    Name     string
    Type     string
    CWD      string
    Install  []Install
    Provides []Provide
}

type Install struct {
    Name       string
    Group      string
    Type       string
    Properties Properties
}

type Properties struct {
    Name string
    URL  string
}

type Provide struct {
    Name       string
    Properties Properties
}

func main() {
    y := Yaml{}

    err := yaml.Unmarshal([]byte(data), &y)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("%+v\n", y)

}

My question are:

The install section can have group and properties so how should I contract the struct to handle this options nicely
if the main is under rootProj-> cmd>main.go assume that the struct's should be extended , how should I build the project structure?

if my project is like following:

myproj
  vendor
  cmd
    main.go
  Gopkg.lock
  Gopkg.toml

Should I create another folder under the root and put the struct there ?


texts: Suitable way for Validating JPA Entities in Spring Boot

texts:
I have been around in Spring Boot eco-system since 2012, I have worked on many little projects. The most important thing in development I experienced id Validation especially JPA Entities. We simply do validation like:
@Entity
public class Input {

  @Id
  @GeneratedValue
  private Long id;

  @Min(1)
  @Max(10)
  private int numberBetweenOneAndTen;

  @Pattern(regexp = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$")
  private String ipAddress;

  // ...

}

as mentioned here, but there is a note highlighted which says :

We usually don't want to do validation as late as in the persistence layer because it means that the business code above has worked with potentially invalid objects which may lead to unforeseen errors...

What is the safe and suitable way of Validating JPA Entities?
I have tried in one of my projects as:
1) Entity class
@Data
@Entity(name = "users")
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class AppUser extends AuditModel{

    private String userFirstName;

    private String userLastName;

    private String userDateOfBirth;

}

2) Dto class
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class AppUserDto {

    private Long id;

    @NotNull(message = "First name must not be null")
    @NotBlank(message = "First name must not be blank")
    private String userFirstName;

    @NotNull(message = "Last name must not be null")
    @NotBlank(message = "Last name must not be blank")
    private String userLastName;

    @NotNull(message = "Date of Birth must not be null")
    @NotBlank(message = "Date of Birth must not be blank")
    @Past()
    private String userDateOfBirth;
}

3) Finally Validating Bean to a Spring Service Method
@Service
@Validated
public class AppUserService {

    private final AppUserRepository appUserRepository;

    @Autowired
    public AppUserService(AppUserRepository appUserRepository) {
        this.appUserRepository = appUserRepository;
    }

    public void update(@Valid AppUserDto appUserDto){
        appUserRepository.update(
                appUserDto.getId(),
                appUserDto.getUserFirstName(),
                appUserDto.getUserLastName(),
                appUserDto.getUserDateOfBirth()
        );
    }

}

Is this approach suitable or there is an other better way than that?
Please give your feed back your reviews are precious to me!


texts:
I have a few "given" things:

An SQL Server 2012 table with certain structure
Data provided as XML with certain structure

My code has to shred that XML into a row in the table. I'm looking to get feedback on how I'm getting the data for each column from the XML variable.

Here's a realistic yet minimal repro of my scenario:

-- Table structure is "a given", i.e. I *have to* work with this:
CREATE TABLE #Person
(
    Id INT IDENTITY(1,1),
    First_Name NVARCHAR(100),
    Last_Name NVARCHAR(100),
    Two_Char_Nationality VARCHAR(2),
    InsertedAt DATETIME -- My code has to manually insert the timestamp here (cannot create a default constraint)
);

-- Xml structure is "a given", i.e. I *have to* work with this:
DECLARE @data XML = '<Person>
  <FirstName>John</FirstName>
  <Surname>Doe</Surname>
  <Nationality>
    <Fullname>Netherlands</Fullname>
    <IsoAlpha2>NL</IsoAlpha2>
  </Nationality>
</Person>';

-- Looking to get feedback on this:
INSERT INTO #Person
(
    First_Name,
    Last_Name,
    Two_Char_Nationality,
    InsertedAt
)
VALUES
(
    (SELECT @data.value('(/Person/FirstName)[1]', 'NVARCHAR(100)')),
    (SELECT @data.value('(/Person/Surname)[1]', 'NVARCHAR(100)')),
    (SELECT @data.value('(/Person/Nationality/IsoAlpha2)[1]', 'VARCHAR(2)')),
    GETDATE()
);

-- For testing purposes only:
SELECT * FROM #Person
DROP TABLE #Person

As you can see I'm doing many sub-select-queries in the VALUES(...) part, which doesn't feel all too smart.

In reality, there's about 10 - 20 columns in my #Person table, and sometimes my XML is slightly more nested, but I'm trying to focus on the basics first.

Any recommendations on the INSERT statement?


texts: Portably generate uniformly random floats from mt19937 output

texts:
My goal is to generate a sequence of random float from a seeded random generator. The sequence should be the same on any machine / any compiler -- this rules out the use of std::uniform_real_distribution since it doesn't make that guarantee. Instead we have to create our own version of this, which we will be able to guarantee is portable / uses the same implementation on all platforms.

We can assume I'm starting from std::mt19937 since the C++ standard does mandate its implementation, so the goal becomes, how can I convert a uniformly random uint32_t to a uniformly random float in the range [0.0f, 1.0f]. The main things I'm concerned about are:

Efficiency
Loss of precision

I threw something together which looks like this:

template <typename RNG>
float uniform_float(RNG & rng) {
  static_assert(std::is_same<std::uint32_t, typename RNG::result_type>::value, "Expected to be used with RNG whose result type is uint32_t, like mt19937");

  float result = static_cast<float>(rng());

  for (int i = 0; i < 32; ++i) {
    result /= 2;
  }
  return result;
}

In preliminary tests it seems to be outputting floats in the range [0.0f, 1.0f].

I did also try looking around in the libstdc++ headers to see where they are doing the equivalent thing, but it looked like it was going to take some digging to actually find it.

Here are some natural questions in my mind:

When static casting uint32_t to float, the value is never outside the representable range, so the behavior is not undefined. Typically it will not be representable exactly though, since both types have 32 bits, and float has to have some overhead. The standard says it is implementation-defined whether I get the next highest or next lowest representable number in this case. I assume that it doesn't matter since I'm going to divide by two anyways many times after this, and then many of these values will collide anyways?
Is it better (faster) to divide by the uint32_t max value, rather than by 2^32? I assume not.
Does dividing by two repeatedly cause a subtle bias as the least significant bits are repeatedly discarded? If they are only being discarded then I would expect not, but possibly there is some rounding that takes place and could cause problems?

An alternative strategy would be, start with 2^{-32} as a float, and then multiply it up by a random integer into the range 0.0f, 1.0f. However it's harder for me to understand in terms of the standard exactly what will happen if I do that -- what if 2^{-32} is not exactly representable? If I simply write it as a multiplication, then the int will be promoted to a float first anyways, right? Is it better to do some kind hand-rolled operation for int * float, using a bit-by-bit doubling routine etc.?


texts: Passing restored packages as artefacts in GitLab Continuous Integration

texts:
Introduction

I'm writing a script in YAML for building ASP.NET Core 2.2 project using GitLab Continuous Integration. In all YAML samples I could find (and there are not many) for building .NET Core based applications using GitLab CI I could see something like this:

before_script:
 - 'dotnet restore'

before_script is running a dependency restore before every job. It makes sense because if you use free GitLab runners (like I do) every job is executed on a different machine. There is no possibility to preserve state from previous jobs (with exception on cache and artifacts, but I'll get to that later). What that means is that on the next job, all previously restored packages will be gone, and they need to be restored again. And on the next job once again. And again on every job in the pipeline which needs the packages. I noticed a redundancy there. A redundancy that takes precious time, because a huge project with a lot of third-party packages takes a while for a full restore.

Using job artifacts

I found a way to preserve those packages and then pass them to the next job via GitLab artifacts:

restore:
 stage: restore
 script:
  - 'dotnet restore --packages .nuget/'
 artifacts:
  paths:
   - 'src/**/obj/*'
   - '.nuget/'

Let's break it down. With dotnet restore --packages .nuget/ I explicitly specify a custom directory for packages to be restored. Then I specify two paths which GitLab CI will be interested in when creating a job artifacts. dotnet restore creates a few files with metadata about packages inside a obj/ directory, so these will be needed as well. I include them in src/**/obj/*. Finally, I include the .nuget/ directory which after dotnet restore should contain all restored dependencies.

Note: A dependency restore saves the path where the packages will be kept inside <PROJECT_NAME>/obj/project.assets.json file. After that, there is no need for explicitly specifying where the restored packages are e.g. when building the project.

Eventually, in the next job I use previously created job artifacts by specifying a job dependecy. In that way, GitLab CI knows that it should download job artifacts from the dependant job.

build:
 stage: build
 script:
  - 'dotnet build --no-restore'
 dependencies:
  - restore

Whole YAML script:

image: microsoft/dotnet:2.2-sdk

variables:
 SOURCE_CODE_DIRECTORY: 'src'
 BINARIES_DIRECTORY: 'bin'
 OBJECTS_DIRECTORY: 'obj'
 NUGET_PACKAGES_DIRECTORY: '.nuget'

stages:
 - restore
 - build

restore:
 stage: restore
 script:
  - 'dotnet restore --packages="$NUGET_PACKAGES_DIRECTORY"'
 artifacts:
  paths:
   - '$SOURCE_CODE_DIRECTORY/**/$OBJECTS_DIRECTORY/*'
   - '$NUGET_PACKAGES_DIRECTORY/'

build:
 stage: build
 script:
  - 'dotnet build --no-restore'
 dependencies:
  - restore

Feedback

Please tell me what you think, any weaknesses of my approach, code smells, or maybe a better solution. All kind of constructive feedback appreciated.


texts: Is this an efficient way to implement Merge Sort in C++?

texts:
I am studying C++ and I wrote the following Merge Sort algorithm. I need some comments from skilled C++ programmers to understand where it can be improved, in terms of execution time, memory usage and "style". I am aware this question is rather generic but really, any comment is appreciated, even more if well motivated.

Is it ok to return a new vector by value every time the recursive function is called?

template<typename T>
vector<T> mergeSort(vector<T> const &v, unsigned long s, unsigned long e){
    if (e-s == 0) return vector<T>{}; //return empty vector
    else if (e-s == 1) return vector<T>{v[s]}; //return vector with single element
    else{
        unsigned long mid = (e+s)/2;
        vector<T> v1 = mergeSort(v, s, mid);
        vector<T> v2 = mergeSort(v, mid, e);
        vector<T> vr (e-s); // allocate the space needed

        typename vector<T>::iterator p1 = v1.begin();
        typename vector<T>::iterator p2 = v2.begin();
        typename vector<T>::iterator pr = vr.begin();

        while (p1 != v1.end() && p2 != v2.end()) *pr++ = (*p1 < *p2) ? *p1++ : *p2++;
        while (p1 != v1.end()) *pr++ = *p1++;
        while (p2 != v2.end()) *pr++ = *p2++;

        return vr;
    }
}

int main(int argc, const char * argv[]) {
    vector<int> v {2, 7, -1, 4, 2, 6, -10};
    vector<int> vsorted = mergeSort(v, 0, v.size());
    return 0;
}


texts: Find the longest common subsequence algorithm - low speed

texts:
I've designed an algorithm to find the longest common subsequence.

These are steps:

Pick the first letter in the first string.
Look for it in the second string and if its found, Add that letter to
common_subsequence and store its position in index, Otherwise
compare the length of common_subsequence with the length of lcs
and if its greater, asign its value to lcs.
Return to the first string and pick the next letter and repeat the
previous step again, But this time start searching from indexth letter
Repeat this process until there is no letter in the first string to
pick. At the end the value of lcs is the Longest Common
Subsequence.

This is an example:

X=A, B, C, B, D, A, B
Y=B, D, C, A, B, A

Pick A in the first string.
Look for A in Y.
Now that there is an A in the second string, append it to common_subsequence.
Return to the first string and pick the next letter that is B.
Look for B in the second string this time starting from the position of A.
There is a B after A so append B to common_subsequence.
Now pick the next letter in the first string that is C. There isn't a C next to B in the second string. So assign the value of common_subsequence to lcs because its length is greater than the length of lcs.

Repeat the previous steps until reaching the end of the first string. In the end the value of lcs is the Longest Common Subsequence.

The complexity of this algorithm is \$\theta(n*m)\$.

I implemented it on two methods. The second one is using a hash table, but after implementation I found it's much slower compared to the first algorithm. I can't understand why.

The first algorithm:

import time
def lcs(xstr, ystr):
    if not (xstr and ystr): return # if string is empty
    lcs = [''] #  longest common subsequence
    lcslen = 0 # length of longest common subsequence so far
    for i in xrange(len(xstr)):
        cs = '' # common subsequence
        start = 0 # start position in ystr
        for item in xstr[i:]:
            index = ystr.find(item, start) # position at the common letter
            if index != -1: # if common letter is found
                cs += item # add common letter to the cs
                start = index + 1
            if index == len(ystr) - 1: break # if reached to the end of ystr
        # updates lcs and lcslen if found better cs
        if len(cs) > lcslen: lcs, lcslen = [cs], len(cs)
        elif len(cs) == lcslen: lcs.append(cs)
    return lcs

file1 = open('/home/saji/file1')
file2 = open('/home/saji/file2')
xstr = file1.read()
ystr = file2.read()

start = time.time()
lcss = lcs(xstr, ystr)
elapsed = (time.time() - start)
print elapsed

The second one using hash table:

import time
from collections import defaultdict
def lcs(xstr, ystr):
    if not (xstr and ystr): return # if strings are empty
    lcs = [''] #  longest common subsequence
    lcslen = 0 # length of longest common subsequence so far
    location = defaultdict(list) # keeps track of items in the ystr
    i = 0
    for k in ystr:
        location[k].append(i)
        i += 1
    for i in xrange(len(xstr)):
        cs = '' # common subsequence
        index = -1
        reached_index = defaultdict(int)
        for item in xstr[i:]:
            for new_index in location[item][reached_index[item]:]:
                reached_index[item] += 1
                if index < new_index:
                    cs += item # add item to the cs
                    index = new_index
                    break
            if index == len(ystr) - 1: break # if reached to the end of ystr
        # update lcs and lcslen if found better cs
        if len(cs) > lcslen: lcs, lcslen = [cs], len(cs)
        elif len(cs) == lcslen: lcs.append(cs)
    return lcs

file1 = open('/home/saji/file1')
file2 = open('/home/saji/file2')
xstr = file1.read()
ystr = file2.read()

start = time.time()
lcss = lcs(xstr, ystr)
elapsed = (time.time() - start)
print elapsed


texts: Optimizing a drawing a circular gradient in Python (aggdraw, PIL or SDL2)

texts:
I need to reduce the latency in creating a circular gradient of arbitrary radius that's then mapped to the current mouse position.

Though the project uses OpenGL for video-card interaction, alas, for legacy reasons, currently uses aggdraw for drawing (with Pillow wrapping PIL). However, PySDL2 runs the rest of the UI, so its drawing library is available in principle to the project.

This function returns an aggdraw object which is elsewhere converted into a byte array with numpy and passed to OpenGL.

I wrote this working, if rudimentary, function because I couldn't find a better one. But the latency between mouse motion and the gradient draw increases dramatically with radius value (see my code; should be obvious why).

I'm very open to solutions that use the SDL2 drawing library instead but I've never used it and would appreciate being treated like the nub I am for such solutions. I know that's more of a stackoverflow request, but my enqueries there aren't getting much attention, leading me to believe that my solution isn't a egregiously wrong haha.

I think it must be possible to do this faster than the screen refresh rate, there is  a latency tolerance of ~30ms (project's context is graduate work in the cognitive science of vision). I know this also depends on hardware; generally, we're talking iMacs no older than 3 years.

Basically, I'm sure this can be done much better, but I am waaay out of my depth; I usually work with with web languages (JavaScript/PHP/HTML/CSS)!

def mouse_gradient(radius):
        mp = mouse_pos()  # custom function, just wraps fetching mouse coords from sdl2
        mouse_grad = None
        mouse_grad = aggdraw.Draw('RGBA', (radius, radius), (0, 0, 0, 0))
        for n in range(radius):
            n = float(n)
            r = float(radius - n)
            opacity = int(( 0.25 * n / radius) * 100)
            brush = aggdraw.Brush((255, 0, 0), int(opacity))
            tl = (radius - r) // 2  # ie. top-left
            br = (radius - r) // 2 + r  # ie. bottom-right
            mouse_grad.ellipse((tl, tl, br, br), brush)

        return mouse_grad  # where it is subsequently blit to the screen

Notes for the specific context if you want them:

Since the code I've provided is so sparse, as a courtesy I should mention that this interfaces with a large module I've been writing for ~1yr (KLIBS). Said module primarily does a lot that's impertinent here, but, the below function does plug into lot of in-house code. Alas, I've yet to write documentation for the module because it's (currently) for a local context.

This function is, verbatim, my code however; and the rest of the library has been well tested; the overhead is <10ms from anything else going on.


texts: check_prime.cpp (checks if input is a prime number)

texts:
check_prime.cpp

Description: Accepts user input to check if the user entered a prime number.

Notes: If any text inputted after an integer will be ignored.

For example: 1234.5678 and 98abc will be interpreted as 1234 and 98, respectively.

Please provide any feedback (positive or negative).

// check_prime.cpp
// Author: Chris Heath
// Date: 12/9/2018
// Description: Accepts user input to check if the user entered a prime number.
// Notes: If any text inputted after an integer will be ignored.
// For example: 1234.5678 and 98abc will be interpreted as 1234 and 98, respectively.

#include <iostream>
#include <string>
#include <limits>

using namespace std;

int is_prime (unsigned long int num)
{
    unsigned long int n;
    // avoid loop;  0 or 1 are never prime
    if (num == 0 || num == 1)
        return 0;
    // loop through numbers 0..(n/2)+1, trying to
    // divide one into the other with no remainder.
    for (n=2; n < (num/2)+1; n++)
    {
        // if we had no remainder during a revision,
        // input number has a divisor... NOT PRIME!
        if ((num % n) == 0)
          return 0;
    }
    // made it through gauntlet...prime!
    return 1;
}

int main()
{
 unsigned long int i;
 cout<<"Enter an integer to check if it is a prime: ";
 cin>>i;
 while(1)
 {
  if(cin.fail())
  {
   cin.clear();
   cin.ignore(numeric_limits<streamsize>::max(),'\n');
   cout<<"You have entered wrong input.\nPlease try again: ";
   cin>>i;
  }
  if(!cin.fail())
  break;
 }
 if ( is_prime(i) )
  cout<<"\n"<<i<<" IS PRIME!"<<endl;
 else
  cout<<"\n"<<i<<" is NOT prime."<<endl;
return 0;
}


texts: Using Stored Procedures in ColdFusion / Lucee

texts:
This is how I write all my database interactions now in Lucee:

storedproc
    procedure='OrderDetail.WhereOrderHeaderID' {
    procparam value=session.Usr.UsrID;
    procparam value=url.OrderHeaderID;
    procresult resultset=1 name='OrderDetail';
    procresult resultset=2 name='OrderHeader';
}

Assuming I've done this in SQL Server:

create schema OrderDetail authorization dbo
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'OrderHeader.[get]') AND type in (N'P', N'PC'))
DROP PROC OrderHeader.[get]
GO
CREATE PROC OrderHeader.[get]
(@UsrID Int
,@OrderHeaderID Int
) AS
SELECT OrderHeaderInfo
FROM OrderHeader
WHERE OrderHeaderID = @OrderHeaderID

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'OrderDetail.WhereOrderHeaderID') AND type in (N'P', N'PC'))
DROP PROC OrderDetail.WhereOrderHeaderID
GO
CREATE PROC OrderDetail.WhereOrderHeaderID
(@UsrID Int
,@OrderHeaderID Int
) AS
SELECT Item,Qty
FROM OrderDetail
WHERE OrderHeaderID = @OrderHeaderID
exec OrderHeader.[get] @UsrID,@OrderHeaderID


texts: Function to run MySQL SELECT queries with no leaks

texts:
I am upgrading an old massive website that is a Classic ASP \ ASP.NET hybrid. I still have a long way to MVC.

Right now I want to convert all code that uses ODBC to the mysql connector specific code.

I've made these 2 functions:

1:

DataTable GetData(string query, List<MySqlParameter> sqlParams, string sComment="")
{
    DataTable dt_tmp = new DataTable();

    if (sqlParams==null)
        sqlParams = new List<MySqlParameter>();

    Trace.Write(sComment, GenerateSQLString(query, sqlParams));
    using(MySqlDataReader myReader = MySqlHelper.ExecuteReader(sCon, query, sqlParams.ToArray()))
    {
        dt_tmp.Load(myReader, LoadOption.OverwriteChanges);
    }
    return dt_tmp;
}

2:

DataTable ReadData(string query, List<MySqlParameter> sqlParams, string sComment="")
{
    DataTable dt_tmp = new DataTable();

    if (sqlParams==null)
        sqlParams = new List<MySqlParameter>();

    Trace.Write(sComment, GenerateSQLString(query, sqlParams));

    using(MySqlConnection myConnection = new MySqlConnection(sCon))
    {
        using(MySqlCommand myCommand = myConnection.CreateCommand())
        {
            myCommand.CommandText = query;
            myCommand.Parameters.AddRange(sqlParams.ToArray());
            using (MySqlDataAdapter myAdapter = new MySqlDataAdapter(myCommand))
            {
                myAdapter.Fill(dt_tmp);
            }
        }
    }

    return dt_tmp;
}

Function #1: gets a ConstraintException (MaxLength) on a specific call... but otherwise performs very well.

Which one will perform better? (Ignoring the fact one throws an exception, which I can handle)

My goal is to have the connection open for the minimum amount of time possible so it won't use all connections from the pool.


texts:
I'm a fan of elegant ways to condense code. I find this ugly. Been staring at it for a while, can't think of a way to write this with less verbosity (ok, short of shorter var names but that's not what I mean). What do you guys think?

if angle < 60:
    red = 1
    green = angle / 60
    blue = 0
elif angle < 120:
    red = 1 - (angle - 60) / 60
    green = 1
    blue = 0
elif angle < 180:
    red = 0
    green = 1
    blue = (angle - 120) / 60
elif angle < 240:
    red = 0
    green = 1 - (angle - 180) / 60
    blue = 1
elif angle < 300:
    red = (angle - 240) / 60
    green = 0
    blue = 1
else:
    red = 1
    green = 0
    blue = 1 - (angle - 300) / 60

Replying to a request for context:

# a color wheel is drawn using aggdraw like so (the list of 360 colors I've obviously omitted but is contained in 'colors', as are several self-evident vars

for i in range(360):
            brush = aggdraw.Brush(colors[i])
            center = surface_width // 2
            inner_radius = radius - 2
            surface.polygon((center, center,
                           int(round(inner_radius + math.sin((rotation - .25) * PI / 180) * inner_radius)),
                           int(round(inner_radius + math.cos((rotation - .25) * PI / 180) * inner_radius)),
                           int(round(inner_radius + math.sin((rotation + 1.25) * PI / 180) * inner_radius)),
                           int(round(inner_radius + math.cos((rotation + 1.25) * PI / 180) * inner_radius))),
                          brush)
            rotation += 1
            if rotation > 360:
                rotation -= 360


texts:
I needed to build a one-way web service for a mobile app I developed. Its only goal is to receive incoming JSON data and insert it into the correct tables. It works, but it looks very "kludgy" and cobbled together (happens a lot with solo development).

I'd like another pair of eyes to see where it could be improved as far as design, robustness, readability, etc. This code is not yet in production, so I can implement suggested changes as needed.

<?php

$body = file_get_contents("php://input");
$json = json_decode($body, true);
//print_r($json);

function extractArray($arr)
{
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            extractArray($arr[$k]);
            foreach ($v as $kk => $vv) {
                if (is_array($vv)) {
                    unset($arr[$k][$kk]);
                    $arr[$kk] = $vv; // if you want the key to the array to be preserved.
                    // $arr[] = $vv; // would be safer, or check isset($arr[$kk]) first.
                }
            }
        }
    }
    return $arr;
}

function dbInsert(&$data)
{
    $tracks = array_shift($data);

//    //remove unneeded parent array
    $tracks = extractArray($tracks);

    /*
     * Note: user_id/page_id purposely unset.  Why? On the client side, Backbone.js
     * creates a model ID if one is not created manually. So, we create one on
     * the client side, but then remove it on the server side. Saves a lot of hassle otherwise.
     * db creates autoincrement id.
     * */
    unset($tracks['user_id']);

    $trackCols = array_keys($tracks);
    $trackVals = array_values($tracks);

    //connect to db
    $dbh = new PDO('mysql:host=localhost;dbname=kpl', 'root', 'root');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //insert tracker data
    try {
        $sth = $dbh->prepare("INSERT INTO tracker (" . implode(", ", $trackCols) . ") VALUES ('" . implode("', '", $trackVals) . "')");

        $sth->execute();

        $tracksPK = $dbh->lastInsertId();
    } catch (PDOException $e) {
        return print_r('Tracker insert failed: ' . $e->getMessage());
    }

    $pages = array_pop($data);

    foreach ($pages as &$page) {
        unset($page['page_id']);
        $pageCols = array_keys($page);

        /*
         * Note: Could not use same query structure as trackers because the foreign key user_id
         * is set dynamically.
         * */
        try {
            $sth = $dbh->prepare("INSERT INTO page (" . implode(", ", $pageCols) . ") VALUES (" . $page['view_count'] . "," . $page['visit_timestamp'] . ",'" . $page['page_viewed'] . "'," . $tracksPK . ",'" . $page['model_type'] . "')");

            $sth->execute();

        } catch (PDOException $e) {
            return print_r('Page insert failed: ' . $e->getMessage());
        }

    }

    return true;
}

if (isset($json)) {

    $info = dbInsert($json);

    print_r($info);

} else {
    die('JSON data fail');
}


texts:
This section of code reside in a utility class (LDAPUtility). It's purpose is to subscribe or unsubscribe a user from an LDAP group. My main questions are if I am using the LDAP library correctly and if I am handling the memory management correctly.

+ (BOOL)addUser:(const char *)userDN toGroup:(const char *)groupDN {
    return [LDAPUtility performOperation:LDAP_MOD_ADD withUser:userDN andGroup:groupDN];
}

+ (BOOL)removeUser:(const char *)userDN fromGroup:(const char *)groupDN {
    return [LDAPUtility performOperation:LDAP_MOD_DELETE withUser:userDN andGroup:groupDN];
}

+ (BOOL)performOperation:(int)op withUser:(const char *)userDN andGroup:(const char *)groupDN {
    LDAPMod **mods;
    LDAPMod mod;

    int err;

    mod.mod_op = op;
    mod.mod_type = "member";
    mod.mod_vals.modv_strvals = malloc(sizeof(char *));
    mod.mod_vals.modv_strvals[0] = (char *)userDN;
    mod.mod_vals.modv_strvals[1] = NULL;

    mods[0] = &mod;
    mods[1] = NULL;

    if ((err = ldap_modify_ext_s(ld, groupDN, mods, NULL, NULL)))
    {
        free(mod.mod_vals.modv_strvals);
        DDLogError(@"   ldap_modify_ext_s(): %s", ldap_err2string(err));
        return false;
    }

    free(mod.mod_vals.modv_strvals);
    return true;
}

And the layer of code above this (which is not what I am submitting for a review, but may help contextualize the code above):

+ (void)subscribeToGroup:(Group *)group completion:(void (^)(BOOL success, NSError *error))completion {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        NSError *error = nil;
        BOOL success = false;

        if (![Authenticator currentUser]) {
            // Go away, you're drunk.
            error = [NSError errorWithDomain:@"Not Authenticated" code:401 userInfo:@{NSLocalizedDescriptionKey:@"User has not authenticated."}];
        } else if (!group) {
            error = [NSError errorWithDomain:@"Missing Parameter" code:400 userInfo:@{NSLocalizedDescriptionKey:@"The group must be specified."}];
        } else {
            const char *userDN = [[Authenticator currentUser].distinguishedName UTF8String];
            const char *groupDN = [group.distinguishedName UTF8String];
            if (![LDAPUtility addUser:userDN toGroup:groupDN]) {
                error = [NSError errorWithDomain:@"LDAP Error" code:500 userInfo:@{NSLocalizedDescriptionKey:@"The LDAP server update was not successful."}];
            } else {
                success = YES;
            }
        }

        dispatch_sync(dispatch_get_main_queue(), ^{
            completion(success, error);
        });
    });
}


texts: Finding the Cox regression coefficients in a mixed model for microarray data

texts:
I have written a code for a project which aims at finding the Cox regression coefficients in a mixed model for microarray data. The study was carried out on the Affymetrix Hgu133a platform. In the following code, I have first attempted to collapsing the probes to genes with the WGCNA package, and then carry out  cox mixed effects models in a loop using the batch date as a random effects variable.I will be grateful if anyone could just check if the code is right, because it takes a very long time in giving results. I want to know not just about speeding up the code , but also if the code is correct.

Just for clarity:

probes = affymetrix probes
genes = genes which are mapped to the affymetrix probes
tdmfs = time variable
edmfs = event variable
chrdate = date of scanning the affymetrix data (proxy for batch effects)
totcomb = data containing the expression data with the expression from probes in columns, also contains the time, event and chrdate variable.

This is a different arrangement from the usual microarray data, where the expression data are usually arranged in rows.

This is a part of a much larger project where the same code is run in different random models. But the general format is the same, so if this gives a correct result, the Cox regression results for the others will also be correct, and any way this code snippet can be made to run quicker, will make the entire project quicker.

#### The expression data and the other data are separated,
#### since only the expression data will be used for collapsing the probes to genes
zz=length(colnames(totcomb))
data=totcomb[,c(1:22283)] #### expression data since affymetrixhgu133a has 22283 probes and they are in the first 22283 columns of the data frame
demo=totcomb[,c(22284:zz)]

##### For the collapsing the probes are supposed to be in rows and the samples in columns, so the data has to be transposed
data=t(data)

#### Only that data representing the probes having a mapping to a Entrez Gene ID are kept.
data=data[c(row.names(data) %in% probes),]
#### The probes are then collapsed to genes. The gene names are represented in the row names
datacol=(collapseRows(data,genes,probes))[[1]]
#### The number of genes finally the data is collapsed to
len=length(row.names(datacol))
#### The collapsed  expression data is to be transposed again so that the genes are in the columns which is needed for the cox regression that is to follow
datacol=t(datacol)
#### The expression data for the genes are then merged again with the data containing the estimated molecular subtypes, AURKA score, scan date and follow up and event times
datacol=merge(datacol, demo, by="row.names")
row.names(datacol)=datacol$Row.names
datacol$Row.names=NULL

####Make an empty matrix to store results
resmat=matrix(nrow=len, ncol=4)

####Model with the scan date serving as a proxy for batch and controlled as a random effects variable in a mixed effects Cox model.
#### The Cox regression coefficients along with the z score and the AIC of the model are calculated for each gene through a loop and the values entered into the empty matrix (column 1 contains the coefficients, column 2 the zscore for the genes and column 3 the AIC )

####Model (i): for just the batch effects modeled as a random variable
for (i in 1:len) {
         coxcomb=coxme(Surv(tdmfs,edmfs)~datacol[,c(i)]+(1|chrdate), data=datacol)
                 resmat[c(i),c(1)]=fixef(coxcomb)
         resmat[c(i),c(2)]=resmat[c(i),c(1)]/sqrt(diag(vcov(coxcomb)))
         resmat[c(i),c(3)]=-2*(coxcomb$loglik[2])+2*coxcomb$df[1]
}
#### The coefficients are then mapped to their Entrez IDs
resmat[,c(4)]=names(datacol)[1:len]