texts:
For my computer science class, I was required to write a lexical analysis program that would perform several functions on a std::string. The assignment required a function for each of the following:

count number of a certain substring
count number of words excluding numbers
count number of unique words (excludes repeated words)
count number of sentences (by end punctuation)
average words per sentence
lexical density as percent (unique word count / word count * 100)

My code is fairly long, but here it is:

#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
#include<iterator>
#include<vector>

using namespace std;

int substringCount(const string&, const string&);
int wordCount(const string&);
int uniqueWordCount(const string&);
int sentenceCount(const string&);
double wordsPerSentence(const string&);
double lexicalDensity(const string&); // different words / total words * 100

int main() {
    string source = ("This is the source text for this program.");
    cout << "\"is\" count: " << substringCount(source," is ") << endl;
    cout << "Word count: " << wordCount(source) << endl;
    cout << "Sentence count: " << sentenceCount(source) << endl;
    cout << "Words per sentence: " << wordsPerSentence(source) << endl;
    cout << "Lexical density: " << lexicalDensity(source) << endl;
    return 0;
}

vector<int> substringIndices(const string& str, const string& sub) { // Find indices of substrings
    vector<int> indices = {};
    for (unsigned int i = 0; i < str.size(); i++) {
        unsigned int t = i;
        for (unsigned int j = 0; j < sub.size(); t++, j++) {
            if (t >= str.size()) {
                break;
            }
            if (str[t] == sub[j]) {
                if (j + 1 == sub.size()) indices.push_back(i);
                continue;
            } else {
                break;
            }
        }
    }
    return indices;
}

vector<string> splitByWhitespace(const string& str) { // split by whitespace
    vector<string> tokens;
    istringstream iss(str); // create istringstream
    copy(istream_iterator<string>(iss),istream_iterator<string>(),back_inserter(tokens)); // copy into tokens
    return tokens;
}

vector<string> deleteNumbers(const vector<string>& data) {
    vector<string> tr = {};
    for (unsigned int i = 0; i < data.size(); i++) {
        for (char c: data[i]) {
            if (string("0123456789").find(c) == -1) continue;
            else goto mainLoop;
        }
        tr.push_back(data[i]);
        mainLoop: continue;
    }
    return tr;
}

int substringCount(const string& str, const string& sub) { // get number of substrings
    return substringIndices(str,sub).size();
}

int wordCount(const string& str) { // wordcount (based on whitespace)
    return deleteNumbers(splitByWhitespace(str)).size();
}

int uniqueWordCount(const string& str) { // unique word count
    vector<string> words = deleteNumbers(splitByWhitespace(str));
    sort(words.begin(),words.end()); // sort
    words.erase(unique(words.begin(),words.end()),words.end()); // delete extra non-unique words
    return words.size();
}

int sentenceCount(const string& str) { // get number of sentences (based on end punctuation)
    return substringCount(str,".") + substringCount(str,"?") + substringCount(str,"!");
}

double wordsPerSentence(const string& str) {
    return double(wordCount(str)) / double(sentenceCount(str));
}

double lexicalDensity(const string& str) {
    return double(uniqueWordCount(str) * 100) / double(wordCount(str));
}

I am relatively new to C++, so if there are any common practices that I am missing it would be great to point them out.


texts: Triggering the execution of a job at the end of a timed campaign

texts:
I have a task that checks for campaigns that are supposed to be finished by checking the end_at date. If finished, then set the status of the campaign to finished, and send the owner of the campaign an email.

The way I see it, is approach 1 and 2 may have the worker queued more than once in the worker pool.

Approach 3, always makes sure that there is only one instance running at a time.
Approach 3 also means making sure the worker is run once on every deploy.

I have 3 scenarios to consider implementing this:

APPROACH #1 - Run the cron job. Cron job determines which campaigns the worker should process

# CRON via whenever gem that runs every 3 minutes
campaigns = Campaign.where("properties -> 'end_at' <= ? AND status = ?", Time.now.utc, 'running')

campaigns.each do |campaign|
  FinishCampaignWorker.perform_async(campaign.id)
end

# FinishCampaignWorker class
class FinishCampaignWorker
  include Sidekiq::Worker

  sidekiq_options({
    retry: false,
    backtrace: true
  })

  def perform(campaign_id)
    begin
      campaign = Campaign.unscoped.find(campaign_id)

      # Do not update campaign if deleted or deactivated
      if campaign.present? && !%w(deleted deactivated).include?(campaign.status)
        campaign.status = 'finished'

        UserMailer.post_campaign_notification(campaign.id, campaign.user.id).deliver

        campaign.save
      end
    rescue
      Airbrake.notify(
        error_class:      'Finish campaign worker',
        error_message:    "#{$!}",
        environment_name: Rails.env
      )
    end
  end
end

APPROACH #2 - Cron triggers the worker to run every 3 minutes. Let the worker handle most of the logic

# CRON via whenever gem that runs every 3 minutes
FinishCampaignWorker.perform_async

# FinishCampaignWorker class
class FinishCampaignWorker
  include Sidekiq::Worker

  sidekiq_options({
    retry: false,
    backtrace: true
  })

  def perform
    begin
      campaigns = Campaign.where("properties -> 'end_at' <= ? AND status = ?", Time.now.utc, 'running')

      campaigns.each do |campaign|
        campaign = Campaign.unscoped.find(campaign_id)

        # Do not update campaign if deleted or deactivated
        if !%w(deleted deactivated).include?(campaign.status)
          campaign.status = 'finished'

          UserMailer.post_campaign_notification(campaign.id, campaign.user.id).deliver

          campaign.save
        end
      end
    rescue
      Airbrake.notify(
        error_class:      'Finish campaign worker',
        error_message:    "#{$!}",
        environment_name: Rails.env
      )
    end
  end
end

APPROACH #3 - Run the worker from console/chef/other on first deployment, let the worker handle most of the logic, and then reschedule the worker 3 minutes after completion

# FinishCampaignWorker class
class FinishCampaignWorker
  include Sidekiq::Worker

  sidekiq_options({
    retry: false,
    backtrace: true
  })

  def perform
    begin
      campaigns = Campaign.where("properties -> 'end_at' <= ? AND status = ?", Time.now.utc, 'running')

      campaigns.each do |campaign|
        campaign = Campaign.unscoped.find(campaign_id)

        # Do not update campaign if deleted or deactivated
        if !%w(deleted deactivated).include?(campaign.status)
          campaign.status = 'finished'

          UserMailer.post_campaign_notification(campaign.id, campaign.user.id).deliver

          campaign.save
        end
      end
    rescue
      Airbrake.notify(
        error_class:      'Finish campaign worker',
        error_message:    "#{$!}",
        environment_name: Rails.env
      )
    end

    FinishCampaignWorker.perform_at(3.minutes.from_now)
  end
end


texts: Solution to knapsack problem exceeds time and RAM limits

texts:
My goal is to code the knapsack problem algorithm. The problem is that a knapsack has a given weight limit, W. I have a collection of items which have a given weight and value in a file that looks like:

# test.txt
1234  4456
4321  7654
...   ...

Where value is the first column, and weight is the second. My algorithm seeks to maximize the value of items in the knapsack while staying at or beneath the weight limit W. This is what I've come up with so far:

import numpy as np
#reading the data:
values = []
weights = []
test = []
with open("test.txt") as file:
  for line in file:
    value, weight = line.split(" ")
    values.append(int(value))
    weights.append(int(weight.replace("\n","")))

W = values.pop(0)
weights
size = weights.pop(0) +1
weights = [0] + weights
values = [0] + values

#Knapsack Algorithm:

hash_table = {}
for x in range(0,W +1):
  hash_table[(0,x)] = 0

for i in range(1,size):
  for x in range(0,W +1):
    if weights[i] > x:
      hash_table[(i,x)] = hash_table[i - 1,x]
    else:
      hash_table[(i,x)] = max(hash_table[i - 1,x],hash_table[i - 1,x - weights[i]] + values[i])

My idea is to use a "hash table" as a part of a dynamic programming technique in order to speed up my code. But I have tried to run it on a big input file and I am out of RAM (and it works very slowly).

Can you review my code and give me some hints how can I speed up my program?


texts:
I am new to oriented object paradigm and I work on Android using Java project for an internship.
I must be able to locate the user and some around buildings I read stuff about how to setup LocationListener and all, and decided that I better write a class that manage everything for me.

public class NetCampusLocation {
    private Activity activity;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private Location freshLocation;

    public NetCampusLocation(Activity activity) {
        this.activity = activity;
        this.locationManager = (LocationManager) this.activity.getSystemService(Context.LOCATION_SERVICE);
        this.locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };
        this.freshLocation = this.locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (this.freshLocation == null) {
            this.freshLocation = this.locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
    }

    public void setLocationUpdate(String provider, int minTimeInterval, int minDistance, LocationListener listener) {
        this.locationManager.requestLocationUpdates(provider, minTimeInterval, minDistance, listener);
    }

    public void stopLocationUpdate() {
        this.locationManager.removeUpdates(this.locationListener);
    }
}

That is the first time I am writing a class on my own (without any pedagogic goal) and I ever seen an example with an interface nested to a class, I am wondering if this is even logical or totally absurd.

I am also wondering if this a good practice to pass my activity to the constructor or the class or not.

All kind of advices would be really good.


texts: AngularJS: Http API Service - any improvements / remarks?

texts:
Could you please review the below AngularJS service. What it does is centralize all (relevant) HTTP action calls.

Do you see any chances for improvement?:

"use strict";

angular.module("services.api")
    .factory("apiService", [
        "$http",
        "$q",
        "coreUtilityService",
        "constantsServiceNames",
        "constantsApiRequestFor",
        function (
            $http,
            $q,
            coreUtilityService,
            constantsServiceNames,
            constantsApiRequestFor
            ) {
            // === START SERVICE === //

            var self = {};

            self.Name = constantsServiceNames.ApiService;

            self.ExecuteRequest = function(verb, fullUri, data) {
                var defer = $q.defer();
                verb = verb.toLowerCase();

                //start with the uri
                var httpArgs = [fullUri];
                if (verb.match(/post|put/)) {
                    httpArgs.push(data);
                }

                $http[verb].apply(null, httpArgs)
                .success(function (response) {
                    defer.resolve(response);
                })
                .error(function (response, status) {
                    defer.reject("HTTP Error: " + status);
                });

                return defer.promise;
            }

            /*
            Do a request to any RESTful receiver. Meant for external use only, use DoViewRequest
            for internal requests.
            */
            self.DoRequest = function (verb, uri, data) {
                var fullUrl = coreUtilityService.GetBaseUrl(constantsApiRequestFor.WebAPI, uri);

                return self.ExecuteRequest(verb, fullUrl, data);
            };

            /*
            This will target an MVC View of the client application. The url will be different.
            */
            self.DoViewRequest = function (verb, uri) {
                var fullUrl = coreUtilityService.GetBaseUrl(constantsApiRequestFor.View, uri);

                return self.ExecuteRequest(verb, fullUrl, null);
            };

            // === PUBLIC === //

            return {
                Get: function (uri) {
                    return self.DoRequest("get", uri);
                },
                Post: function (uri, data) {
                    return self.DoRequest("post", uri, data);
                },
                Put: function (uri, data) {
                    return self.DoRequest("put", uri, data);
                },
                Delete: function (uri) {
                    return self.DoRequest("delete", uri);
                },
                View: function (uri) {
                    return self.DoViewRequest("get", uri);
                }
            }

            // === END SERVICE === //
        }]);


