texts: Counting occurrences of a word in a file

texts:
This gives me the output of how many times the word is in the file. (I will eventually want to enhance the program to output on what line of the file the word is.)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;

public class CountLineWordsDuplicateWords {
     public FileReader fr = null;
     public BufferedReader br =null;

     public String [] stringArray;
     public int counLine = 0;
     public int arrayLength ;
      public String s="";
    public String stringLine="";
     public String filename ="";
     public String wordname ="";

public CountLineWordsDuplicateWords(){

    try{
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the filename: ");
        filename = scan.nextLine();
        Scanner scan2 = new Scanner(System.in);
        System.out.println("Please enter a word: ");
        wordname = scan.nextLine();
        fr = new FileReader(filename);
        br = new BufferedReader(fr);
        while((s = br.readLine()) != null){
            stringLine = stringLine + s;
            //System.out.println(s);
            stringLine = stringLine + " ";
            counLine ++;
        }

        //System.out.println("Contents of file: " + stringLine);

        stringArray = stringLine.split(" ");
        arrayLength = stringArray.length;
                     //System.out.println("The total number of words in the text file is "+arrayLength);
        /*Duplicate String count code */
        for (int i = 0; i < arrayLength; i++) {
            int c = 1 ;
            for (int j = i+1; j < arrayLength; j++) {
                if(stringArray[i].equalsIgnoreCase(stringArray[j])){
                    c++;
                    for (int j2 = j; j2 < arrayLength; j2++) {
                        stringArray[j2] = stringArray[j2+1];
                        arrayLength = arrayLength - 1;
                    }
                    //System.out.println(wordname);
                       if (stringArray[i].equalsIgnoreCase(wordname)){
           System.out.println("The word "+wordname+" is present "+c+" times in the specified file.");
           }

            }//End of Inner for block
       //System.out.println("The word "+stringArray[i]+" is present "+c+" times in the specified file.");

        }
    }//End of Outer for block
        System.out.println("Total number of lines: "+counLine);
        //System.out.println();

        fr.close();
        br.close();
    }catch (Exception e) {
        e.printStackTrace();
    }
}
}


texts:
Expected behavior of the code below:

There will be one static SessionManager accessed by many threads.
Multiple calls to SessionManager.UseTheSession for a given session ID must be processed on a first come first serve basis (similarly, calling EndSession should allow any currently executing UseTheSession's to finish).
The goal of the individual session locks is that a call to SessionManager.UseTheSession by one thread doesn't hold up another thread that is calling the same method with a different session ID.

Things I'm looking for input on are:

Will this perform as expected.
Does sessions need to be a ConcurrentDictionary or does a regular Dictionary work fine here since I'm locking any access of the one key.
What's a good way to handle the memory leak that happens when I keep creating new locks but don't remove them for a given id after I stop using that it?

The code (runnable in Linqpad with the inclusion of the System.Collections.Concurrent namespace):

void Main()
{
    var sm = new SessionManager();

    Guid id = sm.StartSession();

    sm.UseTheSession(id).Dump();
    sm.UseTheSession(id).Dump();

    sm.EndSession(id);
}

public class SessionManager
{
    private ConcurrentDictionary<Guid, object> sessionLocks =
        new ConcurrentDictionary<Guid, object>();

    private ConcurrentDictionary<Guid, ASession> sessions =
        new ConcurrentDictionary<Guid, ASession>();

    public Guid StartSession()
    {
        Guid id = Guid.NewGuid();

        // Takes a sec to create the session.
        var session = new ASession(string.Format("Session {0}", id));
        Thread.Sleep(1000);

        if(!sessions.TryAdd(id, session))
            throw new Exception("Astronomically unlikely situation encountered.");

        return id;
    }

    public int UseTheSession(Guid id)
    {
        lock(this.GetSessionLocker(id))
        {
            ASession session;
            if(sessions.TryGetValue(id, out session))
            {
                return this.DoSomethingWithSession(session);
            }
            else
            {
                throw new Exception(string.format("Session with id {0} does not exist.",
                    id));
            }
        }
    }

    public void EndSession(Guid id)
    {
        lock(this.GetSessionLocker(id))
        {
            ASession removedSession;
            if(sessions.TryRemove(id, out removedSession))
            {
                this.CleanUpSessionRemnants(removedSession);
            }
        }
    }

    private object GetSessionLocker(Guid id)
    {
        return sessionLocks.GetOrAdd(id, x => new object());
    }

    private int DoSomethingWithSession(ASession session)
    {
        Thread.Sleep(1000);

        return 1;
    }

    private void CleanUpSessionRemnants(ASession session)
    {
        Thread.Sleep(1000);
    }
}

public class ASession
{
    public ASession(string name)
    {
        this.Name = name;
    }

    public string Name { get; private set; }
}


texts: Custom ostream for a println-like function

texts:
I am writing a plugin in C++ that uses C API that gives me a single logging function with this signature:

typedef void(*println_t)(const char* text);

I want to wrap this type of a function in a nice ostream to use all C++ formatting features. Having read it is best to use streambuf for this, I made this code:

//println_buf.h

#include <string>
#include <sstream>

class println_buf : public std::streambuf
{
    typedef void(*println_t)(const char* text);
    println_t logfunc_;

    std::string buffer;
public:
    println_buf(println_t logfunc) : logfunc_(logfunc)
    {

    }

    println_buf(const println_buf &) = delete;
    println_buf(println_buf &&);
    println_buf& operator=(const println_buf &) = delete;
    println_buf& operator=(println_buf &&);

    virtual std::streamsize xsputn(const char* s, std::streamsize n) override;
    virtual int overflow(int c) override;
    virtual int sync() override;
};

//println_buf.cpp

#include "println_buf.h"

using namespace std;

println_buf::println_buf(println_buf &&o) : logfunc_(o.logfunc_), buffer(std::move(o.buffer))
{

}

println_buf& println_buf::operator=(println_buf &&o)
{
    logfunc_ = o.logfunc_;
    buffer = std::move(o.buffer);
    return *this;
}

streamsize println_buf::xsputn(const char* s, streamsize n)
{
    streamsize start = 0;
    for (std::streamsize i = 0; i < n; i++)
    {
        if (s[i] == '\n')
        {
            buffer.append(s + start, s + i);
            sync();
            start = i + 1;
        }
    }
    buffer.append(s + start, s + n);
    return n;
}

int println_buf::overflow(int c)
{
    char ch = traits_type::to_char_type(c);
    if (ch == '\n')
    {
        sync();
    } else {
        buffer.append(1, c);
    }
    return c;
}

int println_buf::sync()
{
    logfunc_(buffer.c_str());
    buffer.clear();
    return 0;
}

Usage:

println_t logfunc = ...;
println_buf buffer(logfunc);
std::ostream stream(&buffer);
stream << "Hello world" << std::endl;

It should be noted that println_t includes a newline automatically in the actual output, but I want to have to specify the line separator in C++.

My concern is that the function should not be called with a string containing \n, but the string must be passed to the function only if it originally ended with \n, and be buffered otherwise. Also endl should cause the function to be called immediately.


texts:
I have written a simple image cache script, the purpose is to load the image locally, so i can control the cache times of the images, and i have better load times than the host server, (battle.net serves 350 ms, i serve 65ish ms) this times 20 images is a pretty good performance step.

But being the performance freak i am. I was wondering if i can make it run faster!

Please also include the following in the review:

Better suggestions for function/variable names.
Better writing of code.
Alternate formatting.
Something that could be changed for something better / more correct.
Suggestions about how to make this generic / reusable.
An explanation about why you are right.
An explanation why you down vote this post.

So we all can learn from this.

Comments are only for Code Review and not actually in the file.

<?php
// Checks if the img parameter is set.
if(!isset($_GET['img'])){
    die;
}
// Saves it as a variable
$url = $_GET['img'];
// Compiles the local file string
$img = dirname(__FILE__) . '/media/cache/' . get_image_from_url($url);

// Check if the file exists, if not it dowloads a version of the image.
if(!file_exists($img)){
    // log_message('info', 'file does not exists');
   download_image($img, $url);
}

// Checks if the image existing is more than 24 hours old if it is gets a new image.
if(time()-filemtime($img) > 24 * 3600){
  //  log_message('info', 'file is too old');
    download_image($img, $url);
}

header('Content-Type: image/jpeg');
$handle = imagecreatefromjpeg($img);
imagejpeg($handle);

/*
 * FUNCTIONS
 */

function get_image_from_url($url){
    $url = str_replace('http://eu.battle.net/static-render/','', $url);
    $url = str_replace('/','-',$url);
    return $url;
}

function download_image($img, $url){
    $headers = get_headers($url);
    $response_code = substr($headers[0], 9, 3);

    if($response_code == '404'){

        // Pleas also advice here to make the file more generic.
        $url = 'http://localhost/warlords' . '/media/images/anonymous.jpg';
    }

    $thisurl = file_get_contents($url);
    file_put_contents($img, $thisurl);
}


texts:
I'm coding a Reversi game, with an artificial intelligence using the MinMax as the search algorithm. My concern is that (most) search algorithms needs to store a lot of instances of "states", in my case, board states. What I want is to represent a BoardState with 64 SlotState (Empty, White Disk or Black Disk), with the minimum RAM usage as possible. My current implementation uses a System.Collections.BitArray for storage.

public enum SlotState : byte {
    Empty = 0,
    White = 1,
    Black = 2
}
public sealed class BoardState {

    private const int BitsPerSlot = 2;
    private const int SlotsPerRow = 8;
    private const int SlotsInBoard = 64;
    private const int BitsPerRow = SlotsPerRow * BitsPerSlot;
    private const int BitsInBoard = SlotsInBoard * BitsPerSlot;

    // stores state in big-endian row-major
    private BitArray State;

    public BoardState() {
        State = new BitArray(BitsInBoard);
        this[3, 3] = SlotState.White;
        this[4, 4] = SlotState.White;
        this[3, 4] = SlotState.Black;
        this[4, 3] = SlotState.Black;
    }

    public BoardState(BoardState original) {
        State = new BitArray(original.State);
    }

    public SlotState this[int x, int y] {
        get {
            if (!(IsValidCoordinate(x) && IsValidCoordinate(y))) {
                throw new IndexOutOfRangeException();
            }
            int position = GetPosition(x, y);
            bool majorBit = State[position];
            bool minorBit = State[position + 1];
            if (majorBit && !minorBit) {
                return SlotState.Black;
            } else if (!majorBit && minorBit) {
                return SlotState.White;
            } else {
                return SlotState.Empty;
            }
        }
        set {
            if (!(IsValidCoordinate(x) && IsValidCoordinate(y))) {
                throw new IndexOutOfRangeException();
            }
            int position = GetPosition(x, y);
            State[position] = false;
            State[position + 1] = false;
            if (value == SlotState.White) {
                State[position + 1] = true;
            } else if (value == SlotState.Black) {
                State[position] = true;
            }
        }
    }

    private int GetPosition(int x, int y) {
        return BitsPerSlot * x + BitsPerRow * y;
    }

    private bool IsValidCoordinate(int coordinate) {
        return coordinate >= 0 && coordinate <= 7;
    }

}

More specific questions could be: Is there any way to reduce memory usage even further (does BitArray have a memory overhead)? Is it excessive const declarations? Should I break the get/set into smaller pieces of code? Are the naming and general coding style all right?

I also tried this implementation of the get method. I didn't like it, but couldn't find a reason to use either over the other. Is it any better/worse than the other implementation, in terms of ease of understanding?

get {
    if (!(IsValidCoordinate(x) && IsValidCoordinate(y))) {
        throw new IndexOutOfRangeException();
    }
    int position = GetPosition(x, y);
    bool majorBit = State[position];
    bool minorBit = State[position + 1];
    byte value = 0;
    if (majorBit) value += 2;
    if (minorBit) value += 1;
    return (SlotState)value;
}

If you're going to suggest a library or anything like that, keep in mind this is a XNA project (thus the memory concern).


texts: Distinguishing between people who have likes to posts and those who have dislikes

texts:
I want to distinguish between people who have likes to posts and those who have dislikes. I want to find a way to improve my code without thinking it is efficient.

<% if current_user.voted_up_on? @post %>
  <%= link_to "LIKE #{@post.get_upvotes.size}", like_post_path(@post), method: :post, class: "btn btn-outline-primary" %>
  <%= link_to "DISLIKE #{@post.get_downvotes.size}", dislike_post_path(@post), method: :post, class: "btn btn-outline-dark" %>
<% elsif current_user.voted_down_on? @post %>
  <%= link_to "LIKE #{@post.get_upvotes.size}", like_post_path(@post), method: :post, class: "btn btn-outline-dark" %>
  <%= link_to "DISLIKE #{@post.get_downvotes.size}", dislike_post_path(@post), method: :post, class: "btn btn-outline-danger" %>
<% else %>
  <%= link_to "LIKE #{@post.get_upvotes.size}", like_post_path(@post), method: :post, class: "btn btn-outline-dark" %>
  <%= link_to "DISLIKE #{@post.get_downvotes.size}", dislike_post_path(@post), method: :post, class: "btn btn-outline-dark" %>
<% end %>


texts:
I have been given three values: @lLength, @lWidth, @lHeight. I need to take these DECIMAL(4,2) values and set the values of @lMax, @lMid, @lMin with the values I've been given in order of value. So whichever value of Length, Width or Height is the greatest will be stored in Max, and the second created in Mid, and the lowest value in Min.

Note: I am limited to Microsoft SQL Server 2008.

-- Declarations are for testing purposes only
DECLARE @lLength DECIMAL(4,2) = CAST('1.0' AS DECIMAL(4,2))
DECLARE @lWidth  DECIMAL(4,2) = CAST('2.0' AS DECIMAL(4,2))
DECLARE @lHeight DECIMAL(4,2) = CAST('3.0' AS DECIMAL(4,2))
DECLARE @lMax    DECIMAL(4,2)
DECLARE @lMid    DECIMAL(4,2)
DECLARE @lMin    DECIMAL(4,2)

--Determine which is higher and store it.
IF @lLength > @lWidth BEGIN
    SET @lMax = @lLength
    SET @lMid = @lWidth
END ELSE BEGIN
    SET @lMax = @lWidth
    SET @lMid = @lLength
END

--Now determine where the 3rd value needs to be inserted
IF @lHeight < @lMid BEGIN
    SET @lMin = @lHeight
END ELSE IF @lHeight < @lMax BEGIN
    SET @lMin = @lMid
    SET @lMid = @lHeight
END ELSE BEGIN
    SET @lMin = @lMid
    SET @lMid = @lMax
    SET @lMax = @lHeight
END

--This select is for testing purposes only
SELECT @lMax as MAX, @lMid AS MID, @lMin AS MIN

The code above works, and I added declarations and a select to make that readily apparent. I am looking for a general review of this operation, perhaps a better way to do this. You can criticize the naming convention, but that is something I have no control over. Also, I do not have to worry about scalability of this operation unless our world gets a 4th physical dimension in the near future.


texts:
Several of my Python 2.7 programs need to access server tasks via our server Apache instance.
The 'client' programs will run on Windows in various environments. They may be run on systems that do not use a proxy, or on systems that use a proxy with no authentication, or enterprise systems that use an authenticated proxy server.

The function below is meant to address all three proxy situations.

My main question is whether I have coverage for requirement for all scenarios - i.e. for all possible proxy configurations.  I am not familiar with, for example, the kind of proxy authentication that might be used on Windows Active Directory systems - is it different than what my code can handle?

I'm also interested in suggestions for general improvement of the code.  The exception handlers are incomplete - I'll work on them once I'm sure the code is ok.

def openUrl(url, data=None):
    """ General purpose URL opener
    Handles no proxy - un-authenticated proxy and authenticated proxy

    urlencoding of the data argument to be performed prior to invoking this function

    :param url: The url to access
    :param data: Post data to accompany the url request
    :return: an open urllib object
    """
    # case 1: Proxy not required as no PROXY_URL found in environment.  Fall through to urlopen
    if os.getenv('PROXY_URL') is None:
        pass

    # case 2: un-authenticated proxy, just load the proxy handler and then fall through to urlopen
    elif os.getenv('PROXY_USER') is None:
        proxy_support = urllib2.ProxyHandler({})
        opener = urllib2.build_opener(proxy_support)
        urllib2.install_opener(opener)

    # case 3:  Authenticated proxy.  Load password manager and proxyHandler, the fall through to urlopen
    else:
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        password_mgr.add_password(None, os.getenv('PROXY_URL'), os.getenv('PROXY_USER'), os.getenv('PROXY_PASSWORD'))
        auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr)
        opener = urllib2.build_opener(auth_handler)
        urllib2.install_opener(opener)

    # Access url using proxy defined above (or no proxy at all)
    try:
        connection = urllib2.urlopen(url, data)
    except urllib2.URLError, err:
        print(repr(err))
        exit()
    except urllib2.HTTPError, err:
        print(repr(err))
        exit()

    return connection


