texts: Ensure temporary directory is cleaned up after use

texts:
Often when using temporary folders you need to think about cleaning them up afterwards.  My idea is to make use of the pipeline processing order to have the command which creates the directory also clean it up at the end of the pipeline.  i.e. When using the -Ephemeral parameter my function will tidy up after itself.

I'm interested in what members of the community think about this approach; i.e. as there are some issues which I'm aware of; and likely many more I'm not.

If something breaks the pipeline (e.g. break statement or a pipeline terminating exception), the end block won't run.
Users need to be aware of the pipeline's processing order; i.e. whilst the directory will be available to piped cmdlets' Begin and Process blocks, it will be removed before reaching their End blocks.

Sample Usage

#create a temp directory
New-TemporaryDirectory -Ephemeral | ForEach-Object {
    #generate a couple of CSVs in this directory
    $process = (Join-Path -Path $_.FullName -ChildPath 'processes.csv')
    Get-Process | Export-Csv -Path $process -NoTypeInformation -Encoding UTF8
    $service = (Join-Path -Path $_.FullName -ChildPath 'service.csv')
    Get-Service | Export-Csv -Path $service -NoTypeInformation -Encoding UTF8
    #do something with those files (e.g. send them as a mail)
    Send-MailMessage -SmtpServer 'mySmtp' -from 'me@example.com' -to 'me@example.com' -subject 'demo' -body 'demo' -Attachments $process,$service
    #once we hit the end block all these files will be cleaned up as the temp directory's deleted
}

Code

function New-TemporaryDirectory {
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        # Optional parameter allows us to specify which directory the new folder's created under.  By default this uses the user's temp directory
        [Parameter(ValueFromPipeline = $true)]
        [System.IO.DirectoryInfo]$Path = [System.IO.Path]::GetTempPath()
        ,
        # Behaves as per Credential on New-Object with FileSystem provider
        [Parameter()]
        [PSCredential]$Credential
        ,
        # Behaves as per Force on New-Object with FileSystem provider
        [Parameter()]
        [Switch]$Force
        ,
        #Removes any created folders once the pipeline completes
        #NB: this does not maintain an awareness of any parent directories as a side effect (we deliberately excluded Test-Path on the input to allow non-existent directories to be used for added flexibility)
        [Parameter()]
        [Switch]$Ephemeral
    )
    Begin {
        #choose which properties to splat; i.e. to prevent collision with existing Path variable
        [hashtable]$newItemSplat = $PSBoundParameters | Select-HashTable @('Credential','Force')
        #only bother to record what we're creating if we need to do something later; otherwise we're wasting memory
        if ($Ephemeral.IsPresent) {
            [System.Collections.Generic.List[System.IO.DirectoryInfo]]$DirectoriesCreated = New-Object -TypeName 'System.Collections.Generic.List[System.IO.DirectoryInfo]'
        }
    }
    Process {
        [string]$childPath = [System.Guid]::NewGuid()
        $newDirectory = New-Item -ItemType 'Directory' -Path (Join-Path -Path $Path -ChildPath $childPath) @newItemSplat
        Write-Output $newDirectory
        if ($Ephemeral.IsPresent) {
            $DirectoriesCreated.Add($newDirectory)
        }
    }
    End {
        if ($Ephemeral.IsPresent) {
            $DirectoriesCreated | Remove-Item -Force
        }
    }
}

# Select-Object, but for HashTables; i.e. allows us to grab a subset of "properties" from a given hashtable.
function Select-HashTable {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline=$true)]
        [HashTable]$InputObject
        ,
        [Parameter(Mandatory = $true, Position = 1)]
        [ValidateNotNullOrEmpty()]
        [String[]]$Properties
    )
    Process {
        ([HashTable]($InputObject.GetEnumerator() | Where-Object {$Properties -contains $_.Key})) + @{}
    }
}


texts: Implement The Singleton Pattern for Persistency managers Swift

texts:
I am creating an iOS app and I want to implement Singleton Pattern.
I have created "Singleton" LibraryAPI to act as an entry point UserManager object to get data from web API. after that I used a facade Pattern "method" to call UserManager implementation.

final class LibraryAPI {

    static let shared  =  LibraryAPI()
    private let userManager  =  UsersManager()
    private let isOnline  =  false

    private init(){

    }

    func getUsers() -> [User] {
        return userManager.getUsers()
    }
}

my questions:

if I have another Manager Class like "album" class should I use the same LibraryAPI and it will become a monolithic class and how to avoid that?
should I create a "Singleton" LibraryAPI class for each manager object like UserLibraryAPI and albumLibraryAPI?

Note: any references or articles are welcome :)


texts:
The following class monitors the clipboard and raises an event whenever the contents change. The monitoring starts when the class is created and ends when Dispose is called.

To achieve this a message-only window (a term that comes from the Win32 API) is created using an instance of HwndSource class (since I am using WPF). The window's handle is then registered via AddClipboardFormatListener to receive a message whenever the clipboard changes. The window's messages are processed by WndProc which raises the event when the WM_CLIPBOARDUPDATE message comes.

In other solutions for monitoring the clipboard I saw this was done on the actual main window of the application, but I wanted to separate the logic of monitoring the clipboard form the View and keep a clean MVVM. In an application I would instantiate the ClipboardMonitor in the ViewModel.

I am interested if there may be any hidden pitfalls where this approach may go wrong.

public sealed class ClipboardMonitor : IDisposable
{
    private static class NativeMethods
    {
        /// <summary>
        /// Places the given window in the system-maintained clipboard format listener list.
        /// </summary>
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool AddClipboardFormatListener(IntPtr hwnd);

        /// <summary>
        /// Removes the given window from the system-maintained clipboard format listener list.
        /// </summary>
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool RemoveClipboardFormatListener(IntPtr hwnd);

        /// <summary>
        /// Sent when the contents of the clipboard have changed.
        /// </summary>
        public const int WM_CLIPBOARDUPDATE = 0x031D;

        /// <summary>
        /// To find message-only windows, specify HWND_MESSAGE in the hwndParent parameter of the FindWindowEx function.
        /// </summary>
        public static IntPtr HWND_MESSAGE = new IntPtr(-3);
    }

    private HwndSource hwndSource = new HwndSource(0, 0, 0, 0, 0, 0, 0, null, NativeMethods.HWND_MESSAGE);

    public ClipboardMonitor()
    {
        hwndSource.AddHook(WndProc);
        NativeMethods.AddClipboardFormatListener(hwndSource.Handle);
    }

    public void Dispose()
    {
        NativeMethods.RemoveClipboardFormatListener(hwndSource.Handle);
        hwndSource.RemoveHook(WndProc);
        hwndSource.Dispose();
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == NativeMethods.WM_CLIPBOARDUPDATE)
        {
            OnClipboardContentChanged?.Invoke(this, EventArgs.Empty);
        }

        return IntPtr.Zero;
    }

    /// <summary>
    /// Occurs when the clipboard content changes.
    /// </summary>
    public event EventHandler OnClipboardContentChanged;
}


texts:
I am beginning to learn about object oriented programming in my programming class, and to make sure I had all the ideas down, I made a small palindrome checker program. It works by checking if the letter on the opposite side is the same.

from time import sleep  # To add readability delays

class PalindromeFinder:

    # Makes the variables
    def __init__(self):
        self.letter_count = {}
        self.loop = 0

    def check_for_palindrome(self, base):
        self.loop = 0
        for letter in base:
            # Checks if the letter in x position is the same as the letter in the -x position
            if base[self.loop] != base[-(self.loop + 1)]:
                return (f"{base} is not a palindrome")
            self.loop += 1
        return (f"{base} is a palindrome.")

def introduce_palindromes():
    print("Palindromes are really cool!")
    sleep(2)
    print("It when a word or phrase is the same backwards and forwards!")
    sleep(2)
    print("For example", palindrome_checker.check_for_palindrome("racecar"))
    sleep(2)
    print("While", palindrome_checker.check_for_palindrome("alarm"))
    sleep(2)
    print("Now you enter some palindromes!")

palindrome_checker = PalindromeFinder()
introduce_palindromes()
while True:
    sleep(1)
    print(palindrome_checker.check_for_palindrome(input("Enter your palindrome: ").lower()))

Since I have no idea what I am doing, I just generally want to know if what I am doing is not violating any conventions. More specifically, I want to know if having both functions and classes are ok, as well as if putting the variables in __init__ like I did is fine. Also, when initializing several instances at once, is there any documentation on were you do it? Do you do it between the class and functions or between the functions and the code?

Any other advice is welcome.


texts:
I am currently writing a simple PHP script that uses themes and I found myself writing these methods as part of a class that handles theme config files:

public function getArrayOfThemeNames()
{
    $this->loadUnfilteredDirectoryListing();
    $this->loadThemeFiles();
    return $this->theme_files;
}

private function loadUnfilteredDirectoryListing()
{
    $this->unfiltered_dir_listing = scandir($this->theme_config_directory);
}

private function loadThemeFiles()
{
    foreach($this->unfiltered_dir_listing as $file)
    {
        if($file != ".." and $file != ".")
            $this->theme_files[] = $file;
    }
}

Does the getArrayOfThemeNames() method violate SRP, as it could be argued it does two (or potentially even three)?  It loads the theme files array and then returns it.

Am I over-thinking this or should this be split into two methods -- one that fills the themes array, and another that returns it?


texts: How to make a matrix factorization system recommander faster?

texts:
I used and modified a matrix factorization function for a system recommender from quuxlabs.com. It works well for small sized input but when we get to large matrix it takes too much time. I was wondering if you had any idea to code it better to optimize the time it would take.

Here R is the rating matrix of a user with an item. 0 means that nothing has been predicted yet, the one we have to predict. K is the number of extrab features. P and Q are scores matrix on latent features that would help predict R as a whole.

import numpy

def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02):
    Q = Q.T
    for step in xrange(steps):
        for i in xrange(len(R)):
            for j in xrange(len(R[i])):
                if R[i][j] > 0:
                    try:
                        eij = R[i][j] - numpy.dot(P[i,:],Q[:,j])
                    except IndexError:
                        print("Oops!  i = ",i,"and len(P) = ",len(P))
                        P[i,:]
                        break
                    for k in xrange(K):
                        P[i][k] = P[i][k] + alpha * (2 * eij * Q[k][j] - beta * P[i][k])
                        Q[k][j] = Q[k][j] + alpha * (2 * eij * P[i][k] - beta * Q[k][j])
        eR = numpy.dot(P,Q)
        e = 0
        for i in xrange(len(R)):
            for j in xrange(len(R[i])):
                if R[i][j] > 0:
                    e = e + pow(R[i][j] - numpy.dot(P[i,:],Q[:,j]), 2)
                    for k in xrange(K):
                        e = e + (beta/2) * (pow(P[i][k],2) + pow(Q[k][j],2))
        if e < 0.001:
            break
    return P, Q.T

It works well with the following input :

R = [
     [5,3,0,1],
     [4,0,0,1],
     [1,1,0,5],
     [1,0,0,4],
     [0,1,5,4],
    ]

R = numpy.array(R)

N = len(R)
M = len(R[0])
K = 2

