texts:
I just wrote a short function to parse SO jobs XML feed and return dicts containing information about each job entry.
Now, each job entry page is visited to grab info not present in the xml feed (company logo URL, salary info, etc.) through bs4 with couple functions in the get_so_extras module.

parse_feed.py:

from datetime import datetime as dt
from xml.etree import ElementTree as etree
from get_so_extras import get_company_logo, get_so_salary
import urllib3
import json
import sys

def get_so_listings(url):
    """
    Get remote job listings from stackoverflow.com xml feed
    """

    http = urllib3.PoolManager()

    try:
        so_file = http.request("GET", url).data
    except Exception as e:
        print(e.args)
        sys.exit()

    so_root = etree.fromstring(so_file)
    items = so_root.findall("channel/item")

    # Parse SO xml feed in dict
    so_listings = []
    for e in items:
        job_dict = {
            "so_id": e.findtext("guid"),
            "title": e.findtext("title"),
            "so_url": e.findtext("link"),
            "author": e.findtext(
                """{http://www.w3.org/2005/Atom}author/{http://www.w3.org/2005/Atom}name"""
            ),
            "description": e.findtext("description"),
            "published_at": str(
                dt.strptime(
                    e.findtext("pubDate").strip(), "%a, %d %b %Y %H:%M:%S Z"
                    )
            ),
            "updated_at": str(
                dt.strptime(
                    e.findtext("{http://www.w3.org/2005/Atom}updated"),
                    "%Y-%m-%dT%H:%M:%SZ",
                    )
            ),
            "company_logo_url": get_company_logo(e.findtext("link")),
            "categories": [c.text for c in e.findall("category")],
        }

        # @TODO: get_company_logo(job_dict["so_url"])
        so_listings.append(job_dict)

    print("Jobs imported: {}".format(len(so_listings)))

    # Helper - export to json, ideally pushed to db
    with open('output1.json', 'w', encoding='utf-8') as f:
        json.dump(so_listings, f, indent=4)

    return True

And here the helper function used to grab company logo URLs from get_so_extras module.

get_so_extras.py:

from bs4 import BeautifulSoup
import requests
import time

def get_company_logo(job_url):
    """
    Get company logo from stackoverflow.com job listing page
    """

    try:
        page = requests.get(job_url)
        soup = BeautifulSoup(page.text, 'html.parser')
        logo = soup.find("div", attrs={'class': 's-avatar s-avatar__lg mr8 bg-white fl-shrink0'}).\
            img["src"]
    except Exception as e:
        print(e)
        pass

    time.sleep(5) # Be kind

    return logo

It'd be great to understand whether I made any obvious mistake or bad choice along the way.
Obviously calling get_company_logo within the XML parsing loop slows things down, what would be the best approach to get those fields?
Probably checking if we're looking at a new company/listing from db before visiting the page to scrape the logo would be more efficient.

edit: also, given job listings have pretty much similar attributes, could it make sense to create a class listing with attribute and a method to push it to db (with de-duplication logic perhaps)?

Be ruthless, thanks in advance.


texts: Spring: Creating a Mutable Common Command Object or Controller Interceptor

texts:
I'm integrating with a 3rd party vendor that has Users and Organizations in it. My tool is a user administration tool that allows us to store information in our local database about the Users and Organizations that we manage in the 3rd party vendor. So the Users and Organizations are stored in the 3rd party vendor as well as our database (we act as the middle man sort of). I'm at a crossroads with some ideas and would like to hear what others thought of the following problem and my solution.

Before I dive in, we're using Grails 2.4.4

One use case for the tool is creating a User. We create the user in the 3rd party vendor via an API call, and then we store information about that user in our database. There are many uses cases like this and there are 3 fields that are always in common between them, an API Token a Data Center ID and an Organization ID. These 3 fields are required for just about every API call we make to our 3rd party vendor and most of the Controller Actions result in an API call being made. For this reason, I had the idea to make a "Common" Command Object with these 3 fields on it that can be extended by another Command Object.

@Validateable
class CommonRequestCommand {

    String apiToken
    String dataCenterId
    String orgId

    static constraints = {

        apiToken nullable: true
        dataCenterId nullable: true
    }
}

@Validateable
class UserCreateCommand extends CommonRequestCommand {

    String email
    String firstName
    String lastName

}

There is one catch to this idea. The apiToken and dataCenterId are mutable (which I believe immutability is strongly suggested by Spring). It's possible that the apiToken and/or dataCenterId fields are supplied by the client/UI, or they might not be (orgId will always be supplied from the UI form). If they are not supplied, we query our database for them. If they do not exist in our database, then we throw an error. They almost always will NOT be supplied. To do that, I change the CommonRequestCommand to override the Getter methods and look up the API Token or Data Center ID if they are not provided

@Validateable
class CommonRequestCommand {

    private String apiToken
    private String dataCenterId
    String orgId

    public String getApiToken() {

        if(apiToken == null){
            Organization org = Organization.findById(orgId)
            if(org == null){
                throw new OrganizationException("Organization not found")
            }
            apiToken =  org.apiToken
        }
        return apiToken
    }

    public void setApiToken(String apiToken){
        this.apiToken = apiToken
    }

    public String getDatacenterId(){

        if(this.dataCenterId == null){
            Organization org = Organization.findById(orgId)
            if(org == null){
                throw new OrganizationException("Organization not found")
            }
            dataCenterId = org.dataCenterId
        }

        return dataCenterId
    }

    public void setDatacenterId(String dataCenterId){
        this.dataCenterId = dataCenterId
    }
}

My Question:
Do you think this is an appropriate design? I believe the biggest drawback to this is that the CommonRequestCommand is mutable.

Brainstorming a few other ways:

Drop the CommonRequestCommand and inheritance of command objects and instead create an Interceptor that creates a POGO CommonRequestObject and stores it in the request scope. Then in the controller, I pass both the UserCreateCommand object and the CommonRequestObject to the service layer.
Just pass the 3 fields through the params scope and don't worry about creating the CommonRequestCommand or an interceptor. Instead, every method in the service layer would have an additional 3 arguments for these fields.


texts:
Exponential backoff in the context of various networking protocols looks something like this:

  When a collision first occurs, send a “Jamming signal” to prevent further data being sent.
  Resend a frame after either 0 seconds or 51.2μs, chosen at random.
  If that fails, resend the frame after either 0s, 51.2μs, 102.4μs, or 153.6μs.
  If that still doesn't work, resend the frame after k · 51.2μs, where k is a random integer between 0 and 23 − 1.
  In general, after the cth failed attempt, resend the frame after k · 51.2μs, where k is a random integer between 0 and 2c − 1.

I've written a generator that handles this:

def exponential_backoff(k):
    num_failed = 0
    while True:
        suceeded = yield k*random.randint(0, 2**num_failed-1)
        num_failed = (num_failed + 1) if not suceeded else 0

Usage:

backoff_generator = exponential_backoff(TIME_FRAME)
try:
    send_message("super cool message")
except MessageSendFailed:
    time.sleep(backoff_generator.send(False))
else:
    backoff_generator.send(True)

Does this seem like a reasonable way to handle things? The goal was to have a simple method of getting the amount of time to wait, without having to maintain too much state in the application itself, without adding an unreasonable amount of extra processing time, and without too much kruft.


texts: Trapezoidal rule to approximate the integral of x^2

texts:
I've implemented the trapezoidal rule to compute the integral for a function \$x^2\$. I would like to see another style of the same code. It seems Matlab hates for a matrix to be expanded without specifying the size.

clear all
clc
n = 5; % number  subdivisions
a = 1.0; % lower limit
b = 2.0; % upper limit
sum = 0.0;
dx = (b-a)/(n-1); % step size

% Generate samples
for i = 1:n
    x(i) = a + (i-1)*dx;
end

% Generate function's values
for i = 1:n
    y(i) = x(i).^2;
end

% Compute area using Trapz. method
for i = 1:n
    if ( i == 1 || i == n) % for the first and last data
        sum = sum + y(i)./2;
    else
        sum = sum + y(i); % for the rest of data
    end
end
area = sum * dx;

area


texts:
In a JSP page I have a number of Span elements. Each of this span element will be floating point numbers.

All these span elements has class "format-decimal-precision":

${info.flaot_val}

I would like to display all this floating point numbers with 3 decimal point precision.

Example: 123.12867 should be displayed as 123.123

var floatFields = $('.format-decimal-precision');
    var iter = floatFields.length;
    var mDecDisplay = 3;

    while(iter--) {
        floatFields[iter].innerHTML=roundNumber($.trim(floatFields[iter].innerHTML),mDecDisplay);
    }

    function roundNumber(num, places) {
        return Math.round(num * Math.pow(10, places)) / Math.pow(10, places);
    }

Though the code is working fine, I would like to know a better program to achieve the same behavior.


texts: Performance serving static files with Rust and Hyper

texts:
This seems to be working fine, but it performance testing with wrk is poor compared to what I've come up in other languages. Shouldn't Rust excel in serving static files?

How can I make this faster?
Are there any other potential problems here?

extern crate hyper;
extern crate futures;

use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::ffi::OsStr;
use hyper::StatusCode;
use futures::future::FutureResult;
use hyper::server::{Http, Service, Request, Response};

mod api;

struct Router;
impl Service for Router {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Future = FutureResult<Response, hyper::Error>;

    fn call(&self, req: Request) -> Self::Future {
        futures::future::ok(match req.path() {
            "/json" => api::default::json(req),
            _ => static_file(req.path()),
        })
    }
}

fn main() {
    let addr = "127.0.0.1:5000".parse().unwrap();
    let server = Http::new().bind(&addr, || Ok(Router)).unwrap();
    println!("Listening on http://{} with 1 thread...", server.local_addr().unwrap());
    server.run().unwrap();
}

pub fn static_file(path: &str) -> Response {
    let mut f = match File::open("src/static".to_owned() + path) {
        Ok(f) => f,
        Err(_) => {
            return Response::new().with_status(StatusCode::NotFound)
        },
    };

    let mut data = String::new();
    match f.read_to_string(&mut data) {
        Ok(_) => {},
        Err(_) => {
            return Response::new().with_status(StatusCode::NotFound)
        },
    };

    let mut headers = hyper::header::Headers::new();
    match Path::new(&path).extension().and_then(OsStr::to_str) {
        Some(ext) => match ext {
            "html" => headers.set_raw("Content-Type", "text/html"),
            "css" => headers.set_raw("Content-Type", "text/css"),
            "js" => headers.set_raw("Content-Type", "application/javascript"),
            _ => headers.set_raw("Content-Type", "text/plain"),
        },
        None => headers.set_raw("Content-Type", "text/plain"),
    };

    Response::new()
        .with_status(StatusCode::Ok)
        .with_headers(headers)
        .with_body(data)
}