texts:
I plan to use this menu struct in an RPG played in the terminal.  I want to make a RPG similar to D&D. I would like advice on my methods for the menu struct, especially the "hide" and "unhide" option methods.

main.cpp

#include <string>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <initializer_list>

const int invalid_index = -2;
const int default_index = -1;
const std::string defualt_title = "";
const std::initializer_list<std::string> defualt_options = {""};

struct menu{
    menu(const std::string& title, const std::initializer_list<std::string>& options)
        : title(title), options(options), current_index(default_index){;};
    menu(void)
        : title(defualt_title), options(defualt_options), current_index(default_index){;};

    std::vector<std::string> hidden_options;
    std::vector<std::string> options;
    std::string title;
    int current_index;

    void insert_option(int index, std::string option){
        if(index >= 0 && index < options.size()){
            options.insert(options.begin() + index, option);
        }else{;}
    };

    void delete_option(int index){
        if(index >= 0 && index < options.size()){
            options.erase(options.begin() + index);
        }else{;}
    };

    void obtain_option(int index){
        if(index >= 0 && index < options.size()){
            current_index = index;
        }else{current_index = invalid_index;}
    };

    void hide_option(int index){
        if(index >= 0 && index < options.size()){
            hidden_options.resize(options.size());
            hidden_options[index] = options[index];
            options.erase(options.begin() + index);
        }else{;}
    };

    void unhide_option(int index){
        if(hidden_options[index] != ""){
            if(index >= 0 && index < options.size()){
                options.insert(options.begin() + index, hidden_options[index]);
            }else{;}
        }else{;}
    };

    friend std::ostream& operator<<(std::ostream& ostream, const menu& r){
        ostream << r.title << '\n';
        for(int i = 0; i < r.options.size(); i++){
            ostream << "[" << i << "] " << r.options[i] << '\n';
        }ostream << "Enter index: ";
        return ostream;
    };
};

int main(){
    menu title_screen("Anyone Know a good RPG?", {"Play","Help","Quit"});
    return 0;
}


texts: Checking a DB table before doing an insert using AWS Lambda

texts:
Pretty new to AWS Lambda and Javascript, and particularly Promises.

Simple check db table before insert.

It all seems to be working - I'm just wondering if there was a neater way of doing any of this that I'm not aware of.

import AWS from 'aws-sdk';
const dynamo = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1'})

export function main(event, context, callback) {

  dynamo.get({ TableName: 'client', Key: { id: event.name } })
    .promise()
    .then(function(data) {

      if(data.Item){
        callback(null, `Client name '${event.name}' is already in use.`)
        return
      }

      const timestamp = new Date().getTime()

      dynamo.put({
        TableName: 'client',
        Item: {
          id: event.name,
          created: timestamp,
          updated: timestamp,
          deleted: null
        },
        ConditionExpression: 'attribute_not_exists(id)'
      })
      .promise()
      .then(function(data) {
        callback(null, event)
      }).catch(function(err) {
        callback(err)
      })

  }).catch(function(err) {
     callback(err)
  })

}


texts: Writing to rotating log file via channels

texts:
I'm an experienced programmer (mostly C#, JavaScript, PHP). Go is quite a paradigm shift and I want to make sure I'm starting on the right foot.

This is my first Golang package. It's purpose is to be initiated and sent log lines (in the form of map[string]string to AddEntry. It's using channels since the lines could be added VERY frequently and I don't want to consume I/O time on the receiving function (outside of this package).

Any ways this could better follow Go's practices I am definitely interested to hear.

Usage Example:

testLog := chatlog.NewChatLog("/opt/test/logs/", "IRC", "SomeServerName", 1000)
testEntry := make(map[string]string)
testEntry["Type"] = "PRIVMSG"
testEntry["Entity"] = "SomeUser"
testEntry["Content"] = "This is the message!"
testLog.AddEntry(testEntry)

The Package:

// Package chatlog provides a structure way of storing chatlogs for consumption by CelestialStats.
package chatlog

import (
    "encoding/json"
    "fmt"
    "log"
    "os"
    "path"
    "strconv"
    "time"
)

type ChatLog struct {
    Protocol   string
    Server     string
    logDir     string
    logFile    *os.File
    logChannel chan map[string]string
}

// NewChatLog returns a new ChatLog ready to recieve log entries and write them to disk.
func NewChatLog(LogDir, Protocol, Server string, MaxQueue int) *ChatLog {
    cl := new(ChatLog)
    cl.logDir = LogDir
    cl.Protocol = Protocol
    cl.Server = Server
    cl.logChannel = make(chan map[string]string, MaxQueue)
    go cl.Write()
    return cl
}