P = numpy.random.rand(N,K)
Q = numpy.random.rand(M,K)
nP, nQ = matrix_factorization(R, P, Q, K)

nR = numpy.dot(nP, nQ.T)

Yet, on real big matrix, the function took so long that I eventually cancelled it because I got tired of waiting.


texts: Sentences Clustering - Affinity Propagation & Cosine Similarity - Python & SciKit

texts:
I am looking for advices regarding my code. I am interested about the correctness, legibility and minimality of the solution.

import nltk, string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import AffinityPropagation

punctuation_map = dict((ord(char), None) for char in string.punctuation)
stemmer = nltk.stem.snowball.SpanishStemmer()

def stem_tokens(tokens):
    return [stemmer.stem(item) for item in tokens]

def normalize(text):
    return stem_tokens(nltk.word_tokenize(text.lower().translate(punctuation_map)))

vectorizer = TfidfVectorizer(tokenizer=normalize)

def get_clusters(sentences):
    tf_idf_matrix = vectorizer.fit_transform(sentences)
    similarity_matrix = (tf_idf_matrix * tf_idf_matrix.T).A
    affinity_propagation = AffinityPropagation(affinity="precomputed", damping=0.5)
    affinity_propagation.fit(similarity_matrix)

    labels = affinity_propagation.labels_
    cluster_centers = affinity_propagation.cluster_centers_indices_

    tagged_sentences = zip(sentences, labels)
    clusters = {}

    for sentence, cluster_id in tagged_sentences:
        clusters.setdefault(sentences[cluster_centers[cluster_id]], []).append(sentence)

    return clusters

sentences = [
    'Messi es el mejor jugador de Football.',
    'Neymar juega al football con Messi en el Barcelona.',
    'Los Pumas son la seleccion nacional de Rugby.',
    'Los Pumas ganaron contra Japon.',
    'Las Leonas ganaron una medalla de Oro en las olimpiadas.',
    'Carla Rebecchi es la capitana de las Leonas.'
]

clusters = get_clusters(sentences)
print()
for cluster in clusters:
    print(cluster, ':')
    for element in clusters[cluster]:
        print('  - ', element)

Thank you


texts:
I'm a hobbist trying to become a professional software developer. I do have a lot interest in Data Science in general and my goal is to master Python before diging deeper into specific data science topics.

I created this game when I started studying object oriented programming. Thank you all in advance.

import os
import getpass

class Hangman:
    winner = False
    word = ''
    mask = ''
    mistakes = []

    def __init__(self, word):
        self.word = word
        self.mask = '_ ' * len(word)

    def make_move(self, letter):
        letter_match = self.word.find(letter)
        if letter_match >= 0:
            for i, w in enumerate(self.word):
                if w == letter:
                    new_mask = list(self.mask)
                    new_mask[i * 2] = letter
                    self.mask = ''.join(new_mask)

            self.check_winner()
        else:
            self.mistakes.append(letter)
            print('Wrong!')

    def check_winner(self):
        if self.mask.find('_') < 0:
            self.show_board()
            print('You won!')
            self.winner = True

        return self.winner

    def check_looser(self):
        if len(self.mistakes) > 4:
            print('You loose! The word was %s' % self.word)
            quit()

    def show_board(self):
        os.system('cls')
        print(self.mask)
        print(self.mistakes)

    def play(self):
        while not self.winner:
            self.show_board()

            letter_input = input('Choose a letter: ').upper()
            self.make_move(letter_input)
            self.check_looser()

secret_input = getpass.getpass('Secret Word: ').upper()

game = Hangman(secret_input)
game.play()


texts:
I would like to see how would you write this code for best practices, it will help me to learn from you.

This is my jQuery code I use on scroll event to addClass and animate div element.

$(document).on("scroll", function() {

    var about = $(".media-about"),
        info = $(".media-info"),
        history = $(".media-history"),
        dimension = $(".media-dimension");

    var scroll = $(this).scrollTop();

    if (scroll >= 803) {
        about.closest(".animated").addClass("tada");
    } if (scroll >= 1723) {
        info.closest(".animated").addClass("tada");
    } if (scroll >= 2096) {
        history.closest(".animated").addClass("tada");
    }
    if (scroll >= 2548) {
        dimension.closest(".animated").addClass("flipInY");
    }

    // console.log(typeof scroll);
    console.log(scroll);
});


texts:
I tried to make a Server using Java with a Thread Pool. Any review is welcome:

/* User: koray@tugay.biz Date: 21/02/15 Time: 21:12 */

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Stack;

public class MyConnectionAccepter {

    private Stack<MySocketThread> mySocketThreads = new Stack<MySocketThread>();
    private volatile int currentNumberOfConnections = 0;

    public MyConnectionAccepter() {

        MySocketThread mySocketThreadOne = new MySocketThread(this);
        MySocketThread mySocketThreadTwo = new MySocketThread(this);

        mySocketThreadOne.setDaemon(true);
        mySocketThreadTwo.setDaemon(true);

        mySocketThreadOne.start();
        mySocketThreadTwo.start();

        mySocketThreads.push(mySocketThreadOne);
        mySocketThreads.push(mySocketThreadTwo);

    }

    public void start() throws IOException {

        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) {
            while (currentNumberOfConnections < 2) {
                Socket accept = serverSocket.accept();
                MySocketThread mySocketThread = mySocketThreads.pop();
                mySocketThread.setSocket(accept);
                currentNumberOfConnections++;
            }
        }

    }

    public void informIAmDone(MySocketThread mySocketThread) {
        mySocketThreads.push(mySocketThread);
        currentNumberOfConnections--;
    }
}

and

/* User: koray@tugay.biz Date: 21/02/15 Time: 21:04 */