texts:
I upgrade an old MFC multi-threaded C++ project (from year 2002) to VS2017 Windows 10 x64. I rewrote the mutex sections (MFC's CMutex m_mu). I preferred, of course, to use C++11 std::mutex m_mutex and std::lock_guard<std::mutex> guard(m_mutex) but it throws an exception. I decided to add my own CLockGuard class (code below).

Example: (m_mutex is a protected MFC CMutex member of CMonitorsManager)

void CMonitorsManager::OnMonitorLoginMessageArrive
                        (CMonitorLoginMessage* pMessage)
{
    CLockGuard LockGuard(&m_mutex);

    m_MonitorId2IPMap.SetAt(pMessage->GetDeviceAddress(),
                            pMessage->GetPeerAddress());
};

LockGuard.h file:

#pragma once

#include <afxmt.h>//for CMutex

class CLockGuard
{
public:
    CLockGuard(CMutex* rMutex);
    ~CLockGuard();

    void Unlock();

protected:
    CMutex* m_pMutex = nullptr;
};

LockGuard.cpp file:

#include "stdafx.h"
#include "LockGuard.h"

CLockGuard::CLockGuard(CMutex* pMutex)
{
    pMutex->Lock();

    m_pMutex = pMutex;
}

void CLockGuard::Unlock()
{
    m_pMutex->Unlock();
    m_pMutex = nullptr;
}

CLockGuard::~CLockGuard()
{
    if (m_pMutex)
        m_pMutex->Unlock();
}


texts: Enumerate all items to find those that match a complex condition

texts:
Currently, I have a big for..loop with many if..else inside the loop. I just wonder is there any design pattern or other approach to reduce the long code inside the for..loop. Thank in advance.

foreach ($workingTimes as $hour => $minutes) {
    foreach ($minutes as $shift) {
        $isBookable = $this->isBookabe($hour, $shift);

        if(!$isBookabe) {
            continue;
        }

        $isNotEnoughEmployee = $this->checkEmployees($hours, $shift);

        if(!$isNotEnoughEmployee) {
            continue;
        }

        $isNotEnoughResources = $this->checkResources($hour, $shift);

        if(!$isBookabe) {
            continue;
        }

        $isNotEnoughRooms = $this->checkRooms($hour, $shift);

        if(!$isNotEnoughRooms) {
            continue;
        }

        $formatted = sprintf("%s-%s", $hour, $shift);
        $timetable[$formatted] = 'Bookable';
    }
}


texts: Searching for an object in a list returning boolean and referencing variable

texts:
My method searches through an list of accounts which have the property "Name".

class Accounts
{
    static internal List<Account> accounts = new List<Account>();

    static internal bool findAccount(string name, ref int account)
    {
        for (int i = 0; i < accounts.Count; i++)
        {
            if (accounts[i].Name == name)
            {
                account = i;
                return true;
            }
        }
        return false;
    }
}

The variable it is referencing is in the main form:

public partial class Lodge : Form
{
    public Lodge()
    {
        InitializeComponent();
    }

    private void btn_lodge_Click(object sender, EventArgs e)
    {
        int account = -1;
        bool found = Accounts.findAccount(tBox_wName.Text, ref account);
        if (found && account >= 0)
        {
            decimal lodge = Convert.ToDecimal(tBox_tAmou.Text);
            Accounts.accounts[account].lodge(lodge);
            lbl_stats.Text = "Successfully lodged. Balance is now: " + Accounts.accounts[account].Balance;
        }
        else
        {
            lbl_stats.Text = "Account not found.";
        }
    }

I am still learning C#, so I am still learning the most efficient ways of doing things.  This code works as it should, but I feel like the fact that I am returning a boolean and referencing the account variable seems wrong.

The program is basically lodging money to an account (simply an object containing the person's name, etc..).  So there is a static Accounts class and a non-static class 'Account' for each account.  I have made a static class because these functions are to be shared across multiple forms.

Should I remove the boolean and simply have it return the account to the account variable?  What would be the most accepted way by a more experience programmer?


texts:
In an attempt to get deeper down into Scala, I decided to make a BST using as many interesting concepts as possible in order to explore everything Scala has to offer.

Taking inspiration from this question/accepted answer, I wrote:

package bst

object BST {
  def apply[T <% Ordered[T]]() : BST[T] = new EmptyBST[T]()
}

abstract sealed class BST[T <% Ordered[T]] {
  def insert(e: T) : BST[T]
  def remove(value: T) : BST[T]
  def search(e: T) : Boolean
  def min : T
}

case class EmptyBST[T <% Ordered[T]]() extends BST[T] {
  def insert(e: T) : BST[T] = NonEmptyBST[T](EmptyBST[T](), EmptyBST[T](), e)
  def remove(value: T) : BST[T] = this
  def search(e: T) : Boolean = false
  def min : Nothing = ??? ///Uncertain of how to handle this
}

case class NonEmptyBST[T <% Ordered[T]](left: BST[T], right: BST[T], value: T) extends BST[T] {

  def min : T = this.left match {
    case EmptyBST() => this.value
    case NonEmptyBST(l, _, _) => l.min
  }

  def insert(e: T) : BST[T] = e match {
    case this.value => this
    case `e` if e > value => NonEmptyBST[T](left, right.insert(e), value)
    case _ => NonEmptyBST[T](left.insert(e), right, value)
  }

  def remove(target: T) : BST[T] = target match {
    case this.value => this match {
    case NonEmptyBST(EmptyBST(), EmptyBST(), _) => EmptyBST()
    case NonEmptyBST(EmptyBST(), r, _) => r
    case NonEmptyBST(l, EmptyBST(), _) => l
    case NonEmptyBST(l, r, _) => val min = r.min
                 NonEmptyBST(l, r.remove(min), min)
    }
    case _ if target > this.value => NonEmptyBST(left, right.remove(target), value)
    case _ => NonEmptyBST(left.remove(target), right, value)
  }

  def search(target: T) : Boolean = target match {
    case `value` => true
    case _ if value > target => left.search(target)
    case _ => right.search(target)
  }
}

I would love to hear about how I could improve this. My intention with this is to have practice using some of Scala's more powerful tools, so feel free to suggest improvements that would otherwise be unecessarily complex for something like this.

Something that I'm specifically looking for guidance on is commented as such. It is the min method from EmptyBST.


texts:
This is my first attempt at putting the conceptual knowledge I've gained about graphs into code. When searching for examples they all seem overly complicated, and searching for a tutorial or introduction leads to conceptual information. So here I am trying to code a very simple graph and this is what I have. The vertices represent cities, the edges represent paths  and their distances between cities.

I have two main questions:

Is this a graph? Am I missing anything? I think I have a decent understanding of them conceptually, so at least for a basic graph I think this suffices.
Are the pointers necessary? Is there a better way I could be implementing them? It was my understanding that an Edge is supposed to just contains pointers to vertices.

I believe the code is pretty straightforward: you have your edge, vertex, and graph classes, then main which creates one vertex per city, one pointer per vertex, and one edge per path between cities, most are one way, a couple are bi-directional. Then it just prints the contents of the graph which just prints each city and all paths from that city.

I know it's missing a remove function and I plan on making one soon. Just removing the vertex from the graph and removing any edges that lead to/from that vertex, but I just don't have the time at the moment.

#include <vector>
#include <iostream>
#include <string>

using namespace std;

class Vertex;

class Edge
{
public:
    Edge(Vertex *org, Vertex *dest, int dist)
    {
        origin = org;
        destination = dest;
        distance = dist;
    }

    Vertex* getOrigin() {return origin;}
    Vertex* getDestination() {return destination;}
    int getDistance() {return distance;}
private:
    Vertex* origin;
    Vertex* destination;
    int distance;
};

class Vertex
{
public:
    Vertex(string id)
    {
        name = id;
    }

    void addEdge(Vertex *v, int dist)
    {
        Edge newEdge(this, v, dist);
        edges.push_back(newEdge);
    }

    void printEdges()
    {
        cout << name << ":" << endl;
        for (int i = 0; i < edges.size(); i++)
        {
        Edge e = edges[i];
        cout << e.getDestination()->getName() <<
            " - " << e.getDistance() << endl;
        }
        cout << endl;
    }

    string getName() {return name;}
    vector<Edge> getEdges() {return edges;}

private:
    string name;
    vector<Edge> edges;
};

class Graph
{
public:
    Graph() {}

    void insert(Vertex *v)
    {
        vertices.push_back(v);
    }

    void printGraph()
    {
        for (int i = 0; i < vertices.size(); i++)
            vertices[i]->printEdges();
    }

private:
    vector<Vertex*> vertices;
};

int main()
{
Graph g;

Vertex v1 = Vertex("Seattle");
Vertex v2 = Vertex("Portland");
Vertex v3 = Vertex("Everett");
Vertex v4 = Vertex("Lynnwood");
Vertex v5 = Vertex("Northgate");
Vertex v6 = Vertex("Bellevue");
Vertex v7 = Vertex("Arlington");
Vertex v8 = Vertex("Bellingham");

Vertex *vp1 = &v1;
Vertex *vp2 = &v2;
Vertex *vp3 = &v3;
Vertex *vp4 = &v4;
Vertex *vp5 = &v5;
Vertex *vp6 = &v6;
Vertex *vp7 = &v7;
Vertex *vp8 = &v8;

v1.addEdge(vp2, 100);
v1.addEdge(vp6, 20);
v2.addEdge(vp1, 100);
v3.addEdge(vp1, 30);
v3.addEdge(vp4, 10);
v3.addEdge(vp7, 20);
v4.addEdge(vp5, 15);
v5.addEdge(vp1, 10);
v6.addEdge(vp1, 20);
v8.addEdge(vp7, 45);

g.insert(vp1);
g.insert(vp2);
g.insert(vp3);
g.insert(vp4);
g.insert(vp5);
g.insert(vp6);
g.insert(vp7);
g.insert(vp8);

g.printGraph();

system("PAUSE");

return 1;
}


texts: A prefix notation calculator that asks about everything step by step

texts:
I made a prefix notation calculator.

Prefix notation, aka Polish notation, is a form of notation for logic, arithmetic and algebra, like infix and postfix (reverse Polish) notation.

The expression '+ 3 4' in prefix notation is as valid as '3 + 4' in infix notation, as well as '3 4 +' in postfix notation.

The calculator asks for one value per step, and asks about everything step by step.

"""
Pfxcalc
Programmed by zyabin101
This code is hereby released into the public domain
"""

import ast

def lit_input(prompt):
    """
    Safely evaluate input. Only returns the following Python literal
    structures: strings, numbers, tuples, lists, dicts, booleans, and 'None'.

    Raises ValueError for malformed strings.
    """
    return ast.literal_eval(raw_input(prompt))

def lorr_input(prompt, result):
    inputted = raw_input(prompt)
    return result if inputted == "result" else ast.literal_eval(inputted)

# Initialization
x = None

# Print welcome message
print "Welcome to Pfxcalc. Type 'help' for more information."

# Main program loop
while True:
    # Get user input
    cmd = raw_input(">> ")
    # Process input
    if cmd == "quit":
        break
    elif cmd == "result":
        print x
    elif cmd == "help":
        helpmsg = """
        Pfxcalc is a prefix notation calculator.
        Prefix notation, aka Polish notation, is a form of notation for logic,
        arithmetic and algebra, like infix and postfix (reverse Polish)
        notation.

        The expression '+ 3 4' in prefix notation is as valid as '3 + 4' in
        infix notation, as well as '3 4 +' in postfix notation.

        Every computation starts with entering a command and the result is
        printed *and* saved in a variable that can be recalled by entering
        'result'. The variable can even be used as an argument for functions,
        using the same command.

        List of commands:
        quit - self explanatory
        result - recall the result variable
        help - print this message
        + - add two numbers or sequences
        - - subtract two numbers
        * - multiply two numbers, or a sequence by a number
        / - divide two numbers
        """
        print helpmsg
    elif cmd == "+":
        x = (lorr_input("Left side addend? ", x) +
             lorr_input("Right side addend? ", x))
        print x # Implicitly output result
    elif cmd == "-":
        x = lorr_input("Minuend? ", x) - lorr_input("Subtrahend? ", x)
        print x # Implicitly output result
    elif cmd == "*":
        x = (lorr_input("Left side factor? ", x) *
             lorr_input("Right side factor? ", x))
        print x # Implicitly output result
    elif cmd == "/":
        x = lorr_input("Dividend? ", x) / lorr_input("Divisor? ", x)
        print x # Implicitly output result
    else:
        print "Unrecognized command."

I'm interested in code style and problems the code has. What can be fixed here?


texts:
I implemented an extension for the NSManagedObjectContext that takes any CoreData class as a parameter and performs a fetch request on it.

I am new to CoreData and would very much appreciate any sort of feedback for this function

extension NSManagedObjectContext{
func fetchObjects <T: NSManagedObject>(_ entityClass:T.Type, sortBy: [NSSortDescriptor]? = nil, predicate: NSPredicate? = nil) throws -> [AnyObject]{
    var request: NSFetchRequest<NSFetchRequestResult>

    if #available(iOS 10.0, *) {
        request = entityClass.fetchRequest()
    } else {
        let entityClassName = NSStringFromClass(entityClass)
        let entityName = entityClassName.components(separatedBy: ".").last ?? entityClassName
        request = NSFetchRequest(entityName: entityName)
    }

    var fetchRequestError: Error?
    request.returnsObjectsAsFaults = false

    if let predicate = predicate {
        request.predicate = predicate
    }
    if let sortBy = sortBy {
        request.sortDescriptors = sortBy
    }

    var fetchedResult: [T]?

        do {
            fetchedResult = try self.fetch(request) as? [T]
        }
        catch let error {
            fetchRequestError = error
            //print(fetchRequestError)
        }

    guard let entityArray = fetchedResult else {
        throw fetchRequestError!
    }

    return entityArray
    }
}


texts:
Just an idea I had for a Java exercise. Cracking a password like "testing" takes at least 15 minutes, so obviously it's not as efficient as it can be. What are your thoughts? I also never worked with multithreading, so I can imagine I could be doing things better there.

public class AlgoTester implements Runnable {
    private static final char[] possibleChars = { 'a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    private static int[] arrayIndices;
    private static String testPassword = "testing";
    private static final int passwordLength = testPassword.length();
    private static boolean foundPassword = false;
    private final static int threadCount = 5;
    private static String passwordFound = "";

    public static void main(String[] args) {
        arrayIndices = new int[passwordLength];
        for (int i = 0; i < arrayIndices.length; i++) {
            arrayIndices[i] = 0;
        }
        for (int i = 0; i < threadCount; i++) {
            new Thread(new AlgoTester()).start();
        }

    }

    private synchronized static boolean advanceIndicies() {
        synchronized (arrayIndices) {
            if (foundPassword)
                return false;
            int maxValue = possibleChars.length - 1;
            for (int i = 0; i < passwordLength; i++) {
                int inverse = arrayIndices.length - i - 1;
                if (arrayIndices[inverse] == maxValue) {
                    if (inverse - 1 == -1)
                        return false;
                    arrayIndices[inverse] = 0;
                    continue;
                } else {
                    arrayIndices[inverse] = arrayIndices[inverse] + 1;
                    return true;
                }
            }
            return false;
        }
    }

    private synchronized static String genPassword() {
        synchronized (arrayIndices) {
        StringBuilder builder = new StringBuilder();
        for (int i : arrayIndices) {
            builder.append(possibleChars[i]);
        }
        String returning = builder.toString();
        System.out.println(Thread.currentThread().getName() + ": Checking: " + returning);
        return returning;
    }
    }

    private static boolean checkPassword() {
        // TODO Auto-generated method stub
        return (foundPassword = genPassword().equals(testPassword));
    }

    @Override
    public void run() {
        while (!foundPassword) {
            if (checkPassword()) {
                passwordFound = genPassword();
                System.out.println("----------------------");
                System.out.println("Found Password: " + passwordFound);
                System.out.println("----------------------");
                foundPassword = true;
            }
            if (!advanceIndicies()) {
                return;
            }
        }

    }

}


texts: Creating default parameters for a TestResultDefinition

texts:
I have a method which creates some default values in an ObservableCollection, nothing too fancy, but I'm trying to decide how to write the if statement.

private void CreateDefaultParameters()
    {
        //If there are no parameters, then create default ones.
        if (this.Parameters == null || this.Parameters.Count == 0)
        {
            this.Parameters = new ObservableCollection<TestResultDefinitionParameter>();

            this.Parameters.Add(new TestResultDefinitionParameter()
            {
                ParameterType = TestResultDefinitionParameter.ParameterTypes.Name
            });

            this.Parameters.Add(new TestResultDefinitionParameter()
            {
                ParameterType = TestResultDefinitionParameter.ParameterTypes.Axis,
                Value = "X"
            });

            //And so on.
        }
    }

The logic is essentially: If it's a new TestResultDefinition, then create default parameters, otherwise load the existing paramters from the database.

public TestResultDefinitionWithParameters(TestResultDefinition resultDefinition)
    {
        this.ResultDefinition = resultDefinition;

        //If it's a new result definition, create the default parameters.
        if (resultDefinition.ID == 0)
            CreateDefaultParameters();
        else
            RefreshParameters();
    }

The if statement could become very large, and I'm wondering if something like this would be better:

private void CreateDefaultParameters()
    {
        if (this.Parameters != null || this.Parameters.Count > 0)
            return;

        //Create parameters here

Would this help readability? Any suggestions?


texts:
i try to make an app for a mobile store

class Mobile(models.Model):
    model= models.CharField(max_length=30,unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    edited_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Storage(models.Model):
    model = models.ForeignKey(Mobile,on_delete=models.CASCADE,related_name='models')
    IMEI = models.CharField(max_length=60)
    company_name = models.CharField(max_length=50)
    quantity = models.IntegerField(default=0)
    buying_price = models.IntegerField(default=1)
    cost_price = models.IntegerField(default=1)
    odd_price = models.IntegerField(default=0)
    mul_price = models.IntegerField(default=0)
    second_hand = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    edited_at = models.DateTimeField(auto_now=True)

    def __str__(self):
       return self.IMEI

should i change it to create a new table(model) from Storage named Prices to normalizing and performance or its fine ?thanks


texts: Using the fetch to return and transform data

texts:
I am trying to get data of all users firstnames from an API using fetch. What are the limitations of doing it this way and how can I improve this? (The solution works and the firstNames variable has the desired output.)

const url = 'https://jsonplaceholder.typicode.com/users/';

function get(url) {
  return fetch(url)
    .then(response => response.json());
}

const users = function users() {
  return get(url)
    .then(data => data);
};

let firstNames;

users().then((user) => {
  firstNames = user.map(user => user.name.split(' ')[0]);
});


texts:
I created a small working autoloader based on some of the answers and ideas found on Stack Exchange (I lost the reference). However, I don't know much about PHP (I mainly know C, a bit C++ and Java). I'm trying to create a small MVC website for school project using my own templates and JavaScript as well. I mainly created this autoloader to include class files (I'm not sure if any other files can be included with autoloader too).

Can you please check this autoloader and give your insight on what can be done better and if there are any shortcomings?

It's important to know that I don't use namespaces currently because it would overcomplicate things.

<?php

    class Autoload
    {
        private $allFiles = array();

        public function __construct() {

            $this->findDir(__DIR__, $this->allFiles);
            spl_autoload_register(array($this, 'classLoader'));
        }

        private function classLoader($class) {

            if (class_exists($class, false)) {
                return true;

            } else {
                $this->includeClass($this->allFiles, $class);
                // should I return here true as well?
            }
        }

        private function findDir($currDir, &$files) {

            $dirsInCurr = glob($currDir . "/*", GLOB_ONLYDIR);
            $this->findFiles($currDir, $files);

            //recursive call
            foreach ($dirsInCurr as $dir) $this->findDir($dir, $files);
        }

        private function findFiles($dir, &$files) {

            $fPaths = glob($dir . "/*.php");
            foreach ($fPaths as $f) $files[] = $f . "\n";

        }

        private function includeClass($files, $class) {

            foreach ($files as $f) {
                if (strpos($f, strtolower($class) . ".php")) require_once trim($f);
            }
        }
    }

    $autoload = new Autoload();

?>


texts:
Puzzle Description

  Given \$N\$ numbers, \$N <= 10^5\$, count the total pairs of numbers \$(N_i, N_j)\$ that have a difference of \$K = N_i - N_j\$ where \$0 < K < 10^9\$.

  Input Format:

  1st line contains \$N\$ and \$K\$ (integers).
  2nd line contains \$N\$ numbers of the set. All the \$N\$ numbers are assured to be distinct.

  Output Format:

  One integer saying the number of pairs of numbers that have a difference \$K\$.

  Time limit is 5 seconds.

Sample Input : 5 2
               1 5 3 4 2
Sample Output: 3

First I've tried using ArrayLists and later tried using arrays.  The code is bad and does not at all follow normal conventions of Java.  But I'm not looking at that because execution time doesn't depend on it, right?

But to achieve the puzzle description I couldn't see any better logic than this:

import java.util.Scanner;

public class k_diff {

    public int process() {
        Scanner scanner = new Scanner(System.in);
        int total_nums = scanner.nextInt();
        int diff = scanner.nextInt();
        int ary_nums[] = new int[total_nums];
        for (int i = 0; i < total_nums; i++) {
            ary_nums[i] = scanner.nextInt();
        }
        int len = ary_nums.length;
        int count = 0;
        for (int j = 0; j < len - 1; j++) {
            for (int k = j + 1; k < len; k++) {
                if (Math.abs(ary_nums[j] - ary_nums[k]) == diff) {
                    count++;
                }
            }
        }
        return count;
    }

    public static void main(String args[]) {
        k_diff kdiff = new k_diff();
        System.out.println(kdiff.process());
    }
}


texts: K&R C book, Exercise 1-21: Replace tabs with spaces

texts:
I'm new to C, just started reading K&R C book, and am working through exercises. This is my solution to 1-21, and as far as I tested it works.
Anything that I'm doing wrong, or that it's not idiomatic C? What can be improved ?

  Exercise 1-21. Write a program entab that replaces strings of blanks
  by the minimum number of tabs and blanks to achieve the same spacing.
  Use the same tab stops as for detab. When either a tab or a single
  blank would suffice to reach a tab stop, which should be given
  preference?

#include <stdio.h>

#define TAB_SIZE 4

int main_entab() {
    int c;
    int character_count = 0;
    int whitespace_count = 0;
    while ((c = getchar()) != EOF) {

        if (c == ' ') {

            // A _ B _ | _ C _ _ |
            int numberOfCharsToReachTabStop = (TAB_SIZE - ((character_count + whitespace_count) % TAB_SIZE));

            whitespace_count++;

            if (numberOfCharsToReachTabStop == 1 && whitespace_count > 0) {
                putchar('\t');
                //advance count by how many whitespaces we are replacing, so next tab stop calculation is correct
                character_count = character_count + whitespace_count;
                whitespace_count = 0;
            }

        } else {
            //we encountered a non-whitespace char. Print all 'saved' whitespaces.
            while (whitespace_count > 0) {
                putchar(' ');
                whitespace_count--;
                character_count++;
            }

            //print the non-whitespace char
            character_count++;
            putchar(c);
        }
    }
}


texts: Searching string for character not in array

texts:
I have a string which I want to check for characters other than those in this list {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "i"} however this check gets run several thousand times a second.

I am therefore looking for the most efficient way of performing this check, what I have tried so far:

If Not System.Text.RegularExpressions.Regex.IsMatch(Input, "[^0-9\.i]") Then

This is equivalent to the code below which I have also tried

Imports System
Imports System.Linq

Public Module Module1

    Public Sub Main()
        Console.WriteLine(IsValidString())
    End Sub

    Private Function IsValidString() As Integer
        'Dim Input As String = "Hello World" 'This is Invalid
        'Dim Input As String = "13.4i+4" 'This is Invalid
        Dim Input As String = "13.4i" 'This is valid
        If Function()
            Dim IsValid As Boolean = True
            For Each Character In Input
                If Not {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "i"}.Contains(Character) Then
                    IsValid = False
                End If
            Next

            Return IsValid
        End Function() Then
            Return -1
        Else
            'Do some other stuff
            Return 1 '
        End If
    End Function
End Module

I am looking for optimal performance possibly at the cost of readability as I am willing to write pages on how the code works and what it does if only I can speed up the execution of my app!


texts: Is it effective to use get; set; to avoid redundant processes?

texts:
I wanted to avoid running the code HttpContext.Current.Server.MapPath every time file_path_includes is called.

Is the below an effective way of doing so?

private static string file_path_includes_;
public static string file_path_includes
{
    get
    {
        if (file_path_includes_ == null)
            file_path_includes_ = HttpContext.Current.Server.MapPath("/_includes") + @"\";
        return file_path_includes_;
    }
}

So the better implentation would be a static constructor as such:

public static string file_path_includes;

static ParentClassName()
{
    file_path_includes = HttpContext.Current.Server.MapPath("/_includes") + @"\";
}


texts: Using state transitions to filter C comments

texts:
This is my second attempt at K&R 1-23,

  Write a program to remove all comments from a C program. Don't forget
  to handle quoted strings and character constants properly. C comments
  don't nest.

I was previously packing characters into various io buffers, and someone suggested this was not a good choice. Thought I'd try something more along the lines of a state machine:

#include <stdio.h>

#define NORMAL          0
#define SINGLE_QUOTE    1
#define DOUBLE_QUOTE    2
#define SLASH           3
#define MULTI_COMMENT   4
#define INLINE_COMMENT  5
#define STAR            6

int state_from_normal(char prev_symbol, char symbol)
{
    int state = NORMAL;

    if (symbol == '\'' && prev_symbol != '\\') {
        state = SINGLE_QUOTE;
    } else if (symbol == '"') {
        state = DOUBLE_QUOTE;
    } else if (symbol == '/') {
        state = SLASH;
    }
    return state;
}

int state_from_single_quote(char prev_symbol, char symbol)
{
    int state = SINGLE_QUOTE;

    if (symbol == '\'' && prev_symbol != '\\') {
        state = NORMAL;
    }
    return state;
}

int state_from_double_quote(char prev_symbol, char symbol)
{
    int state = DOUBLE_QUOTE;

    if (symbol == '"' && prev_symbol != '\\') {
        state = NORMAL;
    }
    return state;
}

int state_from_slash(char symbol)
{
    int state = SLASH;

    if (symbol == '*') {
        state = MULTI_COMMENT;
    } else if (symbol == '/') {
        state = INLINE_COMMENT;
    } else {
        state = NORMAL;
    }
    return state;
}

int state_from_multi_comment(char symbol)
{
    int state = MULTI_COMMENT;

    if (symbol == '*') {
        state = STAR;
    }
    return state;
}

int state_from_star(char symbol)
{
    int state = STAR;

    if (symbol == '/') {
        state = NORMAL;
    } else {
        state = MULTI_COMMENT;
    }
    return state;
}

int state_from_inline_comment(char symbol)
{
    int state = INLINE_COMMENT;

    if (symbol == '\n') {
        state = NORMAL;
    }
    return state;
}

int state_from(int prev_state, char prev_symbol, char symbol)
{
    switch(prev_state) {
        case NORMAL :
            return state_from_normal(prev_symbol, symbol);
        case SINGLE_QUOTE :
            return state_from_single_quote(prev_symbol, symbol);
        case DOUBLE_QUOTE :
            return state_from_double_quote(prev_symbol, symbol);
        case SLASH :
            return state_from_slash(symbol);
        case MULTI_COMMENT :
            return state_from_multi_comment(symbol);
        case INLINE_COMMENT :
            return state_from_inline_comment(symbol);
        case STAR :
            return state_from_star(symbol);
        default :
            return -1;
    }
}

int main(void)
{
    char input;
    char symbol = '\0';
    char prev_symbol;

    int state = NORMAL;
    int prev_state;

    while ((input = getchar()) != EOF) {
        prev_symbol = symbol;
        prev_state  = state;
        symbol = input;
        state  = state_from(prev_state, prev_symbol, symbol);

        if (prev_state == SLASH && state == NORMAL) {
            putchar(prev_symbol);
        }
        if (prev_state != STAR && state < SLASH) {
            putchar(symbol);
        }
    }
}


texts:
This takes a field delimited by commas, and splits on the comma.  The newly divided information is put in another field (created at the start of the program) called lob.  Each part of the split is put in the lob field in a duplicate record of the original record from before the split.  The primary key is ID which is automatically generated.

Here is a concise example of desired behavior (many fields omitted for visual clarity):

Before running the module:

 +--------------------------------------------+
 |  ID   | App Code  |   Lines Of Business    |
 +-------+-----------+------------------------+
 |   1   |    AB23   | Value1, Value 2,Value3 |
 +------ +-----------+------------------------+
 |   2   |    XY45   |         Value 2        |
 +--------------------------------------------+

After running the module:

 +-------------------------------------------------------+
 |  ID   | App Code  |   Lines Of Business    |   lob    |
 +-------+-----------+------------------------+----------+
 |   1   |    AB23   | Value1, Value 2,Value3 |  Value1  |
 +-------+-----------+------------------------+----------+
 |   2   |    XY45   |         Value 2        |  Value 2 |
 +-------+-----------+------------------------+----------+
 |   3   |    AB23   | Value1, Value 2,Value3 |  Value 2 |
 +-------+-----------+------------------------+----------+
 |   4   |    AB23   | Value1, Value 2,Value3 |  Value3  |
 +-------------------------------------------------------+

Is there a way to accomplish this task in a more elegant or accurate way?  Efficiency is also good, but this program already runs quick enough on my data-set.

Option Explicit

Public Sub ReformatTable()

    Dim db                       As DAO.Database
    Dim rs                       As DAO.Recordset
    Dim rsADD                    As DAO.Recordset
    Dim fld                      As DAO.Field

    Dim strSQL                   As String
    Dim varData                  As Variant
    Dim i                        As Integer

    Set db = CurrentDb

    ' Add a field into the existing IIPM table called lob.
    ' Values created during the Line Of Business split will be stored here.
    Dim strDdl As String
    strDdl = "ALTER TABLE IIPM ADD COLUMN lob TEXT(255);"
    CurrentProject.Connection.Execute strDdl

    ' Select all fields that have a Line of Business and are unprocessed (lob is Null)
    strSQL = "SELECT *, lob FROM IIPM WHERE ([Lines Of Business] Is Not Null) AND ([lob] Is Null)"

    Set rsADD = db.OpenRecordset("IIPM", dbOpenDynaset, dbAppendOnly)

    Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)

    With rs
        While Not .EOF
            varData = Split(rs![Lines Of Business], ",") ' Get all comma delimited fields

            'Update First Record
            .Edit
            !lob = Trim(varData(0)) ' remove spaces before writing new fields
            .Update

            ' Add records with same first field
            ' and new fields for remaining data at end of string
            For i = 1 To UBound(varData)
                rsADD.AddNew
                For Each fld In rsADD.Fields
                    If fld.Name <> "lob" And fld.Name <> "ID" Then
                        ' Copy all fields except "lob" and "ID"
                        rsADD(fld.Name) = rs(fld.Name)
                    End If
                Next fld
                ' lob is set separately, ID is set automatically
                rsADD!lob = Trim(varData(i)) ' remove spaces before writing new fields
                rsADD.Update
            Next i

            .MoveNext
        Wend

        .Close
        rsADD.Close

    End With

    Set rsADD = Nothing
    Set rs = Nothing

    ' Remove empty rows which only contain an ID.
    CurrentProject.Connection.Execute "DELETE FROM IIPM WHERE lob IS NULL AND [App Code] IS NULL AND [Lines Of Business] IS NULL;"

    db.Close
    Set db = Nothing

End Sub


texts:
This is the way I handle an Ajax response. I am sure it can be improved.

success: function (json) {
                $.each(json, function(index,item){
                    if (item.field == "article_id") {
                        $("#article_id").val(item.value);
                    } else if (item.field == "naslov") {
                        $("#naslov").val(stripslashes(item.value));
                    }else if (item.field == "slug_naslov") {
                        $("#slug_naslov").val(item.value);
                    }else if (item.field == "datum") {
                        $("#datum").val(item.value);
                    }else if (item.field == "url") {
                        $("#url").val(item.value);
                    }else if (item.field == "tekst") {
                        $("#tekst").val(stripslashes(item.value));
                    }else if  (item.field == "tag_title") { //handle tags - tokeninput
                        var tagoviArray = item.value;
                        var tagoviInput = $("#txtTags");
                            $(tagoviInput).tokenInput("clear");
                            $.each(tagoviArray, function (index, value) {
                                var arr = value.split(',');
                                    $.each(arr, function (i, v) {
                                        if (!(v=="")) {
                                            $(tagoviInput).tokenInput("add", {id: "", name: v}); tag
                                        }
                                    });
                            });

                    }else if (item.field == "love") {
                        $("#love").val(item.value);
                    }
                });
                return false;
            }


texts: Renaming video files based on episode title lookup

texts:
I'm new to F#, so I've ported an old Python script I have to F#. It scans a directory for files named something like Game.Of.Thrones.S01E02.xvidblahblah.mp4 or The_Wire_s03e04.somethingelse.avi, and renames them to a nice form like TheWire_s03e04_Hamsterdam.avi (where Hamsterdam is the episode's title, found from a web api). I'd welcome any advice on how to make it more idiomatic or efficient.

open System.Text.RegularExpressions
open System
open System.IO
open FSharp.Data

let RegexPattern pattern input =
    let m = Regex.Match(input, pattern)
    if m.Success then Some(List.tail [for g in m.Groups -> g.Value])
    else None

let (|ShortShowCode|_|) input = RegexPattern @"(.*)[sS](\d{1,2})[^\d]?[eE](\d{1,2})" input
let (|LongShowCode|_|) input = RegexPattern @"(.*)Season ?(\d{1,2}) ?Episode ?(\d{1,2})" input

let uncamelcase phrase = Regex.Replace(phrase, @"(?=[A-Z0-9])", " ")
let compressSpaces phrase = Regex.Replace(phrase, @"[^a-zA-Z0-9]+", " ")
let trim (phrase:string) = phrase.Trim()

let prettify title = title |> uncamelcase |> compressSpaces |> trim

let compress title = Regex.Replace(title, @"\W", "")

let apiUrl showName = sprintf "http://api.tvmaze.com/singlesearch/shows?q=%s&embed=episodes" (Uri.EscapeUriString(showName))
type Shows = JsonProvider<"http://api.tvmaze.com/singlesearch/shows?q=The%20Sopranos&embed=episodes">

let extension filePath = Path.GetExtension(filePath).ToLower()
let fileNameOnly filePath = Path.GetFileName(filePath)

let rec walk dir =
    seq { yield! Directory.EnumerateFiles(dir, "*")
          for subDir in Directory.EnumerateDirectories(dir) do
              yield! walk subDir }

type VideoFileInfo (showName: string, season: int, number: int, fileName: string) =
    member this.ShowName = showName
    member this.Season = season
    member this.Number = number
    member this.FileName = fileName
    member this.Extension = extension fileName

let videoInfo vidFileName =
    match vidFileName with
    | ShortShowCode [showName; season; number]
    | LongShowCode [showName; season; number]
        -> Some <| new VideoFileInfo(prettify showName, season = Int32.Parse season, number = Int32.Parse number, fileName = vidFileName)
    | _ -> None

let episodeMatch (toMatch: VideoFileInfo) (episode: Shows.Episode) =
    (episode.Season = toMatch.Season && episode.Number = toMatch.Number)

let episodeInfo (epData: VideoFileInfo) =
    let show = epData.ShowName |> apiUrl |> Shows.Load
    show.Embedded.Episodes |> Seq.find (episodeMatch epData)

let titleImprovement vidInfo =
    let epInfo = episodeInfo vidInfo
    let newName = sprintf "%s_s%02ie%02i_%s%s" (compress vidInfo.ShowName) epInfo.Season epInfo.Number (compress epInfo.Name) vidInfo.Extension
    if vidInfo.FileName = newName then None
    else Some(vidInfo.FileName, newName)

let renameVideo (dir: string) (oldTitle: string) (newTitle: string) =
    File.Move(dir + oldTitle, dir + newTitle)
    // Prints the command to reverse this rename!
    sprintf "rename \"%s%s\" \"%s%s\"" dir newTitle dir oldTitle

let printeach list = list |> Seq.iter (printfn "%A")

let testfiledir = "C:\\Dummy\\vids\\"
let testfilenames = ["The.Sopranos.Season 5 Episode 6.mp4"; "I am not an episode.txt"; "GameOfThrones_s01e02_TheKingsroad.m4v"; "TheWire.S03E04.avi"]
let createTestFiles dir filenames = filenames |> Seq.iter (fun filename -> File.WriteAllText(dir + filename, ""))

[<EntryPoint>]
let main argv =
    createTestFiles testfiledir testfilenames
    walk testfiledir
    |> Seq.map fileNameOnly
    |> Seq.choose videoInfo
    |> Seq.choose titleImprovement
    |> Seq.map (fun (oldTitle, newTitle) -> renameVideo testfiledir oldTitle newTitle)
    |> printeach
    0


texts: Piano, output all the keys and give a scale

texts:
I've two snippets below, the first one output all the keys of a piano and the second one give me a scale when given a starting note. For those who don't know how a piano is structured here is an image of a piano.
Basically I want to put each notes, in an ordered array. As you can see the black notes have two names, one with b in it and one with #. Those two names are equivalent but I'm using the one with b.

So I have to create this array (like the image):

[ "A0", "Bb0", "B0", "C1", "Db1", "D1", "Eb1", "E1", "F1", "Gb1", "G1", "Ab1", "A1", "Bb1", "B1".............., "B7", "C8"]

Or check the console output from the jsfiddle below.

jsfiddle

const KEYS_NORMAL =  ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];

let keys = KEYS_NORMAL.slice(-3);
keys = keys.map( k => k + '0');

for(let octave = 1; octave < 8; octave++){
  for(let key of KEYS_NORMAL){
    keys.push(key + octave)
  }
}
keys.push('C8')
keys.forEach(k => console.log(k));
// I'm actually doing some work with those notes, So ultimately this is one more loop.

The second algorithm returns a scale given a note. For those who don't know a scale starts on any note and is given by the algorithm below:

Major: 2 - 2 - 1 - 2 - 2 - 2 - 1

Minor : 2 - 1 - 2 - 2 - 1 - 2 - 2

We can distinguish between major and minor because an m is appended to the name, eg: A is major whereas Am is minor.

Where 1 means go one note above, and 2 means go 2 notes above (the black keys are also notes).

Here is jsfiddle

Code :

 majorSemiTones = [2,2,1,2,2,2];
 minorSemiTones = [2,1,2,2,1,2];
 KEYS = ["A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"];
 KEYS_NORMALIZED = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];

 function getScale(scaleName){
        let tonic = scaleName.replace("m", "");
        let keys = [];
        let minor = false;
        let scaleIndex;
        let intervals = this.majorSemiTones;
        if(scaleName.indexOf("m") > -1){
            minor = true;
            intervals = this.minorSemiTones;
        }
        scaleIndex = KEYS.indexOf(tonic);// starts on the tonic
        for(let i = 0; i < 7; i++){
            keys.push(KEYS[scaleIndex]);
            if( scaleIndex + intervals[i] > KEYS.length - 1 ){
                scaleIndex = scaleIndex + intervals[i] - KEYS.length;
            }else{
                scaleIndex += intervals[i];
            }
        }
        return keys;
    }

What I hope to get from this review is ways to improve my code. The second snippet seems needlessly complex and unreadable while the first one seems inefficient and seems like it could benefit from some functional js.


texts:
I have written an implementation of a Mergesort in Python3. An Ideone with the implementation is available. Any suggestions for improvement or any criticisms?

def merge(a, aux, lo, mid, hi):
    assert isSorted(a, lo, mid)
    assert isSorted(a, mid+1, hi)

    for k in range(lo, hi+1):
        aux[k] = a[k]

    i, j = lo, mid + 1
    for k in range(lo, hi+1):
        print("i = ",i, ", j = ",j)
        if i > mid:
            a[k] = aux[j]
            j += 1
        elif j > hi:
            a[k] = aux[i]
            i += 1
        elif aux[i] < aux[j]:
            a[k] = aux[i]
            i += 1
        else:
            a[k] = aux[j]
            j += 1
    assert isSorted(a, lo, hi)

def sort(a, aux, lo, hi):
    if (lo >= hi): return a
    mid = math.floor(lo + (hi-lo) / 2)

    sort(a, aux, lo, mid)
    sort(a, aux, mid+1, hi)
    merge(a, aux, lo, mid, hi)

def merge_sort(a):
    aux = [0] * len(a)
    sort(a, aux, 0, len(a)-1)
    assert isSortedArray(a)

def isSorted(a, lo, hi):
    for i in range(lo, hi):
        if a[i+1] < a[i]:
            return False
    return True

def isSortedArray(a):
    for i in range(0, len(a)-1):
        if a[i+1] < a[i]:
            return False
    return True


texts: Is wrapping the service layer worthwhile?

texts:
I have been trying to design a good data layer that will eventually be generated. I am wondering if I have missed anything. The basic architecture contains a service class that handles connecting and eventually transactions. I wrap the IDbConnection in the service class to make sure it gets disposed properly so that the user will not need to worry about that. Are there any drawbacks to wrapping the IDbConnection in a using statement?

Sample code:

public abstract class SqlService
{
    private readonly string _connectionString;

    protected Service(string connectionString)
    {
        _connectionString = connectionString;
    }

    private IDbConnection CreateConnection()
    {
        var connection = new SqlConnection(_connectionString);
        connection.Open();

        return connection;
    }

    protected T Execute<IDbConnection, T>(Func<IDbConnection, T> query)
    {
         using(var connection = CreateConnection())
         {
             return query(connection);
         }
    }

    protected T ExecuteTransaction<T>(Func<IDbConnection, IDbTransaction, T> query, IsolationLevel level)
    {
        return Execute(c =>
                            {
                                using (var transaction = c.BeginTransaction(level))
                                {
                                    try
                                    {
                                        var result = query(c, transaction);
                                        transaction.Commit();

                                        return result;
                                    }
                                    catch (SqlException)
                                    {
                                        transaction.Rollback();

                                        throw;
                                    }
                                }
                            });
    }
}

public interface ICanGetById<TEntity, TKey>
{
    TEntity GetById(TKey id)
}

public interface IOrderService : ICanGetById<OrderDTO, int>
{
}

public sealed partial class OrderService : SqlService, IOrderService
{
    public OrderService (string connectionString) : base(connectionString) { }

    public OrderDTO GetById(int id)
    {
        var dynamicParameters = new DynamicParameters();
        dynamicParameters.Add("@Id", id);

        return Execute(c => c.Query<OrderDTO>(
                                            "usp_OrderSelect",
                                            dynamicParameters,
                                            commandType: CommandType.StoredProcedure));
    }
}


texts: Simple function to generate a list of letters

texts:
I would like get some suggestions for improvement of this function, and alert me about any dodgy practices that you find.
I have been trying to learn python for a short time now and I would like to get some pointers on writing more pythonic code before I develop bad habits.

from string import ascii_uppercase, ascii_lowercase
from random import choice

def get_letters(case, n, random = False):
    """
    A function to generate a list of letters

    PARAMETERS
    ----------------------
    case (str) - type of case, 'u' for uppercase, 'l' for lowercase
    n (int) - number of letters to return
    random (bool) - specify if letters should be in random order

    RETURNS
    ----------------------
    if case is 'u', returns a list of uppercase letters
    if case is 'l', returns a list of lowercase letters
    if random = True a list of random letters will be returned (default is false)
    """

    case = case.lower()

    if random:
            if case == 'u':
                letters = [choice(ascii_uppercase) for i in range(n)]
            else:
                if case == 'l':
                    letters= [choice(ascii_lowercase) for i in range(n)]
    else:
        if case == 'u':
            letters = [ascii_uppercase[i] for i in range(n)]
        else:
            if case == 'l':
                letters= [ascii_lowercase[i] for i in range(n)]

    return letters


texts: How do I structure my entities for easier persistence?

texts:
I am learning ORM using Hibernate by creating a movie rental application. Currently, I have the following three entities for persistence:

User
Movie
Rental (composite element for many-to-many mapping between above two)

Now, to handle the cart updates, I have the following code in a session scoped bean:

@ManagedBean
@SessionScoped
public class UserManager extends BaseBean implements Serializable
{
   ....

   private Map<Integer, Movie> cart;

   ....

   public void updateCart(Movie selectedMovie)
   {
      if (!isLoggedIn()) {
         return;
      }

      int id = selectedMovie.getMovieID();

      if (cart.containsKey(id)) {
         cart.remove(id);
      }
      else {
         cart.put(id, selectedMovie);
      }
   }
}

Now for user's purchase scenario, I need to keep track of the number of rentals per movie. So, I thought of adding that property to the Rental entity and use it as a value for the map. But, this class itself contains Movie as a property for the mapping as below:

<set name="rentals" cascade="all" lazy="true" table="USER_MOVIES">
      <key column="userRegistrationID" not-null="true"/>
      <composite-element class="Rental">
         <property name="bookingDate" column="bookingDate" type="date"/>
         <many-to-one name="movie" column="bookedMovieID" class="Movie" not-null="true"/>
      </composite-element>
</set>

So, while adding to / removing from cart, I will have to create / destroy an instance of the Rental class, which would be a bad idea. So I am thinking that I should restructure my entities.

Am I right in assuming the above? Is there a better approach for the above?

I am using the following:

JSF 2.1 + PrimeFaces
Hibernate 4.3
MySQL


texts: Calculating exponential moving averages with multiples threads

texts:
I calculate the moving averages of a specific measure. However, multiples threads can access this class in order to compute the average.

public class AvgUtils {

    /** The alpha. */
    private static final double ALPHA = 0.9;

    private double avgOldValue = 1.0;

    public synchronized double computeAvg(double pValue) {
        if (avgOldValue == 0.0d) {
            avgOldValue = pValue;
            return pValue;
        }

        double lValue = avgOldValue + ALPHA * (pValue - avgOldValue);
        avgOldValue = lValue;
        return lValue;
    }
}

In the other class, I'm obliged to create a new instance of this class in other every time to do the calculations.

Can my class be refactored or redesigned in a better way ?


texts:
The end result of this is to allow a user to log in and/or register themselves for a dice game. Please post some suggestions for improvement.

import pickle

logged_in = False

with open('users.pickle', 'rb') as a_file:
    users = pickle.load(a_file)

login_or_signup = input('do you want to login or signup? ')

# sign up (creating new account)
if login_or_signup.lower() == "signup":

    create_username = input("enter a new username: ")
    create_password = input("enter a new password (Your password cannot be the same as your username !!!!!!!): ")

    if create_password in users:
        create_password = input("password taken re-enter: ")

    users[create_username] = create_password

username = input('please enter username: ')

if username in users:
    password = input("enter password: ")
    if password == users[username]:
        print("access granted")
        logged_in = True

else:
    print("access denied")

with open("users.pickle", 'wb') as f:
    pickle.dump(users, f, pickle.HIGHEST_PROTOCOL)


texts:
Can anyone help me remove TLE (time limit exceeded) from this?

  Given integer n and array of string of length n. In each query (q of them) we are given l and r and we need to find LCP in this subsequence. Q and N <= 10^5. The sum of lengths of strings <= 10^5.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int, int> pi;
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<double> vd;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pi> vp;
typedef vector<pl> vpl;

int lcp(string a, string b){
    int sol = 0;
    for (int i = 0; i < min(b.size(), a.size()); ++i){
        if (a[i] == b[i])
            ++sol;
        else
            break;
    }

    return sol;
}

int d[10000][10000];

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cerr.tie(nullptr);

    int t;
    cin >> t;

    for (int e = 0; e < t; ++e){
        int n;
        cin >> n;

        vs s(n);
        for (auto& i : s)
            cin >> i;

        int q;
        cin >> q;

        for (int i = 0; i < q; ++i){
            int l, r;
            cin >> l >> r;
            --l; --r;

            int sol = 0;
            for (int i = l; i < r; ++i){
                for (int j = i + 1; j <= r; ++j){
                    if (!d[i][j]){
                        d[i][j] = lcp(s[i], s[j]);
                        if (d[i][j] == 0)
                            d[i][j] = -1;
                    }
                    sol = max(sol, d[i][j]);
                }
            }

            cout << sol << '\n';
        }
    }
}


texts:
I want to count the total relocations for each of these sorting algorithms. From the results it seems my code is correct, but I need someone to confirm it. Is the counter variable placed in the right position?

int bubblesort(int *p)
{
        int i,j,temp,relocations=0;
        for(i=1;i<N;i++)
                for(j=N-1;j>=i;j--)
                        if(p[j-1]>p[j])
                        {
                                temp=p[j-1];
                                p[j-1]=p[j];
                                p[j]=temp;
                                relocations++;
                        }
        return relocations;
}

int straightSelection(int *p)
{
        int k,i,min,j,relocations=0;
        for(i=0;i<N-1;i++)
        {
                k=i;
                min=p[i];
                for(j=i+1;j<N;j++)
                {
                        if(p[j]<min)
                        {
                                k=j;
                                min=p[j];
                        }
                }
                p[k]=p[i];
                p[i]=min;
                relocations++;
        }
        return relocations;
}

int straightInsertion(int *p)
{
        int x,i,j,relocations=0;
        for(i=2;i<=N;i++)
        {
                x=p[i];
                p[0]=x;
                j=i-1;
                while(x<p[j])
                {
                        p[j+1]=p[j];
                        j=j-1;
                        relocations++;
                }
                p[j+1]=x;
                relocations++;
        }
        return relocations;
}

int quicksort(int left, int right, int *p)
{
        int relocations=0;
        int i,j,mid,x,temp;

        if(left<right)
        {
                i=left;
                j=right;
                mid=(left+right)/2;
                x=p[mid];
                while(i<j)
                {
                        while(p[i]<x)
                                i++;
                        while(p[j]>x)
                                j--;
                        if(i<j)
                        {
                                if(p[i]==p[j])
                                {
                                        if(i<mid)
                                                i++;
                                        if(j>mid)
                                                j--;
                                }
                                else
                                {
                                        temp=p[i];
                                        p[i]=p[j];
                                        p[j]=temp;
                                        relocations++;
                                }
                        }
                }
                relocations += quicksort(left,j-1,p);
                relocations += quicksort(j+1,right,p);
        }
        return relocations;
}


texts: Measuring typing speed in terminal without a mistake

texts:
I tend to dislike my code. It's always a mess. I can't critique my own code though, because I just turn it into another mess. I've been programming slightly better every year, but this year it has hardly changed.

#!/bin/bash

RED='\e[101m'
NC='\033[0m' # No Color

lesson[1]="#!/bin/bash"
lesson[2]="#!/bin/bash"

lessons=${#lesson[@]}
current_lesson=1
speed=70

function start() {
        SECONDS=0 #restart timer

        reset_user_input
        string_to_type=${lesson[$1]};
        length_of_string=${#string_to_type}
        echo $string_to_type

        count=0
        while [ "$count" -ne "$length_of_string" ]; do
                checkCharacter
        done
        time_it_took=$SECONDS
        sec=60
        wpm=$((sec / time_it_took))
        wpm=$((wpm * length_of_string / 5))
        echo " "
        echo "speed: "$wpm
}

function checkCharacter() {
        IFS= read -r -s -n 1 user_input_char
        add_user_input $user_input_char

        if [ "$user_input_char" == " " ]; then
                add_user_input " "
                if [ "$user_input_char" == "${string_to_type:$count:1}" ]; then
                        printf " "
                else
                        printf ${RED}" "${NC}
                fi
        else
                if [ "$user_input_char" == "${string_to_type:$count:1}" ]; then
                        printf $user_input_char
                else
                        printf ${RED}$user_input_char${NC}
                fi
        fi
    let count+=1
}

function check_correct() {
        if [ "$user_input" == "$string_to_type" ]; then
                return;
        else
                echo "too many mistakes, try again!"
                false;
        fi
}

function check_speed() {
        if [ "$wpm" -gt speed ]; then
                return;
        else
                echo "too slow, try again!"
                false
        fi
}

function start_lesson() {
        start $1
        if check_speed && check_correct; then
                echo "you succeeded!"
                echo " " # padding for every lesson
                return;
        fi
        echo " " # padding for every lesson
        false
}

function reset_user_input() {
        user_input=""
}

function add_user_input() {
        user_input=${user_input}$1
}

while [ "$current_lesson" -le "$lessons" ]; do
        echo "lesson:" $current_lesson
        until start_lesson $current_lesson; do : ; done;
        let current_lesson+=1
done


texts: Switched from MySQL to MySQLi requires the connection parameter

texts:
I was working with really old PHP I learned years ago and decided to finally update it, so I changed all the mysql to mysqli. I noticed some MySQLi functions require you to pass the connection in the parameters. I ended doing something like this:

$con = getCon();
$result = mysqli_query($con, "SELECT * FROM sometable WHERE deleted=0");

getCon() is a return like return Database::getConnection(); that uses the next class:

class Database {
    private static $db;
    private $connection;

    private function __construct() {
        $servername = "localhost";
        $username = "...";
        $password = "...";
        $dbname = "...";

        $this->connection = new mysqli($servername, $username, $password, $dbname);
    }

    function __destruct() {
        $this->connection->close();
    }

    public static function getConnection() {
        if(self::$db == null) {
            self::$db=new Database();
        }

        return self::$db->connection;
    }
}

I don't like adding the line $con = getCon(); to the top of every function that uses mysqli_query. Is there a way to avoid this? (it is one extra line multiplied by every function that uses mysqli calls)


texts: Hash and check passwords in node.js using the native pbkdf2

texts:
I use the native crypto . I use the pbkdf2 and the randomBytes for salting, and the timingSafeEqual to check for the password validity when logging in.

I wrote the following functions, based on various examples and the aforementioned APIs and functions. Here is my code

(stack : node 8.11.1 + express 4.16.3 + PostgreSQL 10)

const crypto = require('crypto');

var config = {
  hashBytes: 32,
  saltBytes: 16,
  iterations: 10000,
  digest : 'SHA512'
};

const  hashPassword = (password) =>{
  return new Promise((resolved, rejeted)=>{
    crypto.randomBytes(config.saltBytes, (err, salt) =>{
      if (err){return rejeted('Error while sign in');}
      salt = salt.toString('hex');
      crypto.pbkdf2(password, salt, config.iterations, config.hashBytes, config.digest,(err, hash) =>{
        if (err) {return rejeted('Error while sign in');}
        hash = hash.toString('hex');
        const combined = [salt, hash, config.iterations, config.hashBytes, config.digest].join('$');
        resolved(combined);
      });//closes pbkdf2
    });//closes randomBytes
  })//closes Promise
}//closes hashPassword

const  verifyPassword = (password,original) =>{
  return new Promise((resolved, rejeted)=>{
    let hash = original.split('$')[1];
    let salt = original.split('$')[0];
    let iterations = Number(original.split('$')[2]);
    let hashBytes = Number(original.split('$')[3]);
    let digest = original.split('$')[4];
    hash = Buffer.from(hash, 'hex');

    crypto.pbkdf2(password, salt, iterations, hashBytes, digest, (err, verify) =>{
      if (err){return rejeted('Error while logging in');}
      let equals = crypto.timingSafeEqual(hash, verify);
      resolved(equals);
    });
  })//closes Promise
}//closes verifyPassword

exports.hashPassword = hashPassword;
exports.verifyPassword = verifyPassword;

This works, but, here is what bothers me :

Is it ok if I save the combined from the hashPassword as text in
the DB? (column type text)
I have to convert from text back in Buffer in the verifyPassword
-- hash = Buffer.from(hash, 'hex'); part (that's because timingSafeEqual only accepts buffer). Is this ok? Does it take a lot of time?
Is using text ok, or should I use and save buffer for this?

Any suggestions? Thank you


texts: Add a number to a number to be prime number in python

texts:
The program is to get the nearest prime number to a number while adding a number. I solved the problem but I wish to optimize the code.
import time
def isprime(a ,d):
    b=a
    c=0
    f=b**(0.5)
    for i in range(1,int(f)+1):
        if a%i==0 and c<=1:
            c+=1
    if c==1:
        return d.append(b)
    else:
        b=a+1
        isprime(b,d)

start=time.time()
b=[89, 54,36, 74, 44, 19, 12]   # Input
d=[]
for i in b:
    isprime(i,d)     #function call
print(d)             #output is [89, 59, 37, 79, 47, 19, 13]
stop=time.time()
print(stop-start)    #0.0001347064971923828 Seconds

Help with Code optimization. I'm just a beginner I know code is of lower. Help to learn bit of coding.


texts:
I created a console-based TicTacToe game in Python. So far, everything works as expected. I decided to keep the class static, because I figured there would be no use for multiple game states at once. Is there anything I can improve on?
class TicTacToe:
    """Plays a 2-player TicTacToe Game."""

    __curr_player = False  # simple bool player switch
    __game_matrix = [  # representation of game state
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
    ]

    @classmethod
    def play(cls):
        """Play a single round."""
        while not cls.__game_finished():

            # set current player
            player = 2 if cls.__curr_player else 1

            # get player move
            while 1:
                try:
                    print(f"Player {player}'s turn.")
                    x = int(input("X: "))
                    y = int(input("Y: "))
                    if cls.__is_valid_field(x, y):
                        break
                    else:
                        print("Invalid field.")
                except ValueError:
                    print("Invalid Input.")

            cls.__update(x, y, player)
            print("Current game state: ")
            cls.__display()

            # change player
            cls.__curr_player = not cls.__curr_player

        print("Game finished: ")
        cls.__display()

        # reset state
        cls.__reset()

    @classmethod
    def __game_finished(cls):
        """Returns True if one player has won or all fields are filled."""
        # all filled?
        if all([value for line in cls.__game_matrix for value in line]):
            return True
        # horizontal win?
        if any(all([x == line[0] and x for x in line]) for line in cls.__game_matrix):
            return True
        # vertical win?
        if any(all([line[column] == cls.__game_matrix[0][column] and line[column] for line in cls.__game_matrix]) for column in range(3)):
            return True
        # diagonal win?
        if (cls.__game_matrix[0][0] == cls.__game_matrix[1][1] == cls.__game_matrix[2][2] != 0) or \
           (cls.__game_matrix[0][2] == cls.__game_matrix[1][1] == cls.__game_matrix[2][0] != 0):
            return True
        return False

    @classmethod
    def __is_valid_field(cls, x, y):
        """Checks if field is already filled or out of range."""
        if x > 3 or x < 1 or y > 3 or y < 1:
            return False
        return not cls.__game_matrix[y - 1][x - 1]

    @classmethod
    def __update(cls, x, y, player):
        """Update game state."""
        cls.__game_matrix[y - 1][x - 1] = player

    @classmethod
    def __display(cls):
        """Displays current game state."""
        for line in cls.__game_matrix:
            print(line)

    @classmethod
    def __reset(cls):
        """Reset game state."""
        cls.__curr_player = False
        cls.__game_matrix = [
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
        ]

def main():
    TicTacToe.play()

if __name__ == "__main__":
    main()


texts: HackerRank - Array Manipulation - Follow-up

texts:
This is a follow-up question for HackerRank - Array Manipulation

  Problem

  You are given a list (1-indexed) of size \$n\$, initialized with zeroes.
  You have to perform \$m\$ operations on the list and output the maximum of
  final values of all the  elements in the list. For every operation,
  you are given three integers \$a\$, \$b\$ and \$k\$ and you have to add value
  \$k\$ to all the elements ranging from index \$a\$ to \$b\$ (both inclusive).

  Example input

5 3
1 2 100
2 5 100
3 4 100

  Expected output

200

  Explanation

  After first update list will be:

100 100 0 0 0

  After second update list will be:

100 200 100 100 100

  After third update list will be:

100 200 200 200 100

  So the required answer will be: 200

Final solution

I changed the way of storing the values, which now get indexed into a map. I think now it's efficient in time and space, my main questions left are about style (taking into account the impositions of the hacker rank input output).

#include <algorithm>
#include <iostream>
#include <map>

int main() {
    int n; int m;
    std::cin >> n >> m;
    using val_type = long long;
    std::map<int,val_type> map;
    while(m--){
        val_type start, end, val;
        std::cin >> start >> end >> val;
        map[start] += val;
        map[end+1] -= val;
    }
    val_type max{0};
    val_type partial_sum{0};
    for (const auto& el : map) {
        partial_sum += el.second;
        if (partial_sum > max) {
            max = partial_sum;
        }
    }
    std::cout << max;
    return 0;
}

I don't like for example that I need to declare the variable partial_sum outside the for loop, being in the same scope as max. Any idea on how to write this partial sum to find the max cleaner?


texts: Trait for specifying a type parameter for Into::into

texts:
There are occasionally times when it would be nice to be able to specify a type parameter for Into::into.

This doesn't happen very often—mostly just when you have a long-ish chain of method calls where the object type is changing. In that case, wrapping one part of the chain with T::from, or splitting it into multiple statements so you can specify the type in the variable binding would be kind of awkward.

I put together the following trait:

pub trait TypedInto {
    fn typed_into<T>(self) -> T where Self: Into<T> { self.into() }
}

impl<T> TypedInto for T {}

And I can now specify the type for into:

let clip = clips::table.find(id).first::<db::Clip>(&*conn)?
    .typed_into::<models::Clip>()
    .with_associations(&*conn)?;

Am I going to regret using this? This is in the context of an application rather than a library, so I don't necessarily need to worry about anyone other than myself reading it. Is this a bad habit? Should I just be more verbose?


texts:
I have created an auto-typer that runs through a simple little GUI.This was my first ever Java program so it's pretty simple and not anything special, but I'm curious to know if there's anything that I could have done better.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class AutoTyper{

    private static int interval;
    private static Timer timerMain;
    private static JTextField txtSpam;
    private static JTextField txtInterval;
    private static JButton btnStart;
    private static JButton btnStop;

    public static void main(String[]args){
        ActionListener taskSpam = new ActionListener(){
            public void actionPerformed(ActionEvent evt) {
                sendkeys(txtSpam.getText());
              }
        };
        ActionListener taskStartTimer = new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                timerMain.setDelay(Integer.parseInt(txtInterval.getText()));
                timerMain.start();
                btnStart.setEnabled(false);
                btnStop.setEnabled(true);
                txtInterval.setEnabled(false);
            }
        };
        ActionListener taskStopTimer = new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                timerMain.stop();
                btnStart.setEnabled(true);
                btnStop.setEnabled(false);
                txtInterval.setEnabled(true);
            }
        };

        btnStart = new JButton("Start Spam");
        btnStop = new JButton("Stop Spam");
        btnStart.setBackground(Color.BLACK);
        btnStart.setForeground(Color.GREEN);
        btnStop.setBackground(Color.BLACK);
        btnStop.setForeground(Color.GREEN);
        JLabel lbl1 = new JLabel("Text to Spam");
        JLabel lbl2 = new JLabel("Interval:");
        timerMain = new Timer(1,taskSpam);
        txtSpam = new JTextField("", 13);
        txtSpam.setBackground(Color.BLACK);
        txtSpam.setForeground(Color.GREEN);
        txtInterval = new JTextField("3000",3);
        txtInterval.setBackground(Color.BLACK);
        txtInterval.setForeground(Color.GREEN);

        btnStart.addActionListener(taskStartTimer);
        btnStop.addActionListener(taskStopTimer);
        btnStop.setEnabled(false);

        JPanel intervalpane = new JPanel();
        intervalpane.add(lbl2,BorderLayout.EAST);
        intervalpane.add(txtInterval,BorderLayout.WEST);

        JPanel bottompane = new JPanel();
        bottompane.add(btnStart,BorderLayout.EAST);
        bottompane.add(btnStop,BorderLayout.CENTER);
        bottompane.add(intervalpane,BorderLayout.WEST);

        JPanel toppane = new JPanel();
        toppane.add(lbl1,BorderLayout.EAST);
        toppane.add(txtSpam,BorderLayout.NORTH);

        JPanel pane = new JPanel(new BorderLayout());
        pane.add(toppane,BorderLayout.NORTH);
        pane.add(bottompane,BorderLayout.SOUTH);

        JFrame frame = new JFrame("Auto Typer");
        frame.setForeground(Color.BLACK);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(pane);
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
      }

    private static void sendkeys(String text) {
        try {
            Robot robot = new Robot();
            text = text.toUpperCase();
            for(int i = 0; i < text.length(); i++)
                robot.keyPress(text.charAt(i));
        robot.keyPress(KeyEvent.VK_ENTER);
        }catch(java.awt.AWTException exc) {
            System.out.println("error");
        }
    }
}


