texts:
I've started to use extension methods to provide data layer functionality in our project. Our project is an MVC website using Code First Entity Framework. So, I've done things like this:

namespace OurProject.Models
{
    public class Project
    {
        public int ProjectId {get; set;}
        public string ProjectName {get; set;}
        public bool IsActive {get; set;}
    }

    public static partial class ProjectExtensions
    {
        public static IQueryable<Project> GetProjects(this IDbContext db)
        {
            return db.Project.Where(p => p.IsActive);
        }
    }
}

Then for ViewModels, I can do this:

namespace OurProject.Models.ViewModels
{
    public class ProjectViewModel
    {
        public int ProjectId {get; set;}
        public string ProjectName {get; set;}
        public string OtherProperty {get; set;}
        public bool IsActive {get; set;}
    }

    public static partial class ProjectExtensions
    {
        public static IQueryable<ProjectViewModel> GetProjectsFormatted(this IDbContext db)
        {
            return db.GetProjects()
                .Select(p => new ProjectViewModel{
                    ProjectId = p.ProjectId,
                    ProjectName = p.ProjectName,
                    OtherProperty = p.ProjectName + " Whatever",
                    IsActive = p.IsActive
                });
        }
    }
}

Is there any reason I shouldn't be doing this?


texts: Creating an enumerator based on an ATL collection

texts:
I am designing a COM wrapper for a C++ library using ATL. Currently I am a little bit confused about enumerators that are based on ATL collections. I already wrote several enumerators based on STL collections, but since there is no ICollectionOnATL-interface (such as the ICollectionOnSTL-interface), I am a little bit confused if my implementation is correct.

Here is how I am creating the enumerator at the moment:

STDMETHODIMP CCollectionOnATL::get_NewEnum(IEnumITEM** enumerator)
{
    // IItem implements IUnknown.
    typedef CInterfaceArray<IItem> Container;
    typedef CComEnum<IEnumITEM, &IID_IEnumITEM, IItem*, _CopyInterface<IItem>> CComEnumITEM;

    // Copy all elements to an array that can be enumerated.
    Container items;
    auto elements = m_coll.GetCount();
    //items.SetCount(elements);

    // See below for the definition of m_coll.
    POSITION pos = m_coll.GetHeadPosition();

    for (size_t element = 0; element < elements; element++)
    {
        auto current = m_coll.GetNext(pos);

        // Automatically calls AddRef!
        items.Add(current->m_value);
    }

    // Create an enumerator over the array.
    // Using `new` is valid here (since enumerators do not implement FinalConstruct).
    CComObject<CComEnumITEM>* pEnum = new CComObject<CComEnumITEM>();
    pEnum->Init(&items[0], &items[elements - 1], nullptr, ATL::AtlFlagTakeOwnership);

    // Return the enumerator.
    return pEnum->QueryInterface(enumerator);
}

The member m_coll is defined as CRBMap:

CRBMap<ULONG, IItem*> m_coll;

There are some points with this implementation, where I am not really sure if I understood them correctly:

Iterating the CRBMap should give me an ordered list, where the lowest key is the first and the highest key is the last element. However, I am not sure if there's a "better" (in terms of simplicity) way to perform the iteration.
Usage of CInterfaceArray to initialize the enumerator:

pEnum->Init(&items[0], &items[elements - 1], nullptr, ATL::AtlFlagTakeOwnership);

Is the initialization correct? Especially I am wondering about the third parameter, that references an IUnknown-instance to keep alive for as long as the enumerator lives. Currently I am passing nullptr, but I think the right value should be the items-array, which however does not implement IUnknown.
Regarding the enumerator initialization: Was my choose of ATL::AtlFlagTakeOwnership correct in here? I am not completely sure, because the actual ownership of the instances is taken by m_coll.
Since the size of the final array is known, I could initialize it (and therefor prevent relocations/copy-steps) using items.SetCount(elements);. However, the MSDN only states that CInterfaceArray::Add automatically calls AddRef. There's no information about SetAt or operator[]. Could I simply change the way I add items to the array to

items[element] = current->m_value;

without any change in the behaviour of reference counting?

Also if you have any suggestions on how I can further improve this code, please let me know!


texts: Defensive Fluent Interface Implementation

texts:
Introduction

At this moment in time, I'm in the process of creating some fluent interface, as a result, I've created a DSL style solution for authentication & authorisation.

As a result, the consuming code-base may look something along the lines of this:

public class Demo {

    public String login() throws IllegalStateException {
        JWTState jwt = beginAuth()
                        .authentication()
                        .username("JoeBloggs")
                        .password("Secure_Pa$$w0rD!-#0962")
                        .authenticate()
                        .whenAuthenticationFails(e -> log.error("Authentication failure", e))
                    .then()
                        .authorisation()
                        .adGroup("Basic")
                        .authorise()
                        .whenAuthorisationFails(e -> log.error("Authorisation failure", e))
                    .then()
                        .jwt()
                        .generateJwt()
                        .whenJwtFails(e -> log.error("Unable to generate JWT", e))
                        .getJwt();

        // Safety net, rather than return null or an empty string, throw this exception
        return Optional.of(jwt.isValid())
                .filter(Boolean::valueOf)
                .map(x -> jwt.token())
                .orElseThrow(() -> new IllegalStateException("Unable to generate JWT"));
    }
}

Defensive Example

Since I've gone with a defensive approach, the consuming code-base does not need to worry about exceptions that are thrown, since they're handled internally. Although, these exceptions can be visible to the consuming code upon request, as you can see with the 'whenXFails' methods. Internally, there's a lot of logic going on, an example being one of the guard clauses, an example being this snippet from the password guard clause:

// Start of class....

@Override
public void validate(String password) throws IllegalArgumentException {
    argument(password).
            regex(VALID_PASSWORD_REGEX).
            message("Supplied password is null").whenNull().
            message("Supplied password is empty").whenEmpty().
            message("Supplied password is too short").whenLessThan(MINIMUM_PASSWORD_LENGTH).
            message("Supplied password is too long").whenGreaterThan(MAXIMUM_PASSWORD_LENGTH).
            message("Supplied password does not match the valid password regex").whenNoRegexMatch();
}

// End of class....

To ensure that there's a good ability to log errors & debug this code-base, I've tried to handle nearly every scenario I can think of, expected & unexpected. In which case, you can see above that there are many specific cases where the password validation will fail, but from the consumer's perspective this isn't necessarily visible.

In the event that the consuming code-base wishes to proceed through this unit of work, it will merely alter the current state. Referring back to the Demo class, in the event of some failure, the getJwt() method will return some JWTState such as InvalidJWTState, this is to ensure that something is always returned to the consumer, meaning that the consumer need not check for null values. I've also taken the time to apply the null object design pattern to improve the defensiveness of this code.

Conclusion

Before I ramble on & on, I'd just like to cut to the chase, first off, in this instance, am I applying good practices? If not can anyone make any recommendations on how I could improve the overall quality of this code-base? Secondly, are there better methods that I'm merely not aware of?


texts:
i have made a simple sudoku solver which is a puzzle game where the player has to figure out the empty cell and checks which numbers are absent from the corresponding row, column.

how can I improve it further?

#include <iostream>

int isAvailable(int puzzle[][9], int row, int col, int num)
{
    for (int i = 0; i<9; ++i)
    {
        if (puzzle[row][i] == num) return 0;
        if (puzzle[i][col] == num) return 0;
    }
    return 1;
}

int solveSudoku(int puzzle[][9], int row, int col)
{
    if (row<9 && col<9)
    {
        if (puzzle[row][col] != 0)
        {
            if ((col + 1)<9) return solveSudoku(puzzle, row, col + 1);
            else if ((row + 1)<9) return solveSudoku(puzzle, row + 1, 0);
            else return 1;
        }
        else
        {
            for (int i = 0; i<9; ++i)
            {
                if (isAvailable(puzzle, row, col, i + 1))
                {
                    puzzle[row][col] = i + 1;
                    if ((col + 1)<9)
                    {
                        if (solveSudoku(puzzle, row, col + 1)) return 1;
                        else puzzle[row][col] = 0;
                    }
                    else if ((row + 1)<9)
                    {
                        if (solveSudoku(puzzle, row + 1, 0)) return 1;
                        else puzzle[row][col] = 0;
                    }
                    else return 1;
                }
            }
        }
        return 0;
    }
    else return 1;
}

void printSudoku(int puzzle[9][9])
{
    for (int i = 0; i<9; ++i)
    {
        for (int j = 0; j<9; ++j) {
            std::cout << puzzle[i][j] << " ";
        }
        std::cout << "\n";
    }
}

