texts:
Suppose we have variables, num and let, that may be (possibly nested) list, tuple, or None. The combination is to be such that:

Neither == None -> num + let
num == None -> let
let == None -> num
Both == None -> None
Return type is list or None
1-5 should hold for any number of variables, including one, and >2
Be a one-liner (one statement)

My approach, with test:

def join(_vars):
    return [x for v in _vars if v for x in v] or None

num = ((1, 2), None, [1, (2, 3)], None)
let = (('a', 'b'), ['a', ('b', 'c')], None, None)
vars_all = (let, num)

for i, _vars in enumerate(zip(*vars_all)):
    print(f"Case {i + 1}:", join(_vars))

Case 1: ['a', 'b', 1, 2]
Case 2: ['a', ('b', 'c')]
Case 3: [1, (2, 3)]
Case 4: None

Any better way to accomplish this? E.g. shorter, or more readable, or more intuitive than nested comprehensions.

(For readability I'd opt for less abstract naming: [x for var in _vars if bool(var) for x in var]. Parentheses should also help, though unsure if can insert without changing results.)


texts: Setting the implementation of an abstract class based on settings in config file using smart pointers

texts:
I want to choose the implementation of an abstract class based on settings from a config file. Is this the proper way of doing that?

I am asking because I am having doubts about using std::make_unique inside  the if scope. Will the object created with std::make_unique still be valid outside of the if scope?

#include <iostream>
#include <memory>

// Base class for all position systems
class PositionSystem {
public:
    virtual int getX() const = 0;
};

// GPS implementation
class GPS: public PositionSystem {
public:
    int getX() const {return 42;};
};

// Galileo implementation
class Galileo: public PositionSystem {
public:
    int getX() const {return 21;};
};

int main(){
    // Settings are read from config file
    // and stored in a smiliar struct
    struct {std::string position_system = "Galileo";} settings;

    // Declare position system
    std::unique_ptr<PositionSystem> ps;

    // Choose implementation based on settings
    if(settings.position_system == "GPS"){
        ps = std::make_unique<GPS>(GPS());
    }
    else if (settings.position_system == "Galileo"){
        ps = std::make_unique<Galileo>(Galileo());
    }

    // Use interface
    std::cout << ps->getX() << '\n';

    return 0;
}


texts:
I have this very short program for dealing with thread-safety of C's rand. Is it a correct implementation?

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    pthread_mutex_t mutex;
} thread_safe_rand;

void thread_safe_rand_init(thread_safe_rand* tsr)
{
    if (tsr)
    {
        pthread_mutex_init(&tsr->mutex, NULL);
    }
}

void thread_safe_rand_free(thread_safe_rand* tsr)
{
    if (tsr)
    {
        pthread_mutex_destroy(&tsr->mutex);
    }
}

int thread_safe_rand_get(thread_safe_rand* tsr)
{
    int ret;

    if (tsr)
    {
        pthread_mutex_lock(&tsr->mutex);
        ret = rand();
        pthread_mutex_unlock(&tsr->mutex);
        return ret;
    }
    else
    {
        abort();
    }
}

int main() {
    srand(10);
    thread_safe_rand tsr;
    thread_safe_rand_init(&tsr);
    printf("%d\n", thread_safe_rand_get(&tsr));
    thread_safe_rand_free(&tsr);
}


texts: Make HTML/Javascript Geolocation function more linear

texts:
I'm checking users locations with HTML Geolocation before unlocking the front door.  Geolocation takes a few seconds in addition to the time it takes the user to approve it, so currently I have a callback for what to do next.

function getLocationWithCallbacks(callback, error_callback) {
  navigator.geolocation.getCurrentPosition(
      function (position) {
        let location = { "latitude": position.coords.latitude, "longitude": position.coords.longitude };
        callback(location);
      },
      function (error) {
        if (error.code === error.PERMISSION_DENIED)
          error_callback()
      }
  )
}

And I call this function like so..

getLocationWithCallbacks(unlock_request, get_location_denied);

However, I'm not sure if there's a more logical way than this.  It would be nice if events happened in a more linear fashion like ("pseudo code")...