texts:
I just coded this formatter to format timestamps in javascript (I tied it to underscore for convenience), any remark?

_.toDate = function(epoch, format, locale) {
    var date = new Date(epoch),
        format = format || 'dd/mm/YY',
        locale = locale || 'en'
        dow = {};

    dow.en = [
        'Sunday',
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday'
    ];

    var formatted = format
        .replace('D', dow[locale][date.getDay()])
        .replace('dd', ("0" + date.getDate()).slice(-2))
        .replace('mm', ("0" + (date.getMonth() + 1)).slice(-2))
        .replace('yyyy', date.getFullYear())
        .replace('yy', (''+date.getFullYear()).slice(-2))
        .replace('hh', date.getHours())
        .replace('mn', date.getMinutes());

    return formatted;
}

usage

_.toDate($.now(), "dd-mm-yy at hh:mn");
// Will output:
"27-03-13 at 17:20"


texts: Avoid explicitly writing base class state in a derived class. Suggestions for my method

texts:
I have two classes one base Foo class and one derived Bar class.

Each class has its own associated settings class that can create a new instance from the Load method.  This way all derived class settings can be stored in one list of FooSettings.

public abstract class FooSettings
{
    public int a;
    public int b;
    public float c;

    public abstract Foo Load();
}

public class BarSettings : FooSettings
{
    public float d;