int main()
{
    int puzzle[9][9] = {
    { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
    { 5, 2, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 8, 7, 0, 0, 0, 0, 3, 1 },
    { 0, 0, 3, 0, 1, 0, 0, 8, 0 },
    { 9, 0, 0, 8, 6, 3, 0, 0, 5 },
    { 0, 5, 0, 0, 9, 0, 6, 0, 0 },
    { 1, 3, 0, 0, 0, 0, 2, 5, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 7, 4 },
    { 0, 0, 5, 2, 0, 6, 3, 0, 0 } };

    solveSudoku(puzzle, 0, 0);
    printSudoku(puzzle);
}


texts: Writing filter with one or more comparison values

texts:
(defn ret-match-row
  "Finds a row in in-seqB that matches in-valA and in-seq-keyB"
  [in-valA in-seq-keyB in-seqB]
  (filter #(= in-valA (in-seq-keyB %1)) in-seqB))

I want to expand this function, so that it still must always accept one comparison key and that n more comparison keys could be passed to the function if need be.

The only way I can think of to do this is create a non # anonymous function that would handle the comparison of multiple arguments. I do not know Clojure macros well enough to know if this would be an appropriate place to use a macro.

Minimally I would rewrite the function's argument signature like this:

(defn ret-match-row
  "Finds a row in in-seqB that matches in-valA and other optional vals."
  [match-keyA in-seq-keyB in-seqB & optional-match-keys]

Any thoughts, pointers, or guidance would be appreciated.

Here is some dummied up real data (dummied up to protected sensitive information)

666/0010|RET|xyz-ab-caba|SMITH|JOHN|HEALTHCO|377.94|20140702|201407| 2014-07-01

I need to filter on the ssn field (xyz-...) and the health description as an AND condition. I've dummied up the health description as HEALTHCO, but, in reality, the health description includes words like SPOUSE, SINGLE, and so on and is much more robust.


texts: Implementation of an asynchronous UDP server Listener

texts:
I have written this code in C# and have tested this code to ensure it works well. Any other suggestions for this code would be appreciated as I have a number of users who are sending data on this port.

private Socket serverSocket = null;
private List<EndPoint> clientList = new List<EndPoint>();
private byte[] byteData = new byte[1024];
private int port = 1517;

private void button1_Click(object sender, EventArgs e)
{
    this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    this.serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    this.serverSocket.Bind(new IPEndPoint(IPAddress.Any, this.port));
    EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
    this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);

}

private void DoReceiveFrom(IAsyncResult iar)
{

    try
    {
        EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
        int dataLen = 0;
        byte[] data = null;
        try
        {
            dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
            data = new byte[dataLen];
            Array.Copy(this.byteData, data, dataLen);
        }
        catch (Exception e)
        {
        }
        finally
        {
            EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
            this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
        }

        if (!this.clientList.Any(client => client.Equals(clientEP)))
            this.clientList.Add(clientEP);

        //     DataList.Add(Tuple.Create(clientEP, data));

        string s = Encoding.ASCII.GetString(data);

    }
    catch (ObjectDisposedException)
    {
    }
}

public void Stop()
{
    this.serverSocket.Close();
    this.serverSocket = null;
    this.clientList.Clear();
}


texts:
My previous post had no response, so there is part of the whole - levels service. It stores levels with it's attributes. I'd like to hear any suggestions about code readability and code performance.

(function() {
    'use strict';

    angular
        .module('app.mine')
        .service('levels', LevelsService);

    function LevelsService() {
        var service = {
                addLevel: addLevel,
                getNewLevelCost: getNewLevelCost,
                levels: []
            };

        activate();

        return service;

        function activate() {
            service.addLevel();
        }

        function addLevel() {
            service.levels.push(new Level(service.levels.length + 1));
        }

        function getNewLevelCost() {
            return Math.pow(60, service.levels.length);
        }

    }

    function Level(deep) {
        var level = this;

        level.deep = deep;
        level.workers = [];
    }

    Level.prototype.addWorker = levelAddWorker;
    Level.prototype.dig = levelDig;
    Level.prototype.getNewWorkerCost = levelGetNewWorkerCost;

    function Worker(deep) {
        var worker = this;

        worker.deep = deep;
    }

    Worker.prototype.dig = workerDig;

    function levelAddWorker() {
        var level = this;
        level.workers.push(new Worker(level.deep));
    }

    function levelDig() {
        var level = this;
        return {Coal: Math.pow(10, level.deep - 1)};
    }

    function levelGetNewWorkerCost() {
        var level = this;
        return Math.pow(10, level.deep) * Math.pow(1.4, level.workers.length);
    }

    function workerDig() {
        var worker = this;
        return {Coal: Math.pow(10, worker.deep - 1)};
    }

})();


texts:
Here's the exercise in brief:

  Consider the following file: Code:

  before.csv

A; ; B;
B; A; H;
C; ; D;
D; C; G;
E; D; F;
F; E; H;
G; D; ;
H; G; ;

  And a modified version of the file:

  after.csv

A; ; B;
B; A; H;
C; ; D;
D; ; G;
E; D; F;
F; E; H;
G; D; ;
K; ; E;

  The first field of the CSV is a unique identifier of each line. The
  exercise consists of detecting the changes applied to the file, by
  comparing before and after.

  There are 3 types of changes you should detect:

  ADDED (line is present in after.csv but not in before.csv)
  REMOVED (line is present in before.csv but not in after.csv)
  MODIFIED (line is present in both, but second and/or third field are modified)

  In my example, there are three modifications:

  ADDED line (K)
  REMOVED line (H)
  MODIFIED line (D)

And my code:

import collections
import csv
import sys

class P_CSV(dict):
    '''A P_CSV is a dict representation of the csv file:
       {"id": dict(csvfile)} '''

    fieldnames = ["id", "col2", "col3"]

    def __init__(self, input):
        map(self.readline, csv.DictReader(input, self.fieldnames, delimiter=";",\
                                              skipinitialspace=True))

    def readline(self, line):
        self[line["id"]] = line

    def get_elem(self, name):
        for i in self:
            if i == name:
                return self[i]

class Change:
    ''' a Change element will be instanciated
        each time a difference is found'''.

    def __init__(self, *args):
        self.args=args

    def echo(self):
        print "\t".join(self.args)

class P_Comparator(collections.Counter):
    '''This class holds 2 P_CSV objects and counts
       the number of occurrence of each line.'''

    def __init__(self, in_pcsv, out_pcsv):
        self.change_list = []

        self.in_pcsv = in_pcsv
        self.out_pcsv = out_pcsv

        self.readfile(in_pcsv, 1)
        self.readfile(out_pcsv, -1)

    def readfile(self, file, factor):
        for key in file:
            self[key] += factor

    def scan(self):
        for i in self:
            if self[i] == -1:
                self.change_list.append(Change("ADD", i))
            elif self[i] == 1:
                self.change_list.append(Change("DELETE", i))
            else: # element exists in two files. Check if modified
                j = J_Comparator(self.in_pcsv.get_elem(i), self.out_pcsv.get_elem(i))
                if len(j) > 0:
                    self.change_list += j

class J_Comparator(list):
    '''This class compares the attributes of two lines and return a list
       of Changes object for every difference'''

    def __init__(self, indict, outdict):
        for i in indict:
            if indict[i] != outdict[i]:
                self.append(Change("MODIFY", indict["id"], i, indict[i], "BECOMES", outdict[i]))
        if len(self) == 0:
            self = None

#Main
p = P_Comparator(P_CSV(open(sys.argv[1], "rb")), P_CSV(open(sys.argv[2], "rb")))
p.scan()

print "{} changes".format(len(p.change_list))
[c.echo() for c in p.change_list]

In real life, the code is supposed to compare two very large files (>6500 lines) with much more fields (>10).

How can I improve, both the style of my programming as well as the performance of the script? For the record I'm using Python2.7


texts:
I am learning actionscript 3 coding by making a crappy platformer game :)

The problem I am facing is passing lots of options to a construct function that will setup the  display object where all of them have default values.

I could send the options the normal way, like this:

function Box(param1:Number=1, param2:Number=2, param3:Number=3, param4:Number=4){

}

but this seemed to be parameter pollution, so I made this class:

package
{
    import flash.display.Sprite;
    public class Box extends Sprite {
        public var color:Number = 0x000000;
        public var tileW:Number = 50;
        public var tileH:Number = 50;
        public var walkable:Boolean = true;
        public var speedY:Number = 0;
        public var speedX:Number = 0;
        function Box(options:Object) {
            for(var i:String in options) {
                this[i] = options[i];
            }
            graphics.beginFill(this.color);
            graphics.drawRect(0, 0, this.tileW, this.tileH);
            graphics.endFill();
        }
    }
}

This works, but I have a feeling that I am missing something very basic, that everything I try to write is wrong...


texts:
For a new project, I've started learning Golang. This is one of my very first steps in Go.

The objective that I've given myself is to convert int to a String representing the roman numeral of that int. The supported range shall start with 0, negative numbers can be ignored, and it's okay for now that for negative numbers, an empty String is returned.

File roman_test.go

package main

import "testing"

func TestRoman(t *testing.T) {
    testcases := []struct {
        number int
        roman string
    }{
        { 0, "" },
        { 1, "I" },
        { 2, "II" },
        { 4, "IV" },
        { 5, "V" },
        { 1993, "MCMXCIII" },
        { 2018, "MMXVIII" },
        { 1111, "MCXI" },
        { 2222, "MMCCXXII" },
        { 444, "CDXLIV" },
        { 555, "DLV" },
        { 666, "DCLXVI" },
        { 999, "CMXCIX" },
    }

    for _, testcase := range testcases {
        roman := Roman(testcase.number)
        if roman != testcase.roman {
            t.Errorf("%d expected to convert to %s, got: %s.", testcase.number, testcase.roman, roman)
        }
    }
}

File roman.go

package main

func Roman(number int) string {
    conversions := []struct{
        value int
        digit string
    }{
        {1000, "M"},
        {900, "CM"},
        {500, "D"},
        {400, "CD"},
        {100, "C"},
        {90, "XC"},
        {50, "L"},
        {40, "XL"},
        {10, "X"},
        {9, "IX"},
        {5, "V"},
        {4, "IV"},
        {1, "I"},
    }

    roman := ""
    for _, conversion := range conversions {
        for number >= conversion.value {
            roman += conversion.digit
            number -= conversion.value
        }
    }
    return roman
}

I'm mainly interested in feedback on the following aspects:

Go code style
Idiomatic go
Better structure


texts:
I'm making a Texas Hold'em game for multiple players. So far, I have finished the flow control for betting / calling sequences, player stack / pot updating, and just now - the part responsible for drawing cards and distributing them. It is this last part that I would like reviewed, if possible.

Essentially, I wanted to know what I could do differently / more efficiently, suggested changes, really just anything that could be helpful. Things like checks for proper input from player etc are not yet in place so please ignore them.

import itertools
import random

player_count = int(input("How many players? "))

suits = ['s', 'c', 'd', 'h']
faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']

# Defining deck and drawing cards (5 + 2 per player):

deck = set(itertools.product(faces, suits))
drawn_cards = random.sample(deck,(5 + 2 * player_count))

# Storing a list with player object instances

players = []

class Players:

    def __init__(self, stack):

        self.stack = stack
        self.last_action = "none"  ## last action taken (check, call etc).
        self.street_bets = 0       ## total bets on current street

    def holecards(self):

## pop cards from list and pritifying their display. Cards will later be
## run through a function for checking value of hands:

        card1 = drawn_cards.pop(len(drawn_cards)-1)
        card2 = drawn_cards.pop(len(drawn_cards)-1)
        self.card1 = (card1[0]+"["+card1[1]+"]")
        self.card2 = (card2[0]+"["+card2[1]+"]")
        self.cards = self.card1+ " - " +self.card2
        print (self.cards)

class Table:

    def __init__(self):

        self.total_pot = 0

    def flop(self):

        card1 = drawn_cards.pop(len(drawn_cards)-1)
        card2 = drawn_cards.pop(len(drawn_cards)-1)
        card2 = drawn_cards.pop(len(drawn_cards)-1)
        self.card1 = (card1[0]+"["+card1[1]+"]")
        self.card2 = (card2[0]+"["+card2[1]+"]")
        self.card3 = (card2[0]+"["+card2[1]+"]")
        self.flop = self.card1+ " - " + self.card2 + " - " + self.card3
        print (self.flop)

    def turn(self):

        card = drawn_cards.pop(len(drawn_cards)-1)
        self.card = (card[0]+"["+card[1]+"]")
        self.turn = self.card
        print (self.turn)

    def river(self):

        card = drawn_cards.pop(len(drawn_cards)-1)
        self.card = (card[0]+"["+card[1]+"]")
        self.river = self.card
        print (self.river)

# Add player stacks and distribute holecards:

for i in range(player_count):
    players.append(i)
    players[i] = Players(100)
    players[i].holecards()

# Add dealer to table:

dealer = Table()

dealer.flop()
dealer.turn()
dealer.river()


texts:
A simple algorithm that can be run by two processes to ensure mutual exclusion for one resource.Shared variables are created and initialized before either process starts. The shared variables flag[0] and flag[1] are initialized to FALSE because neither process is yet interested in the critical section. The shared variable turn is set to either 0 or 1 randomly (or it can always be set to say 0)

# include <stdio.h>
# include <unistd.h>
# include <sys/types.h>
# include <sys/mman.h>

    //Shared Global variables to control processes
    static int *flag0;
    static int *flag1;
    static int *turn;

int main(int argc, char const *argv[])
{

    flag0 = mmap(NULL, sizeof *flag0, PROT_READ | PROT_WRITE,
                    MAP_SHARED | MAP_ANONYMOUS, -1, 0);

    flag1 = mmap(NULL, sizeof *flag1, PROT_READ | PROT_WRITE,
                    MAP_SHARED | MAP_ANONYMOUS, -1, 0);

    turn = mmap(NULL, sizeof *turn, PROT_READ | PROT_WRITE,
                    MAP_SHARED | MAP_ANONYMOUS, -1, 0);

    *flag0 = 0;
    *flag1 = 0;
    *turn;

    // creates child process
    pid_t pid = fork();

    //prcess 1 (parent):
    if(pid > 0){

        //process ready
        *flag0 = 1;
        // turn selector
        *turn = 1;
        int counter = 0;
        //while to wait for turn change
         while (*flag1 && *turn == 1)
         {
             // busy wait
            printf("Parent waiting: %d sec.\n", counter);
            sleep(1);
            counter++;

         }
         // critical section
         printf("PARENT: critical section\n");
         sleep(5);
         // end of critical section
         *flag0 = 0;

    }

    //process 2 (child):
    if(pid == 0){

        //process ready
        *flag1 = 1;
        // turn selector
        *turn = 0;
        //while to wait for turn change
        int counter = 0;
         while (*flag0 == 1 && *turn == 0)
         {
             // busy wait
            printf("Child waiting: %d sec.\n", counter);
            sleep(1);
            counter++;

         }
         // critical section
         printf("CHILD: Critical section\n");
         sleep(5);
         // end of critical section
         *flag1 = 0;

    }

    wait(); // wait for child
    return 0;
}


texts: Query for stddev of number of stars per chatroom message

texts:
I am learning SQL today, so I decided to practice by writing some queries for The Nineteenth Byte Data Explorer. This is a PostgreSQL database about messages from The Nineteenth Byte chatroom, created by El'endia Starman. The schema can be found at the bottom of the page.

The code functions correctly (as far as I can tell), but it could surely look better. In particular, I'm interested in knowing more elegant ways to store the result of an expression to be used later in the query. Right now, I'm creating a table containing one value using a WITH clause and then SELECTing * from the table each time I want to reference the number.

The purpose of the code is to, given an SE chat user ID, find the mean and standard deviation of the number of stars on messages posted by that user, among those which have at least one star.

The code can be tested here.

WITH SE_Chat_ID_to_search AS ( SELECT
169713   -- your query here
AS VAL),

internal_id as (
   SELECT max(id)
   FROM "transcriptAnalyzer_user"
   WHERE uid = (SELECT * from SE_Chat_ID_to_search)
),

stats as (
   SELECT AVG(stars) as mean, COUNT(*) as num_starred
   FROM "transcriptAnalyzer_message"
   WHERE user_id = (SELECT * FROM internal_id) AND stars > 0
),

sum_diff_squared as (
   SELECT sum(power((SELECT mean from stats) - stars, 2.)) as sds
   FROM "transcriptAnalyzer_message"
   WHERE user_id = (SELECT * FROM internal_id) AND stars > 0
)

SELECT mean, power(sds / num_starred, 0.5) as stddev from stats, sum_diff_squared


texts:
This problem is identical to the one here:

  Suppose that you have been assigned the job of buying the plumbing
  pipes for a construction project. Your foreman gives you a list of the
  varying lengths of pipe needed, but the distributor sells stock pipe
  only in one fixed size. You can, however, cut each stock pipe in any
  way needed. Your job is to figure out the minimum number of  stock
  pipes required to satisfy the list of requests, thereby saving money
  and minimizing  waste.

  Your job is to write a recursive function

int cutStock(Vector<int> & requests, int stockLength);

  that takes two arguments—a vector of the lengths needed and the length
  of stock pipe  that the distributor sells—and returns the minimum
  number of stock pipes needed to  service all requests in the vector.
  For example, if the vector contains [ 4, 3, 4, 1, 7, 8 ]  and the
  stock pipe length is 10, you can purchase three stock pipes and divide
  them as  follows:

  Pipe 1: 4, 4, 1

  Pipe 2: 3, 7

  Pipe 3: 8

  Doing so leaves you with two small remnants left over. There are other
  possible  arrangements that also fit into three stock pipes, but it
  cannot be done with fewer.

/*
 * File: StockCutting.cpp
 * ----------------------
 * Name: abdulrhman eaita
 * This code minimize the needed stock for a diffrent length requests
 *
 */

#include <iostream>
#include "console.h"
#include "vector.h"
#include "simpio.h"
using namespace std;

/* Function prototypes */

int cutStock(Vector<int> & requests, int stockLength);
void bibesCutter(Vector<int> & requests, int stockLength, int &rest, int &bibes);
/* Main program */

int main() {
   Vector<int> requests;
   while (true) {
       while (true) {
           int x = getInteger("enter your requests, 0 to end: ");
           if(x == 0) break;
           requests.add(x);
       }
       int stoclLen = getInteger("Stock length?: ");
       cout << "Minimum number of stock pipes: " << cutStock(requests, stoclLen) << endl;
       requests.clear();
   }
   return 0;
}

/*
 * Function: cutStock
 * Usage: int units = cutStock(requests, stockLength);
 * ---------------------------------------------------
 * wrapper function for bibesCutter();
 */

int cutStock(Vector<int> & requests, int stockLength) {
    int bibes = 0;
    int rest = 0;
    bibesCutter(requests,stockLength, rest, bibes);
    return bibes;
}
/*
 * Function: bibesCutter
 * USage: bibesCutter(requests, stocklen, rest, bibes);
 * ----------------------------------------------------
 * Computes the minimum number of stock pipes required to satisfy
 * the vector of requests of individual pieces.
 */
void bibesCutter(Vector<int> & requests, int stockLength, int & rest, int & bibes){
    if (requests.size() == 1) {
        if (requests[0] > rest) {
            bibes++;

            //creating new rest as it's new stock and substracting the request after adding new bibe
            rest = stockLength - requests[0];

            return;
        }else{
            // substracting the request from current rest only.
            rest -= requests[0];
            return;
        }
    }else{
        Vector<int> tmp ;
        int toCheck = 0;
        // checking if there's a smaller value to remove first
        for (int i = 0; i < requests.size(); ++i) {
            if (requests[i] < rest) {
                toCheck = i;
            }
        }
        // removing first item by default, if there's no smaller cut.
        tmp += requests[toCheck];
        requests.remove(toCheck);
        bibesCutter(tmp, stockLength, rest, bibes);
        bibesCutter(requests, stockLength, rest, bibes);
        return;
    }
}


texts:
I wrote a function that generates an image like:

The function is as follows:

    /** Draws a texture wherein are spots of "heat" where a pixel's spotColor is of highest alpha, fading as distance from heat
     * spots increases.
     * @param width
     * @param height
     * @param spotColor The color of the spots, ignores alpha.
     * @param density
     * @return */
    public static Texture drawHeatSpots (int width, int height, Color spotColor, Magnitude density) {
        Pixmap p = new Pixmap(width, height, Format.RGBA8888);

        int spotCount;
        if (density == Magnitude.high)
            spotCount = width * height / 5000;
        else if (density == Magnitude.medium)
            spotCount = width * height / 6500;
        else if (density == Magnitude.low)
            spotCount = width * height / 8000;
        else
            throw new IllegalArgumentException(density.name() + " is an invalide Magnitude");

        Array<Vector2> spots = new Array<>();
        boolean next;

        for (int i = 0; i < spotCount; i++) {
            next = false;
            while (!next) {
                Vector2 v = new Vector2(MathUtils.random(width), MathUtils.random(height));
                if (!spots.contains(v, false)) {
                    spots.add(v);
                    next = true;
                }
            }
        }

        Vector2 v = new Vector2();
        Color c = new Color(spotColor);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                v.set(x, y);
                if (spots.contains(v, false)) {
                    c.a = 1;
                    p.drawPixel(x, y, Color.rgba8888(c));
                    continue;
                }
                c.a = calcAlpha(v, spots);
                p.drawPixel(x, y, Color.rgba8888(c));
            }
        }

        return new Texture(p);
    }

    private static float calcAlpha (Vector2 pos, Array<Vector2> spots) {
        float a = 0;
        for (Vector2 v : spots) {
            a += 1f / Math.sqrt(Math.pow(pos.x - v.x, 2) + Math.pow(pos.y - v.y, 2));
        }
        if (a > 1) a = 1;
        if (a < 0) a = 0;

        return a;
    }
}