texts: Is there any way to improve (shorten) this F# code?

texts:
I have a very good grasp of the syntax and features of F# as well as some of the concepts that mesh well with the language. However, I do not have enough experience writing it to feel comfortable that the way I am handling the language is appropriate.

Ignoring the fact that I do not provide proper escaping functionality for the file format, is there any way I could write this code better? I know that this is a trivial example, but I fear that I might be making things too hard on myself with this code.

Also, is there a way that I could write this more robustly so that adding in an escape sequence for the ";" character would be easier?

module Comments

open System.IO

type Comment = { Author: string; Body: string }

let parseComment (line:string) =
    match line.Split(';') with
    | [|author; body|] -> Some({Author=author; Body=body})
    | _                -> None

let filterOutNone maybe = match maybe with | Some(_) -> true | _ -> false
let makeSome some = match some with | Some(v) -> v | _ -> failwith "error"

let readAllComments () =
    File.ReadAllLines("comments.txt")
    |> Array.map parseComment
    |> Array.filter filterOutNone
    |> Array.map makeSome


texts:
I found out the hardway that access to DbContext in .NET is not threadsafe. I have a singleton for logging things using a dbcontext. The original version uses something like

public Logger{
  private MyContext context;
  private static Logger instance = new Logger();

  private Logger(){
    //init stuff, including context
  }

  public static Logger Instance {
      return this.instance;
  }

  public void someMethod(){
    //do something with this.context
  }
}

I'm thinking of a few solutions:

one would be is not making this a singleton at all, but instantiate a logger each time I need one.

I can think of added overhead as a disadvantage for this way, and simplicity as an advantage.

another one is locking (on the context or type) for each public method:

public void someMethod(){
  lock(this.context){
    //do something with this.context
  }
}

This adds extra maintenance complexity.

a third one could be one context per thread in a form of

private ConditionalWeakTable<Thread, MyContext> contexts = new ConditionalWeakTable<Thread, MyContext>();

private MyContext Context{
  get {
    return contexts.GetValue(Thread.CurrentThread, createContext());
  }
}

private MyContext createContext(){
  //instantiate a context
}

Pro: fairly consice, complexity is isolated
Con: batshit insane? Using System.Runtime.CompilerServices for something fairly mondaine, which also isn't what it's meant for.

Am I overlooking any arguments? What would you do?


texts: My first Qt application - a multiple-state window with a menu

texts:
This is my first Qt app and also some of my first non-trivial C++ code. The application displays a menu offering two options. Clicking either option takes you to a sub-page with some text and a back button, taking you back to the menu.

Feedback I'm especially interested in:

Am I doing anything weird, culturally, either in C++ culture or Qt culture?
Am I using the wrong tool for the job at any point, for instance in my use of QStackedLayout?
Is the design robust? For instance, adding buttons to the menu happens separately to adding pages to the StackedLayout. Should I create a MultiPageEnvironment class or something to handle this automatically?
Any major C++ or Qt no-nos?

main.cpp

#include <QApplication>

#include "MainWindow.h"

int main(int argc, char **argv)
{
    QApplication *app = new QApplication(argc, argv);
    MainWindow *mw = new MainWindow();
    mw -> show();
    return app -> exec();
}

MainWindow.cpp

#include <stdio.h>
#include <QWidget>
#include <QPushButton>
#include <QStackedLayout>

#include "MainWindow.h"
#include "MenuPage.h"
#include "SubPage.h"

MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
    setWindowTitle("Application");
    layout = new QStackedLayout();
    MenuPage *menuPage = new MenuPage(this);
    SubPage  *page1    = new SubPage("This is page one.", this);
    SubPage  *page2    = new SubPage("This is page two.", this);

    layout -> addWidget(menuPage);
    layout -> addWidget(page1);
    layout -> addWidget(page2);
    layout -> setCurrentIndex(0);
    this   -> setLayout(layout);

    menuPage -> addButton();
    menuPage -> addButton();
}

void MainWindow::setPage(int index)
{
    layout -> setCurrentIndex(index);
}

void MainWindow::goToMenu()
{
    layout -> setCurrentIndex(0);
}

MenuPage.cpp

#include <stdio.h>
#include <QWidget>
#include <QPushButton>
#include <QSignalMapper>

#include "MenuPage.h"

MenuPage::MenuPage(MainWindow *parent) : QWidget(parent)
{
    signalMapper = new QSignalMapper(this);
    connect(signalMapper, SIGNAL(mapped(int)), parent, SLOT(setPage(int)));

    layout = new QVBoxLayout();
    setLayout(layout);

    nButtons = 0;
}

void MenuPage::addButton()
{
    nButtons += 1;

    QString label = (new QString("Page %1")) -> arg(nButtons);
    QPushButton *button = new QPushButton(label, this);
    layout -> addWidget(button);

    signalMapper -> setMapping(button, nButtons);
    connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
}

SubPage.cpp

#include <stdio.h>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>

#include "SubPage.h"
#include "MainWindow.h"