// Open opens a specific structured file for later writing.
func (chatLog *ChatLog) Open() {
    var logFilename = chatLog.GenerateFilename()
    var parentDir = path.Dir(logFilename)
    if _, err := os.Stat(parentDir); os.IsNotExist(err) {
        os.MkdirAll(parentDir, 0755)
    }
    f, err := os.OpenFile(logFilename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
    if err != nil {
        log.Println("Error opening file:", logFilename)
    }
    chatLog.logFile = f
}

// AddEntry adds a map representing the chat message to the log channel. It
// also appends the current Unix Timestamp in milliseconds to the map.
func (chatLog *ChatLog) AddEntry(newEntry map[string]string) {
    newEntry["Timestamp"] = strconv.FormatInt(time.Now().UTC().UnixNano()/int64(time.Millisecond), 36)
    chatLog.logChannel <- newEntry
}

// Write outputs any additions to the log channel to the current log file.
// If the log does not exist or is old this triggers the log to be opened
// or rotated. All entries are converted to JSON and stored on object per.
// line.
func (chatLog *ChatLog) Write() {
    for i := range chatLog.logChannel {
        chatLog.RotateIfNeeded()
        jsonVal, _ := json.Marshal(i)
        _, err := chatLog.logFile.WriteString(string(jsonVal) + "\n")
        if err != nil {
            log.Println("Error writing to file:", err)
        }
        chatLog.logFile.Sync()
    }
}

// RotateIfNeeded checks if the current ChatLog struct is referencing the
// proper log file. If the reference is incorrect or doesn't exist then this
// function opens the proper log, and if necessary closes the old one.
func (chatLog *ChatLog) RotateIfNeeded() {
    if chatLog.logFile == nil {
        // Open file if not opened
        chatLog.Open()
    } else if chatLog.logFile.Name() != chatLog.GenerateFilename() {
        // If the filename doesn't match where we should be writing
        // close the old file and reopen with a new name.
        chatLog.logFile.Close()
        chatLog.Open()
    }
}

// GenerateFilename returns a filename in the following format
// using the current timestamp:
// $LOGDIR/$PROTOCOL/$SERVER/YYYY/MM/DD/HH.csl
func (chatLog *ChatLog) GenerateFilename() string {
    return path.Join(
        chatLog.logDir,
        chatLog.Protocol,
        chatLog.Server,
        time.Now().UTC().Format("2006/01/02/15.csl"))
}


texts: Renaming PDF files based on given rules in a text file

texts:
I'm learing Python by writing a program to solve some housekeeping I do weekly, namely renaming PDF files according to rules given in a text file.

My end goal is to have idiomatic Python, with full test coverage. I have done some refactoring, and written a couple of tests. Ideally I would have done TDD from the beginning, but I find it challenging to write tests since I don't know Python that well yet.

The PDF documents can be named with two patterns:

xx.pdf
xx-y.pdf

They are stored in the folder ./test relative to the script root.

The text file Instruments.txt contains the following pattern:

01 SopranoCn
02 SoloCn
03 RepianoCn
...
18 Percussion
20 AllParts
...

The whole purpose is to rename files like this:

xx.pdf   (01.pdf)   --> xx_{instrument_name}.pdf (01_SopranoCn.pdf)
xx-y.pdf (02-1.pdf) --> xx_{instrument_name}{part_number}.pdf (02_SoloCn1.pdf)

The y-argument is optional, and can be added to any instrument.

Here's the whole source:

"""
Invoke with "python notesort.py <path to folder>".
A list of instrument numbers with corresponding instrument names
must be available in the root folder of the script.
"""

# Standard library imports
import os

FOLDER = './test'

def create_instrument_map():
    """Create a dictionary mapping each prefix
    to the corresponding instrument name."""
    with open('Instruments.txt') as instrument_file:
        return {
            line.split()[0]: line.split()[1] for line in instrument_file
        }

def rename_files_with_instrument_name(instrument_map):
    """Rename PDF files in folder based on the root of
    the original file name."""
    for filename in os.listdir(FOLDER):
        root, extension = os.path.splitext(filename)
        if not extension.endswith('.pdf'):
            continue
        try:
            if root[2]:
                if root[:2] in instrument_map:
                    new_file_name = '{prefix}_'\
                                    '{instrument_name}'\
                                    '{part_number}'\
                                    '{extension}'.format(
                                        prefix=root[:2],
                                        instrument_name=instrument_map[root[:2]],
                                        part_number=root[3],
                                        extension=extension)
        except:
            if root in instrument_map:
                new_file_name = '{prefix}_{instrument_name}{extension}'.format(
                                    prefix=root,
                                    instrument_name=instrument_map[root],
                                    extension=extension)
        old_path = os.path.join(FOLDER, filename)
        new_path = os.path.join(FOLDER, new_file_name)
        os.rename(old_path, new_path)
        print 'Renamed', filename, '-->', new_file_name

if __name__ == '__main__':
    instrument_map = create_instrument_map()
    rename_files_with_instrument_name(instrument_map)

I have started to write some tests for it, but I find it difficult to test rename_files_with_instrument_name. I do not have any experience writing tests, but I see the benefit and want to practise writing them.

These are the tests I have so far:

import unittest
from notesort import create_instrument_map

class TestNoteSort(unittest.TestCase):

    def test_create_instrument_map_creates_soprano_cornet(self):
        instrument_map = create_instrument_map()
        self.assertEqual(instrument_map['01'], 'SopranoCn')

    def test_create_instrument_map_soprano_not_solo(self):
        instrument_map = create_instrument_map()
        self.assertNotEqual(instrument_map['01'], 'SoloCn')

if __name__ == '__main__':
    unittest.main()

Please feel free to make comments on any part of my implementation. No need to be easy on me, even if I'm a beginner.

I am especially interested in how I can get further with testing, and also how to refactor rename_files_with_instrument_name.


texts:
I'm new to Python, but I really want to get into the swing of doing things the pythonic way. First, does my code follow the pythonic path? Or does it run screaming bloody murder, as it zig-zags through my C++ thought of mind? Probably the latter.

 import sys, random, string
 #import pdb
 #pdb.set_trace()

 def read(name):
     inFile=open(name, 'r')
     content=inFile.read()
     content=list(content.strip())
     return content

 #this function will take a file name and a list of numbers
 #it will convert the nums to chars and write to file
 def write(name, nList):
     outFile=open(name, 'w')
     cList=convertToChar(nList)
     outFile.write(''.join(cList))

 #takes a key length, based on message size and gens rand key
 def gen(keylen):
     i=0
     key=[]
     while i <keylen:
         k=random.SystemRandom()
         k=k.choice(string.printable)
         key.append(k)       #append random letter to key list
         i+=1
     key=convertToNum(key)    #conver the key to numbers for xor later
     write("key.txt", key)
     return key              #for xor'ing later in enc

 #takes a list of chars, converts to nums, and writes to list
 #returns a numList
 def convertToNum(charList):
     numList=[]
     i=0
     for i in charList:
         numList.append(ord(i))
     return numList

 #takes list of nums, converts to chars, and writes to new list
 #retursn the charlist
 def convertToChar(numList):
     charList=[]
     i=0
     for i in numList:
         charList.append(chr(i))
     return charList

 #This will ask the user for a file name
 #converts the
 def enc():
     fileName= raw_input("Please enter a name for your message file")
     #fileName="plaintext.txt"
     plaintext=read(fileName)      #gets a list form of the file
     m= convertToNum(plaintext)    #the message in nums
     mLen=len(m)                   #len of message for size of key
     k=gen(mLen)                   #generate the key
     c=[]                          #list to srote the encrypted message
     c= [a^b for a, b in zip(m,k)] #xor's each element in the tuple (m,k)
     write("ciphertext.txt", c)   #writes the xor'ed message to teh cipher

 def dec():
     ciphertext=read("ciphertext.txt")
     key=read("key.txt")
     ciphertext=convertToNum(ciphertext)
     key= convertToNum(key)
     i=0
     decrypted=([a^b for a, b in zip(ciphertext, key)])
     write("decrypted.txt", decrypted)

 def main():
     enc()
     dec()

  main()


texts:
I had already put up code for review a small poker program but I have rewrote it utilizing a more appropriate data structure.

How would I compare Poker hands accordingly?

Full source repo

enum poker_hands check_hand(vector *hand) /* check what kind of poker hand player has and return a score from 1 to 10 */
{
    sort_hand(hand);
    struct Card_s *temp[MAXHAND];
    for (int t = 0; t < MAXHAND; ++t) {
        temp[t] = (struct Card_s*) vector_get(hand, t);
    }

    /* check for flushes */
    {
        bool flushsuit = true;
        for (int i = 1; i < MAXHAND; ++i) {
            if (temp[0]->nSuit != temp[i]->nSuit) { /* check if card 1 is the same suit as the rest */
                flushsuit = false;
                break;
            }
        }
        if ( flushsuit ) {
            if ( temp[0]->nType == (temp[1]->nType-1) /* check if the cards increment one after the other */
                && temp[1]->nType == (temp[2]->nType-1)
                && temp[2]->nType == (temp[3]->nType-1)
                && temp[3]->nType == (temp[4]->nType-1) )
            {
                if ( temp[4]->nType == ace )
                    return royal_flush; /* found royal flush */
                else
                    return straight_flush; /* found straight flush */
            }
            return normal_flush; /* it was a normal flush */
        }
    }

    int group[MAXHAND+1]    = { 0 } ;
    int rankcount[MAXTYPES] = { 0 } ;

    for(int i = 0; i < MAXHAND; ++i) {
        int rank = temp[i]->nType;  // Get each card's type
        rankcount[rank]++;      // Increment each rank index
        group[rankcount[rank]]++;   // increment each rank's count index
    }

    if ( group[4] )
        return four_kind;

    if ( group[3] && group[2] > 1 ) // Found 3 of a kind and found another pair
        return fullhouse;

    if ( temp[0]->nType == (temp[1]->nType-1)
        && temp[1]->nType == (temp[2]->nType-1)
        && temp[2]->nType == (temp[3]->nType-1)
        && temp[3]->nType == (temp[4]->nType-1) ) {
        return straight; /* found straight */
    }

    if ( group[3] )
        return three_kind;

    if ( group[2] > 1 ) // If the 2nd index of the group[] array is more than 1, two pairs are found
        return two_pair;

    if ( group[2] )
        return pair;

    return highcard ; /* player only has a high card value */
}


texts:
I have made my first game in Python.

My program can determine when there is a winner, however I am unsure what to do if the board is full and there is NO winner (a cats game).

import cTurtle
import random
import sys

def DrawTicTacToeBoard(t):
    #Vertical Lines of board
    t.pensize(3)
    t.up()
    t.goto(.5,-.5)
    t.down()
    t.goto(.5,2.5)
    t.up()
    t.goto(1.5,-.5)
    t.down()
    t.goto(1.5,2.5)
    #Horizontal Lines of board
    t.up()
    t.goto(-.5,.5)
    t.down()
    t.goto(2.5,.5)
    t.up()
    t.goto(-.5,1.5)
    t.down()
    t.goto(2.5,1.5)

def flipPlayer(currentPlayer):
    if currentPlayer==0:
        currentPlayer=1
    else:
        currentPlayer=0
    return currentPlayer

def drawWhiteBox(t,x,y):
    t.up()
    t.goto(x-.25,y+.25)
    t.down()
    t.color("white")
    t.begin_fill()
    for i in range(4):
        t.forward(.8)
        t.right(90)
    t.end_fill()
    t.color("black")

def drawMarker(t,currentPlayer,markerList,move,boardLoL):
    by=int(move[0:1])
    bx=int(move[2:])
    y=by+(.22)
    x=bx-(.15)
    drawWhiteBox(t,x,y)
    t.up()
    t.goto(x,y)
    boardLoL[by][bx]=markerList[currentPlayer]
    t.write(markerList[currentPlayer],move=False,align="left",font=("Arial",48,"normal"))

def getValidMove(validMoveList,markerList,currentPlayer,boardLoL):
    move = ""
    while move not in validMoveList:
        move = input("Enter location to place your marker " + markerList[currentPlayer] + ", or EXIT to end game => ")
        if move=="EXIT":
            sys.exit()
        if move in validMoveList:
            by=int(move[0])
            bx=int(move[2:])
            if boardLoL[by][bx]=="":
                return move
            else:
                print("Location already occupied")
                move=""

def gameWon(b):
    for row in range(3):
        if b[row][0]==b[row][1] and b[row][1]==b[row][2] and b[row][0]!="":
            print("Way to go",b[row][0])
            return b[row][0]
    for column in range(3):
        if b[0][column]==b[1][column] and b[1][column]==b[2][column] and b[0][column]!="":
            print("Way to go",b[column][0])
            return b[0][column]
    for diag in range(2):
        if b[0][0]==b[1][1] and b[1][1]==b[2][2] and b[0][0]!="":
            print("Way to go",b[0][0])
            return b[0][0]
        if b[2][0]==b[1][1] and b[1][1]==b[0][2] and b[2][0]!="":
            print("Way to go",b[2][0])
            return[2][0]

    return ""

def boardIsFull(boardLoL):
    return False

def main():
    boardLoL=[["","",""],["","",""],["","",""]]
    markerList=["O","X"]
    validMoveList=["0,0","0,1","0,2","1,0","1,1","1,2","2,0","2,1","2,2"]
    joe=cTurtle.Turtle()
    joe.setWorldCoordinates(-2,3,4,-1)
    joe.ht()
    currentPlayer=random.randint(0,1)
    DrawTicTacToeBoard(joe)
    move = ""
    while boardIsFull(boardLoL)==False and gameWon(boardLoL)=="" and move !="EXIT":
        move = getValidMove(validMoveList,markerList,currentPlayer,boardLoL)
        drawMarker(joe,currentPlayer,markerList,move,boardLoL)
        currentPlayer=flipPlayer(currentPlayer)
    gameWon(boardLoL)
    boardIsFull(boardLoL)

main()


texts: Dependency Inversion / Injection? - Networking code in model classes

texts:
@implementation User

- (void)refreshProperties
{
    assert(!self.isSyncing);

    NetworkOperation *op = [[NetworkOperation alloc] initWithEndPoint:GetUserDetails parameters:nil];
    [self setupCompletionForRefresh:op];

    [self setNetworkOperation:op];
    [self setSyncing:YES];

    [[NetworkManager sharedManager] enqueueOperation:op];
}

The above code is used by a UIViewController subclass to update the properties of a User instance (i.e. the view controller calls [aUser refreshProperties] in pull-to-refresh).

Concerted efforts have been made to make sure there are clear lines defining the separation of concerns:

Network Operation class only deals with getting data from the network
Network Manager class deals with enqueuing operations and watching
reachability
User class houses the strings, numbers, bools, etc that
make up a User instance

However, there are some problems with the above method. First and foremost is it's  hard to test. There isn't any way to mock a network operation or network manager and get them inside the method call without swizzling. Also, it couples the User class with the NetworkOperation and NetworkManager classes.

While the above code works, I would like to refactor it.

Looking through GoF, it looks like there are some ways to remove the dependency between User and Network-Operation/Manager: adapter, dependency inversion (using a protocol), etc. From what I can tell, that code would look something like:

[aUser setNetworkOperation:<object conforming to protocol>];
[aUser setNetworkManager:<object conforming to protocol>];
[aUser refreshProperties];

But... isn't this just shifting the dependency? The above calls would happen in the view controller, and now it has to know about and use three classes instead of just the main one it was originally concerned with - User.

Thoughts, discussion, resources, or code examples are greatly appreciated!


texts: Simple join between 2 tables with unusual structure


texts:
I'm practicing my OOP and so created this service that stores a user's favorites from an application.

The favorite has an ID, a owner ID, and his type. This service only saves and makes this information available.

When instantiating the service, must be provided a API KEY and the types of favorites available.

class FavoritesService {

  /**
   * string
   */
  private $key;

  /**
   * array
   */
  private $data;

  /**
   * array
   */
  private $types;

  /**
   * @param string $key The key of the application.
   * @param array $types Array containing the type of favorites.
   */
  public function __construct($key, $types) {
    $this->key = $key;
    $this->types = $types;
  }

  /**
   * Saves a favorite.
   *
   * @param integer $id The ID of the favorite.
   * @param integer $ownerId The ID of his owner.
   *
   * @throws InvalidArgumentException If the provided argument is not a valid type.
   * @throws Exception If the save to somewhere goes wrong.
   *
   * @return boolean Indicating that all went fine.
   */
  public function save($id, $ownerId, $type) {
    if (!in_array($type, $this->types)) {
        throw new InvalidArgumentException('Invalid favorite type.');
    }
    $this->data[$ownerId][] = self::buildResult($id, $type);
    // also save everything to somewhere
    return true;
  }

  /**
   * Provides all the favorites of a owner.
   *
   * @param integer $ownerId The ID of the owner.
   *
   * @return array|null All the favorites from the user or, if the user doesn't exists, null.
   */
  public function get($ownerId) {
      if (isset($this->data[$ownerId])) {
        return $this->data[$ownerId];
      }
      // checks somewhere if the data exists
      return null;
  }

  /**
   * Resets all the favorites of a owner.
   *
   * @param integer $ownerId The ID of the owner.
   *
   * @throws Exception If the reset to somewhere goes wrong.
   *
   * @return boolean Indicating that all went fine.
   */
  public function reset($ownerId) {
    unset($this->data[$ownerId]);
    // also update everything to somewhere
    return true;
  }

 /**
  * Builds a result of a favorite.
  *
  * @param integer $id The ID of the favorite.
  * @param string $type The type of the favorite.
  *
  * @return array An array with the favorite.
  */
  private static function buildResult($id, $type) {
    return [
        "id" => $id,
        "type" => $type
    ];
  }
}

An usage example. Users favorite tourism Places.

$favoritesService = new FavoritesService(
  'MY_SECRET_API_KEY',
  ['HOTEL', 'REGION', 'POI']
);

$favoritesService->save(1, 123, 'HOTEL');
$favoritesService->save(1, 321, 'REGION');
print_r($favoritesService->get(1));

$favoritesService->reset(1);
print_r($favoritesService->get(1));

My question, is this a good OOP design?

Is there a better naming than Service? It seems to generic to me.


texts: Better way than setInterval to wait for an image load?

texts:
This is really a simple affair, I just wonder if there is a better way to do it:

let el = document.querySelectorAll('#comic img');
let loadPromise = new Promise(function(resolve, reject) {
    let ticker = setInterval(() => {
        if (el[0].complete) {
            clearInterval(ticker);
            resolve();
        }
    }, 100);
    setTimeout(() => {
        clearInterval(ticker);
        reject('Timeout');
    }, 5000)
});

loadPromise.then(() => {
    console.log(el[0].naturalWidth);
    let container = document.querySelectorAll('.main-wrapper > div > section > section.column.column-1.grid-left-4.grid-width-16');
    container[0].style.width = (el[0].naturalWidth + 420) + 'px';
});

I must wait for the image to load, so I know its size so that I can adjust an element on the page.

But setInterval(aka polling the element) seems so... medieval. Is there a nicer way in modern JS?


texts:
I have written a basic C Shell. It features the builtins cd, programmer, ver and exit. The code for the shell, named vsh, is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

#define BUFSIZE 1024
#define TOK_BUFSIZE 64
#define TOK_DELIM " \t\r\n\a"

char **split_line(char *line)
{
    int bufsize = TOK_BUFSIZE, position = 0;
    char **tokens = malloc(bufsize * sizeof(char*));
    char *token, **tokens_backup;

    if (!tokens) {
        fprintf(stderr, "vsh: allocation error\n");
        exit(EXIT_FAILURE);
    }

    token = strtok(line, TOK_DELIM);
    while (token != NULL) {
        tokens[position] = token;
        position++;

        if (position >= bufsize) {
            bufsize += TOK_BUFSIZE;
            tokens_backup = tokens;
            tokens = realloc(tokens, bufsize * sizeof(char*));
            if (!tokens) {
                free(tokens_backup);
                fprintf(stderr, "vsh: allocation error\n");
                exit(EXIT_FAILURE);
            }
        }

        token = strtok(NULL, TOK_DELIM);
    }
    tokens[position] = NULL;

    return tokens;
}

int main(int argc, char **argv)
{
    int finish = 0;
    char *user = getenv("USER");
    char hostname[BUFSIZE];
    char *cwd;
    char line[BUFSIZE] = {0};
    char **args;
    char *directory;

    printf("Welcome to vsh\n");

    system("/bin/cat /etc/motd");

    printf("\n");

    gethostname(hostname, BUFSIZE);

    while (!finish)
    {
        cwd = getcwd(cwd, BUFSIZE);

        printf("[");
        printf(user);
        printf("@");
        printf(hostname);
        printf("] ");
        printf(cwd);
        printf(" $ ");
        fflush(stdout);

        if(NULL == fgets(line, sizeof line, stdin))
        {
            finish = 1;
            printf("\nLeaving vsh\n");
        }
        else
        {
            printf("The command read was %s", line);
            printf("\n");

            args = split_line(line);

            if(strcmp(line, "") == 0) {
                fprintf(stderr, "vsh: Expected command\n");
            }
            else if(strcmp(args[0], "cd") == 0)
            {
                directory = args[1];
                chdir(directory);
            }
            else if(strcmp(line,"programmer") == 0)
            {
                printf("The programmer of vsh is George Gibson\n");
            }
            else if(strcmp(line,"ver") == 0)
            {
                printf("The current version is 1.0\n");
            }
            else if(strcmp(line,"exit") == 0)
            {
                finish = 1;
                printf("\nLeaving vsh...\n");
                getchar();
            }
            else
            {
                pid_t pid;
                int err;

                pid = fork();

                if(pid == -1) {
                    perror("vsh");
                }
                else if(pid == 0) {
                    execvp(args[0], args);
                    perror("vsh");
                }
                else {
                    waitpid(pid, &err, 0);
                }
            }
        }
    }

    return 0;
}

I'm particularly looking for reviews relating to bugs, optimizations and general improvements.


texts:
Requirement
I have an entity named ImportData which can be processed once in order to extract data from a file fed to the application.
I need to make sure that, in case of concurrency, only one process is capable of processing that import data. Other processes shall not attempt to read the file and insert data into database.
This has to work in a clustered environment, where if two people click on a button (and a third scheduled process triggers at the same time, in the worst case) only one will process data and others will silently fail.
What I did so far
I thought that the simplemost option was to leverage transactions and entity status, as we have a single database.
So if my entity flows from the ACQUIRED to the PROCESSING and then to either PROCESSED_OK or PROCESSED_KO states, I just need to make sure that ACQUIRED->PROCESSING is atomic and exclusive
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW,
        isolation = Isolation.SERIALIZABLE)