In the picture, the magnitude is at high and it takes roughly 3 seconds to generate the image. At low, it takes about 2 seconds. Preferably, I would like the generation to take less than 1 second on high (without decreasing the number of spots).

Is there any way I can speed up the generation of this image? Or is this the best and fastest way to get an image similar to the one?


texts: AngularJS controller to fetch and display employee data from database

texts:
This is the code for an AngularJS controller that I've written:

app.controller('employeeController', function (employeeService) {

    var Controller = this;

    Controller.employees = {};
    Controller.fetchedEmployee = {};

    Controller.populateTable = function (data) {

        Controller.employees = data;
    };

    Controller.error = function (errorResponse) {
        console.log("error function called.");
        console.log(errorResponse);
        // Request Errors
        if(errorResponse.status === 400) alert("Error: " + errorResponse.data.error + ": There was a problem with the data you submitted. \nPlease enter valid form data.");
        else if(errorResponse.status === 401) alert("Error: " + errorResponse.data.error + ": You need to provide proper authorization credentials to continue.");
        else if(errorResponse.status === 403) alert("Error: " + errorResponse.data.error + ": You are not allowed to perform this action.");
        else if(errorResponse.status === 404) alert("Error: " + errorResponse.data.error + ": The requested file or resource was not found.");
        else if(errorResponse.status === 408) alert("Error: " + errorResponse.data.error + ": The connection timed out. Please try again later.");
        else if(errorResponse.status === 410) alert("Error: " + errorResponse.data.error + ": The requested resource is no longer available.");
        else if(errorResponse.status === 418) alert("Error: " + errorResponse.data.error + ": I'm a teapot, not a coffeepot.");
        // Server Errors
        else if(errorResponse.status === 500) {
            if(errorResponse.data.exception === "java.sql.SQLException") alert("Error establishing connection with database. Please try again later.");
            else alert("Error: " + errorResponse.data.error + ": Generic Server Error.");
        }
    };

    Controller.deleteEmployee = function(id) {

        employeeService.getEmployee(id).then(function(data) {
            Controller.fetchedEmployee = data.empInfo;
            var reallyDelete = confirm("Do you really want to delete " + Controller.fetchedEmployee.employeeName + "?");
            console.log(reallyDelete);
            if(reallyDelete === true) employeeService.deleteEmployee(id);

        }, Controller.error);

    };

    // Call Service to List all Employees
    console.log("Service called to populate table.");
    employeeService.getAllEmployees().then(Controller.populateTable, Controller.error);
    Controller.populateTable();
});

