texts: subprocess with logging module: tee with StringIO

texts:
I've got a long-running process. Once it finishes I need the output. But the user should be informed while it's running. With the logging module I get timestamps and whatnot preceding. So let's combine all 3:

Prelude:

import os
import logging
import subprocess

from io import IOBase
from sys import stdout
from select import select
from threading import Thread
from time import sleep

from cStringIO import StringIO

Init:

# Some other file, like __init__.py
logging.basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    level='INFO')
handler = logging.root.handlers.pop()
assert logging.root.handlers == [], "root logging handlers aren't empty"
handler.stream.close()
handler.stream = stdout
logging.root.addHandler(handler)
# Some other file, like __init__.py

log = logging.getLogger(__name__)

Class (based on https://stackoverflow.com/a/4838875):

class StreamLogger(IOBase, logging.Handler):
    _run = None
    def __init__(self, logger_obj, level):
        super(StreamLogger, self).__init__()
        self.logger_obj = logger_obj
        self.level = level
        self.pipe = os.pipe()
        self.thread = Thread(target=self._flusher)
        self.thread.start()
    def __call__(self):
        return self
    def _flusher(self):
        self._run = True
        buf = b''
        while self._run:
            for fh in select([self.pipe[0]], [], [], 1)[0]:
                buf += os.read(fh, 1024)
                while b'\n' in buf:
                    data, buf = buf.split(b'\n', 1)
                    self.write(data.decode())
        self._run = None
    def write(self, data):
        return self.logger_obj.log(self.level, data)
    emit = write

    def fileno(self):
        return self.pipe[1]
    def close(self):
        if self._run:
            self._run = False
            while self._run is not None:
                sleep(1)
            for pipe in self.pipe:
                os.close(pipe)
            self.thread.join(1)

Filtering class (based on https://stackoverflow.com/a/41328542):

class LevelRangeFilter(logging.Filter):
    def __init__(self, min_level, max_level, name=''):
        super(LevelRangeFilter, self).__init__(name)
        self._min_level = min_level
        self._max_level = max_level

    def filter(self, record):
        return super(LevelRangeFilter, self).filter(record) and (
            self._min_level is None or self._min_level <= record.levelno) and (
                   self._max_level is None or record.levelno < self._max_level)

Usage:

stderr_stream = logging.StreamHandler(StringIO())
stderr_stream.addFilter(LevelRangeFilter(logging.ERROR, None))
log.addHandler(stderr_stream)
log.setLevel(logging.ERROR)

stdout_stream = logging.StreamHandler(StringIO())
stdout_stream.addFilter(LevelRangeFilter(logging.INFO, logging.ERROR))
log.addHandler(stdout_stream)
log.setLevel(logging.INFO)

with StreamLogger(log, logging.INFO) as out, StreamLogger(log,
                                                          logging.ERROR) as err:
    subprocess.Popen('ls', stdout=out, stderr=err, shell=True)

print 'stderr_tee =', stderr_tee.stream.getvalue()
print 'stdout_tee =', stdout_tee.stream.getvalue()

With a cleanup like so:

# finally block
for handler in log.handlers:
    log.removeHandler(handler)
    handler.stream.close()
    handler.close()
stderr_tee.stream.close()
stdout_tee.stream.close()


texts: Adding/changing ID3 tags to media files with "artist - title" format

texts:
This code puts or changes ID3 tags to media files based on their file names. It assumes the files are in this format:

morbid angel - maze of torment.mp3

The resulting tag would be:

Artist: morbid angel

Title: maze of torment

I use boost::filesystem to iterate through the directory and taglib to manipulate the tags.
#include <boost/filesystem.hpp>
#define TAGLIB_STATIC
#include <taglib/fileref.h>
#include <iostream>
#include <string>
#include <vector>

using namespace boost::filesystem;
using namespace TagLib;

void changeTag(const path& p) {
    std::string filename = p.filename().string();
    FileRef file(p.string().c_str());
    std::string artist = filename.substr(0,filename.find(" -"));
    Tag* t = file.tag();
    t->setArtist(artist);
    t->setTitle(filename.substr(artist.size()+3, filename.size()-artist.size()-7));
    file.save();
    std::cout << t->artist() << " - " << t->title() << " saved" << '\n';
}

void extractFiles(const std::string& p) {
    std::vector<path> files;
    std::vector<std::string> errors; // for files that might cause errors
    try {
        path filepath = p;
        for (auto& i : directory_iterator(filepath)) {
            changeTag(i.path());
        }
    } catch(const filesystem_error& e) {
        errors.push_back(e.what()); // output later after all files have been processed
    }
    if (errors.size() > 0) {
        std::cout << "Some operations failed with errors:" << '\n';
        for (auto& i : errors) {
            std::cout << i << '\n';
        }
    }
}

int main() {
    std::string dir;
    while (true) {
        std::cout << "Directory: Enter 'x' to close: ";
        std::cin >> dir;
        if (dir == "x") {
            break;
        }
        extractFiles(dir);
    }
}

How can I improve this code? How can I make this faster, cleaner and better?


texts: Get Users and related roles and show on View

texts:
I have 3 tables. Users, Roles and RolesToUsers

Here is User model:

public partial class User
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public User()
    {
        this.UserToRoles = new HashSet<UserToRole>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserToRole> UserToRoles { get; set; }
}

Here is Role Model:

public partial class Role
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Role()
    {
        this.UserToRoles = new HashSet<UserToRole>();
    }

    [Key]
    public int Id { get; set; }
    public string RoleName { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserToRole> UserToRoles { get; set; }
}

And here is UserToRole model:

public partial class UserToRole
{
    [Key]
    public int Id { get; set; }
    [ForeignKey("Role")]
    public Nullable<int> RoleId { get; set; }
    [ForeignKey("User")]
    public Nullable<int> UserId { get; set; }

    public virtual Role Role { get; set; }
    public virtual User User { get; set; }
}

I need to show all Users and related to it Roles.

I write this repo method

public List<UserViewModel> GetUsers()
{
    var users = db.Users
        .Include(u => u.UserToRoles.Select(ur => ur.Role))
        .Select(u => new UserViewModel
        {
            UserName = u.Name,
            Roles = u.UserToRoles.Select(ur => ur.Role.Name)
        })
        .ToList();

    return users;
}

After it I need to show data from database in this format Ronald - Admin,User, where Ronald,etc is Name of Users, after - is Roles related to user.

Repo method is working great

And in View I show it using this code.

function GetUsers() {
let url = "/Home/GetUsers";
$.ajax({
    type: 'GET',
    url: url,
    dataType: 'json',
    success: function (data) {
        var separator = "";
        for (var i = 0; i < data.length; ++i) {
            var userRow = data[i].UserName + " - " + data[i].Roles.join(", ");

            $('#taskresult3').append(separator + userRow);
            separator = ",";
        }
    }
});

Any suggestions or improvements I can do to this code?


texts: Reach C++ policy-based common interface with different template parameters from one container

texts:
Please review my solution for the following problem. I am interested in:

What do you think of the design
Improvement tips
Usability
Efficiency

Problem: Need to be store policy-based objects with different template parameters in one container, and reach the common interface.

Solution:
C++ Shell

#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class SinglePolicy
{
public:
    SinglePolicy() = default;

    void push(int data)
    {
        std::cout << "set to SinglePolicy\n";
        buffer_ = data;
    }

    int pop()
    {
        std::cout << "return from SinglePolicy\n";
        int data = buffer_;

        buffer_ = -1;

        return data;
    }

protected:
    int buffer_;
};

class VectorPolicy
{
public:
    VectorPolicy() = default;

    virtual void push(int data)
    {
        std::cout << "emplace_back to VectorPolicy\n";
        buffer_.emplace_back(data);
    }

    virtual int pop()
    {
        std::cout << "pop front from VectorPolicy\n";
        if(buffer_.empty())
            return -1;

        int data = buffer_[0];
        buffer_.erase(buffer_.begin());

        return data;
    }

protected:
    std::vector<int> buffer_;
};

template<class BufferPolicy>
class PolicyBasedBuffer
        : public BufferPolicy
{
public:
    PolicyBasedBuffer()
        : BufferPolicy()
    {}
};

typedef std::shared_ptr<PolicyBasedBuffer<SinglePolicy>> SinglePolicyPtr;
typedef std::shared_ptr<PolicyBasedBuffer<VectorPolicy>> VectorPolicyPtr;

class PolicyInterface
{
public:
    PolicyInterface(const std::function<void(int)>& pushArg, const std::function<int(void)>& popArg)
        : push(pushArg)
        , pop(popArg)
    {}

    const std::function<void(int)> push;
    const std::function<int(void)> pop;
};

typedef std::shared_ptr<PolicyInterface> PolicyInterfacePtr;

PolicyInterfacePtr saveToPolicyInterface(const SinglePolicyPtr& aPolicy)
{
    return std::make_shared<PolicyInterface>([aPolicy](int data) { aPolicy->push(data); }, [aPolicy]() { return aPolicy->pop(); });
}

PolicyInterfacePtr saveToPolicyInterface(const VectorPolicyPtr& aPolicy)
{
    return std::make_shared<PolicyInterface>([aPolicy](int data) { aPolicy->push(data); }, [aPolicy]() { return aPolicy->pop(); });
}

int main()
{
    auto singleBuffer = std::make_shared<PolicyBasedBuffer<SinglePolicy>>();
    auto vectorBuffer = std::make_shared<PolicyBasedBuffer<VectorPolicy>>();

    const int seven = 7;

    std::cout << "PolicyBasedBuffer test:\n";
    singleBuffer->push(seven);
    if(seven != singleBuffer->pop())
        throw std::runtime_error("SinglePolicy :: wrong return data");

    vectorBuffer->push(seven);
    if(seven != vectorBuffer->pop())
        throw std::runtime_error("VectorPolicy :: wrong return data");

    std::vector<PolicyInterfacePtr> policy;

    policy.push_back(saveToPolicyInterface(std::make_shared<PolicyBasedBuffer<SinglePolicy>>()));
    policy.push_back(saveToPolicyInterface(std::make_shared<PolicyBasedBuffer<VectorPolicy>>()));

    std::cout << "\nPolicyInterface test:\n";

    for(size_t i=0; i < policy.size(); ++i)
    {
        policy[i]->push(seven);
        if(seven != policy[i]->pop())
            throw std::runtime_error("policyInterface :: wrong return data");
    }

    std::cout << std::flush;
}


texts:
I tried to implement the builder pattern of GoF. After searching for almost every related posts/examples on the Internet, I'm still confused. But I found that there are two kinds of patterns, which are both called builder:

Bloch Builder : A famous post, but a comment pointed out it's actually a fluent interface, still useful, though. Also notice that it's not the same as Method Chaining, see the differences.
Builder Pattern @thejavageek.com : The author gives a very clear structure of Builder Pattern: Director, Builder, ConcreteBuilder, Product.

Finally I decide to make my own version of "Builder Pattern", which follows the first link above, with some modifications:

The static method Pizza.makePizza() acts as the Director.
For simplicity, I didn't make the Factory a factory method or abstract factory, but it can be without problem.
Before you want to make a pizza, you have to override some methods, which you can put anything must be done before the pizza is created.

Main.java

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Factory myFactory = new Factory();

        Pizza myPizza = Pizza.makePizza(new Pizza.Builder(myFactory) {
            @Override
            public void prepareDough() {
                myFactory.prepareDough();
            }

            @Override
            public void prepareToppings() {
                myFactory.prepareToppings();
            }
        }.withSize(20).withBacon().withPepperoni());

        System.out.println(myPizza);
    }
}

Pizza.java

public class Pizza {
    private final int size;
    private final boolean cheese;
    private final boolean pepperoni;
    private final boolean bacon;

    private Pizza(Builder builder) {
        size = builder.size;
        cheese = builder.cheese;
        pepperoni = builder.pepperoni;
        bacon = builder.bacon;
    }

    public static Pizza makePizza(Builder builder) throws InterruptedException {
        builder.prepareDough();
        Thread.sleep(2000);
        builder.prepareToppings();
        Thread.sleep(2000);
        return new Pizza(builder);
    }

    public static abstract class Builder {
        private int size;
        private boolean cheese = false;
        private boolean pepperoni = false;
        private boolean bacon = false;

        public Builder(Factory factory) {
        }

        public Builder withSize(int size) {
            this.size = size;
            return this;
        }

        public Builder withCheese() {
            cheese = true;
            return this;
        }

        public Builder withPepperoni() {
            pepperoni = true;
            return this;
        }

        public Builder withBacon() {
            bacon = true;
            return this;
        }

        protected abstract void prepareDough();
        protected abstract void prepareToppings();
    }

    public String toString() {
        return String.format("pizza={size=%d, cheese=%s, pepperoni=%s, bacon=%s}",
            size,
            cheese,
            pepperoni,
            bacon);
    }
}

Factory.java

public class Factory {
    public Factory() {}

    public void prepareDough() {
        System.out.println("Preparing dough...");
    }

    public void prepareToppings() {
        System.out.println("Preparing toppings...");
    }
}

Result:

Preparing dough...
Preparing toppings...
pizza={size=20, cheese=false, pepperoni=true, bacon=true}


texts: Putting thread in sleep while waiting for BroadcastReceiver

texts:
I'm a little puzzled about a procedure inside my Android app. It's actually working but it looks like bad practice and probably it lowers performances.

Short explanation: I'm running a separate Thread inside a Service. Inside the thread I fetch a list of files and the main purpose of the thread is to query the file to a different service that reads the file and answers back to the thread with the file content through a BroadcastReceiver, then the thread sends that content (with some edits, of course) to a different service that write it to the same file and waiting for it to finish, using a second BroadcastReceiver. Doing the same for all the files, one by one.

private class TagProcess extends Thread {

        private boolean tagSaved = false;

        TagProcess(Context context) {
            registerReceiver(mReadReceiver, new IntentFilter(TagReaderService.BROADCAST_CHANNEL_NAME));
            registerReceiver(mWriteReceiver, new IntentFilter(TagWriterService.BROADCAST_CHANNEL_NAME));
        }

        @Override
        public void run() {
            int result;
            do {
                result = scanNextSong();

                if(result == 1) {
                    while (!tagSaved) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } while ( result != -1);

            processTermination();
        }

        private int scanNextSong() {
            if (/* SOME RROOR*/) {
                return -1;
            }

            startService(/* READ SERVICE */);

            tagSaved = false;

            return 1;
        }

        private void processTermination() {
            stopSelf();
        }

        private BroadcastReceiver mWriteReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // Done writing

                tagSaved = true;
            }
        };

        private BroadcastReceiver mReadReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                if(/* SOME ERROR */) {
                    tagSaved = true;
                    return;
                }

                startService(/* START WRITING */);
            }
        };
    }