    public override Foo Load()
    {
        return new Bar(this);
    }
}

The classes themselves have their settings as an argument for the constructor and are created from their associated settings class (null = default settings class state)

public abstract class Foo
{
    private int a = 0;
    private int b = 1;
    private float c = 1.2f;

    public Foo() { }

    public abstract FooSettings WriteSettings();

    protected void WriteBaseFooSettings(ref FooSettings settings)
    {
        settings.a = a;
        settings.b = b;
        settings.c = c;
    }

    public int A
    {
        get { return a; }
        set { a = value; }
    }

    public int B
    {
        get { return b; }
        set { c = value; }
    }

    public float C
    {
        get { return c; }
        set { c = value; }
    }
}

public class Bar : Foo
{
    float d = 0.9f;

    public Bar()
        : base() { }

    // METHOD A
    public override BaseFooSettings WriteSettings()
    {
        DerivedBarSettings settings = new DerivedBarSettings();

        settings.a = A;
        settings.b = B;
        settings.c = C;
        settings.d = d;

        return settings;
    }

    // METHOD B
    public override FooSettings WriteSettings()
    {
        var settings = new BarSettings();

        // Write base settings
        var baseSettings = settings as FooSettings;
        WriteBaseFooSettings(ref baseSettings);

        // Write derived/local settings
        settings.d = d;

        return settings;
    }
}