Not that this code hasn't gone through improvements; initially it was full of this.something or even worse, $scope.something (scope soup), which made it difficult to understand and even resulted in some of the code being broken.

However, it still feels sloppy. It feels like all the functions and variables have been 'injected' randomly in the controller; like someone randomly putting playing cards in a neatly shuffled deck or randomly placing books in a bookshelf.

Could anyone help me devise a methodology to organize this code to have a definite structure?


texts: Arabic to Greek numeral converter, 1 - 10

texts:
One of the things that's straight-forward in JavaScript is Unicode support. If you want to return ϝ (lowercase digamma, not a simple f), you simply tell it to do so. No look-up, conversion or unreadable Unicode codes required.

I want to build a translator between Arabic and Greek numerals. Since my projects tend to take forever to complete, I decided to post what I have instead of waiting till it's finished. The code currently supports 1 - 10 and translates them to the Unicode Greek equivalent.

I wrote it the most straight-forward way I could think of. It's not necessarily the best way.

function arabicToGreek(input) {
    'use strict';
    switch (input) {
    case 1:
        return "α";
    case 2:
        return "β";
    case 3:
        return "γ";
    case 4:
        return "δ";
    case 5:
        return "ε";
    case 6:
        return "ϝ";
    case 7:
        return "ζ";
    case 8:
        return "η";
    case 9:
        return "θ";
    case 10:
        return "ι";
    }
    return "";
}

Usage:

arabicToGreek(4);
arabicToGreek(10);

Output:

δ
ι

Run it at repl.it

I'm aware ϝ (6) should possibly be written as ϛ. I'm also aware I may or may not need to include diacritics.

I'm especially looking for a review on the usual suspects: naming, idiomatic style and modularity. All other advice is welcome as well.


texts: Find non duplicate Triangle Triplets from a list of given numbers- version 3

texts:
It is a continuation of my previous question:

Find non duplicateTriangle Triplets from a list of given numbers

After I realized triplet structure using less space than std:vector<int> and there is a simple way to remove duplicates from the triplets list by modifying loops index I rewrote the code again. On top of that it may be impossible to write a \$O(N^2)\$ solution for a three dimensional problem in this case. There are a few additional changes also: using lambda to avoid a function call and a few direct initialization attempts instead depending on assignment operations.

#include<vector>
#include<iostream>

struct Triplet
{
    int first;
    int second;
    int third;
};

std::vector<Triplet> findTriangleTriplets( std::vector<int>& vec_input )
{
    std::vector<Triplet> triplets;
    unsigned int size = vec_input.size();

    for( unsigned int i=0; i < size; ++i )
    {
        for( unsigned int j = i; j < size; ++j )
        {
            for( unsigned int k = j; k < size; ++k)
            {
                int first  ( vec_input.at( i ) );
                int second ( vec_input.at( j ) );
                int third  ( vec_input.at( k ) );

                if( [ &first, &second, &third ] {
                       return ( ( second + third  ) > first   )&&
                              ( ( first + third   ) > second  )&&
                              ( ( first + second  ) > third  );
                    }())
                {
                    triplets.emplace_back( Triplet{ first, second, third } );
                }
            }
        }
    }
    return triplets;
}

int main()
{
    std::vector<int> vec_input {  2, 4,  5, };

    std::vector<Triplet> triplets = findTriangleTriplets( vec_input );
    for ( auto &x : triplets )
    {
        std::cout<<x.first<<" "<<x.second<<" "<<x.third<<"\n";
    }
    return 0;
}


texts:
I implemented basic string compression algorithm that uses the counts of repeated characters. For example: the string aabcccccaaa would become a2b1c5a3. What do you think about this, is there a better way to do this?

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

char* compressString(char* arr, int size);

int main() {

  char arr[] = "aabcccccaa";
  char *str;
  printf("Before compression: %s\n", arr);
  str = compressString(arr, strlen(arr));
  printf("After compression: %s\n", str);
  // free allocated memory
  free(str);
  return 0;
}

char* compressString(char* str, int len) {
  char last = str[0];
  char *buf = (char *)malloc(len * sizeof(char));
  int count = 1;
  int j = 0;

  for (int i = 1; i < len; i++) {
    if (last == str[i]) {
      count++;
    } else {
      buf[j++] = last;
      buf[j++] += count + '0';
      last = str[i];
      count = 1;
    }
  }
  buf[j++] = last;
  buf[j] += count + '0';
  buf[j] = '\0';
  return buf;
}


texts:
Here is a implementation of the cryptographic hash function SHA1 written in Python.  It does not use any external libraries, only built-in functions. I know that it would be faster to use an external library, but my code is for learning purposes.

I want to know if I am properly implementing the algorithm.  Am I taking any unnecessary steps? What changes can I make to speed up the code?

The code properly works.  I've compared the result to a trusted implementation.

def sha1(data):
    bytes = ""

    h0 = 0x67452301
    h1 = 0xEFCDAB89
    h2 = 0x98BADCFE
    h3 = 0x10325476
    h4 = 0xC3D2E1F0

    for n in range(len(data)):
        bytes+='{0:08b}'.format(ord(data[n]))
    bits = bytes+"1"
    pBits = bits
    #pad until length equals 448 mod 512
    while len(pBits)%512 != 448:
        pBits+="0"
    #append the original length
    pBits+='{0:064b}'.format(len(bits)-1)

    def chunks(l, n):
        return [l[i:i+n] for i in range(0, len(l), n)]

    def rol(n, b):
        return ((n << b) | (n >> (32 - b))) & 0xffffffff

    for c in chunks(pBits, 512):
        words = chunks(c, 32)
        w = [0]*80
        for n in range(0, 16):
            w[n] = int(words[n], 2)
        for i in range(16, 80):
            w[i] = rol((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1)

        a = h0
        b = h1
        c = h2
        d = h3
        e = h4

        #Main loop
        for i in range(0, 80):
            if 0 <= i <= 19:
                f = (b & c) | ((~b) & d)
                k = 0x5A827999
            elif 20 <= i <= 39:
                f = b ^ c ^ d
                k = 0x6ED9EBA1
            elif 40 <= i <= 59:
                f = (b & c) | (b & d) | (c & d)
                k = 0x8F1BBCDC
            elif 60 <= i <= 79:
                f = b ^ c ^ d
                k = 0xCA62C1D6

            temp = rol(a, 5) + f + e + k + w[i] & 0xffffffff
            e = d
            d = c
            c = rol(b, 30)
            b = a
            a = temp

        h0 = h0 + a & 0xffffffff
        h1 = h1 + b & 0xffffffff
        h2 = h2 + c & 0xffffffff
        h3 = h3 + d & 0xffffffff
        h4 = h4 + e & 0xffffffff

    return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4)

print sha1("hello world")


texts: Translate a day in year to month and day

texts:
Take an integer representing a day of the year and translate it to a string consisting of the month followed by day of the month. For example, Day 32 would be February 1.

This is what I came up with. I'm sure that there's something more streamlined than else if statements.

vector<string>DayOfYear::months = { "January","February","March","April",
                                "May","June","July","August",
                                "September","October","November","December"};

string DayOfYear::convertDayOfYear(int num){
if (num <= 31)
    return months[0] + " " + to_string(num);
else if (num > 31 && num <= 59)
    return months[1] + " " + to_string(num - 31);
else if (num > 59 && num <= 90)
    return months[2] + " " + to_string(num - 59);
else if (num > 90 && num <= 120)
    return months[3] + " " + to_string(num - 90);
else if (num > 120 && num <= 151)
    return months[4] + " " + to_string(num - 120);
else if (num > 151 && num <= 181)
    return months[5] + " " + to_string(num - 151);
else if (num > 181 && num <= 212)
    return months[6] + " " + to_string(num - 181);
else if (num > 212 && num <= 243)
    return months[7] + " " + to_string(num - 212);
else if (num > 243 && num <= 273)
    return months[8] + " " + to_string(num - 243);
else if (num > 273 && num <= 304)
    return months[9] + " " + to_string(num - 273);
else if (num > 304 && num <= 334)
    return months[10] + " " + to_string(num - 304);
else if (num > 334 && num <= 365)
    return months[11] + " " + to_string(num - 334);
else
    return "Invalid number.\n";
}


texts:
I have the following Ruby code in an RSpec file:

  describe "order" do
    before do
      LIST_LENGTH ||= 10
      @skills = FactoryGirl.create_list(:skill, LIST_LENGTH)
      @developer = FactoryGirl.create(:user)
      @requests = FactoryGirl.create_list(:request, LIST_LENGTH)
      LIST_LENGTH.times { |i| @requests[i].skills = @skills[0..i] }
    end

    describe "#order_by_interestingness_for" do
      it "orders by interestingness" do
        @developer.add_interested_skills(@skills)
        Request.all.shuffle.map {
          |r| r.interestingness_for(@developer)
        }.should_not be_in_order

        Request.order_by_interestingness_for(@developer).map {
          |r| r.interestingness_for(@developer)
        }.should be_in_order
      end
    end

    describe "#order_by_qualifiedness_for" do
      it "orders by interestingness" do
        @developer.add_proficient_skills(@skills)
        Request.all.shuffle.map {
          |r| r.qualifiedness_for(@developer)
        }.should_not be_in_order

        Request.order(:interestingness, :developer => @developer).map {
          |r| r.qualifiedness_for(@developer)
        }.should be_in_order
      end
    end
  end

Obviously, this is not very DRY. I don't really know how to make it more DRY, though, since the the unique parts are so deeply ingrained in the code. I'm guessing I have a deeper design problem. I'm not really sure, though. Any ideas?


texts:
In my assignment I am executing a long running NodeJs script from C# using EdgeJs. Since the script may take a long time to execute, I also want to provide user an option to Cancel the script execution in the middle. The cancellation status is maintained in the database and function IsScripteExecutionCancelled returns true if the user decides to cancel the execution.

To achieve this I am executing script in a background thread using Task.Run(). The main thread contains a while loop that runs until the ScriptExecution is over or is cancelled. I can solve this problem using native System.Threading.Thread, but here I am trying to do it using TPL. Here is the code I have put in place:

bool executionStarted = false;
bool taskCompleted = false;
Result returnValue;

CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;

Task executionTask;
while (!(taskCompleted || token.IsCancellationRequested))
{
    if (!executionStarted)
    {
        executionStarted = true;
        executionTask = Task.Run(() =>
        {
            returnValue = ExecuteScript();
            taskCompleted = true;
        }, token);
    }
    bool taskExecutionCancelled = IsScripteExecutionCancelled();
    if (taskExecutionCancelled)
    {
        tokenSource.Cancel();
    }
}