public boolean lockForProcessing(Long importId)
{
    if (importId == null)
        throw new NullPointerException();

    ImportData importData = importDataDao.findById(importId);
    if (importData == null)
        throw new NotFoundException(ImportData.class, importId);

    if (importData.getStatus() != ImportStatus.ACQUIRED)
        return false;
    importData.setStatus(ImportStatus.PROCESSING);
    importDataDao.update(importData);

    return true;
}

Comments:

We use Hibernate for all DBMS operations, together with Spring-Tx for transaction management over session factory
Propagation=NEW assures that the transaction is committed after execution of the method, so the transaction doesn't propagate to caller
Isolation=SERIALIZABLE assures that the DBMS should not allow dirty reads
Code is supposed to run on MySQL, SQL Server and Oracle too
If it was not obvious before, application runs on a single database. And for now the database is not clustered or such

Remarks
One of my coworkers remarked that this design is not safe. He said "what if two concurrent processes, at the same time, query the entity for the ACQUIRED state?". He said to add synchronized to the method, but we then agreed that wouldn't solve the cluster issue.
I have answered that, in my design, either one of the following happens:

If threads T1 and T2, no matter on the same node or clustered, perform at the same exact time, one enters the transaction but another is locked from reading by the DBMS
If threads T1 and T2 perform at the same exact time, one is allowed to commit and return true, the other has performed a dirty read and at best throws an exception on commit, preventing from returning a "dirty true"

Question

Is my design correct?
Which of the above statements is correct from a design point of view?


texts: Finds all valid words by arranging 3 cubes

texts:
Given 3 cubes, each cube has 3 different letters(other sides have
  pictures and numbers - they can be ignored for the purposes of this
  program). Find all valid words that can be made by arranging these
  cubes.

  Cube A = 'A', 'J' and 'N'; Cube B = 'B', 'K' and 'O'; Cube C = 'C',
  'L' and 'P'

import re
from itertools import permutations

a = ['A','J','N']
b = ['B','K','O']
c = ['C','L','P']

combinationsList = []#list of all possible variations of 3 letter words
for a_letter in range(len(a)):
    for b_letter in range(len(b)):
        for c_letter in range(len(c)):
            word = a[a_letter] + b[b_letter] + c[c_letter]
            combinationsList.append(word)
print len(combinationsList)

permutationsList = []#list of all permutations of the combinations list [changing positions of the cubes to form different words]
for word in combinationsList:
    perms = [''.join(p) for p in permutations(word)]
    permutationsList += perms

print len(permutationsList)

dictionList = []#list of all valid words found that match the length of number of cubes (in this scenario there are 3 cubes)
with open("/usr/share/dict/words", "r") as diction:
    for line in diction:
        word = line.strip()
        if re.match('.{3}$', word) != None:#improve regex search to only find words in the valid character setw
            dictionList.append(word.upper())
print len(dictionList)

match = []

for word in permutationsList:
    if dictionList.count(word) > 0:#compares all word permutations with all words in diction for matches
        match.append(word)
print match


texts:
I have this working map function and I'm wondering if I can improve anything. Should I prefer templates instead of auto in this case?

auto map = [](auto items, auto fun) {
    vector<decltype(fun(items[0]))> result;

    for (auto item : items) {
        result.push_back(fun(item));
    }

    return result;
};


texts: Am I writing good Go here? Python functions converted to Go

texts:
I originally asked this question on StackOverflow. Reproduced here by recommendation.

I've got a number of Python scripts that I'm considering converting to Go. I'm seeking confirmation that I'm using Go in essentially the way it was meant to be used. Full code is available here: https://gist.github.com/anonymous/7521526

So the primary question is: Am I writing what is considered "good Go" ?

Python function #1: Look at the files in a folder and extract the latest encoded date in the filenames.

def retrieveLatestDateSuffix(target):
    return max(map("".join, filter(lambda x: x,
        map(lambda x: re.findall(r"_([0-9]{8})\.txt$", x),
            os.listdir(target)))))

My translation for #1:

var rldsPat = regexp.MustCompile(`_([0-9]{8})\.txt$`)
func retrieveLatestDateSuffix(target string) (string, error) {
    if fis, e := ioutil.ReadDir(target); e == nil {
        t := ""
        for _, fi := range fis {
            if m := rldsPat.FindStringSubmatch(fi.Name()); m != nil {
                if m[1] > t { t = m[1] }
            }
        }
        return t, nil
    } else {
        return "", e
    }
}

Python function #2: Add a date suffix to each filename inside a folder that doesn't already have a suffix added. Printing the from/to for now instead of doing the rename.

def addDateSuffix(target, suffix):
    for fn in filter(lambda x: re.search(r"(?<!_[0-9]{8})\.txt$", x), os.listdir(target)):
        pref, ext = os.path.splitext(fn)
        gn = "{0}_{1}{2}".format(pref, suffix, ext)
        print(fn, " -> ", gn)

My translation for #2:

var adsPat1 = regexp.MustCompile(`\.txt$`)
var adsPat2 = regexp.MustCompile(`_[0-9]{8}\.txt$`)
func addDateSuffix(target string, suffix string) error {
    if fis, e := ioutil.ReadDir(target); e == nil {
        for _, fi := range fis {
            if m1 := adsPat1.FindStringSubmatch(fi.Name()); m1 != nil {
                if m2 := adsPat2.FindStringSubmatch(fi.Name()); m2 == nil {
                    ext := filepath.Ext(fi.Name())
                    gn := fmt.Sprintf("%s_%s%s", strings.TrimSuffix(fi.Name(), ext), suffix, ext)
                    fmt.Println(fi.Name(), "->", gn)
                }
            }
        }
        return nil
    } else {
        return e
    }
}


texts: Querying a database to find notifications to comments

texts:
I have a solution what I think is not the best, and I want to make this not so expensive.

I'm using MVC 5 + SignalR (hubs) + EF + UnitOfWork + Generic Repos.

I have a table Comments:

Id (Guid Pk)
Comment (Text)
ParentId (nullable FK to PK (ID) self referencing -> a response to another comment)
BrowserId (Id gathered from Context.AnonymousId to recognize anon. users)
IsNotified (if this is a response ParentId not null - will indicate if the response has been notified to original comment)

This is my flow:

User opens the landing page
After page finish loading SignalR will execute code to find if that user had any response to any of his comments while not connected

This is my SignalR logic, where I think we can make things better:

public void GetUserNews()
{
    var news = new List<CommentVm>();

    //1) I browse ALL the DB where the comments have my Anonymous this means that are comments that I made.
    List<Guid> misComentarios = UnitOfWork.CommentService
        .SearchBy(c => c.BrowserId == new Guid(HttpContext.Current.Request.AnonymousID))
        .Select(c => c.Id)
        .ToList();

    //2) Then I go and search all other comments that ARE NOT notified and is a response to users comments because the parent is the users comment.
    var resultados = UnitOfWork.CommentService
        .SearchBy(c => !c.IsNotified && misComentarios.Contains((Guid)c.ParentId))
        .ToList();

    //3) If I have a result...
    if (resultados.Any())
    {
         //I use automapper to convert to vm.
        news = Mapper.Map<List<CommentVm>>(resultados);

        //then I change the notified property to TRUE
        resultados.ForEach(m => m.IsNotified = true);
        UnitOfWork.Save();
      Clients.Caller.receiveNews(news);  //send the news to client
    }
}