SubPage::SubPage(const char messageString[], MainWindow *parent) : QWidget(parent)
{
    message = new QLabel(messageString, this);
    backButton = new QPushButton("Back", this);

    QVBoxLayout *layout = new QVBoxLayout();
    layout -> addWidget(message);
    layout -> addWidget(backButton);
    setLayout(layout);

    connect(backButton, SIGNAL(clicked()), parent, SLOT(goToMenu()));
}


texts: Computing a Discrete Cosine Transform matrix

texts:
I'm learning Haskell and I needed to work with discrete cosine transform matrices, so I made a program that generates text (usable in WolframAlpha) containing the generated matrix.

The elements of the n-square matrix C are defined as:

\$[C]_{jk} = \gamma_jcos\dfrac{\pi(2k+1)j}{2n}\$ where \$\gamma_{j} = \begin{cases}\frac{1}{\sqrt{n}} & \text{j = 0} \\ \frac{2}{\sqrt{n}} & \text{otherwise} \end{cases}\$

I also wanted the program to simplify fractions and sqrt, which is where most of  the "dirtiness" came from. Is there any way to clean this up? It's simple enough, but I want to learn how to be concise.

import Ratio

-- Pretty-print a fraction
showFraction n d
    | n == 0            = "0"
    | d == 0            = error "Division by zero."
    | n == 1 && d == 1  = "1"
    | n == 1            = "1/" ++ show d
    | d == 1            = show n
    | otherwise         = show n ++ "/" ++ show d

-- Pretty-print a fraction, reducing the fraction
showFractionReduced n d = let x = n % d in showFraction (numerator x) (denominator x)

-- Pretty-print a fraction, with an additional numerator factor
showFraction' n d n'
    | n == 0            = "0"
    | d == 0            = error "Division by zero."
    | n == 1 && d == 1  = n'
    | n == 1            = n' ++ "/" ++ show d
    | d == 1            = show n ++ "*" ++ n'
    | otherwise         = show n ++ "*" ++ n' ++ "/" ++ show d

-- Pretty-print a fraction, reducing the fraction, with an additional numerator factor
showFractionReduced' n d = let x = n % d in showFraction' (numerator x) (denominator x)

-- Discrete cosine transform matrix element
dctElement j k n
    | n <= 1            = "1"
    | n == 2 && j > 0   = "cos(" ++ showFractionReduced' (j * (2 * k + 1)) (2 * n) "pi" ++ ")"
    | j == 0            = "sqrt(" ++ showFractionReduced 1 n ++ ")"
    | otherwise         = "sqrt(" ++ showFractionReduced 2 n ++ ")*cos(" ++ showFractionReduced' (j * (2 * k + 1)) (2 * n) "pi" ++ ")"

-- Discrete cosine transform matrix row
dctRow j n = "{" ++ foldr1 (\acc x -> acc ++ "," ++ x) [dctElement j x n | x <- [0..n - 1]] ++ "}"

-- Discrete cosine transform matrix
dctMatrix n = "{" ++ foldr1 (\acc x -> acc ++ ",\n" ++ x) [dctRow x n | x <- [0..n - 1]] ++ "}"

-- Inverse discrete cosine transform matrix row
dctRowInverse j n = "{" ++ foldr1 (\acc x -> acc ++ "," ++ x) [dctElement x j n | x <- [0..n - 1]] ++ "}"

-- Inverse discrete cosine transform matrix
dctMatrixInverse n = "{" ++ foldr1 (\acc x -> acc ++ ",\n" ++ x) [dctRowInverse x n | x <- [0..n - 1]] ++ "}"

The string generated by dctMatrix 3, for example, is:

  {{sqrt(1/3),sqrt(1/3),sqrt(1/3)},
  {sqrt(2/3)*cos(pi/6),sqrt(2/3)*cos(pi/2),sqrt(2/3)*cos(5*pi/6)},
  {sqrt(2/3)*cos(pi/3),sqrt(2/3)*cos(pi),sqrt(2/3)*cos(5*pi/3)}}

while the string generated by dctMatrix 2 is:

  {{sqrt(1/3),sqrt(1/3),sqrt(1/3)},
  {sqrt(2/3)*cos(pi/6),sqrt(2/3)*cos(pi/2),sqrt(2/3)*cos(5*pi/6)},
  {sqrt(2/3)*cos(pi/3),sqrt(2/3)*cos(pi),sqrt(2/3)*cos(5*pi/3)}}

(Notice the simplification of the fractions in the former, and the square root in the latter.)


texts:
I'm learning PHP, HTML and SQL - and wondered if anyone could take a look at this code and give me some feedback?

<!DOCTYPE html>

    <link rel="stylesheet" href="styles.css">
    <title>Store product information</title>

    <?php

    $host = "localhost";
    $database = "shopDB";
    $username = "root";
    $password = "";

    $conn = new mysqli($host, $username, $password);
    $db_handle = $conn->select_db($database);

    if ($db_handle)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            // Upload to server
            $name = mysqli_real_escape_string($conn, $_POST['name']);
            $quantity = mysqli_real_escape_string($conn, $_POST['quantity']);
            $price = mysqli_real_escape_string($conn, $_POST['price']);
            $description = mysqli_real_escape_string($conn, $_POST['description']);

            $insert_sql = "INSERT INTO products (name, quantity, price, description) VALUES ('$name', '$quantity', '$price', '$description')";
            $insert_result = $conn->query($insert_sql);

            if ($insert_result)
            {
                // Uploaded successfully
            } else {
                print mysqli_error($conn);
            }
        }

        $products_sql = "SELECT
                           products.name,
                           products.quantity,
                           products.price,
                           products.description
                         FROM products";
        $products_result = $conn->query($products_sql);

        if ($products_result)
        {
            print "
";

            print "
";
            print "
";
            print "Name	";
            print "Quantity	";
            print "Price	";
            print "Description	";
            print "
";
            print "
";

            print "
";
            while ($db_field = mysqli_fetch_assoc($products_result))
            {
                print "
";
                print "" . $db_field['name'] . "	";

                if ($db_field['quantity'] == '0') {
                    print "" . $db_field['quantity'] . "	";
                } else {
                    print "" . $db_field['quantity'] . "	";
                }

                print "" . $db_field['price'] . "	";
                print "" . $db_field['description'] . "	";
                print "
";
            }
            print "
";
            print "
";
        }
    }

    ?>

Insert items

    <form action="index.php" method="post">

                Name
                Quantity
                Price
                Description

                <input name="name" type="text"></input>
                <input name="quantity" type="text"></input>
                <input name="price" type="text"></input>
                <input name="description" type="text"></input>

    <input id="submit_button" type="submit" value="Register item">
    </form>

Database structure:


texts: Getting the dominant RGB color of a bitmap

texts:
I'm currently running this function 60 times per second in order to get the dominant color on my screen in RGB values. It is using approximately 15% of my CPU on 30FPS and 25% of my CPU on 60FPS. Is there any way I can improve the efficiency of this loop or is there a better way to get the color altogether?

public Color getDominantColor(System.Drawing.Bitmap bmp) {
            BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            int stride = srcData.Stride;

            IntPtr Scan0 = srcData.Scan0;

            int[] totals = new int[] { 0, 0, 0 };

            int width = bmp.Width;
            int height = bmp.Height;

            unsafe
            {
                byte* p = (byte*)(void*)Scan0;

                for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++) {
                        for (int color = 0; color < 3; color++) {
                            int idx = (y * stride) + x * 4 + color;
                            totals[color] += p[idx];
                        }
                    }
                }
            }

            int avgB = totals[0] / (width * height);
            int avgG = totals[1] / (width * height);
            int avgR = totals[2] / (width * height);

            bmp.UnlockBits(srcData);

            return Color.FromArgb(avgR, avgG, avgB);
        }


texts: DM::OJ Slot Machines challenge in Python 3

texts:
I have written a solution to the Slot Machines challenge on DM::OJ:

  Martha takes a jar of quarters to the casino with the intention of becoming rich. She plays three machines in turn. Unknown to her, the machines are entirely predictable. Each play costs one quarter. The first machine pays 30 quarters every 35th time it is played; the second machine pays 60 quarters every 100th time it is played; the third pays
  9 quarters every 10th time it is played.

  Input Specification

  Your program should take as input the number of quarters in Martha's jar (there will be at least one and fewer than 1000), and the number of times each machine has been played since it last paid.

  Output Specification

  Your program should output the number of times Martha plays until she goes broke.

  Sample Input

48
3
10
4

  Sample Output

Martha plays 66 times before going broke.

I am seeking to make it run in 2 seconds or less.

money = int(input())
m1 = int(input())
m2 = int(input())
m3 = int(input())
turns = 0

while (money != 0):
  #machine 1
  money -= 1
  m1 += 1
  if (m1 == 35):
    money += 30
    m1 = 0
  turns += 1

  #machine 2
  money -= 1
  m2 += 1
  if (m2 == 100):
    money += 60
    m2 = 0
  turns += 1

  #machine 3
  money -= 1
  m3 += 1
  if (m3 == 10):
    money += 9
    m3 = 0
  turns += 1

print ('Martha plays {} times before going broke.'.format(turns))


texts:
I have a CLS_Comparison_Predicate which will take an input value, perform a logical comparison and return a Boolean.

CLS_Compound_Predicate instead takes lists of predicates and an inputValue, and performs MatchAny() or MatchAll() operations on the predicate list.

E.G.

  predicate_1 has >= 3
  predicate_2 has = 5

  MatchAny(6) Returns True
  MatchAll(6) Returns False

Thoughts?

Option Explicit

Private predicateList As Variant

Private Const NULL_ERROR_TEXT As String = "Invalid Compare input. Cannot compare against Null"
Private Const OBJECT_ERROR_TEXT As String = "Invalid Compare input. Input must be a value, not an object"
Private Const NOTHING_ERROR_TEXT As String = "Invalid Compare Input. Predicate cannot be Nothing"
Private Const EMPTY_ERROR_TEXT As String = "Invalid Compare Input. Input cannot be empty"
Private Const ZLS_ERROR_TEXT As String = "Invalid Compare Input. Input cannot be a Zero-Length-String"

Public Sub AddPredicate(ByRef inputPredicate As CLS_Comparison_Predicate)

    If inputPredicate Is Nothing Then
        PrintErrorMessage NOTHING_ERROR_TEXT
        Stop
    End If

    If IsEmpty(predicateList) Then
        ReDim predicateList(1 To 1)
        Set predicateList(1) = inputPredicate
    Else
        Dim LB1 As Long, UB1 As Long
        GetBounds LB1, UB1

        ReDim Preserve predicateList(LB1 To UB1 + 1)
        Set predicateList(UB1 + 1) = inputPredicate
    End If

End Sub

Public Sub ClearPredicates()

    If Not predicateList Is Nothing Then Erase predicateList

End Sub

Public Function MatchAny(ByVal leftValue As Variant) As Boolean
    '/ compares leftValue against predicateList. If any return true, then return true, else return false

    CheckInputValue leftValue

    Dim LB1 As Long, UB1 As Long
    GetBounds LB1, UB1

    Dim matchesAny As Boolean
    matchesAny = False

    Dim predicate As CLS_Comparison_Predicate
    Dim ix As Long
    For ix = LB1 To UB1
        Set predicate = predicateList(ix)
        If predicate.Compare(leftValue) Then
            matchesAny = True
            Exit For
        End If
    Next ix

    MatchAny = matchesAny