if(token.IsCancellationRequested)
    returnValue= GetDefaultValueForCancellation();

return returnValue;

So, if IsScripteExecutionCancelled returns true the program will come out of the loop and will check if the script was cancelled, in which case I will return a default response. If the ExecuteScript completes my program will return the value returned by function ExecuteScript. I am able to get the desired results using this implementation however I would like to get it validated.

Question: Is it the right way to address this problem?


texts: Is this the right approach for Controller-Service-Dao implementation?

texts:
I am a bit confused with Controller Service Dao implementation . I created a dummy User servlet along with Model controller dao and a service , though it will work , but is it the right approach. I am still confused about the purpose of service class

//user registration Service
//add user , delete user
@WebServlet("/useraction")
class UserController
{
    UserService userService = new userService();
    int id = request.getParameter("id");

    userService.userAction(int id,String action);
    //minimum code for sake of question
}

class UserService
{
    UserDao userDao = UserDaoImpl.getInstance();

    void userAction(int id,String action)
      switch(action){
       case "add" :
         userDao.addUser(id);
         break;
       case "delete" :
         userDao.deleteUser(id);
         break;
       default :
         throw IllegalArgumentException();
      }
    }
}

interface UserDao
{
    void deleteUser(int id);
    void addUser(int id);
}

class UserDaoImpl implements UserDao
{
    private static UserDaoImpl userDaoImpl = new UserDaoImpl();

    public static UserDaoImpl getInstance(){
        if(userDaoImpl == null)
            userDaoImpl = new UserDaoImpl();
        return userDaoImpl;
    }

    void deleteUser(int id){
        //some validations and db activity
    }

    void addUser(int id){
        //some validations and db activity
    }

}

//Model
class User
{
    private int id;
    private String name;
    private String email;
    //a lot more parameters
}

Questions i want to ask :

Is this the right approach for Controller dao service pattern?
Purpose of service class , is it for redirection only to dao or for validations also
Do we need to use inheritance for Dao classes ?

Thanks in Advance


texts: Build clusters from connections (virus propagation)

texts:
The scenario is the following: There is a list of persons and places where those persons visit. Each person is connected to a single or multiple places. See the picture below, where O[i] represents objects (persons) and P[i] places, respectively.

I need to get the list of places connected by those persons.

Codes:

class Program
{
    static void Main(string[] args)
    {
        var Connections = new List<Tuple<string, List<string>>>()
        {
            new Tuple<string, List<string>>("O1", new List<string>(){ "P1", "P2" }),
            new Tuple<string, List<string>>("O2", new List<string>(){ "P2", "P3", "P4" }),
            new Tuple<string, List<string>>("O3", new List<string>(){ "P8" }),
            new Tuple<string, List<string>>("O4", new List<string>(){ "P5", "P11" }),
            new Tuple<string, List<string>>("O5", new List<string>(){ "P2", "P3" }),
            new Tuple<string, List<string>>("O6", new List<string>(){ "P4"}),
            new Tuple<string, List<string>>("O7", new List<string>(){ "P7", "P10" }),
            new Tuple<string, List<string>>("O8", new List<string>(){ "P5", "P6", "P7", "P12" }),
            new Tuple<string, List<string>>("O9", new List<string>(){ "P7", "P11" }),
            new Tuple<string, List<string>>("O10", new List<string>(){ "P13" }),
            new Tuple<string, List<string>>("O11", new List<string>(){ "P8", "P9" }),
        };

        var Clusters = Connections.Select(x => x.Item2).ToList();

        bool proceed = true;
        do
        {
            var pairs = Clusters.SelectMany(x => Clusters, (x, y) =>
            Tuple.Create(x, y)).Where(x => x.Item1 != x.Item2);

            proceed = false;
            foreach (var pair in pairs)
            {
                var cluster1 = pair.Item1;
                var cluster2 = pair.Item2;

                if (cluster1.Intersect(cluster2).Any())
                {
                    cluster1.AddRange(cluster2.Where(x => !cluster1.Contains(x)));
                    Clusters.Remove(cluster2);
                    proceed = true;
                    break;
                }
            }
        } while (proceed);

        foreach (var cluster in Clusters.OrderByDescending(x => x.Count()))
        {
            Console.WriteLine(cluster.OrderBy(x => x).Aggregate((i, j) => i + ", " + j));
        }
        Console.Read();
    }
}

Output:

P10, P11, P12, P5, P6, P7
P1, P2, P3, P4
P8, P9
P13

Questions:

Is this optimal way to solve the given problem for larger data?
How can I estimate the computational complexity of those operations?
Am I doing here something potentially dangerous or excessive with the collections?
Any other concerns or remarks?

Any feedback would be appreciated.


texts:
Task description

  You are given a list and an item, find the length of the longest consecutive subsequence of the list containing only the item.

Testcases

[1, 1, 2, 3] 1 -> 2
[1, 0, 0, 2, 3, 0, 4, 0, 0, 0, 6] 0 -> 3

This code is pretty readable in my opinion but I fear that the \$O(N^2)\$ time complexity is sub-optimal.

def subsequences(arr)
  ((0...arr.length).to_a)
    .repeated_permutation(2)
    .select {|start, finish| finish >= start}
    .collect {|start, finish| arr[start..finish] }
end

def longest_item_only_subsequence_len(arr, item)
   subsequences(arr)
     .select {|seq| seq.all? {|i| i == item} }
     .max_by(&:length)
     .length
end

p subsequences([1, 2, 3])
p longest_item_only_subsequence_len([1, 0, 0, 2, 3, 0, 4, 0, 0, 0, 6], 0)


texts:
I've written an implementation of a dynamic array in C, but I'm not sure if my implementation is correct... This is what I'm worried about: if I add an element, will it remain in the collection? This problem has arisen from my (apparently) limited knowledge on void pointers. I haven't found any answers to my question online...

The List struct is defined like this:

typedef struct list
{
    /**
     * C-style array containing the data in this list.
     */
    void** data;
    /**
     * Amount of elements currently present in this list.
     */
    unsigned int size;
    /**
     * Amount of elements that could be present in this list (i.e. size + number of empty spots).
     */
    unsigned int capacity;
} List;

So far so good?

Now, when I want to add an element to a list l, I call List_Add(&l, &element)...

void List_Add(List* list, void* element)
{
    if (list->data == NULL)
    {
        return;
    }

    if (list->size == list->capacity)
    {
        // Double the data array of list.
        list->data = realloc(list->data, 2 * list->capacity * sizeof(void*));
        list->capacity *= 2;
    }

    if (list->data != NULL)
    {
        list->data[list->size] = element;
        ++(list->size);
    }
}

By the way: yes, list->data is malloced before calling this function.

I've done some testing with adding elements, but I'm not sure if it's entirely correct. If I were to call this function with an element created on the stack (example below), would it continue to work for the entirety of the program's lifetime?

Example

List l;
List_Init(&l);
int i = 1;
List_Add(&l, &i);


texts: jQuery UI tabs: navigation thru tabs using active options

texts:
I am using jQuery UI Tabs for a web application and I would like to navigate thru different tabs with these four buttons:

next-tab: takes you to the next tab
prev-tab: takes you to the previous tab
preview-btn: takes you to the preview tab (a specific tab or the last tab)
back-btn: takes you to the last active tab from preview tab (in my code does not work yet).

For example, if you were in the tab no 2 and clicked on preview-btn, it takes you to the preview-tab. If you click on the back-btn, it should take you back to the tab no. 2.

How can I achieve all these goals in an efficient way?

(document).ready(function() {

  // initializing the tabs
  $('#tab-container').tabs();

  // tabs min height
  $('#tab-container').tabs().css({
    'min-height': '500px',
    'overflow': 'auto'
  });

  // takes you to the next tab
  $(".next-tab").click(function() {
    var active = $("#tab-container").tabs("option", "active");
    $("#tab-container").tabs("option", "active", active + 1);
  });

  // takes you to the previous tab
  $(".prev-tab").click(function() {
    var active = $("#tab-container").tabs("option", "active");
    $("#tab-container").tabs("option", "active", active - 1);
  });

  // takes you to the preview tab
  $(".preview-btn").click(function() {
    $("#tab-container").tabs("option", "active", 5);
  });

  // takes you back to your last tab from preview tab
  $(".back-btn").click(function() {
    var active = $("#tab-container").tabs("option", "active");
    $("tab-container").tabs("option", "active", active);
  });

});

Nunc tincidunt

Proin dolor

Aenean lacinia

Aenean lacinia

Aenean lacinia


texts:
Warning: I'm quite new to low-level programming and memory management so please don't mind it when I'm asking incredibly stupid things.

I'm working on a project where I need to read all the lines from a file and store them for further usage. I decided to use a linked list of untyped pointers for this which will contain pointers to characters.

The following code for testing actually does the job but I've got a feeling that the creation and extending of the list could be done in a "cleaner" way.

list-test.c

struct Node {
  void *value;
  struct Node *next;
};

long int count_to_next(char which, char *buffer, long int max);
void string_copy(char *from, char *to, long int chunk_size);

int main() {
  char *raw = "Line 1\nLine 2\nLine 3";
  int remaining = 20;
  int chunk_size;
  char *pointer = raw;
  char *buffer;
  struct Node *root = malloc(sizeof(struct Node));
  struct Node *last = root;
  struct Node *lines;

  while (remaining > 0) {
    chunk_size = count_to_next('\n', pointer, remaining);

    buffer = malloc(chunk_size * sizeof(char) + 1);

    string_copy(pointer, buffer, chunk_size);
    *(buffer + chunk_size) = '\0';

    last->next = malloc(sizeof(struct Node));
    last->next->value = (void *) buffer;
    last->next->next = NULL;
    last = last->next;

    /* + 1 bc the '\n' is ignored */
    remaining -= chunk_size + 1;
    pointer += chunk_size + 1;
  }

  lines = root->next;

  /* do something with lines */
}


texts: A multi-threaded key-value cache that only has thread contention while querying for same key simultaneously

texts:
Maybe the title fails to make myself clear, more explanation to the requirements: Implement a thread-safe key-value cache. User of this cache will use an unique key to query for data. If the data is not found in cache, it should call a data provider to load data and then return it.