The problem with this setup is that I found it somewhat wasteful to have to rewrite the base class settings in the derived class method each time I wrote the derived class settings (METHOD A).

In order to get around this problem I went with METHOD B but I am not certain as to whether this is a good solution.  Some advice on improving METHOD B or a better alternative would be welcome.


texts:
I'm simple looking for what the general preference is between the below options:

anon function directly to variable

middleware.customer = function(req, res, next){
    req.customer = function(){
        var customer = false;
        if(req.method == "POST") customer = req.body;
        if(req.method == "GET") customer = req.query;
        return customer;
    }();
    return next();
}

raw build variable up

middleware.customer = function(req, res, next){
    req.customer = false;
    if(req.method == "POST") req.customer = req.body;
    if(req.method == "GET") req.customer = req.query;
    return next();
}

complete separation

var customer = function(req){
    var customer = false;
    if(req.method == "POST") customer = req.body;
    if(req.method == "GET") customer = req.query;
    return customer;
}

middleware.customer = function(req, res, next){
    req.customer = customer(req);
    return next();
}


texts: String 'expanding' - reinserting repeating characters

texts:
The challenge: Given a String, for each digit in that original string, replace that digit with that many occurrences of the character following it. So a3tx2z yields attttxzzz.

My Solution:

import java.util.Scanner;