End Function

Public Function MatchAll(ByVal leftValue As Variant) As Boolean
    '/ compares leftValue against predicateList. If any return false, then return false, else return true

    CheckInputValue leftValue

    Dim LB1 As Long, UB1 As Long
    GetBounds LB1, UB1

    Dim matchesAll As Boolean
    matchesAll = True

    Dim predicate As CLS_Comparison_Predicate
    Dim ix As Long
    For ix = LB1 To UB1
        Set predicate = predicateList(ix)
        If Not predicate.Compare(leftValue) Then
            matchesAll = False
            Exit For
        End If
    Next ix

    MatchAll = matchesAll

End Function

Private Sub CheckInputValue(ByVal inputValue As Variant)
    '/ Check for NULL, Objects, Empty and ZLS

    If IsNull(inputValue) Then
        PrintErrorMessage NULL_ERROR_TEXT
        Stop
    End If

    If IsObject(inputValue) Then
        PrintErrorMessage OBJECT_ERROR_TEXT
        Stop
    End If

    If IsEmpty(inputValue) Then
        PrintErrorMessage EMPTY_ERROR_TEXT
        Stop
    End If

    On Error Resume Next
        If Len(inputValue) = 0 Then
            PrintErrorMessage ZLS_ERROR_TEXT
            Stop
        End If
    On Error GoTo 0

End Sub

Private Sub GetBounds(Optional ByRef LB1 As Long, Optional ByVal UB1 As Long)

    LB1 = LBound(predicateList)
    UB1 = UBound(predicateList)

End Sub


texts: Returning MIME types according to input filenames' extensions

texts:
I am coding on codingame.com, where one of the 'easy' challenges is to assign MIME type strings to input strings of file names based on their extensions.

My code passes four out of five of the test cases, and the last one is an optimization test. A big data set is inputted, and my approach times out.

I started coding in python under a year ago, and I haven't had much practice. I would like to know what I could do to improve my code.

I have seen really short solutions to other puzzles in the 'other solutions' tab, so I am not surprised if there is a clever workaround to make this shorter.

import sys
import math

n = int(input())  # Number of elements which make up the association table.
q = int(input())  # Number Q of file names to be analyzed.

MIMETable = {}
fileNames = {}
extensions = {}
answer = ''

#extract association input to table
for i in range(n):
    # ext: file extension
    # mt: MIME type.
    ext, mt = input().split()
    MIMETable [ext.lower()] = mt
    #print(str(ext) + '\t|   ' + str(mt), file=sys.stderr)

#print('\n', file=sys.stderr)

#extract filename input
for i in range(q):
    fname = input()  # One file name per line.
    fileNames[i] = fname
    #print(str(i) + ' ' + fname, file=sys.stderr)

#   find the extensions of the filenames
#   and add them to extensions{} in lowercase as they are in MIMETable
for index, name in fileNames.items():
    if '.' in name:
        try:
            extensions[index] = name.split('.')[-1].lower()
        except IndexError:
            extensions[index] = 'unknown'
    else:
        extensions[index] = 'unknown'
    #print(extensions[index], file=sys.stderr)

#print('', file=sys.stderr)

#if there is an extension, find the corresponding MIME type
for fileIndex in range(q):
    extensionFound = False
    for mimeExtension, mimetype in MIMETable.items():
        if extensions[fileIndex] == mimeExtension:
            answer += mimetype
            extensionFound = True
            #print('extension found: ' +  extensions[fileIndex] + '\t' + mimetype, file=sys.stderr)
    if not extensionFound:
        answer += 'UNKNOWN'
    answer += '\n'

print('\n', file=sys.stderr)

# For each of the Q filenames, display on a line the corresponding MIME type. If there is no corresponding type, then display UNKNOWN.
print(answer)


texts:
I'm making a Mandelbrot set viewer in JavaFX. It takes a while, like maybe 5 seconds to finish.  Here's my code:

package sample;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {
    private static int MAX_ITER = 80;
    private static double w = 10*100;
    private static double h = 2*Math.PI*100;

    static double RE_START = -2;
    static double RE_END = 1;
    static double IM_START = -1;
    static double IM_END = 1;

    public static int mandelbrot(Complex c) {
        Complex z = new Complex(0,0);
        int n = 0;
        while (Complex.abs(z).isLessThanOrEqual(2) && n < MAX_ITER) {
            z = Complex.add(Complex.multiply(z,z),c);
            n++;
        }
        return n;
    }

    public void start(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setTitle("Mandelbrot Viewer");
        primaryStage.setScene(new Scene(root, w, h));
        primaryStage.show();

        Canvas canvas = new Canvas();
        GraphicsContext gc = canvas.getGraphicsContext2D();
        canvas.setWidth(w);
        canvas.setHeight(h);
        canvas.relocate(0, 0);
        root.getChildren().add(canvas);
        update(gc);
    }

    private static void update(GraphicsContext gc) {
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                Complex c = new Complex(RE_START + (x / w) * (RE_END - RE_START),
                        IM_START + (y / h) * (IM_END - IM_START));
                int m = mandelbrot(c);
                int hue = 360 * m / MAX_ITER;
                System.out.println(hue);
                int saturation = 255;
                int value = 0;
                if (m < MAX_ITER) {
                    value = 255;
                }
                gc.setFill(Color.hsb(hue, saturation/255d, value/255d));
                gc.fillRect(x, y, 1, 1);
            }
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

    static class Complex {
        double r;
        double i;

        Complex(double r, double i) {
            this.r = r;
            this.i = i;
        }

        static public Complex abs(Complex c) {
            return new Complex(Math.abs(c.r), Math.abs(c.i));
        }

        public boolean isLessThanOrEqual(double n) {
            if (r <= n || i <= n) {
                return true;
            }

            return false;
        }

        static public Complex add(Complex c1, Complex c2) {
            return new Complex(c1.r + c2.r, c1.i + c2.i);
        }

        static public Complex multiply(Complex c1, Complex c2) {
            return new Complex((c1.r*c2.r)-(c1.i*c2.i), (c1.r*c2.i)+(c1.i*c2.r));
        }

        public String toString() {
            return (r + ", " + i);
        }
    }
}

I eventually want it so that I can move around and zoom into the mandelbrot set with at least 10 fps.  How might I be able to make it faster?  Should I try switching from JavaFX to AWT or something?  Should I try using the GPU? if so, what would be the most simple way to do so? (because I don't really want to spend too much time on this project)


texts:
This code works great and does exactly as it should, but there has to be a better way of doing this and I just can't figure out how!

I'm pretty new to jQuery and am trying to use it more myself instead of using plugins and I can get stuff to work fine. It just isn't the tidiest or neatest code, which I'm trying to move away from!

I've included a fiddle here just so you can see the functionality as it currently stands.

HTML

Example 1

Example 2

Sub Example 2.1

Sub Example 2.2

Sub Example 2.3

Sub Example 2.4

Example 3

Sub Example 3.1

Sub Example 3.2

Sub Example 3.3

jQuery

var menu = $('li.open ul');
menu.css('display','none');
     $('li.open')
     .mouseenter(function(){
          menu.slideDown(400);
     })
     .mouseleave(function(){
          menu.slideUp(400);
     });

var menu2 = $('li.open2 ul');
menu2.css('display', 'none');
    $('li.open2')
    .mouseenter(function(){
         menu2.slideDown(400);
     })
     .mouseleave(function(){
         menu2.slideUp(400);
     });


texts:
This supposed to implement a Maybe type that can either hold a value T or "nothing". It's designed to work well with vectors (that's why I take extra care to noexcept constructors whenever possible). I'm governing the actual data with ::std::aligned_storage. Note: The just member function is a reference to the Haskell Maybe data-constructor Just.

Did I miss anything?

#pragma once

#include <utility>
#include <algorithm>
#include <type_traits>

namespace ads {
  template <typename T>
  class Maybe {
    public:
      typedef typename ::std::aligned_storage<sizeof(T),alignof(T)>::type storage_type;
      typedef T value_type;
    private:
      storage_type data;
      bool is_valid;
      inline T* ptr() {
        return reinterpret_cast<T*>(&data);
      }
      inline T const* ptr() const {
        return reinterpret_cast<T const*>(&data);
      }
    public:
      Maybe() noexcept : data(), is_valid(false) {}
      template <typename U>
      Maybe(U&& v) noexcept(::std::is_nothrow_move_constructible<T>::value) : data(), is_valid(false) {
        create(::std::forward<U>(v));
      }
      Maybe(Maybe const& from) noexcept(::std::is_nothrow_copy_constructible<T>::value) : data(), is_valid(false) {
        if (from.is_valid)
          create(*from.ptr());
      }
      Maybe(Maybe&& from) noexcept(::std::is_nothrow_move_constructible<T>::value) : data(), is_valid(false) {
        if (from.is_valid)
          create(::std::move(*from.ptr()));
      }
      template <typename U>
      Maybe& operator=(U&& v) noexcept(::std::is_nothrow_move_constructible<T>::value && ::std::is_nothrow_copy_constructible<T>::value && ::std::is_nothrow_assignable<T,U>::value) {
        create(::std::forward<U>(v));
        return *this;
      }
      Maybe& operator=(Maybe const& from) noexcept(::std::is_nothrow_copy_constructible<T>::value && ::std::is_nothrow_assignable<T,T>::value) {
        if (from.is_valid) {
          create(*from.ptr());
        } else {
          destroy();
        }
        return *this;
      }
      Maybe& operator=(Maybe&& from) noexcept(::std::is_nothrow_move_constructible<T>::value && ::std::is_nothrow_assignable<T,T>::value) {
        if (from.is_valid) {
          create(::std::move(*from.ptr()));
        } else {
          destroy();
        }
        return *this;
      }
      ~Maybe() noexcept(::std::is_nothrow_destructible<T>::value) {
        destroy();
      }

      bool valid() const noexcept {
        return is_valid;
      }
      operator T&() noexcept {
        return *ptr();
      }
      operator T const&() const noexcept {
        return *ptr();
      }
      T& just() noexcept {
        return *ptr();
      }
      T const& just() const noexcept {
        return *ptr();
      }

      template <typename U>
      void create(U&& v) noexcept(::std::is_nothrow_move_constructible<T>::value && ::std::is_nothrow_copy_constructible<T>::value && ::std::is_nothrow_assignable<T,U>::value){
        if (is_valid) {
          *ptr() = ::std::forward<U>(v);
        } else {
          new(&data) T(::std::forward<U>(v));
          is_valid = true;
        }
      }
      void destroy() noexcept(::std::is_nothrow_destructible<T>::value) {
        if (is_valid) {
          ptr()->~T();
          is_valid = false;
        }
      }
  };
}


texts: Converting a JSON object to XML to be passed to an ASMX webservice

texts:
What I have is a scenario where we need to be able to call any ASMX web service and pass any data structure to it that has been constructed on the JavaScript side.