The provider could take long time to load and return data, so if more than one user (e.g. user A and User B) are querying by using the same key (e.g. key1) at the same time , user B should be blocked until the data is loaded (by user A's query); but if user B is querying a different key (e.g. key2) and the corresponding data is already in the cache, the data should be returned to user B immediately from the cache , while user A is still waiting for data for key1 being loaded.

Please help to review my implementation below (the code can compile and is testable), I wonder

Is this implementation correct ? Is there a scenario that could break it ?
Are there better solutions? I think we can also use Condition, but don't see there's any fundamental difference ...

Cache.java

import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class Cache <K,V> {
    private static class Wrapper<V> {
        V value;
    }

    private final Function<K,V>  provider;
    private final ConcurrentMap<K,Wrapper<V>> cache;

    public Cache(Function<K, V> provider) {
        if(provider == null) throw new NullPointerException("Need a valid provider!");
        this.provider = provider;
        this.cache = new ConcurrentHashMap<>();
    }

    public V get(K key){
        Wrapper<V> wrapper = cache.get(key);
        if(wrapper ==null){
            //cache miss
            wrapper = new Wrapper();
            Wrapper<V> savedWrapper = cache.putIfAbsent(key, wrapper);
            if(savedWrapper==null) savedWrapper=wrapper;
            synchronized (savedWrapper){
                if(savedWrapper!=wrapper){
                    //if savedWrapper is not the one created by this thread then another thread has already set the data with the same key
                    //in this case the data is ready as long as we get into the critical section (freed by the other thread that just loaded data)
                    //we don't need to do anything, just exit critical section and return the data
                }
                else{
                    //get data from provider and save it, if there is another thread querying the same key now,
                    //it will get blocked until data is set in this thread
                    savedWrapper.value = provider.apply(key);
                }
            }
            return savedWrapper.value;
        }
        else{
            synchronized (wrapper){ //the other thread might be loading data
                return  wrapper.value;
            }
        }
    }
}


texts:
I know Gorilla and others have packages that accomplish this, but I'm trying to learn Go by making stuff. In the router below, the first route / is for all http methods, the second route /hello is only for GET, and the third route hello/:name has one parameter for all HTTP methods.

func main() {
    http.HandleFunc("/", route)
    http.ListenAndServe(":8080", nil)
}

func match(re string, route string) bool {
    match, err := regexp.MatchString(re, route)
    if err != nil {
        return false
    }

    return match
}

func route(w http.ResponseWriter, r *http.Request) {
    route := r.URL.Path
    switch {
    case route == "/":
        home(w, r)
    case route == "/hello" && r.Method == "GET":
        hello(w, r)
    case match("^/hello/([^/]+)$", route) == true:
        var re = regexp.MustCompile("^/hello/([^/]+)$")
        match := re.FindStringSubmatch(route)

        helloName(w, r, match[1])
    default:
        notFound(w, r)
    }
}

// func home, hello, helloName, and notFound

How can I make this more efficient? Is it reliable?


texts: Ensure every element in array passes asynchronous test

texts:
I've written a function which ensures all objects in the items array belong to the user. This involves a database check, which results in the code being asynchronous. This code works, but feels sloppy. I'd appreciate a review and suggestions for how to improve it.

The main challenge I had with writing this was to use items.every() with Promises and I don't think the solution I came up with was very elegant. I spent quite a bit of time on it and couldn't think of a better way to do it.

Intuitively async/await feels like a good fit for this type of problem but I had difficulty applying it here.

function belongTo (user, items) {
  return new Promise(resolve => {
    resolve(items.every((item) => {
      return new Promise((resolve, reject) => {
        Item.findOne({ owner: user,
          assetID: item.assetid,
          appid: item.appid,
          contextid: item.contextid,
          marketHashName: item.marketHashName
        }).then((item) => {
          if (Object.keys(item).length !== 0) resolve(true)
          else resolve(false)
        }).catch(reject)
      })
    }))
  })
}

I'm using the JavaScript Standard style guide.


texts: Code duplication for just an if condition

texts:
I have two methods that are near-perfect duplicates. There is of course a code smell. The only thing that changes is the condition to increment a variable.

Language: Java7

private int pathsDFS(int currentDepth, int maxDepth, Airports s, Airports e, Predicate predicate) {
    int counter = 0;
    if (currentDepth > maxDepth) return counter;
    int newDepth = currentDepth + 1;
    for (Edge x : g.getNeighboursOf(s)) {
        if ( x.getDestination() == e) {
            counter++;
        }
        counter += pathsDFS(newDepth, maxDepth, x.getDestination(), e, predicate);

    }
    return counter;
}

and

private int pathsDFSB(int currentDepth, int maxDepth, Airports s, Airports e) {
    int counter = 0;
    if (currentDepth > maxDepth) return counter;
    int newDepth = currentDepth+1;
    for (Edge x : g.getNeighboursOf(s)) {
        if (x.getDestination() == e && currentDepth == maxDepth) {
            counter++;
        }
        counter += pathsDFSB(newDepth, maxDepth, x.getDestination(), e);
    }
    return counter;
}

What pattern can I apply to remove duplication? I was trying to apply like a Predicate class (calling apply) but that doesn't solve the fact the the values to use are known at runtime inside the for method. Could be considered a strategy pattern the entire for loop?


texts: Finding all words without a certain character

texts:
I am doing some exercises in this book. I've been trying to avoid Regex so far in my mission to teach myself computer science, as it makes my head hurt. That said - one of the exercises is to find all words without the letter 'e'.

I have:

/\b([^e ]+)\b/

There must be a better way using Regex to find all words that don't contain a certain character.

Here is an example:

toMatch = /\b([^e ]+)\b/;
testArr = ["platypus", "elvis", "javascript", "stackoverflow"];

for (str in testArr)
  console.log(testArr[str] + " has no e -> " + toMatch.test(testArr[str]));


texts: Including a file (is this safe and effective?)

texts:
I'm not that experienced with PHP and I'm trying to make it so when I load a page, instead of directly browsing to the file, it will be "included" instead.

I have the code finished and it works.  I just wanted to get an opinion of if it's safe (will people be able to exploit it in anyway?) and if I'm going about this the right way.

<?php
error_reporting(0); // I'm not expecting any errors and don't want users to see any.

    $page = strtolower($_GET['page']); // File names will always be lowercase

    if (isset($page))
    {
        $page .= ".php";
        $page = basename($page); // Prevent users from entering a directory path to access other files.

        if ((file_exists($page)) && ($page != "index.php")) // Check if exists and prevent infinite include loop.
        {
            die(include($page));
        }
    }

    include("base.php");
?>


texts: Rubberduck VBA Parser, Episode V: The ANTLR Strikes Back

texts:
I changed my mind. I don't want to implement 200-some Node classes. Instead, I'll be working directly with the ANTLR generated classes, to implement the Rubberduck code inspections, unit test method discovery, the "Code Explorer" tree view, and everything else Rubberduck might need a parse tree for.

The Node derived classes already implemented aren't wasted though: I'll eventually use them to expose a high-level view of the VBA code, to VBA itself (through COM interop) - that will enable very cool stuff, like VBA code that can enumerate its modules' members.

I changed the VBParser - I renamed ParseInternal to Parse (it becomes an overload of the public Parse method), and made it public as well:

public class VBParser : IRubberduckParser
{
    public INode Parse(string projectName, string componentName, string code)
    {
        var result = Parse(code);
        var walker = new ParseTreeWalker();

        var listener = new VBTreeListener(projectName, componentName);
        walker.Walk(listener, result);

        return listener.Root;
    }

    public IParseTree Parse(string code)
    {
        var input = new AntlrInputStream(code);
        var lexer = new VisualBasic6Lexer(input);
        var tokens = new CommonTokenStream(lexer);
        var parser = new VisualBasic6Parser(tokens);

        return parser.startRule();
    }
}

Now I can have an ANTLR IParseTree wherever I need it. One place I'm going to need it, is to discover test methods in the active VBA project. Rubberduck test methods are always public, parameterless methods, so I wrote this extension method/class:

public static class ParseTreeExtensions
{
    /// <summary>
    /// Finds all public procedures in specified parse tree.
    /// </summary>
    public static IEnumerable<VisualBasic6Parser.SubStmtContext> GetPublicProcedures(this IParseTree parseTree)
    {
        var walker = new ParseTreeWalker();

        var listener = new PublicSubListener();
        walker.Walk(listener, parseTree);

        return listener.Members;
    }

    private class PublicSubListener : VisualBasic6BaseListener
    {
        private readonly IList<VisualBasic6Parser.SubStmtContext> _members = new List<VisualBasic6Parser.SubStmtContext>();
        public IEnumerable<VisualBasic6Parser.SubStmtContext> Members { get { return _members; } }

        public override void EnterSubStmt(VisualBasic6Parser.SubStmtContext context)
        {
            var visibility = context.visibility();
            if (visibility == null || visibility.PUBLIC() != null)
            {
                _members.Add(context);
            }
        }
    }
}

Here's a unit test for it:

    [TestMethod]
    public void GetPublicProceduresReturnsPublicSubs()
    {
        IRubberduckParser parser = new VBParser();
        var code = "Sub Foo()\nEnd Sub\n\nPrivate Sub FooBar()\nEnd Sub\n\nPublic Sub Bar()\nEnd Sub\n\nPublic Sub BarFoo(ByVal fb As Long)\nEnd Sub\n\nFunction GetFoo() As Bar\nEnd Function";

        var module = parser.Parse(code);
        var procedures = module.GetPublicProcedures().ToList();
        var parameterless = procedures.Where(p => p.argList().arg().Count == 0).ToList();

        Assert.AreEqual(3, procedures.Count);
        Assert.AreEqual(2, parameterless.Count);
    }

This works, so I'm going to run with it. I don't want to expose the ANTLR generated classes to COM, so I'm moving it all into its own assembly, which Rubberduck will reference.

It looks to me like VBParser is somewhat mixing abstraction levels... but is that much of an issue? Is it a good idea to "walk" the tree like this? I'm not re-parsing the code, but I'll probably end up walking it multiple times when I run code inspections, and I'll have to implement several [simple] tree listeners, to retrieve the "interesting" nodes. Is this how I'm supposed to be doing this?

Anything else strikes you as weird with this approach?


texts:
I'm designing a generic interface for a MessageEntry class for a .h file.

I'm looking for guidance on form and terminology (would I call this an interface/template/generic class?):

#ifndef cppmq_message_types_h
#define cppmq_message_types_h

template <class T>
struct MessageEntry {
 public:
  MessageEntry<T>() {}
  MessageEntry<T>(T data) : data(data) {
    creation_time =
        std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  }
  time_t CreationTime() { return creation_time; }

 private:
  T data;
  time_t creation_time;
};

#endif`


texts:
I tried to solve the question at https://leetcode.com/problems/roman-to-integer/ i.e Converting an Roman Digit to a Integer  using C#. It passes all the test cases but any suggestions to reduce  run time and memory usage would be appreciated.

    public static int RomanToInt(string s)
    {
        if (s.Length>=2)
        {
            int currentIndex = s.Length - 1,HighestValue=CharacterValue(s[currentIndex]),number=HighestValue;
            currentIndex--;
            while (currentIndex>=0)
            {
                int currentValue = CharacterValue(s[currentIndex]);
                if(currentValue >= HighestValue)
                {
                    number = number + currentValue;
                    HighestValue = currentValue;
                }

                else
                {
                    number = number - currentValue;
                }

                currentIndex--;
            }

            return number;

        }
        else
        {
            return CharacterValue(s[0]);
        }
    }

    public static int CharacterValue(char c)
    {
        switch (c)
        {
            case 'I': return 1;
            break;
            case 'V':
                return 5;
                break;
            case 'X':
                return 10;
                break;
            case 'L':
                return 50;
                break;
            case 'C':
                return 100;
                break;
            case 'D':
                return 500;
                break;
            case 'M':
                return 1000;
                break;
             default:
                 return 0;
             break;
        }

    }

}