public class Standford1 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter string to blowup: ");
        String userInput = input.nextLine();
        System.out.println(blowup(userInput));
    }

    public static String blowup(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (!isNumeric(str.substring(i, i + 1))) {
                sb.append(str.charAt(i));
            }
            else {
                sb.append(lengthen(str.charAt(i + 1),
                    Integer.parseInt(str.substring(i, i + 1))));
            }
        }
        return sb.toString();
    }

    public static boolean isNumeric(String str) {
        try {
            int num = Integer.parseInt(str);
        }
        catch(NumberFormatException nfe) {
            return false;
        }
        return true;
    }

    public static String lengthen(char c, int i){
        if (i == 0 || c == ' ') { return ""; }
        int count = 0;
        StringBuilder sb = new StringBuilder(c);
        while (count != i) {
            sb.append(c);
            count++;
        }
        return sb.toString();
    }
}

Could this be more readable? I alternate a lot between char and string (it seems optimal, am I wrong?), but should I just stick with one? Any and all feedback/suggested revisions/general optimizations welcomed with gratitude.

Edit: Stay within the specifications of the challenge. In the case of a number following a number this code is WAI i.e. the correct yield of blowup("a231") results in "a33111."

Edit 2: End digits just get ignored, since they have nothing to repeat, i.e. blowup("a2x3") would yield "axxx" - I realize I overlooked this case due to a question below, I have now amended this, but left the original question and code intact.