function getLocation() {
  navigator.geolocation.getCurrentPosition(
   function(position) { return ['success', position] },
   function(error) { return ['failure', error] }
}

And invoke it with...

let response = getLocation();
response[0] === 'success' ? unlock_request(response[1]) : get_location_denied(response[1])

However I believe this would involve adding promises and await statements which might make the original callback method more desirable.

I'm just not sure what's the cleanest, most logical way of implementing a getLocation function?


texts: From Q to compiler in less than 30 seconds

texts:
(See the newer version here:  CodeReview question markdown downloader)

As an adjunct to From new Q to compiler in 30 seconds, I've created a Python script to automatically download the markdown from any question on Code Review and save it to a local file using Unix-style line endings.

For instance, to fetch the markdown for this question, one could write:

python fetchQ.py 124479 fetchquestion.md

I'm interested in a general review including style, error handling or any other thing that could be improved.

fetchQ.py

""" Code Review question fetcher.  Given the number of the question, uses
the StackExchange API version 2.2 to fetch the markdown of the question and
write it to a local file with the name given as the second argument. """
import sys
import urllib
import StringIO
import gzip
import json
import HTMLParser

def make_URL(qnumber):
    return 'https://api.stackexchange.com/2.2/questions/'+str(qnumber)+'/?order=desc&sort=activity&site=codereview&filter=!)5IYc5cM9scVj-ftqnOnMD(3TmXe'

def fetch_compressed_data(url):
    compressed = urllib.urlopen(url).read()
    stream = StringIO.StringIO(compressed)
    data = gzip.GzipFile(fileobj=stream).read()
    return data

def fetch_question_markdown(qnumber):
    url = make_URL(qnumber)
    try:
        data = fetch_compressed_data(url)
    except IOError as (err):
        print "Error: {0}: while fetching data from {1}".format(err, url)
        sys.exit()
    try:
        m = json.loads(data)
    except ValueError as (err):
        print "Error: {0}".format(err)
        sys.exit()
    try:
        body = m['items'][0]['body_markdown']
    except KeyError:
        print "Error: item list was empty; bad question number?"
        sys.exit()
    except IndexError:
        print "Error: response does not contain markdown; bad question number?"
        sys.exit()
    h = HTMLParser.HTMLParser()
    md = h.unescape(body)
    return md

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Usage: fetchQ questionnumber mdfilename')
        sys.exit()
    qnumber, qname = sys.argv[1:3]

    md = fetch_question_markdown(qnumber)
    with open(qname, 'wb') as f:
            f.write(md.encode('utf-8').replace('\r\n','\n'))

Note: This code and its companion C++ project are now available in a github repo.


texts:
My code takes input from the user and creates a receipt with the information the program receives from the user:

import easygui

items = []
prices = []
amount = []
amounts = 0
finished = False
total_price = 0.00
list_num = -1

def take_item():
    global list_num, amounts, finished
    item = easygui.enterbox("What item is it?")
    if item == "done" or item == "None":
        finished = True
    else:
        how_many = easygui.integerbox("How many {0:} do you have?".format(item))
        amounts = how_many
        items.append(item)
        amount.append(how_many)
        list_num += 1

def pricing():
    global list_num, total_price
    if finished:
        pass
    else:
        try:
            price = easygui.enterbox("What is the price of 1 {0:}".format(items[list_num]))
        new_price = float(price)
        except ValueError:
            easygui.msgbox("Please enter a number.")
            pricing()
        else:
            total_price += float(price) * amounts
            prices.append(new_price)

def create_receipt():
    print "Item \t Amount \t Price \t Total Price"
    for i in range(0, list_num+1):
        print items[i], "\t\t", amount[i], "\t\t 3", prices[i]
    print "\t\t\t ", "$",total_price
    print "Thank you for using Tony's Receipt Maker!"
    print "-----------------------------------------------------------"

while 1:
    take_item()
    pricing()
    if finished:
        create_receipt()
    else:
        continue

Are there any ways to improve the efficiency of the code and shorten it? Is there anything I should improve in my code?


texts: Counting number of `1` digits in the value of \$11^n\$

texts:
I am trying to improve the efficiency of my code,

The Question is:

Given a value n, where n is in the range [0 .. 500], return the number of digits equal to 1 in the decimal representation of the number \$11^n\$.

Naturally when dealing with a larger power (where n is a large number), this reduces the efficiency drastically.

I managed to produce a quick but inefficient rough solution, that seems to work, but what could I do to improve the code and its efficiency?

import java.util.ArrayList;

public class Solution {

private static int num = 11;

public static int solution(int n) {

    int counter = 0;
    String compare = "1";
    double answer = Math.round(Math.pow(num, n));
    System.out.println(answer);

    String s = String.valueOf(answer);
    String[] parts = s.split("");

    for (int i=0; i<parts.length; i++){
        if (parts[i].equals(compare)){
            counter++;
        }
    }
    System.out.println(counter);
    return counter;
}

public static void main(String[] args) {

    solution(8);
    solution(3);

    }
}

Any help in improving my understanding of the techniques of writing more efficient code would be much appreciated as well as improvements to the code example above.


texts: Sanitizing words extracted from text files and writing them to a database

texts:
This code reads text files from some path, tokenizes, removes stop words, lowercases, removes punctuation and numbers, then writes the result to a database.

# -*- coding: utf-8 -*-
from __future__ import print_function
import os, codecs, re, string, mysql
import mysql.connector

'''Reading files with txt extension'''
y_ = ""
for root, dirs, files in os.walk("/Users/Documents/source-document/part1"):
    for file in files:
        if file.endswith(".txt"):
            x_ = codecs.open(os.path.join(root,file),"r", "utf-8-sig")
            for lines in x_.readlines():
                y_ = y_ + lines
#print(tokenized_docs)

'''Tokenizing sentences of the text files'''

from nltk.tokenize import sent_tokenize
raw_docs = sent_tokenize(y_)

tokenized_docs = [sent_tokenize(y_) for sent in raw_docs]

'''Removing stop words'''

stopword_removed_sentences = []
from nltk.corpus import stopwords
stopset = stopwords.words("English")
for i in tokenized_docs[0]:
    tokenized_docs = ' '.join([word for word in i.split() if word not in stopset])
    stopword_removed_sentences.append(tokenized_docs)

''' Removing punctuation marks'''

regex = re.compile('[%s]' % re.escape(string.punctuation))
nw = []
for review in stopword_removed_sentences:
    new_review = ''
    for token in review:
        new_token = regex.sub(u'', token)
        if not new_token == u'':
            new_review += new_token
    nw.append(new_review)

'''Lowercasing letters after removing puctuation marks.'''

lw = []  #lw stands for lowercase word.
for i in nw:
    k = i.lower()
    lw.append(k)

'''Removing number with a dummy symbol'''
nr = []
for j in lw:
    string = j
    regex = r'[^\[\]]+(?=\])'
# let "#" be the dummy symbol
    output = re.sub(regex,'#',string)
    nr.append(output)
nrfinal = []
for j in nr:
    rem = 0
    outr = ''
    for i in j:
        if ord(i)>= 48 and ord(i)<=57:
            rem += 1
            if rem == 1:
                outr = outr+ '#'
        else:
             rem = 0
             outr = outr+i
    nrfinal.append(outr)
'''Inserting into database'''
def connect():
    for j in nrfinal:
        conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis' )
        cursor = conn.cursor()
        cursor.execute("""INSERT INTO splitted_sentences(sentence_id, splitted_sentences) VALUES(%s, %s)""",(cursor.lastrowid,j))
        conn.commit()
        conn.close()
if __name__ == '__main__':
    connect()

I am not getting any error with this code. Please review it for writing it in a more optimized way.


texts: Make loading icon appear only after 2 seconds

texts:
On any ajax calls made that take more than 2 seconds, I want a loading icon to appear. I have css that takes care of showing the loading icon when the 'loading' class is added to the body.

And here is the relevant code:

<script>
    var loadingIconOn = false;

    $(document).on({
        ajaxStart: function () {
            loadingIconOn = true;
            setTimeout(function () {
                if(loadingIconOn == true)
                    $('body').addClass("loading");
            }, 2000);

        },
        ajaxStop: function () {
            $('body').removeClass("loading");
            loadingIconOn = false;
        }
    });
</script>

This seems to be working fine, but I'm wondering if this might get me into trouble if multiple actions are made at the same time to do different ajax operations, and is there a better way of doing this?

EDIT (Here's why I want to wait 2 seconds):

There are actions that show immediate feedback, however the ajax call takes a split second to process. I don't want the user to see the loading symbol flicker on and off in cases like this. I only want to show it when something is actually taking a long time. No reason for them to feel like the site is slow when they wouldn't otherwise notice any slow down.


texts: Attempt at solution for Dining Philosopher algorithm

texts:
I know there are a lot of different solutions to solve the "Dining Philosophers" problem, but I wanted to get some feedback on a solution that I have so far.

My motivation for working on this is to prepare for future job interviews and to get more familiar with threads and C++.

#define P 5
#include <iostream>
#include <mutex>
#include <thread>
#include <Windows.h>

std::thread *threads[P]; //my philosophers
std::mutex mtx[P]; //forks
std::mutex cout;

bool pickUp(int left, int right) {
    if (mtx[left].try_lock()) {
        if (mtx[right].try_lock()) {
            return true;
        }
        else {
            mtx[left].unlock();
        }
    }
    return false;
}

void putDown(int left, int right) {
    mtx[left].unlock();
    mtx[right].unlock();
}

void run(int philID) {
    int leftIndex = philID-1;
    int rightIndex = (philID) % (P-1);
    while (1) {
        if (pickUp(leftIndex, rightIndex)) {
            cout.lock();
            std::cout << "Philosopher " << philID << " eats.\n";
            cout.unlock();
            putDown(leftIndex, rightIndex);
            Sleep(50); //cannot acquire again right away
        }
        else {
            cout.lock();
            std::cout << "Philosopher " << philID << " thinks.\n";
            cout.unlock();
        }
    }
}
int main() {

    for (int i = 1; i <= P; i++) {
        threads[i-1] = new std::thread(run, i);

    }
    for (int i = 1; i <= P; i++) {
        if (threads[i - 1]->joinable())
            threads[i - 1]->join();
    }
    return 0;
}

My pickUp() function takes the indices of the philosophers "fork" in the array of mutexes and tries to get first the left and then the right fork. If it cannot get the right immediately, it simply puts the left fork down and returns false. If this happens then the philosopher "thinks" before trying to pickup his forks again.

If both forks are able to be picked up, then he eats and then puts down both his forks. This alone was enough to avoid deadlock, but there was the problem of starvation for other philosophers. To solve this, I added a Sleep() call of 50 milliseconds so that a philosopher cannot instantly grab his forks again.

Is this enough to be considered an adequate answer to this problem? It works fine, but is there a "better" solution that I am missing?


texts:
After answering a question about Factor, I decided that it looked interesting. To get the hang of the syntax and such, I decided to write some basic physics code to "solve" the three-body problem. Then, I realized that math is harder than I thought it would be, so instead I just made a vocabulary to solve some basic problems about classical gravitational attraction.

I'm looking for advice on:

Idiomatic-ness: The functions feel pretty long for Factor, but they seem about as short as they'll get.
Naming: Some of my function names are subpar, but I can't find better names for them.
Separation: I feel like the vector arithmetic should be in its own vocabulary, but I'm not sure. Also, I have no idea how to do that.
Removing rounding errors: The program is fairly accurate, but some rounding error leads to ever-so-slightly wrong numbers (i.e. \$49.99999999999999\$ instead of \$50\$)

USING: locals math.functions math.vectors math.trig math.constants ;
IN: q.physics.gravitational-attraction

TUPLE: body
  { mass     initial: 0       }
  { position initial: { 0 0 } }
  { velocity initial: { 0 0 } }
;
:: array>body ( array -- obj )
  body new
    array first         >>mass
    array second 2 head >>position
    array third 2 head  >>velocity
;
: >body ( mass position velocity -- obj )
  3array array>body
;

! Constants
SYMBOLS: G ;
! Throws an error if it's 6.674e−11 so let's use 1
1 G set

:: vector-between ( from to -- v )
  to first from first -
  to second from second -
  2array
;

:: dot ( u v -- rad )
  u first v first * u second v second * +
  u first sq u second sq + sqrt v first sq v second sq + sqrt *
  /
;
: angle-between ( u v -- rad ) dot ;

:: v+ ( u v -- sum )
  u first v first +
  u second v second +
  2array
;

:: s*v ( k v -- scaled )
  v first k *
  v second k *
  2array
;

:: -1*v ( v -- neg )
  v first -1 *
  v second -1 *
  2array
;

:: magnitude ( v -- num )
  v first sq v second sq + sqrt
;

:: unit ( v -- unit )
  v magnitude :> len
  v first len /
  v second len /
  2array
;

:: force-on ( obj from -- force )
  obj position>> from position>> vector-between :> vec
  G get obj mass>> * from mass>> *
  vec magnitude
  /
  vec unit s*v
;

:: forces ( bodies -- forces )
  bodies [
    :> body
    body bodies remove [
      body swap force-on
    ] map
  ] map
;

I don't know the math well enough to test the edge cases, but I did check with this code:

SYMBOLS: b1 b2 b3 ;
10 { 0 0 } { 0 0 } >body b1 set
10 { 1 0 } { 0 0 } >body b2 set
10 { 0 1 } { 0 0 } >body b3 set
b1 get b2 get b3 get 3array forces [| f | f first f second v+ ] map .

which gave me the result:

{
    { 100.0 100.0 }
    { -150.0 49.99999999999999 }
    { 49.99999999999999 -150.0 }
}

And according to my math, that's correct. Note that the results are in terms of \$G\$, not multiplying by it, since it gives me an error when I try to put in 6.674e−11.


texts: Python 3 - Get n greatest elements in dictionary

texts:
Given an dictionary with lists as values this piece of code is dedicated to find the n keys with the longest lists as values. It works, but there has to be a more elegant solution.

def get_n_longest_values(dictionary, n):
    result = []

    for key, value in dictionary.items():
        if len(result) < n:
            result.append((key, len(value)))
        else:
            # (index, length) of smallest element
            smallest = (10e10, 10e10)
            for index in range(0, n):
                if result[index][1] < smallest[1]:
                    smallest = (index, result[index][1])

            if len(value) > smallest[1]:
                result[smallest[0]] = (key, len(value))

    return result


texts: Using jquery to prepare jQuery UI tabs, optimize?

texts:
I am looking for someone to review my solution to a jQuery DOM manipulation exercise on appendto.com: http://learn.appendto.com/lesson/dom-manipulation-101#exercise

I'm wondering if there is a way I can optimize or if there are other aspects I need to consider when building a solution like this.

The problem is outlined in the fiddle: http://jsfiddle.net/KhwZS/1283/

Here is my solution:

var getFirstTwoWords = function(str) {
    return str.split(/\s+/).slice(1,3).join(" ");
}

var tabLinks = $("

");
$("div.tab").each( function( idx ) {
    var id = "tabs-" + (idx + 1);

    var text = $(this)
        .removeClass("tab")
        .attr("id", id)
        .text();

    var tabLabel = getFirstTwoWords(text);

    // Create corresponding tab link
    tabLinks.append("
" + tabLabel + "
");
});

$(".tabs div:first").before(tabLinks);
$( ".tabs" ).tabs();

Optimized version:

var tabLinks = $("

");
$("div.tab").each( function( idx ) {
    var id = "tabs-" + (idx + 1);

    var tabLabel = $(this)
        .removeClass("tab")
        .attr("id", id)
        .find("h3")
        .remove()
        .text();

    // Create corresponding tab link
    tabLinks.append("
" + tabLabel + "
");
});

$(".tabs")
   .prepend(tabLinks)
   .tabs();


texts:
I want to be able to store and retrieve a unique user throughout the app. Multiple accounts are not used. The code I have written is stated below.

This is my first attempt using KeyChain. The test succeeds. I am wondering if anything if the code can be improved. Security issues perhaps?

import XCTest

class KeyChain {
    struct User {
        let identifier: Int64
        let password: String
    }

    static func save(user: User) -> Bool {
        let identifier = Data(from: user.identifier)
        let password = user.password.data(using: .utf8)!
        let query = [kSecClass as String : kSecClassGenericPassword as String,
                     kSecAttrService as String : "comapp",
                     kSecAttrAccount as String : identifier,
                     kSecValueData as String : password]
            as [String : Any]

        let deleteStatus = SecItemDelete(query as CFDictionary)

        if deleteStatus == noErr || deleteStatus == errSecItemNotFound {
            return SecItemAdd(query as CFDictionary, nil) == noErr
        }

        return false
    }

    static func retrieveUser() -> User? {
        let query = [kSecClass as String : kSecClassGenericPassword,
                     kSecAttrService as String : "comapp",
                     kSecReturnAttributes as String : kCFBooleanTrue!,
                     kSecReturnData as String: kCFBooleanTrue!]
            as [String : Any]

        var result: AnyObject? = nil
        let status = SecItemCopyMatching(query as CFDictionary, &result)

        if status == noErr,
            let dict = result as? [String: Any],
            let passwordData = dict[String(kSecValueData)] as? Data,
            let password = String(data: passwordData, encoding: .utf8),
            let identifier = (dict[String(kSecAttrAccount)] as? Data)?.to(type: Int64.self) {

            return User(identifier: identifier, password: password)
        } else {
            return nil
        }
    }
}

private extension Data {
    init<T>(from value: T) {
        var value = value

        self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
    }

    func to<T>(type: T.Type) -> T {
        withUnsafeBytes { $0.load(as: T.self) }
    }
}

class SecureStoreTests: XCTestCase {
    func testUser() {
        let user = KeyChain.User(identifier: 200, password: "somePassword")

        let didAddedUser = KeyChain.save(user: user)

        XCTAssertTrue(didAddedUser)

        let retrievedUser = KeyChain.retrieveUser()!

        XCTAssert(user.identifier == retrievedUser.identifier)
        XCTAssert(user.password == retrievedUser.password)
    }
}


texts: Solving the coin change algorithm using 10 coins

texts:
I'm solving the coin change problem having target of n and upper bound as n.

Also the maximum number of coins is 10.

For example. if the target is 11. then the possible outcomes are -

11
10,1
9,2
9,1,1
....
....
....
2,1,1,1,1,1,1,1,1,1

So the last iteration having eleven 1's are not allowed as the max coins is 10.

I have written code for solving the problem, but that is too complicated and cumbersome and I think it can be optimized for better performance.

The code as in this link and below:

import java.util.ArrayList;

public class Numbers {

/**
 * @param args the command line arguments
 */
static ArrayList<Integer> list;
static int target;
static boolean bl;
static boolean ex;
static int rpl;
public static void main(String[] args) {

    Numbers nm = new Numbers();
    /*
    nm.list = new ArrayList();
    new Numbers().test1();
    */
    list = new ArrayList<Integer>();
    bl = false;
    ex = false;
    target = 24;
    nm.test(24);
}

public void test(int k) {
    int r = 0;
    for (int i = k; i>0; i--) {
        if(!ex) {
            if(sum(list) + i > target) {
                test(i-1);
            }
            else if(list.size() == 10) {
                /*
                list.add(target - sum(list));
                printFill(list); */
                int p = list.get(0);
                if(p*10>=target) {
                    i = p;
                    list.clear();
                }

            } else {
                list.add(i);
                if(sum(list) == target) {
                    printFill(list);
                    if(bl)
                        i = rpl;
                    bl = false;
                } else {
                    test(i);
                }
            }
        } else {
            System.out.print("t");
        }
    }
}

public void printFill(ArrayList lt) {
    int i = 0;
    for ( i = 0; i< lt.size()-1; i ++) {
        System.out.print(lt.get(i)+",");
    }
    System.out.print(lt.get(i));
    System.out.println("");

    i = list.get(list.size()-1);
    if(i > 1) {
        list.remove(list.size()-1);
        if(list.size()>0) {
            try {
                while (list.get(list.size()-1) == 1) {
                    list.remove(list.size()-1);
                }
            } catch(Exception e ) { }
            /*if(list.size()==0) {
                System.out.println("test");
                ex = true;
            }*/
        }
    } else if(i == 1 ) {
        try {
            while (list.get(list.size()-1) == 1) {
                list.remove(list.size()-1);
            }
        } catch(Exception e ) { }
        if(list.size()>0) {
            bl = true;
            rpl = list.remove(list.size()-1);
        } else {
            ex = true;
        }
    }
}

public int sum(ArrayList<Integer> lt) {
    int k = 0;
    for ( int i = 0; i< lt.size(); i ++) {
        k = k + lt.get(i);
    }
    return k;
}

public void test1() {
    for(int i=1; i<= 4; i++) {
        if(!list.contains(i)) {
            list.add(i);
            test1();
            list.remove(list.indexOf(i));
        }
    }
    if(list.size() == 4)
    {
        for(int i=0; i< 4; i++) {
            System.out.print(list.get(i));
        }
        System.out.println("");
    }
}
}


texts:
I am new to unit testing and I am unsure how to design classes that use third party libraries, so that I can easily test them. The example I'll use is with EPPlus-OfficeOpenXml (an Excel document manipulator). I have a class to import excel documents and validate them.

Here is a sample of my code:

Imports OfficeOpenXml
Public Class TestImporter

    Private errorList As New List(Of String)

    Public Function import(fileName As String) As List(Of String)
        Dim openFile As New FileInfo(fileName)
        Dim document As New ExcelPackage(openFile)
        Dim sheet As ExcelWorksheet = document.Workbook.Worksheets(1)

        validateAll(sheet)

        Return errorList
    End Function

    Private Sub validateAll(sheet As ExcelWorksheet)
        validateHeaders(sheet)
    End Sub

    Private headers As String() = {"Header 1", "Header 2", "Header 3", "Header 4", "Header 5"}

    Private Sub validateHeaders(sheet As ExcelWorksheet)
        For i As Integer = 1 To headers.Length
            If Not (sheet.Cells(1, i).Value = headers(i - 1)) Then
                errorList.Add(String.Format("The header '{0}' does not match '{1}'", sheet.Cells(1, i).Value, headers(i - 1)))
            End If
        Next
    End Sub
End Class

The validation subroutines are private, because the only action I want to expose for this class is the import functionality.

How should I design this class in order to test my validation of Excel inputs? My first thought is have a test file for each test. Then pass in the name of the test file into the import function in each test. This doesn't seem to be the correct solution, and seems kind of hackish.


texts: Evaluating a math expression given in string format

texts:
I am currently working on building a calculator using Java and JavaFX to practice my coding skills. I wrote the following methods to evaluate a given expression.

What can I improve? Is there anything you would recommend me to change to optimize my program?

public static String evaluate(String expression) {
    char[] tokens = expression.toCharArray();
    List<String> list = new ArrayList<>();

    String s = "";

    String operator = "";
    String firstNum = "";
    String secondNum = "";

    boolean operationOnQueue = false;

    for (int i = 0; i < tokens.length; i++) {
        if (Character.isDigit(tokens[i])) {
            s += Character.toString(tokens[i]);
        } else {
            list.add(s);
            list.add(Character.toString(tokens[i]));

            if (operationOnQueue) {
                operationOnQueue = false;
                secondNum = s;

                list.set(list.lastIndexOf(firstNum), eval(firstNum, operator, secondNum));
                list.remove(list.lastIndexOf(operator));
                list.remove(list.lastIndexOf(secondNum));
            }

            if (tokens[i] == '*' || tokens[i] == '/') {
                operationOnQueue = true;

                operator = Character.toString(tokens[i]);
                firstNum = list.get(list.lastIndexOf(operator) - 1);
            }

            s = "";
        }

        if (i == tokens.length - 1 && s.length() > 0) {
            list.add(s);

            if (list.get(list.size() - 2).equals("*") || list.get(list.size() - 2).equals("/")) {
                firstNum = list.get(list.size() - 3);
                operator = list.get(list.size() - 2);
                secondNum = list.get(list.size() - 1);

                list.set(list.size() - 3, eval(firstNum, operator, secondNum));
                list.remove(list.size() - 2);
                list.remove(list.size() - 1);
            }
        }
    }

    while (list.size() > 1) {
        firstNum = list.get(0);
        operator = list.get(1);
        secondNum = list.get(2);

        list.set(0, eval(firstNum, operator, secondNum));
        list.remove(2);
        list.remove(1);
    }

    return list.get(0);
}

public static String eval(String a, String operator, String b) {
    double r = 0;

    switch (operator) {
        case "/":
            r += Double.parseDouble(a) / Double.parseDouble(b);
            break;
        case "*":
            r += Double.parseDouble(a) * Double.parseDouble(b);
            break;
        case "-":
            r += Double.parseDouble(a) - Double.parseDouble(b);
            break;
        case "+":
            r += Double.parseDouble(a) + Double.parseDouble(b);
            break;
    }

    return Double.toString(r);
}

These are the results of my tests. The first line is the string inputted, along with the answer to the expression. The second line is the output of the program.

8+4/2+10*3+5*10 = 90
90.0

60*60+8+384/7/4-44*26 = 2477.71
2477.714285714286

64/16*18-51*7+5 = -280
-280.0

64/16*18-5100*7+5 = -35623
-35623.0

7325+92+44/4+57-84 = 7401
7401.0

14+54/9+1 = 21
21.0

7*4/7+9+12*3 = 49
49.0


texts:
In order to concisify the handling of a failed call to malloc, realloc, or calloc, I have made a few files to dictate "safe" memory management. This is part of my project stac, so the prefix will appear in the following code snippets. Further, I have made the decision to use snake_case as opposed to standard camelCase.

What I hope to get out of this, and questions I have: are these functions in bad practice? Is there a different way I should be handling failed calls to memory allocators? And is there anything particularly wrong with the code I have written?

safe_mem.c

#include "safe_mem.h"

void* safe_malloc(size_t size){
    void* memory = malloc(size);

    if(memory == NULL){
        free(memory);
        runtime_error("failed to allocate memory.");
    }

    return memory;
}

void* safe_calloc(size_t num, size_t size){
    void* memory = calloc(num, size);

    if(memory == NULL){
        free(memory);
        runtime_error("failed to allocate memory.");
    }

    return memory;
}

void* safe_realloc(void* ptr, size_t size){
    void* memory = realloc(ptr, size);

    if(memory == NULL){
        free(memory);
        runtime_error("failed to reallocate memory.");
    }

    return memory;
}

safe_mem.h

#ifndef STAC_SAFE_MEM
#define STAC_SAFE_MEM
#include <stdio.h>
#include <stdlib.h>
#include "error.h"

void* safe_malloc(size_t);
void* safe_calloc(size_t, size_t);
void* safe_realloc(void*, size_t);
#endif

error.c

#include "error.h"

void make_error(char* type, char* message){
    eprintf("%s error: %s\n", type, message);
}

void fatal_error(char* type, char* message, int exit_code){
    make_error(type, message);
    exit(exit_code);
}

void runtime_error(char* message){
    fatal_error("Runtime", message, STATUS_RUNTIME_ERROR);
}

void generic_error(char* message){
    fatal_error("Generic", message, STATUS_GENERIC_ERROR);
}

error.h

#ifndef STAC_ERROR
#define STAC_ERROR
#include <stdio.h>
#include <stdlib.h>

#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#define STATUS_OKAY (0)
#define STATUS_RUNTIME_ERROR (1)
#define STATUS_GENERIC_ERROR (-1)

void make_error(char*, char*);
void fatal_error(char*, char*, int);

void runtime_error(char*);
void generic_error(char*);

#endif


texts: How can I make this XML gallery snippet prettier?

texts:
Everything works, i just want to know if i can change the way the xml tags are retreived. This way seems a bit bulky - but i could be wrong. Thoughts?

    var d = 0

    $(".timeline").children().eq(d).addClass("active")

    // default traverse function to buttons, inject node
    prev.data("node", array.length-1)
    next.data("node", 1)

    // use default node to get default properties
    src = xml.getElementsByTagName("src")[d].childNodes[0].nodeValue
    name = xml.getElementsByTagName("name")[d].childNodes[0].nodeValue
    date = xml.getElementsByTagName("date")[d].childNodes[0].nodeValue
    desc = xml.getElementsByTagName("desc")[d].childNodes[0].nodeValue
    img = '<img alt="'+name+'" src="'+src+'">'
        // inject default image properties
        $(".stage").html(img)
        $(".window").width($(".stage").width())
        $(".name").html(name), $(".date").html(date), $(".desc").html(desc)


texts: Implementation of String object as an exercise

texts:
I am reading "Object-Oriented JavaScript" by Stoyan Stefanov to learn JavaScript and in the end of the chapter named "Objects", there's an exercise that asks you to implement your own String object. I have implemented some methods of String (not all), I'd be happy if you could check and let me know how it could be done better:

function MyString(primitive) {
    this.length = 0;
    var i = 0;
    // Here length is calculated and the indexer is set.
    for (var c in primitive) {
        this[i++] = primitive[c];
        this.length++;
    }

    this.toString = function() { return primitive; };
    this.valueOf = this.toString;
    this.substring = function(start, end) {
        var result = '';

        // Edge cases for the parameters.
        if ((typeof end !== 'number' && typeof parseInt(end) !== 'number') || end > this.length)
            end = this.length;
        if (end <= 0 || isNaN(end)) {
            end = start;
            start = 0;
        }

        for (var i = start; i < end; i++) {
            result += this[i];
        }

        return result;
    }
    this.charAt = function(i) {
        var x = parseInt(i);
        x = isNaN(x) ? 0 : x;
        return this.substring(x, x+1);
    };

    return this;
}

var s = new MyString('hello');
console.log(s.length);
console.log(s[0]);
console.log(s.toString());
console.log(s.valueOf());
console.log(s.charAt(1));
console.log(s.charAt('2'));
console.log(s.charAt('e'));
console.log(s.substring(1, 3));

Any and all suggestions are welcome. I'm completely new to JavaScript and would love to hear my mistakes.


texts:
What do you use for refactoring away from exceptions while programming functional in C#? I defined this class to hold function outcome:

public class Result
{
    public static readonly Result OK = new Result();
    public static implicit operator Result(Exception error) => new Result(error);

    protected Result(Exception error = null)
    {
        Error = error;
    }

    public Exception Error { get; }
    public bool Succeeded => Error == null;
    public bool Failed => !Succeeded;

    public override string ToString() =>
        Succeeded ? "OK" : Error.Message;
}

And its subclass to hold return value where necessary:

public class Result<T> : Result, IEnumerable<T>
{
    public static implicit operator Result<T>(Exception error) => new Result<T>(error);
    public static implicit operator Result<T>(T value) => new Result<T>(value);
    public static implicit operator T(Result<T> result)
    {
        if (result.Failed)
            throw result.Error;

        return result.Value;
    }

    protected Result(T value)
        : base(error: null)
    {
        Value = value;
    }

    protected Result(Exception error)
        : base(error)
    {
    }

    T Value { get; }

    IEnumerable<T> Values =>
        Failed ? new T[0] : new[] { Value };

    public IEnumerator<T> GetEnumerator() =>
        Values.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() =>
        GetEnumerator();
}

It is enumerable, exposing 0..1 elements, so amount of if-statements can be reduced.

Usage:

        var r1 = Div(
            Div(100, 10),
            Div(10, 2));

        var r2 = Div(
            Div(100, 10),
            Div(0, 0));

        Console.WriteLine(r1.Succeeded); // True
        Console.WriteLine(r1.Count()); // 1
        Console.WriteLine(r1); // 2

        Console.WriteLine(r2.Succeeded); // False
        Console.WriteLine(r2.Count()); // 0
        // Console.WriteLine(r2); // throws DivideByZeroException

Where:

    static Result<int> Div(Result<int> a, Result<int> b)
    {
        try
        {
            return a / b;
        }
        catch (DivideByZeroException ex)
        {
            return ex;
        }
    }

Idea comes from: Refactoring away from exceptions


texts:
I am trying to sort a list on basis of C before .
Is there better way to do this?
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

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

    List<String> activeLoadList = new LinkedList<String>();
    List<String> tempList = new LinkedList<String>();
    activeLoadList.add("REL1110C.PZ");
    activeLoadList.add("REL1110Z.PS");
    activeLoadList.add("REL1110C.AB");
    activeLoadList.add("REL1110Z.CD");
    activeLoadList.add("REL1110C.OP");

    System.out.println("Queue is ***" + activeLoadList);

    Iterator<String> iter = activeLoadList.iterator();
    while (iter.hasNext()) {
        String next = iter.next();
        if (next.contains("C.")) {
            iter.remove();
            tempList.add(next);
        }
    }

    activeLoadList.addAll(tempList);
    System.out.println("Queue is ***" + activeLoadList);
  }
}

Output:

Queue is ***[REL1110C.PZ, REL1110Z.PS, REL1110C.AB, REL1110Z.CD, REL1110C.OP]
Queue is ***[REL1110Z.PS, REL1110Z.CD, REL1110C.PZ, REL1110C.AB, REL1110C.OP]


texts: Picasso's Transformation class to Crop borders from Image

texts:
It's a implementation of Transformation from Picasso library looks for the first different pixel color in both sides, in the vertical and horizontal, and crops the bitmap from there.

Here is the Bitmap class doc from Android library.

public class CropMiddleFirstPixelTransformation implements Transformation {
    private int mWidth;
    private int mHeight;

    @Override
    public Bitmap transform(Bitmap source) {
        int width = source.getWidth();
        int height = source.getHeight();

        int[] horizontalMiddleArray = new int[width];
        source.getPixels(horizontalMiddleArray, 0, width, 0, height / 2, width, 1);

        int[] verticalMiddleArray = new int[height];
        source.getPixels(verticalMiddleArray, 0, 1, width / 2, 0, 1, height);

        int left = getFirstNonWhitePosition(horizontalMiddleArray);
        int right = getLastNonWhitePosition(horizontalMiddleArray);

        int top = getFirstNonWhitePosition(verticalMiddleArray);
        int bottom = getLastNonWhitePosition(verticalMiddleArray);

        mWidth = right - left;
        mHeight = bottom - top;

        if (!isNegative(left, right, top, bottom)) {
            return source;
        }

        Bitmap bitmap = Bitmap.createBitmap(source, left, top, mWidth , mHeight);
        source.recycle();
        return bitmap;

    }

    private boolean isNegative(int... values) {
        for (int i : values) {
            if (i < 0) {
                return false;
            }
        }
        return true;

    }

    private int getFirstNonWhitePosition(int[] horizontalMiddleArray) {
        int left = 0;
        for (int i = 0; i < horizontalMiddleArray.length; i++) {
            if (i == 0) {
                left = horizontalMiddleArray[i];
            }
            if (left != horizontalMiddleArray[i]) {
                return i;
            }
        }
        return -1;
    }

    private int getLastNonWhitePosition(int[] horizontalMiddleArray) {
        int right = 0;
        int length = horizontalMiddleArray.length;
        for (int i = length - 1; i > 0; i--) {
            if (i == length - 1) {
                right = horizontalMiddleArray[i];
            }
            if (right != horizontalMiddleArray[i]) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public String key() {
        return "CropMiddleFirstPixelTransformation(width=" + mWidth + ", height=" + mHeight + ")";
    }
}

What could be improved in this implementation?

I think I could eliminate one of this methods: getLastNonWhitePosition, getFirstNonWhitePosition using Java 8 and functional programming, but I cannot do that.


texts: php most elegant function call returning array

texts:
I am asking your preference between two similar solutions.

First way :

public function test($myvar) {

    switch ($myvar) {
        case 'test1': return [
                          'value' => 'Value of test1',
                          'short' => 'Val 1'
                      ];
        break;
     }
}

$this->test('test1')['short']  // Val 1

Second way:

public function test($myvar, $key) {

    switch ($myvar) {
        case 'test1': $array = [
                          'value' => 'Value of test1',
                          'short' => 'Val 1'
                      ];
    }

    return $array[$key];
}

$this->test('test1', 'short')  // Val 1

Even if both function return same value, what is the most elegant and readable way for you guys ?


texts: Deadbeef : finding all words made of hexadecimal digits

texts:
Hexadecimal 0xdead, 0xbeef are the magic numbers because they're also English words.
I decided to find such words as many as possible. How to do it? We need large English text let's say Ulysses by James Joyce and a program which extracts all words consists of hexadecimal digits. For simplicity, I decided to drop leet-language support. It dramatically shrinks the range but keeps real words only.

The code below extract magic numbers from given text and prints them to stdout in lower case

#include <ctype.h>
#include <stdio.h>

#define MAX_LEN 256

int process_file(FILE* file);

int main(int argc, char* argv[]) {

  if (argc == 1) {
    process_file(stdin);
  } else {
    size_t i = 0;
    char* filename;
    FILE* file;
    int err;
    while ((filename = argv[++i]) != NULL) {
      file = fopen(filename, "r");
      if (!file) {
        perror("fopen() failed");
        return 1;
      }
      err = process_file(file);
      fclose(file);
      if (err) {
        return 2;
      }
    }
  }

  return 0;
}

int process_file(FILE* file) {
  char word[MAX_LEN];
  size_t p = 0;
  int c;
  while (1) {
    c = getc(file);
    if (isspace(c) || c == EOF) {
      /* end of word or end of emptiness */

      if (p > 0 && p < MAX_LEN && p % 2 == 0) {
        word[p] = 0;
        printf("%s\n", word);
      }

      if (c == EOF) {
        break;
      }

      p = 0;
      continue;
    }

    if (p > MAX_LEN - 1) {
      continue;
    }

    if ((c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) { /* abcdef ABCDEF */
      word[p++] = tolower(c);
    } else {
      /* skip this word */
      p = MAX_LEN;
    }
  }

  if (feof(file)) {
    return 0;
  }

  if (ferror(file)) {
    perror("i/o error occurred");
  }

  return 1;
}

Commands

echo "Dead of being fed with beef for a decade" | ./deadbeaf | sort | uniq

should give

beef
dead
decade


texts: Finding the common iterator category in C++

texts:
I created a template trait which finds the common iterator category between a set of given iterator categories. More specifically, it's a class with a member type alias to one of the iterator tags which is the most efficient for the specific requirement set that is implied by both categories given as template arguments (the least "powerful" in the iterator hierarchy).

For example, given std::forward_iterator_tag, std::random_access_iterator_tag and std::bidirectional_iterator_tag, it provide std::forward_iterator_tag.

If all the given types are std::output_iterator_tag then it will provide std::output_iterator_tag. Otherwise, there is no member type alias. (std::output_iterator_tag must be treated differently because it is not in the input iterator hierarchy.)

#include <algorithm>
#include <iterator>
#include <tuple>
#include <type_traits>

namespace detail {
    // Gets the index of the first occurrence of a type in a tuple (inverse of std::tuple_element_t).
    template <typename T, class Tuple>
    struct tuple_type_index;

    // Specialisation for match on parameter pack's first type.
    template<typename T, typename... Ts>
    struct tuple_type_index<T, std::tuple<T, Ts...>> : std::integral_constant<std::size_t, 0> {};

    // Specialisation for no match on parameter pack's first type.
    template<typename T, typename U, typename... Ts>
    struct tuple_type_index<T, std::tuple<U, Ts...>> : std::integral_constant<std::size_t, 1 + tuple_type_index<T, std::tuple<Ts...>>::value> {};

    // Helper variable template.
    template<typename T, class Tuple>
    constexpr std::size_t tuple_type_index_v = tuple_type_index<T, Tuple>::value;

    // Hierarchy of input iterator categories (output iterator category is handled separately) from least to most powerful.
    using iterator_categories = std::tuple<std::input_iterator_tag, std::forward_iterator_tag, std::bidirectional_iterator_tag, std::random_access_iterator_tag>;
}

// Primary template (for 0 categories).
template<class... IteratorCategories>
struct common_iterator_category {};

// Helper type alias.
template<class... IteratorCategories>
using common_iterator_category_t = typename common_iterator_category<IteratorCategories...>::type;

// Specialisation for 1 category.
template<class IteratorCategory>
struct common_iterator_category<IteratorCategory> {
    using type = IteratorCategory;
};

// Specialisation for 2 non-output-iterator categories.
template<class IteratorCategory1, class IteratorCategory2>
struct common_iterator_category<IteratorCategory1, IteratorCategory2> {
    using type = std::tuple_element_t<
        std::min(
            detail::tuple_type_index_v<IteratorCategory1, detail::iterator_categories>,
            detail::tuple_type_index_v<IteratorCategory2, detail::iterator_categories>),
        detail::iterator_categories>;
};

// Specialisation for 2 output iterator categories.
template<>
struct common_iterator_category<std::output_iterator_tag, std::output_iterator_tag> {
    using type = std::output_iterator_tag;
};

// Specialisation for 3+ categories.
template<class IteratorCategory1, class IteratorCategory2, class... IteratorCategories>
struct common_iterator_category<IteratorCategory1, IteratorCategory2, IteratorCategories...> :
    common_iterator_category<common_iterator_category_t<IteratorCategory1, IteratorCategory2>, common_iterator_category_t<IteratorCategories...>> {};

The code with tests/examples is live here.

I am specifically interested in feedback with regards to the conciseness/efficiency of the design, and also whether it is well formed (I am worried about UB but "happens to work" or no diagnostic required issues). I'm not so much concerned with the tuple_type_index utility (it's just there because it happens to be required). But feedback of any sort is of course welcome.


texts: LINQ query to select subjects of interest

texts:
Here's the query:

 using (var db = CreateContext())
        {
            // performing the check for HasBeenAdded inline here, is this only one db call?
            return db.Subjects.Select(s => new SubjectDto(s){HasBeenAdded = db.Interests.Any(x => x.SubjectId == s.SubjectId)}).ToList();
        }

Basically I create a DTO from a subject and then populate a property of that DTO (HasBeenAdded) based on whether or not that entry's foreign key exists in another table.  Is this the right way to go?


texts: Refactor a legacy application to a less-unwieldy state

texts:
Follow-up posted here: Refactor this method to a cleaner state (continued)

I am refactoring a legacy application. I DO NOT have the ability to change the Permissions, CustomerReport or the ListItems classes. They are in external dlls that are given to me. I realize that the ref usage is dumb and it makes NO SENSE. I am going to work with my peers to follow better practices.

This whole class looks ugly and mind you I have refactored some of it out into methods but it still is too large and unwieldy:

public class ReportService : IReportService
{
    private readonly Permissions _Permissions;

    public ReportService()
    {
        _Permissions = new Permissions();
    }

    public IList<Node> GetFor(string userGroup)
    {
        var nodes = new List<Node>();
        var ListItems = new List<ListItem>();

        //Yes this is silly since statusReturn is never used
        var statusReturn = _Permissions.GetReportsForUserGroupName(userGroup, ref ListItems);

        if (ListItems.Any())
        {
            var initialReportType = ListItems[0].value;
            var initialCrs = ListItems[0].key;
            var parent = AssembleNode(initialReportType);
            var child = AssembleNode(initialCrs, parent);
            foreach (var item in ListItems)
            {
                var customerReport = (CustomerReport)item.dataObject;
                var grandChild = AssembleGrandChild(child, customerReport);
                if (item.value.Equals(initialReportType))
                    if (item.key.Equals(initialCrs))
                        child.Children.Add(grandChild);
                    else
                    {
                        initialCrs = item.key;
                        parent.Children.Add(child);
                        child = AssembleNode(item.key, parent);
                        child.Children.Add(grandChild);
                    }
                else
                {
                    initialReportType = item.value;
                    initialCrs = item.key;
                    parent.Children.Add(child);
                    nodes.Add(parent);
                    parent = AssembleNode(item.value);
                    child = AssembleNode(item.key, parent);
                    grandChild = AssembleGrandChild(child, customerReport);
                    child.Children.Add(grandChild);
                }
            }
            parent.Children.Add(child);
            nodes.Add(parent);
        }
        return nodes;
    }

    private static Node AssembleNode(string value, Node parent = null)
    {
        //This is an extension method on object that was used at my last dev shop.
        //I got used to using it so out of habit it is here
        return parent.IsNotNull() ?
            new Node(parent){ Text = value, Value = value } :
            new Node { Text = value, Value = value };
    }

    private static Node AssembleGrandChild(Node child, CustomerReport customerReport)
    {
        return new Node(child)
        {
            Text = customerReport.FileName,
            Value = customerReport.ReportKey.ToString(),
            Title = customerReport.Description
        };
    }
}

I really want to refactor this to a better state; any suggestions?


texts: Better way to fetch JSON data from a server from iOS app

texts:
I have successfully coded a network request to fetch JSON data from our server. The remote function is written in ColdFusion. However, the code is quite lengthy and involved. I also noticed in the API there are other seemingly very similar ways one can go about making network requests, such as NSURLSession. (I know NSURLConnection will be deprecated in the future, replaced by NSURLSession.) I would like to know what is the best way to make a network request - using modern code that is not going to be deprecated in the near future. Is NSURLSession the best way to go?

Here are my requirements:

Fetch JSON data from a function in a .cfc file on the server
Must be secure
Must be able to perform error checking
Only need to support iOS 7+
Preferably more concise code

Here is my current and lengthy code, using several variables, NSMutableURLRequest, and NSURLConnection:

dispatch_queue_t queue = dispatch_queue_create("Q", NULL);
dispatch_async(queue, ^{
    NSInteger success = 1;

    NSURL *url = [NSURL URLWithString:MYURL];
    NSData *postData = [[[NSString alloc] initWithFormat:@"method=methodName&username=%@&password=%@", usernameVar, passwordVar] dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody:postData];

    NSError *requestError = [[NSError alloc] init];
    NSHTTPURLResponse *response = nil;
    NSData *urlData = [NSURLConnection sendSynchronousRequest:request
                                            returningResponse:&response
                                                        error:&requestError];

    //if communication was successful
    if ([response statusCode] >= 200 && [response statusCode] < 300) {
        NSError *serializeError = nil;
        NSDictionary *jsonData = [NSJSONSerialization
                                  JSONObjectWithData:urlData
                                  options:NSJSONReadingMutableContainers
                                  error:&serializeError];
        success = [jsonData[@"ERROR"] integerValue];

        if (success == 0) {
            //success! do stuff with the jsonData dictionary here
        }
        else {
            //handle ERROR from server
        }
    }
    else {
        //handle error for unsuccessful communication with server
    }
});

Could you help me clean this up to be implemented the most preferred way for modern apps of today?


texts:
I am trying to implement Stack using a linked list. Looking for code-review, best practices and optimizations.

public class StackUsingLinkedList<T> {

    private Node<T> top;
    int size;

    public StackUsingLinkedList() {
    }

    private static class Node<T> {
        Node<T> next;
        T item;

        public Node (T item, Node<T> next) {
            this.item = item;
            this.next = next;
        }
    }

    /**
     * Push the item into the stack
     *
     * @param item  the item to be pushed.
     */
    public void push(T item) {
        final Node<T> node = new Node<T>(item, top);
        top = node;
        size++;
    }

    /**
     * Pops the item from the stack
     *
     * @return  the popped item
     * @throws EmptyStackException if attempt is made to access/pop out of an empty stack.
     */
    public T pop() {
        if (top == null) {
            throw new EmptyStackException();
        }

        T item = top.item;
        top = top.next;
        return item;
    }

    /**
     * Returns the item at top of the stack.
     *
     * @return  the item at top of stack.
     * @throws EmptyStackException if attempt is made to access empty stack
     */
    public T peek () {
        if (top == null) {
            throw new EmptyStackException();
        }
        return top.item;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return top == null;
    }

    public static void main(String[] args) {
        StackUsingLinkedList<Integer> s = new StackUsingLinkedList<Integer>();
        s.push(10);
        s.push(20);

        // expected 20, 10.
        while (!s.isEmpty()) {
            System.out.println(s.pop());
        }
    }


texts: Handling access to database connection both inside and outside of classes

texts:
Is this an OK way to handle access to database connection both inside and outside of classes?

I used to include a PHP file -- database.detl.php -- at the very top of my index.php file containing the following code:

try{
    $dbh_options = array(/*...*/);
    $dbh = new PDO('mysql:host=localhost;dbname='.db_name.';charset=utf8',db_user,db_user_pw,$dbh_options);
} catch(PDOException $e) {
    /*...*/
}

Now every document that got included by index.php could use $dbh to access my database. This made it quite easy to work with.

But despite including that file before any classes got loaded, this $dbh-variable was not available from inside the classes. This was not possible to do:

class KD_sql {
    public static function get_recipes(){
        $qry = $dbh->query('SELECT * FROM recipes');
        $get = $qry->fetchAll();
        return $get;
    }
}

new KD_sql();

$recipes = sql_query::get_recipes();

This resulted in a fatal error: Call to a member function query() on a non-object....

So I guess no variables outside of a class is ever available inside unless you somehow send it there as an additional parameter to the method.

Anyway:

This is how I rewrote the code in order to still be able to have the $dbh-variable available throughout the entire site - just like before, and also have the connection available inside my KD_sql-class - without creating the connection in multiple locations:

First I changed database.detl.php into this:

try{
    $_SITE_DATABASE_details = function(){  //  <  added a function that holds the connection details
        $dbh_options = array(/*...*/);
        $dbh = new PDO('mysql:host=localhost;dbname='.db_name.';charset=utf8',db_user,db_user_pw,$dbh_options);
        return $dbh;  //  <  return connection details
    };
    new KD_db($_SITE_DATABASE_details);  //  the details is sent to a new class
    $dbh = KD_db::con();  //  <  a method, in this new class, returns the connection in order to still have $dbh available
} catch(PDOException $e) {
    /*...*/
}

This might seem a bit wierd, but let me finish.
Here's the new KD_db-class:

class KD_db {
    protected static $con = null;
#   initiate and stores the connection to the $con-variable
    public function __construct(callable $db_details){
        if (self::$con===null){
            self::$con = call_user_func($db_details);
        }
    }
//
#   the method that returns the database connection.
    public static function con(){
        return self::$con;
    }
//
}

This class is basically just a parent class that other classes can extend to in order to have the database connection available as well.

Here is the rewritten KD_sql-class:

class KD_sql extends KD_db {
    public static function get_recipes(){
        $qry = self::$con->query('SELECT * FROM recipes');  //  uses the $con -variable from parent class
        $get = $qry->fetchAll();
        return $get;
    }
}

I can now easily create quick-queries inside my KD_sql-class and just do this:

$recipes = KD_sql::get_recipes();

which quickly returns an array of all the recipes. Or, if that doesn't cut it, I can write a more complex SQL query like this:

$recipes = $dbh->prepare('
    SELECT r.columns,
        ot.columns
    FROM recipes r
        JOIN other_table ot ON r.fk_other_table_pk = ot.id
    WHERE r.some_column = :value
');

But I do have some "bugs" with the returned resultset from the class. If I only use fetch(), instead of fetchAll(), I can't do a while()-loop like this:

$recipes = KD_sql::get_recipes();
while($recipes){
    echo $recipes['id'].' '.$recipes['name'].'<br>';
}

Nothing happens, beside it looks like the loop is never ending or something. That's why I'm using fetchAll() for now. Then uses foreach() because that works.

But besides that. I would really appreciate som feedback on my way of doing this. I'm not that good with classes, oop and such. So if I'm breaking any golden rules or something - please let me know.


texts:
I'm writing some code for someone to update a pivot table field based on the contents entered in a particular cell.

I am unfamiliar with VBA and programming for excel but I followed some tutorials and would like if someone here could look over what I've done just to see if everything looks ok before I give it to them as I don't have access to their excel worksheet.

Private Sub Worksheet_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Not Intersect(Target, Application.Range(B8)) _
    Is Nothing Then
        UpdatePivotFieldFromRange _
        B8, B3, Outfield
End If
End Sub

Public Sub UpdatePivotFieldFromRange(RangeName As String, Fieldname As       String, PivotTableName As String)

Dim rng As Range
Set rng = Application.Range(RangeName)

Dim pt As PivotTable
Dim Sheet As Worksheet

For Each Sheet In Application.ActiveWorkbook.Worksheets
    On Error Resume Next
    Set pt = Sheet.PivotTables(PivotTableName)
Next
If pt Is Nothing Then GoTo Ex
On Error GoTo Ex

pt.ManualUpdate = True
Application.EnableEvents = False
Application.ScreenUpdating = False

Dim Field As PivotField
Set Field = pt.PivotFields(Fieldname)
Field.ClearAllFilters
Field.EnableItemSelection = False
SelectPivotItem Field, rng.Text
pt.RefreshTable

Ex:
pt.ManualUpdate = False
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

Public Sub SelectPivotTableItem(Field As PivotField, ItemName As String)
Dim Item As PivotItem
For Each Item In Field.PivotItems
    Item.Visible = (Item.Caption = ItemName)
Next
End Sub


texts: Dividing the screen in two halves using LinearLayout

texts:
I want to divide the screen in two halves. The layout is locked on portrait mode. The top half will have one button and the bottom half will have many buttons. That's why I choose this division, since the top half can be potentially scrollable.

This is my layout xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/play_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/play_button" />

    </LinearLayout>

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button_1" />

        <Button
            android:id="@+id/button_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button_2" />

        <Button
            android:id="@+id/button_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button_3" />

    </LinearLayout>

</LinearLayout>

And this is how it looks like:

It looks as expected, but I was wondering if I'm doing it correctly. Is there a better, easier, more common, different, (etc) way to achieve this? Are there any mistakes or anti-patterns or bad things in there?


texts: Find tags in text for replacement, my brute force solution

texts:
I have a text such as

string text = "Hi [img-2] tst[img-3] test ttteessstt grawr[img-1-800]tet";

I want to find img tags in the text and get their id (second value) and possibly the third value if it exists.

string text = "Hi [img-2] tst[img-3] test ttteessstt grawr[img-1-800]tet";

var th = new TagHandler(null);
var res = th.FindImgTags(text);

foreach(var tag in res)
{
    Debug.WriteLine(string.Join(", ", tag.Tag, tag.Id, tag.Width));
}

The above code outputs this:

[img-2], 2, 0
[img-3], 3, 0
[img-1-800], 1, 800

This is my "find tags code". Its crude but gets the job done...
Any suggestions on how to make this less verbose / brute

public List<ImgReplaceItem> FindImgTags(string data)
{
    var result = new List<ImgReplaceItem>();

    var pieces = data.Split(new string[] { "[img-" }, StringSplitOptions.RemoveEmptyEntries);
    foreach (var item in pieces)
    {
        if (item.Contains(']'))
        {
            var backend = item.Split(new char[] { ']' }, StringSplitOptions.RemoveEmptyEntries);
            var dataInside = backend[0];

            var r = new ImgReplaceItem();
            r.Tag = "[img-" + dataInside + "]";
            var pid = -1;
            if (dataInside.Contains('-'))
            {
                var widthParts = dataInside.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                int.TryParse(widthParts[0], out pid);

                if (widthParts.Count() > 1)
                {
                    var width = -1;
                    int.TryParse(widthParts[1], out width);
                    r.Width = width;
                }
            }
            else
            {
                int.TryParse(dataInside, out pid);
            }
            r.Id = pid;
            result.Add(r);
        }
    }

    return result;
}


texts: SQL to match string value against multiple columns

texts:
I have a table called tblStudent having data as

I want to retrieve records having single value compared against multiple columns. For example -
find all students having Grade 'C' in any of the subjects.
One way could be -

SELECT * FROM tblStudent
WHERE Grade_Maths = 'C' OR
Grade_Science = 'C' OR
Grade_English = 'C'

Another (cleaner/shorter) way of achieving same is

SELECT * FROM tblStudent
WHERE 'C' IN (Grade_Maths, Grade_Science, Grade_English)

Because the table data can be considerably huge in real-time, I am not sure whether second method will always return correct result.
Can please suggest if there could be any potential issue with using second approach.

Thanks a lot!


texts: Finding nearest city from a center place (latitude and longitude) with radius in miles

texts:
This is my code for finding the nearest city within a certain radius. I am not sure, is my code is OK or is it wrong? Please review and offer suggestions on my code.

<?
//Suppose,I have selected a city and fetch the selected city's lat and long and radius
//in to this page.
$file_handle = fopen("Londonstations.csv", "r");
$i=0; $j=0; $k=0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$locat[$i++] = $line_of_text[0];
$lat[$j++] = $line_of_text[3];
$long[$k++] = $line_of_text[4];
//print $line_of_text[0]; . $line_of_text[1]. $line_of_text[2] . "
";
}
$l = $_POST['l'];//This value is received from previous page selected places latitude and longitude index from array.
$r = $_POST['r'];//This value is received from previous page selected places for //finding city that are in located in this radius
$radius = 3958.761; //earth's radius in miles
 // we'll want everything within, say, distance
$distance = $r;//This value is received from previous page, radius of selected
 //places for finding city that are in located in this radius

// latitude boundaries
$maxlat = $lat[$l] + rad2deg($distance / $radius);
$minlat = $lat[$l] - rad2deg($distance / $radius);

// longitude boundaries (longitude gets smaller when latitude increases)
$maxlng = $long[$l] + rad2deg($distance / $radius / cos(deg2rad($long[$l])));
$minlng = $long[$l] - rad2deg($distance / $radius / cos(deg2rad($long[$l])));
$n=1;
echo 'Nearest Stations:';
echo '
';
for($ii=1;$ii<$i;$ii++){
if($lat[$ii]<=$maxlat && $lat[$ii]>=$minlat){
    if($long[$ii]<=$maxlng && $long[$ii]>=$minlng)
        echo '
'.$rs[$n++] = $locat[$ii].'
';
}
}
echo '
';
?>


texts: Cyclic "dependency detection" in JavaScript

texts:
I have written some simple code to detect cyclic dependencies for a module loading system and I'd like some feedback on how I can go about improving it. The code itself finds the first cycle in the dependency graph that starts at the provided node and returns a list of all of the nodes traversed along the way.

Here's an example:

The white node is the one we are starting the traversal at. The JS representation of this graph would look like this:

{
  'A': ['B', 'C'],
  'B': [],
  'C': ['D'],
  'D': ['A']
}

The output from my function is ['A', 'C', 'D', 'A'], which is a list of the nodes traversed before finding a cycle.

Here is the code I have written to generate the array:

function findCyclicDependencies(definitions, identifier) {
  var stack = [];

  // Internal search function.
  var internalSearch = function(currentIdentifier) {

    // If we have visited this node, return whether or not it is the one we
    // are looking for.
    if (stack.indexOf(currentIdentifier) !== -1) {
      return currentIdentifier === identifier;
    }

    stack.push(currentIdentifier);

    // Check all of the child nodes to see if they contain the node we are
    // looking for.
    var found = definitions[currentIdentifier].some(internalSearch);

    // Remove the current node from the stack if it's children do not
    // contain the node we are looking for.
    if (!found) {
      stack.splice(stack.indexOf(currentIdentifier), 1);
    }

    return found;
  };

  // If there isn't a cyclic dependency then we return an empty array,
  // otherwise we return the stack.
  return internalSearch(identifier) ? stack.concat(identifier) : [];
}

And some not-so great code for doing the tests:

[
  {
    name: 'Non-cyclic',
    definitions: {
      'A': ['B', 'C'],
      'B': [],
      'C': ['D'],
      'D': []
    },
    identifier: 'A',
    expected: []
  },
  {
    name: 'Cyclic',
    definitions: {
      'A': ['B', 'C'],
      'B': [],
      'C': ['D'],
      'D': ['A']
    },
    identifier: 'A',
    expected: ['A', 'C', 'D', 'A']
  }
].forEach(function(test) {
  var result = findCyclicDependencies(test.definitions, test.identifier),
      passed = true;

  if (test.expected.length === result.length) {
    for (var i = 0; i < test.expected.length; i++) {
      if (test.expected[i] !== result[i]) {
        passed = false;
        break;
      }
    }
  } else {
    passed = false;
  }

  if (passed) {
    console.log(test.name + ': pass');
  } else {
    var message = test.name + ': fail\n' +
                  '  Got: ' + JSON.stringify(result) + '\n' +
                  '  Expected: ' + JSON.stringify(test.expected);

    console.warn(message);
  }
});

I'm not all that bothered about the quality of the test code as it's mainly for demonstration purposes to show my function works.

One thing I'm not sure about with my code (that I'm not even sure is in the scope of Code Review):

Is there any case where found is false but the stack doesn't contain currentIdentifier (i.e. stack.indexOf(currentIdentifier) === -1? I'm wondering if I need to check whether or not currentIdentifier is in the stack before trying to remove it, as trying to remove something not present ends up with the last element being removed erroneously (indexOf returns -1 and splice(-1, 1) removes the last element from the array).


texts: Including the necessary polyfills for every combination of browser support

texts:
My project uses a Promise polyfill and the fetch polyfill, that I am only including if the browser does not yet support it

// Browser doesn't have Promise
if (!window.Promise) {
  require(['es6-promise'], function(promise) {
    promise.polyfill();
    // Browser doesn't have Promise or fetch
    if (!window.fetch) {
      require(['fetch'], function(fetch) {
        run();
      });

    // Browser doesn't have Promise but does have fetch
    } else {
      run();
    }
  });
// Browser has Promise but doesn't have fetch
} else if (!window.fetch) {
  require(['fetch'], function(fetch) {
    run();
  });
// Browser has Promise and fetch
} else {
  run();
}

This accounts for every permutation of browser support for Promise and fetch, but it seems like a verbose way of doing things. Is there a better to dynamically load these polyfills?


texts:
I use zypper to download and install for openSUSE Tumbleweed (much like everyone else of course). Unfortunately it downloads packages serially, and having about a thousand packages to update a week, it gets quite boring. Also, while zypper can download packages one-by-one in advance, it can't be called concurrently. I found the libzypp-bindings project but it is discontinued. I set myself to improve the situation.

Goals:

Download all repositories in parallel (most often different servers);
Download up to MAX_PROC (=6) packages from each repository in parallel;
Save packages where zypper picks them up during system update: /var/cache/zypp/packages;
Alternatively, download to $HOME/.cache/zypp/packages;
Avoid external dependencies, unless necessary.

Outline:

Find the list of packages to update;
Find the list of repositories;
For each repository:

Keep up to $MAX_PROC curl processes downloading packages.

Copy files to default package cache;

#!/bin/bash

MAX_PROC=6

function repos_to_update () {
    zypper list-updates | grep '^v ' | awk -F '|' '{ print $2 }' | sort --unique | tr -d ' '
}

function packages_from_repo () {
    local repo=$1

    zypper list-updates | grep " | $repo " | awk -F '|' '{ print $6, "#", $3, "-", $5, ".", $6, ".rpm" }' | tr -d ' '
}

function repo_uri () {
    local repo=$1

    zypper repos --uri | grep " | $repo " | awk -F '|' '{ print $7 }' | tr -d ' '
}

function repo_alias () {
    local repo=$1

    zypper repos | grep " | $repo " | awk -F '|' '{ print $2 }' | tr -d ' '
}

function download_package () {
    local alias=$1
    local uri=$2
    local line=$3
    IFS=# read arch package_name <<< "$line"

    local package_uri="$uri/$arch/$package_name"
    local local_dir="$HOME/.cache/zypp/packages/$alias/$arch"
    local local_path="$local_dir/$package_name"
    printf -v y %-30s "$repo"
    printf "Repository: $y Package: $package_name\n"
    if [ ! -f "$local_path" ]; then
        mkdir -p $local_dir
        curl --silent --fail -L -o $local_path $package_uri
    fi
}

function download_repo () {
    local repo=$1

    local uri=$(repo_uri $repo)
    local alias=$(repo_alias $repo)
    local pkgs=$(packages_from_repo $repo)
    local max_proc=$MAX_PROC
    while IFS= read -r line; do
        if [ $max_proc -eq 0 ]; then
            wait -n
            ((max_proc++))
        fi
        download_package "$alias" "$uri" "$line" &
        ((max_proc--))
    done <<< "$pkgs"
    wait
}

function download_all () {
    local repos=$(repos_to_update)
    while IFS= read -r line; do
        download_repo $line &
    done <<< "$repos"
    wait
}

download_all
sudo cp -r ~/.cache/zypp/packages/* /var/cache/zypp/packages/

There's 2 or 3 places where grep/tr are subject to issues, but the nature of the data doesn't require much more than that.


texts: Normalizing `DateTime` values to strings

texts:
I have this as part of a project to normalize DateTime values to more readable strings, localized to the relative time in the past that they happened.
It allows you to make several customizations. If you don't want a time to show up, specify "" for the timeFormat, etc. You can change the reference DateTime so that you can measure values between any two DateTime points.
The idea is to put them in forms like:

Event happened just now
Event happened 29 minutes ago
Event happened yesterday at 3:54 pm
etc

I'm looking for any and all improvements (as per the standard rules).
I assume my use of optional statements is less than idea, but I'm open to any and all suggestions about everything here.
public static string ToNormalizedString(this DateTime DateTime, DateTime? reference = null, string dateFormat = "MMM d, yyyy", string timeFormat = "h:mm tt", string preDateString = "", string preTimeString = "at", bool capitalizeModifiers = true)
{
    string result = "";

    DateTime referenceDateTime = DateTime.UtcNow;

    if (reference.HasValue)
    {
        referenceDateTime = reference.Value;
    }

    if (DateTime.Date == referenceDateTime.Date)
    {
        TimeSpan TimeDifference = referenceDateTime - DateTime;

        if (TimeDifference < new TimeSpan(0, 1, 0))
        {
            result = (capitalizeModifiers ? "Just now" : "just now");
        }
        else if (TimeDifference < new TimeSpan(0, 2, 0))
        {
            result = (capitalizeModifiers ? "About a minute ago" : "about a minute ago");
        }
        else if (TimeDifference < new TimeSpan(1, 0, 0))
        {
            result = (capitalizeModifiers ? "About " : "about ") + Math.Ceiling(TimeDifference.TotalMinutes).ToString() + " minutes ago";
        }
        else
        {
            result = (capitalizeModifiers ? "About " : "about ") + Math.Ceiling(TimeDifference.TotalHours).ToString() + " hours ago";
        }
    }
    else if (DateTime.Date.AddDays(1) == referenceDateTime.Date)
    {
        result = (capitalizeModifiers ? "Yesterday at " : "yesterday at ") + DateTime.ToString(timeFormat);
    }
    else if (DateTime.Date.AddDays(7) > referenceDateTime.Date)
    {
        result = preDateString + DateTime.DayOfWeek.ToString() + (timeFormat == "" ? "" : " " + preTimeString + " " + DateTime.ToString(timeFormat));
    }
    else
    {
        result = preDateString + DateTime.ToString(dateFormat) + (timeFormat == "" ? "" : " " + preTimeString + " " + DateTime.ToString(timeFormat));
    }

    return result;
}

As usual this code is free to anyone who wishes to use it.


texts:
I have the following datastructure to perform a longest-match lookup via nested dicts. For example. cs['a b c d'] with a and a b c being in the structure will return a b c and the remainder d.

I wonder if there's a better way to implement the _lookup method and possible the __setitem__ method. I'm also not completely sure if the way __getitem__ works (returning a tuple with the data in the structure and the remainder of the input) isn't a bit confusing when used with the [] operator.

class CommandStorage(object):
    """Stores multi-part commands.

    Performs fast lookups returning the command and any arguments which were
    not part of the command.
    """

    def __init__(self, commands={}):
        self._root = {}
        self._commands = {}
        for cmd, func in commands:
            self[cmd] = func

    def _lookup(self, line):
        parts = line.split(' ')
        found = None
        found_container = None
        container = self._root
        command_parts = 0
        for i, part in enumerate(parts):
            if part not in container:
                return found_container, found, parts[command_parts:]
            container = container[part]
            if None in container:
                found_container = container
                found = container[None]
                command_parts = i + 1
        return found_container, found, parts[command_parts:]

    def __setitem__(self, cmd, func):
        container = self._root
        parts = cmd.split(' ')
        for part in parts:
            container = container.setdefault(part, {})
        if None in container:
            raise ValueError('Command %s already exists' % cmd)
        container[None] = func
        self._commands[cmd] = func

    def __getitem__(self, line):
        return self._lookup(line)[1:]

    def __contains__(self, item):
        cmd, args = self[item]
        return cmd is not None and not args

    def __delitem__(self, cmd):
        if cmd not in self:
            raise KeyError(cmd)
        container = self._lookup(cmd)[0]
        del container[None]
        del self._commands[cmd]

    def __iter__(self):
        return iter(self._commands)

    def __len__(self):
        return len(self._commands)

    def __nonzero__(self):
        return bool(self._commands)

    def iterkeys(self):
        return self._commands.iterkeys()

    def iteritems(self):
        return self._commands.iteritems()

    def itervalues(self):
        return self._commands.itervalues()

    def __repr__(self):
        return '<CommandStorage(%r)>' % self._commands.keys()

The full code (with a doctest) is in this gist as the doctest is not really relevant for the question


texts:
I have this code to remove nodes in a linked list which have odd values. This works well but I want to fine tune it for better reading. Can you please suggest improvements?

public class MyLinkedList
{
    public int data;
    public MyLinkedList next;

    public MyLinkedList(int v)
    {
        this.data = v;
    }

    //public void add(int i)
    //{
    //    this.next = new MyLinkedList(i);
    //    this.next.next = null;
    //}

    public void printLL()
    {
        MyLinkedList mmm = this;
        while (mmm != null)
        {
            Console.Write(mmm.data);
            Console.Write("->");
            mmm = mmm.next;
        }
    }
}

public static void deleteOdd(ref MyLinkedList mll)
{
    MyLinkedList head, previous, curr;
    head = mll;
    while (head.data % 2 != 0)
    {
        head = head.next;
    }
    mll = head;

    previous = head;
    curr = previous.next;

    while (curr != null)
    {
        if (curr.data % 2 != 0)
        {
            previous.next = curr.next;
            curr = previous.next;
        }
        else
        {
            previous = previous.next;
            curr = curr.next;
        }
    }
}

static void Main(string[] args)
    {
        MyLinkedList myll1 = new MyLinkedList(1); MyLinkedList myll2 = new MyLinkedList(3);
        MyLinkedList myll3 = new MyLinkedList(4); MyLinkedList myll4 = new MyLinkedList(4);
        MyLinkedList myll5 = new MyLinkedList(5); MyLinkedList myll6 = new MyLinkedList(6);
        MyLinkedList myll7 = new MyLinkedList(5); MyLinkedList myll8 = new MyLinkedList(6);
        MyLinkedList myll9 = new MyLinkedList(6); MyLinkedList myll10 = new MyLinkedList(9);
        MyLinkedList myll11 = new MyLinkedList(11); MyLinkedList myll12 = new MyLinkedList(12);

        myll1.next = myll2; myll2.next = myll3; myll3.next = myll4; myll4.next = myll5;
        myll5.next = myll6; myll6.next = myll7; myll7.next = myll8; myll8.next = myll9;
        myll9.next = myll10; myll10.next = myll11; myll11.next = myll12; myll12.next = myll12; myll12.next = null;

    myll1.printLL();
    Console.WriteLine();
    deleteOdd(ref myll1);
    Console.WriteLine();
    myll1.printLL();
}


texts:
I've been using this method to test file-system functions as an alternative to mock-fs due to its lack of symlink support. I'd love to hear what others think and the possible dangers, pitfalls, or improvements.

var CWD = process.cwd()
var assert = require('assert')
var path = require('path')
var os = require('os')
var Promise = require('bluebird')
var fs = Promise.promisifyAll(require('fs-extra'))
// note this is a custom verison of fs-extra :(

// [[fileName, contents], expectation]
var files = [
  ['hello.js', ''],
  ['folder/file-require-local.js', 'var local = require(\'../file-require-sibling.js\')'],
  ['file-require-sibling.js', 'var local = require(\'./file-require-underscore.js\')'],
  ['file-require-underscore.js', 'var underscore = require(\'underscore\')'],
  ['file-import-underscore.js', 'import underscore from \'underscore\''],
  ['file-require-path.js', 'var path = require(\'path\')'],
  ['file-require-local.js', 'var hello = require(\'./hello.js\')'],
  ['file-import-local.js', 'import hello from \'./hello.js\''],
  ['file-require-json.js', 'var pkg = require(\'./package.json\')'],
  ['file-multi-file.js', (function () {
    var file = []
    file.push('var underscore = require(\'underscore\')')
    file.push('var path = require(\'path\')')
    file.push('var hello = require(\'./hello.js\')')
    return file.join('\n')
  }())]
]

/* global describe, before, after, beforeEach, afterEach, it */

var ROOT_DESC = 'recursive-deps'
var TEST_DIR = path.join(os.tmpdir(), ROOT_DESC)

describe(ROOT_DESC, function () {

  before(function () {
    fs.emptyDirSync(TEST_DIR)
    process.chdir(TEST_DIR)
  })

  beforeEach(function () {
    return Promise.map(files, function (file) {
      return fs.ensureFileAsync.apply(null, file)
    })
  })

  afterEach(function () {
    fs.emptyDirSync(TEST_DIR)
  })

  after(function () {
    process.chdir(CWD)
    fs.removeSync(TEST_DIR)
  })

  it('should have mock file system', function () {
    var dir = fs.readdirSync(TEST_DIR)
    var expected = [
      'file-import-local.js',
      'file-import-underscore.js',
      'file-multi-file.js',
      'file-require-json.js',
      'file-require-local.js',
      'file-require-path.js',
      'file-require-sibling.js',
      'file-require-underscore.js',
      'folder',
      'hello.js'
    ]
    assert.equal(process.cwd().indexOf(TEST_DIR) > -1, true)
    assert.deepEqual(dir, expected)
  })

})


texts:
The following are an example of methods supported by a proprietary device:

Monitor
ControlTemp
PutPeakInfo
GetPeakInfo

I have a class that builds the packets for the above corresponding methods:

GetMonitorPacket
GetControlTempPacket
GetPutPeakInfo

Example:

public byte[] GetMonitorPacket(int ddcNum)
    {
        byte[] monitorPacket = new byte[MONITOR_PACKET_BYTE_COUNT];
        Buffer.BlockCopy(START_HEADER_BYTES, 0, monitorPacket, 0, START_HEADER_BYTES.Count());
        monitorPacket[2] = (byte) ddcNum;
        monitorPacket[3] = 0x01;
        byte checksum = 0;
        foreach (var b in monitorPacket)
        {
            checksum = (byte) (((ushort) checksum + (ushort) b) & 0xff);
        }
        checksum = (byte) (checksum ^ 0x55);
        monitorPacket[4] = checksum;
        return monitorPacket;
    }

All they do is return the bytes in proper format, which then will be sent to the proprietary device via TCP to call the methods. Now I'm screwed on my naming convention for GetPeakInfo method.

How do I name this? What about GetGetPeakInfoPacket (two gets for a method name)?
Do I break the naming convention here as an exception case and drop one of the gets?
Do I use some other naming convention?

Actually, GetPutPeakInfo sounds a little bit weird too, but at least there's no duplication.


texts:
How is this function?

/// Extension methods used by RedViewerLibrary.
internal static class Extensions
{
    /// A string array extension method that gets the human readable enumerated version of the array.
    /// <param name="items">The strings to act on.</param>
    /// <returns>A string containing the enumerated results.</returns>
    /// <example>null => ""</example>
    /// <example>{} => ""</example>
    /// <example>{"foo"} => "foo"</example>
    /// <example>{"foo", "bar"} => "foo, and bar"</example>
    /// <example>{"foo", "bar", "baz"} => "foo, bar, and baz"</example>
    internal static string GetEnumerated(this string[] items)
    {
        if (items == null || items.Length == 0)
        {
            return string.Empty;
        }
        else if (items.Length == 1)
        {
            return items[0];
        }

        const string COMMA_SPACE = ", ";
        const string AND_STRING = "and ";

        var totalNamesLength = items.Aggregate(0, (oldValue, name) => name.Length + oldValue);
        var numberOfCommaSpaces = items.Length - 1;
        var commaSpacesLength = numberOfCommaSpaces * COMMA_SPACE.Length;
        var predictedLength = totalNamesLength + commaSpacesLength + AND_STRING.Length;
        var sb = new StringBuilder(predictedLength);

        int loopCount = items.Length - 1;
        sb.Append(items[0]);
        for (int idx = 1; idx != loopCount; ++idx)
        {
            sb.Append(COMMA_SPACE);
            sb.Append(items[idx]);
        }

        sb.Append(COMMA_SPACE);
        sb.Append(AND_STRING);
        sb.Append(items[items.Length - 1]);
        return sb.ToString();
    }
}


texts: PDO multiple queries with 2 different tables

texts:
I joined this 2 tables and dropped the user_id afterwards. I am defining the user_id elsewhere in my code based on my session/cookies and I do not want to return this value as a global. Is there a more compact or elegant way to write this:

public function test($user_id)
{
    $stmt = $this->conn->prepare("CREATE TEMPORARY TABLE `temp_tb`
                                  SELECT a.*, b.token
                                  FROM $this->tableName a
                                  LEFT JOIN `requests` b
                                  ON a.$this->user_id = b.uid
                                  WHERE $this->user_id=:user_id ");
    $stmt->execute(array(":user_id"=>$user_id));
    $stmt = $this->conn->prepare("ALTER TABLE `temp_tb` DROP $this->user_id ");
    $stmt->execute();
    $stmt = $this->conn->prepare("SELECT * FROM `temp_tb` ");
    $stmt->execute();
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

Thank you!


texts: Extracting time duration in the session from 30 million rows

texts:
I am looking for making my code faster. I am working on yoochoose recsys 2015 dataset.. and trying to perform some transformations.. [recsys2015], it has got 30 million plus rows of data. The goal of my code is to extract time duration in the session with the help of python, and the day , hour segment etc, however I realized that my code with pandas is taking hell lot of time, any alternative approaches is well appreciated
below is sample data and code
Data:
sessioid,timestamp,itemid,category
1,2014-04-07T10:51:09.277Z,214536502,0
1,2014-04-07T10:54:09.868Z,214536500,0
1,2014-04-07T10:54:46.998Z,214536506,0
1,2014-04-07T10:57:00.306Z,214577561,0
2,2014-04-07T13:56:37.614Z,214662742,0
2,2014-04-07T13:57:19.373Z,214662742,0
2,2014-04-07T13:58:37.446Z,214825110,0
2,2014-04-07T13:59:50.710Z,214757390,0

Code
import pandas as pd
import datetime as dt
clickspath='/tmp/gensim/yoochoose/yoochoose-clicks.dat'
buyspath='/tmp/gensim/yoochoose/yoochoose-buys.dat'
clicksdat=pd.read_csv(clickspath,header=None)
clicksdat.columns=['Sid','Timestamp','itemid','itemcategory']
buysdat=pd.read_csv(buyspath,header=None)
buysdat.columns=['Sid','Timestamp','itemid','price','qty']
segment={}
for i in range(24):
    if i<7:
        segment[i]='EM'
    elif i<10:
        segment[i]='M'
    elif i<13:
        segment[i]='A'
    elif i<18:
        segment[i]='E'
    elif i<23:
        segment[i]='N'
    elif i<25:
        segment[i]='MN'
#*******************************************
buyersession=buysdat.Sid.unique()
clickersession=clicksdat.Sid.unique()
with open('/tmp/gensim/yoochooseclick_new.dat','w') as f1:
    for session in clickersession:
        purchased=1 if session in buyersession else 0
        temp=clicksdat[clicksdat.Sid==session]
        maxtime=dt.datetime.strptime(temp.Timestamp.max(),"%Y-%m-%dT%H:%M:%S.%fZ")
        mintime=dt.datetime.strptime(temp.Timestamp.min(),"%Y-%m-%dT%H:%M:%S.%fZ")
        day=maxtime.day
        month=maxtime.month
        noofnavigations=len(temp.Timestamp)-1
        duration=int((maxtime-mintime).total_seconds())
        totalcats=len(temp.itemcategory.unique())
        totalitems=len(temp.itemid.unique())
        timesegment= segment[maxtime.hour]
        segmentchange=1 if (segment[maxtime.hour]!=segment[mintime.hour]) else 0
        f1.write(str(purchased)+','+str(day)+','+str(month)+','+str(noofnavigations)+','+str(duration)+','+str(totalcats)+','+str(totalitems)+','+str(timesegment)+','+str(segmentchange)+'\n')

Note: This works on both Python 2 and Python 3


texts: Partial page refresh Ajax call on button click

texts:
function RequestValidation() {
    $(".RequestTrigger").on("click", function () {
        var selectedButton = $(this);
        var arr = [];

        if ($(this).data('multiple') == true) {

            var ids = $('input:checkbox:checked.check-box').map(function () {
                var value = $(this).data('entityid');

                if (!isNaN(value)) {
                    arr.push(value);
                }
            });
        } else {
            var value = selectedButton.data('entityid');

            if (!isNaN(value)) {
                arr.push(value);
            }
        }

        var data = {
            ids: arr
        };

        $.ajax({
            url: selectedButton.data('url'),
            data: data,
            type: 'post',
            success: function (result) {
                $('#largeModal').modal('hide');
                $('#ApprovalTable').html(result);
                checkBox();
                accountRequestValidation();
            }

        });

    });

};

This functions binds to buttons with .RequestTrigger If the button has a data-attribute called multiple with a value of true the functions gets the entity-id of every checkbox and passes the values to the ajax request or if the value of multiple is false then it just gets the entity-id of the button clicked


texts: TPL Dataflow BatchBlock with Batch Size & Timeout

texts:
I needed BatchBlock with support for timeout (act greedy on what it received at that time) and by some search and study, this is the outcome.

What are drawbacks or rooms for improvement in this code?

class BatchedQueue
{
    static readonly Logger SlotClassLogger = LogManager.GetCurrentClassLogger();
    protected static Logger ClassLogger { get { return SlotClassLogger; } }
}

class BatchedQueue<T> : BatchedQueue
{
    readonly int _interval;
    readonly TimeSpan _loopWait;
    readonly BatchBlock<T> _queue;
    readonly Timer _timer;
    readonly BufferBlock<T> _source;

    public event Action<T[]> Received;

    protected virtual void OnReceived(T[] obj)
    {
        var handler = Received;
        if (handler != null) handler(obj);
    }

    public BatchedQueue(int interval, int size)
    {
        _interval = interval;

        _loopWait = TimeSpan.FromMilliseconds(2.19 * (1.3 + _interval)); //study

        _queue = new BatchBlock<T>(size, new GroupingDataflowBlockOptions { Greedy = true });
        _timer = new Timer(_ => _queue.TriggerBatch());

        var transformer = new TransformBlock<T, T>(v =>
        {
            _timer.Change(_interval, Timeout.Infinite);
            return v;
        });
        transformer.LinkTo(_queue);
        _source = new BufferBlock<T>();
        _source.LinkTo(transformer);

        Utl.SafeTask(Loop, t =>
        {
            if (t == null || t.Exception == null) return;
            ClassLogger.Error(t.Exception);
        }, TaskCreationOptions.LongRunning);
    }

    public virtual void Post(T t) { _source.Post(t); }
    void Loop()
    {
        while (true)
        {
            var buffer = _queue.Receive(_loopWait);
            if (buffer != null) { OnReceived(buffer); }
        }
    }
}