texts:
I have a simple class inheritance in JS:

var Class = function(){};

Class.extend = function(){

    var Extended = function(constructor){

        function extend_obj(destination, source) {
            for(var property in source){
                if(typeof source[property] === "object" && source[property] !== null && destination[property]){
                    extend_obj(destination[property], source[property]);
                }else{
                    destination[property] = source[property];
                }
            }
        };

        extend_obj(Extended.prototype, constructor);

        this.constructor.init();
    };

    Extended.init = function(){};

    for(var key in this.prototype){
        Extended.prototype[key] = this.prototype[key];
    }

    Extended.prototype.constructor = Extended;

    for (var key in this) {
        Extended[key] = this[key];
    };

    return Extended;
};

Which allow me to do so:

var SubClass = Class.extend();

SubClass.static_property = "a static property";

SubClass.static_method = function(){
    return "a static method";
};

SubClass.prototype.a_new_property = "something new"; //instance method

var instance = new SubClass({
    name: "custom name"
});

SubClass.init = function(){
    //custom constructor
};

this.constructor.static_method_or_property //call instance method

I need:

multiple inheritance
the possibility to use module pattern

There's a cleaner/better/faster way to do that?


texts: Check if two strings are permutations of one another

texts:
I am working my way through "Cracking the coding interview" problems and have finished implementing this question: "Given, two strings, write a method to decide if one is a permutation of the other". Can anyone give me any feedback on my implementation in regards of efficiency or improvements?