As I said, I think there's much room for improvement, but I could not end up with something better. My worry is that the BroadcastReceiver sends data back to the thread while it's sleeping so it might get lost. I didn't experience such an issue, but will it ever happen?
Note that I cannot edit those two external services and I do not want tasks to be concurrent.

Can you propose a better way of doing this?


texts: Non brute force algorithm for Birthday Chocolate

texts:
Problem: https://www.hackerrank.com/challenges/the-birthday-bar/problem

Lily has a chocolate bar that she wants to share it with Ron for his birthday. Each of the squares has an integer on it. She decides to share a contiguous segment of the bar selected such that the length of the segment matches Ron's birth month and the sum of the integers on the squares is equal to his birth day. You must determine how many ways she can divide the chocolate.

Function Description

It should return an integer denoting the number of ways Lily can divide the chocolate bar.

s: an array of integers, the numbers on each of the squares of chocolate
d: an integer, Ron's birth day
m: an integer, Ron's birth month

Print an integer denoting the total number of ways that Lily can portion her chocolate bar to share with Ron.

Example: Lily wants to give Ron  m =2 squares summing to d = 3. The following two segments meet the criteria:

Here is my brute force solution that enumerates all possibilities:

// Complete the birthday function below.
static int birthday(List<int> s, int d, int m) {
    int n = 0;
    for(int i = 0; i < s.Count; i++) {
        if(s.Skip(i).Take(m).Sum() == d)
            n++;
    }
    return n;
}

Question: any non brute-force solutions to this problem?


texts:
I'm interested in mimicking a simple version of Mathematica's Manipulate function in javascript. This is my first project in javascript, but I was hoping to make a library that I can use to quickly draw up several plots on several pages with manipulable parameters.

Here's what I came up with, using Plotly.js to draw the plots and jQuery UI for the sliders:

function Plotter(divName) {
    this.divName = divName;
    this.xMin = 0;
    this.xMax = Math.PI;
    this.xStep = Math.PI/100;
    this.xVals = range(this.xMin, this.xMax, this.xStep);
    this.params = [0, 0];
    this.yVals = [];
    this.layout = {};
}

Plotter.prototype = {
    constructor:Plotter,

    //creates the plot panel
    initializePlot: function() {
        Plotly.newPlot(this.divName, [{x:this.xVals, y:this.yVals}], this.layout);
    },

    //function that calculates y given x and parameters. This is hard-coded here, but ideally would be easily entered in the html page.
    yFunction(xVals, params) {
        var yVals = [];
        for (var ii = 0; ii < xVals.length; ii++) {
            yVals.push(params[0] * Math.sin(params[1] * xVals[ii]));
        }
        return yVals;
    },

    //keeps the plot panel, but refreshes the y values.
    refreshPlot: function() {
        this.yVals = this.yFunction(this.xVals, this.params);
        Plotly.restyle(this.divName, {y: [this.yVals]});
    }
}

//adds a slider to the element that controls a given parameter index
function addSlider(element, sliderName, paramIndex) {
     var slider = $("#" + sliderName).slider({
                orientation: "horizontal",
                value: element.params[paramIndex],
                min: 0, //the slider range is hard-coded for now, but should be set in the html page eventually.
                max: 3 * Math.PI,
                step: Math.PI/32,
                slide: function( event, ui ) {
                    //when the slider moves, the element parameters are updated and the panel is refresehd
                    element.params[paramIndex] = ui.value;
                    element.refreshPlot();
                }
        });
}

//Generate array of evenly spaced points, from:
//http://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-an-array-based-on-suppl
function range(start, stop, step){
    var a=[start], b=start;
    while(b<stop){b+=step;a.push(b)}
    return a;
};

Here is how I can implement a panel in HTML (after loading this library):

The good news is that I can add several manipulable panels to a page with relatively ease. I'd like to know:

am I following generally good practice in how I implement these functions?
what is a good way to assign a y-function to the plotter object from the HTML? For now, the y(x) is hard-coded while I get everything else working.

Thanks for your help.


texts: Clojure macro to gather functions in a namespace into a map

texts:
I'm learning Clojure via a pet project. The project would consist of several workers that would be called from other functions.

Each worker is defined in their own namespace as a set of functions (currently two: get-data for gathering data and write-data for writing the gathered data into a file).

In order to make the code a bit DRYer, I decided to write a macro that would gather functions from namespace into a map that can be passed around:

(ns clojure-bgproc.workers)