import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class MySocketThread extends Thread {

    private volatile Socket socket;
    MyConnectionAccepter myConnectionAccepter;

    public MySocketThread(MyConnectionAccepter myConnectionAccepter) {
        this.myConnectionAccepter = myConnectionAccepter;
    }

    @Override
    public synchronized void run() {
        serve();
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public void serve() {
        while(socket == null) {

        }
        while (socket != null) {
            Scanner scanner = null;
            try {
                scanner = new Scanner(socket.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            String readLine;
            while (!(readLine = scanner.nextLine()).equals("bye")) {
                System.out.println(readLine);
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            socket = null;
            myConnectionAccepter.informIAmDone(this);
        }
        serve();
    }

}

and the Test Class:

/* User: koray@tugay.biz Date: 21/02/15 Time: 21:18 */

import java.io.IOException;

public class MyTestClass {

    public static void main(String[] args) throws IOException {
        MyConnectionAccepter myConnectionAccepter = new MyConnectionAccepter();
        myConnectionAccepter.start();
    }
}

My goal was to allow 2 connection at any time. So I can connect from Terminal like this:

Korays-MacBook-Pro:~ koraytugay$ telnet localhost 8888
Trying ::1...
Connected to localhost.
Escape character is '^]'.

But a new Thread will not be created, an available Thread will popped from the Stack and that will be used. If no Threads are available in the pool, the new connection will simply need to wait until some other connection closes. Closing a connection does not stop a Thread, it only makes it free.

Any review is welcome from any aspect.


texts: Grid walk problem and solving it recursively

texts:
On CodeEval, there's a Grid Walk challenge:

  There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1).

  Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to 19 are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 19. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than 19. How many points can the monkey access if it starts at (0, 0), including (0, 0) itself?

The first solution that came to my mind, intuitively, is to walk possible points recursively, breadth-first. Like this:

var monkey = function (x, y) {
    if (isPointAllowed(x, y) && !isPointVisited(x, y)) {
        visited.push({x: x, y: y});
        return 1 + monkey(x - 1, y) + monkey(x + 1, y) + monkey(x, y - 1) + monkey(x, y + 1);
    } else {
        return 0;
    }
};

So I return the count of current point and all adjacent points recursively, checking each point that it's allowed by game rules and hasn't been visited before. First is that the sum of the digits of x and y is less or equal 19; second is that the point isn't in visited array. The complete code is like:

var visited = [];

var isPointAllowed = function (x, y) {
    var o = 0;
    for (var i = 0, x = Math.abs(x), s = x.toString(), l = s.length; i < l; o += +s[i++]);
    for (var i = 0, y = Math.abs(y), s = y.toString(), l = s.length; i < l; o += +s[i++]);
    return o <= 19;
};

var isPointVisited = function (x, y) {
    for (var i = 0; i < visited.length; i++) {
        if (visited[i].x == x && visited[i].y == y)
            return true;
    }

    return false;
};

var monkey = function (x, y) {
    if (isPointAllowed(x, y) && !isPointVisited(x, y)) {
        visited.push({x: x, y: y});
        return 1 + monkey(x - 1, y) + monkey(x + 1, y) + monkey(x, y - 1) + monkey(x, y + 1);
    } else {
        return 0;
    }
};

console.log(monkey(0, 0));

The problem is that, on CodeEval's environment, my code executes more than 10 seconds, thus is always being terminated, and the challenge failed.

I tried to optimize the search and modified it to search only one (first) quadrant:

var monkey = function (x, y) {
    if (isPointAllowed(x, y) && !isPointVisited(x, y)) {
        visited.push({x: x, y: y});
        return 1 + monkey(x + 1, y) + monkey(x, y + 1);
    } else {
        return 0;
    }
};

console.log(monkey(0, 0)*4 - 299*4 + 1);

It outputs correct value but is still too slow.

Am I doing it wrong with recursion? Should I abandon this idea and implement simple nested cycle search?

What are most inefficient fragments of my code, like searching exhaustively for each point within visited array?

P.S. The problem itself is duplicate here but I believe my question is unique.


texts:
Lots of Prim's algorithm implementations seem long, and rely on a priority queue implementation.

If I use an adjacency matrix I can then calculate the next item to take using functional programming in Swift.

func prims (_ matrix : [[Int]]) {
    var selected = 0
    var selectedSoFar = Set<Int>()
    selectedSoFar.insert( (matrix[selected].enumerated().min{ $0.element < $1.element }?.offset)! )

    while selectedSoFar.count < matrix.count {
        var minValue = Int.max
        var minIndex = selected
        var initialRow = 0
        for row in selectedSoFar {
            let candidateMin = matrix[row].enumerated().filter{$0.element > 0 && !selectedSoFar.contains($0.offset) }.min{ $0.element < $1.element }
            if (minValue > candidateMin?.element ?? Int.max ) {
                minValue = candidateMin?.element ?? Int.max
                minIndex = (candidateMin?.offset) ?? 0
                initialRow = row
            }
        }
        print ("edge value \(minValue) with \(initialRow) to \(minIndex)")
        selectedSoFar.insert(minIndex)
        selected = (minValue)
    }
}

let input = [[0,9,75,0,0],[9,0,95,19,42],[75,95,0,51,66],[0,19,51,0,31],[0,42,66,31,0]]
prims(input)

Essentially is there anything "wrong" with this implementation? This is not homework, my code runs correctly for the included output, I've stepped through the output with pen and paper, and I appreciate this is faster if I use an adjacency list. However the Ray Wenderlich implementation of Prims uses 7 files and >200 lines of code. Am I missing something?


texts:
I have the below function that works and cycles through 3 possible levels. Is there a way to do the same as the function below but not have to do the multiple foreach statements, and not have to specify the number of levels as it is dynamic?

Basically the responses list can contain multiple GroupResponseTypes each of these can contain multiple ElementResponseBaseTypes which can be a variety of types themselves I'm interested in finding a value in an ElementResponseType And each ElementResponseBaseType itself can be a GroupResponseType, it to containing multiple types.

I'm looking at an easy way to scan through the whole structure for a specific Element.Reference and return the relevant value.

public static string GetValueFromFormField(List<ResponseBaseType> responses, string fieldref)
    {
        string fieldvalue = String.Empty;
        foreach (GroupResponseType groups in responses)
        {
            foreach (ElementResponseBaseType firstelements in groups.Responses)
            {
                if (firstelements.GetType() == typeof(ElementResponseType))
                {
                    if (firstelements.Element.Reference == fieldref)
                    {
                        ElementResponseType firstelement = new ElementResponseType();
                        firstelement = (ElementResponseType)firstelements;
                        fieldvalue = firstelement.Value;
                    }
                }
                else if (firstelements.GetType() == typeof(GroupResponseType))
                {
                    GroupResponseType secondgroup = new GroupResponseType();
                    secondgroup = (GroupResponseType)firstelements;
                    foreach (ElementResponseBaseType secondelements in secondgroup.Responses)
                    {
                        if (secondelements.GetType() == typeof(ElementResponseType))
                        {
                            if (secondelements.Element.Reference == fieldref)
                            {
                                ElementResponseType secondelement = new ElementResponseType();
                                secondelement = (ElementResponseType)secondelements;
                                fieldvalue = secondelement.Value;
                            }
                        }
                        else if (secondelements.GetType() == typeof(GroupResponseType))
                        {
                            GroupResponseType thirdgroup = new GroupResponseType();
                            thirdgroup = (GroupResponseType)secondelements;
                            foreach (ElementResponseBaseType thirdelements in thirdgroup.Responses)
                            {
                                if (thirdelements.GetType() == typeof(ElementResponseType))
                                {
                                    if (thirdelements.Element.Reference == fieldref)
                                    {
                                        ElementResponseType thirdelement = new ElementResponseType();
                                        thirdelement = (ElementResponseType)thirdelements;
                                        fieldvalue = thirdelement.Value;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return fieldvalue;
    }


texts:
I'm playing around with PHP, trying to write a small ORM. Having worked with Magento quite a bit lately, I've fallen in love with the automagic getters/setters that Magento, I think, inherited from Zend.

For those, who've never seen it in action, this is what I'm talking about:

$my_object->setSomeProperty('foo');

just works, as does:

$my_object->getSomeProperty();

which obviously yields "foo".

Since I'm trying to implement an ORM, my goal is to provide the user with the ability to use generic functions on one hand, where:

$orm_object->setSomeProperty('foo'):

would map to:

$orm_object->set('some_property', 'foo') // set() would obviously be a generic part of the ORM

by convention.

On the other hand, if the user wanted to handle some situations differently, he could do so by defining a more specifically named function.

class foo extends ORM {
    function setSome($arg_1, $arg_2)
    {
        …
    }
}

The above example call

$orm_object->setSomeProperty('foo')

would now be mapped to

$orm_object->setSome('property', 'foo')

instead of the default set().

Do you have any feedback on my implementation?

function __call($name, $arguments) {
    if(preg_match('/([a-z]+)/', $name, $matches))
    {
        $action = $matches[0];
        if(preg_match_all('/([A-Z]+)([^A-Z]+)/', $name, $matches))
        {
            $matches = $matches[0];
            array_unshift(&$matches, $action);
            for ($i = count($matches); $i > 0; $i--)
            {
                $potential_func_name = implode('', array_slice($matches, 0, $i));
                if (method_exists($this, $potential_func_name))
                {
                    $arguments_rest = array_slice($matches, $i);
                    break; // found matching function!
                }
            }

            // handle number of arguments now!
            $reflector = new ReflectionClass($this);
            $num_expected_params = count($reflector->getMethod($potential_func_name)->getParameters());

            $num_expected_params = $num_expected_params - count($arguments);

            $params = array();
            for ($i = $num_expected_params; $i > 1; $i--)
            {
                $params[] = strtolower(array_shift($arguments_rest));
            }

            $last_var = '';
            $i = 0;
            foreach($arguments_rest as $part)
            {
                $last_var .= strtolower($part);
                $i++;
                if ($i != count($arguments_rest)) $last_var .= '_';
            }

            $params[] = $last_var;

            if (count($arguments) == 1) {
                $arguments = array_shift(&$arguments);
            }

            $params[] = $arguments;

            return(call_user_func_array(array($this, $potential_func_name), $params));
        }
    }
}


texts: Finds a position to break a string that is not part of a

texts:
I have a 'read more' angular directive copied from:
https://github.com/doukasd/AngularJS-Components/blob/master/dd-text-collapse/dd-text-collapse.js

Some of my text can already have
 tags in it (I ONLY allow just
) so I just needed to handle that...below is only the extra code I wrote for this purpose.

Does it seems long for something seemingly trivial?

    //---All this to not break upon
 --
    if (text.includes('
')) {
        var charAtMaxLength = text.charAt(maxLength).toLowerCase();
        //console.log(charAtMaxLength);
        switch (charAtMaxLength) {
            case '<':
                if (text.charAt(maxLength + 3).toLowerCase() === '>') {
                    //console.log('Decrease maxLength by 1');
                    maxLength -= 1;
                }
                break;
            case 'b':
                if (text.charAt(maxLength - 1).toLowerCase() === '<') {
                    //console.log('Decrease maxLength by 2');
                    maxLength -= 2;
                }
                break;
            case 'r':
                if (text.charAt(maxLength - 2).toLowerCase() === '<') {
                    //console.log('Decrease maxLength by 3');
                    maxLength -= 3;
                }
                break;
            case '>':
                if (text.charAt(maxLength - 3).toLowerCase() === '<') {
                    //console.log('Increase maxLength by 1');
                    maxLength += 1;
                }
                break;
            default:
                //Do nothing.
                break;
        }
        //console.log(charAtMaxLength);
    }
    //--------------------------------------


texts:
I'm new to Haskell and I've made a very short KenKen solver. Any input is welcome.

import Data.List
import Control.Monad

set :: [Int] -> Bool
set x = x == nub x

mats :: Int -> [[[Int]]]
mats x = filter (all set . transpose) . replicateM x $ permutations [1 .. x]

doIt :: Int -> [([(Int, Int)], [Int] -> Int, Int)] -> [[Int]]
doIt n blocks = join . take 1 . foldl' (flip filter) (mats n) $ map bfun blocks

revSort :: Ord a => [a] -> [a]
revSort = sortBy $ flip compare

quotient :: [Int] -> Int
quotient = foldl1 div . revSort

sub :: [Int] -> Int
sub = foldl1 (-) . revSort

bfun :: ([(Int, Int)], [Int] -> Int, Int) -> [[Int]] -> Bool
bfun (locs, opp, res) mat = res == opp (map (\ (x, y) -> mat !! x !! y) locs)

sampleBlocs :: [([(Int, Int)], [Int] -> Int, Int)]
sampleBlocs = [([(0, 0), (1, 0)], quotient, 2),
               ([(0, 1), (1, 1)], sub, 1),
               ([(0, 2)], sum, 1),
               ([(2, 0), (2, 1)], sub, 2),
               ([(1, 2), (2, 2)], product, 6)]

sampleBlocs2 :: [([(Int, Int)], [Int] -> Int, Int)]
sampleBlocs2 = [([(0, 0), (0, 1)],         sub,      2),
                ([(1, 0)],                 sum,      4),
                ([(2, 0), (2, 1)],         quotient, 2),
                ([(3, 0), (3, 1)],         sub,      1),
                ([(0, 2), (1, 1), (1, 2)], product,  8),
                ([(2, 2), (3, 2), (3, 3)], sum,      8),
                ([(0, 3), (1, 3), (2, 3)], sum,      6)]

-- doIt 3 sampleBlocs == [[2,3,1],[1,2,3],[3,1,2]]
-- doIt 4 sampleBlocs2 == [[1,3,4,2],[4,1,2,3],[2,4,3,1],[3,2,1,4]]


texts:
These two classes are part of a networking layer module that I am building:

public abstract class BaseRequest {

    protected RequestCreator mCreator;

    public BaseRequest() {
        setupRequestCreator();
    }

    private setupRequestCreator() {
        mCreator = new RequestCreator.Builder()
            .headers(getHeaders())
            .parser(getParser())
            .build();
    }

    public abstract Headers getHeaders();
    public abstract Parser getParser();
}

public class UserRequest extends BaseRequest {

    private Headers mHeaders;
    private Request<User> mRequest;

    private interface UserService {
        @GET("/users/{id}")
        User getUser(String id);
    }

    public UserRequest(Headers headers) {
        mHeaders = headers;
        mRequest = mCreator.createRequest(UserService.class);
    }

    @Override
    public Headers getHeaders() {
        return mHeaders;
    }

    @Override
    public Parser getParser() {
        return null;
    }
}

The framework that I am using requires me to configure/build a RequestCreator for each type of Request that I am going to use.

To make the process of adding new classes for different requests as pain-free as possible, I moved the building logic of the RequestCreator in an abstract class. This way I'll only have to extend it and override some methods that indicate how the RequestCreator should be configured - sort of a template method pattern.

The actual problem is this: when someone creates an instance of UserRequest, super() gets called right before UserRequest's member variables are set. What this means is that the RequestCreator will already be built by the time mHeaders are set. This is wrong because the building process needs a reference to mHeaders in order for it to behave as intended.

One way to get around this is to leave BaseRequest's constructor empty and to call setupRequestCreator() in the UserRequest's constructor, but only after setting the instance variables first. This however feels "hacky" because other people will have to be aware of this when they are creating new subclasses.

I tried other workarounds too, but nothing felt quite right. I was hoping someone could provide me with a better solution.


texts: How to efficiently (fast) calculate the transpose of a *permutation matrix* in Python3?

texts:
The permutation matrix is represented as a list of positive integers, plus zero. The number indicates the position of the 1 in that row, e.g. a number zero would mean that the 1 is in the right-most position².

My first attempt is as follows, together with a printing function to help assess the result.
It seems too convoluted to me.
Please note that a permutation matrix multiplication is simpler than an ordinary matrix multiplication.

def transpose(m):
    """Transpose a permutation matrix.
    m: list of positive integers and zero."""
    c = {}
    idx = 0
    for row in reversed(m):
        c[-row] = idx
        idx += 1

    return list(map(
        itemgetter(1), sorted(c.items(), reverse=False, key=itemgetter(0))
    ))

def print_binmatrix(m):
    """Print a permutation matrix 7x7.
    m: list of positive integers and zero."""

    for row in m:
        print(format(2 ** row, '07b'), row)

# Usage example with a matrix 35x35. Ideally, it should scale up without sacrificing speed at smaller matrices like this.
transpose([8, 4, 21, 17, 30, 28, 1, 27, 5, 3, 16, 12, 11, 14, 20, 6, 33, 19, 22, 25, 31, 15, 13, 18, 10, 0, 7, 2, 9, 23, 24, 26, 29, 32, 34])
# Result
[25, 6, 27, 9, 1, 8, 15, 26, 0, 28, 24, 12, 11, 22, 13, 21, 10, 3, 23, 17, 14, 2, 18, 29, 30, 19, 31, 7, 5, 32, 4, 20, 33, 16, 34]

[2]: This way, the "zero matrix" is the one with 1's in the secondary diagonal, since only one 1 is allowed per column.


texts: RAII and code duplication in constructor/destructor

texts:
I have a class hierarchy similar to this:

struct VideoCapture { virtual open(const string& uri) = 0; virtual close() = 0; };
struct VideoCapture1 : public VideoCapture {...};
struct VideoCapture2 : public VideoCapture {...};
struct VideoCapture3 : public VideoCapture {...};

I added the following constructor and destructor in each of these classes:

VideoCaptureN(const string& uri) { open(uri); }
~VideoCaptureN() { if (!isOpen()) { close(); } }

Though, providing RAII this did not pass the code review as I had to duplicate the same exact code in every classes.

What would be the solution to get RAII and avoid code duplication?


texts: Notify observers when object attributes update

texts:
I have a Singleton manager class for managing request model and its attributes.

My main aim is update object observers when some of the object attributes changes.

class FlightSearchManager {

    private val _flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData()
    val flightSearchRequestModelLiveData : LiveData<FlightSearchRequestModel> get() = _flightSearchRequestModelLiveData

    var flightSearchRequestModel : FlightSearchRequestModel

    init {
        flightSearchRequestModel =
            FlightSearchRequestModel(
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null)
    }

    fun updateFlightSearchRequestModel(_arriveAirport : String? = null,
                                       _arriveAirportId: Int? = null,
                                       _departureAirport : String? = null,
                                       _departureAirportId: Int? = null,
                                       _departureDate : String? = null,
                                       _isRoundTrip : Boolean? = false,
                                       _paxTypeCount : List<PaxTypeCount>? = null,
                                       _returnDate : String? = null,
                                       _seatClass : String? = null) {
        flightSearchRequestModel.apply {
            arriveAirport = _arriveAirport ?: arriveAirport
            arriveAirportId = _arriveAirportId ?: arriveAirportId
            departureAirport = _departureAirport ?: departureAirport
            departureAirportId = _departureAirportId ?: departureAirportId
            departureDate = _departureDate ?: departureDate
            isRoundTrip = _isRoundTrip ?: isRoundTrip
            paxTypeCount = _paxTypeCount ?: paxTypeCount
            returnDate = _returnDate ?: returnDate
            seatClass = _seatClass ?: seatClass
            // Notify all listeners of live data
            _flightSearchRequestModelLiveData.value = this
        }
    }
}

When I want to notify observers I call:

flightSearchManager.updateFlightSearchRequestModel(_seatClass = "1")

This solution does not seem good solution. How can I write it more intelligently?


texts:
I am reordering columns in an array and removing one column. The mapping is as follows:

| Item   | In index | Out Index |
|--------|----------|-----------|
| Item1  | 1        | 6         |
| Item2  | 2        | 4         |
| Item3  | 3        | 5         |
| Item4  | 4        | 7         |
| Item5  | 5        | 8         |
| Item6  | 6        | 9         |
| Item7  | 7        | 10        |
| Item8  | 8        | #N/A      |
| Item9  | 9        | 1         |
| Item10 | 10       | 2         |
| Item11 | 11       | 3         |

So, with the following data in range A1:K2 of the active sheet:

| Category 1 | RX9 | East Midlands | 4588 | 14:47:36 | 00:08:25 | 00:14:52 |   | 01/10/17 | 09/02/18 | England |
|------------|-----|---------------|------|----------|----------|----------|---|----------|----------|---------|
| Category 1 | RX9 | East Midlands | 4588 | 14:47:36 | 00:08:25 | 00:14:52 |   | 01/10/17 | 09/02/18 | England |

I get, after running the code:

| 01/10/17 | 09/02/18 06:09 | England | RX9 | East Midlands | Category 1 | 4588 | 0.616388889 | 0.005844907 | 0.010324074 |
|----------|----------------|---------|-----|---------------|------------|------|-------------|-------------|-------------|
| 01/10/17 | 09/02/18 06:09 | England | RX9 | East Midlands | Category 1 | 4588 | 0.616388889 | 0.005844907 | 0.010324074 |

Notes:

I don't expect the array number of rows to ever exceed 12,240.
The time columns have become doubles in the output. Sorted with code to format the relevant columns - not pertinent to question.

Is there a more efficient way to do this without making arrays left, right and centre?

Option Explicit
Public Const OutputColumnsTotal As Long = 10

Private Sub test()

    Dim tempArr() As Variant

    With ActiveSheet

        tempArr = .Range("A1:K2").Value
        tempArr = ShuffleArrayColumns(tempArr)

        .Range("A5").Resize(UBound(tempArr, 1), UBound(tempArr, 2)) = tempArr

    End With

End Sub

Private Function ShuffleArrayColumns(ByRef tempArr As Variant) As Variant

    If Not UBound(tempArr, 2) - 1 = OutputColumnsTotal Then

        Debug.Print "Array tempArr as wrong # columns in " & Application.VBE.Activecodepane.CodeModule
        Exit Function

    Else

        Dim i As Long
        Dim tempArr2() As Variant
        ReDim tempArr2(1 To UBound(tempArr, 1), 1 To OutputColumnsTotal)

        For i = LBound(tempArr, 1) To UBound(tempArr, 1)

            tempArr2(i, 1) = Format$(tempArr(i, 9),"yyyy-mm-dd") 'to preserve UK date format. Sheet is formatted to display "mmm-yy".
            tempArr2(i, 2) = tempArr(i, 10)
            tempArr2(i, 3) = tempArr(i, 11)
            tempArr2(i, 4) = tempArr(i, 2)
            tempArr2(i, 5) = tempArr(i, 3)
            tempArr2(i, 6) = tempArr(i, 1)
            tempArr2(i, 7) = tempArr(i, 4)
            tempArr2(i, 8) = tempArr(i, 5)
            tempArr2(i, 9) = tempArr(i, 6)
            tempArr2(i, 10) = tempArr(i, 7)

        Next i

    End If

    ShuffleArrayColumns = tempArr2

End Function


texts:
I am currently developing a password generator and just finished my first version. I know there is a lot to do but before I proceed with the next version I would like to have feedback on my current source code.

GitHub

The embedded source code does not contain comments to reduce characters.

Main.cpp

void main()
{
    Controller::PwGenerator* oController = new Controller::PwGenerator();
    oController->Run();
    delete oController;
}

PwGenerator.h

#pragma once
namespace View
{
    class Terminal;
}
namespace Utility
{
    class Security;
}
namespace Controller
{
    class PwGenerator
    {
        private:
            View::Terminal* oTerminal;
            Utility::Security* oSecurity;
        public:
            PwGenerator();
            void Run();
            ~PwGenerator();
    };
}

PwGenerator.cpp

#include "PwGenerator.h"
#include "Terminal.h"
#include "Security.h"
#include <fstream>
#include <ctime>
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
Controller::PwGenerator::PwGenerator()
{
    this->oTerminal = new View::Terminal();
    this->oSecurity = new Utility::Security();
}
void Controller::PwGenerator::Run()
{
    bool bFinish = false;
    int iMenuItem = 1;
    std::ofstream oFstream;
    std::time_t oTime = time(0);
    std::tm* timePtr = std::localtime(&oTime);
    this->oTerminal->Programminfo();
    #ifdef WIN32
    Sleep(3000);
    #else
    usleep(3000 * 1000);
    #endif
    do
    {
        this->oTerminal->Menu();
        iMenuItem = this->oTerminal->SelectMenuOption();
        switch (iMenuItem)
        {
            case 0:
                bFinish = true;
            break;
            case 1:
                this->oTerminal->Programminfo();
            break;
            case 2:
                this->oSecurity->GeneratePw( this->oTerminal->MenuePwGen() );
                if (this->oTerminal->MenueSavePw() == true)
                {
                    this->oTerminal->Print("The password has been saved in a file.");
                    oFstream.open("PasswordGenerator.txt", std::fstream::app);
                    oFstream << "\r\n[" << (timePtr->tm_year + 1900) << "." << (timePtr->tm_mon+1) << "." << timePtr->tm_mday << " " << timePtr->tm_hour << ":" << timePtr->tm_min << ":" << timePtr->tm_sec << "] " << this->oSecurity->GetPw();
                    oFstream.close();
                }
                else
                {
                    this->oTerminal->Print("Generated password:");
                    this->oTerminal->Print( this->oSecurity->GetPw() );
                }
            break;
            default:
            break;
        }
    } while (bFinish == false);
}
Controller::PwGenerator::~PwGenerator()
{
    delete this->oTerminal;
}

Security.h

#pragma once
#include <string>
namespace Utility
{
    class Security
    {
        private:
            std::string sPassword;
            std::string sAllowedCharacter;
        public:
            Security();
            void GeneratePw(int iLength);
            std::string GetPw();
            ~Security();
    };
}

Security.cpp

Utility::Security::Security()
{
    this->sPassword = std::string("");
    this->sAllowedCharacter =      std::string("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789!$%&()[]{}=?");
}
void Utility::Security::GeneratePw(int iLength)
{
    this->sPassword = this->sAllowedCharacter;
    std::random_shuffle(this->sPassword.begin(), this->sPassword.end());
    this->sPassword = this->sPassword.substr(0, iLength);
    std::random_shuffle(this->sPassword.begin(), this->sPassword.end());
}
std::string Utility::Security::GetPw()
{
    return this->sPassword;
}
Utility::Security::~Security()
{
}


texts:
I'm trying to find the best - read: readable, maintainable, robust, threadsafe, usable - solution for a State Machine in python.
For this I've been looking at the State Design Pattern. However I want a pythonic and lean solution (saying not implementing functions in subclasses that are not needed).

Long story short, here's what I came up with. What do you think?

#!/bin/env python
# -*- utf-8 -*-
"""Boiler Plate code for implementing a state machine according to
state design pattern

"""

class State(object):
    """Base class for a state in a statemachine

    No statemachine class is needed. State transitions have to be
    defined in self.transitions.

    The object is callable and by calling it input is handled and
    the next state is returned.

    Example usage:

    def handle(self, msg):
        self._state = self._state(msg)

    """
    transitions = [(None, None, None)]

    def __init__(self, state_context):
        self._context = state_context

    def __call__(self, inp):
        new_state = self

        state_action_list = [(state, action) for cls, state,
                     action in self.transitions if
                     isinstance(inp, cls)]
        if 1 == len(state_action_list):
            state, action = state_action_list[0]
            if action is not None:
                try:
                    action(inp)
                except TypeError:
                    action(self, inp)
            new_state = state(self._context)

        elif 1 < len(state_action_list):
            raise AmbiguousTransitionError(inp, self)

        print ("[DEBUG] %s -- %s --> %s" %
               (self.__class__.__name__,
            inp.__class__.__name__,
            new_state.__class__.__name__ ))

        return new_state

class AmbiguousTransitionError(Exception):
    """Raised if more than one state transition was found for a
    given input

    """
    pass

################################################## Example

class MsgA(object): pass
class MsgB(object): pass
class MsgC(object): pass

class StateA(State): pass

class StateB(State):
    @staticmethod
    def print_msg(inp):
        print "Inp: ", inp

class StateC(State):
    def print_context(self, unused_inp):
        print "Context: ", self._context

StateA.transitions = [(MsgA, StateB, None)]
StateB.transitions = [(MsgB, StateC, StateB.print_msg)]
StateC.transitions = [(MsgB, StateB, None),
              (MsgC, StateA, StateC.print_context)]

class Context(object):
    def __init__(self):
        self._state = StateA(self)

    def handle(self, msg):
        self._state = self._state(msg)

if __name__ == "__main__":
    CONTEXT = Context()
    CONTEXT.handle(MsgA())
    CONTEXT.handle(MsgB())
    CONTEXT.handle(MsgC())
    CONTEXT.handle(MsgB())

The output looks like this:

python State.py

[DEBUG] StateA -- MsgA --> StateB
Inp:  <__main__.MsgB object at 0x1eb6250>
[DEBUG] StateB -- MsgB --> StateC
Context:  <__main__.Context object at 0x1eb6150>
[DEBUG] StateC -- MsgC --> StateA
[DEBUG] StateA -- MsgB --> StateA


texts: Loops through each row in a binary image and gets the width of each group of black or white pixels

texts:
Example image:

Code:

#get height and width of image
height, width = possible_barcode_img.shape[:2]

#prepare list for rows
barcode_rows = []

for i in range(height):

    # set variables and list for beginning of row
    white_bar_width = 0
    black_bar_width = 0
    barcode_row = []

    for j in range(width):
        if possible_barcode_img[i,j] == 0:
            #add to count
            black_bar_width = black_bar_width +1

            #ensure last bar is gotten if there was one
            if white_bar_width > 0:
                #add bar to row
                barcode_row.append(["white", white_bar_width])
                white_bar_width = 0

        elif possible_barcode_img[i,j] > 0:
            #add to width
            white_bar_width = white_bar_width +1

            #ensure last bar is gotten if there was one
            if black_bar_width > 0:
                #add bar to row
                barcode_row.append(["black", black_bar_width])
                black_bar_width = 0

    #ensure last bar is gotten since a row just finished
    if white_bar_width > 0:
        #add bar to row
        barcode_row.append(["white", white_bar_width])

    elif black_bar_width > 0:
        #add bar to row
        barcode_row.append(["black", black_bar_width])

    #add entire row to rows
    barcode_rows.append(barcode_row)

Print row 50 of the picture in the question print(barcode_rows[50]):

[['black', 3], ['white', 7], ['black', 4], ['white', 6], ['black', 4], ['white', 6], ['black', 13], ['white', 5], ['black', 4], ['white', 15], ['black', 4], ['white', 5], ['black', 5], ['white', 5], ['black', 13], ['white', 15], ['black', 13], ['white', 5], ['black', 13], ['white', 6], ['black', 3], ['white', 15], ['black', 5], ['white', 4], ['black', 4], ['white', 14], ['black', 13], ['white', 6], ['black', 4], ['white', 14], ['black', 13], ['white', 14], ['black', 5], ['white', 5], ['black', 4], ['white', 5], ['black', 4], ['white', 14], ['black', 4], ['white', 5], ['black', 4], ['white', 5], ['black', 13], ['white', 14], ['black', 13], ['white', 5], ['black', 14], ['white', 4], ['black', 5], ['white', 4]]

50 bars found as in the picture, ready for decoding.

This has quite an effect on fps when doing it with video. I know that I don't have to loop through the entire image, I will have it send to a decoder after each row of pixels and end the loop if successful.

However I'm hoping there's a more optimized way to do this than using the Python loops on each individual pixel because I don't think the above will be fast enough for my needs.


texts: Helper method to shuffle cards list for online gaming

texts:
I have written this code to shuffle a deck of cards. I would like to hear your inputs.

public static class Helper
{

    public static Int32 GetRandomNo(this RNGCryptoServiceProvider rng, byte[] data)
    {
        rng.GetBytes(data);
        var randomNo = BitConverter.ToInt32(data, 0);
        return randomNo;
    }

    public static void Shuffle<T>(this List<T> source)
    {
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            // Buffer storage.
            byte[] data = new byte[4];

            source =
                source.Select(element => new {element, randomValue = rng.GetRandomNo(data)})
                    .OrderBy(entry => entry.randomValue)
                    .Select(entry => entry.element)
                    .ToList();
        }
    }
}


texts:
I remembered a cwrite application that I used in the good old DOS times.

Basically it took a color code as first argument and some text as the second and printed the given text in the specified color. Also it supported some escape sequences.

Since Windows NT does not support ANSI Escape Codes it's not as easy to change the color of certain text within a batch script.

Well Windows 10 does support ANSI.... (It took MS 10 Versions to implement that?!)

Now I wanted to re-implement that cwrite from those days. With minimal requirements. Just win32 api. Nothing else.

I have commented some lines in the code that I am unsure of.

#include <Windows.h>

int main(int argc, char ** argv) {
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    if(!h) { return -2; } // god help us

    CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
    BOOL v = GetConsoleScreenBufferInfo(h, &csbiInfo);
    if(!v) { return -1; } // still... god should help us

    WORD wOld = csbiInfo.wAttributes;

    // No arguments: show the user how it works
    //  and how the colors look...
    if(argc < 2) {
        printf("%s <color> [text]\n", argv[0]);
        printf(" <color> can be any of the following:\n");
        WORD i;

        for(i = 0; i < 0x100; i++) {
            v &= SetConsoleTextAttribute ( h, i );
            if(i % 0x10 == 0) { printf("\n"); }
            printf("%4i", i);

        }
        printf("\n");
        v &= SetConsoleTextAttribute( h, wOld);
        return v;
    }

    WORD wNew = (WORD)atoi(argv[1]);

    v &= SetConsoleTextAttribute ( h, wNew );
    // well now this is... unfortunate
    if(!v) { return -3; }

    /*
     * Classic "it's not a bug, but a feature"
     * If there is no argv[2] then we just change the color
     * ... without resetting to the original
     */
    if(argc < 3) { return 2; }

    // Now this is to handle some special characters
    // parhaps I should use sprintf?
    WORD j;
    for(j = 0; j < strlen(argv[2]); j++) {
        if(argv[2][j] == '\\') {
            switch(argv[2][j + 1]) {
                case 'n':
                case 'r':
                    argv[2][j]   = 0xa;
                    argv[2][j+1] = 0xd;
                    break;
                case 't':
                    argv[2][j] = ' ';
                    argv[2][j+1] = ' ';
                    break;
                default:
                    /* ignore */
                    break;
            }
        }
    }

    // Okay:
    // How do I turn a char ** into a va_list ???
    printf(argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9]);

    // Now reset the color
    v &= SetConsoleTextAttribute ( h, wOld );
    if(!v) { /* nop */ } // could not reset color...

    return v;
}


texts:
I built a 404 page which involves parallax scrolling text. The program updates the position of 100-200 text nodes at each animation frame called with window.requestAnimationFrame. It runs decently well on my MacBook (although it occupies significant CPU), but on weaker computers like my phone, it runs very sluggishly.

How can I optimize my code to achieve better performance?

var scene;

function randint(low, high) { // Return a random integer between low and high
  return Math.floor(( Math.random()*(high-low) ))+low;
}

// Add a layer to the scene

function addLayer() {
  // Make  a "layer" in the parallax animation
  var layer = document.createElement("div");
  // Give it a random Z value (0 to 1)
  layer.setAttribute("class", "layer");
  layer.setAttribute("data-z", Math.random().toFixed(2));

  // Make a div inside that says "404"
  layer.appendChild(document.createTextNode("404"));
  // Random X position
  layer.style.left = randint(-10, window.innerWidth) + "px";
  // Below bottom of screen
  layer.style.top = window.innerHeight + "px";
  // Font size and weight based on Z value
  var z = parseFloat(layer.getAttribute("data-z"));
  layer.style.fontSize = Math.floor(z * 150) + "px";
  layer.style.fontWeight = Math.ceil(z * 4) * 100;
  // Random opacity
  layer.style.opacity = (Math.random() / 10).toFixed(2);

  // Add nodes to appropriate parents
  scene.appendChild(layer);
}

function updatePositions() {
  var layers = scene.getElementsByTagName("div");
  var layer, div, z;
  for (var i = 0; i < layers.length; i++) {
    layer = layers[i];
    z = parseFloat(layer.getAttribute("data-z"));
    y = parseInt(layer.style.top.slice(0, layer.style.top.length - 2));
    layer.style.top = (y - Math.ceil(z * 10)).toFixed(2) + "px";

    if (y < (-150)) { // Max fontsize is 150px
      scene.removeChild(layer);
    }
  }
}

function updateColor() {
  var hue = (parseFloat(document.body.getAttribute("data-hue")) + 0.25) % 360;
  document.body.setAttribute("data-hue", hue.toString());
  var hex = chroma(hue, 1, 1, "hsv").brighten().hex();
  document.body.style.color = hex;
  document.getElementsByTagName("a")[0].style.backgroundColor = hex;
}

function update() {
  addLayer();
  updatePositions();
  updateColor();
  window.requestAnimationFrame(update); // Recur
}

scene = document.getElementById("scene");
window.requestAnimationFrame(update);
body {
  background-color: #222;
  margin: 0;
  width: 100vw;
  height: 100vh;

  /* Global font settings */
  color: #fff;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#scene {
  position: fixed;
  top: 0;
  left: 0;
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.layer {
  position: absolute;
}

.main {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;

  text-align: center;

  opacity: 0.5;
}

h1 {
  font-size: 200px;
  margin-bottom: 0;
}

.main p {
  font-size: 150%;
  margin-top: 0;
}

.main a {

  color: #222;
  background-color: #fff;
  padding: 10px;

  text-decoration: none;
  font-size: 150%;
  font-weight: 600;
}

404

That page couldn't be found.

    Home

Running this snippet in full window will more accurately emulate how it will appear on my website.

Here's a JSFiddle if it's preferred.


texts:
As part of an online course exercise, I was supposed to implement Merge Sort in C. Pointers were still not discussed prior to this exercise, so I have to work with arrays. Memory efficiency is not something I'm supposed to be focused on.

#include <cs50.h>
#include <stdio.h>

#define DEBUG

void getArray(int[], int);
void printArray(int[], int);
void mergesort(int[], int);
void merge(int[], int, int[], int, int[]);

int main(void)
{
    printf("Length of array: ");
    int len = GetInt();

    int array[len];
    getArray(array, len);

    printf("Before sort: ");
    printArray(array, len);

    mergesort(array, len);

    printf("After sort: ");
    printArray(array, len);

    return 0;
}

void getArray(int values[], int len)
{
    for (int i = 0; i < len; i++)
    {
        printf("Number %i: ", i + 1);
        values[i] = GetInt();
    }
}

void printArray(int values[], int len)
{
    for (int i = 0; i < len; i++)
    {
        printf("%i ", values[i]);
    }

    printf("\n");
}

void mergesort(int array[], int len)
{
    if (len <= 1)
        return;

    // right side and left side lengths
    int rlen, llen;

    //calculate lengths of the half-arrays
    rlen = len / 2;
    llen = len - rlen;

    int rhalf[rlen];
    int lhalf[llen];

    // copy first half of array into rhalf
    for (int i = 0; i < rlen; i++)
    {
        rhalf[i] = array[i];
    }

    // copy the remainder of array into lhalf
    for (int i = 0; i < llen; i++)
    {
        lhalf[i] = array[i + rlen];
    }

    #ifdef DEBUG
        printf("len: %i\nrlen: %i\nllen: %i\n", len, rlen, llen);
        printf("rhalf: ");
        printArray(rhalf, rlen);
        printf("lhalf: ");
        printArray(lhalf, llen);
    #endif

    mergesort(rhalf, rlen);
    mergesort(lhalf, llen);
    merge(rhalf, rlen, lhalf, llen, array);
}

void merge(int rhalf[], int rlen, int lhalf[], int llen, int array[])
{
    int i = 0, j = 0, k = 0;

    // iterate over rhalf and lhalf until one counter reaches its end
    while (i < rlen && j < llen)
    {
        if (rhalf[i] < lhalf[j])
        {
            array[k] = rhalf[i];
            i++;
        }

        else
        {
            array[k] = lhalf[j];
            j++;
        }

        k++;
    }

    // place the remaining elements (if any) in either half in their place
    while (i < rlen)
    {
       array[k] = rhalf[i];
       i++;
       k++;
    }

    while (j < llen)
    {
        array[k] = lhalf[j];
        j++;
        k++;
    }

    #ifdef DEBUG
        printf("merged: ");
        printArray(array, llen + rlen);
    #endif
}

What can I do to improve the code in terms of readability, style and performance?


texts: Bash code to install bootstrap in a Ruby on Rails repository

texts:
Wrote some code to install bootstrap (latest) in a newly created rails application.

update: fixed a typo

yarn add bootstrap jquery popper.js expose-loader
yarn install --check-files
perl -pi.bak -e "s/extract_css: false/extract_css: true/" config/webpacker.yml
s1=$'\n\nimport "bootstrap/dist/js/bootstrap";'
echo "$s1" >> app/javascript/packs/application.js
echo '@import "~bootstrap/scss/bootstrap";' > app/javascript/packs/styles.scss
(gsed $'/module.exports = environment/{e cat expose-loader.txt\n}' config/webpack/environment.js) > config/webpack/environment.js.new
mv config/webpack/environment.js.new config/webpack/environment.js
(gsed $'/javascript_pack_tag .application/{e cat stylesheet_pack_tag.txt\n}' app/views/layouts/application.html.erb) > app/views/layouts/application.html.erb.new
mv app/views/layouts/application.html.erb.new app/views/layouts/application.html.erb


texts: Aggregate query for drawing temporal statistic

texts:
I used to write simple Mongo queries, but this time I had to create an aggregate query. The purpose is to draw temporal statistic on the main page of my web app.

I'm not confident about his performance in production environment, so I'm looking for advice and review about this one.

db.runs.aggregate([
    {$project: {
        "month": {
                $cond: [
                    {$ifNull: ["$startTime", false]},
                    {$month:"$startTime"},
                    -1
                ]
            },
        "year": {
                $cond: [
                    {$ifNull: ["$startTime", false]},
                    {$year:"$startTime"},
                    -1
                ]
            },
        "nbItem": 1,
        "cleanUp.nb": 1,
        "startTime": 1
    }},
    {$match: {
        "startTime" : {$ne:null}
    }},
    {$group: {
        "_id": {
            "month":"$month",
            "year":"$year"
        },
        "nbRun":{$sum:1},
        "sumItem":{$sum:"$nbItem"},
        "sumInserted":{$sum:"$cleanUp.nb"}
    }}
])

As expected the result looks like:

{
    "_id" : {
        "month" : 2,
        "year" : 2017
    },
    "nbRun" : 5,
    "sumItem" : 567372,
    "sumInserted" : 35107
}
{
    "_id" : {
        "month" : 10,
        "year" : 2016
    },
    "nbRun" : 3,
    "sumItem" : 677722,
    "sumInserted" : 16090
}
...


texts: Takes json input and builds dynamic json output based on values in input: Looking for a better way to accomplish this

texts:
I have this specific scenario where I'm going to get a JSON that could have multiple Objects. From the Multiple Objects I will create a new Json that can have nested arrays growing by n amount depending on some json object values.

I hoping there is a better way to do this. Maybe my example below is the best way? I took a look at https://realpython.com/python-data-classes/ but I don't think that will help since it seems complicated to turn the dataclass object into another json.

Update: I think I will ingest the original json object into a dataclass. Then iterate over the objects.

Example Input: Note that 3 and 4 are break start and end times. Which is why you will see the start and end times show up in the break array.

[{
    "name": "Jay",
    "clock_type": 1,
    "start": "4am"
}, {
    "name": "Jay",
    "clock_type": 4,
    "start": "5am"
},
{
    "name": "Jay",
    "clock_type": 3,
    "end": "6am"
},
{
    "name": "Jay",
    "clock_type": 4,
    "start": "7am"
},
{
    "name": "Jay",
    "clock_type": 3,
    "end": "8am"
}]

Example output:

{
    "name": "Jay",
    "start": "4am",
    "break": [{
        "start": "5am",
        "end": "6am"
    }, {
        "start": "7am",
        "end": "8am"
    }]
}

What i'm doing right now is looping through the array, and building the punch dynamically based on the "clock_type".

import json

def write_new_json(data):

    request = {}
    break_count = 0

    for i in data:
        # 1 = New Object. First Clock In
        if i['clock_type'] in [1]:
            request.update({"name": i["name"],
                            "start": i["start"]})
        # 3 = Break End
        if i['clock_type'] in [3]:
            request["break"][break_count].update({"end": i["end"]})
            break_count += 1

        # 4 = Break start. If there is already a breaks object, then we do not create a breaks array,
              # we just append to the existing one.
        if i['clock_type'] in [4]:
            if break_count == 0:
                request.update({"break": []})

            request["break"].append({"start": i["start"]})

       # 2 = Not in the example, but a punch of 2 would reset break_count to 0.

    return request

with open('example.json') as f:
    api_request = write_new_json(json.load(f))

print(json.dumps(api_request))


texts: Web scraping the titles and descriptions of trending YouTube videos

texts:
This scrapes the titles and descriptions of trending YouTube videos and writes them to a CSV file. What improvements can I make?

from bs4 import BeautifulSoup
import requests
import csv

source = requests.get("https://www.youtube.com/feed/trending").text
soup = BeautifulSoup(source, 'lxml')

csv_file = open('YouTube Trending Titles on 12-30-18.csv','w')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Title', 'Description'])

for content in soup.find_all('div', class_= "yt-lockup-content"):
    try:
        title = content.h3.a.text
        print(title)

        description = content.find('div', class_="yt-lockup-description yt-ui-ellipsis yt-ui-ellipsis-2").text
        print(description)

    except Exception as e:
        description = None

    print('\n')
    csv_writer.writerow([title, description])

csv_file.close()


texts: Finding words of a given length only using given letters

texts:
It's a (simple) guesser for game where you need to find words of a given length only using given letters. I'd like to know if there's a more pythonic way to do things here.

#!/usr/bin/env python3
import sys

if len(sys.argv) < 3:
    sys.exit("Usage: " + sys.argv[0] + " letters number_of_letters [dictionnaryfile]")

letters = sys.argv[1].upper()
wordsize = int(sys.argv[2])
dictionnary_name =  "dict.txt" if len(sys.argv) < 4 else sys.argv[3]

try:
    wordlist = open(dictionnary_name).read().split('\n')
except FileNotFoundError:
    sys.exit("Couldn't find dictionnary file \"" + dictionnary_name + "\"")

good = []
for w in wordlist:
    if len(w) == wordsize:
        up = w.upper()
        ok = True
        for c in up:
            if not c in letters:
                ok = False
                break
        if ok:
            good.append(w)

print("Found " + str(len(good)) + " results:")
print(good)


texts:
In this question, I asked for feedback on a class that provided my program with periodical signals.
I have rewritten that class based on the feedback from the accepted answer. As this again uses a complex library I've never worked with before, I'd really appreciate some feedback!

The class runs a function in a separate thread using std::async. Every interval seconds, this function sends a 'tick' to the other parts of my program using my ZeroMQ wrapper classes Client and Message. This is thread-safe, because all other behaviour in my program is also triggered via messages read by the same ZeroMQ socket that is reading these 'ticks'.

Some notes:

In the accepted answer to the previous question, it was suggested to use chrono literals, but as I am restricted to gcc 4.8.5 and thus c++11, I can't do this, so I am using an int respresenting a number of seconds.
I instantiate Client in the asynchronously called function so it cannot be used from another thread, but I should probably move the instantiation to the constructor as it uses a ZeroMQ context that is created in another thread.
The accepted answer to the previous question included some generalizations. I left these out of my implementation, because they were unnecessary in this application and this kept the code simpler.
async_future is not used, but I need to store it, otherwise async won't return.

And finally, the actual code:

Ticker.hpp

#ifndef TICKER_HPP
#define TICKER_HPP

#include <future>
#include "ipc/Client.hpp"
#include "ipc/Message.hpp"

namespace sdp {

    class Ticker {
    private:
        const std::chrono::seconds interval;
        std::promise<void> done_promise;
        std::shared_future<void> done_future;
        std::future<void> async_future;
    public:
        Ticker(unsigned int interval);
        Ticker(const Ticker& orig) = delete;
        virtual ~Ticker();
        void stop();
    private:
        void tickfunction();
    };
}

#endif /* TICKER_HPP */

Ticker.cpp

#include "Ticker.hpp"
#include <chrono>

using namespace std;
using namespace sdp;

Ticker::Ticker(unsigned int interval)
: interval(interval), done_promise(), done_future(done_promise.get_future()) {
    async_future = async(launch::async, &Ticker::tickfunction, this);
}

Ticker::~Ticker() {
    stop();
}

void Ticker::stop() {
    done_promise.set_value();
}

void Ticker::tickfunction() {
    Client socket("inproc://ticker");

    std::future_status status;
    do {
        status = done_future.wait_for(interval);
        if (status == std::future_status::timeout) {
            Message message;
            message.addEmptyPart();
            message.add("tick");
            socket.send(message);
        }
    } while (status != std::future_status::ready);
}


texts: Use of mediator design pattern with mailing list implementation

texts:
I have implemented the following scenario for the Mediator pattern sample:

MailingListMediator: Manages the subscription and send the mail back and forth.

JavaMailingList
SQLMailingList

(Colleagues)MailUsers: They can login, subscribe to the mailing list, send mails to mailing list.

GmailUsers
YahooUsers

My implementation looks like this:

MailingListMediator

public abstract class MailingListMediator {

    protected List<MailUser> mailingList;

    public MailingListMediator() {
        this.mailingList = new ArrayList<MailUser>();
    }

    public void sendMail(String message){
        for(MailUser mUser:mailingList){
            System.out.println("Mail message: '"+message+"' sent to "+ mUser.getMailId());
        }
    }
    public abstract String subscribe(MailUser mailUser);
}

MailUser

public abstract class MailUser {
    public abstract void login(String mailID);
    public abstract void sendMailToMailingList(MailingListMediator mailingList, String message);
    public abstract String getMailId();
}

GmailUser

public class GmailUser extends MailUser {
    String mailID;

    @Override
    public void login(String mailID) {
        this.mailID = mailID;
    }

    @Override
    public void sendMailToMailingList(MailingListMediator mailingList, String message)     {
        mailingList.sendMail(message);
    }

    @Override
    public String getMailId() {
        if(mailID != null){
            return mailID;
        }else{
            return "Login First";
        }
    }
}

YahooUser

public class YahooUser extends MailUser {
    String mailID;

    @Override
    public void login(String mailID) {
        this.mailID = mailID;
    }

    @Override
    public void sendMailToMailingList(MailingListMediator mailingList, String message) {
        mailingList.sendMail(message);
    }

    @Override
    public String getMailId() {
        if(mailID != null){
            return mailID;
        }else{
            return "Login First";
        }
    }
}

JavaMailingList

public class JavaMailingList extends MailingListMediator {
    private final String mailingListId = "java";

    @Override
    public String subscribe(MailUser mailUser) {
        mailingList.add(mailUser);
        return mailingListId;
    }
}

SQLMailingList

public class SQLMailingList extends MailingListMediator {
    private final String mailingListId = "sql";

    @Override
    public String subscribe(MailUser mailUser) {
        mailingList.add(mailUser);
        return mailingListId;
    }
}

ForumUsers

public class ForumUsers{
    public static void main(String[] args) {
        MailingListMediator javaMailingList = new JavaMailingList();
        //User 1
        MailUser gmail = new GmailUser();
        gmail.login("iamgmail@gmail.com");
        javaMailingList.subscribe(gmail); // He subscribes

        //User 2
        MailUser yahoo = new YahooUser();
        yahoo.login("iamyahoo@yahoo.com");
        javaMailingList.subscribe(yahoo); // He subscribes

        //gmail user sends a question to the Java Mailing List
        gmail.sendMailToMailingList(javaMailingList, "How to excel in Java??!!");
    }
}

Does this implementation adhere to the Mediator Design? What improvements can be made?


texts: Implementing a thread safe log class with simple functionality

texts:
I have finally assembled an attempt to create a thread safe logging class and also ensured by file flags that file should not be accessed by different processes at same time. This classed will be inside DLL. Below is the implementation,

   static class GMLogger
    {

       private static List<string> _buffer = new List<string>();
       private static int _maxBufferSize = 25;  // number of messages  permitted in the buffer at a time
       public static string _logDir = "C:\\Logs";
       private static readonly object _syncObject = new object();

       // Log message
        public static  void Log(string logMessage)
        {
            try
            {
                lock (_syncObject)
                {
                    _buffer.Add(logMessage);

                    Save(_buffer);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

       // Save buffer if needed
        private static void Save(List<string> buffer)
        {
            if (buffer.Count > _maxBufferSize)
            {
                // Write to file
                if (!_logDir.EndsWith("\\")) _logDir += "\\";
                DirectoryInfo di = Directory.CreateDirectory(_logDir);
                var todaysLogFilePath = Path.Combine(_logDir,
                                                       ("Log" + DateTime.Now.ToString("yyyy-MMMM-dd") + ".txt"));
                using (FileStream aFile = new FileStream(todaysLogFilePath, FileMode.Append, FileAccess.Write, FileShare.None))
                using (StreamWriter sw = new StreamWriter(aFile))
                {
                    for (int i = 0; i < buffer.Count(); i++)
                    {
                        sw.WriteLine(buffer[i]);
                    }
                }

                // Clear buffer
                buffer.Clear();
            }

    }
}

Please note I am a beginner first of all, and if this class achieves the simple functionality of writing simple lines to file I am OK with it.

Of course you can comment also about other things which are in the context of CodeReview site. But please not too advanced feedback since as I said I am beginner.

Second, here are some specific questions I have about it:

Have I used the lock correctly?
This class maybe used by many threads, will I have performance problems because of thread waiting for each other? NOTE: I log only ERRORS so even if many threads are using it, not many errors should be occurring right? Also note how because of performance I have a cache for log messages.
Finally, only problem I see if different programs use this class to write to same file, how can I distinguish inside logs which program or process made an entry? How is this solved typically? (I assume one process can write to this file if another finished writing, isn't it?)

PS. This is all the functionality I want, I don't plan to extend this class. So please no recommendations about 3rd party libs. If my class achieves above points well, I am ok with it. Or if you see some problem with it, please tell.

And in general I am interested if its safe to use my class because some people always say to not create your own logging class. Is it ok if I use this class? I see people creating log classes such as here http://www.codeproject.com/Tips/585796/Simple-Log, so what is problem if I created one as above?


texts:
Could I get some feedback on my simple start to an admin template:
http://jsfiddle.net/spadez/GHKxW/3/

HTML

Dashboard

Title

Content

CSS

* {
    margin: 0;
    padding: 0;
    border: 0;
}

li {
    list-style: none;
}
a {
    text-decoration: none
}

html, body {height: 100%; max-height: 100%; padding:0; margin:0;}
.wrapper {display:table; width:100%; height:100%;}
.wrapper > div {display:table-cell; vertical-align: top;}
.wrapper .left {width:200px; background-color:#34495E}

#btn_pri {
    background-color: 60A0DF;
    color: white;
}
#btn_sec { background-color: #e74c3c;
color:white;
}

.navigation {
}
.navigation li {
}
.navigation li span {
    display: inline-block;
    background: url(http://www.otlayi.com/web_images/content/free-doc-type-sprite-icons.jpg) no-repeat left center;
    width: 16px;
    height: 16px;
    overflow: hidden;
    margin-left: 15px;
    margin-right: 15px;
}
.navigation li a {
    display: block;
    color: white;
    padding-top: 15px;
    padding-bottom: 15px;
    font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-size: 14px;
}
.navigation li a:hover {
    background-color: #495C6D;
}
.navigation li a.active {
    background-color: #495C6D
}
#rss span {
    background-position: -52px -68px;
}
#photos span {
    background-position: -90px -66px;
}
#links span {
    background-position: -45px 0;
}

h1 {font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-size: 30px; font-weight: 500;}

.logo {height: 50px; margin-bottom: 30px;}

.btn {
    letter-spacing: 1px;
    font-weight:bold;
    padding-left: 10px;
    padding-right: 10px;
    height: 34px;
    border-radius:3px;
    border: 0px;
    text-transform:uppercase;
    font-size:12px;
}

#btn_pri {
    background-color: #60A0DF;
    color: white;
}
#btn_sec { background-color: #e74c3c;
color:white;
}


texts:
Please take a moment and review my code and tell me how I did. This is the first time in my class (CSC 111) I've been given an assignment in which I had to use a lot of my own resources and develop most of it on my own.

  Write an application that prompts for and reads a double value
  representing a monetary amount. Then determine the least
  number of each bill and coin needed to represent that amount,
  starting with the highest. Assume that ten dollars is the
  maximum size needed.
  For example, if the value 47.63 is entered the program should
  display

  4 ten dollar bills
  1 five dollar bills
  2 one dollar bills
  2 quarters
  1 dimes
  0 nickels
  3 pennies

My code works mostly flawlessly (I believe). I would like to hear other people's opinion on my solution. I understand it probably isn't the most efficient out there. How can it be improved? Are there things to watch out for?

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Scanner;
import java.util.Locale;

public class Assignment01
{
    public static void main(String[] args)
    {

    /* Define Constants */

    BigDecimal tenDollar = BigDecimal.valueOf(10);
    BigDecimal fiveDollar = BigDecimal.valueOf(5);
    BigDecimal oneDollar = BigDecimal.valueOf(1);
    BigDecimal quarter = BigDecimal.valueOf(0.25);
    BigDecimal dime = BigDecimal.valueOf(0.10);
    BigDecimal nickel = BigDecimal.valueOf(0.05);
    BigDecimal penny = BigDecimal.valueOf(0.01);

             /* Get Input From User */

    System.out.print("Please enter the amount to be converted: ");
   Scanner scan = new Scanner(System.in);
    BigDecimal money = scan.nextBigDecimal();

    NumberFormat usdFormat = NumberFormat.getCurrencyInstance(Locale.US);
    usdFormat.setMinimumFractionDigits(2);
    usdFormat.setMaximumFractionDigits(2);

    System.out.println("Amount you entered: " + usdFormat.format(money));

            /* Begin Processing and Displaying Information */

    BigDecimal tenDollarNext = money.divideToIntegralValue(tenDollar);
    System.out.println(tenDollarNext.intValue() + " Ten Dollar Bills");

    BigDecimal fiveDollarNext = money.subtract(tenDollar.multiply(tenDollarNext));
    BigDecimal i = fiveDollarNext.divide(fiveDollar);
    System.out.println(i.intValue() + " Five Dollar Bills");

    BigDecimal oneDollarNext = fiveDollarNext.subtract(fiveDollar.multiply(BigDecimal.valueOf(i.intValue())));
    BigDecimal f = oneDollarNext.divide(oneDollar);
    System.out.println(f.intValue() + " One Dollar Bills");

    BigDecimal quarterNext = oneDollarNext.subtract(oneDollar.multiply(BigDecimal.valueOf(f.intValue())));
    BigDecimal q = quarterNext.divide(quarter);
    System.out.println(q.intValue() + " Quarters");

    BigDecimal dimeNext = quarterNext.subtract(quarter.multiply(BigDecimal.valueOf(q.intValue())));
    BigDecimal d = dimeNext.divide(dime);
    System.out.println(d.intValue() + " Dimes");

    BigDecimal nickelNext = dimeNext.subtract(dime.multiply(BigDecimal.valueOf(d.intValue())));
    BigDecimal n = nickelNext.divide(nickel);
    System.out.println(n.intValue() + " Nickels");

    BigDecimal pennyNext = nickelNext.subtract(nickel.multiply(BigDecimal.valueOf(n.intValue())));
    BigDecimal p = pennyNext.divide(penny);
    System.out.println(p.intValue() + " Pennies");

    }
}


texts:
I had to build a cash register that included a Coin class that allowed for all types of coins to be used. Please note that for this, no control structures can be used and no data structures such as arrays, lists, and what not. Any constructive criticism is welcome.

public class CashRegisterTest
{
    //Test the methods in CashRegister class
    //@param args not used
    public static void main(String[] args)
    {
        //European Coins
        final double EURO = 1;
        final double FIFTY_CENT = .5;
        final double TWENTY_CENT = .2;
        final double TEN_CENT = .1;
        final double FIVE_CENT = .05;
        final double ONE_CENT = .01;

        //American Coins
        final double DOLLAR = 1;
        final double QUARTER = 0.25;
        final double DIME = 0.10;
        final double NICKEL = 0.05;
        final double PENNY = 0.01;

        CashRegister register = new CashRegister();
        register.recordPurchase(10.99);
        register.recordPurchase(10.01);
        register.enterPayment(20, new Coin(EURO));
        register.enterPayment(2, new Coin(FIFTY_CENT));

        System.out.println(register.returnChange());

        CashRegister registerTwo = new CashRegister();
        registerTwo.recordPurchase(10.99);
        registerTwo.recordPurchase(10.01);
        registerTwo.enterPayment(20, new Coin(DOLLAR));
        registerTwo.enterPayment(4, new Coin(QUARTER));

        System.out.println(register.returnChange());
    }
}

public class CashRegister
{
    private double purchase;
    private double payment;

    private int items;

    //Construct a cash register with no money.
    public CashRegister()
    {
        payment = 0;
        purchase = 0;
        items = 0;
    }

    //Records the purchase price of an item
    //@param amount the price of the purchased item
    public void recordPurchase(double amount)
    {
        purchase += amount;
        items++;
    }

    //Enter payment recieved.
    //@param amount the amount of coins given
    //@param value the coin that has been given.
    public void enterPayment(int amount, Coin value)
    {
        payment += amount * value.getValue();
    }

    //Compute the change due and set the machine for the next customer.
    //@return change the amount due to the customer.
    public double returnChange()
    {
        return payment - purchase;
    }

    //Get the item count
    //@return items the amount of items in this transaction
    public int getItemCount()
    {
        return items;
    }
}

public class Coin
{
    private double value;

    public Coin(double value)
    {
        this.value = value;
    }

    public double getValue()
    {
        return value;
    }
}


texts: A matrix-vector multiply parallelized using boost::MPI

texts:
This program performs a matrix-vector multiply using MPI to split the computation up. It is not extremely robust (for example, it doesn't handle the case where the number of MPI processes does not divide evenly into the dimensions of the matrix), but I mainly wanted to get some practice using MPI. Is my use of the functions correct, and what are some ways I can improve this code?

#include <iostream>
#include <string>
#include <boost/mpi.hpp>
#include <numeric>

void matVecMult( double ** mat, double * vec, double * result, int beg, int end, unsigned N) {
    for (auto i = beg; i < end; i++) {
        result[i] = std::inner_product(mat[i], mat[i] + N, vec, 0.0);
    }
}

int main(int argc, char ** argv) {
    boost::mpi::environment env;
    boost::mpi::communicator world;

    int dim = (argc > 1) ? std::stoi(argv[1]) : 4;
    auto N = static_cast<unsigned>(dim);

    auto **matrix = new double *[N]();
    auto  *vector = new double[N]();
    auto  *result = new double[N]();

    for(unsigned i = 0; i < N; i++){
        matrix[i] = new double[N]();
        for(unsigned j = 0; j < N; j++){
            if(i==j) {matrix[i][j] = i+j;}
        }
        vector[i] = i + i;
    }

    int beg = world.rank() * (N/world.size());
    int end = beg + (N/world.size());

    matVecMult(matrix, vector, result, beg, end, N);

    world.isend(0, world.rank(), result + beg, (N/world.size()));
    if(world.rank() == 0){
        for(int i = 0; i < world.size(); i++) {
            world.recv(i,i, result+(i*N/world.size()), (N/world.size()));
        }
    }

    for(unsigned i = 0; i < N; i++){
        delete[] matrix[i];
    }

    delete[] matrix;
    delete[] vector;
    delete[] result;

    return 0;
}


texts:
I am new to Perl and I wrote this Perl script to calculate bytes of code and lines of code in a directory. I want to know if there are any improvements that can be made to it.

#!/usr/bin/perl
# codestats.pl
# A perl script to calculate the number of lines of code in a project
# and what type of lines those code are, such as comments, code, or
# newlines. This script is specific to C/C++, but it should work with any
# language that has the same commenting scheme, so it should probably work
# with java too.
#
# Henry J Schmale
# April 30, 2015

use strict;
use warnings;

my @srcext = ("*.cpp", "*.c", "*.h", "*.hpp", "*.ino", "*.cxx", "*.cc");

my $commLines = 0; # Lines that start with a comment symbol
my $bothLines = 0; # Lines that have a comment and code
my $newLines  = 0; # Lines that are just whitespace
my $codeLines = 0; # Lines of code - lines that don't fit in another space
my $totLines  = 0; # Total lines of code
my $srcBytes  = 0; # Total Number of bytes in src code
my $fCount    = 0; # Number of files read

my $files;
for($a = 0; $a < scalar(@srcext); $a++){
    $files .= `find . -name "$srcext[$a]"`;
}
my @inputs = split("\n", $files);
for($a = 0; $a < scalar(@inputs); $a++){
    my $prev = $totLines;
    countLines($inputs[$a]);
    printf("Read %d ln. In %s\n", $totLines - $prev, $inputs[$a]);
    $fCount++;
}
printResults();

# Count the lines in the given file
# The first param is the file to open for counting
sub countLines{
    my ($srcfile) = @_;
    open(FILE, "<$srcfile") or die "Couldn't open file: $!\n";
    my @lines = <FILE>;
    for($b = 0; $b < scalar(@lines); $b++){
        $srcBytes += length($lines[$b]);
        $totLines++;
        if($lines[$b] =~ /^\s$/){ # is only whitespace ==> newLine
            $newLines++;
            next;
        }
        if(($lines[$b] =~ /^\s*\/\//) || # comments only lines
           ($lines[$b] =~ /^\s*\/\*/) ||
           ($lines[$b] =~ /^\s*\*/)){
            $commLines++;
            next;
        }
        # code + comments
        if(($lines[$b] =~ /\/\//) ||
           ($lines[$b] =~ /\/\*.*\*\//)){
            $bothLines++;
            next;
        }
        $codeLines++;
    }
    close FILE;
}

sub calcPercent{
    return ($_[0] / $_[1]) * 100.0;
}

sub printResults{
    # print out the results
    printf("Read %d Files\n", $fCount);
    printf("Average Lines Per File: %d\n", $totLines / $fCount);
    printf("Code    : %09d ln. %06.3f", $codeLines, calcPercent($codeLines, $totLines));
    print "%\n";
    printf("Comment : %09d ln. %06.3f", $commLines, calcPercent($commLines, $totLines));
    print "%\n";
    printf("Blank   : %09d ln. %06.3f", $newLines,  calcPercent($newLines,  $totLines));
    print "%\n";
    printf("Both    : %09d ln. %06.3f", $bothLines, calcPercent($bothLines, $totLines));
    print "%\n";
    printf("Total   : %09d ln.\n", $totLines);
    printf("CodeSize: %09d bytes\n", $srcBytes);
}


texts:
So we have a RESTful webservice that implements CRUD operations for a model, like this one:

class MyModel {
    private long id;
    private String name;
    // other fields
    private boolean completed;
    private boolean active;
    // getter and setters
}

In this webservice there is also a path like /service/{id}/complete that updates just the field completed to true. This indicates a final step for the creation.

The save and the complete operation are pretty simple and similar (they both end up calling a saveOrUpdate ). Where they differ is the validation. The complete validation is stricter.

The one before me declared an interface:

interface Validator<T> {
    void validate(T t);
}

And then to check that all mandatory fields where there before setting the complete attribute to true we have something like (writing in pseudocode):

MandatoryFieldsValidator implements Validator<MyModel> {

    list = {'id', 'active'}

    public void validate(MyModel model) {
        foreach(element in list) {
            if(myModel.get(element) is null) throw ValidationException(element + " is mandatory");
        }
    }
}

So then I needed another type of validator and started doing something like this because I needed specific controls over the name field:

NameValidator implements Validator<MyModel> {
    public void validate(MyModel model) {
        if(model.name is null or empty)
        throw ValidationException(element + " is mandatory");
        if(model.name.startswith("something"))
            throw ValidationException("something not valid prefix");
        if(model.name.length > 10)
        throw ValidationException("too long");
    }
}

The controller had an attribute of type Validator that instantiated a MandatoryFieldsValidator so I added another attribute of the same type instantiating a NameValidator.

Now what I don't like about this:

The fact that I need to add a new attribute to the class as soon as I have a new validator to use;
The fact that I'm repeating checks in different validators because even if name is not included in the MandatoryFieldValidator I'm applying the same logic inside NameValidator (is null or empty);
I will also add a new type of model and a MandatoryFieldValidator<NewModel> with the same type of control logic is a non-sense.

Can you give me some advice? I'm looking into a general pattern to organize this kind of validation but I'm using Java so if you have some Java specific solution is ok.


texts: Consuming APi using Rx in an MVP project

texts:
I would like to have some input here if possible, this code should make a request to an API and the call should return the desired object. The client to make the requests was made with Retrofit and Okkhttp3.

I did the following structure so I can mock and unit test more friendly.

I'm implementing it using Single, and when it is subscribed, I create a new instance of a custom SingleObserver to deal with the emitted result and trigger the view update.

Feel free to give feedback or suggestions of how to improve or why I should not apply this structure to trigger the view in an MVP application.

Any feedback or suggestions to improve it I guess...

Interface

public interface MovieService {
@GET("/services/movie")
Single<Movie> getMovie(@Query("name") String name);

Interactor

public class MovieInteractor implements MovieService {

    private final MovieService client;

    public MovieInteractor(MovieService client) {
        this.client= client;
    }

    @Override
    public Single<Movie> getMovie(String name) {
        return client.getMovie(movie);
    }
}

MoviePresenter

    @ConfigPersistent
        public class MoviePresenter extends BasePresenter<MovieView> implements Serializable {
            @Inject
            public MoviePresenter() {

            }

            @Override
            public void attachView(MovieView mvpView) {
                super.attachView(mvpView);
            }

            @Override
            public void detachView() {
                super.detachView();
            }

            public void requestMovieData(String name, MovieService client) {
                MovieIntercator interactor = new MovieInteractor(client);
                interactor.getMovie(name)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new MovieSingleObserver(getMvpView()));
            }
}

MovieSingleObserver

  public class MovieSingleObserver extends BaseSingleObserver<Movie>{
       private MovieView mView;

        public MovieSingleObserver(MovieView mView) {
            super(mView);
            this.mView = mView;
      }

        @Override
        public void onSuccess(Movie item) {
           super.onSuccess(item);
           mvView.onFetchData(item);
       }

       @Override
        public void onError(Throwable e) {
        super.onError(e);
        mvView.onFetchDataError(e);
      }
    }

MovieInteractorTest

    @RunWith(MockitoJUnitRunner.class)
public class MovieInteractorTest {
    @Mock
    MovieView view;

    @Mock
    MovieInteractor interactor;

    MockedServer mockedServer;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockedServer = new MockedServer();
    }

    @Test
    public void requestMovie_shouldReturn_OnSuccess() {
        MockResponse response = new MockResponse().setBody(new Gson().toJson(new Movie()));
        response.setResponseCode(200);

        mockedServer.setResponse(response);

        interactor = new MovieInteractor(mockedServer.getService("/services/movie/", MovieInterface.class));
        interactor.getMovie("").subscribe(new MovieSingleObserver(view));

        verify(view, atLeastOnce()).onFetchData(refEq(new Movie()));
    }