Edit 3: These should all be true:

/* Two plain cases */
System.out.println("Test 1: " + "xxaaaabb".equals(blowup("xx3abb")));
System.out.println("Test 2: " + "xxxZZZZ".equals(blowup("2x3Z")));
/* digit at the end */
System.out.println("Test 3: " + "axxx".equals(blowup("a2x3")));
/* Adjacent digits */
System.out.println("Test 4: " + "a33111".equals(blowup("a231")));
/* Digit include 0 */
System.out.println("Test 5: " + "aabb".equals(blowup("aa0bb")));
/* Unusual Characters */
System.out.println("Test 6: " + "AB&&,- ab".equals(blowup("AB&&,- ab")));
/* Empty String */
System.out.println("Test 7: " + "".equals(blowup("")));
/* Only digits */
System.out.println("Test 8: " + "".equals(blowup("2")));
System.out.println("Test 9: " + "33".equals(blowup("23")));

Note: So this isn't incorrectly perceived as a 'do this for me' question, as stated in edit 2,  I've already accounted for all cases.


texts:
I've execute this code in Android for inserting 100+ rows in SQLite database.
My current approach takes more time to initialize the database.

private void getInitialization() {
    try {
        dao = new IdentifyImageDao(MainActivity.this);
        dao.open();
        level = new Level();

        for (int i = 0; i < Level.LEVEL_NO_ARRAY.length; i++) {

            level.setLevelNo(Level.LEVEL_NO_ARRAY[i]);
            level.setTotalGuess(0);
            level.setTotalImages(Level.TOTAL_IMAGES_PER_LEVEL[i]);
            if (i < 2)
                level.setLevelStatus(Level.LEVEL_UNLOCK);
            else
                level.setLevelStatus(Level.LEVEL_LOCK);
            dao.insertLevel(level);
        }

        images = new Images();
        // IMAGES_ID.length = 150
        for ( int i = 0; i < Images.IMAGES_ID.length; i++ ) {
            images.setLogoId(Images.IMAGES_ID[i]);
            images.setLogoCheck(Images.IMAGE_UNCHECK);
            dao.insertImages(images);
        }
        dao.close();
    } catch (Exception e) {

    }
}