My questions and observations are:

I search the whole comment base to get all my comments (my AnonymousID)
I get all the comments that are not notified whose parentId are in my resulset

This will execute just on landing page, then I will use signalR if a user gets a response while connected.

Do you think there is a much easier way to query the DB and get what I'm looking for?


texts: Creation of MxM matrix: Python version much slower than Matlab version

texts:
I have written the same code in Python (NumPy) and in Matlab, and I tried to use the same structure for both language and follow the same procedure. Now my problem is that when I run my code in Python it's very very slow but it runs fast in Matlab.

How can I improve my Python code?  I want to work on the Python version of my code.

In the code I am trying to create an MxM matrix (M can vary between 100 to 1000) and trying to fill this matrix 16 times, each time I add the previous value of M[i,j] with the current value. The operation inside the code is simple just some add and divide, and now I wonder why Matlab performs better than Python.

Python:

import numpy as np
import matplotlib.pyplot as plt

from datetime import datetime
startTime = datetime.now()

bb = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
bb = ['{0:04b}'.format(x) for x in bb]

step_prob=0.01

step = int(1/step_prob)

out_t = np.zeros((step,step), dtype=float)
out_f = np.zeros((step,step), dtype=float)
s = np.zeros((step,step), dtype=float)
improve = np.empty((step,step))

for ii in range(1, step+1):
    print ii
    pti=ii*step_prob
    for  jj in range(1, step+1):
        pfi=jj*step_prob
        improve[ii-1,jj-1]=0
        si=(1-pfi+pti)/2
        for k in range(len(bb)):
            f1 = int(bb[k][0])
            f2 = int(bb[k][1])
            f3 = int(bb[k][2])
            f4 = int(bb[k][3])
            for i in range(1, step+1):
                for j in range(1, step+1):
                    ptj=i*step_prob
                    pfj=j*step_prob
                    out_t[i-1,j-1] = f1*pti*ptj+f2*pti*(1-ptj)+f3*(1-pti)*ptj+f4*(1-pti)*(1-ptj)
                    out_f[i-1,j-1] = f1*pfi*pfj+f2*pfi*(1-pfj)+f3*(1-pfi)*pfj+f4*(1-pfi)*(1-pfj)
                    sj=(1-pfj+ptj)/2;
                    s[i-1,j-1] = ((1-out_f[i-1,j-1]+out_t[i-1,j-1])/2)-max(si,sj);

#         temp=s*(s>0)*tril(ones(size(s)));
            temp = s*(s>0)*np.tril(np.ones((len(s),len(s))).astype(int))
            improve[ii-1,jj-1]=improve[ii-1,jj-1]+sum(sum(temp))

im = plt.imshow(improve*np.tril(np.ones((len(improve),len(improve))).astype(int)),interpolation='bilinear', aspect='auto') # s*[s>0]
# im = plt.imshow(improve, interpolation='bilinear', aspect='auto') # s*[s>0]
plt.colorbar(im, orientation='vertical')
plt.show()

Matlab:

close all
clear all
clc

bb = de2bi([0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15],4,'left-msb');
% bb = de2bi([1],4);

step_prob=0.01;
for ii=1:1*(1/step_prob)
    ii
    pti=ii*step_prob;
    for jj=1:1*(1/step_prob)
        pfi=jj*step_prob;
        improve(ii,jj)=0;
        si=(1-pfi+pti)/2;
        for k=1:size(bb,1)
            f1=bb(k,1);
            f2=bb(k,2);
            f3=bb(k,3);
            f4=bb(k,4);
            for i=1:1*(1/step_prob)
                for j=1:1*(1/step_prob)
                    ptj=i*step_prob;
                    pfj=j*step_prob;
                    out_t(i,j)=f1*pti*ptj+f2*pti*(1-ptj)+f3*(1-pti)*ptj+f4*(1-pti)*(1-ptj);
                    out_f(i,j)=f1*pfi*pfj+f2*pfi*(1-pfj)+f3*(1-pfi)*pfj+f4*(1-pfi)*(1-pfj);
                    sj=(1-pfj+ptj)/2;
                    s(i,j)=((1-out_f(i,j)+out_t(i,j))/2)-max(si,sj);
                end
            end
            temp=s.*(s>0).*tril(ones(size(s)));
            improve(ii,jj)=improve(ii,jj)+sum(sum(temp));
            clear f1 f2 f3 f4
        end
    end
end
scale=step_prob:step_prob:1;
imagesc(scale,scale,improve.*tril(ones(size(improve))))
xlabel('Pfj')
ylabel('Ptj')
axis xy


texts: Calculate the sum of the square of two biggest numbers out of three

texts:
I'm reading Structure and Interpretation of Computer Programs.  In the first exercise, I came across a programming problem to add the squares of the 2 bigger numbers out of 3 numbers.

I came up with the following procedure:

(define (sum-of-larger-two a b c)
  (
    if (> a b)
      (if (> b c)
        (+ (* a a) (* b b))
        (+ (* a a) (* c c))
      )
      (if (> c a)
        (+ (* b b) (* c c))
        (+ (* b b) (* a a))
      )
  )
)

Is there a more succinct way to write this program?


texts: More concise and/or idiomatic max subarray in Clojure?

texts:
I've implemented the following two versions of the classic "Max Sub-Array" problem in Clojure, using the Kadane algorithm.

First with loop / recur

(defn max-sub-array [A]
  (loop [x (first A)
         a (rest A)
         max-ending-here 0
         max-so-far 0]
    (if (seq a)
      (recur (first a) (rest a) (max x, (+ max-ending-here x)) (max max-so-far, max-ending-here))
      max-so-far)))

Then with reduce

(defn max-sub-array-reduction [A]
  (letfn [(find-max-sub-array [[max-ending-here max-so-far] x]
             [(max x (+ max-ending-here x)) (max max-so-far max-ending-here)])]
    (second (reduce find-max-sub-array [0 0] A))))

Is there a more concise implementation, perhaps using filter or merely by making the reduce version more "idiomatic" somehow?


texts: Chrome extension to get youtube video's URL

texts:
I needed something that would get the URL of a chosen video from YouTube and store it in a file.

Since I didn't find a way to write/edit an existing file with the URL alone, I had to use a patchwork of JavaScript and bash to stitch together the complete URL.

I'm asking if there were things I could have done better or with a different approach.

Here's the code of the extension:

manifest.json:

{
    "manifest_version": 2   ,

    "name": "Adder",
    "description": "Add video's URL to file for future download",
    "version": "1.3.1",
    "icons": { "128": "icons/square_youtube.png"},
    "background": {
        "scripts": ["background.js"],
        "persistent": false
     },

     "permissions": [
        "tabs",
        "downloads",
        "declarativeContent"
    ],

    "page_action": {
        "default_name": "Adder",
        "default_icon": "icons/square_youtube.png",
        "default_popup": "popup.html",
        "default_title": "Add it!"
    }
}

background.js:

// Update the declarative rules on install or upgrade.

chrome.runtime.onInstalled.addListener(function() {
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
            chrome.declarativeContent.onPageChanged.addRules([{
                conditions: [
                    // When a page contains a <video> tag...
                    new chrome.declarativeContent.PageStateMatcher({
                        css: ["video"]
                    })
                ],
                // ... show the page action.
                actions: [new chrome.declarativeContent.ShowPageAction() ]
            }]);
    });
});

popup.js (popup.html just call this script):

var stripThis = "https://www.youtube.com/watch?v=";

chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
    var currentUrl = tabs[0].url;
    var smallUrl = currentUrl.substring(stripThis.length, currentUrl.length);
    var pathDL = "URLs/"+smallUrl+".txt";

    chrome.downloads.download({url: currentUrl, filename:pathDL}, function(downloadId) {});
});

Let me explain what this does in particular:

I built a panel_action extension that only shows if there is a video in the page. Then if I click on the icon in the omnibar, the extension download the WHOLE html page in a .txt file named after the videoID.

Then using a bash script I take all the names of the files and merge them in a single list.

Here's the bash script:

#!/bin/bash
DownloadAndConvert() {
    echo Avvio...
    echo Importo URLs da files...
    echo creo lista unificata...
    cd /home/faceless/Dropbox/URLs/
    count=`ls -1 *.txt 2>/dev/null | wc -l`
    YTBSTR="https://www.youtube.com/watch?v="
    if [ $count != 0 ]; then
        touch mergedList
        for filename in *.txt; do
            echo $YTBSTR$(basename "$filename" .txt) >> mergedList
            if [ $filename != mergedList ]; then
                rm $filename
            fi
        done
        download
        cleanup
    elif [ -e mergedList ]; then
        echo La lista è già presente! - Procedo...
        download
        cleanup
    else
        echo Non ci sono video! - Esco
        exit
    fi
}
download() {
    echo Inizio Scaricamento...
    youtube-dl -x -a "mergedList" --no-playlist
}

cleanup() {
    echo Pulisco lista...
    rm mergedList
    echo FINE
}

trap exit SIGINT
DownloadAndConvert

I then use another program (built exactly for this task) to download and convert as desired all the video in that list.

This system feel a lot clumsy and it is mostly a patchwork of snippets of code took here and there (especially the JavaScript ones). That's why I'm asking for insights for improvements!

In the bash script, I could most likely just use the videoID instead of the whole URL. I still have to check youtube-dl documentation, but it doesn't change much.

I chose the download location (with some ln hacks) in such a way that the videoID.txt would end up in the same shared folder in dropbox.


texts: Project Euler #14 (Longest Collatz Sequence) in Haskell

texts:
You can check the problem here:
http://projecteuler.net/problem=14

My first approach in Haskell was this:

import Data.Ord
import Data.List

computeCollatzSequenceLength n = let
    compute l n
        | n == 1 = l+1
        | even n = compute (l+1) (n `div` 2)
        | otherwise = compute (l+1) (3*n+1)
    in generate 0 n

main = print $ fst $ maximumBy (comparing snd) $ zip [1..1000000] $ map computeCollatzSequenceLength [1..1000000]

Too slow it was, so I tried to use a sort of memoization by using an unboxed array:

import Data.Ord
import Data.List
import Data.Int
import Data.Array.Unboxed

computeCollatzSequenceLength :: (UArray Int64 Int64) -> Int64 -> (Int64, [Int64])
computeCollatzSequenceLength a n = let
    compute :: Int64 -> [Int64] -> Int64 -> (Int64, [Int64])
    compute l s n'
        | n' == 1 = (l+1, reverse s)
        | v > 0 = (l+v, reverse s)
        | even n' = compute (l+1) (n':s) (n' `div` 2)
        | otherwise = compute (l+1) (n':s) (3*n'+1)
        where v = if n' > (snd $ bounds a) then 0 else a!n'
    in compute 0 [] n

computeMax m = let
    compute :: (Int64,Int64) -> Int64 -> (UArray Int64 Int64) -> (Int64,Int64)
    compute candidate n a
        | n == (m+1) = candidate
        | otherwise = let
            (l, u) = computeCollatzSequenceLength a n
            a' = a//(filter (\(n',_) -> n' <= m) (zip u [l,l-1..]))
            in if (snd candidate) < l then compute (n,l) (n+1) a' else compute candidate (n+1) a'
    in compute (0,0) 1 (array (1,m) [ (i,0) | i <- [1..m] ])

