texts: Find The Duplicates using binarySearch python

texts:
I got this interview question from Pramp. You can find it online through their website: https://www.pramp.com/challenge/15oxrQx6LjtQj9JK9XlA

  Find The Duplicates

  Given two sorted arrays arr1 and arr2 of passport numbers, implement a
  function findDuplicates that returns an array of all passport numbers
  that are both in arr1 and arr2. Note that the output array should be
  sorted in an ascending order.

  Let N and M be the lengths of arr1 and arr2, respectively. Solve for
  two cases and analyze the time & space complexities of your solutions:
  M ≈ N - the array lengths are approximately the same M ≫ N - arr2 is
  much bigger than arr1.

  Example:

  input:  arr1 = [1, 2, 3, 5, 6, 7], arr2 = [3, 6, 7, 8, 20]

  output: [3, 6, 7] # since only these three

def find_duplicates(arr1, arr2):
    output = []

    for val in arr1:
        if b_search(arr2, val):
            output.append(val)

    return output

def b_search(A, value):
    lower_ind = 0
    upper_ind = len(A) - 1

    while lower_ind <= upper_ind:
        middle_ind = lower_ind + (upper_ind - lower_ind) // 2

        if A[middle_ind] == value:
            return value
        elif A[middle_ind] > value:
            upper_ind = middle_ind - 1
        elif A[middle_ind] < value:
            lower_ind = middle_ind + 1
    return False

#I also tested it against the test cases, and it passed all of the test cases.

# Input: [1, 2, 3, 5, 6, 7], [3, 6, 7, 8, 20]

print(find_duplicates([1, 2, 3, 5, 6, 7], [3, 6, 7, 8, 20]))
# Output: [3,6,7]

Test Case #1
Input: [11], [11],
Expected: [11],
Actual: [11]
Test Case #2
Input: [1,3,5,9], [2,4,6,10],
Expected: [],
Actual: []
Test Case #3
Input: [1,2,3,5,6,7], [3,6,7,8,20],
Expected: [3,6,7],
Actual: [3, 6, 7]
Test Case #4
Input: [1,2,3,5,6,7], [7,8,9,10,11,12],
Expected: [7],
Actual: [7]
Test Case #5
Input: [10,20,30,40,50,60,70,80], [10,20,30,40,50,60],
Expected: [10,20,30,40,50,60],
Actual: [10, 20, 30, 40, 50, 60]
Test Case #6
Input: [10,20,30,40,50,60,70], [10,20,30,40,50,60,70],
Expected: [10,20,30,40,50,60,70],
Actual: [10, 20, 30, 40, 50, 60, 70]


texts:
Could the performance of this function be optimized (without making the code much longer)?

The function zips two arrays into another.

function zip(p,q) {
  if( p.length > 1 || q.length > 2) {
    return ([[p[0],q[0]]]).concat(zip(p.slice(1),q.slice(1)));
  } else {
    return ([[p[0],q[0]]]);
  }
}

How exactly does the slice work? Is it immutable, like getting the tail in Haskell?
What values are inside the value returned by .concat()? Are these copy-constructed values from references, or are these references and are copied when a new array is constructed with the call to .concat()?


texts: Filtering a dictionary by subject of definitions

texts:
I am writing a function to filter a "dictionary" by the "subject" of its definitions.

The dictionary data structure is a hash-map of this kind:

{ "word1" {:foo :bar
           :definitions [{:definition "def1" :subject ["Subject1" "Subject2"]}
                         {:definition "def2" :subject ["Subject3" "Subject1"]}]}
  "word2" {:foo :baz
           :definitions [{:definition "def3" :subject "Subject2"}
                         {:definition "def4" :subject ["Subject2" "Subject3"]}]}

The function needs to return a new dictionary with only definitions of the specified subject (no word entry if no definition available).

I came up with two (working) different functions that returns the same exact result.
The first version uses map, the second version uses loop/recur.

map version:

(defn filter-by-subject [dict subject]
  (apply hash-map
         (flatten (map (fn [[word entry]]
                           (let [definitions (definitions-for-subject entry subject)]
                              (if (> (count definitions) 0)
                                  [word (assoc entry :definitions definitions)]
                                  [])))
                       dict))))

loop/recur version:

(defn filter-by-subject2 [dict subject]
  (loop [old-dict dict
         new-dict {}]
     (if-let [[word entry] (first old-dict)]
             ;; then
             (recur (dissoc old-dict word)
                    (let [definitions (definitions-for-subject entry subject)]
                       (if (> (count definitions) 0)
                           (assoc new-dict word
                                  (assoc entry :definitions definitions))
                           new-dict)))
             ;; else
             new-dict)))

Supporting functions:

(defn subjects-of-definition [definition]
  (let [sbjs (:subject definition)]
     (if (coll? sbjs)
         sbjs
         [sbjs])))

(defn definitions-for-subject [entry subject]
  (into [] (filter (fn [definition]
                       (some #{subject} (subjects-of-definition definition)))
                   (:definitions entry))))

I would like to hear your opinion on these functions.

Do they follow the common "functional style"?
Which version of the two do you find more readable, clear, understandable or even faster?

UPDATE

A little clarification.
If a word has two definitions, one of subjects A and B, and one of subjects B and C, and we filter by subject A, the resulting dictionary will have only the first definition of word (the one of subjects A and B).

Some examples:

=> (def dictionary { "Bit" { :definitions [
                                { :definition "A unit of information storage on a computer"
                                  :subject "IT" }
                                { :definition "Beijing Institute of Technology"
                                  :subject ["Acronyms" "Education"] }] }
                     "Matrix" { :definitions [
                                { :definition "A rectangular array of numbers, symbols or expressions"
                                  :subject "Mathematics"}
                                { :definition "A 1999 science fiction film"
                                  :subject "Movies"}]}})
#'user/dictionary

=> (filter-by-subject dictionary "Education")
{"Bit" {:definitions [{:subject ["Acronyms" "Education"], :definition "Beijing Institute of Technology"}]}}

=> (filter-by-subject dictionary "IT")
{"Bit" {:definitions [{:subject "IT", :definition "A unit of information storage on a computer"}]}}

=> (filter-by-subject dictionary "Movies")
{"Matrix" {:definitions [{:subject "Movies", :definition "A 1999 science fiction film"}]}}

(note that, for example, filtering by "Education" deletes the "IT" definition of "Bit".)


texts:
I have some efficient methods that recursively creates a tree structure (NSTreeNode) of by looping recursively over a directory structure. The result is displayed in a NSOutlineView. This works well with one exception where I have to non-concurrently update a NSMutableDictionary that holds the structure of the tree. This turns out to be a real bottleneck in my program.

I am wondering if anyone has suggestions for how I can make this method more efficient or avoid the whole method.

-(void) addDictionaryItem:(NSString *) mykey withURL:(NSString *)myurl isDir:(BOOL) myIsDir andLR:(NSString *)LR
{
    NSDictionary *mydict=nil;

    @synchronized(@"concurrentDictAccess") {
        mydict = [self.dict objectForKey:mykey];
    }
    if ( mydict !=nil) {

            NSMutableArray *myarray = [mydict objectForKey:@"myarray"];
            NSMutableArray *myarrayIsDir = [mydict objectForKey:@"isdir"];
            NSMutableArray *myarrayLR = [mydict objectForKey:@"LR"];

            if (![myarray containsObject:myurl]){
                [myarray addObject:myurl];
                [myarrayLR addObject:LR];
                [myarrayIsDir addObject:[NSNumber numberWithBool:myIsDir]];
            }
        }
    else {

        NSMutableArray *arrayOfFiles = [NSMutableArray array];
        [arrayOfFiles addObject:myurl];

        NSMutableArray *arrayIsDir = [NSMutableArray array];
        [arrayIsDir addObject:[NSNumber numberWithBool:myIsDir]];

        NSMutableArray *arrayOfLR = [NSMutableArray array];
        [arrayOfLR addObject:LR];

        NSMutableDictionary *attrDict = [NSMutableDictionary   dictionaryWithObjectsAndKeys:arrayOfLR, @"LR",
                                     arrayOfFiles, @"myarray", arrayIsDir, @"isdir",
                                     nil];
        @synchronized(@"concurrentDictAccess") {
             [self.dict setObject:attrDict forKey:mykey];
        }
    }
}


texts: common lisp: nested loop beautification (checkboard texture generator)

texts:
I've written a small code snippet that generates checkboard texture using cl-opengl.

(defun init-texture (tex)
    (gl:bind-texture :texture-2d tex)
    (gl:tex-parameter :texture-2d :texture-min-filter :nearest)
    (gl:tex-parameter :texture-2d :texture-mag-filter :nearest)
    (print *test-texture*)
    (let* ((tex-w 16) (tex-h 16) (pixel-size 4)
        (pixel-data (make-array (* (* tex-w tex-h) pixel-size) :element-type '(unsiged-byte 8) :adjustable nil :initial-element 0)))
    (loop for y from 0 to (- tex-h 1) do
        (let ((line-offset (* (* tex-w pixel-size) y)))
            (loop for x from 0 to (- tex-w 1) do
                (let ((x-offset (+ line-offset (* x pixel-size))) (c (if (oddp (+ x y)) 255 0)))
                    (setf (aref pixel-data x-offset) 255)
                    (setf (aref pixel-data (+ x-offset 1)) c)
                    (setf (aref pixel-data (+ x-offset 2)) c)
                    (setf (aref pixel-data (+ x-offset 3)) 255)))))
    (gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))

Problem:
it looks ugly and is unnecessarily verbose, especially (- tex-h 1) and 4 setf in a row.

How can I "beautify"/simplify this?

Program logic:

generate 1d array of (unsigned-byte 8). Array size is tex-w*tex-h*pixel-size, where tex-w is 16, tex-h is 16, pixel-size is 4. 1 pixels. That's 16x16 texture data in rgba format where every pixel takes 4 elements.
Fill array. If (oddp (+ x y)), put white pixel, otherwise put blue pixel.


texts: Output the average values of binned columns in Excel VBA

texts:
This code is meant to run through a column of values, bin the values based on specified ranges, then output the average value of each bin.  The problem is the code is running quite slowly (approximately 30 min for around 100000 values).  I am definitely a beginner at coding and was hoping there was some way to speed this code along.

Sub BinValues()
'binns seperation distance values for the creation of variogram

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Dim Cell As Object
Dim R1 As Range
Dim R2 As Range
Dim rng As Range
'define range before running
Set rng = Range("A1:A105570")
Dim K, n, L As Integer
'n is equal to the number of lags
'L is the lag size
n = 12
L = 600
For K = L To (n * L) Step 600
    For Each Cell In rng
    Dim min As Integer
    min = K - L
    'upper bound exclusive and lower bound inclusive
        If Cell.Value >= min And Cell.Value < K Then
            If R1 Is Nothing Then
                Set R1 = Range(Cell.Address)
            Else
                Set R1 = Union(R1, Range(Cell.Address))
            End If
            Cells((K / L), 5) = WorksheetFunction.Average(R1)
        End If

    Next
    Set R1 = Nothing
Next

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

End Sub


texts: Solution discussion on the best way to reverse a number in Python

texts:
I'm practicing some python exercise and I have some doubts about the solution of reversing a number. Example, 42 -> 24, -314 -> -413.
The book has this solution:

def reverse(x: int) -> int:
  result, x_remaining = 0, abs(x)
  while x_remaining:
      result = result * 10 + x_remaining % 10
      x_remaining //= 10
  return -result if x < 0 else result

My solution:
def reverse_digit(x: int) -> int:
  s = str(abs(x))
  result = s[::-1]
  if x >= 0:
    return int(result)
  else:
    return int("-" + result)

The book says that converting the number to string would be a brute-force solution but don't they have the same time complexity, O(n)?
Is the book solution that much better than mine (that in my opinion is much simpler and easy to read)?


texts: Pythonic indenting `with` statement blocks

texts:
Python doesn't remove the variables once a scope is closed (if there's such a thing as scope in Python, I'm not sure). I mean, once I finish a for variable in range(1, 100), the variable is still there, with a value (99 in this case).

Now I usually indent a whole block when I use the with ... as statement. But should I close the file and end the indentation as soon as I'm done with it? I mean, should I write:

with open('somefile', 'r') as f:
    newvar = f.read()

newvar.replace('a', 'b') # and etc

Instead of:

with open('somefile', 'r') as f:
    newvar = f.read()
    newvar.replace('a', 'b') # and etc


texts:
I'm trying to essentially replace an element and make it transition smoothly to the new size... I started off trying to work with the appended element itself, but the padding and margins made that difficult, so I switched to using a container.

var template = "
I've replaced the button
and in a very smooth
fashion!
";

var doAnimation = function(e) {
    var parent = $(this).parent();
    var oldHeight = parent.height();

    $(this).fadeOut(400, function() {
        this.remove();

        var paragraph = $(template).appendTo(parent);
        var newHeight = parent.height();

        paragraph.hide().fadeIn();
        parent.height(oldHeight).animate({height: newHeight});
    });
}

$(document).on('click', 'button', doAnimation);

Here is the demo on jsFiddle: first attempt, second attempt

Is there a better way to go about doing this and how would I extract it to something that's reusable?

Edits:

3rd attempt - simply extracted the template to the HTML...

4th attempt - added some data attributes and string replacements.


texts:
I wrote this to query the Trello API to find the cards that haven't been updated in 7 days and send an email notification to the card's members as a digest.

I'm a Node.JS & client-side JS dev, and this is my first Python script. I'd really appreciate any suggestions around best practices, how it could be more modular/reusable, etc.

import os
from os.path import join, dirname
from dotenv import load_dotenv
from urllib import urlencode
import json
import urllib2
from datetime import datetime
import dateutil.parser
import pytz
import mandrill
from jinja2 import Environment, PackageLoader

# Load environment variables
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

MIN_DAYS = os.environ.get("MIN_DAYS")
TRELLO_KEY = os.environ.get("TRELLO_KEY")
TRELLO_TOKEN = os.environ.get("TRELLO_TOKEN")
TRELLO_BOARD = os.environ.get("TRELLO_BOARD")
MANDRILL_KEY = os.environ.get("MANDRILL_KEY")
MSG_FROM_EMAIL = os.environ.get("MSG_FROM_EMAIL")
MSG_FROM_NAME = os.environ.get("MSG_FROM_NAME")
MSG_SUBJECT = os.environ.get("MSG_SUBJECT")
MEMBER_EMAILS = os.environ.get("MEMBER_EMAILS")

mandrill_client = mandrill.Mandrill(MANDRILL_KEY)

# Prepare template
template_env = Environment(loader=PackageLoader(__name__, "templates"))
template = template_env.get_template("reminder_email.html")

# Split member emails into a dict
member_emails = {}
member_email_lines = MEMBER_EMAILS.split(",")
for member_email_line in member_email_lines:
    member_email_line_parts = member_email_line.split(":")
    member_emails[member_email_line_parts[0].strip()] = member_email_line_parts[1].strip()

# Querystring parameters
params = {
    "key": TRELLO_KEY,
    "token": TRELLO_TOKEN,
    "fields": "name,url,dateLastActivity",
    "members": "true"
}

# Construct trello URL and fetch
url = "https://api.trello.com/1/boards/" + TRELLO_BOARD + "/cards?" + urlencode(params)
cards = json.load(urllib2.urlopen(url))

today = datetime.now(pytz.utc)
members = {}

# For each card that's older than a week
for card in cards:
    dateLastActivity = dateutil.parser.parse(card[u'dateLastActivity'])
    if abs(today - dateLastActivity).days > int(MIN_DAYS):
        # Add card to each member's list
        for member in card[u'members']:
            username = str(member[u'username'])
            if username not in members:
                members[username] = []
            members[username].append(card)

# For each member
for username in members:
    if username in member_emails:
        # Build message data
        message = {
            "subject": MSG_SUBJECT,
            "from_email": MSG_FROM_EMAIL,
            "from_name": MSG_FROM_NAME or MSG_FROM_EMAIL,
            "to": [{
                "email": member_emails[username],
                "name": username,
                "type": "to"
            }],
            # Construct HTML from template
            "html": template.render(num_days=MIN_DAYS, cards=members[username])
        }

        # Send email
        try:
            result = mandrill_client.messages.send(message=message)
            print result
        except mandrill.Error, e:
            print 'A mandrill error occurred: %s - %s' % (e.__class__, e)
            raise


texts:
I have these struct(s) to keep data about temperature measurement:

// data structure representing day
struct Day{
   vector<double>hour;
   Day();
};
Day::Day(): hour(24){
   for(int i=0; i< hour.size();++i) hour[i]=not_a_reading;
}

// data structure representing month
struct Month{
    int month;
    vector<Day>day;
    Month(): month(not_a_month),day(32) { }
};

// data structure representing year
struct Year{
    int year;
    vector<Month>month;
    Year(): month(12) { }
};

// vector holding measured data
vector<Year>yrs;

I am trying to write a program to print all the data inside yrs. Here is what I got so far:

void print_year(ostream os, vector<Year>& v){
for(size_t i=0; i<v.size(); ++i){
    os << "{year " << v[i].year;
    for (size_t j=0; j<v[i].month.size(); ++j){
        os << " {month " << v[i].month[j].month;
        for (size_t k=0; k<v[i].month[j].day.size();++k){
            os << '(' <<v[i].month[j].day <<" "<< v[i].month[j].day[k].hour;
            //--^^---- (No << operator matches these operands) WHY?
            os  << ') ';
            }
        os << "}";
        }
    os << "}";
    }
}

If I have one measurement on: 10th of Jan 1992 at 10 o'clock with temperature 61.6 Fahrenheit and two on: 11th and 22th of Feb 1992 with temperatures: 64 and 65.2. The output (format) will be: (year 1992 { month jan ( 10 61.5)} {month feb (11 64) (22 65.2)})

I'm probably using the vector access operator[] wrong.

I was trying to fix it and got to this:

void print_year(ostream os, vector<Year>& v){
for(size_t i=0; i<v.size(); ++i){
    os << "{year " << v[i].year;
    for (size_t j=0; j<v[i].month.size(); ++j){
        os << " {month " << month_input_tb[v[i].month[j].month];
        for (size_t k=0; k< v[i].month[j].day.size();++k){
            os <<  '('<< k <<" "; // loop counter coincides with day of the month
            for (size_t z=0; z < v[i].month[j].day[k].hour.size(); ++z){
                os << v[i].month[j].day[k].hour[z];
                os  << ')';
        }
        os << "}";
    }
    os << "}";
}

}

Then I saw your (Loki Astari) answer and I am writing separate << operators now.


texts: Detecting when the contents of a web page changes

texts:
This is the code I'm using at the moment

/*
 * Adjust content height so that it always fills browser height
 *
 * written by Tom Jenkinson
 */

jQuery(document).ready(function() {

    refreshContentSize(); //run initially

    $(window).resize(function() { //run whenever window size changes
        refreshContentSize();
    });

    setInterval('refreshContentSize()', 500); // in case content size changes. THIS IS WHAT I WANT TO CHANGE
});

function refreshContentSize()
{
    var startPos = $("#content").position();
    var topHeight = startPos.top;
    var contentHeight = $("#content").outerHeight(true);
    var footerHeight = $("#footer").outerHeight(true);
    var viewportHeight = $(window).height();
    var spaceForContent = viewportHeight - footerHeight - topHeight;

    if (spaceForContent <= contentHeight)
    {
        var newHeight = 0;
    }
    else
    {
        var newHeight = spaceForContent - contentHeight;
    }
    $("#filler").css('height', newHeight);
    return;
}

The site is http://wncba.co.uk/results and the script is at http://wncba.co.uk/results/javascript/fill-pagev2.js.

At the moment you can see that I'm using a timer to keep calling the refreshContentSize(). I am doing this because some of the content on the page can change dynamically meaning the page height will change.

Is there a handle for this like jquery's 'resize' so I don't need the timer?


texts: Documenting and commenting code using xml tags

texts:
I am going to rewrite my AddIn I made for the Autodesk Inventor software. It is supposed to do specific task that are not available by default in the program.

I am not a programmer but a draftsman that is interested in programming, so bare with me.

The reason for me to rewrite my program is to make it better documented and commented. Plus there is alot of code that is duplicated and hardcoded lines that must be removed.

Now I made a small sample for a class that I am doing, and how I think it should be commented and xml documented. Please feel free to comment on ALL the code not only the xml tags.

Imports Inventor

''' <summary>
''' The document object represents the Inventor Document,
''' it allows the you to rapidly access certain values and perform specific tasks
''' </summary>
Public Class Document

    ''' <summary>
    ''' Read-only property that returns the <c>Inventor.Document</c> that is associative with the XT document.
    ''' </summary>
    ''' <example>Document.ReferencedDocument() As Inventor.Document</example>
    Public Overridable ReadOnly Property ReferencedDocument As Inventor.Document

    ''' <summary>
    ''' Creates a new XT document object
    ''' </summary>
    ''' <param name="InventorDocument">The Inventor document where the new XT document will be associated with.</param>
    ''' <example>Dim XTdocument as New Document(InventorDocument As Inventor.Document)</example>
    Public Sub New(ByVal InventorDocument As Inventor.Document)

        ' Store the InventorDocument as ReferencedDocument
        ReferencedDocument = InventorDocument
    End Sub

    ''' <summary>
    ''' Gets the description of the current document
    ''' </summary>
    ''' <returns>string</returns>
    Public Property Description As String
        Get

            ' Set reference to the document property sets
            Dim oPropertySets As PropertySets =
                ReferencedDocument.PropertySets

            ' Set reference to the Design Tracking Property set
            Dim oDesignTrackingPropertySet As PropertySet =
                oPropertySets.Item("Design Tracking Properties")

            ' Set reference to the Description property
            Dim oDescriptionProperty As [Property] =
                oDesignTrackingPropertySet.Item("Description")

            ' Return the description value (as string)
            Description = oDescriptionProperty.Value

        End Get
        Set(value As String)

            ' Set reference to the document property sets
            Dim oPropertySets As PropertySets =
                ReferencedDocument.PropertySets

            ' Set reference to the Design Tracking Property set
            Dim oDesignTrackingPropertySet As PropertySet =
                oPropertySets.Item("Design Tracking Properties")

            ' Set reference to the Description property
            Dim oDescriptionProperty As [Property] =
                oDesignTrackingPropertySet.Item("Description")

            ' Return the description value (as string)
            oDescriptionProperty.Value = value

        End Set
    End Property

End Class


texts:
I have a very easy question for you guys out there. It's been a while since I took my programming courses (switched majors) but am trying to get my feet wet again.
Objective:
I will be creating a program that will output 10 random full names (and have it be different every time the program is run).  Before I complete it, I'd like some feedback on the first iteration, which just chooses random first names.
Info:
I have a file called firstnames.txt, containing a list of 10 first names.
Premise:
I'm a beginner and I/O really throws me.  I feel this is a basic enough program for me to learn from, and with your advice, I'll be able to copy/paste the same code to get a last name.
Thanks!
Here's what I have so far:
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <string> //random headers because it's been awhile :P
#include <fstream>
#include <time.h>

using namespace std;

int main()
{
//Variable declarations
int a = 0;
int randNum;

ifstream myFile;
myFile.open("firstnames.txt");
string names[10]; // holds the 10 names in the file.
string randomNames[10];// holds the randomly generated names FROM the file.

while (myFile.good())
{
    getline(myFile, names[a]); // reads the names from the text file, into an array named "names[]."
    a++;
}
for (int i = 0; i < 10; i++)  // makes this program iterate 10 times; giving you 10 random names.
{
    srand( time(NULL) ); // seed for the random number generator.
    randNum = rand() % 10 + 1; // gets a random number between 1, and 10.
    randomNames[i] = names[randNum];
}
for (int i = 0; i < 10; i++)
{
    cout << randomNames[i] << endl; // outputs all 10 names at once.
}

myFile.close();
return EXIT_SUCCESS;
}

My firstnames.txt looks like:
Ryan
John
Daniel
Gavin
Frank
Danielle
Lucy
Sarah
Katie
Nicole

My lastnames.txt will look similar:
Johnson
Lewis
Walker
Robinson
Wood
Thompson
White
Watson
Jackson
Wright

(Another question I guess would be is the way I formatted the names (each name on a new line) a bit over complicated in the text file? Like would it be better/shorter to just separate each name by a space or something?)
Thanks again!


texts: Finding the busiest time-frame in a parking lot

texts:
The text file containing cars' arrival and departure time will upload stuff from the parking lot.

Text will be like this:

10:10, 11:10
10:30, 12:40
10:25, 11:10
11:10, 12:20

I created a ParkedCar class:

public class ParkerCar
{
    public DateTime ArrivalTime { get; set; }
    public DateTime DepartureTime { get; set; }
}

The method that parses the text file, fills into List<ParkedCar>, and sorts them by the cars' arrival time:

public class ParkingLotRepository
{
    public List<ParkedCar> getParkedCars()
    {
        List<ParkedCar> parkedCars = new List<ParkedCar>();
        foreach (string line in File.ReadLines(path))
        {
            string[] times = line.Split(',');
            bool isValid = true;
            DateTime dtStart;
            if (!DateTime.TryParseExact(times[0].Trim(), "HH:mm",
                CultureInfo.InvariantCulture,
                DateTimeStyles.NoCurrentDateDefault, out dtStart))
                isValid = false;

            DateTime dtEnd;
            if (!DateTime.TryParseExact(times[1].Trim(), "HH:mm",
                CultureInfo.InvariantCulture,
                DateTimeStyles.NoCurrentDateDefault, out dtEnd))
                isValid = false;

            if (isValid)
            {
                parkedCars.Add(new ParkedCar
                {
                    ArrivalTime = dtStart,
                    DepartureTime = dtEnd
                });
            }
        }
        parkedCars = parkedCars
            .OrderBy(c => c.ArrivalTime)
            .ThenBy(c => c.DepartureTime)
            .ToList();

        return parkedCars;
    }
}

I wrote the method shown below to find the busiest time-frame and how many cars were in the parking lot. I'm not sure if this is an effective way to do that:

public static ParkTimeframe getPickTimeframe(List<ParkedCar> cars)
{
    List<ParkTimeframe> timeFrames = new List<ParkTimeframe>();
    DateTime dtStart = cars.First().arrivalTime;
    DateTime dtEnd = cars.First().leavingTime;
    int count = 0;

    foreach (ParkedCar car in cars)
    {
        if (car.arrivalTime <= dtEnd && car.arrivalTime >= dtStart)
        {
            count++;
        }
        else
        {
            timeFrames.Add(new ParkTimeframe
            {
                startTime = dtStart,
                endTime = dtEnd,
                countCars = count
            });
            dtStart = car.arrivalTime;
            dtEnd = car.leavingTime;
            count = 0;
        }
    }

    int maxCountCar = timeFrames.Max(x => x.countCars);
    return timeFrames.First(x => x.countCars == maxCountCar);
}

public class ParkedCar
{
    public DateTime arrivalTime { get; set; }
    public DateTime leavingTime { get; set; }
}

Also, is there a better way to do that using LINQ?


texts: UPenn CIS 194 Homework 2: Log file parsing

texts:
I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course.

HW2 - Log file parsing - Full description

{-# OPTIONS_GHC -Wall #-}
module LogAnalysis where

import Log

parseMessage :: String -> LogMessage
parseMessage x = case words x of
                      "E":s:t:m -> LogMessage (Error (read s::Int)) (read t::Int) (unwords m)
                      "W":t:m -> LogMessage Warning (read t::Int) (unwords m)
                      "I":t:m -> LogMessage Info (read t::Int) (unwords m)
                      r -> Unknown (unwords r)

parse :: String -> [LogMessage]
parse x = case lines x of
                f:xs -> [parseMessage f] ++ parse (unlines xs)
                [] -> []

insert :: LogMessage -> MessageTree -> MessageTree
insert (Unknown _) t = t
insert m Leaf = (Node Leaf m Leaf)
insert message@(LogMessage _ t1 _) (Node l root@(LogMessage _ t2 _) Leaf)
  | t1 > t2 = (Node l root (Node Leaf message Leaf))
insert message@(LogMessage _ t1 _) (Node Leaf root@(LogMessage _ t2 _) r)
  | t1 <= t2 = (Node (Node Leaf message Leaf) root r)
insert message@(LogMessage _ t1 _) (Node l root@(LogMessage _ t2 _) r)
  | t1 > t2 = (Node l root (insert message r))
  | otherwise = (Node (insert message l) root r)

build :: [LogMessage] -> MessageTree
build [] = Leaf
build (x:xs) = insert x (build xs)

inOrder :: MessageTree -> [LogMessage]
inOrder Leaf = []
inOrder (Node left message right) = (inOrder left) ++ [message] ++ (inOrder right)

whatWentWrong :: [LogMessage] -> [String]
whatWentWrong log = (filterEmpty (errorsWithSeverity50 (inOrder (build log))))

errorWithSeverity :: LogMessage -> Int -> String
errorWithSeverity (LogMessage (Error s) _ m) severity
  | s >= severity = m
  | otherwise = ""
errorWithSeverity _ _ = ""

errorsWithSeverity50 :: [LogMessage] -> [String]
errorsWithSeverity50 [] = []
errorsWithSeverity50 (x:xs) = [(errorWithSeverity x 50)] ++ errorsWithSeverity50 xs

filterEmpty :: [String] -> [String]
filterEmpty [] = []
filterEmpty ("":xs) = filterEmpty xs
filterEmpty (x:xs) = [x] ++ filterEmpty xs


texts: Getting data from service and storing it in MongoDB

texts:
I wrote code to get data from HTTP service and store it in MongoDB.  Please, can someone let me know how efficient my code is and whether it is good from the OOP point of view?

/*global Promise, getData, httpReq, searchData, getHotData, storeData*/

var http = require('http');
var CoubVideo = require('./models/coubdb.js');

function CoubApi (url, numPerPage, numOfPages) {
  this.url = url;
  this.numOfPages = numOfPages;
  this.numPerPage = numPerPage;
  this.getData = getData;
  this.httpReq = httpReq;
  this.searchData = searchData;
  this.getHotData = getHotData;
  this.storeData = storeData;
}

// Get data from server
function httpReq (url) {
  var promise = new Promise (function (resolve, reject) {

    http.get(url, function (res) {
      var data = '';

      res.on('data', function (chunk) {
        data += chunk;
      });

      res.on('end', function () {
        if(data.length > 0) {
          resolve(JSON.parse(data));
        } else {
          reject("Error: HTTP request rejected!");
        }
      });

    }).on('error', function (err) {
      console.log(err);
    });

  });

  return promise;
}

// Store data in MongoDB
function storeData (data, per_page) {

  function insertVideoDoc (i) {
    CoubVideo.count({id: data.coubs[i].id}, function (err, count) {
      if (err) {
        console.log(err);
      }

      if (count === 0 || count === null) {
        var video = new CoubVideo(data.coubs[i]);

        video.save(function (err) {
          if (err) {
            console.log(err);
          }
          console.log("Saved successfully!");
        });
      } else {
        console.log("Duplicate");
      }
    });
  }

  var i;
  for(i = 0; i < per_page; i++) {
    insertVideoDoc(i);
  }
}

// Search for coubs
function searchData (searchtext, order, page, per_page) {
  var url = this.url +
            "search?q=" + searchtext +
            "&order_by=" + order +
            "&per_page=" + per_page +
            "&page=" + page;

  this.httpReq(url).then(function (data) {
    this.storeData(data, per_page);
  }.bind(this));
}

// Get hot coubs
function getHotData (order, page, per_page) {
  var url = this.url +
            "timeline/hot?page=" + page +
            "&per_page=" + per_page +
            "&order_by=" + order;

  this.httpReq(url).then(function (data) {
    this.storeData(data, per_page);
  }.bind(this));
}

// Get data
function getData () {
  var i;
  for(i = 0; i < this.numOfPages; i++) {
    this.getHotData("newest_popular", i, this.numPerPage);
  }
}

var coub = new CoubApi("http://coub.com/api/v2/", 2, 50);
coub.getData();


texts:
Recently I was asked in an interview to convert the string say "aabbbccccddddd" to "a2b3c4d5". i.e we have to avoid repeating same character and just adding the repeat count. Here 'a' is repeated twice in the input and so we have to write it as 'a2' in the output. Also i have to write a function to reverse the format (i.e from the string "a2b3c4d5" to "aabbbccccddddd") back to the original one. I was free to use either C or C++ language. I have tried the below code. But the interviewer seems to be not very happy with this. He asked me to try some smart way than this.

In the below code, I used formatstring() to eliminate repeated chars by just adding the repeated count and used reverseformatstring() to convert back to the original string.

formatstring()

void formatstring(char* target, const char* source)
{
    int charRepeatCount = 1; bool isFirstChar = true;
    while (*source != '\0')
    {
        if (isFirstChar)
        {
            //Whatever be the first character, we have to add it to the target
            isFirstChar = false;
            *target = *source;
            source++; target++;
        }else
        {
            if (*source == *(source-1))
            {
                //Comparing the current char with previous one and incrementing repeat count
                charRepeatCount++;
                source++;
            }else
            {
                if (charRepeatCount > 1)
                {
                    //Converting repeat count to string and appending it to the target
                    char repeatStr[10];
                    _snprintf(repeatStr, 10, "%i", charRepeatCount);
                    int repeatCount = strlen(repeatStr);
                    for (int i = 0; i < repeatCount; i++)
                    {
                        *target = repeatStr[i];
                        target++;
                    }
                    charRepeatCount = 1; //Reseting repeat count
                }
                *target = *source;
                source++; target++;
            }
        }
    }
    if (charRepeatCount > 1)
    {
        //Converting repeat count to string and appending it to the target
        char repeatStr[10];
        _snprintf(repeatStr, 10, "%i", charRepeatCount);
        int repeatCount = strlen(repeatStr);
        for (int i = 0; i < repeatCount; i++)
        {
            *target = repeatStr[i];
            target++;
        }
    }
    *target = '\0';
}

reverseformatstring()

void reverseformatstring(char* target, const char* source)
{
    int charRepeatCount = 0; bool isFirstChar = true;
    while (*source != '\0')
    {
        if (isFirstChar)
        {
            //Whatever be the first character, we have to add it to the target
            isFirstChar = false;
            *target = *source;
            source++; target++;
        }else
        {
            if (isalpha(*source))
            {
                //If current char is alphabet, we can simply add it to the target
                *target = *source;
                target++; source++;
            }
            else
            {
                while (isdigit(*source)) //Getting repeat count of previous character
                {
                    int currentDigit = (*source) - '0';
                    charRepeatCount = (charRepeatCount == 0) ? currentDigit : (charRepeatCount * 10 + currentDigit);
                    source++;
                }
                //Decrement repeat count as we have already written first unique char to the target
                charRepeatCount--;
                while (charRepeatCount > 0) //Repeating the last char for this count
                {
                    *target = *(target - 1);
                    target++; charRepeatCount--;
                }
            }
        }
    }
    *target = '\0';
}

I didn't find any issues with the above one. Is there any better way of doing the same?


texts: A C++ iterator that adds an extra layer of indirection

texts:
This iterator is designed with one purpose in mind. If before you had an iterator where you could do
int x = *it;

now you do
int x = **make_wrap_iterator(it);

This is useful for example if you want to use a range-based for loop to produce iterators to each element rather than values. You could do
std::vector<int> source = {1,2,3,4};
for(std::vector<int>::const_iterator it :
    boost::make_iterator_range(
        make_wrap_iterator(source.begin()),
        make_wrap_iterator(source.end())
    )
{
    std::out << *it << std::endl;;
}

Try it on Godbolt.
The implementation for WrapIterator is:
#include <iostream>
#include <vector>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/range/iterator_range.hpp>

template <typename T>
struct WrapIterator : boost::iterator_facade
    < WrapIterator<T> ,T ,typename T::iterator_category ,T >
    {
        WrapIterator(T ptr) : m_ptr(ptr) {}
        T dereference() const { return m_ptr; }

        void increment() { m_ptr++; }
        void decrement() { m_ptr--; }
        void advance(int n){ m_ptr+=n; }
        typename T::difference_type distance_to
            (WrapIterator<T> const & other) const
        {
            return other.m_ptr - m_ptr;
        }
        bool equal(WrapIterator<T> const & other) const {
            return other.m_ptr == m_ptr;
        }

    private:
        T m_ptr;
};

template <typename T>
WrapIterator<T> make_wrap_iterator(T it){return WrapIterator<T>(it);}

I have two questions.

WrapIterator is a terrible name. Is there a better name for this iterator? Boost already has a class called indirect_iterator which does the exact opposite of my iterator in that if you do '*it' indirect iterator does '**it'. Essentially if you wrap my iterator with a boost indirect_iterator you get back the same thing you started with. I found this because I was going to call my class indirect_iterator and then was confused for a while until I realized that what I found in boost was the opposite of what I intended.

Is the class complete? Can it wrap any iterator type correctly?


texts:
I am attempting to validate a set of business rules in order for a user to successfully add to cart. The rules vary from requiting to add/decline a requested add-on to not having more then 60 items in your shopping cart.

For my end goal, I need to be able to have several dozen rule sets and if any return false then execute the needed function and prevent cart submit.

Separation of the rules logic seemed like a great thing so that I do not clutter my plugin or ajax call it's self, but I wonder if there is a better way because I tend to over engineer things.

JS Fiddle example

Here is the basic object:

var req = {
    type: function(name){
        switch(typeof name){
            case "function":
                return "function";
            break;
            case "object":
                if($.isArray(name)){
                    return "array";
                }else{
                    return "object";
                };
            break;
            case "string":
                return "string";
            break;
            case "number":
                return "number";
            break;
            case '':
            case "undefined":
            default:
                return "undefined";
            break;
        };
    },
    check: function(v){
        var valid = new Array();

        if(this.type(v) === "array"){
            if(v.length > 0){
                for(var i = 0; i < v.length; i++){
                    if(this.type(v[i]) === "function"){
                        valid.push(v[i]());
                    };
                };
            }else{
                return true;
            };
        }else{
            if(this.type(v) === "function"){
                valid.push(v());
            };
        };

        if(valid.indexOf(false) > -1){
            return false;
        }else{
            return true;
        };
    }
};

Here is how the basic functions are pushed into the array:

var addHelper = {
    invoke: function(type, fun){
        gb[type].push(fun);
    }
};

addHelper.invoke("validate",
    function(){
        if(parseInt($("#fakeQty").val()) > 59){
            var qtyMsg = "For bulk or commercial orders, please call our online support";
            alert(qtyMsg);
            return false;
        }else{
            return true;
        };
    }
);

Each function is stored in its own object, but for space sake I just simple passed it directly.


texts: Functional Javascript Practice with AJAX

texts:
I am currently doing projects in freecodecamp.com to brush up on my javascript skills and just finished a weather report widget. It does the following:

Gets api from openweathermap.org and displays the weather based on
user's latitude and longitude
Displays the city, weather description and wind speed
Can toggle between celsius and ferenheit

I want to become a better javascript developer and use best-practice tools and design patterns. Therefore, I would kindly ask if anyone has design pattern suggestions for making my code more efficient, less redundant, and more functional.

Also, the console displays getCurrentPosition() and watchPosition() are deprecated on insecure origins why is this, and is there an alternative for getting the user's position from directly from the browser?

The following is my javascript code:

if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(function(position) {

      var latitude = position.coords.latitude;
      var longitude = position.coords.longitude;

      $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eee5ab7fffb62d126756d9b810ee1875", function(data) {

     var temp = JSON.stringify(data.main.temp);
     //Convert to Ferenheit
     var temp2 = temp * 9 / 5 - 459.67;
     //Round to 2nd decimal place
     var temp3 = Math.round(temp2 * 10) / 10;
     //Display
     $('#temperature').html(temp3 + " F");

     //Description
     var description = data.weather[0].description;

     //Wind speed
     var wind = JSON.stringify(data.wind.speed);

     //HTML disaply
     $(".report").html("
" + data.name + "
" + "
" + description + "

" + wind + " knots
");

     //Toggle Logic
     $('#celsius').on('click', function() {
       var celsius = temp - 273.15;
       var celsius2 = Math.round(celsius * 10) / 10;
       $('#temperature').html(celsius2 + " C");
       $('#celsius').removeClass('btn-default').addClass('btn-primary');
       $('#ferenheit').removeClass('btn-primary').addClass('btn-default');
     });

     $('#ferenheit').on('click', function() {
       var temp = JSON.stringify(data.main.temp);
       var temp2 = temp * 9 / 5 - 459.67;
       var temp3 = Math.round(temp2 * 10) / 10;
       $('#temperature').html(temp3 + " F");
       $('#ferenheit').removeClass('btn-default').addClass('btn-primary');
       $('#celsius').removeClass('btn-primary').addClass('btn-default');
     });

     //Icons logic
     if (description == "broken clouds" || "scattered clouds") {
       $("i").addClass("wi-cloudy");
     } else if (description == "few clouds") {
       $("i").addClass("wi-cloud");
     } else if (description == "clear sky") {
       $("i").addClass("wi-day-sunny");
     } else if (description == "shower rain" || "rain") {
       $("i").addClass("wi-rain");
     } else if (description == "thunderstorm") {
       $("i").addClass("wi-storm-showers");
     } else if (description == "snow") {
       $("i").addClass("wi-snowy");
     } else if (description == "mist") {
       $("i").addClass("wi-dust");
     };
   });
 });
}

You can find the rest of my code in the gist here.


texts: Select highest and second highest values

texts:
i've written a procedure to where it selects the first and second highest values not already selected (as designated by previous highlights of green and yellow). The first highest ignores anything already highlighted in green or yellow and selects the highest value. The second highest value ignores anything highlighted in green or yellow AND ignores the first highest highlighted in red. It then designates each selection with a 1 for 1st highest and 2 for second highest. It works but the problem is... it takes 1 minute 30 seconds to run, which isn't ideal. Is there another way I can write this? Please see below and thank you.

Sub Macro1()
' Select highest value not already selected (as designated by highlights green and yellow)

Sheets("sheet1").Select
Dim rng As Range, s As Range
Set rng = Range("C2:D500000")
Set s = Range("C2")
For Each r In rng
If r.Value > s And r.EntireRow.Interior.ColorIndex <> 4 And r.EntireRow.Interior.ColorIndex <> 6 Then Set s = r
Next r
For Each r In rng
If s.Value = r.Value And r.EntireRow.Interior.ColorIndex <> 4 And r.EntireRow.Interior.ColorIndex <> 6 Then r.EntireRow.Interior.ColorIndex = 22
Next r

' Select second highest value not already selected (as designated by highlights green, yellow, and red, which is first highest)

Dim rng2 As Range, q As Range
Set rng2 = Range("C2:D500000")
Set q = Range("C2")
For Each r In rng2
If r.Value > q And r.EntireRow.Interior.ColorIndex <> 22 And r.EntireRow.Interior.ColorIndex <> 4 And r.EntireRow.Interior.ColorIndex <> 6 Then Set q = r
Next r
For Each r In rng2
If q.Value = r.Value And r.EntireRow.Interior.ColorIndex <> 22 And r.EntireRow.Interior.ColorIndex <> 4 And r.EntireRow.Interior.ColorIndex <> 6 _
Then r.EntireRow.Interior.ColorIndex = 20
Next r

'Designates 1st highest with the number 1

Dim rg As Range

Set rg = Range("V2:V500000")
For Each cell In rg
If cell.EntireRow.Interior.ColorIndex = 22 Then
cell.Offset(0, 1) = "1"
End If
Next

'Designates second highest with the number 2

Set rg3 = Range("V2:V500000")
For Each cell In rg3
If cell.EntireRow.Interior.ColorIndex = 20 Then
cell.Offset(0, 1) = "2"
End If
Next
End Sub


texts: Animal, Dog, and IDangerous - Using interfaces and inheritance with C#

texts:
I'm quite new to object-oriented C#. I wanted to test my knowledge by creating a Dog/Animal classes. I also tried to implement an IDangerous interface in my code.
Is there anything I could've done better/differently? Again, this is my first time on this Stack Exchange so if I could've restructured this post differently please tell me.
public class Animal
{
    public int Age { get; }
    public string Color { get; }
}
public class Dog : Animal
{
    public bool IsVaccinated { get; set; }
    public string Name { get; set; }
}
public interface IDangerous
{
    void TightenLeash(string Reason, int LeashTightness);
}
public class GoldenRetriever : Dog { }
public class Beagle : Dog { }
public class PitBull : Dog, IDangerous
{
    public void TightenLeash(string Reason, int LeashTightness)
    {
        Console.WriteLine("Leash tightened...");
    }
}
static class Program
{
    static void Main(string[] args)
    {
        Dog obj1 = new GoldenRetriever();

        obj1.Name = "Fluffy";
        obj1.IsVaccinated = true;
        Console.WriteLine(obj1.Name + obj1.IsVaccinated + obj1.Color);

        List<Dog> DogList = new List<Dog>()
        {
            new Beagle()
            {
                IsVaccinated = false,
                Name = "Korg"
            },
            new GoldenRetriever()
            {
                IsVaccinated = true,
                Name = "Juan"
            },
            new Beagle()
            {
                IsVaccinated = false,
                Name = "Toby"
            },
        };

        List<IDangerous> AngryPitBulls = new List<IDangerous>()
        {
            new PitBull()
            {
                IsVaccinated = false,
                Name = "Angry"
            },
            new PitBull()
            {
                IsVaccinated = false,
                Name = "Ryder"
            }
        };
        AngryPitBulls[0].TightenLeash("For biting another dog", 3);
        AngryPitBulls[1].TightenLeash("For biting the cat", 2);

        Console.ReadLine();
    }

}


texts:
I am learning PHP 7 and decided to implement a simple FIFO singly-linked queue in it:

<?php

class QueueNode {
    var $item;
    var $next;

    function __construct($item) {
        $this->item = $item;
    }

    function get_item() {
        return $this->item;
    }
}

class Queue {
    var $head;
    var $tail;
    var $size;

    function push($item) {
        if ($this->size == 0) {
            $this->head = $this->tail = new QueueNode($item);
        } else {
            $new_node = new QueueNode($item);
            $this->tail->next = $new_node;
            $this->tail = $new_node;
        }

        $this->size++;
    }

    function pop() {
        if ($this->size == 0) {
            throw new Exception("Popping from an empty queue.");
        }

        $ret = $this->head->item;
        $this->head = $this->head->next;

        if (--$this->size == 0) {
            $this->head = $this->tail = null;
        }

        return $ret;
    }
}

$queue = new Queue();

for ($i = 1; $i <= 10; $i++) {
    $queue->push($i);
}

for ($i = 1; $i <= 10; $i++) {
    echo $queue->pop() . " ";
}

echo "<br>";
?>

As always, any critique is much appreciated.


texts:
I need someone with experience to judge my first project to let me know what I have to work on. I recently started learning C++ using resources like Solo Learn and Bucky's tutorials on YouTube hoping to eventually gain enough experience to find a job in software development.

#include <iostream>
#include <string>
using namespace std;
//Functions

// addition function
int calc_sum(){
double x;
double y;
cout << "enter two numbers to get a sum" <<endl;
cin >> x >> y;
double sum = x+y;
cout <<"The sum is "<< sum <<"."<<endl;

}
// multiplication function
int calc_pro(){
double a;
double b;
cout<<"enter two numbers to find the product"<<endl;
cin>> a >> b;
double product = a * b;
cout<< "The product is "<< product <<"."<<endl;

}
// division function
int calc_div(){
double x;
double y;
cout<< "enter two numbers to divide."<<endl;
cin>> x >> y;
double div = x/y;
cout << "The quotient is "<< div <<"." <<endl;
}
// Subtraction function
int calc_sub() {
double a;
double b;
cout<< "Enter two numbers to subtract."<< endl;
cin>> a >> b;
double diff = a-b;
cout<< "The difference is "<< diff <<endl;

}

//core function

void core2(){
string choice;
cout<<"Would you like to multiply, divide, add, or subtract? (typer in lowercase)"<<endl;
cin>>choice;

if(choice=="add"){
calc_sum();
core2();
}
else if(choice=="subtract"){
calc_sub();
core2();
}
else if(choice=="multiply"){
calc_pro();
core2();
}
else if(choice=="divide"){
calc_div();
core2();
}
else{
cout<<"USER ERROR"<<endl<< "you typed in something wrong, try again."<<endl;
core2();
}
}

int main(){

core2();

}


texts: Map reduce tester ported from bash to Python

texts:
My MapReduce tester is clearly ported from Shell, short of args=None for line in args or read_input(), what's a better way of importing->testing the function outside of subprocess?
Or does it not matter, i.e.: my "hack" is fine?
test_mapreduce.py
from unittest import TestCase, main as unittest_main
from subprocess import check_output as run
from os import path

class TestMapReduce(TestCase):
    top_path = ''
    map_reduce = lambda self, mapper_name, reducer_name, datafile_name: run(
        ['python', path.join(self.top_path, reducer_name),  # Reduce
         run(['sort',  # Shuffle, could be replaced with python `sorted`
              run(['python', path.join(self.top_path, mapper_name),  # Map
                   path.join(self.top_path, 'data', datafile_name)])])])

    @classmethod
    def setUpClass(cls):
        if not path.isfile('setup.py'):
            cls.top_path = path.join('..', '..')
            if not path.isfile(path.join(cls.top_path, 'setup.py')):
                raise AssertionError("Haven't found right directory to `cd` into")

    def test_with_student_test_posts(self):
        print self.map_reduce('mapper.py', 'reducer.py', 'student_test_posts.csv')

if __name__ == '__main__':
    unittest_main()

mapper.py
#!/usr/bin/env python

from fileinput import input as read_input

def mapper():
    for line in read_input():
        data = line.strip().split('\t')

        if len(data) != 6:
            continue

        date, time, store, item, cost, payment = data
        print "{0}\t{1}".format(store, cost)

if __name__ == '__main__':
    mapper()

PS: Should I refactor to use the map and reduce inbuilt functions?


texts:
I have a project that uses a library to save serialized objects in items and loads them again, when needed.
To do the de-/serialization, this library uses Gson.

Due to how Gson works and how the library is set up, I can't add support for custom types easily and thus have to rely heavily on reflection.
I don't like this, but it has to be like this, sadly.

I am asking, whether there is a way to make this code use more Kotlin idioms.
My issue is that because the fields I am accessing are private, the usual reflection using :: doesn't work.

Anyways, here is my code:

/**
 * Registers a custom GSON handler to handle the [Location] class.
 */
private fun registerGsonHandlers() {
    logger.entering(LobbyMain::class, "registerGsonHandlers")
    // Gets private static final Gson gson = new Gson();
    val fGson = NBTReflectionUtil::class.java.getDeclaredField("gson")
    fGson.isAccessible = true

    val modifiersField = Field::class.java.getDeclaredField("modifiers")
    modifiersField.isAccessible = true
    modifiersField.setInt(fGson, fGson.modifiers and Modifier.FINAL.inv())

    // Gets  private final List<TypeAdapterFactory> factories;
    val fFactories = Gson::class.java.getDeclaredField("factories")
    fFactories.isAccessible = true
    val factories = fFactories.get(fGson.get(null)) as List<*>

    // Sets private static final Gson gson
    fGson.set(null, GsonBuilder().apply {
        registerTypeAdapter(Location::class.java, LocationTypeAdapter)
        factories.forEach { this::registerTypeAdapterFactory }
    }.create())
    logger.exiting(LobbyMain::class, "registerGsonHandlers")
}

It pulls the Gson object out of the NBTReflectionUtil class, makes it modifiable and gets its list of TypeAdapterFactories.
I then create a new Gson object with all the old TypeAdapters and mine added and set it as the new Gson object for the library.


texts: Priority in pair inside priority_queue on basis of both elements

texts:
I want a priority queue such that first it should be done on basis of first element (increasing order)and when clash occurs then on basis of second element(decreasing order). I came up with the following code :

#include<bits/stdc++.h>
using namespace std;

struct Compare {
    constexpr bool operator()(pair<int, int> const & a,
                              pair<int, int> const & b) const noexcept
    { return a.first > b.first && a.second<b.second; }
};

int main()
{
    priority_queue<pair<int,int>,
                   std::vector<pair<int,int> >,
                   Compare> Q;
    int n;
    cin>>n;

    for(int i=0;i<n;i++)
    {
        ll a,b;
        cin>>a>>b;
        Q.push(make_pair(a,b));
    }

    for(ll i=0;i<n;i++)
    {
        pair<ll,ll> m;
        m=Q.top();
        cout<<m.first<<" "<<m.second<<"\n";
        Q.pop();
    }
}

For eg - If I have following pairs : (1,10),(1,7),(1,5),(2,8),(2,6),(3,5),(3,9)

My output should be as follows on calling Q.top() and Q.pop()

1 10
1 7
1 5
2 6
2 8
3 5
3 9

But instead I'm getting the following output:

1 10
1 5
3 9
1 7
2 8
2 6
3 5

Can someone help me out ?


texts: Expressing current time with natural language

texts:
def current_time():
    '''Returns a tuple containing (hour, minute) for current local time.'''
    import time
    local_time = time.localtime(time.time())
    return (local_time.tm_hour, local_time.tm_min)

(hour,minute) = current_time()

def ishtime(hour, minute):
    import random

    Starting_str = ['it is','its',"it's","Current time is"]

    h_str = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve']

    mid_str = ['almost','nearly','roughly','maybe']

    Ex = ['Exactly' , 'Perpectly' ,'']

    m_str = ['ten','twenty','thirty','fourty','fifty']

    End_str = ['in the morning','in the afternoon','in the evening','at night']

## - define random strings

    Head = Starting_str[int(random.random()*4)]

    Mid = mid_str[int(random.random()*4)]

    Hour = h_str[(int(hour)-1)%12]

    if round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
        Rand_m_str = ''
    else:
        Rand_m_str = m_str[int((round(int(minute),-1)/10))-1]

## -define for final ex)its , it's , almost, one two three..

    if int(hour)>=6 and int(hour)<13:
        Ending = End_str[0]

    elif int(hour)>=13 and int(hour)<19:
        Ending = End_str[1]

    elif int(hour)>=19 and int(hour)<=23:
        Ending = End_str[2]

    elif int(hour)>=0 and int(hour)<6:
        Ending = End_str[3]

## - define 'ending str' ex) in the morning

    if minute == 0 or minute == 00:
        Result = "%s %s 'o clock %s" %(Head,Hour,Ending)

    elif minute%10 == 0:
        Result = "%s %s %s after %s %s" %(Head,Ex[int(random.random()*4)],Rand_m_str,Hour,Ending)

    elif round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
        Result = "%s %s %s%s %s" %(Head,Mid,Rand_m_str,Hour,Ending)

    else:
        Result = "%s %s %s minute after %s %s" %(Head,Mid,Rand_m_str,Hour,Ending)

    return Result

print ishtime(hour,minute)

I did this job.. how could i make it simpler?


texts: Youtube Iframe load only when thumbnail image is clicked

texts:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Youtube Iframe load on thumb click</title>

Credits to embedresponsively.com for Responsive embed, labnol.org For the javascript functionality

What it is supposed to do?
This is going to make page faster to load if you have youtube iframe in your page. This code will replace all divs like

With youtube thumbnail image. And only when user clicks on it it will load the iframe.

This is a mix I've made based on labnol script and embed resposively. (basically I just renamed and removed some classes)
demo on codepen http://codepen.io/AucT/pen/PzvyXq

Help improve code. I want it to be as efficient as possible.
p.s. you can use jQuery


texts: Rename subkeys of nested dictionary dynamically

texts:
My nested (ordered) dictionary looks like this:

OrderedDict([
    ('1', OrderedDict([('1994_fte_count', '4'), ('1995_fte_count', '2'), ('1996_fte_count', '5'), ('1997_fte_count', '7')])),
    ('2', OrderedDict([('1994_fte_count', '5'), ('1995_fte_count', '22'), ('1996_fte_count', '6'), ('1997_fte_count', '3')])),
    ('3', OrderedDict([('1994_fte_count', '6'), ('1995_fte_count', '7'), ('1996_fte_count', '7'), ('1997_fte_count', '81')]))
    ])

The subkeys ("1994_fte_count", "1995_fte_count", etc.) all range up until 2000. I want to replace the year with the difference to a given year. This shall happen dynamically for a lot of years. For example, I start with 1995, and "1995_fte_count" shall be renamed "lag0_fte_count", while "1994_fte_count" shall be renamed "lag1_fte_count". I read the file in a several times, each time with a different benchmark year.

I currently use the following nested loop:

year = "1996" # comes as string
lag_length = 2
year_range = range(int(year)-lag_length, int(year))
replacement = ["lag" + str(i) for i in reversed(range(0,lag_length))]
for ID in my_dict.keys():
    for subkey in my_dict[ID].keys():
        for i in range(0, len(year_range)):
            acutal_year = str(year_range[i])
            if subkey.startswith(acutal_year):
                newkey = subkey.replace(acutal_year, replacement[i])
                my_dict[ID][newkey] = my_dict[ID].pop(subkey)

Given the nature of the task (simple text replace), I do think that there must be a shorter, more readable and faster way than to iterate over all the subkeys multiple times. Who knows how to?


texts:
This is a verification code generator, which generates n-digit numeric strings. (code can be 0000, so I chose String as a return type rather than Int or Long.)

It'll be great if anyone review this code and suggest more elegant or scalaish solution.

import scala.util.Random

object VerificationCodeGenerator {
  val rand = new Random

  def generate(digit: Int): String = {
    val sb = new StringBuilder
    for (i <- 1 to digit) {
      sb.append(rand.nextInt(10))
    }
    sb.toString()
  }
}


texts:
Here is my working code for a min-heap sort using an Array-List. I would like any input as to areas that need additional refining and any areas that are against proper formatting/usage. Although not defined, I was attempting to use an array implementation instead of the Array-List collection as the class has been creating your own implementations of collections rather than using the collections. I struggled some and reverted to the collection as it is about the heap implementation rather than array/Array-List. The one area that I feel may be incorrect is the output. It is in a fully sorted order rather than what I was expecting IE:

expected: B, H, F, L, T, G, S, S, M, V
actual: B, F, G, H, L, M, S, S, T, V

expected: 1, 2, 5, 3, 3, 7, 6, 9, 4, 6
actual: 1, 2, 3, 3, 4, 5, 6, 6, 7, 9

Here is my code:

import java.util.ArrayList;

final class Heap<T extends Comparable<T>> {
private final ArrayList<T> heapArray = new ArrayList<>();

public Heap() {

}

public Heap(T[] objects) {
    for (T object : objects) {
        add(object);
    }
}

public void add(T newObject) {
    heapArray.add(newObject);
    int currentIndex = heapArray.size() - 1;

    while (currentIndex > 0) {
        int parentIndex = (currentIndex - 1) / 2;

        if (heapArray.get(currentIndex).compareTo(heapArray.get(parentIndex)) > 0) {
            T temp = heapArray.get(currentIndex);
            heapArray.set(currentIndex, heapArray.get(parentIndex));
            heapArray.set(parentIndex, temp);
        } else {
            break;
        }

        currentIndex = parentIndex;
    }
}

public T remove() {
    if (heapArray.isEmpty()) {
        return null;
    }

    T removedObject = heapArray.get(0);
    heapArray.set(0, heapArray.get(heapArray.size() - 1));
    heapArray.remove(heapArray.size() - 1);

    int currentIndex = 0;
    while (currentIndex < heapArray.size()) {
        int leftChildIndex = 2 * currentIndex + 1;
        int rightChildIndex = 2 * currentIndex + 2;

        if (leftChildIndex >= heapArray.size()) {
            break;
        }

        int maxIndex = leftChildIndex;

        if (rightChildIndex < heapArray.size()) {
            if (heapArray.get(maxIndex).compareTo(heapArray.get(rightChildIndex)) < 0) {
                maxIndex = rightChildIndex;
            }
        }

        if (heapArray.get(currentIndex).compareTo(heapArray.get(maxIndex)) < 0) {
            T temp = heapArray.get(maxIndex);
            heapArray.set(maxIndex, heapArray.get(currentIndex));
            heapArray.set(currentIndex, temp);
            currentIndex = maxIndex;
        } else {
            break;
        }
    }

    return removedObject;

}

public int getSize() {
    return heapArray.size();
}
}

public class HeapSort {

public static <T extends Comparable<T>> void heapSort(T[] list) {

    Heap<T> heap = new Heap<>();

    for (T list1 : list) {
        heap.add(list1);
    }

    for (int i = list.length - 1; i >= 0; i--) {
        list[i] = heap.remove();
    }

}

public static void main(String[] args) {

    Integer[] Test1 = {9, 7, 6, 3, 4, 6, 5, 1, 2, 3};
    heapSort(Test1);

    for (Integer Test11 : Test1) {
        System.out.print(Test11 + " ");
    }

    System.out.println();

    Character[] Test2 = {'L', 'F', 'G', 'S', 'V', 'B', 'S', 'M', 'H', 'T'};
    heapSort(Test2);

    for (Character Test21 : Test2) {
        System.out.print(Test21 + " ");
    }

}
}


texts:
Problem Statement

  Write a HTML page holding a form and a text field. Using JavaScript make the text field to accept numbers only. When a non-number character is entered through the keyboard (or by any other way), make the field red for a while and do not accept the change (preserve the previous value of the field).

  Expected Output

Solution

<!DOCTYPE html>
<html>
    <head>
        <title>Text field</title>
        <meta charset="UTF-8">
        <script type="text/javascript">
            window.onload = function(){
                document.formex.numberinput.onchange = checkIfNumber;
                function checkIfNumber(){
                     if (isNaN(parseInt(document.formex.numberinput.value, 10))){
                        document.formex.numberinput.innerHTML = document.formex.numberinput.value;
                        document.formex.numberinput.readOnly = true;
                        setTimeout(function(){
                           document.formex.numberinput.readOnly = false;
                        }, 10000);
                      }
                 }
            }
        </script>
        <style type="text/css">
                input[readonly] {
                   background-color: red;
                }
        </style>
    </head>
    <body>
        <form name="formex">
            <input type="text" name="numberinput">
        </form>
    </body>
</html>

Above code uses name attributes as element lookup approach.

Can we improve this code?


texts: Cross browser JavaScript implementation of xhr

texts:
I wrote a small, cross browser compliant implementation of xhr requests in client JavaScript that closely follows the jQuery $.ajax() API and standards. The goal is to keep the xhr() very small in size, yet cover most common xhr scenarios and needs.

I'd like code review for performance, general best practice, and the most browser support (IE8+, Firefox, Chrome, Safari).

function xhr(options) {
    if(!options) {
        options = {};
    }

    var url = options.url ? options.url : window.location.href;
    var method = options.method ? options.method.toUpperCase() : 'GET';
    var data = options.data ? JSON.stringify(options.data) : null;
    var contentType = (typeof options.contentType !== 'undefined') ? options.contentType : null;
    var headers = (options.headers && typeof options.headers === 'object') ? options.headers : {};
    var username = options.username ? options.username : null;
    var password = options.password ? options.password : null;
    var timeout = options.timeout ? options.timeout : 0;
    var withCredentials = (typeof options.withCredentials !== 'undefined') ? options.withCredentials : false;
    var onSuccess = (options.onSuccess && typeof options.onSuccess === 'function') ? options.onSuccess : null;
    var onError = (options.onError && typeof options.onError === 'function') ? options.onError : null;
    var onTimeout = (options.onTimeout && typeof options.onTimeout === 'function') ? options.onTimeout : null;

    var _xhr = new window.XMLHttpRequest();
    _xhr.open(method, url, true, username, password);

    _xhr.timeout = timeout;

    _xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    if(contentType) {
        _xhr.setRequestHeader('Content-Type', contentType);
    } else if(contentType !== false && data) {
        _xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    }

    if(withCredentials) {
        _xhr.withCredentials = withCredentials;
    }

    for (var key in headers) {
        _xhr.setRequestHeader(key, headers[key]);
    }

    _xhr.onreadystatechange = function() {
        if (this.readyState === 4) {
            var responseHeaders = this.getAllResponseHeaders();

            if (this.status >= 200 && this.status < 400) {
                if(onSuccess) {
                    onSuccess(this.responseText, this.status, responseHeaders, this);
                }
            } else {
                if(onError) {
                    onError(this, this.status, responseHeaders);
                }
            }
        }
    };

    if(onTimeout) {
        _xhr.ontimeout = onTimeout;
    }

    _xhr.send(data);
    _xhr = null;
}

Usage examples:

xhr({
    url: "http://foo.bar"
});

xhr({
    url: "http://foo.bar/create",
    method: "POST",
    data: 'foo=bar'
});

xhr({
    url: "http://foo.bar/create",
    method: "POST",
    contentType: "application/json; charset=UTF-8",
    data: { foo: "bar" },
    headers: {
        "X-Key": "Value"
    },
    timeout: 5000,
    onSuccess: function(response, statusCode, responseHeaders, xhr) {
    },
    onError: function(xhr, statusCode, responseHeaders) {
    },
    onTimeout: function(event) {
    }
});


texts: Finding the lowest and highest values in an array... with "Poor Man's DI"

texts:
I am practicing my object oriented knowledge, so I created a very simple program that determines which is the lowest and highest number inside array.

This is my main method:

class Program
{
    static void Main()
    {
        Console.Write("How many numbers would you like to enter?: ");
        int num = int.Parse(Console.ReadLine());

        int[] arr = new int[num];

        for (int x = 0; x < num; x++ )
        {
            Console.Write("Enter number {0}: ", (x+1));
            arr[x] = int.Parse(Console.ReadLine());
        }

        Console.WriteLine();
        Console.Write("Lowest (1) \nHighest (2) \nEnter choice: ");
        int choice = int.Parse(Console.ReadLine());

        Math math;

        if (choice == 1){
            math = new Math(new HighestNumber(), arr);
            Console.WriteLine("Answer: " + math.returnAnswer());
        }
        else if (choice == 2){
            math = new Math(new LowestNumber(), arr);
            Console.WriteLine("Answer: " + math.returnAnswer());
        }

        Console.ReadKey();
    }
}

The IMathPerformer interface:

interface IMathPerformer
{
    int getAnswer(int[]arr);
}

...and its implementations:

class HighestNumber : IMathPerformer
{
    public int getAnswer(int[]arr)
    {
        int highNum = 0;
        for(int x = 0; x<arr.Length - 1; x++)
        {
            if(arr[highNum] > arr[x+1])
            {
                highNum = (x + 1);
            }
        }

        return arr[highNum];
    }
}

class LowestNumber : IMathPerformer
{
    public int getAnswer(int[]arr)
    {
        int lowNum = 0;
        for (int x = 0; x < arr.Length - 1; x++)
        {
            if (arr[lowNum] < arr[x + 1])
            {
                lowNum = (x + 1);
            }
        }

        return arr[lowNum];
    }

The Math class:

class Math
{
    private int[] arr;
    private readonly IMathPerformer imathPerformer;
    public Math(IMathPerformer imathPerformer, int[]arr)
    {
        this.imathPerformer = imathPerformer;
        this.arr = arr;
    }

    public int returnAnswer()
    {
        return imathPerformer.getAnswer(arr);
    }
}

I just want to know if I am doing right or this is a bad practice. If it is bad, it would be greatly appreciated if you could point out why and how to fix it and add some more advice and suggestions.


texts: Optimization with a lower value constraint for positive solutions

texts:
Let \$D\$ be a \$N\times N\$ positive definite matrix. I am minimizing a quadratic funtion

$$ f(w)=w^T D\ w$$

with respect to the weight vector \$ w=(w_1, w_2, ..., w_N)\$, subject to the following
constraints:

\$\displaystyle\sum_n w_n =1\$
\$w_n\geq 0\$
\$w_n \geq \theta \$ or \$ w_n = 0 \quad \forall n\$, for some threshold \$\theta>0\$.

The last constraint means that if the optimizer finds a non-zero solution, then it should be at least
as large as a threshold \$\theta\$.

I am using solve.QP() from quadprog for the optimization and so I have to input
the constraints in the form \$A^T w \geq b\$. The last constraint is problematic, since I don't see any way of writting it in that form.

What I am doing to deal with this, so far, is this:

Ignore the last constraint and find a solution that satisfies the rest of the constraints
Set weights under the threshold \$ \theta\$ to zero, manually, afterwards and then divide the removed weight ammount
equally to the rest of the weights that satisfy the last constraint.

I expect that this gives an approximation for what the optimizer would have found as a solution, if I could include the last constraint from the begining.  Using this solution the value for the function \$ f\$ is close to the initial solution, but of course differs, depending on \$\theta\$.

I was wondering if there is some way to implement this, by including the last constraint in the optimization somehow.

Toy example:

library(quadprog)
library(corpcor)

#Sample matrix to work with:
set.seed(0)
Dmat <- cov( volcano+15*rnorm(87*61) ); Dmat
is.positive.definite(Dmat)

N  <- ncol(Dmat)
dvec <- rep(0, N)

#Constraints:
##sum equals 1:
a0 <- rep(1, N)
b0 <- 1
##everything positive:
a1 <- diag(1, N)
b1 <- rep(0, N)

#combine the constraints:
Amat <- cbind(a0,a1)
bvec <- append(b0,b1)

#Solve:
sol <- solve.QP(Dmat = Dmat, dvec, Amat, bvec, meq = 1)
w   <- zapsmall(sol$solution) ; w

#Manually set weights under a certain threshold to zero
theta <- .01
w[w <  theta] <- 0 ; w

#scale to sum up to 1:
w <- w/sum(w)

#Compare function values:
t(sol$solution) %*% Dmat %*% sol$solution/2
t(w)%*%Dmat%*%w/2


texts:
I tried to implement a cyclic Queue using an array, as a task from a coding interview.

Please comment about style, as well as any edge cases I may have missed.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CirucularArray
{
    [TestClass]
    public class CyclicQueueUsingArray
    {
        [TestMethod]
        public void QueueTest()
        {
            CyclicQueue Q = new CyclicQueue(5);
            Q.Enqueue(1);
            Assert.AreEqual(1, Q.Front);
            Q.Enqueue(2);
            Assert.AreEqual(1, Q.Front);
            Assert.AreEqual(2, Q.Rear);
            Q.Enqueue(3);
            Assert.AreEqual(1, Q.Front);
            Assert.AreEqual(3, Q.Rear);

            Assert.AreEqual(1, Q.Dequeue());
            Assert.AreEqual(2, Q.Front);
            Assert.AreEqual(3, Q.Rear);

            Assert.AreEqual(2, Q.Dequeue());
            Assert.AreEqual(3, Q.Front);
            Assert.AreEqual(3, Q.Rear);

            Assert.AreEqual(3, Q.Dequeue());
        }

        [TestMethod]
        public void QueueOverflowTest()
        {
            CyclicQueue Q = new CyclicQueue(5);
            Q.Enqueue(1);
            Q.Enqueue(2);
            Q.Enqueue(3);
            Q.Enqueue(4);
            Q.Enqueue(5);
            Assert.AreEqual(1, Q.Dequeue());
            Q.Enqueue(6);
            Assert.AreEqual(2, Q.Front);
            Assert.AreEqual(6, Q.Rear);
        }
    }

    public class CyclicQueue
    {
        public int[] _buffer;
        private int _start;
        private int _end;
        private int _size;
        private int _maxSize;
        public CyclicQueue(int maxSize)
        {
            _maxSize = maxSize;
            _buffer = new int[_maxSize];
            _start = 0;
            _end = 0;
        }
        public void Enqueue(int newValue)
        {
            if (_size == _maxSize)
            {
                throw new OutOfMemoryException("Queue at full capacity");
            }
            if (_size > 0)
            {
                _end = (_end + 1) % _maxSize;
            }
            _buffer[_end] = newValue;
            _size++;
        }

        public int Dequeue()
        {
            if (_size == 0)
            {
                throw new IndexOutOfRangeException("Queue is empty");
            }

            int result = _buffer[_start];
            _size--;

            _start = (_start + 1) % _maxSize;
            return result;
        }
        public int Front
        {
            get { return _buffer[_start]; }
        }

        public int Rear
        {
            get { return _buffer[_end]; }
        }
    }
}


texts:
I'm trying to parse an object generated from an Excel file. The output lists each cell with its contents. If the cell is just a number then it remains a number but if the cell contains a formula (has attribute f) I want to make that a getter so whenever that cell is called the result is updated in case the other cells change.

var Sheet = function Sheet(obj) {
    var i;
    for (i in obj){
        if (obj[i].f !== undefined){
            this['_'+i] = obj[i].f;

        } else {
            this[i] = obj[i].v;
        }
    }
}

var SheetConstructor = function(obj){
    var new_sheet = new Sheet(obj);
    var getters = Object.keys(new_sheet).filter(
        function(attr){
            if (attr.charAt(0) === '_'){
                return attr
            }
        });

    for (g in getters){
        Object.defineProperty(new_sheet, getters[g].substring(1), {
            get: function(){
                return eval(new_sheet[getters[g]]);
            }
        });
    }
    return new_sheet;
}

Input object:

{
  B2: { t: 'n', v: 20, w: '20' },
  C2: { t: 'n', v: 115, w: '115' },
  B3: { t: 'n', v: 400, f: 'this.B2*20', w: '400' },
  C3: { t: 'n', v: 600, w: '600' },
  B5: { t: 'n', v: 20, w: '20' },
  D6: { t: 'n', v: 22, w: '22' },
  D7: { t: 'n', v: 36, w: '36' },
  B8:
   { t: 'n',
     v: 26.666666666666668,
     f: 'this.B2 * this.C2',
     w: '26.66666667' },
  D8: { t: 'n', v: 153, f: 'this.B5 + this.D6 + this.D7', w: '153' }
}

I know the security implications of eval() and am not worried about them in this case. This setup currently works but eventually I will have references across multiple sheets so I wanted some feedback on my solution.


texts: Iterative "counting change" implementation in mit-scheme

texts:
Here is my iterative implementation of the Counting change example in SICP. Please note that I'm a beginner, which means I only know the basic syntax for the time being.

Requirement:

  How many different ways can we make change of $ 1.00, given
  half-dollars, quarters, dimes, nickels, and pennies? More generally,
  can we write a procedure to compute the number of ways to change any
  given amount of money?

Code:

(define (count-change-iterative amount)
  ;; penny is not in the signiture, bacause it equals (- amount
  ;;                                                     (* half-dollar 50)
  ;;                                                     (* quarter 25)
  ;;                                                     (* dime 10)
  ;;                                                     (* nickeli 5))
  (define (count-iter half-dollar quarter dime nickeli)
    (cond ((> (* half-dollar 50) amount)
           0)
          ((> (+ (* half-dollar 50)
                 (* quarter 25)) amount)
           (count-iter (+ half-dollar 1) 0 0 0))
          ((> (+ (* half-dollar 50)
                 (* quarter 25)
                 (* dime 10)) amount)
           (count-iter half-dollar (+ quarter 1) 0 0))
          ((> (+ (* half-dollar 50)
                 (* quarter 25)
                 (* dime 10)
                 (* nickeli 5)) amount)
           (count-iter half-dollar quarter (+ dime 1) 0))
          (else (+ 1
                   (count-iter half-dollar quarter dime (+ nickeli 1))))))
  (count-iter 0 0 0 0))

If you run (count-change-iterative 100), it would tell you 292.

I think this is the best scheme code I've written by now. How can I improve it?


texts: Maximum subarray problem solved with divide and conquer also for the all negative element case

texts:
Solving the maximum subarray problem with added cases of finding non maximum non contiguous subarray as well. I used divide and conquer approach and tackled the 'all negative' case by keeping a counter for that and branching it.

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

// finding maximum non contiguous  subarray by adding up all the non negative elements in array

int max_noncont_sub(int a[],int *lower, int *upper)
{
    int sum=0, i ;
for(i = *lower; i <= *upper; i++)
{
    if(a[i]>0)
        sum += a[i];
}
return sum;
}

// finding max subarray which include the middle term, starting from mid and branching both sides till we encounter negative element

int max_cross_sub(int A[], int *lower, int mid, int *upper)
{
int left_sum = INT_MIN;
int sum = 0;
int i, max_left;

for(i = mid; i>=*lower; i--)
{
    sum = sum + A[i];
    if(sum>left_sum)
        left_sum = sum;
    max_left = i;
}

int right_sum = INT_MIN;
sum = 0;
int max_right;

for(i = mid+1; i<=*upper; i++)
{
    sum = sum + A[i];
    if(sum>right_sum)
        right_sum = sum;
    max_right = i;
}
*lower = max_left;
*upper = max_right;
return left_sum + right_sum;

}

//dividing the problem into 3 parts, left subarray and right have same substructure, 3rd one is solved by max_noncont_sub().

int max_sub(int A[], int *lower, int *upper)
{
    if(*lower == *upper)
    {
        return A[*lower];
    }   else
          {
               int mid = *lower + (*upper - *lower)/2;
               int left_low = *lower;
               int left_high = mid;
               int left_sum = max_sub(A, &left_low, &left_high);

               int right_low = mid+1;
               int right_high = *upper;
               int right_sum = max_sub(A, &right_low, &right_high);

               int cross_low = *lower;
               int cross_high = *upper;
               int cross_sum = max_cross_sub(A, &cross_low, mid, &cross_high);

               if(left_sum >=right_sum && left_sum>= cross_sum)
               {
                   *lower = left_low;
                    *upper = left_high;
                  return left_sum;
               } else if(right_sum >=left_sum && right_sum>= cross_sum)
                   {
                        *lower = right_low;
                        *upper = right_high;
                        return right_sum;
                   } else
                       {
                            return cross_sum;
                        }

        }
 }

int main()
{
    int T, N, nc=0;
     scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&N);
        int *a = (int*)malloc(N*sizeof(int));
        int i;

        nc=0;
        for(i = 0; i<N; i++)
       {
            scanf("%d",&a[i]);
            if(a[i]<0)
                nc++; // counting the negative numbers for later tackling with all negative special case
       }

    int lower = 0;
    int upper = N-1;

    if(nc == N)  // if all elements are negative, we just get the least negative and its the answer.
    {
        int max=INT_MIN;
        for(i =0;i<N;i++)
        {
            if(a[i]>max)
                max = a[i];
        }
        printf("%d %d\n",max, max);

    }
    else
    {
        printf("%d %d\n",max_sub(a, &lower, &upper), max_noncont_sub(a, &lower, &upper));
    }
 }
   return 0;
}

Any review and suggestions are welcome.
Is there a better way to do it? I know there's kadane's algorithm with O(n) running time.


texts:
I'm trying to create an alarm function with Python3. The below code does work but it doesn't seem like this is the most optimal way of achieving something like this. Is there a more pythonic way?

#!/usr/local/bin/python3

import os
import time

def alarm():
    os.system('amixer -D pulse sset Master 30%')     # >> Set initial volume
    for beep in range(0, 20):
        time.sleep(.002)
        os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (.08, 2500))

alarm()


texts: Reading a property on a main thread that is set on a background thread

texts:
I am currently handling some setup of an object on a background thread (I am using a concurrent queue within the following initWithDocumentFileURL method):

+ (TWReaderDocument *)initWithDocumentFileURL:(NSURL *)url withLoadingCompletionBlock:(loadingCompletionBlock)completionBlock{

 __block NSError *error;
TWReaderDocument * twDoc = [[TWReaderDocument alloc] init];
twDoc.status = ReaderDocCreated;
twDoc.doc = [ReaderDocument withDocumentFilePath:[url path] withURL:url withLoadingCompletionBLock:^(NSError *_error) {

    if (_error)
    {
        _error = error;
        twDoc.status = ReaderDocReady;
    }
    else twDoc.status = ReaderDocFailed;

}];

//completionBlock(error);

return twDoc;
}

Header

@property (nonatomic, assign, readonly) TWReaderDocumentStatus status;

Implementation

- (TWReaderDocumentStatus) status {

    __block TWReaderDocumentStatus readStatus;

    dispatch_sync([ReaderDocument concurrentLoadingQueue], ^{
        readStatus = _status;
    });

    return readStatus;

}

If I would like to access the status property on the main thread do I need to take any precaution or there is nothing to take care of as I am just reading the property on the main thread?


texts: Shortening if-statements of displaying errors

texts:
Is it possible to shorten this piece of PHP code?

Honestly, I think it does not look clean but like a mess.

if(Input::exists() && $token) {
    if($validation->error('firstname') && $validation->error('lastname')) {
        echo str_repeat(' ', 20), '
↳ You did not enter your name.
', "\n";
    } else if($validation->error('firstname')) {
        echo str_repeat(' ', 20), '
↳ You did not enter your first name
', "\n";
    } else if($validation->error('lastname')) {
        echo str_repeat(' ', 20), '
↳ You did not enter your last name.
', "\n";
    }
}
if(!Input::exists()) {
        echo str_repeat(' ', 20), '
↳ We will address you by this name.
', "\n";
}

if(Input::exists() && $token) {
    if($validation->error('emailConfirm') == 'match') {
        echo str_repeat(' ', 20), '
↳ The email address you entered does not match.
', "\n";
    } else if($validation->error('emailConfirm') == 'type') {
        echo str_repeat(' ', 20), '
↳ You did not re-enter a valid email address.
', "\n";
    } else if($validation->error('emailConfirm')) {
        echo str_repeat(' ', 20), '
↳ You did not re-enter your email to confirm.
', "\n";
    }
}else if(!Input::exists()) {
        echo str_repeat(' ', 20), '
↳ Re-enter your email to make sure it\'s correct.
', "\n";
    }


texts: Detecting a certain amount of violet in an image - follow-up

texts:
I'm trying to write a program to detect the colour violet in an image.As discussed in my previous Post @Johnbot suggested that I try using HSL / HSV to determine if the pixel is some shade of violet.

this.button2.Click += async (sender, e) =>
{
    Task task = Task.Run(() =>
    {
      ProcessImage(pictureBox1.Image);
    });
      Task.WaitAll(task);
      await task;
    };
}

    private void ProcessImage(Image image)
    {
        if (image == null)
        {
            return;
        }
        using (var selectedImage = new Bitmap(image))
        {
            double total = 0;
            double infected = 0;

            Color violet = Color.FromKnownColor(KnownColor.Violet);
            Color selectedPixel;

            for (int x = 0; x < selectedImage.Width; x++)
            {
                for (int y = 0; y < selectedImage.Height; y++)
                {
                    selectedPixel = selectedImage.GetPixel(x, y);

                    if (selectedPixel.GetHue() == (violet.GetHue()))
                    {
                        infected++;
                    }
                    total++;
                }
            }
            //TODO: Needs to be rounded
            //Change the value eg: 0.0030, 0.0010, 0.0050
            try
            {
                double percentage = (infected / total);
                Console.WriteLine(percentage);

                double result;
                if (Double.TryParse(Convert.ToString(percentage).Substring(0, 6), out result))
                {
                    if (result > 0.0017)
                    {
                        MessageBox.Show(string.Format("Image is infected: {0:P}", percentage));
                    }
                    else
                    {
                        MessageBox.Show("Threshold not reached");
                    }
                }
            }
            catch
            {
                MessageBox.Show("No Violet Pixels Whatsoever were found");
            }
            finally
            {
                selectedImage.Dispose();
            }
        }
    }

Here are two of the images I'm working with.
The first one has the colour violet in it quite a lot with a percentage of 0.64% or 0.00636199367565126The second one from what I can tell doesn't have any violet in it, however the application believes it does with 0.36% violet pixels or 0.00355871886120996.The code above is working so to speak, however is there something I could be doing to improve it for reliability and performance? I did see a post about Bitmap locking however because its only going to be scanning a image every hour or so for any violet pixels, it didn't implement it, should i still do it?


texts: Method Ordering - Readability / Maintainability

texts:
What is your opinion on method ordering?

Should it be public methods at the top followed by private methods?

or

Should it be linear order so that methods calling methods stack on top of each other?

Which do you think is better for maintainability / readability?

Examples

Public first:

public class Main {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //
    }

    @Override
    protected void onResume() {
        startUploadActivity();
    }

    @FromXML
    public void onSignInClick(View button){
        startAuthorisationForYouTube();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultIsASignInAttempt(requestCode) && signedInSucccessfully(resultCode)){
            dealWithResult(data);
        } else
        if(resultIsASignInAttempt(requestCode) && signInFailed(resultCode)){
            startRefusalActivity();
        }
    }

@Override
protected void onStop() {
    super.onStop();
}

    private void startUploadActivity() {
        //
    }

    private void startAuthorisationForYouTube() {
        //
    }

    private static boolean resultIsASignInAttempt(int requestCode) {
        //
    }

    private static boolean signedInSucccessfully(int resultCode) {
        //
    }

    private static boolean signInFailed(int resultCode) {
        //
    }

    private void dealWithResult(Intent data) {
        //
    }

    private static Tokens getAccessTokens(Intent data) {
        //
    }

    private void startRefusalActivity() {
        //
    }
}

Calling order:

public class Main {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //
    }

    @Override
    protected void onResume() {
            startUploadActivity();

    }

    private void startUploadActivity() {
        //
    }

    @FromXML
    public void onSignInClick(View button){
        startAuthorisationForYouTube();
    }

    private void startAuthorisationForYouTube() {
        //
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultIsASignInAttempt(requestCode) && signedInSucccessfully(resultCode)){
            dealWithResult(data);
        } else
        if(resultIsASignInAttempt(requestCode) && signInFailed(resultCode)){
            startRefusalActivity();
        }
    }

    private static boolean resultIsASignInAttempt(int requestCode) {
        //
    }

    private static boolean signedInSucccessfully(int resultCode) {
        //
    }

    private static boolean signInFailed(int resultCode) {
        //
    }

    private void dealWithResult(Intent data) {
        //
    }

    private static Tokens getAccessTokens(Intent data) {
        //
    }

    private void startRefusalActivity() {
        //
    }

@Override
protected void onStop() {
    super.onStop();
}
}


texts:
I'm easing back into C after several months of using Python and Matlab. Can anyone give me some pointers on how to improve my code's efficiency and readability?

#include <stdio.h>

#define MAX_ARG 2

int count( char FNAME[] );

int main( int argc, char *argv[]) {
    if( argc > MAX_ARG ) {
        printf("Too many arguments ( %d ) supplied.\n", argc);
        return 0;
    }
    int FILE_LENGTH = 0;
    FILE_LENGTH = count( argv[1] );
    printf("The length of %s is: %d lines.\n", argv[1], FILE_LENGTH);
    return 0;
}

int count( char FNAME[] ) {
    FILE *fp;
    int CHR;
    int LINE_COUNT = 0;
    fp = fopen( FNAME,"r" );
    while( ( CHR = fgetc( fp ) ) != EOF ) {
        if( CHR == '\n' ) {
             LINE_COUNT++;
        }
    }
    fclose( fp );
    return LINE_COUNT;
}


texts:
Here is a snippet of code that generates a thumbnail from a given file.  It works well, but is much slower than desired.  Without using an external library (which I'm trying to avoid for learning purposes), is there anything that can be done to increase the speed?

I know the fastest way would be to retrieve the stored thumbnail.  I've looked into reading for any EXIF thumbnail data by parsing out the embedded information, but gave up since it was taking me a lot of effort with no finished end result.  Again, I'd prefer not to rely on a library specifically because I want to learn more about the format itself.

I know many will state right away I shouldn't be messing with EXIF data unless I use an external library, so as an alternative, what can be done specifically with this snippet to make things (significantly) faster?

Feel free to give me feedback about my coding style as well, except for the use of JavaDoc comments.

class ThumbIcon extends ImageIcon implements Runnable {
   public int    thumbWidth;
   public int    thumbHeight;

   Image         image;
   Graphics2D    g2dBuffer;
   ThumbButton   parent;
   BufferedImage scaledImage;

   public ThumbIcon(final ThumbButton theParent) {
      super();
      parent = theParent;
   } // End ThumbIcon(ThumbButton, String)

   public void run() {
                         image   = Toolkit.getDefaultToolkit().getImage(filePath);
      final MediaTracker tracker = new MediaTracker(new Container());
      tracker.addImage(image, 0);
      try {
         tracker.waitForID(0);
      } catch (InterruptedException e) {
         System.out.println("Interrupted getting thumb");
      } // End try

      // Get dimensions from the now-loaded image
      final int width   = image.getWidth(null);
      final int height  = image.getHeight(null);

      // Use the width to determine if the image is legitimate and loaded
      // Limit importable images to <54MiB or <51.5MP (9000px x 6000px)
      if ((width > 0) && (width * height < 54000000)) {
         // This is an actual image, so display on screen

         // Set the thumbnail size depending on image orientation
         // We are assuming a square thumbnail
         if (width > height) { // Landscape
            thumbWidth  = THUMBS_SIZE;
            thumbHeight = (int)((double)height / (double)width * THUMBS_SIZE);
         } else {              // Portrait
            thumbWidth  = (int)((double)width / (double)height * THUMBS_SIZE);
            thumbHeight = THUMBS_SIZE;
         } // End if

         scaledImage = new BufferedImage(thumbWidth, thumbHeight,
                                         BufferedImage.TYPE_INT_RGB);

         // Simultaneously load image into g2d buffer and scale to desired size
         g2dBuffer = scaledImage.createGraphics();
         g2dBuffer.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

         //g2dBuffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
         //                           RenderingHints.VALUE_ANTIALIAS_ON);

         // Size image (no matter initial size) to destWidth x destHeight
         g2dBuffer.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
         ...
         // Create the thumbnail
         setImage(Toolkit.getDefaultToolkit().createImage(scaledImage.getSource()));
         scaledImage.flush();
         image.flush();
         //g2dBuffer.finalize();
         g2dBuffer = null;
      } else {
         ...
      } // End if
   } // End run()
   ...
} // End ThumbIcon

I shaved off some time by disabling anti-aliasing.  It looks nasty, but it serves its purpose.


texts: Building an ACL based on permission level

texts:
I'm building a symfony project and at some point I've come up with a switch case to manage the acl rights. I would prefer using a dynamic access to the constant but havn't find a good solution. I've seen reflection but that doesn't seem to be the proper solution to me.

$mask = null;

switch ($participant->getRight()) {
    case 'VIEW':
        $mask = MaskBuilder::MASK_VIEW;
        break;
    case 'EDIT':
        $mask = MaskBuilder::MASK_EDIT;
        break;
    case 'OPERATOR':
        $mask = MaskBuilder::MASK_OPERATOR;
        break;
    default:
        break;
}
$this->aclManager->addObjectPermission($project, $mask, $user);

So, this switch is in a foreach, that gets the $user entity, then with the result of the list box from the view, I get the rights of the user which can be (for now) EDIT VIEW or OPERATOR. These right were chosen because they are directly related to the MaskBuilder masks.

The thing is, if there is a refactor to be done, I will need to modify this switch AND the part where the form is defined. I would like to do something like

$mask = 'MASK_' . $participant->getRight();
$this->aclManager->addObjectPermissions($project, MaskBuilder::$mask, $user);

But havn't find a way to do it.

Is my switch a good way to do it ? Or is there a proper php way to do the same, that would reduce refactor cost?