Database method for image insertion

public long insertImages(Images images) throws SQLException {
    ContentValues value = new ContentValues();
    value.put(LOGO_NO, images.getLogoId());
    value.put(LOGO_CHEECK, images.getLogoCheck());
    return database.insert(TABLE_LOGO_MASTER, null, value);
}

Please review my code and suggest a more efficient and faster approach for inserting multiple data.


texts: Counting consecutive streaks in random numbers

texts:
I heard that when you toss a die often enough, you could get the value "one" a million times in a row.

I am a beginner in Python 3 and I tried to write a little program that generates 1 or 2 randomly and counts how often the value "one" has occured successively and how big this count could get.

You can also print out the program run or write it to a file to understand the result.

I would like to know if there are possibilities to improve the code quality by using tricks and mechanisms that Python offers to me or if I can reduce something / make something better in general.

from random import randint
import os.path

iterations = int(input("number of iterations: "))
file_with_details = input("create a log file? (y/n): ")
details = input("printing out details about the program run? (y/n): ")
log_file = "is not existing"

# generate folder and log file for program run information
if file_with_details == "y":
    if not os.path.isdir("./logs"):
        os.mkdir("./logs")
    file_number = 1
    file_name = "./logs/log" + str(file_number) + ".txt"
    while os.path.isfile(file_name):
        file_number += 1
        file_name = "./logs/log" + str(file_number) + ".txt"
    log_file = open(file_name, "w")

# start of random experiment
biggest_succession = 0
actual_succession = 0
random_number_before = 0

for i in range(iterations):
    random_number = randint(1, 2)
    if details == "y":
        print("generated number:", random_number)
    if file_with_details == "y":
        log_file.write("generated number:" + str(random_number) + "\n")

    if random_number == 1 and random_number_before == 1:
        actual_succession += 1
        if details == "y":
            print("actual succession:", actual_succession)
        if file_with_details == "y":
            log_file.write("actual_succession:" + str(actual_succession) + "\n")
    else:
        if actual_succession > biggest_succession:
            biggest_succession = actual_succession
            if details == "y":
                print("biggest succession has changed:", biggest_succession)
            if file_with_details == "y":
                log_file.write("biggest succession has changed:" + str(biggest_succession) + "\n")
        actual_succession = 0
    random_number_before = random_number

print("the number one was generated", biggest_succession, "times behind each other")
if file_with_details == "y":
    log_file.write("the number one was generated " + str(biggest_succession + 1) + " times behind each other")
    log_file.close()


texts: What is the best way to refactor out “temporal dependence” of instance methods?

texts:
For example, suppose in a view class we need to instantiate some UI components and then populate the fields. Something like:

var View = function() {
  this._initUI();
  this._populateFields();
};

View.prototype = {
  _initUI: function() {
    this.textField = new TextField();
    this.comboBox = new Combobox();
  },

  _populateFields: function() {
    this.textField.setText('foo');
    this.comboBox.setVal('bar');
  }
};

This doesn't quite smell right, as you must call _initUI before _populateFields, and it's pretty hidden that _initUI will be creating some instance variables that will later be used by _populateFields.

What's your opinion of a better way of doing this?