main = print $ fst $ computeMax 1000000

But, this was also very slow...(Both took more than a few minutes on my machine. Actually, the latter seems to take much longer...) I don't know what I've done wrong(I'm still a novice in Haskell.) In theory, the memoized version should be faster. I want to avoid using one of existing memoization packages out there.

What are issues with the current approach and how can I optimize this while still keeping its overall structure/approach?

EDIT: I found an elegant solution here: http://www.haskell.org/haskellwiki/Euler_problems/11_to_20#Problem_14 (The last one there, I mean.) Imperativeness and assignment are so hardwired in me as an inveterate C++ programmer, I cannot think of such a solution on my own at the moment. Still, I'd like to know what were issues with my approach above.

EDIT2: My not-working try based on @Hammar's advice:

import Data.Int(Int64)
import Data.List(maximumBy)
import Data.Ord(comparing)
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed

getCollatzSequenceLengthUpto :: Int64 -> (UArray Int64 Int64)
getCollatzSequenceLengthUpto n = runSTUArray $ do
    seqLengths <- newArray (1,n) 0
    forM_ [1..n] $ \i -> do
        let compute l s n' = do
            v <- if n' > n then 0 else (readArray seqLengths n')
            if n' == 1
            then
                return (l+1, reverse s)
            else
                if v > 0
                then
                    return (l+v, reverse s)
                else
                    if even n'
                    then do
                        out <- compute (l+1) (n':s) (n' `div` 2)
                        return out
                    else do
                        out <- compute (l+1) (n':s) (3*n'+1)
                        return out
        (l, u) <- compute 0 [] i
        forM_ (filter (\(n',_) -> n' <= n) $ zip u [l,l-1..]) $ \(ix, e) -> do
            writeArray seqLengths ix e
    return seqLengths

main = print $ fst $ maximumBy $ (comparing snd) $ assocs $ getCollatzSequenceLengthUpto 1000000


texts: Is this a safe way of using HTTP query parameters to build a SQL query?

texts:
Is it? And maybe theres a better way to do this?

$allowed = array("name_desc", "name_asc", "level_desc", "level_asc", "vocation_desc", "vocation_asc");
$order = isset($_GET['order']) ? $_GET['order'] : "name";
$order = in_array($order, $allowed) ? str_replace("_", " ", $order) : "name";

$query = "SELECT * FROM players
          WHERE status = 0 AND group_id < 3 ORDER BY $order";


texts:
I was looking for a way to calculate a score 'x' for each pair of elements in two separate arrays.  The goal of the code is to return an output array containing the score for each entry in the input arrays.

from math import sqrt
import numpy as np

downs = np.genfromtxt('path\file.csv', dtype=long, delimiter=',', skiprows=1, usecols=(1,))
ups = np.genfromtxt('path\file.csv', dtype=long, delimiter=',', skiprows=1, usecols=(2,))

n = np.add(ups,downs)

def _confidence(n):

   for i, j in zip[n, ups]:

    z = 1.0 #1.0 = 85%, 1.6 = 95%

    if n == 0:
        return 0

    phat = float(ups) / n

    x = ((phat + z*z/(2*n) - z * sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n))

    print [x]


texts: "Guess my Number" game in Python (2.7.9)

texts:
First time posting to Code Review. Just looking to get some advice on how I can write better code.

I found the following exercise for a "Guess my Number" game on DaniWeb, but the linked source code file is no longer active. So while I know my code works, I'm not sure if I've written it in the best way.

  "The computer randomly generates a number. The user inputs a number,
  and the computer will tell you if you are too high, or too low. Then
  you will get to keep guessing until you guess the number."

(I also added a limited number of tries to the game, so the user can't try 1-10 in order until they guess right.)

from random import randint

### Variable declarations
correct = False
tries = 0
number = randint(1,10)
###

print ("I'm thinking of a number between 1 and 10.")
print ("I'll give you 5 chances to guess it.\n")

# Ask the user for their guess, as long as there are tries remaining
# and they haven't already guessed correctly.
while correct == False and tries < 5:

    guess = raw_input("What number am I thinking of?: ")

    # Make sure user's input is an integer
    try:
        guess = int(guess)

        if guess == number: # Correct answer
            correct = True
            print ("\nYou got it!")

        elif guess > number:    # Guess too high
            if guess > 10:
                tries += 1
                print ("\nWay too high! Try a number 10 or lower.")
            else:
                tries += 1
                print ("\nTry something lower.")

            remaining = 5 - tries
            print ("\nYou have " + str(remaining) + " guesses left.\n")

        else:
            if number > guess > 0:    # Guess too low
                tries += 1
                print ("\nTry something higher.")
            else:
                tries += 1
                print ("\nMake sure you guess a number 1 or higher!")

            remaining = 5 - tries
            print ("\nYou have " + str(remaining) + " guesses left.\n")

    # Input not an integer
    except ValueError:
        print ("\nThat wasn't a number! Try again.")
        print ("(I won't count that attempt.)")

        remaining = 5 - tries
        print ("\nYou have " + str(remaining) + " guesses left.\n")

### Game over! ###

# Ran out of guesses
if tries > 5:
    print ("\nSorry, you ran out of guesses!")
    print ("My number was " + str(number) + ".")

# Exited loop with tries left, must have guessed correctly
else:
    print ("Well done. Thanks for the game.")

I'd love to get some feedback on what I have here. Thanks in advance!


texts: Javascript reducing an array of arrays to a single array with concat or push

texts:
Which is more efficient? (Both memory usage and speed.)

arrayOfArrays.reduce((acc, innerArray) => {
  acc.push(...innerArray);
  return acc;
}, []);

Or

arrayOfArrays.reduce((acc, innerArray) => acc.concat(innerArray), []);


texts:
I've created a form to choose the settings: These settings are automatically saved in a file from the game client in this form:

["Setting"] = {
    ["track"] = "Spell Reflect",
    ["duration"] = {
        ["minimum"] = {
            ["enabled"] = 1,
            ["value"] = 3,
        },
        ["maximum"] = {
        },
    },
    ["stack"] = {
        ["minimum"] = {
        },
        ["maximum"] = {
            ["enabled"] = 1,
            ["value"] = 4,
        },
    },
}

To save the settings in this form I used this function:

function UnitScan_onAdvancedOptionClose()
    if not (db["duration"]) then
        db["duration"] = {}
        db["duration"]["minimum"] = {}
        db["duration"]["maximum"] = {}
    end
    db["duration"]["minimum"].enabled = minduration.cbutton:GetChecked()
    db["duration"]["minimum"].value = tonumber(minduration.ebox:GetText())
    db["duration"]["maximum"].enabled = maxduration.cbutton:GetChecked()
    db["duration"]["maximum"].value = tonumber(maxduration.ebox:GetText())

    if not (db["stack"]) then
        db["stack"] = {}
        db["stack"]["minimum"] = {}
        db["stack"]["maximum"] = {}
    end
    db["stack"]["minimum"].enabled = minstack.cbutton:GetChecked()
    db["stack"]["minimum"].value = tonumber(minstack.ebox:GetText())
    db["stack"]["maximum"].enabled = maxstack.cbutton:GetChecked()
    db["stack"]["maximum"].value = tonumber(maxstack.ebox:GetText())
end

Where

db = The "Setting" table
GetChecked() = Returns whether the check button is checked
GetText() = Returns the edit box's text contents

Could you help me to make the code less repetitive and more elegant?


texts:
The task is to select all posts tagged with a certain tag, along with other tags the post may have, given as text rather than ID.

Table posts

CREATE TABLE `posts` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `title` text NOT NULL,
 `text` text NOT NULL,
 `date` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8

Table tags

CREATE TABLE `tags` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `tag` varchar(20) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `tag` (`tag`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

Table posts_tags

CREATE TABLE `posts_tags` (
 `post` int(10) unsigned NOT NULL,
 `tag` int(11) NOT NULL,
 PRIMARY KEY (`post`,`tag`),
 KEY `tag` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

And here is the SQL I've come up with:

SELECT posts.id,
       title,
       posts.text,
       date,
       t.tag
FROM   tags
       LEFT JOIN posts_tags
              ON tags.id = posts_tags.tag
       LEFT JOIN posts
              ON posts.id = posts_tags.post
       LEFT JOIN posts_tags pt
              ON posts.id = pt.post
       LEFT JOIN tags t
              ON t.id = pt.tag
WHERE  tags.tag = ?
ORDER  BY posts.id DESC

Are there any optimizations that can be done to this code?


texts: Stack Exchange userscript for showing spoilers on questions with particular tags

texts:
Stack Exchange sites support hiding text as a spoiler with >!; for example:

   This text will be hidden until you hover over it/tap the "show spoiler" button.

This gets a lot of use on the Sci-Fi & Fantasy stack, usually to cover up key plot elements of a particular work (like the recent Star Wars film).

That’s a good way to avoid spoilers if you haven’t seen the work in question, but it can be annoying if you already know the plot.  Over on Meta SFF, somebody asked whether it would be possible to unhide spoilers on questions with particular tags.

I wrote this UserScript, which allows the user to specify an array of tags, and will unhide spoilers on questions with those tags:

// ==UserScript==
// @name         SFF.SE Show spoilers on questions with particular tags
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Show all spoilers on SFF.SE questions with specified tags
// @author       alexwlchan
// @match         *://scifi.stackexchange.com/questions/*
// @match         *://meta.scifi.stackexchange.com/questions/*
// @grant        none
// ==/UserScript==
/* jshint -W097 */
'use strict';

// If every tag on a question is in this array, then the spoilers on this
// question will be shown.
var SHOW_ME_SPOILERS_IF_TAGGED = [
    "harry-p0tter",
    "star-w4rs",
];

// Returns an array of tags on a question
var getTagsOnQuestion = function() {
    var taglist = document.getElementsByClassName("post-taglist")[0];
    var hrefs = taglist.getElementsByClassName("post-tag");

    var tags = [];
    for (var ii = 0; ii < hrefs.length; ii++) {
        tags.push(hrefs[ii].innerText);
    }
    return tags;
}

// Returns true/false depending on whether the spoilers on this question
// should be shown -- that is, whether every tag on the question is in
// SHOW_ME_SPOILERS_IF_TAGGED.
var shouldShowSpoilersOnQuestion = function() {

    // Get the tags on a question.  All questions have at least one tag.
    var tags = getTagsOnQuestion();

    for (var jj = 0; jj < tags.length; jj++) {
        // If we don't find the tag in the array of spoiler-able tags,
        // then we have to reject the question.
        if (SHOW_ME_SPOILERS_IF_TAGGED.indexOf(tags[jj]) == -1) {
            return false;
        }
    }
    return true;
}

// Modify all the spoilers on the page to show their spoiler text
var showSpoilers = function() {
    var spoilers = document.getElementsByClassName("spoiler");
    for (var kk = 0; kk < spoilers.length; kk++) {
        spoilers[kk].transition = "none";
        spoilers[kk].style.color = "#222426";
    }
}

if (shouldShowSpoilersOnQuestion()) {
    showSpoilers();
}

Any feedback is welcome, but particularly:

Is this good/idiomatic JavaScript?
Is the intent of the code clear?
Are there any edge cases that I’ve missed?
Is there a better way to check if (tags on the question) is a subset of (tags the user wants spoilers to be shown for)? I feel like my current approach is quite inefficient.


texts:
I'm trying to devise a tkinter gui, that, among others, lets users choose a 'working folder' and a 'destination folder (and there is more coming). I stripped the code to its bare functionality hereunder.
I found myself duplicating code for the selection of both the 'working folder' and the 'destination' folder. I came up with the solution to put these variables in a dictionary (I could pass them as mutable objects along with the lambda). Although it is a working solution, I have the feeling there is more standard way of achieving this objective.
My question therefore is: how can I make my _browsefile() function work whilst changing the value of self.working_dir and self.destination_dir, without using an artificial dictionary structure, hence avoiding duplicate code? This would implicate that I can generalize the _browsefile func somehow.
I have seen very advanced reusage features in text books, but currently this is out of my league. If I can learn to tackle this 'easy' one, it would possibly help me on my journey.
Thank you for giving me advice in doing it the Pythonic way...
import tkinter as tk
from tkinter import filedialog

class View():
    def __init__(self, parent):
        self.parent = parent

        self.gui_variables = {'working dir': '',
                              'destination dir': ''}

        self.menu()

    def menu(self):
        self.folder_button1 = tk.Button(self.parent, text="Choose Working Folder",
                                       command=lambda: self._browsefile(self.gui_variables['working dir']))
        self.folder_button1.pack()

        self.folder_button2 = tk.Button(self.parent, text="Choose Dest. Folder",
                                       command=lambda: self._browsefile(self.gui_variables['destination dir']))
        self.folder_button2.pack()

    def _browsefile(self, directory):
        answer = tk.filedialog.askdirectory()
        self.gui_variables[directory] = answer

if __name__ == '__main__':
    root = tk.Tk()
    View(root)
    root.mainloop()


texts: Given a path to a directory, print the path to the biggest file in it

texts:
Here is my code. I simulated a stack rather than used some regular recursive algorithm because I needed to keep track of two variables: the path to the biggest file and its size. Besides I wrote a few tests.

My solution on Github.

DirectoryIterator.java

import java.io.File;
import java.util.ArrayDeque;
import java.util.Deque;

public class DirectoryIterator {

    private DirectoryIterator() {
        throw new AssertionError();
    }

    public static String getLargestFilePath(File initPath) {
        if (initPath == null) {
            throw new IllegalArgumentException("The init path cannot be null");
        }
        long maxFileLength = 0;
        String maxFilePath = null;
        Deque<File> stack = new ArrayDeque<>();
        stack.push(initPath);
        while (!stack.isEmpty()) {
            File current = stack.pop();
            if (current.isDirectory()) {
                File[] files = current.listFiles();
                if (files != null) {
                    for (File file : files) {
                        stack.push(file);
                    }
                }
            } else if (current.length() > maxFileLength) {
                maxFileLength = current.length();
                maxFilePath = current.getAbsolutePath();
            }
        }
        return maxFilePath;
    }

}

DirectoryIteratorTest.java

import org.junit.Assert;
import org.junit.Test;

import java.io.File;

public class DirectoryIteratorTest {

    private String mTestDir = "C:\\Users\\Maksim\\Downloads\\Test" + File.separatorChar;

    @Test
    public void singleFileIsInit() {
        File initPath = new File(mTestDir + "Android_Accelerometer.png");
        Assert.assertEquals(initPath.getAbsolutePath(), DirectoryIterator.getLargestFilePath(initPath));
    }

    @Test
    public void onlyDirs() {
        File initPath = new File(mTestDir + "only_dirs");
        Assert.assertEquals(null, DirectoryIterator.getLargestFilePath(initPath));
    }

    @Test(expected = IllegalArgumentException.class)
    public void nullPath() {
        Assert.assertEquals(null, DirectoryIterator.getLargestFilePath(null));
    }

    @Test
    public void emptyPath() {
        File initPath = new File("");
        Assert.assertEquals(null, DirectoryIterator.getLargestFilePath(initPath));
    }

    @Test
    public void manyFiles() {
        File initPath = new File("C:\\Users\\Maksim\\Google Drive");
        Assert.assertEquals("C:\\Users\\Maksim\\Google Drive\\Career\\TODO\\AnDevCon Boston 2015.zip", DirectoryIterator.getLargestFilePath(initPath));
    }
}


texts: Wrapper that accepts both scalar and collection

texts:
Can I somehow refactor this into one class? Some things are common here like Metadata property.

public class Resource<TEntity>
{
    public TEntity Data { get; set; }

    public Dictionary<string, string> Metadata { get; set; }

    public Resource(TEntity data)
    {
        Data = data;
    }
}

public class ResourceCollection<TEntity>
{
    public ICollection<TEntity> Data { get; set; }

    public Dictionary<string, string> Metadata { get; set; }

    public int Count { get; set; }

    public ResourceCollection(ICollection<TEntity> data)
    {
        Data = data;

        Count = data.Count;
    }
}

Is this possible to make interface that expects either ICollection<TEntity> or TEntity alone?

This wrapper class is used for serialization it simply acts as a wrapper, but still I have some doubts about it that it could be done better

I also came up with this:

public class Resource<T>
{
    public T Data { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();

    public Resource(T data)
    {
        Data = data;

        if (data is ICollection collection)
        {
            Metadata["count"] = collection.Count;
        }
    }
}


texts:
I've used encountered this exercise from a tutorial:

  Create a function that takes a string as a parameter and returns True if the initial word of the string passed is an article (“The”, “A”, “An”) and returns False if it isn't an article.

  Be careful, if the string starts with “There”, it does not start with an article.

I have written the following code for it:

def startsWithArticle(str):
    '''Return True if the first word of str is "The", "A" or "An"'''

    if(str.startswith("The") and str.find(' ')==3):
        return True
    elif(str.startswith("An") and str.find(' ')==2):
        return True
    elif(str.startswith("A") and str.find(' ')==1):
        return True

    return False

which works as expected. I tested it using:

print('"A boy" returned', startsWithArticle("A boy"))
print('"An apple" returned', startsWithArticle("An apple"))
print('"The cat" returned', startsWithArticle("The cat"))
print('"Abyss" returned', startsWithArticle("Abyss"))
print('"There" returned', startsWithArticle("There"))
print('"Ant" returned', startsWithArticle("Ant"))

and this gave the expected output:

"A boy" returned True
"An apple" returned True
"The cat" returned True
"Abyss" returned False
"There" returned False
"Ant" returned False

Is there anything to improve in the function? Do note that I'm a beginner in python. BTW, I'm using python 3.4.3


texts: Find index of lowest unique integer in each line of the file

texts:
The code below finds the index of the lowest unique integer on each line of the file. The numbering starts at 1, and when there's no unique value, the 0 should be output.

The sample input looks like this:

3 3 9 1 6 5 8 1 5 3
9 2 9 9 1 8 8 8 2 1 1

And the sample output is this:

5
0

I wonder if this code can be simplified or made more elegant and idiomatic in any way. It's also interesting to me, could I get by w/o the IntMap and solve the problem with i.e. lists beautifully.

module Main where

import Prelude hiding (filter)
import Control.Applicative ((<$>))
import Data.IntMap (IntMap, alter, empty, filter, findMin, fromList, size)

import System.Environment

counts :: [(Int, Int)] -> IntMap [Int]
counts = foldl f empty
  where f m (i,v) = alter f' v m
          where f' :: Maybe [Int] -> Maybe [Int]
                f' (Just is) = Just (i:is)
                f' (Nothing) = Just [i]

g :: IntMap [Int] -> Int
g a = i
  where rs = filter ((== 1) . length) a
        h m | size m == 0 = fromList [(0, [0])]
            | otherwise = m
        (_, [i]) = findMin $ h rs

minUnique :: [Int] -> Int
minUnique l = g r
  where r = counts (zip [1..] l)

main =
  head <$> getArgs >>= readFile >>=
    putStrLn . unlines . map (show . minUnique . map read . words) . lines


texts: Polymorphic animals speak their name and make a noise

texts:
I'm new to GNU Smalltalk. I'd like to port a script I've written in Ruby, Scala, CoffeeScript, and several others. It's the one I use to try to learn the classic OOP concepts of abstract classes, abstract methods, overriding, dispatch, etc. It goes like this:

Define an abstract class Animal with a constructor to set the animal's name, a speak method to return a string N says S where N is the name and S is the sound the animal makes.
Define three concrete subclasses Horse, Cow, and Sheep, each with their own sound-returning string method.
Create a horse and sheep and a cow, and make them speak. For the horse and cow, create a variable. For the sheep, call the speak method on an "anonymous" object.

My GNU Smalltalk solution is:

Object subclass: Animal [
    | name |
    Animal class >> new: n [^super new init: n]
    init: n [name := n]
    speak [^name, ' says ', self sound]
]

Animal subclass: Horse [
    sound [^'neigh']
]

Animal subclass: Sheep [
    sound [^'baaaa']
]

Animal subclass: Cow [
    sound [^'moooo']
]

h := Horse new: 'CJ'.
h speak displayNl.
c := Cow new: 'Bessie'.
c speak displayNl.
(Sheep new: 'Little Lamb') speak displayNl.

I get the expected output but I am unhappy with the solution. I'd appreciate input on:

The whole new and init thing. Is there a way to make it cleaner?
I noticed I did not have to override new or init in my subclasses; did the subclasses really inherit new? It is a classmethod and I don't know if it is inherited or not.
Are we supposed to give an implementation of new? I had heard this was not a good idea. I know from Ruby that you just define initialize and use the built-in new to automatically invoke the initialize instance method.
Is this GNU Smalltalk syntax I got from the GNU tutorial proper or is it an extension of some sort? Should this be written in a proper, "purer" Smalltalk style? I've seen some where there is an instanceVariables message.
I know Smalltalk has something called subclassResponsibility. Is it wise to declare the sound method in the Animal class (as an abstract method)?


texts: Find minimum and maximum coordinates for a set of points

texts:
I wrote the Python3 code below. This is actually a stripped down version of a bigger project, but in essence it boils down to this code. There are two classes: Point, which is a point in 3D space and PointCloud, which is a sequence (list) of points.

In the PointCloud class, I have a method to calculate the minimum and maximum values for each axis: minmax_coords, which returns a dict (keys: the axes 'x', 'y', 'z') of a dict (keys: 'min' and 'max'). So you can do: somepointcloud.minmax_coords()['x']['min'] for the minimal x-axis value.

As it is, the code doesn't feel very pythonic and isn't really self-explanatory.

My question is: please review the code of the minmax_coord method and give me some suggestions how to refactor the code to make it more pythonic and more self explanatory.

Any suggestions to improve the code are welcome.

Repl link to the code.

class Point:
    """ Point with coordinate """
    def __init__(self, coordinate=None):
        """ Constructor """
        self.coordinate = coordinate

class PointCloud:
    """ A cloud (list) of Points """
    def __init__(self, point_list=None):
        """ Constructor """
        self.points = point_list

    def minmax_coords(self):
        """ Return minimum and mainum coordinate for each axis """
        if not self.points:
            raise IndexError("PointCloud has no Points.")

        result = {'x': {}, 'y': {}, 'z': {}}
        for i, axis in zip(range(3), ['x', 'y', 'z']):
            result[axis]['min'] = self.points[0].coordinate[i]
            result[axis]['max'] = self.points[0].coordinate[i]

        for point in self.points:
            for i, axis in zip(range(3), ['x', 'y', 'z']):
                result[axis]['min'] = min(result[axis]['min'],
                                          point.coordinate[i])
                result[axis]['max'] = max(result[axis]['max'],
                                          point.coordinate[i])

        return result

if __name__ == "__main__":
    P = PointCloud([Point((1, 2, 3)), Point((5, 4, 3))])
    print(f"Minimum and maximum coordinates: {P.minmax_coords()}")


texts: Hanging semicolons in multiline statements

texts:
I'm writing code to do line printing to a template -- counting characters to box A, then to box B, etc. -- and as such, it's not very modular. There are a lot of (long) variable names and each statement, which adds to the string to be printed, is pretty long.

So I've been breaking up the statements across multiple lines. But I don't know how I should be indenting it or where I should put the semicolon.

Here's a sample line:

$rbt .= "\n"
    . str_repeat(" ", $rbtSt_billToBox_leadingWidth)
    . padBothAndTruncate($statementInfoArray['bill-to-addr1'], $rbtSt_billToBox_addr_maxWidth)
    . str_repeat(" ", $rbtSt_billToBox_innerMargin)
    . substr($statementInfoArray['bill-to-code'], 0, $rbtSt_billToBox_acctNum_maxWidth)
;

I like how the concat operators are lined up and how it looks bracketed, but the naked semicolon on the following line makes me a little nervous. Putting it at the end of the line makes me even more nervous, since then it's hard to see.

It gets a little trickier when there's more nesting.

$rbt .= "\n"
    . str_repeat(" ", $rbtSt_billToBox_leadingWidth)
    . padBothAndTruncate(
        $statementInfoArray['bill-to-city'] . ", " . $statementInfoArray['bill-to-state']
            . " " . $statementInfoArray['bill-to-zip']
    )
;

Do I always do multiple lines? Just when it is more than a certain number of characters (say, 120)? Once a statement is multiline, should I only have one operator per line?

I'm feeling a bit paralyzed by choices here and I fear that none of them are very good.


texts: Count the frequency of words in a text file

texts:
#!/usr/bin/python
file=open("C:/python27/python operators.txt","r+")

wordcount={}

for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1

for k,v in wordcount.items():
    print k, v


texts: Find all row combinations which sum elements equal to any given number

texts:
It works fine, but it is slow.

Could anybody help make this faster?

import itertools

from decorators import timer
from settings import MENU, CASH

class Cocktail(object):
    def __init__(self, group, name, sell, count=0):
        self.group = group
        self.name = name
        self.sell = sell
        self.count = count

class Check(object):
    def __init__(self, cash, menu=MENU):
        self.__cash = cash
        self.__cheapest_cocktail = 10000
        self.__menu = self.__read_menu(menu)
        self.__matrix = self.__create_matrix()
        self.correct = []

    def __read_menu(self, menu):
        result = []
        for group in menu:
            key = group.keys()[0]
            for cocktail in group[key]:
                if self.__cheapest_cocktail > cocktail['sell']:
                    self.__cheapest_cocktail = cocktail['sell']

                result.append(Cocktail(
                    key,
                    cocktail['name'],
                    cocktail['sell'],
                ))

        return result

    def __create_matrix(self):
        result = []
        max_count = self.__cash // self.__cheapest_cocktail
        for cocktail in self.__menu:
            row = []
            for i in range(0, max_count):
                row.append(Cocktail(
                    cocktail.group,
                    cocktail.name,
                    cocktail.sell,
                    i
                ))

            result.append(row)
        return result

    def find_combinations(self):
        for check in itertools.product(*self.__matrix):
            if sum([(c.sell * c.count) for c in check]) == self.__cash:
                self.correct.append(check)

check = Check(CASH)
check.find_combinations()
check.__matrix size 80x25


texts: Removing untagged docker images using Python

texts:
I have written a piece of code in Python for removing the docker images which are not tagged only:

# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
release             3.1                 b6bf9d19cc6c        5 hours ago         869MB
release             3.2                 b6bf9d19cc6c        5 hours ago         869MB
<none>              <none>              3dfdfcb0769d        6 hours ago         433MB
<none>              <none>              d505190470fd        6 hours ago         433MB
<none>              <none>              979a42368814        7 hours ago         433MB
<none>              <none>              f8bcf895ffce        7 hours ago         433MB
<none>              <none>              8c1ed97822da        7 hours ago         433MB
release             1.0                 36e9ea407082        7 hours ago         433MB
ubuntu              16.04               6a2f32de169d        6 days ago          117MB
vault               latest              144fecac962b        3 weeks ago         64.4MB

Python code:

import subprocess

output = subprocess.Popen(["docker", "images"], stdout=subprocess.PIPE)

result = output.communicate()[0].split("\n")
image_list = []

for line in result[1:]:

    if ("<none>" == line.split("  ")[0]):
        image_list.append(filter(None,line.split("  "))[2])

for image in image_list:
     #Piping both stdout and stderr to stdout.
     output = subprocess.Popen(["docker", "rmi", "-f", image], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
     print(output.communicate()[0])

Final output:

docker images

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
release             3.1                 b6bf9d19cc6c        5 hours ago         869MB
release             3.2                 b6bf9d19cc6c        5 hours ago         869MB
release             1.0                 36e9ea407082        7 hours ago         433MB
ubuntu              16.04               6a2f32de169d        6 days ago          117MB
vault               latest              144fecac962b        3 weeks ago         64.4MB

Please let me know if the code can be optimized or can be written in a more pythonic way.


texts: Javascript querystring to object conversion

texts:
The below code converts the window.location.search querystring into a JavaScript object. In particular, if a key occurs more than once the resulting value in the object will be an array. Please feel free to comment on both readability and speed of execution. Thanks!

window.location.search.split(/[?&]/g).reduce(function (prev, cur, idx, arr) {
    var segment = cur.split("="),
        key = segment[0],
        val = segment[1];
    if (prev[key]) {
        if (prev[key] instanceof Array) {
            prev[key].push(val);
        } else {
            prev[key] = [prev[key], val];
        }
    } else {
        prev[key] = val;
    }
    return prev;
}, { });


texts: Building session-variables from a SQL stored procedure

texts:
Calling code and attempt at building session variables:

DataTable dtServerVars = clCommonFunctions.TryAutoLogin("europe\\MrTest");
Session["CablingUserID"]= dtServerVars.Rows[0]["CablingUserID"].ToString();
Session["CablingUseremail"] = dtServerVars.Rows[0]["CablingUseremail"].ToString();
Session["CablingLogin"] = dtServerVars.Rows[0]["CablingLogin"].ToString();
Session["CablingPassword"] = dtServerVars.Rows[0]["CablingPassword"].ToString();
Session["CablingPersonnel"] = dtServerVars.Rows[0]["CablingPersonnel"].ToString();
Session["CablingSurname"] = dtServerVars.Rows[0]["CablingSurname"].ToString();
Session["CablingFirstName"] = dtServerVars.Rows[0]["CablingFirstName"].ToString();
Session["CablingSuperUser"] = dtServerVars.Rows[0]["CablingSuperUser"].ToString();
Session["CablingDateAdded"] = dtServerVars.Rows[0]["CablingDateAdded"].ToString();
Session["CablingContact"] = dtServerVars.Rows[0]["CablingContact"].ToString();
Session["CablingApprovalAuthority"] = dtServerVars.Rows[0]["CablingApprovalAuthority"].ToString();
Session["CablingAdminUser"] = dtServerVars.Rows[0]["CablingAdminUser"].ToString();
Session["SharedInfoID"] = dtServerVars.Rows[0]["SharedInfoID"].ToString();
Session["SharedInfousername"] = dtServerVars.Rows[0]["SharedInfousername"].ToString();
Session["SharedInfopassword"] = dtServerVars.Rows[0]["SharedInfopassword"].ToString();
Session["SharedInfoname"] = dtServerVars.Rows[0]["SharedInfoname"].ToString();
Session["SharedInfoemail"] = dtServerVars.Rows[0]["SharedInfoemail"].ToString();
Session["SharedInfoICLlocation"] = dtServerVars.Rows[0]["SharedInfoID"].ToString();
Session["SharedInfoPhone"] = dtServerVars.Rows[0]["SharedInfoPhone"].ToString();
Session["SharedInfoSecLevel"] = dtServerVars.Rows[0]["SharedInfoSecLevel"].ToString();
Session["IMSUserID"] = dtServerVars.Rows[0]["IMSUserID"].ToString();
Session["IMSUserName"] = dtServerVars.Rows[0]["IMSUserName"].ToString();
Session["IMSIsAnonymous"] = dtServerVars.Rows[0]["IMSIsAnonymous"].ToString();
Session["IMSLastActivityDate"] = dtServerVars.Rows[0]["IMSLastActivityDate"].ToString();
Session["loggedin"] = "unknown";

Code being called:

public static DataTable TryAutoLogin(string strREMOTE_USER)
{
    SqlConnection siConnection = new SqlConnection();
    siConnection.ConnectionString = Databases.getDbConnectionString("csSharedInfo");
    siConnection.Open();
    SqlCommand seCmd = new SqlCommand("GetSignOnDetails", siConnection);
    seCmd.CommandType = CommandType.StoredProcedure;
    seCmd.Parameters.Add(new SqlParameter("@DomainAccount", SqlDbType.NVarChar, 300));
    seCmd.Parameters["@DomainAccount"].Value = strREMOTE_USER;
    seCmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter sda = new SqlDataAdapter();
    seCmd.Connection = siConnection;
    sda.SelectCommand = seCmd;
    DataTable dtServerVars = new DataTable();
    sda.Fill(dtServerVars);
    siConnection.Close();
    if (dtServerVars != null)
    {
        if (dtServerVars.Rows.Count > 0)
    {
        return dtServerVars;
    }
}
    return null;
}


texts:
I have a list of palindromes

List<string> palindromes = new List<string>()
{
    hijkllkjih,
    ijkllkji,
    jkllkj,
    kllk,
    ll,
    defggfed,
    efggfe,
    fggf,
    gg,
    abccba,
    bccb,
    cc,
    qrrq,
    rr,
    mnnm,
    nn,
    pop,
    o,
    s,
    q,
    r
};

But I want to remove palindromes that are substring of other palindromes. So, the list would become

List<string> palindromes = new List<string>()
{
    hijkllkjih,
    defggfed,
    abccba,
    qrrq,
    mnnm,
    pop,
    s,
    q,
    r
};

To do this I have written the following code

List<int> indexList = new List<int>();
for (int i = 0; i < palindromes.Count; ++i)
{
    if (indexList.Contains(i))
        continue;

    string tmp = palindromes[i];
    for (int j = 0; j < palindromes.Count; ++j)
    {
        if (i == j
            || indexList.Contains(j)
            || palindromes[j].Length > palindromes[i].Length)
            continue;

        if (tmp.Contains(palindromes[j]))
            indexList.Add(j);
    }
}

foreach (var index in indexList.OrderByDescending(l => l))
    palindromes.RemoveAt(index);

Can this be improved?


texts:
I made a very simple OS in Assembly. But my code is too long. I want to make my code shorter.
Here is my code:
    BITS 16

start:
    mov ax, 07C0h
    add ax, 288
    mov ss, ax
    mov sp, 4096

    mov ax, 07C0h
    mov ds, ax

    mov si, text_string
    call print_string

    jmp $

    text_string db 'OS', 0

print_string:
    mov ah, 0Eh

.repeat:
    lodsb
    cmp al, 0
    je .done
    int 10h
    jmp .repeat

.done:
    ret

    times 510-($-$$) db 0
    dw 0xAA55

Makefile:
DIR=build build
$(shell mkdir -p $(DIR))
$(shell nasm -f bin OS1.asm -o build/OS1.flp)
$(shell mkisofs -no-emul-boot -o build/OS1.iso -b OS1.flp build)

Can I make this code shorter? Is it possible to do? If it is, how?
(This code may be updated in my GitHub account.)