(defmacro gen-worker-info []
  (let [get-data (ns-resolve *ns* 'get-data)
        write-data (ns-resolve *ns* 'write-data)]
    `(def ~(quote worker-info)
       {:get-data ~get-data
        :write-data ~write-data}
       )
    )
  )

In my worker code, I use my macro (code abridged for clarity):

(ns clojure-bgproc.workers.summary
  (:require [clojure-bgproc.workers :refer [gen-worker-info]]))

(defn get-data [params]
  <...>
  )

(defn write-data [data file]
  ;; <...>
  )

(gen-worker-info)

While it does work (I get my get-data and write-data functions in clojure-bgproc.workers.summary/worker-info, I find it a bit icky, especially since, if I move the macro call to the top of the file, it doesn't work.

My question is, is there a more idiomatic way to do so? Is this idiomatic Clojure at all?

P. S. It looks like I haven't made my intentions quite clear, so I've decided to include a usage example:

(ns clojure-play.play-worker
  (:require [clojure.string :refer (join)])
  )

;; Those two workers will be pulled from other namespaces
(def worker1
  {:get-data (fn [] (take 10 (repeatedly #(int (rand 10)))))
   :write-data (fn [data] (join "," data))}
  )

(def worker2
  {:get-data (fn []
               (take 10 (repeatedly #(int (rand 50))))
               )
   :write-data (fn [data]
                 (join "\n" (map #(str "<row>" % "</row>") data))
                 )
   }
  )

(def workers
  {"worker1" worker1 "worker2" worker2}
  )

(defn -do-work [worker-name]
  (let [worker (workers worker-name)
        get-data (worker :get-data)
        write-data (worker :write-data)]
    (write-data (get-data))
    )
  )

(defn example []
  (println "Worker 1 results:")
  (println (-do-work "worker1"))
  (println)
  (println "Worker 2 results:")
  (println (-do-work "worker2"))
  )

When I run (example), this is what I get:

Worker 1 results:
5,9,6,2,4,6,0,0,7,0

Worker 2 results:
<row>9</row>
<row>26</row>
<row>42</row>
<row>37</row>
<row>1</row>
<row>38</row>
<row>0</row>
<row>31</row>
<row>10</row>
<row>35</row>


texts: Monkey patching extra events in Node.js HTTP/Express

texts:
This question is related to Express under Node.js.

Background

With Express, you stack up several "middleware" modules to handle a specific HTTP request.

app.use(express.logger());
app.use(express.favicon()));
app.use(express.cookieParser());
app.use(express.session());
app.use(app.router);

When a request comes in, Express goes through all of the functions in the stack until a module handles the request.  Specifically, each middleware module is a function (req, res, next), and that function will call next() to call the next module in the stack.  Functions can modify data in the req or res objects if they choose.

The Problem

I was interested in making custom log middleware modules for my Express application, and I needed to use more than one module at a time.  The data I need to log cannot be logged until the response has been sent to the client.  (I am tracking bytes sent, and the amount of time a connection was established.)  Unfortunately, Node.js's HTTP response object does not raise an end event.  Presumably, this is because it is up to the application to do any "end" work prior to calling .end() on the response object in the first place.  Express does not expose a hook prior to .end() being called.

Express/Connect's built-in logger middleware is able to track how long a request was running, so I decided to see what method they use.  They actually replace the res.end function with their own.  When their own res.end function is called, it swaps the old res.end back in place, finishes logging, then calls res.end with the parameters that their own res.end was called with.  Their method works, but can be problematic when a handful of modules try to do this.  (The order in which res.end function replacement occurs becomes critical.)

My Solution

I have used their method to patch res to fire end events so that any module in the chain can subscribe to that event in the usual way.

function (req, res, next) {
    var end = res.end;

    res.end = function () {
        res.end = end;
        res.emit('end');
        res.end.apply(this, arguments);
    }

    next();
}

Then, all my logger module has to do is:

res.on('end', function () { /* log here */ });

Is there any problem with what I have done?  Is there a better way to do it?


texts:
This program displays a list of TV characters. You can kill them off by random or bring them back by name. I have used the random.choice function. I've defined a couple of functions so that the while loop looks a little more clean. In two of the functions, bring_back and check_decision, we assign True to invalid_input if user input is invalid, like a flag.
This program is for learning purposes.
from random import choice

tv_characters = [
    'john', 'henry', 'maria', 'jason',
    'max', 'lara', 'gilbert', 'paris'
    ]

killed_tv_characters = []
valid_decision_input = ['kill off', 'bring back']

start_prompt = "Would you like to start (yes/no)?"
decision_prompt = "\nWould you like to bring back a character you killed?"
decision_prompt += "\nOr would you like to kill off another character?"
decision_prompt += "\nEnter 'kill off' or 'bring back' ->"
character_from_dead_prompt = "\nPlease enter the name of character you would like to bring back: "
confirm_kill_prompt = "\nEnter 'kill off' to kill your first character: "

def kill_tv_characters():
    """Kills a random tv character and displays the name on the screen."""
    if tv_characters:
        killed_tv_character = choice(tv_characters)
        tv_characters.remove(killed_tv_character)
        print(f"You have killed off {killed_tv_character.title()}")
        killed_tv_characters.append(killed_tv_character)
    else:
        print("You have killed off all the characters!")

def bring_back(name):
    """Brings back a dead character."""
    name = name.lower().strip()
    if name in killed_tv_characters:
        killed_tv_characters.remove(name)
        tv_characters.append(name)
        print(f"\nYou have brought {name.title()} back to life!")
    elif name in tv_characters:
        print(f"{name} isn't dead!")
        invalid_input = True
    else:
        print(f"{name} isn't a character!")
        invalid_input = True

def check_decision(user_input):
    """Checks user input for decision."""
    if user_input in valid_decision_input and user_input == 'kill off':
        return user_input
    elif user_input in valid_decision_input and user_input == 'bring back':
        return user_input
    else:
        invalid_input == True
        print("Please enter a valid input!")
print("\nYou can kill off characters randomly and add them back my name!")

start = input(start_prompt)
if start == 'yes':
    start = True
else:
    start = False

while tv_characters and start:
    invalid_input = None

    print("\nThese are the living TV characters:")
    for tv_character in tv_characters:
        print(tv_character.title())
    if killed_tv_characters:
        user_decision = input(decision_prompt)
        decision = check_decision(user_decision)
        if invalid_input:
            continue
        if decision == 'kill off':
            kill_tv_characters()
        if decision == 'bring back':
            character_from_dead = input(character_from_dead_prompt)
            bring_back(character_from_dead)
            if invalid_input:
                continue

    else:
        confirm_kill = input(confirm_kill_prompt)
        if confirm_kill != 'kill off':
            print("You have entered an invalid input.")
            continue
        kill_tv_characters()

if tv_characters == False:
    print("You have killed off all the characters.")
    print("Thanks for playing!")

else:
    print("Goodbye")


texts: Count number of occurrences of each word of text, display as circles of varying size

texts:
My focus was to have clean, structured code. It has to be efficient. The display doesn't have to look that good. The circles do overlap and sometimes the word doesn't fit inside the circle, but those are problems aren't really my concern right now and I will fix later.

circle.py

import pygame
import random

# Define the colors and screen sizes, define center

# Colors
black = (0, 0, 0)
blue = (0, 128, 255)
red = (255, 102, 102)
green = (102, 255, 178)
purple = (178, 102, 255)
yellow = (255, 255, 102)
colors = [blue, red, green, purple, yellow]
white = (255, 255, 255)

# Radius and font size
radius = [30, 40, 50, 60, 70, 80, 90, 100]

# Screen dimensions and title
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
CENTER = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)
TITLE = "Occurences"

# Actual screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# Initialize screen
pygame.display.set_caption(TITLE)
screen.fill(white)

class Circle:
    def __init__(self, size, text):
        rand_color = random.randint(0, 4)
        rand_x = random.randint(size+5, SCREEN_WIDTH-size)
        rand_y = random.randint(size+5, SCREEN_HEIGHT-size)

        self.x = rand_x
        self.y = rand_y
        self.size = size
        self.color = colors[rand_color]
        self.screen = screen
        self.text = text

    def display(self):
        pygame.draw.circle(self.screen, self.color, (self.x, self.y), self.size)

        myfont = pygame.font.SysFont("monospace", self.size-15, bold=True)
        label = myfont.render(self.text, 1, black)
        screen.blit(label, (self.x-self.size+10, self.y-20))

occurences.py

import pygame
from pygame.locals import *
import circle
import time
import re
from operator import itemgetter
from collections import Counter

# Intro
pygame.init()

intro_text = ["Hi!", "Welcome to 'occurences'!", "A program (with a misspelt name) that counts the number",
        "of occurrences in a piece of text", "and displays circles with sizes based on", "the number of occurrences of each word."]

for sentence in intro_text:
    print sentence
    time.sleep(2)

text =  raw_input("Enter some text:\n") # Prompt the user for text

# Action!!!

#word_count = Counter(words) # Count them
#sorted_count = word_count.most_common() # Sort the count
#sorted_copy = sorted_count[:] # A copy of the sorted count, just in case

# Here's a one liner for the code above.
words = Counter(re.findall(r"[\w']+", text.lower())).most_common() # Split words

while words: # While the list of words isn't empty,
    max_occ = max(words, key=itemgetter(1))[1] # Take current max occurrence of the list

    for word in words:

        if word[1] == max_occ: # If the current word's occurrence is same as the max occurrence
            curr_word = word

            if len(circle.radius) != 1:
                c = circle.Circle(circle.radius[-1], word[0]) # Draw a circle with the current largest size of circle.radius
                c.display() # Displaying the word on the circle
                circle.radius.pop() # Remove that current largest size
            else:
                c = circle.Circle(30, word[0]) # When there's only one size left (the smallest one), make all other words that size.
                c.display()

            words = [x for x in words if x != curr_word] # Change the list so that the words already dealt with are gone, making a new max_occ

pygame.display.flip()

# Event loop
running = 1
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = 0

pygame.display.update()


texts:
I would like to know if my Routing system respects the solid principle ?
The system is simple, Router class contains the routes and returns the correct route and Route class represents a route, contains a path and an action to call. Router takes the Request class as a parameter in its constructor to try to respect the solid principle.

https://en.wikipedia.org/wiki/SOLID
https://guillaume-richard.fr/principe-solid-simplifies-avec-des-exemples-en-php/
ETC...........

I would like to know what's good and what isn't.
class Router
{
    private $request;
    private $routes = [];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function get(string $path, string $action)
    {
        return $this->addRoute($path, $action, 'GET');
    }

    private function addRoute(string $path, string $action, string $method)
    {
        $route = new Route($path, $action);
        $this->routes[$method][] = $route;
        return $route;
    }

    public function run()
    {
        if(!isset($this->routes[$this->request->getMETHOD()])) {
            throw new RouterException('REQUEST_METHOD does not exist');
        }
        foreach ($this->routes[$this->request->getMETHOD()] as $route) {
            if ($route->match($this->request->getUri())) {
                return $route->call();
            }
        }
        throw new RouterException("La page demandée est introuvable.");
    }
}

class Route
{
    private $path;
    private $action;
    private $matches;
    private $parameters = [];

    public function __construct(string $path, string $action)
    {
        $this->path = trim($path, '/');
        $this->action = $action;
    }

    public function where(string $param, string $regex)
    {
        $this->parameters[$param] = str_replace('(', '(?:', $regex);
        return $this;
    }

    public function match(string $requestUri)
    {
        $requestUri = trim($requestUri, '/');
        $path = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], $this->path);
        $regex = "#^$path$#";
        if (preg_match($regex, $requestUri, $matches)) {
            array_shift($matches);
            $this->matches = $matches;
            return true;
        } else {
            return false;
        }
    }

    private function paramMatch(array $match)
    {
        if (isset($this->parameters[$match[1]])) {
            return '(' . $this->parameters[$match[1]] . ')';
        }
        return '([^/]+)';
    }

    public function call()
    {
        $parameters = explode('@', $this->action);
        $controller = "Src\\Controller\\" . $parameters[0];
        $controller = new $controller();
        $method = $parameters[1];
        return call_user_func_array([$controller, $method], $this->matches);
    }
}


texts:
I have a task to connect to S3 get a JSON file with the names of artists, use the youtube-data-api and search for the top 10 songs.
Then send it back in a given format to S3 back.

console.log("Loading up the best code ever!!!");

//packagess import
var fs = require('fs');
var AWS = require('aws-sdk');
var Singer = require('./Singer')

//prepare all the AWS S3 data
AWS.config.update({ region: "us-west-1" });
var credentials = new AWS.SharedIniFileCredentials();
AWS.config.credentials = credentials;
// Create S3 service object
s3 = new AWS.S3({ apiVersion: '2006-03-01' });

// Create the parameters for calling createBucket
var bucketParams = {
    Bucket: 'pc-backend-exercises',
    Key: 'toSearch.json',
    ResponseContentType: 'application/json'
};

/// prepare the youtube-data-api
var YTAPI = require('node-youtubeapi-simplifier');
var APIKEY = 'AIzaSyDS1p3m9wnZLLCPc1hDQBX3K_UnS4j0CdY'
YTAPI.setup(APIKEY);

console.log('connecting to s3 to get the json file');

var singers = [];

s3.getObject(bucketParams, function (err, data) {
    // Handle any error and exit
    if (err) {
        console.log(err, err.stack);
        return err;
    }
    var fileContents = data.Body.toString();
    var json = JSON.parse(fileContents);

    for (var i = 0; i < json.Search.artists.length; i++) {
        var newSinger = new Singer(json.Search.artists[i]);
        singers.push(newSinger);
    }
    console.log('the list of the singers has %d singers',json.Search.artists.length);
    search10TopForASinger();
});

//this function searches using youtube-api-simplfier for each artist name
//returns the list of songs and collects only 10, stores them into a map in the singer object
function search10TopForASinger() {
    console.log('entered search10TopForASinger ')
    var promises = [];

    for (var i = 0; i < singers.length; i++) {
        //Gets only 10 results
        promises.push(YTAPI.searchFunctions.simpleSearch(singers[i].name));
    }
    Promise.all(promises)
           .then((results) => {
               console.log('all the threads of the youtube api are back')
               for (var i = 0; i < singers.length; i++) {
                   setSongsArray(results[i], singers[i].songs);
               }

               printJsonAndUpload();
               console.log('we are done you can test yourself with testGiladFile.js');
            })
             .catch((e) => {
                    // Handle errors here
            });

}

//sets 10 or less songs for each artist into an array
//we use the Singer object in order to store the data
function setSongsArray(data, songs) {
    console.log('entered setSongsArray')
    var size = 10;
    if (data.length < 10) {
        size = data.length;
    }

    for (var i = 0; i < size; i++) {
       songs.push(data[i].title);
    }
}

//The team wanted a json file with a certain format
//we create here to format and upload it back to S3
function printJsonAndUpload() {

    console.log('entered printJson')
    var data = {
        results: []
    };

    for (var i = 0; i < singers.length; i++) {
        var singerName = singers[i].name;
        var singerObj = {}
        singerObj[singerName] = []
        for (var song = 0; song < singers[i].songs.length; song++) {
            var songObj = {};
            songObj[song+1] = singers[i].songs[song];
            singerObj[singerName].push(songObj)
        }
        data.results.push(singerObj);
    }

    console.log('uploading file to s3')
    s3.putObject({Bucket: 'pc-backend-exercises',Key:'gilad.json',Body: JSON.stringify(data), ContentType: "application/json"},
        function(err, data) {
            //console.log('error');
            //console.log(JSON.stringify(err)+" "+JSON.stringify(data));
        });
    console.log('the name of the file is gilad.json');
}

This is the first code I have ever written in Node.js, please give me any feedback about style and performance.


texts:
I'm an EE student who's taken a a couple digital logic/design courses, but they were focused on schematic representation, so I'm teaching myself Verilog to implement what I've learned.

For a basic Hello World project, I've implemented a basic 8-bit ALU with addition/subtraction with carry/borrow, NOT, AND, OR, XOR, and carry/zero/sign flags.

I've implemented it on an FPGA and everything works, but I want to make sure I'm not falling for any beginner traps which can lead to dramatic/undesired results in the final implementation of the circuit.

module ALU(A, B, Cin, Op, Out, Cout, Zero, Sign);
    input[7:0] A, B;
    input Cin;
    //011-A+B, 111-A-B, 000-NOT A, 001-A AND B, 010-A OR B, 100-A XOR B
    input[2:0] Op;
    output reg[7:0] Out;
    output Cout;
    output reg Zero;
    output reg Sign;

    wire FinalCin;          //Final value of Cin fed to ALU after XOR
    wire[7:0] FinalB;       //Final value of B fed to ALU after XOR
    wire[7:0] AddResult;
    wire[7:0] LogicResult;

    Adder DEV_ADD(A, FinalB, FinalCin, AddResult, Cout);
    LogicUnit DEV_LOG(A, B, Op, LogicResult);

    assign FinalCin = Cin ^ Op[2];  //Cin XOR Subtract Line
    assign FinalB = B ^ {8{Op[2]}}; //XOR B with Subtract Line

    always @ (Op or AddResult or LogicResult) begin
        if(Op == 3'b011 || Op == 3'b111)
            Out <= AddResult;
        else if(Op == 3'b000 || Op == 3'b001 || Op == 3'b010 || Op == 3'b100)
            Out <= LogicResult;
        else
            Out <= 8'b00000000;
    end

    always @ (Out) begin
        if(Out == 8'b00000000)
            Zero <= 1'b1;
        else
            Zero <= 1'b0;

        Sign <= Out[7];
    end
endmodule

Adder Module:

module Adder(A, B, Cin, S, Cout);
    input[7:0] A, B;
    input Cin;
    output wire[7:0] S;
    output wire Cout;

    assign {Cout, S} = A + B + Cin;

endmodule

Logic Unit:

module LogicUnit(A, B, Op, Out);
    input[7:0] A, B;
    input[2:0] Op;  //000-NOT A, 001-A AND B, 010-A OR B, 100-A XOR B
    output reg[7:0] Out;

    always @ (Op or A or B) begin
        case(Op)
            3'b000: Out <= ~A;
            3'b001: Out <= A & B;
            3'b010: Out <= A | B;
            3'b100: Out <= A ^ B;
        endcase
    end

endmodule


texts: ASP.NET MVC using an N-Tier Model and DDD

texts:
Any comments are welcome. However I'd like to call specific attention to my... interpretation of the N-Tier application architecture and how I'm consuming data. Note that the namespacing and inline comments have been factored out for brevity.

The Data Tier (DataModel.csproj)

// Base class for EF4 Entities
public abstract class EntityBase {
    public int Id { get; set; }
}

// Entities
public class Account : EntityBase {
    public string UserName { get; set; }
    public string Password { get; set; }
    public byte[] Salt { get; set; }
    public string EmailAddress { get; set; }
}

public class Entry : EntityBase {
    public string Title { get; set; }
    public DateTime Created { get; set; }
    public Account Owner { get; set; }
}

// EF4 Code-First Data Context
public class DataContext : DbContext {
    public DbSet<Account> Accounts { get; set; }
    public DbSet<Entry> Entries { get; set; }
}

// Repository Pattern
public interface IRepository<TEntity>
    where TEntity : EntityBase {
    TEntity Create();
    void Delete(TEntity entity);
    TEntity Get(int id);
    TEntity Get(Expression<TEntity,bool>> where);
    void Insert(TEntity entity);
    void Save();
    IQueryable<TEntity> Where(Expression<TEntity,bool>> where);
}

public class Repository<T> : IRepository<T>
    where T : EntityBase, new() {
    private readonly DataContext context;
    private readonly DbSet<T> set;

    public Repostory(DataContext context) {
        // context injected via ioc.
        this.context = context;
        this.set = this.context.Set<T>();
    }

    // Implementation of IRepository<T>
}

Business Logic Tier (Runtime.csproj)

// IOC Container
public static class IOC {
    public static readonly IWindsorContainer Container = new WindsorContainer();

    static IOC() {
        InstallAssembly("Presentation");
        InstallAssembly("Runtime");
        InstallAssembly("DataModel");
    }

    public static void InstallAssembly(string name) {
        Container.Install(FromAssembly.Named(name));
    }
}

// Also includes System.Configuration ConfigSections, HttpModules and Provider classes
// which are strongly tied to IRepository<>.

Presentation Layer (Mvc App) (Presentation.csproj)

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    // Controller Factory instance makes initial reference to IOC class, causing
    // the installers to run.
    ControllerBuilder.Current.SetControllerFactory(new Runtime.Mvc.WindsorControllerFactory());
}

// Data-Driven Controller
public class DashboardController : SecureController {
    private readonly IRepository<Entry> entries;

    public DashboardController(IRepository<Entry> entries) {
        // entries injected via ioc.
        this.entries = entries;
    }

    [ChildActionOnly, HttpGet]
    public ActionResult RecentEntries() {
        var viewModel = new RecentEntriesViewModel( entries.Where( stuffHappens ) );
        return PartialView(viewModel);
    }
}

I feel like letting IRepository<> reach the presentation layer may be a violation of the pattern. Exposition of an IQueryable<> through IRepository<>.Where seems like a bad idea at the Presentation level. There's no way to moderate the use of IQueryable and could lead to brittle code. Inputs?


texts: Determining which octant has a specific point

texts:
I am interested in octants in plane geometry, which basically involves dividing a plane into 8 equal parts according to a certain point.

Octants are particularly useful while implementing the Bresenham's algorithm.

Problem

Given two points A = (x1, y1) and B = (x2, y2), how to determine in which octant belongs B according to A?

Counting octants is performed as shown: starting from the upper right and iterating anticlockwise.

Naive implementation

def get_octant(pA, pB):
    AX = pA[0]
    AY = pA[1]
    BX = pB[0]
    BY = pB[1]

    if BX > AX:
        if BY > AY:
            if (BY - AY) < (BX - AX):
                octant = 0
            else:
                octant = 1
        else:
            if (AY - BY) < (BX - AX):
                octant = 7
            else:
                octant = 6
    else:
        if BY > AY:
            if (BY - AY) < (AX - BX):
                octant = 3
            else:
                octant = 2
        else:
            if (AY - BY) < (AX - BX):
                octant = 4
            else:
                octant = 5

    return octant

Would it not possible to find a cleverer implementation?

Using the symmetry properties, I am convinced that it is possible to make a shorter and more readable code. Unfortunately, I do not find it myself, so does anyone have an idea, please?


texts: Dynamic Multi-threading lock with while loop

texts:
I have already asked a question about a dynamic multi threaded lock, and the reviewer found a problem.

Here is the description of the problem that I need to solve:

  I need to create a structure to control dynamically created locks. For example, I have 100 threads running, and each thread will "process" a "key". Sometimes two threads could be processing the same "key", and if that occurs, a dynamic lock needs to be created and used by both, so only one thread can process the key at a time.

I rewrote my code again with a new idea, and I would like you to review it for possible bugs/leaks caused by multithreaded processing.

//Implementation of the class who will block to two process don't execute if they have the same key.
public class DynamicLockGenerator
{
    private static Dictionary<string, object> _locksByKeys = new Dictionary<string, object>();

    private static object _lock = new object();

    public static void ExecuteLock(string key, Action action)
    {
        try
        {
            bool isFree = true;

            do
            {
                lock (_lock)
                {
                    if (!_locksByKeys.ContainsKey(key))
                        _locksByKeys.Add(key, new GuidLock(Guid.NewGuid()));

                    isFree = Monitor.TryEnter(_locksByKeys[key]);
                }

                if (!isFree)
                {
                    Thread.Sleep(50);
                }

            } while (!isFree);

            action.Invoke();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            Monitor.Exit(_locksByKeys[key]);
        }
    }
}

//This is the method call.
DynamicLockGenerator.ExecuteLock(key, () => SomeMethodToExecuteAlone());


texts: Rotating lists in linear time and constant space (Java)

texts:
(The next iteration.)

I have this small utility method for rotating java.util.Lists in linear time, constant space:

package net.coderodde.util;

import java.util.Arrays;
import java.util.Collections;
import static java.util.Collections.swap;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

/**
 * This class contains a static method for rotating lists in linear time and
 * constant space.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Oct 6, 2017)
 */
public final class ListReversal {

    private ListReversal() {}

    /**
     * Performs the list rotation.
     *
     * @param <T>           the list element type.
     * @param list          the list whose content to rotate.
     * @param rotationCount the number of steps to rotate to the right. If
     *                      negative, rotates to the left.
     */
    public static <T> void rotate(List<T> list, int rotationCount) {
        Objects.requireNonNull(list, "The input list is null.");

        if (rotationCount < 0) {
            rotateLeft(list, -rotationCount);
        } else if (rotationCount > 0) {
            rotateRight(list, rotationCount);
        }
    }

    private static <T> void rotateLeft(List<T> list, int rotationCount) {
        Collections.<T>reverse(list);
        rotationCount %= list.size();
        reverse(list, list.size() - rotationCount, list.size());
        reverse(list, 0, list.size() - rotationCount);
    }

    private static <T> void rotateRight(List<T> list, int rotationCount) {
        Collections.<T>reverse(list);
        rotationCount %= list.size();
        reverse(list, 0, rotationCount);
        reverse(list, rotationCount, list.size());
    }

    private static <T> void reverse(List<T> list, int fromIndex, int toIndex) {
        for (int i = fromIndex, j = toIndex - 1; i < j; ++i, --j) {
            swap(list, i, j);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
        System.out.println(list);

        while (true) {
            int rotationCount = scanner.nextInt();
            rotate(list, rotationCount);
            System.out.println(list);
        }
    }
}

I would like to hear any comments regarding the above.


texts: Find the maximum value of | Ai - Aj | + | i - j |:

texts:
hackerearth.com practice problem Can you solve it?:

  Given an array 'A' consisting of 'n' integers, find the maximum value of the following expression:
  \$\lvert A_i - A_j\rvert + \lvert i - j\rvert\$

where \$A_i\$ is the element of the array at the i-th position (0-indexed array)

My solution:

def solve(n,l):
    ans=0
    for i in range(n):
        for j in range(n):
            if ans < (abs(l[i]-l[j])+abs(i-j)):
                ans=(abs(l[i]-l[j])+abs(i-j))
                print(ans)

t=int(input())
for _ in range(t):
    n=int(input())
    l = list(map(int,input().split()))
solve(n,l)

This code passes all the sample test cases but when I finally submit the code
for two inputs it shows wrong and
for all the other inputs it shows time limit exceeded.

Kindly point out what is wrong and what can be done in order to get the correct output.


texts: Find maximum difference between values in an array

texts:
My task is to use the following pseudocode and improve it (make it run faster). Also I have to analyze the runtime of the given pseudocode and of my new code that i improved.

What does this algorithm do? It finds the smallest and greatest number in an array and creates the difference of them.

Pseudocode (given in task):

Input: Array Y, length n with n >= 2
Output: x (number)
x = 0
for i = 0 to n do
   for j = i + 1 to n do
      if x < A[i] - A[j] then
      x = A[i] - A[j];
      end if
   end for
end for
return x;

My code, improved:

public class Improved
{
    public static void main (String[] args)
    {
        int A[] = {1, 2, 3, 4, 5};
        int min = A[0];
        int max = A[0];

        for (int i = 0; i < A.length; i++)
        {
            if (min > A[i])
            {
                min = A[i];
            }

            if (max < A[i])
            {
                max = A[i];
            }
        }
        System.out.println(max - min);
    }
}

The only problem I got now is counting the runtime.
I think for the pseudocode, it runs in \$\mathcal{O}(n^2)\$ because of the 2 for loops.
Then my code will run in \$\mathcal{O}(n)\$, since it only has 1 for loop, right? :P
What would be the worst case by the way?


texts: Testable authentication handler for web API

texts:
I need to unit test my authentication handler. I don't really want do an assert against the text message returned by the handler. How could this be improved ?

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    // Check for API key
    if (!request.Headers.Contains(AuthConfig.ApiKeyHeader))
    {
        return SendResponseText("ApiKey is required");
    }

    // Check for timestamp
    if (request.GetQueryNameValuePairs().Where(k => k.Key.ToLower() == "timestamp").Count() != 1)
    {
        return SendResponseText("Timestamp is required");
    }

    // Validate timestamp
    if (IsValidTimestamp(request) == false)
    {
        return SendResponseText("Invalid timeStamp");
    }

    // Check for signature
    if (request.Headers.Authorization == null || request.Headers.Authorization.Scheme != AuthConfig.AuthenticationScheme)
    {
        return SendResponseText("Signature is required");
    }

    // Validate API Key
    string apikey = request.Headers.GetValues(AuthConfig.ApiKeyHeader).First();
    UserDTO user = _userRepo.GetUserAuthInfo(apikey);
    if (user == null)
    {
        return SendResponseText("Invalid API key");
    }

    // Validate signature
    string signature = _signatureCalculator.GetSignature(user.Secret, request.RequestUri.OriginalString);
    if (request.Headers.Authorization.Parameter != signature)
    {
        return SendResponseText("Invalid signature");
    }

    return base.SendAsync(request, cancellationToken);
}

private Task<HttpResponseMessage> SendResponseText(string text)
{
    Logger.Error(text);

    var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
    response.ReasonPhrase = text;
    response.Content = new StringContent(text);

    var tcs = new TaskCompletionSource<HttpResponseMessage>();
    tcs.SetResult(response);

    return tcs.Task;
}

So far, I have put the custom reason phrases in a constant

public sealed class AuthError
{
    public const string ApiKeyMissing = "ApiKey is required";
    ...
}

And my tests look like this

[TestMethod]
public void SecurityHandler_ApiKeyMissingFromHeader_ReturnsUnauthorizedHttpStatus()
{
    var handler = new SecurityHandler(new Mock<IClientRepository>().Object, new Mock<ISignatureCalculator>().Object);

    var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

    var client = new HttpClient(handler);
    var result = client.SendAsync(httpRequestMessage).Result;

    Assert.AreEqual(result.StatusCode, HttpStatusCode.Unauthorized);
    Assert.AreEqual(result.ReasonPhrase, SecurityHandler.AuthError.ApiKeyMissing);
}

I'm not too happy with this, and I'm doing 2 asserts which is bad practice.. Any ideas ?


texts:
I recently decided that putting strategically placed print statements scattered about my python programs to debug was getting to be a little messy.

I had thought to try out other debugging plugins I found online, but thought I would give writing my own simple breakpoint plugin a shot.

I know of python's pdb module, but my goal was to minimize the amount that I had to type to debug my programs.

Only a few keybinds are mapped:

Normal mode:

<leader>b — Toggle breakpoint for the current line
<leader>B — Run debugger in a new tmux split

Visual Mode:

<leader>b — Toggle breakpoint for the selected lines

This has only been tested on Linux. The only requirement is tmux

" Define breakpoint highlight color and mark in number column
hi Breakpoint ctermfg=1 ctermbg=NONE
sign define Breakpoint text=● texthl=Breakpoint

" Map of lines that have breakpoints
let b:breakpoints = {}

function ToggleBreakpoint(lnum)
    let is_breakpoint = get(b:breakpoints, a:lnum, 0)

    if is_breakpoint
        " Remove the line number in breakpoints and unplace the mark
        call remove(b:breakpoints, a:lnum)
        exe ":sign unplace"
    else
        " Add the line number in breakpoints and place the mark
        let b:breakpoints[a:lnum] = 1
        exe ":sign place 2 line=" . a:lnum . " name=Breakpoint file=" . expand("%:p")
    endif
endfunction

function BreakpointIndentation(lnum)
    " Get the line's current indentation level and first character
    let indent_count = indent(a:lnum)
    let curline = getline(a:lnum)
    let firstChar = curline[0]

    " Build the indentation to use for the breakpoint
    if firstChar == "\t"
        " Handle user defined `tabstop` variable
        return repeat(firstChar, indent_count / &tabstop)
    else if firstChar == " "
        return repeat(firstChar, indent_count)
    else
        return ""
    endif
endfunction

function RunPDB()
    let lnum = 1
    let num_lines = line("$")

    " The lines to write to the temporary file
    " Start out by importing pdb
    let lines = ["import pdb"]

    " Iterate over each line in the current buffer
    while lnum <= num_lines
        let is_breakpoint = get(b:breakpoints, lnum, 0)

        " If the line is a breakpoint, add `pdb.set_trace` before that line
        if is_breakpoint
            let indentation = BreakpointIndentation(lnum)
            let breakpoint_line = "pdb.set_trace()"
            if indentation != ""
                let breakpoint_line = indentation . breakpoint_line
            endif
            call add(lines, breakpoint_line)
        endif

        call add(lines, getline(lnum))
        let lnum += 1
    endwhile

    " Create a new temporary file with the contents of `lines`
    let tmpfile = tempname()
    call writefile(lines, tmpfile)

    " Make a new vertical tmux split and run the temporary file with python
    silent exe "!tmux split-pane -v"
    silent exe "!tmux send-keys 'python " . tmpfile . "' Enter"

endfunction

nnoremap <leader>b :call ToggleBreakpoint(line("."))<CR>
vnoremap <leader>b :call ToggleBreakpoint(line("."))<CR>
nnoremap <leader>B :call RunPDB()<CR>

This is my first attempt to write anything particularly useful in vimscript.

Are there any sections that can be improved upon?


texts: Initializing a multidimensional with many default values

texts:
I need to create a \${n} \times {n}\$ multidimensional array filled with default values.

Right now, I'm using this code:

//--- how many columns?
var colNumber = 10;
//--- how many rows?
var rowNumber = 20;

//--- default value
var defaultValue = "default";

var defRow = [];
var defaultArray = [];

for(var x = 0; x < colNumber; x++){
    defRow.push(defaultValue);
}
for(var x = 0; x < rowNumber; x++){
    defaultArray.push(defRow);
}
console.log(defaultArray);

find fiddle here

Is there any better approach to do this?


texts:
This is my code:

function search() {
    $("#myInput").keyup(function () {
        var value = this.value;

        $("table").find("tr").each(function (index) {
            if (index === 0) return;
            var id = $(this).find("td").first().text();
            $(this).toggle(id.indexOf(value) !== -1);
        });
    });
}

$('body').on('click', '#searchFonts', function () {
    var value = "Font"
    $("table").find("tr").each(function (index) {
        if (index === 0) return;
        var id = $(this).find("td").first().text();
        $(this).toggle(id.indexOf(value) !== -1);
    });
});

$('body').on('click', '#searchScripts ', function () {
    var value = "script"
    $("table").find("tr").each(function (index) {
        if (index === 0) return;
        var id = $(this).find("td").first().text();
        $(this).toggle(id.indexOf(value) !== -1);
    });
});

I'm looking for ways to make this run more effectively, as I'm sure there is a more efficient way to search for the specific value's seen below such as 'Font' and 'Script'.


texts: Querying a data structure that contains various triples

texts:
I wrote code that queries a data structure that contains various triples - 3-item tuples in the form subject-predicate-object. I wrote this code based on an exercise from Programming the Semantic Web textbook.

def query(clauses):
    bindings = None
    for clause in clauses:
        bpos = {}
        qc = []
        for pos, x in enumerate(clause):
            if x.startswith('?'):
                qc.append(None)
                bpos[x] = pos
            else:
                qc.append(x)
        rows = list(triples(tuple(qc)))
        if bindings == None:
            # 1st pass
            bindings = [{var: row[pos] for var, pos in bpos.items()}
                        for row in rows]
        else:
            # >2 pass, eliminate wrong bindings
            for binding in bindings:
                for row in rows:
                    for var, pos in bpos.items():
                        if var in binding:
                            if binding[var] != row[pos]:
                                bindings.remove(binding)
                                continue
                        else:
                            binding[var] = row[pos]
    return bindings

The function invocation looks like:

bg.query([('?person','lives','Chiapas'),
          ('?person','advocates','Zapatism')])

The function triples inside it accepts 3-tuples and returns list of 3-tuples. It can be found here.

The function query loops over each clause, tracks variables (strings that start with '?'), replaces them with None, invokes triples, receives rows, tries to fit values to existing bindings.

How can I simplify this code? How can I make it more functional-style, without nested for-loops, continue keyword and so on?


texts:
I found this old color fading function in my snippets folder and would like to implement it to one of my projects. It can be used to fade one color to another. It's a very long one-liner:

D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor)
{
    return (factor<0.0f)?from:((factor>1.0f)?to:(((((from>>24)>(to>>24))?((from>>24)-
    (D3DCOLOR)(factor*(float)((from>>24)-(to>>24)))):((from>>24)+(D3DCOLOR)(factor*(float)
    ((to>>24)-(from>>24)))))<<24)|(((((from<<8)>>24)>((to<<8)>>24))?(((from<<8)>>24)-
    (D3DCOLOR)(factor*(float)(((from<<8)>>24)-((to<<8)>>24)))):(((from<<8)>>24)+(D3DCOLOR)
    (factor*(float)(((to<<8)>>24)-((from<<8)>>24)))))<<16)|(((((from<<16)>>24)>
    ((to<<16)>>24))?(((from<<16)>>24)-(D3DCOLOR)(factor*(float)(((from<<16)>>24)-
    ((to<<16)>>24)))):(((from<<16)>>24)+(D3DCOLOR)(factor*(float)(((to<<16)>>24)-
    ((from<<16)>>24)))))<<8)|(((((from<<24)>>24)>((to<<24)>>24))?(((from<<24)>>24)-(D3DCOLOR)
    (factor*(float)(((from<<24)>>24)-((to<<24)>>24)))):(((from<<24)>>24)+(D3DCOLOR)(factor*
    (float)(((to<<24)>>24)-((from<<24)>>24))))))));

}

D3DCOLOR is just a DWORD (unsigned long). A color can for example be 0xAARRGGBB (A-alpha, R-red, G-green, B-blue), but works with other compositions aswell.

Obviously it's a total mess.

I actually don't know how it works and don't remember where I have it from, so I would ask for a review to improve the code and make it readable and understandable.


texts:
I've been working on an older project with framework is 3.5 as the target. There is a new user control that displays a list of data from a web service. I hit the web service (Soap/XML) and deserialize the data into a list of a custom model/class (this is in a helper class outside the user control).

Back in the user control code behind, I'm looping through the data and displaying it using a HtmlTextWriter. Here is an example of some of the code (simplified):

        var sb = new StringBuilder();
        using (var writer = new HtmlTextWriter(new StringWriter(sb)))
        {
            foreach  (
                var month in
                    courses.SelectMany(x => x.Offerings)
                        .Where(x => !string.IsNullOrEmpty(x.StartDate))
                        .Select(x => DateTime.Parse(x.StartDate))
                        .Select(x => new DateTime(x.Year, x.Month, 1))
                        .Distinct()
                        .OrderBy(x => x.Year)
                        .ThenBy(x => x.Month)
                        .ToList())
            {

            //some display code using the writer

                foreach (var offering in
                    courses.SelectMany(x => x.Offerings)
                        .Where(x => !string.IsNullOrEmpty(x.StartDate))
                        .Where(
                            x =>
                                DateTime.Parse(x.StartDate).Year == month.Year
                                && DateTime.Parse(x.StartDate).Month == month.Month)
                        .OrderBy(x => DateTime.Parse(x.StartDate))
                        .ToList())
                {
                    //more display code using the writer
                }
            }
        }
        thisisadiv.InnerHtml = sb.ToString();

The HTML markup is a design that was already in place somewhere else so I chose not to change it at all in the interest of time.

Is there a more efficient way of looping through the classes/data that I could benefit from? I'm currently not seeing any speed issues but want to make sure I'm using an adequate technique.


texts:
I need to filter Turkish words according to vovel alternation rules. For example -ler is plural but can have form of -lar thus I use metaphonemes for these transitive allomorphs as vovel_dict in my algorithm.

There is only one condition not to alternate vovel it's 'ken' which excluded. I wrote this but it takes too much runtime do you have any suggestions?

def char_filter(morph):
    char_dict = {'d': 'D', 't': 'D', 'a': 'A', 'e': 'A', 'ı': 'H', 'i': 'H', 'u': 'H', 'C': 'C', 'g': 'G', 'k': 'G'}
    res = []
    res1 = []
    flag = []

    if 'ken' in morph:
        flag.append([morph.rindex('ken'), ['k','e','n']])

    for i in morph:
        res2 = i
        if i in char_dict:
            res2 = i.upper()
        res1.append(res2)

    if len(flag) > 0:
        for z in flag:
            res1[z[0]:z[0]+3] = z[1]
    res.append(string.join(res1, sep=''))
    return res[0]


texts: Retrieve a city list for a country and state

texts:
The code below is working properly but how do I make this code faster and more efficient. How do I perfect this code?

Let's assume I have 1000 country, state and city records in a mongodb collection. I want to retrieve all the city data by matching country id and state id. Please tell me the perfect way to code.

// @route   GET citylist/:countryid/:stateid
// @desc    get all the city from mongodb for countryid and stateid

router.get("/citylist/:countryid/:stateid", (req, res) => {
  const isValidCountryid = mongoose.Types.ObjectId.isValid( req.params.countryid);
  const isValidStateid = mongoose.Types.ObjectId.isValid(req.params.stateid);

  if (isValidCountryid && isValidStateid) {
    CityModel.find({
      country_id: req.params.countryid,
      state_id: req.params.stateid
    })

      .then(cities => {
        if (!cities || !cities[0]) {
          return res.status(404).json({ msg: "City not found" });
        } else {
          res.json(cities);
        }
      })
      .catch(error => res.status(500).send(error));

  } else {
    res.json({ msg: "Country or State Id is not valid" });
  }
});

how to make this code highly fast, efficient, great time complexity and perfect way of code.


texts: The largest odd number (follow-up code using nested functions)

texts:
Ask user to input 10 integers and then print the largest odd number that was entered. If no odd number was entered, print a message to that effect.

This is my follow-up code on feedback from Find the largest odd number (follow-up code)

This time I'm trying to achieve the same result with nested functions. I need your comments please. Also, please note that I'm working through a book and it's meant to be used with Python 2.x

def find_largest_odd():
    numbers_entered = []

    def get_ten_ints():
        while len(numbers_entered) < 10:
            try:
                number = int(raw_input('Enter an integer: '))
                numbers_entered.append(number)
            except ValueError:
                print 'That was not an integer!'

    get_ten_ints()

    try:
        largest_odd_number = max(item for item in numbers_entered if item % 2)
        return 'The largest odd number entered was {}.'.format(largest_odd_number)
    except ValueError:
        return 'No odd number was entered.'


texts: Drag Drop, get filename and last 23 characters

texts:
I want to get the filename and last 23 characters when I drag into a textbox.

I have it working, but I would like to just have one line.  Currently, I think I am doing a bit of a workaround. As I must use a string array, and I only want one string, so I don't really need an array.

private void First_DragDrop(object sender, DragEventArgs e)
{
    string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];
    string filename = Path.GetFileNameWithoutExtension(fileList[0]);
    First.Text = filename.Substring(filename.Length - 23, 23);
}

As you can see, I must do it in 3 steps. First, get the string array.  Then, get one string from that array and turn it into a filename.  FInally, I need to get the last 23 characters of that string.

I think I should be able to just get everything immediately. Though maybe it's not possible?  It just seems weird that I must use an array that contains one thing.


texts:
In this post, I asked a question regarding how to create a matrix of integers where elements in each row satisfy a particular property.

The notation in the original post is a bit cumbersome so I will try to explain the question in a nutshell. I have a vector of integers cvec, which has length l-1, and I enumerate all the possibilities in a matrix such that every integer in each of the l columns is less than or equal to cvec[1] (first three lines of code). Then I iteratively reduce that large set possibilities into a smaller matrix, such that for a given row:

Consecutive elements taken 2,3,...l-1 at a time must be no larger than cvec[2], cvec[3], ..., cvec[l-1], respectively
The total sum of the l elements is equal to x.

By first subsetting mat to only those rows with sum x, and then running the nested for loops, I've been able to reduce the runtime by over 1/10th. For the above example, it now runs 7.8 seconds. However, I still think this could be faster if I somehow eliminate the nested loops. Any suggestions?

valid.counts2 <- function(x,l,cvec){
  #l>1
  vec = seq(from=0,to=cvec[1])
  lst = lapply(numeric(l), function(i) vec)
  mat = as.matrix(expand.grid(lst))
  mat = mat[which(rowSums(mat)==x),]

  if(l>2){
    #k=1 is redundant since all must be less than or equal to cvec[1]
    for (k in seq(from=2, to=l-1)){
      row.indx = NULL
      for (r in seq(l-k+1)){
        #pick out the index of the row(s) that satisfy constraint
        row.indx = which(rowSums(mat[,r:(r+k-1),drop=FALSE])<=cvec[k])
        #filter rows of mat
        mat = mat[unique(row.indx),]
      }
    }
  }
  return(mat)
}


texts:
My code calculates \$e^x\$ with series expansion. Is there any way to make it shorter and cleaner?

#lang racket
; evaluate e^x with series expansion, use first 10 terms.

(define (exp x)
  (letrec ([f1 (lambda (n cx cn)
                 ;(writeln (list n cx cn))
                 (if (>= n 10)
                     0
                     (+ (/ cx cn) (f1 (+ n 1) (* cx x) (* cn (+ n 1))))))])
    (+ 1 (f1 1 x 1))
    )
  )

(letrec ([N (read)]
         [rd (lambda (n)
               (unless (zero? n)
                       (define x (read))
                       (writeln (exp x)) (rd (- n 1))))])
  (rd N))


texts:
I have been using this code for a while. I got it from a tutorial 5 years back. Now I'm wondering if it still is secure, or if it's time to find a new one? Maybe it has never been secure enough.

LOGIN

<?php
//Connect to database
require("include/config.php");

//Empty Variable
$submitted_username = '';

//Check if something is posted
if(!empty($_POST)){

    //Check if user exists
    $query = "SELECT * FROM usrs WHERE usr_email = :usr_email";
    $query_params = array(':usr_email' => $_POST['usr_email']);
    try{
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }

    //Fetch result
    $row = $stmt->fetch();

    //Reset var
    $login_ok = false;

    //If usr exists, check password
    if($row){
        //Check if password matches
        $check_password = hash('sha256', $_POST['usr_password'] . $row['usr_salt']);
        for($round = 0; $round < 65536; $round++){
            $check_password = hash('sha256', $check_password . $row['usr_salt']);
        }
        if($check_password === $row['usr_password']){
            $login_ok = true;
        }
    }

//LOGIN OK
    if($login_ok){
        //UNSET VARS
        unset($row['usr_salt']);
        unset($row['usr_password']);

        //LOG USR LOGIN DATA
        $dateTime = date('Y-m-d H:i:s');
        //Create array
        $usr_data = array(
            ':usr_id' => $row['id'],
            ':usr_name' => $row['usr_fname']. " " . $row['usr_lname'],
            ':dateTime' => $dateTime,
            ':ip' => $_SERVER['REMOTE_ADDR']
        );

        //CREATE SESSION
        $_SESSION['usr'] = $row;

        //REDIRECT TO STARTPAGE
        header("Location: start.php");

    }
    else{
        echo "<script type='text/javascript'>alert('Fel uppgifter..');</script>";
        $submitted_username = htmlentities($_POST['usr_email'], ENT_QUOTES, 'UTF-8');
    }
}
?>

CONFIG

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

//SET HEADER
header('Content-Type: text/html; charset=utf-8');

//START SESSION
if(!isset($_SESSION)){
    session_start([
        'cookie_lifetime' => 86400,
    ]);
}

//SET TIMEZONE
date_default_timezone_set('Europe/Stockholm');
?>

CHECK IF LOGGED IN

<?php

//CHECK IF USR IS LOGGED IN
if(empty($_SESSION['user'])){
    echo "<script>window.location = '/index.php'</script>";
    die("Redirecting to index.php");
}


texts:
This code takes a YouTube video and download it. It supports only non-copyrighted videos due to YouTube's new algorithms.

Any thoughts about the structure and the logic? I would like to learn from my mistakes, I've just started coding with python.

#!/usr/bin/env python3.5.2

import urllib.request, urllib.parse
import os

def main():
    """
    This code will download only non copyrighted youtube videos due to the new algorithms for accessing video files taht Youtube had changed.
    Instead of "token" they now use "signature" variable, and "signature" seems to be dependent on either cookie-stored data or IP address of the client
    """
    print("\n                          * * * * * * * * * * * * * * *")
    print("                          *                           *")
    print("                          * Youtube Video Downloader! *")
    print("                          *                           *")
    print("                          * * * * * * * * * * * * * * *\n")
    # make sure to change directory path
    directory = r'C:\Users\SalahGfx\Desktop\DownloadedVideos'

    def get_sourcecode(url):
        return urllib.request.urlopen(url).read()

    def get_info():
        return urllib.parse.parse_qs(get_sourcecode(url).decode('unicode_escape'))

    def get_video_title_path():
        try:
            return os.path.join(directory, '{}.mp4'.format(get_info()['title'][0]))

        except KeyError:
            print('Parsing error, please rerun the code!')

    def get_stream_map():
        return get_info()['url']

    def get_stream_map_list():
        video_links = []
        for video_stream in get_stream_map():
            if "googlevideo" == video_stream.split('/')[2].split('.')[1]:
                video_links.append(video_stream)

            else:
                pass
        return video_links

    def validate_url(url):
        return url.startswith('https://www.youtube.com/')

    def download_video(k):
        return urllib.request.urlretrieve(get_stream_map_list()[k], get_video_title_path())

    def download_hq_video(quality):
        k = 0
        download_video(k)
        print("Downloading {} -----------> {} in {} quality.".format(get_stream_map_list()[k], get_video_title_path(),
                                                                     quality))

    def download_md_video(quality):
        k = 1
        download_video(k)
        print("Downloading {} -----------> {} in {} quality.".format(get_stream_map_list()[k], get_video_title_path(),
                                                                     quality))

    def download_sm_video(quality):
        k = 2
        download_video(k)
        print("Downloading {} -----------> {} in {} quality.".format(get_stream_map_list()[k], get_video_title_path(),
                                                                     quality))

    while True:
        try:
            url, quality = input(
                "Please type a youtube video url and its quality(choose between high, medium and small) and separate them with a space: ").split()

        except ValueError:
            print("Please type the right url and quality.");
            print("Make sure the url start with 'https://www.youtube.com/'");
            print("high - for downloading high quality video");
            print("medium - for downloading medium quality video");
            print("small - for downloading small quality video");
            continue

        if validate_url(url) and quality == 'high':
            get_sourcecode(url)
            download_hq_video(quality)
            break

        elif validate_url(url) and quality == 'medium':
            get_sourcecode(url)
            download_md_video(quality)
            break

        elif validate_url(url) and quality == 'small':
            get_sourcecode(url)
            download_sm_video(quality)
            break

        else:
            break

if __name__ == '__main__':
    main()


texts: Performance concerns when converting GTK image to greyscale

texts:
I have a function which takes GTK Image (It is RGB) and returns a representation of this image as list of grey levels.

This is my code:

grayscaleFromRGB :: Image -> IO [Word8]
grayscaleFromRGB img = do
    imgType <- img `get` imageStorageType
    if imgType == ImageEmpty
        then
            return (replicate 256 0)
        else do
            pixbuf <- imageGetPixbuf img
            pixels <- (pixbufGetPixels pixbuf :: IO (PixbufData Int Word8))
            rgbList <- getElems pixels
            nChannels <- pixbufGetNChannels pixbuf
            return (map convert $ chunksOf nChannels rgbList)

    where
        convert channels = round $ foldl (+) 0 $ zipWith (*) [0.3, 0.59, 0.11] $ map fromIntegral channels

But I have a problem: this function uses too much memory and CPU time. For example for an image with a size of 500x500 it takes nearly 100MB of memory. Opening an image with a size of 2000x1000 it use more than 1GB of memory and it takes a lot of time.

How can it be written in an efficient way? What is the reason for this behavior?

Update:

Whole code which use this function (this program takes too much RAM):

import Graphics.Rendering.Cairo
import Graphics.UI.Gtk
import Data.List.Split
import Data.Array.MArray
import Data.Array.IO
import Data.Word
import Data.List
import Foreign.Storable

grayscaleFromRGB :: Image -> IO [Word8]
grayscaleFromRGB img = do
    imgType <- img `get` imageStorageType
    if imgType == ImageEmpty
        then
            return (replicate 256 0)
        else do
            pixbuf <- imageGetPixbuf img
            pixels <- (pixbufGetPixels pixbuf :: IO (PixbufData Int Word8))
            rgbList <- getElems pixels
            nChannels <- pixbufGetNChannels pixbuf
            return (map convert $ chunksOf nChannels rgbList)

    where
        convert channels = round $ foldl' (+) 0 $ zipWith (*) [0.3, 0.59, 0.11] $ map fromIntegral channels

main :: IO ()
main= do
     initGUI
     window <- windowNew
     set window [windowTitle := "Hello Cairo",
                 windowDefaultWidth := 300, windowDefaultHeight := 200,
                 containerBorderWidth := 30 ]

     image <- imageNew
     let menuBarData = [
                  ("File", [("Open", openPressed image),
                            ("Exit", mainQuit)
                           ])
                      ]

     tab <- tableNew 5 10 True

     menuBar <- createMenuBar menuBarData

     scrolled <- scrolledWindowNew Nothing Nothing
     scrolledWindowAddWithViewport scrolled image

     tableAttachDefaults tab menuBar    0 10 0 1
     tableAttachDefaults tab scrolled   0 5 1 10

     containerAdd window tab

     widgetShowAll window
     onDestroy window mainQuit
     mainGUI

createMenuBar menuBarData = do
    menuBar <- menuBarNew

    mapM_ (setMenuEntries menuBar) menuBarData
    return menuBar

    where
        setMenuEntries menuBar (entryName, items) = do
            entry <- menuItemNewWithLabel entryName
            menu <- menuNew
            mapM_ (addItemToEntry menu) items
            menuItemSetSubmenu entry menu
            menuShellAppend menuBar entry

        addItemToEntry menu (name, action) = do
            item <- menuItemNewWithLabel name
            item `on` menuItemActivated $ action
            menuShellAppend menu item

openPressed :: Image -> IO ()
openPressed image = do
    chooser <- fileChooserDialogNew
                (Just "Open file")
                Nothing
                FileChooserActionOpen
                [("OK", ResponseOk),
                 ("Cancel", ResponseCancel)]

    widgetShow chooser
    res <- dialogRun chooser
    filename <- performResponse res chooser
    widgetHide chooser

    where
        performResponse ResponseCancel _ = return ()
        performResponse ResponseOk chooser = do
            Just fname <- fileChooserGetFilename chooser
            imageSetFromFile image fname
            grey <- grayscaleFromRGB image
            putStrLn $ show $ grey


texts: Changing the foreground and background colors of substrings based on ANSI escape codes

texts:
I am checking for particular keywords in a string, and then changing the foreground and background colors of substrings based on the keywords. Following is the snippet for checking the background code:

if(string.contains("[30;42m") || string.contains("[31;42m") || string.contains("[32;42m") ||
    string.contains("[33;42m") || string.contains("[34;42m") || string.contains("[35;42m")
    || string.contains("[36;42m") || string.contains("[37;42m")){
        //the parameter of indexOf and replaceAll will be one from the above
        //using [30;42m as an example
        index = string.indexOf("[30;42m");
        string = string.replaceAll("\\[30;42m", "");
        backgroundColor = Color.GREEN;
        //foreground is already set using separate conditions for 30,32,32...37m
     }

Is there any way that I can do something as I have shown above? Currently, I have separate conditions for each substring, which doesn't incorporates "DRY" principle. My code is working, but I am looking for a way to reduce these if statements.

Edit:
The if blocks are for setting the background and foreground colors. For example if I have "34;42" code, this means text foreground color is Blue and background color is Green, and so on.


texts:
Is this code correct? Is there any major improvement I can ad in terms of number of operations?

#include <stdio.h>

/* function that yields 1 when run on a machine that uses
arithmetic right shifts for int's and 0 otherwise */

/* use only << >> ! & ~ ^ and constants between 0x0 and 0xff*/

int int_what_shifts();

int main(){
    int_what_shifts();
}

int int_what_shifts(){

    int mask = (0x80 << 24);

    printf("%d\n",!!(mask>>31));

    return !!(mask >> 31);
}


texts: Different way of writing multiple click functions

texts:
I have the following .click() functions:

$('.tab').click(function(){
    $('.tab').removeClass('activeTab');
    $(this).addClass('activeTab');
});

$('.edit').click(function(){
    $(this).hide();
    $(this).next().show();
});

$('.cancel').click(function(){
    $(this).parent().hide();
    $(this).parent().prev().show();
});

Is it possible to combine these functions doing something like this?

Pseudocode:

$.click(function(){
    for $('.tab'){
        //do this
    }
    for $('.edit'){
        //do this
    }
    for $('.cancel'){
        //do this
    }
});

HTML:

Edit

    Cancel |
    Save


texts:
Usually it is a good style in Java to create a named constant for a string (and other) hardcoded values. Using the example below I want to know how pedantic I should be in it.

I use a Java class as a wrapper of XML settings. Each function is suppose to return a value from a related XML file.

I defined a lot of constants with keys names on the top and each function use one single constant. Is it a good idea to remove constants and use hardcoded strings directly in each function?

Here is my settings file:

package com.art.backend.configs;

import com.art.backend.configs.inherited.Config;

public class ConfigStorage extends Config {

    private static final String SETTINGS_FILENAME = "storage.cfg.xml";

    private static final String KEY_HOST = "host";
    private static final String KEY_PORT = "port";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_CONNECTION_TYPE = "connection_type";
    private static final String KEY_SEPARATOR= "separator";
    private static final String KEY_REMOTE_ROOT = "remote_root";
    private static final String KEY_SUBDIR_UPLOADED = "subdir_uploaded";

    public ConfigStorage() {
        super(SETTINGS_FILENAME);
    }

    public String getHost(){ return getString(KEY_HOST); }

    public int getPort(){ return getInt(KEY_PORT); }

    public String getUsername(){ return getString(KEY_USERNAME); }

    public String getPassword(){ return getString(KEY_PASSWORD); }

    public String getSeparator(){ return getString(KEY_SEPARATOR); }

    public String getConnectionType(){ return getString(KEY_CONNECTION_TYPE); }

    public String getRemoteRoot(){ return getString(KEY_REMOTE_ROOT); }

    public String getSubdirUploaded(){ return getString(KEY_SUBDIR_UPLOADED); }
}

Also I will attach file "Config" as a base class for my settings and XML settings file just in case, but they are not really important.

package com.art.backend.configs.inherited;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public abstract class Config {
    private static final String MSG_SETTING_NOT_FOUNT = "Settings file not found";

    private final String filename;
    private Properties properties = null;

    public Config(String filename){
        this.filename = filename;
        init();
    }

    private void init(){

        //Reading properties file in Java example
        try {
            properties = new Properties();
            InputStream fis = getClass().getClassLoader().getResourceAsStream("storage.cfg.xml");
            properties.loadFromXML(fis);
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException(MSG_SETTING_NOT_FOUNT);
        }
    }

    public String getFilename(){ return filename; }

    public String getString(String key){
        return properties.getProperty(key);
    }

    public int getInt(String key){
        return Integer.parseInt(properties.getProperty(key));
    }

    public float getFloat(String key){
        return Float.parseFloat(properties.getProperty(key));
    }

    public boolean getBoolean(String key){
        return Boolean.parseBoolean(properties.getProperty(key));
    }
}

XML settings

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="host">***</entry>
    <entry key="port">***</entry>
    <entry key="username">***</entry>
    <entry key="password">***</entry>
    <entry key="connection_type">sftp</entry>
    <entry key="separator">/</entry>
    <entry key="remote_root">/home/adzhus/art_storage/</entry>
    <entry key="subdir_uploaded">uploaded/</entry>
</properties>


texts: DAL Returns a collection of business objects in MVP

texts:
In Model View Presenter (MVP) pattern, it is said that our DAL always should returns business models.

If I want to get a list of business objects from my DAL, is it acceptable to do it as follows or better to get a DataTable from DAL and then in the applications BLL, converts it to a List?

public List<Employee>  GetNewEmployees()
{
    string selectStatement = "SELECT Employee.Emp_ID, Employee.Initials + ' ' + Employee.Surname AS Name,...";

    using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
    {
        using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
        {
            sqlConnection.Open();
            using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
            {
                List<Employee> list = new List<Employee>();
                while (dataReader.Read())
                {
                    list.Add (
                    new EpfEtfMaster {
                        EmployeeID = (int) dataReader ["emp_id"],
                        EmployeeName = (string) dataReader ["Name"],
                        AppointmentDate = (DateTime) dataReader["appointment_date"],
                    });
                }
                return list;
            }
        }
    }
}


texts: Formatting some data about some airlines

texts:
function reformat($data, $registration = false) {
    // Initializing aircompanies codes
    $iata = new iata;
    for ($i = 0; $i < count($data); $i = $i + 6) {
        if ($registration) {
            $r = str_replace('<nobr>', '', $this->prep_value($data[$i]));
            $block[$i]['reis'] = str_replace('</nobr>', '', $r);
            $a = explode(' ', $block[$i]['reis']);
            $block[$i]['company'] = $a[0];
        } else {
            $r = explode('&nbsp;', $this->prep_value($data[$i]));
            $block[$i]['reis'] = (strlen($r[0]) > 2) ? strrev(substr(strrev($r[0]), 15, 2)) . ' ' . $r[1] : $r[0] . ' ' . $r[1];
            $block[$i]['company'] = (strlen($r[0]) > 2) ? strrev(substr(strrev($r[0]), 15, 2)) : $r[0];
        }
        $block[$i]['companyname'] = $iata->aircompanies[strtoupper($block[$i]['company'])];
        if (file_exists(ROOT_HTML_PATH . '/content/aircompanies/' . $block[$i]['company'] . '.png')) {
            $block[$i]['company'] = $block[$i]['company'] . '.png';
        } else {
            /**
             * @todo Write e-mail notifications, but only once;
             */
        }
        $block[$i]['airport'] = $this->prep_value($data[$i + 1]);
        $block[$i]['terminal'] = substr(strrev($this->prep_value($data[$i + 2])), 2, 1);
        $block[$i]['shedtime'] = $this->prep_value($data[$i + 3]);
        $block[$i]['facttime'] = str_replace('&nbsp;', '', $this->prep_value($data[$i + 4]));
        $block[$i]['status'] = str_replace('&nbsp', '<br />', trim(strip_tags($this->prep_value($data[$i + 5]), '<img />'), '&nbsp;/r/n'));
        $block[$i]['status'] = str_replace(';', '', $block[$i]['status']);
    }
    return $block;
}


texts: Dynamic variable - is that best way to dynamically assign?

texts:
Normally I could just declare the 'email' variable as the base class for both of EmailInbound & EmailOutbound, then cast-up to the inherited class.
However, I don't think when defining EF codefirst classes you can use inherited classes, only POCOs. I could be wrong. Hence I've used the dynamic keyword. Could I use Object() instead? Some direction appreciated here...

             if (source.ActionTypeId == (int)ActionTypes.EmailInbound  ||
                source.ActionTypeId == (int)ActionTypes.EmailOutbound)
            {
                dynamic email;
                if ( source.ActionTypeId == (int)ActionTypes.EmailInbound )
                {
                    email = source.EmailMessage.EmailInbound;
                }
                else
                {
                    email = source.EmailMessage.EmailOutbound;
                }

                return new ActionModel
                {
                    ActionTypeId = (ActionTypes)source.ActionTypeId,
                    Content = email.Body,
                    Created = email.DateSent,
                    GravatarUrl = HtmlHelperExtensions.getGravatarUrl(email.FromAddress, 25),
                    Subject = email.Subject,
                    User = Mapper.Map<User, UserModel>(source.EmailMessage.User),
                    EmailReplyTo = email.From,
                    ShowReplyButton = true,
                    ThreadUid = source.ThreadUid,
                    IsReply = source.IsReply
                };
            }
...


texts:
I attempted the Project Euler question #7 in C++ ("What is the 10 001st prime number?").

I took into account what I've been told about primes in order to create the most efficient algorithm I could in order to solve this. I would like to know if there is anything else I can do to check even fewer numbers for an even more efficient algorithm.

Also, I'm wondering if creating and using functions would be good practice in this scenario, and how I could go using functions more in coding.

#include <iostream>
#include <vector>

using namespace std;

// What is the 10 001st prime number?
int main()
{
    int countPrimes = 2;
    int checkIfPrime = 6;       // multiples of 6

    // sees if numbers adjacent to 6 are prime
    bool lessOnePrime = true;
    bool plusOnePrime = true;

    vector<int> primeVector;    // for holding primes to check for future primes
    //account for primes 2 and 3 beforehand:
    primeVector.push_back(2);
    primeVector.push_back(3);

    while (countPrimes < 10001)                 // checks until the 10001st prime has been found
    {
        for (int i = 0; primeVector[i] <= sqrt(checkIfPrime + 1); i++)      //checks only prime factors up to the square root
        {
            // checks if numbers adjacent to 6 have prime factors
            // if so, makes their respective booleans false
            if ((checkIfPrime - 1) % primeVector[i] == 0)
            {
                lessOnePrime = false;
            }
            if ((checkIfPrime + 1) % primeVector[i] == 0)
            {
                plusOnePrime = false;
            }
            // if both adjacent numbers to multiples of 6 aren't prime, exits loop
            if (lessOnePrime == false && plusOnePrime == false)
            {
                break;
            }
        }

        if (lessOnePrime)
        {
            primeVector.push_back(checkIfPrime - 1);
            countPrimes++;
            // cout << "#" << primeVector.size() << " prime number:\t" << checkIfPrime - 1 << endl;
        }
        if (plusOnePrime)
        {
            primeVector.push_back(checkIfPrime + 1);
            countPrimes++;
            // cout << "#" << primeVector.size() << " prime number:\t" << checkIfPrime + 1 << endl;
        }
        lessOnePrime = true;
        plusOnePrime = true;
        checkIfPrime += 6;
    }

    cout << "The " << countPrimes << "st prime number is:\n" << primeVector[countPrimes - 1] << endl;

    return 0;
}   // end main()