Until now, I have been creating service references for ASMX web services in order to call them, but in this scenario, I can no longer do that. This is my first go at passing XML to service references manually.

What I am not too sure of is the level of complexity required to get a JSON string into basically an XML string to be passed to the webservice.

 string func_name = "//some asmx web service function"
 string json_string = "//some json encoded string here";
 XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(variables, "root");
 StringWriter stringWriter = new StringWriter();
 XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
 doc.WriteTo(xmlTextWriter);
 string xml_parameters = stringWriter.ToString();

 //remove <root> and </root> from the string
 xml_parameters = xml_parameters.Replace("<root>", null).Replace("</root>", null);

string request_xml= "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                            "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
                               "<soap:Body>" +
                                   "<" + func_name + " xmlns=\"http://tempurl.org\" >" +
                                     xml_parameters+
                                   "</" + func_name +" >" +
                               "</soap:Body>" +
                           "</soap:Envelope>";

HttpResponseMessage response = client.PostAsync(uri, new StringContent(xml, Encoding.UTF8, request_header_type)).Result;

An awful lot of objects have been instantiated here in order to get my JSON converted into XML to be passed to the web service. Can anyone suggest any improvements or potential problems?


texts: Backbone/ChaplinJS view with various template

texts:
I have ChaplinJS View, with template which varies according to the condition.
I try to avoid switch statements, but I think it's messy at this moment.

What can you advise?

var SiteView = View.extend({
    region: 'date',
    autoRender: true,
    className: 'date-label',
    containerMethod: 'append',

    initialize: function(params) {
        this.type = params.type;
        this.types[this.type].call(this);
    },

    attach: function() {
        View.prototype.attach.call(this);
        var _this = this;

        _this.$el.addClass('active');
    },

    types: {
        day: function() {
            var source = "{{day}}, {{dayNum}} {{month}}. {{year}} г.";
            var template = Handlebars.compile(source);

            this.template = template({
                day: moment(Chaplin.mediator.currentDate).format('dd'),
                dayNum: moment(Chaplin.mediator.currentDate).format('D'),
                month: moment(Chaplin.mediator.currentDate).format('MMM'),
                year: moment(Chaplin.mediator.currentDate).format('YYYY')
            });
        },

        week: function() {
            var source = "{{weekStart}} – {{weekEnd}} {{month}}, {{year}} (н. {{week}})";
            var template = Handlebars.compile(source);

            this.template = template({
                weekStart: moment(new Date()).startOf('week + 1').isoWeekday(1).format('D'),
                weekEnd: moment(new Date()).startOf('week + 1').isoWeekday(7).format('D'),
                week: moment(Chaplin.mediator.currentDate).format('wo'),
                month: moment(Chaplin.mediator.currentDate).format('MMM'),
                year: moment(Chaplin.mediator.currentDate).format('YYYY')
            });
        },

        month: function() {
            var source = "{{month}} {{year}}";
            var template = Handlebars.compile(source);

            this.template = template({
                month: moment(Chaplin.mediator.currentDate).format('MMMM'),
                year: moment(Chaplin.mediator.currentDate).format('YYYY')
            });
        },

        year: function() {
            var source = "{{year}}";
            var template = Handlebars.compile(source);

            this.template = template({
                year: moment(Chaplin.mediator.currentDate).format('YYYY')
            });
        }
    }
});


texts: script to check sequence number in a binary file

texts:
This is a script to check the sequence number (8 bit unsigned integer) in a binary file and make sure it is incrementing till the end and not missing any sequence number in between. Sequence number is some 'x' bytes from a sentinel found in the binary file. The fixed size packet (some audio data) in binary file gets repeated and this aforementioned packet also has the sentinel along with other audio data.

I am new to python so I'd appreciate a code review.

#!/usr/bin/python
import sys,getopt

def parse_arguments():
  def usage():
    print("python script to check missing sequence number in a binary file")
    print("pass filename, packet_size(optional) and sequence offset where sequence number is found in the packet")
    print("python %s -f filename -s packet_size -i sequence_offset"% (sys.argv[0]))

  filename, packet_size, sequence_offset = None, 0, None
  try:
      opts,args = getopt.getopt(sys.argv[1:],'ha:f:i:s:', ['help', 'filename', 'index'])
  except getopt.GetoptError as err:
      print(err)
      sys.exit(2)

  if len(opts) != 0:
     for (o, a) in opts:
        if o in ('-h', '--help'):
           usage()
           sys.exit()
        elif o in ('-f', '--filename'):
           filename = a
        elif o in ('-s', '--packet_size'):
           packet_size = int(a)
        elif o in ('-i', '--sequence_offset'):
           sequence_offset = int(a)
        else:
           usage()
           sys.exit(2)
  else:
     usage()
     sys.exit(2)
  return filename, packet_size, sequence_offset

def is_sequence_missing(filename, packet_size = 5392, sequence_offset = 11):
  def get_sequence_idx(filename, sentinel = ['0x4f', '0x5f', '0x4d', '0x41']):
    blob = None
    with open(filename,"rb") as f:
      blob = f.read()
      len_sentinel = len(sentinel)
      for i in range(len(blob)):
        if i + len_sentinel < len(blob) and sentinel == [hex(ord(j)) for j in blob[i:i+len_sentinel]]:
          return (blob, i)
    return (blob, None)

  missing, start, counter = False, True, 0

  blob, idx = get_sequence_idx(filename)
  if not idx:
    print("sentinel not found")
    return not missing
  print("sentinel starting at 0x%x"% (idx))

  for i in range(idx - sequence_offset, len(blob), packet_size):
    v = ord(blob[i])
    if start:
      print("started with sequence number 0x%x"% (v))
      start = False
      counter = v + 1
      continue
    if counter == v:
      counter += 1
      if counter == 256:
        counter = 0
    else:
      print("not matching expected: 0x%x receieved: 0x%x at 0x%x"% (counter, v, i))
      counter = v + 1
      missing = True
  return missing

if __name__ == "__main__":
  filename, packet_size, sequence_offset = parse_arguments()
  print("passed filename %s packet_size %d sequence_offset %d"% (filename, packet_size, sequence_offset))
  if is_sequence_missing(filename, packet_size, sequence_offset) == True:
    print("sequence is missing")
  else:
    print("sequence is not missing")


texts:
We are thinking about hiring more developers so I was asked to compose a test.  I have been looking online for ideas.  I found this question: How to add n days to a Date in java without importing Date/Calendar from java API?.  I have attempted this myself as follows:

public class Date : IEquatable<Date>
    {
        private readonly static int[] _daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        private readonly int _month;
        private readonly int _day;
        private readonly int _year;

        public Date(int day, int month, int year)
        {
            this._day = day;
            this._month = month;
            this._year = year;
        }

        //static because thinking about using in constructor for validation.
        public static int MaxDays(int month, int year)
        {
            int maxDays = _daysInMonth[month - 1];
            if (month == 2)
            {
                if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
                    maxDays = maxDays + 1;
            }
            return maxDays;
        }

        public Date AddDays(int daysToAdd)
        {
            int day = this._day + daysToAdd;
            int month = this._month;
            int year = this._year;
            while (day > MaxDays(month,year))
            {
                day = day - MaxDays(month,year);
                month++;
                if (month > 12)
                {
                    year++;
                    month = 1;
                }
            }
            return new Date(day, month, year);
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as Date);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hash = 17;
                hash = hash * 23 + _day.GetHashCode();
                hash = hash * 23 + _month.GetHashCode();
                hash = hash * 23 + _year.GetHashCode();
                return hash;
            }
        }

        public static bool operator ==(Date date1, Date date2)
        {
            if (ReferenceEquals(date1, null) && ReferenceEquals(date2, null))
                return true;
            if (ReferenceEquals(date1, null) || ReferenceEquals(date2, null))
                return false;
            return date1.Equals(date2);
        }

        public static bool operator !=(Date date1, Date date2)
        {
            return !(date1 == date2);
        }

        public bool Equals(Date other)
        {
            if (ReferenceEquals(other, null))
                return false;
            return _day == other._day && _month == other._month && _year == other._year;
        }
    }

I would be grateful for comments.  I reviewed the terms of posting here: https://codereview.stackexchange.com/help/on-topic.  This is real code (no stubs) that works and therefore I believe it is on topic.


texts:
I am studying about how to use an interface for decoupling, and I wrote a program.  Does it actually implemented decoupling?  Are there any possible modifications to make it better?

public partial class MainPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        IDBInterface idbInterface = new SQL();
        CommunicationChannel com = new CommunicationChannel();
        com.Update(idbInterface);
    }
}

interface IDBInterface
{
    void Update();
}

class SQL:IDBInterface
{
    public void Update()
    {
        MessageBox.Show("Please wait.. We are updating SQL Server...");
    }
}

class Oracle : IDBInterface
{
    public void Update()
    {
        MessageBox.Show("Please wait.. We are updating Oracle Server...");
    }
}

class CommunicationChannel
{
    public void Update(IDBInterface idb)
    {
        idb.Update();
    }
}
}


texts: Using the ConcurrentBag as an object pool for an ASP.NET application

texts:
Is there anything wrong with this implementation of an object pool that will be called from an ASP.NET application?

The object I want to pool has extremely expensive initialization, so currently I am storing one instance of it in a static variable and using C# lock() to avoid race conditions.  I want to change to an object pool so that more that one asp.net thread can make use of it simultaneously.

The object pool must have a maximum size restriction, so that callers of GetObject wait in line to get an instance of the pooled object.  For example, if I have a maximum size of 10, and suddenly 20 asp.net threads need an instance, 10 threads should get an instance immediately, and the other 10 threads should wait patiently (and in turn) for one of the 10 instances to be freed up.

The object pool class below is stolen nearly in-toto from this MSDN article, except that it incorporates Scott Chamberlain's suggestion to use a BlockingCollection:

public class ObjectPool<T>
{
    private ConcurrentBag<T> _objects;
    private Func<T> _objectGenerator;

    public ObjectPool(Func<T> objectGenerator,
        int boundedCapacity,
        int initializeCount = 0)
    {
        if (objectGenerator == null) throw new ArgumentNullException("objectGenerator");
        _objects = new BlockingCollection<T>(new ConcurrentBag<T>(), boundedCapacity);
        _objectGenerator = objectGenerator;
        if (initializeCount > 0)
        {
            int counter = 0;
            while (counter++ < initializeCount)
            {
                _objects.Add(_objectGenerator());
            }
        }
    }

    public T GetObject()
    {
        T item;
        if (_objects.TryTake(out item)) return item;
        return _objectGenerator();
    }

    public void PutObject(T item)
    {
        _objects.Add(item);
    }

}

From my ASP.NET code, I'm instantiating the pool as a static variable:

static ObjectPool<MyClass> _pool = new ObjectPool<MyClass>(() => {
            var myClass = new MyClass();
            myClass.DataSource = something;
            return myClass;
        }, 10, 5);

And then using it like this, in a try-finally block so that the PutObject method is always called.  The ConcurrentBag is called "thread safe" so I am not locking access to the GetObject or PutObject methods.