public static boolean containsPremutation(String firstString, String secondString){

    //Checking if either string is empty.
    if(firstString.isEmpty() || secondString.isEmpty())
        return false;

    //Checking if one string is larger than the other.
    if(firstString.length() > secondString.length() || secondString.length() > firstString.length())
        return false;

    //First convert the Strings into char[]
    char [] charFirstString =  firstString.toCharArray();
    char [] charSecondString = secondString.toCharArray();

    //Secondly, aplhabetize/sort the char arrays
    Arrays.sort(charFirstString);
    Arrays.sort(charSecondString);

    //Thirdly, create new Strings out of the sorted char arrays
    String alphaFirstString = new String(charFirstString);
    String alphaSecondString  = new String(charSecondString);

    //Now you can begin comparing each char in the Strings.
    // Begin iterating at the same char and if they are not the same char return false
    //otherwise continue iterating.
    for (int i = 0; i < alphaFirstString.length(); i++){
        if(alphaFirstString.charAt(i) != alphaSecondString.charAt(i))
            return false;
    }
    return true;


texts:
I'm a Go (and programming in general) newbie and the task was to program a Go server that would accept incoming messages, take each line, reverse its order and case and send it back. Besides doing that I also wrote a client (just for the hell of it and to help me test my server). I wonder if some things could've been done better and just want feedback on my code.

I'm particularly interested in proper usage of those break statements I used to forcefully finish Scan() loops and if I really have to send end of line symbols from my client as a hardcoded measure (rather than use some other function that automatically adds end of line symbols when reading input).

Server:

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func swapCase(s string) string {
    return strings.Map(func(r rune) rune {
        switch {
        case unicode.IsLower(r):
            return unicode.ToUpper(r)
        case unicode.IsUpper(r):
            return unicode.ToLower(r)
        }
        return r
    }, s)
}

func handleServerConnection(c net.Conn, i int) {
    for {
        // scan message
        scanner := bufio.NewScanner(c)
        for scanner.Scan() {
            msg := scanner.Text()
            log.Printf("Client %v sends: %v", i, msg)
            msgNew := swapCase(reverse((msg)))
            c.Write([]byte(msgNew + "\n"))
            log.Printf("Client %v receives: %v", i, msgNew)
            fmt.Println("---")
        }
        if errRead := scanner.Err(); errRead != nil {
            log.Printf("Client %v disconnected...", i)
            fmt.Println("---")
            return
        }
    }
}

func main() {
    log.Println("Server launched...")
    // listen on all interfaces
    ln, _ := net.Listen("tcp", ":9999")
    i := 0
    for {
        // accept connection on port
        c, _ := ln.Accept()
        i++
        log.Printf("Client %v connected...", i)
        fmt.Println("---")
        // handle the connection
        go handleServerConnection(c, i)
    }
}

Client:

func main() {
    i := 0 // connection index
    // connect to server
    for {
    connect:
        c, errConn := net.Dial("tcp", "127.0.0.1:9999")
        if errConn != nil {
            continue
        } else {
            i++
            if i <= 1 {
                log.Println("Connected to server...")
                fmt.Println("---")
            } else {
                log.Println("Reconnected to server...")
                fmt.Println("---")
            }
        }
        for {
            // read in input from stdin
            scannerStdin := bufio.NewScanner(os.Stdin)
            fmt.Print("Server message: ")
            for scannerStdin.Scan() {
                text := scannerStdin.Text()
                fmt.Println("---")
                // send to server
                _, errWrite := fmt.Fprintf(c, text+"\n")
                if errWrite != nil {
                    log.Println("Server offline, attempting to reconnect...")
                    goto connect
                }
                log.Print("Server receives: " + text)
                break
            }
            // listen for reply
            scannerConn := bufio.NewScanner(c)
            for scannerConn.Scan() {
                log.Println("Server sends: " + scannerConn.Text())
                break
            }
            if errReadConn := scannerStdin.Err(); errReadConn != nil {
                log.Printf("Read error: %T %+v", errReadConn, errReadConn)
                return
            }
            fmt.Println("---")
        }
    }
}


texts: Compute histrogram bins for a large data.frame fast

texts:
I know about apply, but I'm not sure how to write it so that it works for embedded for loops with if statements and so forth. It gets messy. I am a novice so if you can show me how to properly rewrite the following efficiently it should help a lot.

This is an example of what the dataframe inFile() should look like. In the code below I subset on the dataframe so that rows are between two dates, abs_start and abs_end (you'll notice the CSV has a dates column). I then am trying bin the rows into bins that are input$binning seconds long. I simply iterate through all the dates and for each date I iterate through all the bins until I find the one that a particular row belongs to. Then I add this bin's number to a list. After doing this for all rows in the dataframe I add the list as a new column to the data.frame as it now specifies which bin each row belongs to.

This is slow though. The user specifies the bin length and then I want the histrogram to automatically update (using R Shiny framework). How can I speed it up?

  # Subset between start and end with bin column and selected mice
  subsetTable<-reactive({
    subsetMice<-inFile()[inFile()[,TAG_COL]%in%input$tagChooser,]

    abs_start <- strptime(input$abs_start,"%Y-%m-%d %H:%M:%S",tz='US/Pacific')
    abs_end <- strptime(input$abs_end,"%Y-%m-%d %H:%M:%S",tz='US/Pacific')

    if(is.null(subsetMice)||nrow(subsetMice)<=0){
      return()
    }

    # subset between abs_start and abs_end
    convertedDates<-strptime(as.character(subsetMice[,DATE_COL]),"%Y-%m-%d %H:%M:%S",tz='US/Pacific')
    inF<-subsetMice[convertedDates>abs_start&convertedDates<abs_end,]
    convertedDates<-convertedDates[convertedDates>abs_start&convertedDates<abs_end]

    bins<-seq(abs_start,abs_end,by=as.integer(input$binning))
    bin_no<-length(bins)

    bin_nos<-c(NULL)
    bin_starts<-c(NULL)
    for(i in 1:length(convertedDates)){
     for(j in 1:length(bins)){
        # Check if at right bin
        if(!is.na(bins[j+1])){
          if(bins[j]<=convertedDates[i]&&convertedDates[i]<bins[j+1]){
            bin_nos[i] <- j
            bin_starts[i] <- bins[j]
            break
          }
        }
       else{
         stopifnot(bins[j]<=convertedDates[i])
         bin_nos[i] <- j
         bin_starts[i] <- bins[j]
       }
      }
    }
    cbind(inF,bin_starts,bin_nos)
    })


texts: nTier architecture for an MVC application

texts:
I am endeavoring to build my first non-trivial web application and so I'd like to confirm a couple of design decisions.

I have three tiers as follows:

UI (my MVC project)
Business Logic (separate project)
Data Access Logic (a simple .dbml that is part of project #2)

Is this a reasonable approach to separating concerns? Should my DAL consist of more than just my Linq .dbml file?

To play this out, lets say I have an Orders table and a Shipments table in my database.  Furthermore lets say that I want to pass a list of orders and shipments through to a page in the UI.  Here's how I'm envisioning that would work.

OrdersBLL.cs

Public IEneumerable<Order> GetAllOrders()
{
DataContext db = new DataContext();
 return db.Orders;

}

ShipmentsBLL.cs

Public IEneumerable<Shipment> GetAllShipments()
{
DataContext db = new DataContext();
return db.Shipments;
}

ViewModels.cs

public class ShowAll
{
    public IQueryable<Order> order { get; set; }
    public IQueryable<Shipment> shipment { get; set; }
}

Then when I create the view in the MVC app to display all orders and shipments I would simply pass in a ShowAll object from the ViewModel.

Over all I think this approach separates concerns reasonably well.  However, I'd be interested in learning if others have a better approach.  One concern I have is that my approach requires instantiating Order and Shipment objects in the View Model.  However, these come from classes that are defined in my data layer.  This strikes me as a bad idea given that I read somewhere that only the BLL should talk to the DAL.  Is this correct?


texts: Duplicating Excel-workbook, and transferring data

texts:
This is a follow up to the simpler question here.

I have hundreds of files looking something like this:

These files have names such as:

2301 Item 1.xlsx
2014 Item 2.xlsx
5321 Item 3.xlsx
3212 Item 200.xlsx

I also have a template file (Template.xlsx) looking like this:

I want to:

Copy the template file, and for each of the other files

Give it the filename in cell C6.
Copy the values of B2,B3,B3 over to the appropriate spot in the template (B4,B5,B6).
Copy the filename to B8

I've written the following script in Python 3:

import os
import shutil

from xlrd import open_workbook
from xlutils.copy import copy

def duplicate_and_transfer(path):

    for filename in os.listdir(path):
        if filename == 'Template.xlsx':
            continue
        else:
            filepath = os.path.join(path, filename)
            excel_file = open_workbook(filepath)
            worksheet = excel_file.sheet_by_index(0)
            new_filename = worksheet.cell_value(5,2)
            new_filepath = os.path.join(path, new_filename + '.xls')
            r_value = [0,0,0]
            for row in range(3):
                r_value[row] = worksheet.cell_value(row+1,1)

            shutil.copy2(os.path.join(path, 'Template.xlsx'),new_filepath)
            rb = open_workbook(new_filepath)
            wb = copy(rb)
            s = wb.get_sheet(0)
            s.write(7,2,new_filename)
            for r in range(3):
                s.write(r+3,1,r_value[r])

            wb.save(new_filepath)

if __name__ == '__main__':
    duplicate_and_transfer(r'C:\Users\Stewie\Documents\excel_folder')

A few things:

I have to make the new files xls instead of xlsx. They get corrupted if not (someone else have had this problem). Can I avoid this?
Should I split this up into more functions?

This is fast enough, so my main issue is not with performance.


texts: A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++

texts:
This is the follow-up question for A Summation Function For Arbitrary Nested Vector Implementation in C++. The following code is the improved version based on Zeta's answer. I am trying to enhance this the sum function which can deal with iterable things which has begin() and end() (such as std::array) of various types (such as int, char or unsigned int) number. I am not familiar with the usage of std::enable_if and std::is_arithmetic for checking type constraint in template. If there is any possible improvement, please let me know.
template<class Container, typename = typename Container::value_type>
inline long double Sum(const Container& numbers)
{
    long double sumResult = 0.0;
    for (auto& element : numbers)
    {
        sumResult += Sum(element);
    }
    return sumResult;
}

template<class T,
    std::enable_if_t<std::is_arithmetic<T>::value, int> = 0,
    std::enable_if_t<std::is_arithmetic<T>::value, double> = 0>
T Sum(T inputNumber)
{
    return inputNumber;
}

Some tests for this sum function:
int testNumber = 1;

std::vector<decltype(testNumber)> testVector1;
testVector1.push_back(testNumber);
testVector1.push_back(testNumber);
testVector1.push_back(testNumber);
std::cout << std::to_string(Sum(testVector1)) + "\n";

std::vector<decltype(testVector1)> testVector2;
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
std::cout << std::to_string(Sum(testVector2)) + "\n";

std::vector<decltype(testVector2)> testVector3;
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
std::cout << std::to_string(Sum(testVector3)) + "\n";

//  std::array test case
std::array<long double, 90> numberArray;
for (size_t i = 0; i < 90; i++)
{
    numberArray[i] = 1;
}
std::cout << std::to_string(Sum(numberArray)) + "\n";

The summary information:

Which question it is a follow-up to?
A Summation Function For Arbitrary Nested Vector Implementation in C++

What changes has been made in the code since last question?

The previous question focus on single type long double and the goal in this question is trying to deal with various type number.

The previous question focus on std::vector and the other iterable things which has begin() and end() are considered here.

The variable name has been modified in order to make better understanding.

Why a new review is being asked for?
Is it a good idea to set the type constraint like std::enable_if_t<std::is_arithmetic<T>::value, int> = 0, std::enable_if_t<std::is_arithmetic<T>::value, double> = 0>?

Oct 18, 2020 Update

The further implementation with c++-concepts:
https://stackoverflow.com/q/64414869/6667035


texts:
My goal is to make web page loading faster by bundling all the CSS files together. The web browser will then only have to load only CSS files. This will only run when the application is starting.

void function setupApplication() {
  application.initialized           = now();

...

var renderCSSFile = application.GWASSETS & "combo.css";
if (FileExists(renderCSSFile)) FileDelete(renderCSSFile);

var renderCSS = "";
for (var myCSS in ListToArray("
    bootstrap, bootstrap-theme, bootstrap-jasny, font-awesome.min,
    datepicker,daterangepicker-bs3,
    datatables.bootstrap, datatables.colvis, datatables.fixedcolumns,
    select2, select2-bootstrap,
    main, scorecard"))  {

    if(FileExists(application.GWASSETS & trim(myCSS) & ".css")) {
        renderCSS &= FileRead(application.GWASSETS & trim(myCSS) & ".css");
        }
    }
FileWrite(renderCSSFile, renderCSS);

...

}

Is this the cleanest way to do this?


texts: Documentation for a Minecraft server plugin

texts:
I'm working on a minecraft plugin for my Spigot Minecraft server.

I have a class which works as expected. I've done my best to hammer every single bug out (famous last words, I know) and am now taking a look at the way it's written. I've noticed that documentation definitely is not lacking, and looks over documented, to the point where it becomes unhelpful. My code is as follows:

package <redacted>;

import java.util.List;
import java.util.Random;

import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;

import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import org.inventivetalent.bossbar.BossBar;
import org.inventivetalent.bossbar.BossBarAPI;

/**
 *
 * @author Spotlight
 */
public class BossBarUpdate extends BukkitRunnable {

    private Player p;

    /**
     * Set global variables.
     *
     * @param p Player
     */
    public BossBarUpdate(Player p) {
        this.p = p;
    }

    @Override
    public void run() {
        // Cancel task if player logged off or crashed
        if (p == null || !p.isOnline()) {
            p = null;
            cancel();
            return;
        }
        if (!Main.SHOW_BAR) {
            // Do nothing, as AttentionManager or another class has taken over.
            return;
        }
        // Get list of possible messages
        List<String> messages = Main.barConfig.getStringList("messages");
        // Create color instance
        BossBarAPI.Color barColor;
        // Get current (first) boss bar
        BossBar firstBossBar = BossBarAPI.getBossBars(p).iterator().next();
        // Create possible string instance
        String possibleMessage;
        // Make current message a String
        BaseComponent[] components = ComponentSerializer.parse(firstBossBar.getMessage());
        String currentMessage = new TextComponent(components).toLegacyText();
        // Choose a random color + message
        do {
            // Get random color
            barColor = new Utils(null).randomEnum(BossBarAPI.Color.class);
            // Get random number between message size
            int index = new Random().nextInt(messages.size());
            // Get random message at random number index
            possibleMessage = messages.get(index);
        } while (!firstBossBar.getColor().equals(barColor) & currentMessage.equals(possibleMessage));

        TextComponent message = new TextComponent(TextComponent.fromLegacyText(possibleMessage));
        // Temporarily reset bars
        BossBarAPI.removeAllBars(p);
        // Choose a random color
        BossBarAPI.addBar(p, // The receiver of the BossBar
                message, // Displayed message
                barColor, // Color of the bar
                BossBarAPI.Style.PROGRESS, // Bar style
                1.0F); // Fullness
    }
}

I'm looking to increase the helpfulness of this code's documentation, so that it's not as verbose, but you can still tell what's going on. All comments are welcome, even if they aren't related to documentation.


texts: Simplifying minimum search of two dimensional vector with complex struct

texts:
Is there a way to simplify this function? I tried to use the std::min_element function inside the lambda, but i don't get it to work with *var.

const auto miniFunc = [](const std::vector<std::vector<KEntryContact>> & entryContact, double KEntryContact::*var) -> double
{
    double min = DBL_MAX;
    for (const std::vector<KEntryContact> &entryvec : entryContact) {
        for (const KEntryContact &entry : entryvec) {
            min = std::min(min, entry.*var);
        }
    }

    return min;
};

The function can then be used like this:

double rAMin = miniFunc(tPOC->getEntryContact(), &KEntryContact::r1);


texts:
I am just sharing the method that i am using to convert stacktrace to string. This stacktrace is then being used in AWS Lambda to log. There are two things i am mainly concerned about

private String convertStackTrace(Throwable throwable){
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    String stackTrace;

    try {
        throwable.printStackTrace(printWriter);
        stackTrace = stringWriter.toString();
    }
    catch(Exception e){
        logSelf("Error converting exception. Simple exception message will be logged");
        stackTrace = throwable.getMessage();
    } finally {
        try {
            stringWriter.flush();
            stringWriter.close();
            printWriter.flush();
            printWriter.close();
        } catch (Exception e){
            logSelf("Error closing writers");
        }
    }

    return stackTrace;
}

Here is logSelf method

private void logSelf(String error){
    lambdaLogger.log(formatMessage(
            this.getClass().getCanonicalName(), LOG_LEVEL_ERROR, error, null)
    );
}

Shall i be opening/closing those printwriters everytime an error is logged?
Is it correct way to convert stacktrace to string?


texts:
Original problem:
Given \$x\$ number of tests that should run in \$y\$ number of seconds shift the time per test so that each test takes a little longer than the next.
Example: If running 10 tests over 10 seconds, the equal time per test would be 1 second each.
Instead, have the first test take .5 seconds and the last test take 1.5 seconds while each subsequent test take a progressively longer duration.  We shift the time per test around while still maintaining the original duration of 10 seconds for the 10 tests.
I am slightly ignorant of what math principles are occurring.  I knew how I wanted to solve the problem but I can't describe the problem. I've made it possible to adjust how much shifting can be done.  Since the array of times is linear (and we can't really have negative times) I put a limit on that 'shifting' value.

How do you describe this function / math problem?  (which would hopefully result in a better name for it).
What should the pct variable be called?  I originally thought it to be a percentage of each second, but as I developed the function I realized this was inaccurate; since after the first value, the percentage of shifting per time slice goes down then back up again.

def duration_spread(tests: float, seconds: float, pct: float = .75):
    assert -1 <= pct <= 1, "pct must be within +/-100% otherwise it will push times into negative"
    pct *= 2
    original_velocity = seconds/tests
    seconds_per_tests = original_velocity  # couldn't decide on naming convention
    average_velocity = original_velocity
    diff_average_velocity = pct * average_velocity
    acceleration = diff_average_velocity/tests

    multiplier_list = get_multipliers(tests)
    results = []
    for i, multiplier in enumerate(multiplier_list):
        newadjustment = (multiplier * acceleration)
        newtime = original_velocity + newadjustment
        print(f"{original_velocity} -> {newtime} :: {abs(newadjustment)}")
        results.append(newtime)

    return results

def get_multipliers(tests: float):
    odd = int(tests % 2)
    half_tests = int(tests // 2)
    result = list(range(-half_tests, half_tests+1))
    if not odd:
        result.pop(half_tests)
    return result


texts: Find if items in a list of list matches to another list

texts:
We have two lists:

l=["a","b","c"]
s=[["a","b","c"],
["a","d","c"],
["a-B1","b","c"],
["a","e","c"],
["a_2","c"],
["a","d-2"],
["a-3","b","c-1-1","d"]]
print l
print s

Now, I am try to see if each 2nd-level list of s has fuzzy match to any of items in list l:

matches=list()
matchlist2=list()
print s2
for i in range(len(s)):
    matches.append([])
    for j in range(len(s[i])):

        for x in l:
            if s[i][j].find(x)>=0:
                print s[i][j]
                matches[i].append(True)

                break
        else:
            matches[i].append(False)

    matchlist2.append(all(x for x in matches[i]))
print matches
print matchlist2

This gives me what was intended. But I am not happy with how it has so many loops. I am also working with pandas and if there is pandas solution that will be great to. In pandas, there are just two columns of two dataframes.

[[True, True, True], [True, False, True], [True, True, True], [True, False, True], [True, True], [True, False], [True, True, True, False]]

[True, False, True, False, True, False, False]