MyClass myClass = _pool.GetObject();
try
    {
        myClass.Input = "123 Main, Anytown, MI";
        var result = myClass.ValidateAddress();
    }
finally
    {
        _pool.PutObject(myClass);
    }


texts:
Linq's AsParallel() call would be my normal way of doing something like this, but Rust hasn't stolen that just yet. This method has obvious shortcomings, but I'm still sort of hoping for it to shave off a little time by engaging a second core.

How can I achieve this less terribly?

use std::num::Float;
use std::sync::Future;

fn main() {
    // This implementation cheats because it knows the biggest prime value
    // in the range: 7919. Getting primes in parallel is a pain in the ass
    // pretty much no matter what, and it's probably not worth it, but on
    // the up side... Eh. Whatever. Only other way I know to do this would
    // be to get the first *1001* primes, sort them, and then fold the first
    // thousand after stuffing them into a vector.

    let mut path_1 = Future::spawn(proc() {
        Unfold::new(3, incr).filter(prime).take_while(|n| *n <= 7919).fold(0i, |a, b| a + b)
    });
    let mut path_2 = Future::spawn(proc() {
        Unfold::new(5, incr).filter(prime).take_while(|n| *n <= 7919).fold(0i, |a, b| a + b)
    });

    // As you can see, my plan here was to get 999 primes (skipping 2)
    // and then add 2 back in later on.
    println!("{}", path_1.get() + path_2.get() + 2);
}

fn incr(n: &mut int) -> Option<int> {
    let r = Some(*n);
    *n = *n + 4;
    r
}

fn prime(n: &int) -> bool {
    match n {
        &1 => false,
        &2 => true,
        &3 => true,
        n if *n % 2 == 0 => false,
        _ => {
            let max = (*n as f64).sqrt() as int + 1;
            !range(2, max).any(|i| *n % i == 0)
        }
    }
}


texts: Java Crypto library number of padding bytes using PKCS5Padding

texts:
I have implemented AES encryption in Java using the following function. What puzzles me is the number of padding bytes added using the PKCS5Padding method. For example, when calling the following function with a text byte of length 12, the output is a 32 byte array. I would expect a 16 byte output of which 4 bytes are padding.
How can the initialization of the cipher be changed to do this?

public byte[] do_decryption(byte[] text) {

        String key_val = new String("1234567890123456");
        byte[] key = key_val.getBytes();

        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            System.out.println("Block size: " + cipher.getBlockSize());

            byte[] output = cipher.doFinal(text);
            return output;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


texts:
I have written a simple system to load plugins from files in Python 2.7, and I'd like to see if any of it can be improved upon.

vedo.py

from __future__ import absolute_import

import os.path
import inspect

from vedo.event_emitter import EventEmitter
from vedo import VedoPlugin

def _get_module_name(directory, filename):
    return '{0}.{1}'.format(os.path.basename(directory), filename)

def _is_plugin_class(plugin_class):
    return (inspect.isclass(plugin_class) and
            issubclass(plugin_class, VedoPlugin) and
            plugin_class != VedoPlugin)

class Vedo(EventEmitter):
    def __init__(self, plugin_directory):
        self._plugin_directory = plugin_directory
        self._plugins = []

    @property
    def plugin_directory(self):
        return self._plugin_directory

    @property
    def plugins(self):
        return self._plugins

    def load_module(self, module):
        plugin_classes = [c for c in module.__dict__.values() if
                          _is_plugin_class(c)]

        for plugin_class in plugin_classes:
            self.plugins.append(plugin_class(self))

    def load_file(self, name):
        try:
            plugin_module = _get_module_name(self._plugin_directory, name)
            namespace = __import__(plugin_module)
        except ImportError:
            return

        self.load_module(getattr(namespace, name))

Each plugin must inherit from VedoPlugin, and is loaded by the Vedo class.

Here's an example plugin:

plugins/first.py

class MyFirstPlugin(VedoPlugin):
    def __init__(self, vedo):
        super(MyFirstPlugin, self).__init__(vedo)

And a quick example of how to use Vedo:

vedo = Vedo("./plugins")
vedo.load_file("first")

vedo.plugins[0] # This is an instance of `MyFirstPlugin'

Here's some things I'm not too fond of, but I'm not sure what I can do about them:

Should the private functions in the top of vedo.py be moved inside the Vedo class?
Should load_module be private? It's only really going to be used when loading files.
Is there a way to get around the ugliness that is the plugin __init__ function? Every single plugin will need to have that constructor, which I'm not too happy about.


texts: Custom C++ exception class with stack trace generation

texts:
I wanted to implement my own runtime error class in C++, that could provide more meaningful information on where the error occurred than std::runtime_error does.

I decided to use boost::stacktrace to generate a stack trace, appended to the exception message.

Anyway, this is my code:

/**
    \brief Represents a runtime error.

    Equivalent of std::runtime_error, but contains a stacktrace
    generated by Boost.
*/
class Exception : public std::runtime_error
{
    public:
        /**
            \brief Returns error description.

            If the backtrace was generated successfully,
            returns the message along with stack trace.
            Otherwise, behaves like std::runtime_error::what().
        */
        const char *what( ) const noexcept override
        {
            if ( has_backtrace )
                return message.c_str( );
            else
                return std::runtime_error::what( );
        }

        /**
            \brief Constructs an exception, generates a backtrace if possible.

            \param cmessage The error description.
        */
        Exception( const char *cmessage ) :
            std::runtime_error( cmessage ) // std::runtime_error will store the original message
        {
            // Attempt to generate stacktrace
            try
            {
                std::stringstream buffer;
                buffer << cmessage << std::endl << boost::stacktrace::stacktrace( );
                message = buffer.str( );
                has_backtrace = true;
            }
            catch ( std::exception &ex )
            {
                has_backtrace = false;
            }
        }

    protected:
        bool has_backtrace; //!< Determines if backtrace is present
        std::string message; //!< Contains the user message along with backtrace.
};

I can tell it works on this simple example

void foo( )
{
    throw Exception( "some message" );
}

void bar( )
{
    foo( );
}

int main( )
{
    try
    {
        bar( );
    }
    catch ( std::exception &ex )
    {
        std::cerr << ex.what( );
    }

    return 0;
}

because it generates following message:

some message
 0# Exception::Exception(char const*) in ./ex
 1# foo() in ./ex
 2# bar() in ./ex
 3# main in ./ex
 4# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 5# _start in ./ex

However, what I'd like to know is if my code isn't too complicated
as for an exception class and if it properly handles possible stack trace
generator exceptions and properly falls back to std::runtime_error functionality.

Also, is there some important property/method that all exception classes should have, that I had overlooked and forgot to implement? Maybe the whole idea of having such class is bad in general and I should use some other solution?

Other suggestions are obviously welcome too.


texts:
I have this working code. I think this must be easier with a while loop.

if not c.e1.nil?
  extrapreis = number_to_currency Extra.find(c.e1).aufschlag, :unit=>"EUR "
  array.push Extra.find(c.e1).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e1).aufschlag
end
if not c.e2.nil?
  extrapreis = number_to_currency Extra.find(c.e2).aufschlag, :unit=>"EUR "
  array.push Extra.find(c.e2).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e2).aufschlag
end
if not c.e3.nil?
  extrapreis = number_to_currency Extra.find(c.e3).aufschlag, :unit=>"EUR "
  array.push Extra.find(c.e3).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e3).aufschlag
end
if not c.e4.nil?
  extrapreis = number_to_currency Extra.find(c.e4).aufschlag, :unit=>"EUR "
  array.push Extra.find(c.e4).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e4).aufschlag
end
if not c.e5.nil?
  extrapreis = number_to_currency Extra.find(c.e5).aufschlag, :unit=>"EUR "
  array.push Extra.find(c.e5).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e5).aufschlag
end

It is always the same code, except for the variable e (1, 2, 3, 4, 5). How can I put this in a while loop and put the counter together with e?


texts: Find minimum number of coins (count and list of coins too)

texts:
For a given set of denominations, you are asked to find the minimum number of coins with which a given amount of money can be paid. Assume that you can use as many coins of a particular denomination as necessary.
For example, given the denominations 1, 3, 4, and the target amount 6,
the algorithm should find the optimal 2 coins required: 3 + 3.

As an exercise while learning Scala,
I implemented two versions.
One to find just the number of coins,
and one to find the list of coins.
I'm looking for a review of all aspects of this code.
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class FindMinCoinsTest extends FunSuite {

  def findMinCoins(amount: Int, coins: Set[Int]): Int = {
    def findMinCoins(amount: Int, count: Int): Int = {
      if (amount == 0) count
      else if (amount < 0) Integer.MAX_VALUE
      else coins.map(coin => findMinCoins(amount - coin, count + 1)).min
    }

    val count = findMinCoins(amount, 0)
    if (count == Integer.MAX_VALUE) 0
    else count
  }

  test("find 10 with 1, 5, 7") {
    assert(2 == findMinCoins(10, Set(1, 5, 7)))
  }

  test("find 10 with 1, 5, 10") {
    assert(1 == findMinCoins(10, Set(1, 5, 10)))
  }

  test("find 7 with 3, 5") {
    assert(0 == findMinCoins(7, Set(3, 5)))
  }

  test("find 6 with 1, 3, 4") {
    assert(2 == findMinCoins(6, Set(1, 3, 4)))
  }

  def findMinCoinsList(amount: Int, coins: Set[Int]): List[Int] = {
    def findMinCoinsList(amount: Int, list: List[Int]): (Boolean, List[Int]) = {
      if (amount == 0) (true, list)
      else if (amount < 0) (false, Nil)
      else {
        val solutions = coins.map(coin => findMinCoinsList(amount - coin, coin :: list)).filter(_._1)
        if (solutions.nonEmpty) solutions.minBy(_._2.size)
        else (false, Nil)
      }
    }

    findMinCoinsList(amount, Nil)._2.sorted
  }

  test("find sorted list, for 10 with 1, 5, 7") {
    assert(List(5, 5) == findMinCoinsList(10, Set(1, 5, 7)))
  }

  test("find sorted list, for 10 with 1, 5, 10") {
    assert(List(10) == findMinCoinsList(10, Set(1, 5, 10)))
  }

  test("find sorted list, for 7 with 3, 5") {
    assert(Nil == findMinCoinsList(7, Set(3, 5)))
  }

  test("find sorted list, for 6 with 1, 3, 4") {
    assert(List(3, 3) == findMinCoinsList(6, Set(1, 3, 4)))
  }

  test("find list 7 with 1, 3, 4") {
    assert(List(3, 4) == findMinCoinsList(7, Set(1, 3, 4)))
  }

}


texts: Function that returns index of Forex candle according opening hours (weekly session)

texts:
The output of the function is as desired. When Forex opens at Sunday, first candle is annotated with 1 and the number increments with every new candle, till weekend, when the imaginary counter is reset.

I am aware of those risks (it is solved elsewhere):

passed datetime must be python datetime
time must be in GMT

My concerns are about readability and optimality of the code. Any advice?

def weektag_from_time(timestamp, freq):
    """
    This function returns index of the current time in Forex session,
    according to chosen granularity.
    Forex session - Sunday 2200 to Friday 2200.
    If the session is off, it should return 0.

    Args:
        * timestamp : python datetime in GMT
        * freq : desired granularity (minute, hour, ...)

    Returns:
        * weektag : integer index in Forex session
    """
    # init
    assert freq in ["H1", "M1"], "Required granularity is not known."
    d = timestamp.weekday()
    h = timestamp.hour
    m = timestamp.minute
    # get tag
    if (d == 5) or (d == 4 and h > 21) or (d == 6 and h < 22):
        # market is closed
        weektag = 0
    else:
        # estimate week day offset in hours and add it to current day hours
        offset = (24*d)+2 if d < 6 else -22
        h += offset
        # set result according granularity
        if freq == "H1":
            weektag = h
        elif freq == "M1":
            weektag = (h*60) + m
    return weektag


texts:
The idea is to take a sequence of sequences (of the same type) and use tuples of [iterator, current index, sequence size] to keep track of the current state, such that the cartesian_product object can return one sequence at a time.
General questions:

bugs? (would hope not!)
code quality ok? anything i've missed?
is there a simpler way to keep track of the object state (iterators, counts, etc)
would it make sense to make this into an iterator (it could probably be bidirectional?)

Improvement ideas:

when the number of sequences is known at compile time, maybe it would be better for next() to return a tuple/static array instead of a std::vector<T>?
use a simple aggregate type instead of a tuple to avoid all the std::get ugliness?

Thanks a lot!
#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>

template <typename T>
class cartesian_product {
public:
    template <typename... Args, typename = typename std::enable_if<(sizeof...(Args) > 1)>::type>
    cartesian_product(Args&&... args)
        : count(1)
    {
        std::cout << "constructor 1\n";
        static_assert(std::is_arithmetic<T>::value, "T must be an arithmetic type.");
        append(args...);
    }

    cartesian_product(std::vector<std::vector<T>> const& sequences)
        : count(1)
    {
        std::cout << "constructor 2\n";
        tuples.reserve(sequences.size());
        for(auto&& s : sequences) {
            tuples.emplace_back(s.cbegin(), 0ul, s.size());
            count *= s.size();
        }
    }

    cartesian_product(std::vector<std::vector<T>>&& sequences)
        : cartesian_product(sequences)
    {
        std::cout << "constructor 3\n";
    }

    bool has_next() { return count > 0; }

    // next combination
    std::vector<T> next()
    {
        std::vector<T> res(tuples.size());
        auto s = res.rbegin();

        for (auto p = tuples.rbegin(); p < tuples.rend(); ++p, ++s) {
            *s = *std::get<0>(*p);

            if (p > tuples.rbegin()) {
                auto q = p - 1;
                if (std::get<1>(*q) == std::get<2>(*q)) {
                    std::get<0>(*q) -= std::get<2>(*q);
                    std::get<1>(*q) = 0;

                    ++std::get<0>(*p);
                    ++std::get<1>(*p);
                }
            } else {
                ++std::get<0>(*p);
                ++std::get<1>(*p);
            }
        }

        --count;
        return res;
    }

private:
    using I = typename std::vector<T>::const_iterator;
    using E = std::tuple<I, std::size_t, std::size_t>;
    std::vector<E> tuples;
    int count;

    template <typename... Args>
    void append(std::vector<T> const& vec, Args&&... args)
    {
        append(vec);
        append(args...);
    }

    void append(std::vector<T> const& vec)
    {
        count *= vec.size();
        tuples.emplace_back(std::cbegin(vec), 0ul, vec.size());
    }
};

int main(int argc, char** argv)
{
    std::vector<int> a { 1, 2 };
    std::vector<int> b { 3, 4 };
    std::vector<int> c { 5, 6 };
    std::vector<int> d { 7, 8, 9 };

    std::vector<std::vector<int>> s{ a, b, c, d };

    cartesian_product<int> p(a, b, c);
    cartesian_product<int> q(s);
    cartesian_product<int> r(std::vector<std::vector<int>>{ a, b, c, d });

    auto print = [](auto&& vec) { for (auto v : vec) std::cout << v << " "; std::cout << "\n"; };

    while (p.has_next())
        print(p.next());

    return 0;
}


texts: Read n lines, and count the lines that do not contain the string "CD"

texts:
I would like to know how to improve the execution speed of the code below.

The context : n is an integer read from the stdin, and represents the number of cases. Each case is represented by a sequence of characters (can only be uppercase alphabet letters), that are read from stdin. For each case, if the sequence doesn't contain the sub-string "CD", we add 1  to the variable wins.

Finally, we print out wins : the number of strings not containing the string "CD".

n = int(raw_input()) #number of cases
wins = 0
for i in range(n):
    if "CD" not in raw_input(): #count number of strings that doesn't contain "CD"
        wins += 1
print wins

Note: Official Python performance tips suggest using map or list comprehension instead of for loop  to speed up, but I couldn't implement those without the for loop.

What other ways to speed the execution speed, knowing that every thing read from the stdin is necessary, and that the typing speed (I use python filename.py <input.txt method) isn't an issue (I'm looking for a way pertaining to the code structure, to speed the execution itself) ?


texts:
I'm building a JSON API. I'm writing my controller tests so that they compare the response body to actual JSON I'm generating in my tests using ActiveRecord. I wrote two helper methods that make the process easier. The first simply parses the actual response body and returns it.

def json_response_body(&block)
  JSON.parse(response.body, symbolize_names: true).tap do |content|
    yield content if block_given?
  end
end

The second method returns a JSON representation of an object, and accepts options. This is what I expect the response to be. So I compare the output of this method to the actual response.

def as_parsed_json(object, options = {})
  # Converting to JSON and reparsing ensures
  # dates are in the same format as my controller responses.
  JSON.parse object.to_json(options), symbolize_names: true
end

This way, I can write my tests like this:

test "GET #show" do
  product = create(:product)
  get :show, id: product

  expected =
    as_parsed_json(product, only: [:id, :title, :price_in_cents])

  assert_equal expected, json_response_body
  assert_response :success
end

Is this a good way of testing me controllers? The part that makes me think is where I'm generating the JSON using Rails helpers instead of explicitly writing the JSON myself, or looking for keys in the response body. For example:

expected = { id: product.id, title: product.title }.to_json
# Or
assert_equal product.id, request.body[:id]

But since Rails is pretty well tested, I feel like I can trust its JSON return. I'm not sure if this approach makes my tests brittle, since any change in the response body will cause the tests to fail. But maybe that's a good thing? Here's another example:

test "POST #create with valid attributes" do
  user = create(:user)
  api_authorization_header token: user.auth_token

  post :create, product: attributes_for(:product)
  expected = as_parsed_json Product.last, json_options

  assert_equal expected, json_response_body
  assert_response :created
end

And it's controller action:

  # app/controllers/api/v1/users_controller.rb
  def create
    @user = User.new
    @user.assign_attributes permitted_attributes(@user)
    if @user.save
      render :create, status: 201, location: [:api, @user]
    else
      render json: { errors: @user.errors }, status: 422
    end
  end

I'm using Jbuilder to render the actual JSON.

# app/views/api/v1/users/create.json.jbuilder
json.(@user, :id, :name, :email, :created_at)
json.auth_token @user.auth_token


texts: Client-side validator for contact information form (name, phone, e-mail)

texts:
My recent post had some things to fix. I think this should be well structured and written for you.

How does this code look to you? If something needs to be changed please tell me.

// Gets all elements by ID's
function elem(id) {
    return document.getElementById(id);
};
//

//Check box id"RadioGroup1_0" will be checked on start up of page (Phone)
window.onload = function () {
    document.querySelector("#RadioGroup1_0").click();
    //

//Gets my Form name (form) and on submission (submit) checks the rules below...

/* first name must be greater than 0
last name must be greater than 0
email must be greater than zero and follow the email reg ex
phone must be greater than 7 but shorter than 11
*/
    var form = document.getElementById('form');
    form.onsubmit = function (e) {
        var rules = [
        ['first-name', elem('first-name').value.length > 0],
        ['last-name', elem('last-name').value.length > 0],
        ['email', elem('email').value.length > 0 && /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-z0-9]{2,4})+$/.test(elem('email').value)],
        ['phone', elem('phone').value.length > 7 && elem('phone').value.length < 11 ]

    ];

   //This is the (reqMsg) error, it follows the ID's listed above above and if there is an error it must be "inline" and if there is no error it will be "none",
        var valid = true;
        var firstFocus = null;
        for (var i = 0; i < rules.length; i++) {
            var parent = elem(rules[i][0]).parentNode;
            if (!rules[i][1]) {
                valid = false;
                parent.children[2].style.display = "inline";
                if (firstFocus == null) firstFocus = parent.children[1];
            } else {
                parent.children[2].style.display = "none";
            }

        }
          if (!valid) {
            firstFocus.focus();
            return false;
        }

        return true;
    };
};

// Using only alphabet keys NO Numeric for certain field boxes...
// First Name and Last Name
function onlyAlphabets(e) {
    try {
        if (window.event) {
            var charCode = window.event.keyCode;
        } else if (e) {
            var charCode = e.which;
        } else {
            return true;
        }
        if ((charCode == 64) ||
        (charCode == 32) ||
        (charCode >= 65 && charCode <=90) ||
        (charCode >= 97 && charCode <=122))
        return true;
        else return false;
    } catch (err) {
        alert(err.Description);
    }
}

/* isNumeric
*/

// This is for the phone field, only allowing NUMERIC numbers so no alphabets. It's referencing my above JS minimum 8 and maximum 10.

var specialKeys = new Array();
function IsNumeric(e) {
    var keyCode = e.which ? e.which : e.keyCode
    var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode === 8));
    return ret;
}


texts:
I have written this logic for logging, but is getting replication for all fields (last name, DOB,city, state, ZIP, etc). Here only validation logic is going to differ, whereas logging functionality will remain the same.
public boolean validFirstName(UserInputDetails record) {
        if (CommonUtil.isNullOrEmpty(record.getFirstName())) {
            record.setErrorCode(ErrorCodes.FIRSTNAME_NULL.getErrorCode());
            if(record.isDetailedLoggingEnabled()){
                Map<String,String> dtlLogMap = new HashMap<>(5);
                dtlLogMap.put("transId",String.valueOf(record.getTransactionId()));
                dtlLogMap.put("firstName",record.getFirstName());
                dtlLogMap.put("validationName","VALID_FIRSTNAME_CHECK");
                dtlLogMap.put("validationStatus","Errored");
                dtlLogMap.put("errorCode",record.getErrorCode());
                DetailedLogger.log(dtlLogMap);
            }
            return false;
        }

        if ( record.getFirstName().length() >=50) {
            record.setErrorCode(ErrorCodes.FIRSTNAME_INVALID_LENGTH.getErrorCode());
            if(record.isDetailedLoggingEnabled()){
                Map<String,String> dtlLogMap = new HashMap<>(6);
                dtlLogMap.put("transId",String.valueOf(record.getTransactionId()));
                dtlLogMap.put("firstName",record.getFirstName());
                dtlLogMap.put("firstNameLength",returnStringifNotNull(record.getFirstName().length()));
                dtlLogMap.put("validationName","VALID_FIRSTNAME_LENGTH_CHECK");
                dtlLogMap.put("validationStatus","Errored");
                dtlLogMap.put("errorCode",record.getErrorCode());
                DetailedLogger.log(dtlLogMap);
            }
            return false;
        }
        if(record.isDetailedLoggingEnabled()){
            Map<String,String> dtlLogMap = new HashMap<>(4);
            dtlLogMap.put("transId",String.valueOf(record.getTransactionId()));
            dtlLogMap.put("firstName",record.getFirstName());
            dtlLogMap.put("validationName","VALID_FIRSTNAME_CHECK");
            dtlLogMap.put("validationStatus","passed");
            DetailedLogger.log(dtlLogMap);
        }
        return true;
    }


texts:
A method that I'm working on in a C# project includes the following:

if (isDailyRateRequired)
{
    CalculatedDailyRate = dailyRate;
}

if (isWeeklyRateRequired)
{
    CalculatedDailyRate = weeklyRate / 7;
}

if (isMonthlyRateRequired)
{
    CalculatedDailyRate = monthlyRate / 30;
}

There has to be a cleaner implementation than this. I could compress it to one line with a set of nested ternary operators, but that would be pretty much unreadable.

Other suggestions?


texts: Return a path between graph nodes using depth-first search redo

texts:
I previously attempted to implement a Graph class which has a method that returns a path between 2 nodes using depth-first search. This is my latest attempt at this (using the feedback I got from last time).

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

class Graph:
    def __init__(self):
        self.nodes = set()

    def add_node(self, id):
        new_node = Node(id)
        self.nodes.add(new_node)
        return new_node

    def get_node(self, id):
        for node in self.nodes:
            if node.id == id:
                return node
        return None

    def dfs(self, start, end):
        stack = [start]
        parents = {}
        seen = set([start])

        while stack:
            cur_node = stack.pop()
            if cur_node is not end:
                for neighbour in cur_node.neighbours:
                    if neighbour not in seen:
                        seen.add(neighbour)
                        stack.append(neighbour)
                        parents[neighbour] = cur_node
            else:
                path = self.get_path(start, cur_node, parents)
                return path
        return None

    def get_path(self, start, end, parents):
        stack = [end]
        cur_node = end
        while cur_node is not start:
            cur_node = parents[cur_node]
            stack.append(cur_node)

        path = []
        while stack:
            cur_node = stack.pop()
            path.append(cur_node)
        return path

class Node:
    def __init__(self, id):
        self.id = id
        self.neighbours = {}

    def add_neighbour(self, to, weight):
        self.neighbours[to] = weight


texts:
I am using the bxslider jQuery plugin as a welcome banner with a overlay (see image below for illustration.)

This is however causing render block and cannot figure out how I can improve my code to eliminate the bxslider from being a render block.

My code is as follows:

(Html)

  <li style="background-image: url('<?php get_theme_url(); ?>/img/Image1.jpg');">

Header

LOREM IPSUM...

            Find Out More

  <li style="background-image: url('<?php get_theme_url(); ?>/img/Image2.jpg');">

  <li style="background-image: url('<?php get_theme_url(); ?>/img/img3.jpg');">

(CSS)

.bxslider .img-bg{width:100%;z-index:0;}
.bxslider .slide-overlay{position:absolute;top:0;left:0;right:0;bottom:0;width:100%;height:100%;z-index:1;background:rgba(35, 46, 58, .4);color:#fff;}
.v-align{overflow:auto;position:relative;top:50%;transform:perspective(1px) translateY(-50%);}
.bxslider, .bxslider li{height:100% !important;}
.bxslider li{background-color:rgb(29, 27, 27);background-repeat:no-repeat;background-position:center center;background-size:cover;}

(js)

$(document).ready(function() {
        $('.bxslider').bxSlider({
            auto: true,
            autoHover: true,
            speed: 800,
            pager: false
        });
});


texts: How to create a 'tee' command in Ruby for a Unix like pipeline?

texts:
I came across the question about creating memory-efficient Ruby pipe class with lazy evaluation. Some code is given to effectively create a pipeline of commands using lazy enumerators. I have been messing round with it and have implemented a tee command shown below. I feel like there is a better way to do it though.

class Pipe

  class Tee

    def initialize(pipe)
      @pipe = pipe
      @buffer = []
      @pipe.source = self.to_enum
    end

    def <<(item)
      @buffer << item
      # puts "Added '#{item}' to buffer: #{@buffer.inspect}"
    end

    def to_enum
      Enumerator.new do |yielder|
        item = @buffer.shift
        yielder << item if item
      end.lazy
    end

  end

  attr_writer :source

  def initialize
    @commands = []
    @source = nil
  end

  def add(command, opts = {})
    @commands << [command, opts]
    self
  end

  def run
    enum = @source

    @commands.each do |command, options|
      enum = method(command).call(enum, options)
    end

    enum.each {}

    enum
  end

  def cat(enum, options)
    Enumerator.new do |yielder|
      enum.map { |line| yielder << line } if enum

      options[:input].tap do |ios|
        ios.each { |line| yielder << line }
      end
    end.lazy
  end

  def out(enum, options)
    Enumerator.new do |yielder|
      enum.each do |line|
        puts line
        yielder << line
      end
    end.lazy
  end

  def cut(enum, options)
    Enumerator.new do |yielder|
      enum.each do |line|
        fields = line.chomp.split(%r{#{options[:delimiter]}})

        yielder << fields[options[:field]]
      end
    end.lazy
  end

  def upcase(enum, options)
    Enumerator.new do |yielder|
      enum.each do |line|
        yielder << line.upcase
      end
    end
  end

  def tee(enum, options)

    teed = Tee.new(options.fetch(:other))
    Enumerator.new do |yielder|
      enum.each do |line|
        yielder << line
        teed << line
      end
    end
  end

  def grep(enum, options)
    Enumerator.new do |yielder|
      enum.each do |line|
        yielder << line if line.match(options[:pattern])
      end
    end.lazy
  end

end

another_pipe = Pipe.new
another_pipe.add(:grep, pattern: /testing/i)
another_pipe.add(:out)

pipe = Pipe.new
pipe.add(:cat, :input => StringIO.new("testing\na new\nline"))
# pipe.add(:grep, pattern: /line/)
pipe.add(:tee, :other => another_pipe)
pipe.add(:upcase)
pipe.add(:out)
pipe.run

puts "================================================="
another_pipe.run

Here's the output:

TESTING
A NEW
LINE
=================================================
testing

Does anyone see a smarter way of doing this?


texts: Project Euler 8: Largest product in a series in Functional Programming (FP)


texts: Refactoring method in ApplicationController for Rails App

texts:
Here is a method I have in my ApplicationController, but it's "ugly" and needs some cleanup.

  def user_root_path
    return root_url unless user_signed_in?
    return admin_root_url if current_user.admin?
    return contributor_dashboard_url if current_user.athlete_contributor? && !current_user.class.name.eql?("Athlete")
    return school_admin_athletes_path if current_user.role?("School Admin")

    case current_user.class.name
    when "Athlete"
      if current_user.username.present?
        edit_vitals_athlete_profile_path
      else
        account_finalize_path
      end
    when "HighSchoolCoach"
      school_admin_athletes_path
    when "CollegeCoach"
      if current_user.sports.blank? || current_user.college_id.blank?
        account_finalize_path
      else
        search_index_path
      end
    else
      root_url
    end
  end


texts: How to avoid using exec() and eval() in Python

texts:
I wrote a script to execute a service on the Forestry TEP platform via its REST API. This service has certain input parameters, some of them are numerical values, other strings or files. The current workflow is:

There is a configuration file that has options for file and literal inputs. Each option is a dictionary, where each key is equal to one parameter of the service I want to execute. Example of such file:
file_inputs= {"cfg" : "forest_flux/FTEP_service/cfg.ini",
              "parsawen" : "forest_flux/FTEP_service/parsawen.csv",
              "weather" : "forestflux/data/fin_01/weather/weather_2004.csv"}
literal_inputs = {"version" : 3}

In the script, I read the cfg and iterate over items in these dictionaries. For each key,value pair, I use exec() to store the value in a class variable of the same name. For file inputs, I first upload the file on the platform and store the file's location on the platform in the variable.
    input_files_dict = json.loads(cfg.get("service_info", "file_inputs"))
    for key, val in input_files_dict.items():
        exec("self.{} = self.post_data('{}')".format(key, val))

    literal_inputs_dict = json.loads(cfg.get("service_info", "literal_inputs"))
    for key, val in literal_inputs_dict.items():
        exec("self.{} = '{}'".format(key, val))

I request service inputs and I try to match the service parameters with my class variables. I add it to a dictionary of parameters which I then send to the platform when executing the service.
    r2 = requests.get(url = url2, verify=False, allow_redirects=False, cookies=self.session_cookies)
    data_inputs = json.loads(r2.text)['serviceDescriptor']['dataInputs']
    for _input in data_inputs:
        value_to_set = eval("self." + _input["id"].lower())
        job_config["inputs"][_input["id"]] = [value_to_set]

This current workflow works well for me but I have strong suspicion that it is a very bad practice. I have read that using exec() and eval() is discouraged as there are security issues. However, I cannot think of a better way to achieve this functionality, i.e. to pair values in configuration with service inputs automatically. I want this script to be generic, i.e. usable for any service on the platform.
Question: How could I do this without using the problematic functions? How could using these functions be problematic in this case?
Please note that I removed a lot of code that is not related to the problem I am asking about (e.g. error handling).


texts: Checking an authentication decision in a JSON response

texts:
I've been working on this login screen logic.

It checks for the parameters in the JSON response to decide which action to follow. It works but it's kinda ugly and verbose. Any suggestions to refactor to make it look more elegant and simple?

  Alamofire.request(apiLink, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
    .responseJSON { response in
            guard response.result.error == nil else {
                print("error calling POST in /###/###/###")
                print("Error: \(response.result.error)")
                return
            }

            if let JSON = response.result.value {
                print(response.result)
                print("JSON: \(JSON)")

                if let dictionary = response.result.value as? [String: Any] {
                    if let status = dictionary["status"] as? String {
                        if status == "ok" {
                              self.performSegue(withIdentifier: "Home", sender: nil)
                        } else {
                            if let message = dictionary["message"] as? String {
                                if message == "invalid_username" {
                                    let alertMessage = UIAlertController(title: "Invalid User", message: "Please check out the user name", preferredStyle: .alert)
                                    alertMessage.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
                                    self.present(alertMessage, animated: true, completion: nil)
                                } else {
                                    if let message = dictionary["message"] as? String {
                                        if message == "incorrect_password" {
                                            let alertMessage = UIAlertController(title: "Invalid Password", message: "Please check out the password", preferredStyle: .alert)
                                            alertMessage.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
                                            self.present(alertMessage, animated: true, completion: nil)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }