texts: Determine whether three sides form a valid triangle, and classify the triangle

texts:
This is a my first Python program, and whilst I am new to Python I would like to keep in good practice

Below is a short program to work out what type a triangle is and if it makes a valid triangle

I have tried to use as little documention for this as possible to try and get used to how things work in Python so I can only imagine the mistakes I have made. However please do mention anything that should have be done better

# Determin if triangle is Scalene. Isosceles or equilateral
# Also works out if lengths can make a triangle

from decimal import *

getcontext().prec = 3
getcontext().rounding = ROUND_HALF_UP

#Needs to be divided to re-set decimal place I think
a = Decimal(input("Length of side a = ")) / 1
b = Decimal(input("Length of side b = ")) / 1
c = Decimal(input("Length of side c = ")) / 1

if a != b and b != c and a != c:
    print("This is a a Scalene triangle")
    triangle_type = 'Scalene'
elif a == b and c == b:
    print("This is an Equilateral triangle")
    triangle_type = 'Equilateral'
else:
    print("This is an Isosceles triangle")
    triangle_type = 'Isosceles'

def is_valid_triangle(a, b, c,triangle_type):
    if triangle_type == 'Equilateral':
        return True #all same lengths will be a valid triangle
    elif triangle_type == 'Isosceles' or triangle_type == 'Scalene':
        if a == b:
            return a + b > c
        elif b == c:
            return b + c > a
        elif a == c:
            return a + c > b
        else: #This will be the scalene triangle
            return a + b > c
    else:
        return False #Message is unclear as could be lengths are negitive or correct int type not used

print('Is this a valid triangle?', is_valid_triangle(a,b,c,triangle_type))


texts: Improving time efficiency of finding maximum area rectangles in a histogram

texts:
Here's my solution but I am looking for ways to improve the time complexity of solution. Also this question is categorized as being solved by stack so I would like to know how to approach it using stacks?

Problem statement: Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

class Solution:
    # @param A : list of integers
    # @return an integer
    def largestRectangleArea(self, A):
        global_max_sum = 0
        if len(A) == 0:
            return None
        for i in range(len(A)):
            count = 1
            round_max_sum = 0
            while i+count  <= len(A)-1:
                sum = min(A[i:i+count+1]) *  (count+1)
                count += 1
                if sum >= round_max_sum:
                    round_max_sum = sum
                if round_max_sum > global_max_sum:
                    global_max_sum = round_max_sum
        return max(global_max_sum, max(A))

s = Solution()
#list = []
#list = [1]
#list = [ 2, 82, 11, 89, 7, 21, 92, 13, 11, 94, 4, 96, 3 ]
#list = [ 90, 58, 69, 70, 82, 100, 13, 57, 47, 18 ]
"""
list =  [ 65, 19, 8, 39, 14, 21, 83, 87, 95, 11, 14,
          58, 11, 90,34, 96, 34, 62, 96, 38, 58, 57,
          12, 78, 57, 60, 7, 58,56, 49, 36, 67, 69,
          30, 74, 46, 97, 62, 47, 42, 43, 98,60, 32,
          39, 75, 69, 28, 35, 52, 89, 78, 4, 26, 65,
          21,39, 89, 87, 69, 48, 60, 6, 21, 5, 98, 52, 59 ]
"""
#list = [51,33]
list = [ 6, 2, 5, 4, 5, 1, 6 ]

print(s.largestRectangleArea(list))


texts: Use of scoped objects in a JavaScript Tic-tac-toe implementation

texts:
I have been using the w3 org's JavaScript Best Practices web page's examples for coding an object literal for a game.

It is my understanding that I should use this to keep all my variables and arrays that are not associated with/inside functions. I should then use methods to access and update the values and arrays.

I wanted to make sure I was on the right track (and learning code practices) before I got too far into the code.

So, using the code listed below, I would access values as follows:

var valueSquareA = t3Game.checkSquare(a);

and

var arrSq = t3Game.getSquares();

var t3Game = (function(){

    var playerImg = "images/blankSpace.gif";
    var compImg = "images/blankSpace.gif";

    var squares = []; // For keeping track of the board.

    return{
        getImgFileName: function(playerOrComp){
            if(playerOrComp ==="player"){
                return playerImg;
            }
            else {
                return compImg;
            }
        },

        setImgFileName: function(choice){
            if(choice === "X"){
                playerImg = "images/X.gif";
                compImg = "images/O.gif";
            }
            else {
                playerImg = "images/O.gif";
                compImg = "images/X.gif";
            }
        },

        setBoard: function(){
            for(i=1; i<=9; i++){
                squares[i] = "empty";
            }
            // alert(squares);
        },

        setSquare: function(nbr, playerOrComp){
            squares[nbr] = playerOrComp;
            // alert(squares);
        },

        checkSquare: function(nbr){
            return squares[nbr];
        },

        getSquares: function(){
            return squares;
        }

        } // end return

})();


texts: How effective is it to default to user input in C++ function parameters?

texts:
This defaults to user input if the arguments are not passed at compile time.. How effective is this technique and where can it be applied?

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

void foo(unsigned number = []() {unsigned num = 0; std::cin >> num; return num; } ()) {
    std::cout << number << "\n";
}

int main() {
    foo(1); //prints 1
    foo();  //defaults to user input
    return 0;
}


texts: Count complete trips to the basement and back to ground floor

texts:
An elevator starts on the ground floor 0 and moves up or down by one floor at a time as described by an input string travel. Here's an example travel string udddudduuuuddu where u is a move up 1 floor and d is a move down 1 floor.
count-basement-trips takes a travel string and counts how many times the elevator returns back to the ground floor from the dark and mysterious underground levels.
(defun count-basement-trips (travel)
  (flet ((finished-basement-trip-p (old-floor new-floor)
           (and (= -1 old-floor)
                (=  0 new-floor)))
         (change (c)
           (if (char= c #\u) 1 -1)))
    (let ((floor 0)
          (count 0))
      (loop for c across travel
            do (let ((new-floor (+ floor (change c))))
                 (if (finished-basement-trip-p floor new-floor)
                     (incf count))
                 (setf floor new-floor)))
      count)))

(count-basement-trips "udddudduuuuddu")

The last expression evaluates to 2.
What changes would make this more idiomatic Common Lisp? My goal is to speak more like a native. Thanks!


texts: Determining the number of days in a month

texts:
Overall logic: determine number of days in a month. Loop through table (wsUploadTable) and increment value if condition is met. Loop to next day in month and repeat.

For example: 10/1/2016, loops through table for date match and increment value. Next date, 10/2/2016 loop table for match... until last day of month 10/31/2016, loop table, find match and increment value.

'Determine DaysinMonth and assign DaysinMonth_Distro value
DaysInMonth = DateSerial(dtTrickle_Year, dtTrickle_Month + 1, 1) - _
              DateSerial(dtTrickle_Year, dtTrickle_Month, 1)
DoM_Distro = 1 / DaysInMonth

ReDim Days(1 To DaysInMonth)
For i = 1 To DaysInMonth
    Days(i) = DateSerial(dtTrickle_Year, dtTrickle_Month, i)

  'loop table and increment cell value if condition is met

    With wsUploadTable
    lngER_PrimaryID = .Cells(1048576, 2).End(xlUp).Row
        For intPrimaryID = 2 To lngER_PrimaryID
            'store current cell value
            dblLeadsValue = .Cells(intPrimaryID, col_Upload_Leads)
            'match UploadTable row on user input and increment new value
              If.Cells(intPrimaryID, 3).Value = Days(i) Then
              .Cells(intPrimaryID, 11).Value = dblLeadsValue + DoM_Distro
            End If
        Next 'Next PrimaryID
    End With
Next i


texts: Transform DataReader to List using reflections

texts:
I have implemented the code to convert datareader to list of objects. My intention was to not to use column name string literals while reading the datareader.

public static IEnumerable<T> GetListFromDataReader<T>(IDataReader reader) where T : new()
{
    var properties = typeof(T).GetProperties();

    var modelProperties = new List<string>();
    var columnList = (reader.GetSchemaTable().Select()).Select(r => r.ItemArray[0].ToString());
    while (reader.Read())
    {
        var element = Activator.CreateInstance<T>();
        Dictionary<string, string> dbMappings = DBColumn(element);
        string columnName;
        foreach (var f in properties)
        {

            if (!columnList.Contains(f.Name) && !dbMappings.ContainsKey(f.Name))
                continue;
            columnName = dbMappings.ContainsKey(f.Name) ? dbMappings[f.Name] : f.Name;
            var o = (object)reader[columnName];

            if (o.GetType() != typeof(DBNull)) f.SetValue(element, ChangeType(o, f.PropertyType), null);
        }
        yield return element;
    }

}

public static object ChangeType(object value, Type conversion)
{
    var t = conversion;

    if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        if (value == null)
        {
            return null;
        }

        t = Nullable.GetUnderlyingType(t); ;
    }

    return Convert.ChangeType(value, t);
}

public static Dictionary<string,string> DBColumn<T>(T item) where T:new()
{

    Dictionary<string, string> dbMappings = new Dictionary<string, string>();
    var type = item.GetType();
    var properties = type.GetProperties();
    foreach (var property in properties)
    {
        var attributes = property.GetCustomAttributes(false);
        var columnMapping = attributes
    .FirstOrDefault(a => a.GetType() == typeof(DbColumnAttribute));
        if (columnMapping != null)
        {
            dbMappings.Add(property.Name, ((DbColumnAttribute)columnMapping).Name);
        }
    }
    return dbMappings;
}

Can somebody help me by providing a review?  I am doubtful of too much usage of reflections in loops would downgrade the performance. Or should I compromise and better to go with string literals itself while reading?


texts:
I have created a blackjack game in Python3 but I am worried that it is not very efficient and also there are some problems with it.
Problem 1) The player almost always wins unless he goes bust as the program allows the player to take multiple cards but the computer only chooses 2 and I can't think of any solutions.
Problem 2) Because of how I have done the choosing of the suits it is entirely possible to get e.g. 2 Kings of spades which is impossible with a regular deck of cards.
Since I am new to python any help would be much appreciated.

import random

cards = {
    "Ace": 1,
    "two": 2,
    "three": 3,
    "four": 4,
    "five": 5,
    "six": 6,
    "seven": 7,
    "eight": 8,
    "nine": 9,
    "ten": 10,
    "Jack": 10,
    "Queen": 10,
    "King": 10
}

suits = [" of spades", " of clubs", " of hearts", " of diamonds", " of spades", " of clubs", " of hearts",
         " of diamonds", " of spades", " of clubs", " of hearts", " of diamonds", " of spades", " of clubs",
         " of hearts", " of diamonds", " of spades", " of clubs", " of hearts", " of diamonds", ]

again = "yes"

while again == "yes":

    def firstcards():
        global first_card
        global second_card
        global total
        total = 0
        first_card = random.choice(list(cards))
        second_card = random.choice(list(cards))
        total += cards.get(first_card)
        total += cards.get(second_card)

    firstcards()

    def gameplay():
        global total
        another_card = "yes"
        print("Your first card is the " + first_card + random.choice(suits))
        print("Your second card is the " + second_card + random.choice(suits))
        print("Your total is: " + str(total))

        while another_card == "yes" and total < 21:
            print("Would you like another card?")
            another_card = input("Y/N:  ")
            if another_card == "Y":
                card = random.choice(list(cards))
                total += cards.get(card)
                print("Your next card is the " + card + random.choice(suits))
                print("Your total is now: " + str(total))
                another_card = "yes"
            elif another_card == "N":
                num1 = random.randint(1, 10)
                num2 = random.randint(1, 10)
                computerTotal = num1 + num2
                print("The computer got a total of " + str(computerTotal))
                if computerTotal > total:
                    print("The computer wins!")
                else:
                    print("You win!")
                another_card = "no"
            else:
                print("That is not a valid option.")
                another_card = "yes"
        if total > 21:
            print("You have gone bust!")
            print("The computer wins!")

        def play_again():
            global again
            print("")
            print("Would you like to play again?")
            again = input("yes/no: ")
            if again != "yes" and again != "no":
                print("That is not a valid option")
                play_again()
            elif again == "yes":
                print("")
                print("")
            elif again == "no":
                again = "no"
        play_again()

    gameplay()

Once again any help would be much appreciated.


texts: Parse recursively a json object with AngularJS

texts:
Is there a better way, or the correct one to have this approach for a JSON object that hast the following structure? (it's only a portion of my object, the most important one)

{
    "Questions": [
        {
            "AnswerType": "single-choice",
            "Answers": [
                {
                    "AnswerValue": null,
                    "Description": "Yes",
                    "ID": 124877,
                    "Questions": [
                        {
                            "AnswerType": "multiline",
                            "Answers": [
                                {
                                    "AnswerValue": null,
                                    "Description": null,
                                    "ID": 124879,
                                    "Questions": []
                                }
                            ],
                            "Description": "Other text",
                            "ID": 37932,
                            "SelectedAnswers": []
                        },
                        {
                            "AnswerType": "singleline",
                            "Answers": [
                                {
                                    "AnswerValue": null,
                                    "Description": null,
                                    "ID": 124880,
                                    "Questions": []
                                }
                            ],
                            "Description": "Hoeveelperweek?",
                            "ID": 37933,
                            "SelectedAnswers": []
                        }
                    ]
                },
                {
                    "AnswerValue": null,
                    "Description": "No",
                    "ID": 124878,
                    "Questions": []
                }
            ],
            "Description": "Question text",
            "ID": 37931,
            "SelectedAnswers": []
        }
    ]
}

AngularJS template for parsing it recursively:

    {{question.Description}}

        {{answer.Description}}

            {{qanswer.Description}}

The structure can go infinitely. This is the structure that is being repeated over and over:

Questions []
-Answers []
--Answer [i]
---Questions []

JSBin example is here


texts: Using reflection in a test to check if a private variable is really null after a function, is this okay?

texts:
I am using reflection to check if a private variable is set to null after the logout function. This is needed because the getUser function will always attempt to set and return an user if no user is set. Am I doing something wrong or can I do something better?

This is the bean that has the logout and getUser function:

@ManagedBean(name = "authBean")
@SessionScoped
public class AuthorizationBean implements Serializable{

    //Data access object for the users
    @Inject
    UserDao userDao;

    private User user; // The JPA entity.
    public User getUser() {
        if (user == null) {
            user = (User) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
            if (user == null) {
                Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
                if (principal != null) {
                    user = userDao.findByEmail(principal.getName()); // Find User by j_username.
                }
            }
        }
        return user;
    }

    /**
     * Function that handles the logout
     * @return Redirect string that points to the login page
     */
    public String doLogout() {
        // invalidate the session, so that the session is removed
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        user = null;
        // return redirect to login page
        return "/login.xhtml?faces-redirect=true";
    }

}

This is the test class, with the reflection:

@RunWith(PowerMockRunner.class)
@PrepareForTest(FacesContext.class)
public class AuthorizationBeanTest {

    private AuthorizationBean authorizationBean;

    @Mock
    User user;

    @Mock
    FacesContext facesContext;

    @Mock
    ExternalContext externalContext;

    @Before
    public void setUp() {
        authorizationBean = new AuthorizationBean();
        Map<String,Object> sessionMap = new HashMap<>();
        sessionMap.put("user", user);

        //Mocking the static function getCurrentInstance from FacesContext,
        //so a mocked user can be returned for the test
        PowerMockito.mockStatic(FacesContext.class);
        PowerMockito.when(FacesContext.getCurrentInstance()).thenReturn(facesContext);
        when(facesContext.getExternalContext()).thenReturn(externalContext);
        when(externalContext.getSessionMap()).thenReturn(sessionMap);
    }

    @Test
    public void doLogoutTest() throws NoSuchFieldException, IllegalAccessException {
        assertNotNull(authorizationBean.getUser());
        assertEquals("/login.xhtml?faces-redirect=true", authorizationBean.doLogout());

        //Check through reflection if the private field user is now null
        Field userField = authorizationBean.getClass().getDeclaredField("user");
        userField.setAccessible(true);
        User testUser = (User) userField.get(authorizationBean);
        assertNull(testUser);
    }

}


texts:
I implemented a virtual file system library with POSIX file mode representation.
Any suggestions regarding optimization are welcome.

"""POSIX file system library."""

from collections import namedtuple

__all__ = ['PosixPermission', 'PosixMode']

MIN_PERM = 0b000
MAX_PERM = 0b111
DEF_PERM = 0b110    # rw-
MIN_MODE = 0o000
MAX_MODE = 0o777
DEF_MODE = 0o640

class PosixPermission(namedtuple('PosixPermission', 'read write execute')):
    """POSIX file permissions."""

    @classmethod
    def from_int(cls, perm=DEF_PERM):
        """Creates the file permissions from the respective integer value."""
        if MIN_PERM <= perm <= MAX_PERM:
            return cls(bool(perm & 4), bool(perm & 2), bool(perm & 1))

        raise ValueError('Permission value must be between {} and {}.'.format(
            MIN_PERM, MAX_PERM))

    def __int__(self):
        """Returns the integer value of the file permission."""
        return (self.read and 4) + (self.write and 2) + (self.execute and 1)

    def __str__(self):
        """Returns binary representation of the file permission."""
        return ''.join(map(
            lambda perm: perm or '-',
            (self.read and 'r', self.write and 'w', self.execute and 'x')))

class PosixMode(namedtuple('PosixMode', 'user group other')):
    """POSIX file mode."""

    @classmethod
    def from_int(cls, mode=DEF_MODE):
        """Creates the file mode from the respective integer value."""
        if MIN_MODE <= mode <= MAX_MODE:
            return cls(
                PosixPermission.from_int(mode >> 6 & 7),
                PosixPermission.from_int(mode >> 3 & 7),
                PosixPermission.from_int(mode & 7))

        raise ValueError('File mode must be between {} and {}.'.format(
            oct(MIN_MODE), oct(MAX_MODE)))

    def __int__(self):
        """Returns the integer value of the file mode."""
        return (int(self.user) << 6) + (int(self.group) << 3) + int(self.other)

    def __str__(self):
        """Returns the octal representation of the file mode."""
        return ''.join((str(self.user), str(self.group), str(self.other)))


texts:
Currently, I'm writing a program that encrypts/decrypts text using Caesars cipher.  The code below shifts a character.

    /// <param name="originalChar"> char to shift </param>
    /// <param name="shift"> amount to shift by </param>
    /// <param name="letterA"> letter A in ASCII </param>
    /// <param name="lettera"> letter a in ASCII </param>
    /// <param name="letterCount"> range of alphabet </param>
    /// <returns> shifted letter </returns>
    private static char Shifter(char originalChar, int shift, int letterA, int lettera, int letterCount)
        => (char) (letterA + (char.ToUpper(originalChar) - letterA + shift + letterCount) % letterCount
                + (char.IsLower(originalChar) ? lettera - letterA : 0));

This happens by shifting the char around the upper case alphabet then if it was originally a lower case char move it up to the lowercase part of ASCII.

I don't think my current method of doing this is particularly efficient and I can't think of anything to improve it.


texts: Subscribing and manipulating data from API in Angular

texts:
I'm trying to display the fetched data on a table. I structured the data based on the columns table in the UI and stored them in an array, then *ngFor on the table rows on the frontend. Good or bad practice? Or are there other ways to do this in a much simpler way?

    getLicensesofDealer(id) {
        this._license.get_license_by_id(id).subscribe(
            (data: License[]) => {
                let counter = 1;

                // Structure data and store in an array
                data.forEach(l => {
                    const license = {
                        unique_key: l.licenseId,
                        count: counter,
                        key: l.licenseKey,
                        date: l.dateCreated
                    }
                    this.license_data.push(license);
                    counter++;
                })
                // Structure data and store in an array

            }
        )
    }


texts:
With my original code I kept getting Error: Parse error: [expr level ;] expected after "in" (in [expr]) on the line let numDigits = numDigits - 1 in

Original:

let rec rev_int num =
  if num / 10 == 0 then
     num
  else
    let temp = num mod 10 in

    let numDigits = String.length(string_of_int num) - 1 in

    if num < 0 then
      let numDigits = numDigits - 1 in
    else
      let numDigits = numDigits + 0 in

    let num = (num - temp) / 10 in
    temp * int_of_float(10.0 ** float_of_int numDigits) + rev_int num

With variations of:

if num < 0 then
   let numDigits = numDigits - 1 in;
else
   let numDigits = numDigits + 0 in;

if num < 0 then
   let numDigits = numDigits - 1 in
else begin
   let numDigits = numDigits + 0 in end

I revised the code and now it works, but I was wondering if there was a way to do it with nested if and less redundancy.

Revised:

let rec rev_int num =
  if num / 10 == 0 then
    num
  else
    let temp = num mod 10 in

    let numDigits = String.length(string_of_int num) - 1 in

    if num < 0 then
      let numDigits = numDigits - 1 in
      let num = (num - temp) / 10 in
      temp * int_of_float(10.0 ** float_of_int numDigits) + rev_int num
    else
      let numDigits = numDigits + 0 in
      let num = (num - temp) / 10 in
      temp * int_of_float(10.0 ** float_of_int numDigits) + rev_int num


texts: Project Euler 357 prime number generator in Python 3

texts:
I'm brute forcing the Project Euler 357 since no better algorithm comes to my mind. The challenge asks:

  Find the sum of all positive integers n not exceeding 108 such that for every divisor d of n, d+n/d is prime.

The code is this:

#!/bin/env python3

import time
import math

"""
https://projecteuler.net/problem=357

"""

start = time.time()

def primes(ubound=10**5):
    """ Generating prime numbers LIST
        https://stackoverflow.com/a/8627193/1770460
    """
    size = (ubound - 3) // 2
    a = [False] * size
    s = 0
    primes = []
    while s < size:
        t = 2 * s
        p = t + 3
        primes.append(p)
        for n in range(t * (s + 3) + 3, size, p):
            a[n] = True
        s = s + 1
        while s < size and a[s]:
            s = s + 1
    return primes

the_primes = primes()

def number_divisors(max_limit=10**5):
    """ Find the divisors of every number.
        Return it in a dict in the format:
        { number1: [divisor1, divisor2 ... ], .. }
    """
    num_divs = {}
    for i in range(4, max_limit):
        if i in the_primes:
            continue
        else:
            sq = math.sqrt(i)
            for n in range(2, int(sq) + 1):
                if i not in num_divs:
                    num_divs[i] = [1]
                if i % n == 0:
                    if n == i / n:
                        num_divs[i].append(n)
                    else:
                        num_divs[i].extend((n, i / n))
    return num_divs

def find_count(d):
    """ Check every number whether the divisors i.e. d + number / d is
        prime.
    """
    assert d is not None

    count = 0
    for number, list_divisors in d.items():
        all_primes = True
        for each_div in list_divisors:
            val = (each_div + (number / each_div))
            if val not in the_primes:
                all_primes = False
                break
        if all_primes:
            count += 1
    return count

if __name__ == '__main__':

    num_divisors = number_divisors()
    print(find_count(num_divisors))

    elapsed_time = (time.time() - start)
    print('time elapsed %s sec.' % elapsed_time)

Profiling the script shows that the find_count is the first bottleneck and by advice of other answers the values should be cached(?) somehow.

$ python3 -m cProfile 357.py
275
time elapsed 167.41558241844177 sec.
         583580 function calls in 167.416 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000  167.416  167.416 357.py:3(<module>)
        1    0.020    0.020    0.020    0.020 357.py:30(primes)
        1   24.526   24.526   24.740   24.740 357.py:51(number_divisors)
        1  142.655  142.655  142.655  142.655 357.py:75(find_count)

Any advice on how to improve find_count()?


texts: Aspect-oriented vs explicit style in Python

texts:
Readability counts, but is very subjective. The following snippets are equivalent in functionality and turn a generator iterator into a chunked HTTP response in Flask. Which of those two patterns is more Pythonic, readable and convenient?

A) Aspect style with function decorators that change the return value:

@app.route('/')
@flask_response_decorator
@optional_streaming_decorator
@progress_log_decorator
def index() -> Iterator:
    """Index page, optionally HTTP chunk-streamed and formatted."""
    return Foo.get_instance().are_changes_locked()

or

B) explicit decorators within the function body

@app.route('/')
def index() -> flask.Response:
    """Index page, optionally HTTP chunk-streamed and formatted."""
    response = Foo.get_instance().are_changes_locked()
    return flask.Response(optional_iterator_to_stream(iterator_to_progress_log(response)))


texts: Get only intended input from user through the console

texts:
I finally worked out all of the bugs in this bit of code. I'm pretty proud of it and I wanted to give it to all of you so that you could have it if you wanted it for any console programs that you make.

At the same time, this is ridiculous. C++ is double my age and there should seriously be a better way of getting valid, error free, inputs from the user. If anyone knows, please tell me.

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

void gValid_Input(std::string& var, std::string question) {
    using namespace std;

    do {
        cin.clear();
        cin.sync();
        cout << question;

        // Code will not work as intended on Linux without the following
        // but will work on windows (tested with g++)
        // this must also be done after clearing, syncing cin
        // and asking the question string otherwise the code will loop forever
        if (cin.peek() == '\n'){
            cin.ignore(1,'\n');
        }
    } while (!(getline(cin, var)));
}

template <typename t>
void gValid_Input(t& var, std::string question) {
    using namespace std;

    do {
        cin.clear();
        cin.sync();
        cout << question;
    } while (!(cin >> var));
}

void gValid_Option(char& response, std::vector<char> valid_Responses = {'y','n'}){
    using namespace std;
    const char diff = 'a' - 'A';

    do{
        cin.clear();
        cin.sync();
        cin >> response;

        // Comment the following out if you care about getting an upper case answer
        if (response >= 'A' && response <= 'Z'){
            response += diff;
        }

    } while (find(valid_Responses.begin(), valid_Responses.end(), response) == valid_Responses.end());
}

void gValid_Option(char& response, std::string question, std::vector<char> valid_Responses = {'y','n'}){
    using namespace std;
    const char diff = 'a' - 'A';

    do{
        cin.clear();
        cin.sync();
        cout << question;
        cin >> response;

        // Comment the following out if you care about getting an upper case answer
        if (response >= 'A' && response <= 'Z'){
            response += diff;
        }

    } while (find(valid_Responses.begin(), valid_Responses.end(), response) == valid_Responses.end());
}


texts:
As a part of my Tabv Vim plugin (which at this stage is nothing more than a pitiful rag-tag assortment of half-baked hacks), I have a function which attempts to guess the directory paths for main source and unit tests. The first working version of this function is (full source):

let g:tabv_grunt_file_path='Gruntfile.js'

function s:GuessPathsFromGruntfile()
    execute "sview " . g:tabv_grunt_file_path
    global/^\_s*['"].*\*\.spec\.js['"]\_s*[,\]]\_s*/y a
    let l:matches = matchlist(getreg('a'), '[''"]\(.*\)/\*\.spec\.js[''"]')
    if len(l:matches) > 1
        let g:tabv_javascript_unittest_directory = l:matches[1]
    endif
    global/^\_s*['"].*\*\.js['"]\_s*[,\]]\_s*/y a
    let l:matches = matchlist(getreg('a'), '[''"]\(.*\)/\*\.js[''"]')
    if len(l:matches) > 1
        let g:tabv_javascript_source_directory = l:matches[1]
    endif
    close
endfunction

Also relevant, from the same script, and above the function shown:

let g:tabv_javascript_source_directory="src"
let g:tabv_javascript_source_extension=".js"
let g:tabv_javascript_unittest_directory="unittests"
let g:tabv_javascript_unittest_extension=".spec.js"

Now, the algorithm needs some help, but that's not what I'm worried about at the moment. (I try to build out this plugin on an as-needed basis, rather than going for the gold, so to speak.) What I do not like is:

The code duplication

The fact that the first and second parts of the function are similar.
The fact that I am not using the global variables for the file extensions in the regular expression.

The fact that I am actually visually opening and closing the Gruntfile.
The execute statement

What else do you see wrong here, and how could I do better? What can I do to correct the problems mentioned above?


texts: Finding weight on various different planets

texts:
I'm hoping I could get some help in understanding as well as optimizing code! I've been working on a few exercises on some online resources, and I decided to try and take it to the next level and start using methods.

import java.util.Scanner;

public class SpaceBoxing
{
    static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args)
    {
        double weight = getEarthWeight();
        int choice = getPlanetChoice();
        double realWeight = computeEffectiveWeight(weight, choice);
        System.out.println("Your weight would be " + realWeight + " on that planet. ");
    }

    static double getEarthWeight()
    {
        System.out.println("Please enter your current Earth weight: ");
        return keyboard.nextDouble();
    }

    static int getPlanetChoice()
    {
        System.out.println("I have information on the following planets: ");
        System.out.println("1. Venus");
        System.out.println("2. Mars");
        System.out.println("3. Jupiter");
        System.out.println("4. Saturn");
        System.out.println("5. Uranus");
        System.out.println("6. Neptune");
        return keyboard.nextInt();
    }

    static double computeEffectiveWeight(double weight, int choice)
        {
            double realWeight = 0;
            if(choice == 1)
                realWeight = (weight * 0.78);

            else if(choice == 2)
                realWeight = (weight * 0.39);

            else if(choice == 3)
                realWeight = (weight * 2.65);

            else if(choice == 4)
                realWeight = (weight * 1.17);

            else if(choice == 5)
                realWeight = (weight * 1.05);

            else if(choice == 6)
                realWeight = (weight * 1.23);

            return realWeight;
        }
}

I've been working on calling methods and passing parameters between them, and so far I think I've got 2/3 of the methods completed except for the final one. Just a quick run down, I'm using the first two methods to return a typed input, and saving them into weight and choice. And the final method will take those two variables and computes a final result, which I hope to be able to print out. I'm not sure what to return the input values as, because I'm trying to pull the parameter and use it in another... instead of passing it in.

I'm not sure, but what am I missing? Are there some style things that I should do? Is there a better way in doing this (still with methods though)?


texts: Project Euler #8 in C++: greatest product of k consecutive digits

texts:
This a problem from Hackerrank.com and Project Euler #8. The problem statement is as below. Is there a specific algorithm to solve such problems? Can my code be made more efficient?

  Find the greatest product of K consecutive digits in the N digit
  number.

  Input Format: First line contains T that denotes the number of test cases.  First line of each test case will contain two integers
  N & K. Second line of each test case will contain an N digit
  integer.

  Output Format

  Print the required answer for each test case.

  Constraints

  \$1 \le T \le 1000\$

  \$1 \le K \le 7\$

  \$K \le N \le 1000\$

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ctoi(c)(int)((c)-'0')

inline unsigned long long prodK(string number, int start, int end){
    unsigned long long product=1;
    for (int j=start;j<end;j++){
        product*=ctoi(number[j]);
    }
    return product;
}

int main() {
    int T,N,K;
    string number;
    unsigned long long product,max;
    cin>>T;
    for (int i=0;i<T;i++){
        cin>>N>>K;
        cin>>number;
        product=1;
        product=prodK(number,0,K);
        max=product;
        for (int l=K;l<N;l++){
            if (ctoi(number[l-K])!=0){
                product=(product/ctoi(number[l-K]))*ctoi(number[l]);
            }else{
                product=prodK(number,l-K+1,l+1);
            }
            max=(product>max)?product:max;
        }
        cout<<max<<"\n";
    }
    return 0;
}


texts: Create custom Queue class with O(1) Enqueue and O(1) Dequeue

texts:
I am implementing a Queue class in C# using a Node/LinkedList class that I also implemented, and I wonder if there is a way to implement the enqueue and the dequeue methods, both in algorithmic efficiency of \$O(1)\$.

In the Queue class I have a field of the tail and the head, and I managed to implement the enqueue method in \$O(1)\$, but the dequeue is \$O(n)\$.

This is the code for the Node and the Queue classes:

public class Node<T>
{
    #region Fields

    private Node<T> next;
    private T data;

    #endregion Fields

    #region Constructors

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

    public Node(T data) : this(data, null)
    {

    }

    #endregion Constructors

    #region Properties

    public Node<T> Next
    {
        get { return next; }
        set { next = value; }
    }

    public T Data
    {
        get { return data; }
        set { data = value; }
    }

    #endregion Properties

    #region Methods

    public bool HasNext()
    {
        return next != null;
    }

    #endregion Methods
}

public class Queue<T>
{
    private Node<T> head;
    private Node<T> tail;

    public Queue()
    {
        head = null;
        tail = null;
    }

    public void Enqueue(T data)
    {
        if (IsEmpty())
            head = new Node<T>(data);
        else if (tail == null)  // There is only one element in the queue
            tail = new Node<T>(data, head);
        else
            tail = new Node<T>(data, tail);
    }

    public T Dequeue()
    {
        if (IsEmpty())
            throw new InvalidOperationException("The queue is empty");

        T data = head.Data;

        if (tail == null)  // There is only one element in the queue
        {
            head = null;
            return data;
        }

        Node<T> temp = tail;

        while (temp.Next != head)  // Get the previous Node of the head
            temp = temp.Next;

        temp.Next = null;
        head = temp;

        if (tail == head)
            tail = null;

        return data;
    }

    public T Head()
    {
        if (IsEmpty())
            throw new InvalidOperationException("The queue is empty");

        return head.Data;
    }

    public bool IsEmpty()
    {
        return head == null;
    }
}


texts:
I wrote simple generic function to check if any STL container has an element. It seems work fine. I have tested it with VC++, GCC and Clang compilers. It works perfectly.

How can I improve it further.

#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <set>
#include <vector>
#include <array>
#include <type_traits>

// Detect if container has C::find
template <typename C> decltype(std::declval<C>().find(0), std::true_type{}) test(int);
template <typename C> std::false_type test(...);
template <typename C> using has_find = decltype(test<C>(0));

// Based on std::conditional
template <bool B, typename T, typename F>
struct conditional_impl
{
    constexpr static F pick(T&& , F&& f)
    {
        return std::forward<F>(f);
    }
};

template <typename T, typename F>
struct conditional_impl<true, T, F>
{
    constexpr static T pick(T&& t, F&&)
    {
        return std::forward<T>(t);
    }
};

template <bool B, typename T, typename F>
auto conditional(T&& t, F&& f)
{
    return conditional_impl<B,T,F>::pick(std::forward<T>(t), std::forward<F>(f));
}

// one for all and all for one
template <typename C, typename T>
auto contains(const C& container, const T& key)
{
    static auto first = [] (auto&& c, auto&& k)
    {
        return c.end() != c.find(k);
    };

    static auto second = [] (auto&& c, auto&& k)
    {
        return c.end() != std::find(c.begin(), c.end(), k);
    };

    auto op = conditional<has_find<C>::value>(first, second);

    return op(container, key);
}

int main()
{
    std::cout << std::boolalpha;

    std::array<int, 3> a = {{ 1, 2, 3 }};
    std::cout << contains(a, 0) << "\n";
    std::cout << contains(a, 1) << "\n\n";

    std::vector<int> v = { 1, 2, 3 };
    std::cout << contains(v, 0) << "\n";
    std::cout << contains(v, 1) << "\n\n";

    std::set<int> s = { 1, 2, 3 };
    std::cout << contains(s, 0) << "\n";
    std::cout << contains(s, 1) << "\n\n";

    std::map<int, int> m = { { 1, 1}, { 2, 2}, { 3, 3} };
    std::cout << contains(m, 0) << "\n";
    std::cout << contains(m, 1) << "\n";
}


texts:
I am preparing for an upcoming exam and have the following practice question..

  Write a method to determine if a word is a palindrome, without using
  the reverse method.

Most of you probably know what a palindrome is, but for those that don't.. a palindrome is a word which reads the same backward or forward.

Anyway, here's my answer to the question. I've written my own reverse method as directed.

How would you refactor this?

def reverse(word_arr)
  reverse = []
  index = word_arr.length
  until index == 0 do
    reverse << word_arr[index - 1]
    index -= 1
  end
  reverse
end

def is_palindrome?(word)
  word_arr = word.downcase.gsub(/ /,'').split('')
  true if word_arr == reverse(word_arr)
end

p is_palindrome?('Anna')
p is_palindrome?('Joe')
p is_palindrome?('Go dog')


texts: Use callback style to start a worker thread and receive result in Qt

texts:
After using JavaScript for a while, I think callbacks are pretty good for asynchronous programming, but I haven't seen anything similar in C++. What I want to achieve is to start a worker thread from a function/lambda, and then use a callback to receive the result, which will be run in the main thread. The callback is required to run in the main thread because Qt GUI code is limited to run there. asyncRun is a convenient function to achieve the above. Let me know what you think.

template <typename AsyncFunc, typename Callback>
void asyncRun(QObject* obj, AsyncFunc asyncFunc, Callback callback) {
    auto asyncFuncWrapper = [=]() {
        auto result = asyncFunc();
        QTimer::singleShot(0, obj, std::bind(callback, result));
    };
    QtConcurrent::run(asyncFuncWrapper);
}

// Convenient function to run the callback in the main thread.
template <typename AsyncFunc, typename Callback>
void asyncRun(AsyncFunc asyncFunc, Callback callback) {
    asyncRun(QCoreApplication::instance(), asyncFunc, callback);
}

// Example usages
asyncRun([]() {
    qDebug() << "thread:" << QThread::currentThreadId();
    QThread::msleep(500);
    return 666;
}, [=](int result) {
    qDebug() << "thread:" << QThread::currentThreadId() << result;
});


texts: Command-line utility to capitalize long words in a file

texts:
I have been developing a capitalizer in Python. This is actually a script that an end user will type at their terminal/command prompt. I have made this script to:

Taking the first argument as a file name and process it.
Don't process words that have 3 or less alphabet.

Here's some code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from os import linesep
from string import punctuation
from sys import argv

script, givenfile = argv

with open(givenfile) as file:
    # List to store the capitalised lines.
    lines = []
    for line in file:
        # Split words by spaces.
        words = line.split()
        for i, word in enumerate(words):
            if len(word.strip(punctuation)) > 3:
                # Capitalise and replace words longer than 3 letters (counts
                # without punctuation).
                if word != word.upper():
                    words[i] = word.capitalize()
        # Join the capitalised words with spaces.
        lines.append(' '.join(words))
    # Join the capitalised lines by the line separator.
    capitalised = linesep.join(lines)

print(capitalised)

A lot more features still have to be added but this script does the stuff it is made for.
What I want (from you):
I want this script to be emerge as a command line utility. So,

How can I make this a better command line utility?
Could I have written in a better way?
Can this script be faster?
Are there any flaws?
Other than GitHub, how can I make it available to the world (so that it is easier to install for end users)? because GitHub is for developers.

Please also post links to make my script and me even more mature.


texts: Using a bool flag to determine whether in root-level or not

texts:
I have several situations in which I need to write a recursive function that does things. I'm asking about one special pattern that I use in recursive methods from time to time.
But first an example, so that you know what I'm talking about.

Example

Assume the following C# code:

class Item
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
}

void Main()
{
    var items = new List<Item>
    {
        new Item{Id = 1, ParentId = 0, Name = "Root"},
        new Item{Id = 2, ParentId = 1, Name = "Sub1"},
        new Item{Id = 3, ParentId = 2, Name = "Sub2"},
        new Item{Id = 4, ParentId = 2, Name = "Sub3"},
        new Item{Id = 5, ParentId = 2, Name = "Sub4"},
        new Item{Id = 6, ParentId = 4, Name = "Sub5"}
    };

    Console.WriteLine(GetPath(items, items[5]));
}

string GetPath(List<Item> list, Item current, bool inRecursion = false)
{
    if (current == null)
    {
        return "";
    }

    var res = GetPath(list, list.FirstOrDefault(m => m.Id == current.ParentId), true) + "/" + current.Name;

    if (!inRecursion)
    {
        res = res.TrimStart('/');
    }

    return res;
}

Explanation

The GetPath method tries to construct a path from one item down to a root item.
It gets a list of all items (list), where each item has an Id, a ParentId and a Name.  As second parameter, it takes an item to start with (current).
When called, it calls itself, but with the parent item as current item.
Finally, when an item has no parent, it returns an empty string. The return values from the recursive calls are then appended to the current item's name.

(It's always a little bit hard to explain recursion, I hope it's understandable...)

So, the code above gives me Root/Sub1/Sub3/Sub5 as result.

Question

As you see, the method has a third parameter (inRecursion), which indicates whether the method is in recursion, or not. I use it, to remove the leading / in the path.

I see myself using a boolean flag like this in recursive methods from time to time, but I wonder if this is the way to go, or if there is a better way to solve the problem of indicating the first call, where the method hasn't called itself. Using a flag like this seems somehow dirty to me.

So, is this considered bad practice, or am I all fine with using a flag like this?


texts:
Here I have a simple algorithm to percent-encode any string.

(Specification from Wikipedia; note that this is not compatible with URLEncoder.encode())

Is this an efficient solution to the problem?

Using a StringBuilder should be efficient, but it doesn't seem great since every character is added to the StringBuilder individually.  Could this have any significant impact?

This method works only for ASCII characters; that is sufficient for my use case.

private static String urlEscape(String toEscape){
    //if null, keep null (no gain or loss of safety)
    if (toEscape==null)
        return null;

    StringBuilder sb=new StringBuilder();
    for (char character: toEscape.toCharArray())//for every character in the string
        switch (character){//if the character needs to be escaped, add its escaped value to the StringBuilder
        case '!': sb.append("%21"); continue;
        case '#': sb.append("%23"); continue;
        case '$': sb.append("%24"); continue;
        case '&': sb.append("%26"); continue;
        case '\'': sb.append("%27"); continue;
        case '(': sb.append("%28"); continue;
        case ')': sb.append("%29"); continue;
        case '*': sb.append("%2A"); continue;
        case '+': sb.append("%2B"); continue;
        case ',': sb.append("%2C"); continue;
        case '/': sb.append("%2F"); continue;
        case ':': sb.append("%3A"); continue;
        case ';': sb.append("%3B"); continue;
        case '=': sb.append("%3D"); continue;
        case '?': sb.append("%3F"); continue;
        case '@': sb.append("%40"); continue;
        case '[': sb.append("%5B"); continue;
        case ']': sb.append("%5D"); continue;
        case ' ': sb.append("%20"); continue;
        case '"': sb.append("%22"); continue;
        case '%': sb.append("%25"); continue;
        case '-': sb.append("%2D"); continue;
        case '.': sb.append("%2E"); continue;
        case '<': sb.append("%3C"); continue;
        case '>': sb.append("%3E"); continue;
        case '\\': sb.append("%5C"); continue;
        case '^': sb.append("%5E"); continue;
        case '_': sb.append("%5F"); continue;
        case '`': sb.append("%60"); continue;
        case '{': sb.append("%7B"); continue;
        case '|': sb.append("%7C"); continue;
        case '}': sb.append("%7D"); continue;
        case '~': sb.append("%7E"); continue;
        default: sb.append(character);//if it does not need to be escaped, add the character itself to the StringBuilder
        }
    return sb.toString();//build the string, and return
}


texts: Function which will fire off a specific template depending on which element is selected

texts:
I have this function which will fire off a specific template depending on which element is selected. However, with the way it is, I'd have to update the JavaScript and the HTML when a new element is added. What I'd like is to have the function scale up to as many HTML elements one would add.

So far I have figured out if I do this:

 function templateLoader(e) {
        var doc = document,
            body = doc.getElementsByTagName('body'),
            event = EventUtility.getEvent(e),
            target = EventUtility.getTarget(event),
            overlay = $('#overlay');

        console.dir(event.currentTarget);

        if (target !== event.currentTarget) {

            switch(target.id){
                case '1':
               $.get('../../../templates/index.html',function(template) {
                 modal.append(Mustache.render($(template).filter('#templateID').html()))
                 modal.listview("refresh");
                 });
                break;

                case '2':
                alert(target.title);
                break;

                case '3':
                alert(target.title);
                break;

                case '4':
                alert(target.title);
                break;

                case '5':
                alert(target.title);
                break;
            }
        }

        EventUtility.stopPropagation(event);

    }

    EventUtility.addHandler(flimFlam, 'click', templateLoader);

});

HTML:

But of course that depends on me going int there and adding newer case conditions when needed. I know I'll have to go into the files anyway when the HTML is added. But I wanted a way to have the JS ready for any amount of cases.

I began with something like this:

 for (var i = 0, l = event.target.length; i < l; i++) {
                console.log(target.id[i]);
            };


texts: Set discounted ticket price, with a floor of 0

texts:
Is there a shorter way to write this?

discounted_price = original_ticket_price - discount_value
if discounted_price < 0:
    discounted_price = 0


texts:
I'm trying to play around with Godot to learn C# and I was trying to creating pure functions to do the velocity, but I found I was repeating myself.

    public override void _PhysicsProcess(float delta)
    {
        base._PhysicsProcess(delta);
        Vector2 moveVelocity = velocity;

        moveVelocity = Run(moveVelocity);
        moveVelocity = Jump(moveVelocity);
        moveVelocity = Dash(moveVelocity);
        moveVelocity = Friction(moveVelocity);
        moveVelocity = Gravity(moveVelocity);

        Animate();

        velocity = MoveAndSlide(moveVelocity, Vector2.Up);

    }

Is there a nicer way of doing the above method so I don't copy moveVelocity over and over but not change velocity or create a new class property?

Something like

velocity = Apply(velocity,
  Run,
  Jump,
  Dash,
  Friction,
  Gravity);


texts: Writing a function to add or modify an existing object inside an array

texts:
I have an array of objects. Each object has two properties, id and quantity.

I wrote a function to add an object to the array. But the function must check if the object already exists within the array. If it does exist the function must increment the quantity property. Otherwise it must add a new object.

Is there an idiomatic way to achieve the same result? I feel that looping over the array to compare the id of the object at index against the id passed as argument is not the right approach.

I am also suspicious of the found = false temporary variable.

Finally, in Ruby we are encouraged to break down long methods into smaller ones. I am aware that JavaScript is not the same, but I feel that this could be further refactored.

addItem = function(id, items) {
  var found, i;
  found = false;
  i = 0;
  while (i < items.length) {
    if (id === items[i].id) {
      items[i].quantity++;
      found = true;
      break;
    }
    i++;
  }
  if (!found) {
    return items.push({
      id: id,
      quantity: 1
    });
  }
};


texts:
I've seen everybody claims the nested ternary to be an evil even when an operation couldn't be written with switch-case; and here's even more, my code could be easily written with switch-case statement.

/// <summary>
/// Control sequence character
/// </summary>
private readonly string CSI = "\u001b";

public string ComposeTermSeqs1(TermActions action)
{
    switch(action) {
        case TermActions.Right:
            return CSI + "[C";
        case TermActions.Up:
            return CSI + "[A";
        case TermActions.Left:
            return CSI + "[D";
        case TermActions.Down:
            return CSI + "[B";
        case TermActions.ForwardWord: //readline lib
            return CSI + "f";
        case TermActions.BackWord: //readline lib
            return CSI + "b";
        case TermActions.BackSearch:
            return "\u0012";
        case TermActions.Interrupt:
            return "\u0003";
        default: //TermActions.SuspendApp:
            return "\u001a";
    }
}

But when I am looking at the ternary version of the function…

public string ComposeTermSeqs2(TermActions action)
{
    return (action == TermActions.Right)      ? CSI + "[C"
        : (action == TermActions.Up)          ? CSI + "[A"
        : (action == TermActions.Left)        ? CSI + "[D"
        : (action == TermActions.Down)        ? CSI + "[B"
        : (action == TermActions.ForwardWord) ? CSI + "f" //readline lib
        : (action == TermActions.BackWord)    ? CSI + "b" //readline lib
        : (action == TermActions.BackSearch)  ? "\u0012"
        : (action == TermActions.Interrupt)   ? "\u0003"
        : "\u001a";
}

I don't know, the switch-case is α) longer β) is harder to maintain because you ought to write every time one case in the «default», and γ) the ternary version is pure, i.e. here's no need to tackle with debugging of this function when something gone wrong, only with the result. You might say that the first version is pure too, but actually someone could easily add a side code to a case.

I am hesitating… Which one should I choose?


texts: Hacker rank - Left rotation - PHP code feedback for Timeout

texts:
Here is the problem description: https://www.hackerrank.com/challenges/ctci-array-left-rotation

  A left rotation operation on an array of size \$n\$ shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array \$[1,2,3,4,5]\$, then the array would become \$[3,4,5,1,2]\$.

  Given an array of \$n\$ integers and a number, \$d\$, perform \$d\$ left rotations on the array. Then print the updated array as a single line of space-separated integers.

My code passes all test cases but is stuck on Hacker rank timeout.  I want to know where is the part that takes too long to execute, in order to optimize my code.

<?php

function rotateOnce($a)
{
    if ($a[0] >= 1 && $a[0] <= 1000000) {
        $left = array_shift($a);
        $a[] = $left;
    }
    return $a;

}

function checkConstrains($d, $n)
{
    if ($d >= 1 && $d <= $n && $n >= 1 && $n <= 10 ^ 5)
        return true;

    return false;
}

// Complete the rotLeft function below.
function rotLeft($a, $d)
{
    global $n;
    if (checkConstrains($d, $n)) {
        for ($i = 0; $i < $d; $i++) {
            $a = rotateOnce($a);
        }
    }
    return $a;

}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$stdin = fopen("php://stdin", "r");

fscanf($stdin, "%[^\n]", $nd_temp);
$nd = explode(' ', $nd_temp);

$n = intval($nd[0]);

$d = intval($nd[1]);

fscanf($stdin, "%[^\n]", $a_temp);

$a = array_map('intval', preg_split('/ /', $a_temp, -1, PREG_SPLIT_NO_EMPTY));

$result = rotLeft($a, $d);

fwrite($fptr, implode(" ", $result) . "\n");

fclose($stdin);
fclose($fptr);


texts: Calling a function within stored procedure to derive a value

texts:
I am trying to write a sql storeprocedure that basically returns a derived value from an outcome of a function call. The  derived field returns the difference in days and if the difference is less than 24 hours then returns hours. It is working as desired but just need to ensure if the approach is right.

Storeprocedure query

SELECT ua.ID AS UserAgreementID
          , A.ID AS AgreementID
          , A.Code
          , A.ComplianceCode
          , A.Name
          , A.Description
          , A.Version
          , ua.UserAgreementStateID
          , uas.Name AS UserAgreementStateName
          , ua.AcceptanceWindowExpiry
          , declaration.GetDifferenceInDaysOrHours(ua.AcceptanceWindowExpiry) AS NoOfDays
          , A.Data
          , pa.ID AS AuthoredByID
          , pa.FirstName + ' ' + pa.LastName AS AuthoredByName
          , A.Authored
          , ia.ID AS IssuedByID
          , ia.FirstName + ' ' + pa.LastName AS IssuedByName
          , A.Issued
        FROM declaration.Agreement AS A
        INNER JOIN declaration.UserAgreement AS ua
            ON A.ID = ua.AgreementID
        INNER JOIN declaration.UserAgreementState AS uas
            ON ua.UserAgreementStateID = uas.ID
        LEFT JOIN common.Person AS pa
            ON A.AuthoredBy = pa.ID
        LEFT JOIN common.Person AS ia
            ON A.IssuedBy = ia.ID
        WHERE ua.UserID = 607
        AND uas.Code IN ('ISS', 'DEF') -- Issued, Deferred
        AND A.Draft = CONVERT(BIT, 0) -- Not a draft.
        AND A.Deleted = CONVERT(BIT, 0) -- Not deleted.
        AND ISNULL(A.Issued, '9999-12-31') <= GETUTCDATE() -- Issued date less than equal to today's date (Issued date).
        AND ISNULL(A.Expires, '9999-12-31') > GETUTCDATE()

I am not sure if writing a function and calling it within the storeprocedure has any implications and is the right way to do it. The results that I am getting are correct though. Could somebody throw some light.

CREATE FUNCTION declaration.GetDifferenceInDaysOrHours(@AcceptanceWindowExpiry datetime)
RETURNS int
AS

BEGIN
    DECLARE @timeDifferenceInDays INT;
    DECLARE @timeDifferenceInHours INT;
    DECLARE @timeDifference INT;

    SELECT @timeDifferenceInDays = DATEDIFF(d,  GETUTCDATE(), @AcceptanceWindowExpiry)
    IF @timeDifferenceInDays > 1
      BEGIN
            SELECT @timeDifference = @timeDifferenceInDays
       END
    ELSE
     BEGIN
        SELECT @timeDifferenceInHours = DATEDIFF(HOUR,  GETUTCDATE(),  @AcceptanceWindowExpiry)
          IF @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24
             BEGIN
                SELECT @timeDifference = @timeDifferenceInHours
             END
          ELSE
            BEGIN
                SELECT @timeDifference = -1
          END
        END
        RETURN @timeDifference;
    END;


texts:
I just started learning Java, and wrote up a linked list. I'm coming from just having learned Haskell, so I've been out of the mindset of stateful computations for awhile.

I'd like to know how it could be improved in any way. Please be critical. Mainly though, I'd like suggestions on readability, and safe practices.

It's very simple right now, only allowing additions at the end and deletions; but I figured it would be sufficient for a review.

class Node<T> {
    T cargo;
    Node<T> tail;

    public Node(T nCargo) {
        cargo = nCargo;
        tail = null;
    }

    public Node<T> getNext() {
        return tail;
    }

    public T getCargo() {
        return cargo;
    }

    public boolean isLast() {
        return tail == null;
    }

    public Node<T> getLast() {
        Node<T> curNode = this;
        while (!curNode.isLast()) {
            curNode = curNode.getNext();
        }
        return curNode;
    }

    public void add(T nCargo) {
        tail = new Node<T>(nCargo);
    }

    public boolean canLink() {
        return this.getNext().getNext() != null;
    }

    public void deleteNext() {
        if (this.canLink()) { tail = tail.getNext();
            } else { tail = null; }
    }

}

public class Vect<T> {
    Node<T> head;
    int vSize;

    public Vect() {
        head = null;
        vSize = 0;
    }
    public Vect(T cargo) {
        head = new Node<T>(cargo);
        vSize = 1;
    }

    public void pushBack(T cargo) {
        Node<T> last = head.getLast();
        vSize += 1;
        last.add(cargo);
    }

    private Node<T> getNodeAt(int i) {
        Node<T> curNode = head;
        for (int cI = 0; i > cI; cI++) {
            curNode = curNode.getNext();
        }
        return curNode;
    }

    public T getAt(int i) {
        return getNodeAt(i).getCargo();
    }

    public int length() {
        return vSize;
    }

    public void deleteHead() {
        if (head.getNext() != null) { head = head.getNext();
            } else { head = null; }
        vSize -= 1;
    }

    public void deleteAt(int i) {
        if (i == 0) {
            deleteHead();
        } else {
            Node<T> curNode = this.getNodeAt(i - 1);
            curNode.deleteNext();
            vSize -= 1;
        }
    }
}

and its use:

public class Main {

    public static void main(String[] args) {
        Vect <Integer> v = new Vect<Integer>(2);
        v.pushBack(3);
        v.pushBack(4);
        v.pushBack(5);
        v.pushBack(6);

        for (int i = 0; i < v.length(); ++i) {
            System.out.println(v.getAt(i));
        }

        v.deleteAt(2);

        for(int i = 0; i < v.length(); ++i) {
            System.out.println(v.getAt(i));
        }

    }
}


texts:
Based off the coding puzzle: Who is this chatbot?

The code's purpose is to create an AI that the user can communicate with. Due to there being no hard-coded strings, the AI learns from what the user has said.

In my version of this AI, all messages said by the user are stored in an array and when it comes time for the computer to speak, a random message from the array is written to standard output.

The code

Main.java

public class Main {
    public static void main(String[] args) {
        String name;
        if(args.length >= 1) {
            name = args[0];
        } else {
            name = "You";
        }
        Conversation c = new Conversation(new AI(), new User(name));
        while(true) {
            String input = c.getUser();
            if(input.equals(":exit")) {
                System.exit(0);
            }
            c.getAI();
        }
    }
}

Converstaion.java

public class Conversation {
    private AI ai;
    private User user;

    private DynamicArray saidStrings = new DynamicArray(1);
    private int saidCount = 0;

    public Conversation(AI a, User u) {
        ai = a;
        user = u;
    }

    public String getUser() {
        String input = user.getInput();
        saidStrings.push(input);
        saidCount++;
        return input;
    }
    public void getAI() {
        ai.saySomething(saidStrings, saidCount);
    }
}

AI.java

import java.util.Random;

public class AI {
    private Random rand = new Random();

    public void saySomething(DynamicArray saidStrings, int saidCount) {
        System.out.printf("Bot: %s\n", saidStrings.get(getRandom(saidCount)));
    }
    public int getRandom(int max) {
        return rand.nextInt(max);
    }
}

User.java

import java.util.Scanner;

public class User {
    private Scanner input = new Scanner(System.in);

    private String name;

    public User(String n) {
        name = n;
    }

    public String getInput() {
        System.out.printf("%s: ", name);
        return input.nextLine();
    }
}

DynamicArray.java

/*

Strongly based off of: http://stackoverflow.com/questions/3536153/c-dynamically-growing-array

*/

public class DynamicArray {
    private String[] array;
    private int used;
    private int size;

    public DynamicArray(int initialSize) {
        array = new String[initialSize];
        used = 0;
        size = initialSize;
    }

    public void push(String e) {
        if(used == size) { // if the limit has been reached
            size *= 2;

            String[] temp = array; //  a median for the trade
            array = new String[size];
            copy(temp, array);
        }
        array[used++] = e; // append the provided element
    }

    public String get(int i) {
        return array[i];
    }

    private void copy(String[] src, String[] dest) {
        System.arraycopy(src, 0, dest, 0, src.length);
    }
}

Concerns:

Am I following common OOP practices?
Am I following common Java practices
Do I have too many classes?
Do I have too few classes?
Am I handling input and output in the correct places?
Do I have too few/many comments?

Any other recommendations for improvement are welcome.


texts:
This is a continuation of my LINQ stories from Pangrams-Hackerrank. Similarly, this challenge has been asked before in python Pangrams python Implementation but I have tried to accomplish this challenge using LINQ.

Here is a summary of the question

  Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)

  After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.

  Given a sentence , tell Roy if it is a pangram or not.

  Input Format

  Input consists of a string .

  Constraints

  Length of  can be at most 103(1≤|s|≤103) and it may contain spaces, lower case and upper case letters. Lower-case and upper-case instances of a letter are considered the same.

  Output Format

  Output a line containing pangram if  is a pangram, otherwise output not pangram.

Sample Input

Input #1

We promptly judged antique ivory buckles for the next prize

Input #2

We promptly judged antique ivory buckles for the prize

Sample Output

Output #1

pangram

Output #2

not pangram

Explanation

In the first test case, the answer is pangram because the sentence contains all the letters of the English alphabet.

Here is my implementation

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */

            string pangramInput = Console.ReadLine();
            var alphabet = Enumerable.Range(97, 26).Select((x) => (char)x);
            var pangramCheck = pangramInput.Replace(" ", "").ToLower().OrderBy((letter) => letter).Distinct().SequenceEqual(alphabet);
            string answer = pangramCheck ? "pangram" : "not pangram";
            Console.WriteLine(answer);
    }
}

Thoughts

I know this is a simple exercise and can be achieved without LINQ but the main idea is to know how to use LINQ functions.

Is the use of LINQ right? are there other simpler alternatives?


texts: Asynchronously receiving data from a connected socket

texts:
Can anyone tell me if this is the right way to call BeginReceive asynchronously? The code works fine but I want to make sure.

private static void message_listener(Socket sock)
        {
            byte[] m_buffer = new byte[5000];
            sock.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.None, ar => { int dat=sock.EndReceive(ar); processdata(m_buffer, dat); }, null);
         }

        private static void processdata(byte[] r_buffer,int dat)
        {
            Console.Write("Data Received: " + dat);
        }


texts:
Looking for general feedback on this module.  remember is property that a user sets via clicking "remember me" when logging in.

A token identifies the user - h_token.  If localStorage.h_token is set, it is assumed the user has clicked remember me, this is checked at load time.

When the remember state is changed manually by the user setRemember() is called.

Not looking for advice on any security issues or naming conventions at the moment it is not a concern.

Just general things.

/*SClientStorage
**
**
**
*/
SStorage = NS.support({
    Name: 'Storage',
    hold: {},
    clientStorage: localStorage.h_token ? localStorage : sessionStorage,
    setRemember: function (remember) {
        this.clientStorage = remember ? localStorage : sessionStorage
    },
    clear: function () {
        this.clientStorage.clear();
    },
    setAll: function (o) {
        var key;
        for (key in o) {
            if (o.hasOwnProperty(key)) {
                this.clientStorage[key] = o[key];
            }
        }
    },
    getAll: function () {
        var o = {},
            key;
        for (key in this.clientStorage) {
            if (this.clientStorage.hasOwnProperty(key)) {
                o[key] = this.clientStorage[key];
            }
        }
        return o;
    },
    set: function (key, value) {
        this.clientStorage[key] = value;
    },
    get: function (key) {
        return this.clientStorage[key];
    }
});


texts: Calculating the amount of cubes needed to form a sum

texts:
Since I've never done any performance programming (Aside from the better choices such as array vs list etc. The real basics.), I should probably read up on it. But I had to start somewhere, so, someone I know - which is a much better programmer than I am - tasked me with making this "assignment":

  You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?

  The parameter of the function findNb (find_nb, find-nb) will be an integer m and you have to return the integer n such as \$n^3 + (n-1)^3 + \dots + 1^3 = m\$ if such a n exists or -1 if there is no such n.

He gave me this template with it:

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(findNb(4183059834009));
        Console.WriteLine(findNb(24723578342962));
        Console.WriteLine(findNb(135440716410000));
        Console.WriteLine(findNb(40539911473216));
    }

    public static long findNb(long m)
    {

    }
}

In which I inserted:

for(long n = 1; n < (m / 3); n++)
{
    double vol = 0;
    for(long i = 0; i < n; i++)
        vol += Math.Pow((n - i), 3);

    if(vol > m)
        return -1;

    if(vol == m)
        return n;
}
return -1;

This code works, but it takes incredibly long for the larger numbers, as is my main problem.

What can I do to shorten the time it takes for this code takes to complete?


texts:
I would like to make a portable thread pool using boost::thread. Some one could tell me to look at boost::thread_group and boost::asio. I know, but I am not really familiar with these things so I don't know if they are suitable for my purpose.

Please give me comments on what I supposed to do here.

JobItem and JobQueue:

class JobItem
{
private:
    uint32_t        job_type_;      //!< Job type
    char*           job_ptr_;       //!< Pointer to job content
// ...
};

class JobQueue
{
private:
    queue<JobItem*>                 job_queue_;
public:
    // Definitely I need to use mutex and condition variable here
    JobItem* pick();
    void push(JobItem* job_item);
};

JobWorker (worker thread):

class JobWorker
{
private:
    JobQueue* shared_job_queue_;
    boost::thread the_thread_;

public:
    JobWorker(JobQueue* shared_queue) : shared_job_queue_(shared_queue);

    // exec_job will be overridden by concrete subclasses
    virtual void exec_job(JobItem* job_item) = 0;
    void run()
    {
        while(true)
        {
            JobItem* job = shared_job_queue_->pick();
            exec_job(job);
            delete job;
        }
    }
    void start()
    {
        the_thread_ = boost::thread(boost::bind(&JobWorker::run, this));
    }
    void stop()
    {
        the_thread_.join();
    }
};

Concrete JobWorker subclasses:

class Task_1_Worker : public JobWorker
{
    // override exec_job
    void exec_job(JobItem* job)
    {
        // Process job item here
    }
}

class Task_2_Worker : public JobWorker
{
    // override exec_job
    void exec_job(JobItem* job)
    {
        // Process job item here
    }
}

Now, WorkerPool with template:

template <class JobWorkerT>
class WorkerPool
{
private:
    JobQueue shared_job_queue_;
    list<JobWorkerT> job_workers_;

public:
    WorkerPool(const int num_threads);
    ~WorkerPool(void) {};

    void push(JobItem* job)
    {
        shared_job_queue_.push(job);
    }
    void start();
    void stop();
};

template <class JobWorkerT>
WorkerPool<JobWorkerT>::WorkerPool(const int num_threads)
{
    for(int i=0; i<num_threads; i++)
    {
        JobWorkerT job_worker(&shared_job_queue_);
        job_workers_.push_back(job_worker);
    }
}

template <class JobWorkerT>
void WorkerPool<JobWorkerT>::start()
{
    for(std::list<JobWorkerT>::iterator iter = job_workers_.begin(); iter != job_workers_.end(); iter++)
    {
        ((JobWorkerT)(*iter)).start();
    }
}

template <class JobWorkerT>
void WorkerPool<JobWorkerT>::stop()
{
    for(std::list<JobWorkerT>::iterator iter = job_workers_.begin(); iter != job_workers_.end(); iter++)
    {
        ((JobWorkerT)(*iter)).stop();
    }
}

main()

int main()
{
    WorkerPool<Task_1_Worker>* task1_grp = new WorkerPool<Task_1_Worker>();
    WorkerPool<Task_2_Worker>* task2_grp = new WorkerPool<Task_2_Worker>();

    task1_grp->start();
    task2_grp->start();

    // Producers should call task1_grp.push(JobItem*) or task2_grp.push(JobItem*) to dispatch new jobs to thread pools
}


texts: Build a local cache of all streams from Twitch.TV API

texts:
I am trying to cache the entirety of streams from Twitch.TV public API with the following code. It is successful but takes almost a full minute to execute so I am wondering if it's my code or just the speed of the API delivery. In any case, because it is my first PHP script (and really, I'm new in general), I am certain there are logical missteps and performance crushing flows and I would appreciate some review!

The function buildPages() is mainly what is in question for this post.

The data is always returned as json and I dump it all to disk for local testing. Suggestions on how to implement an accelerator for this collection are welcomed since I've never played with one before. APC or Memcache(d)? I have a lot of reading to do..

Also, I am not certain why the lines

$length = count($page->streams);
$length = count($page['streams']);

had to be written as such. stdClass Object versus ArrayAccess? I don't really understand why I would get errors when trying to use the same accessor in the case of my code. Is $page not always an associative array created from the JSON data?

<?php

$base = 'https://api.twitch.tv/kraken/';

$thatlist = array(
    'games'=> array(
        'url'=>'games/top',
        'params'=> array(
            'limit'=>100,
            'offset'=>0
        )
    ),
    'featured'=>array(
        'url'=>'streams/featured',
        'params'=>array(
            'limit'=>100,
            'offset'=>0
        )
    ),
    'summary'=>array(
        'url'=>'streams/summary',
        'params'=>array(
            'limit'=>100,
            'offset'=>0
        )
    ),
    'teams'=>array(
        'url'=>'teams',
        'params'=>array(
            'limit'=>100,
            'offset'=>0
        )
    )
);

foreach($thatlist as $key => $val) {

    $fullurl = $base . $val['url'];

    foreach($val['params'] as $foo => $bar){

        $fullurl .= '?' . $foo . '=' . $bar;

    }

    $quicklist[$key] = json_decode(file_get_contents($fullurl), true);

}

function buildPages() {

    $streams = array();
    $offset = 0;

    $page = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?offset=".$offset."&limit=100", true));

    $length = count($page->streams);

    array_push($streams, $page);

    // request always returns 100 items unless at the end of live data
    while($length = 100) {

        $index = count($streams);
        $offset = $index * 100;

        $page = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?offset=".$offset.'&limit=100'), true);

        $length = count($page['streams']);

        echo "Index: ".$index."
";
        echo "Length: ".$length."
";

        array_push($streams, $page);

    }

    var_dump($streams);
    $sd = fopen('streams-dump.json', 'w');
    fwrite($sd, json_encode($streams));
    fclose($sd);

}

$qld= fopen('quicklist-dump.json', 'w');
fwrite($qld, json_encode($quicklist));
fclose($qld);

buildPages();

?>


texts: Buy and Sell a Stock for maximum profit (given a day and a price)

texts:
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example one:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.

Example two:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

My solution:

walked the array grabbing the initial price and continued to swap it with the smallest value. Between the current smallest value < and only the proceeding larger peaks. With the solution being the largest chasms (difference) between the lowest peak and highest summit in value within an interval.  TimeComplexity is O(n) space complexity is O(1) only using one object.

const perfectPrice = (prices, peak = {
  buy: null,
  buy_day: null,
  sell_day: null,
  sell: null,
  profit: 0,
  profitable: {}
}) => {
  const week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  prices.forEach((price, day, all) => {
    if (peak['buy'] === null) {
      peak['buy_day'] = day
      peak['buy'] = price

    } else if (price < peak['buy']) {
      peak['buy'] = price
      peak['buy_day'] = day
    }
    if (peak['profit'] < (price - peak['buy'])) {
      peak.profitable = {
        buy: week[peak.buy_day],
        buy_at: peak['buy'],
        sell: week[day],
        sell_at: price,
        profit: price - peak['buy']
      }
      peak['profit'] = price - peak['buy']
    }
  });
  return ((peak || {}).profitable || {}).profit ? peak.profitable : 'not profitable to sell';
}

console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}


texts:
I tried a binary solution to 3Sum problem in LeetCode:

  Given an array nums of \$n\$ integers, are there elements \$a\$, \$b\$, \$c\$ in nums such that \$a + b + c = 0\$? Find all unique triplets in the array which gives the sum of zero.

  Note:

  The solution set must not contain duplicate triplets.

  Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Ｍy plan: divide and conquer threeSum to

an iteration
and a two_Sum problem.
break two_Sum problem to

a loop
binary search

The complexity is: \$O(n^2\log{n})\$.

 class Solution:
    """
    Solve the problem by three module funtion
    threeSum
    two_sum
    bi_search
    """
    def __init__(self):
        self.triplets: List[List[int]] = []

    def threeSum(self, nums, target=0) -> List[List[int]]:
        """
        :type nums: List[int]
        :type target: int
        """
        nums.sort() #sort for skip duplicate and binary search

        if len(nums) < 3:
            return []

        i = 0
        while i < len(nums) - 2:
            complement = target - nums[i]

            self.two_sum(nums[i+1:], complement)
            i += 1 #increment the index
            while i < len(nums) -2 and nums[i] == nums[i-1]: #skip the duplicates, pass unique complement to next level.
                i += 1

        return self.triplets

    def two_sum(self, nums, target):
        """
        :type nums: List[int]
        :tppe target: int
        :rtype: List[List[int]]
        """
        # nums = sorted(nums) #temporarily for testing.
        if len(nums) < 2:
            return []

        i = 0
        while i < len(nums) -1:
            complement = target - nums[i]

            if self.bi_search(nums[i+1:], complement) != None:

                # 0 - target = threeSum's fixer
                self.triplets.append([0-target, nums[i], complement])
            i += 1

            while i < len(nums) and nums[i] == nums[i-1]:
                i += 1

    def bi_search(self, L, find) -> int:
        """
        :type L: List[int]
        :type find: int
        """
        if len(L) < 1: #terninating case
            return None
        else:
            mid = len(L) // 2
            if find == L[mid]:
                return find

            if find > L[mid]:
                upper_half = L[mid+1:]
                return self.bi_search(upper_half, find)
            if find < L[mid]:
                lower_half = L[:mid] #mid not mid-1
                return self.bi_search(lower_half, find)

I ran it but get the report

  Status: Time Limit Exceeded

Could you please give any hints to refactor?

Is binary search is an appropriate strategy?


texts: Collecting Parameter vs overloading addition

texts:
I'm reading TDD By Example by Kent Beck (which I highly recommend, if you haven't read it!) In The xUnit Example, he discusses how to collect the results of multiple tests in a single TestResult. His code looks like this:

# in TestCase
def run(self, result):
    result.testStarted()
    self.setUp()
    try:
        method = getattr(self, self.name)
        method()
    except:
        result.testFailed()

# in TestSuite
def run(self, result):
    for test in self.tests:
        test.run(result)

In short, Beck passes in the currently running TestResult and asks the tests to add their results to it; the TestSuite acts in much the same way. (Beck says the TestSuite is a Composite, and the pattern of passing in the TestResult is called Collecting Parameter.) In other words, somewhere at the top of the call stack, something is creating a single TestResult which gets passed all the way down to the TestCase.

I find the single TestResult object aesthetically distasteful - I generally don't like sharing state between different components. It smacks of C#'s out keyword (which is not a compliment).

My approach would be to return a TestResult from every TestCase, and allow TestResults to be added to one another:

# in TestResult
def __init__(self, runCount=0, errorCount=0):
    self.runCount = runCount
    self.errorCount = errorCount
def __add__(self, other):
    runCount = self.runCount + other.runCount
    errorCount = self.errorCount + other.errorCount
    return TestResult(runCount, errorCount)

# in TestCase
def run(self):
    result = TestResult()
    result.testStarted()
    self.setUp()
    try:
        method = getattr(self, self.name)
        method()
    except:
        result.testFailed()
    return result

# in TestSuite
def run(self):
    result = TestResult()
    for test in self.tests:
        result += test.run()
    return result

How would you weigh up these two approaches? The state of any given instance of TestResult is now local to the methods. On the other hand, there's more duplication in mine - every method now creates and returns a new TestResult, which might make writing a new implementation of run harder work.


texts: Python program for converting scientific notation to fixed point

texts:
I had to replace all instances of scientific notation with fixed point, and wrote a Python script to help out.  Here it is:

#!/usr/bin/python2

# Originally written by Anton Golov on 29 Jan 2012.
# Feedback can be sent to <email> .

"""Provide functions for converting scientific notation to fixed point.

When imported, reads lines from stdin and prints them back to stdout with
scientific notation removed.

WARNING:  The resulting fixed point values may be of a different precision
than the original values.  This will usually be higher, but may be lower for
large numbers.  Please don't rely on the precision of the values generated by
this script for error analysis.

"""

from re import compile

exp_regex = compile(r"(\d+(\.\d+)?)[Ee](\+|-)(\d+)")

def to_fixed_point(match):
    """Return the fixed point form of the matched number.

    Parameters:
        match is a MatchObject that matches exp_regex or similar.

    If you wish to make match using your own regex, keep the following in mind:
        group 1 should be the coefficient
        group 3 should be the sign
        group 4 should be the exponent

    """
    sign = -1 if match.group(3) == "-" else 1
    coefficient = float(match.group(1))
    exponent = sign * float(match.group(4))
    return "%.16f" % (coefficient * 10**exponent)

def main():
    """Read lines from stdin and print them with scientific notation removed.

    """
    try:
        while True:
            line = raw_input('')
            print exp_regex.sub(to_fixed_point, line)
    except EOFError:
        pass

if __name__ == "__main__":
    main()

I am primarily interested about the way the regex is used (can it match something it can't replace?), but comments on code clarity and features that may be simple to add are also welcome, as well as any further nitpicking .


texts:
I was in need of a method to dynamically generate a week range, so that the view reads something like "Week of May 16 - 22" and updates automatically. Here's the helper method I came up with, but I'm wondering if there's a more efficient way to have gone about this.

Dashboards Helper:

def week_range
  today = DateTime.now
  week_start = today.beginning_of_week(:monday).strftime("%B %d")
  week_end = today.end_of_week(:monday).strftime("%d")
  "#{week_start} - #{week_end}"
end

Dashboards View:

Week of <%= week_range %>

Output:

Week of May 16 - 22


texts:
Email<input type="text" id="email" /><br />
Re-enter Email<input type="text" id="confirm-email" />

I'm thinking that I want a model so that I can have this partial page strongly typed.  But what a lame model....

It would look like this, and if this is a good Idea, what should I name this model?

public class ConfirmEmailModel?????
{
    [Required]
    [Display(Name = "Email",ResourceType=typeof(mvc3test.Resources.Common))]
    public string Email{ get; set; }

    [Display(Name = "Confirm Email")]
    [Compare("Email", ErrorMessage = "no match.")]
    public string ConfirmEmail{ get; set; }
}


texts:
As you review this, please keep in mind I'm using Jython 2.1 as shipped with IBM's WebSphere 7.0 (their latest-and-greatest).  I don't have decorators, properties, new style objects, or any other Python feature invented in the last decade.

Problem:

Using WebSphere's Jython interface to determine app server configuration information is not exactly fast. I had already begun work on a simple Jython module to encapsulate the convoluted WebSphere Jython API when I decided to try and cache the results of each method invocation.  WebSphere configuration details tend not to change very often.

Inspired by Python 3.2's @functools.lru_cache and Python 2.2's properties I came up with:

from org.python.core import PyString, PyTuple

class Getter:

    def getter(self,attr,valid_attrs):

        if attr == 'valid_attrs': return valid_attrs
        if attr not in valid_attrs.keys(): raise AttributeError

        attr_value = None
        if type(valid_attrs[attr]) == PyString:
            function = getattr(self,valid_attrs[attr])
            attr_value = function()

        elif type(valid_attrs[attr]) == PyTuple:
            function = getattr(self,valid_attrs[attr][0])
            args = []
            kwargs = {}
            for arg in valid_attrs[attr][1:]:
                if type(arg) == PyTuple:
                    if len(arg) > 2:
                        err = ('Named argument tuple %s in %s length > 2.'
                            % (arg, self.__class__.__name__ ))
                        raise NameError(err)

                    kwargs[arg[0]] = arg[1]

                elif type(arg) == PyString:
                    args.append(arg)

                else:
                    err = ('Unknown argument in %s __getattr__ dispatch list'
                            % self.__class__.__name__ )
                    raise NameError(err)

            attr_value = function(*args,**kwargs)

        else:
            raise AttributeError

        return attr_value

class App(Getter):

    def __init__(self, name=None):

        if name:
            self.app_name = name
        else:
            print 'App instance requires name.'
            raise NameError

    def __getattr__(self,attr):

        valid_attrs = { 'app_id': ('get_app_id'),
                        'deployed_nodes': ('get_deployed_nodes'),
                        'deployed_servers': ('get_deployed_servers'),
                        }

        attr_value = Getter.getter(self,attr,valid_attrs)
        setattr(self,attr,attr_value)
        return attr_value

    def get_app_id(self):
        return AdminConfig.getid('/Deployment: %s/' % self.app_name)

    def get_deployed_node(self):
        ### ...

    def get_deployed_servers(self):
        ### ...

As I use this in other classes I change the function dispatch dict (valid_attrs) as needed.

Is this an evil abuse of __getattr__?  Next to code execution speed, I'm most worried about maintainability.  Does this trigger a "WTF?" Or, does it make sense when viewed against the limitations of Jython 2.1 and features, such as @property, found in newer versions?


texts: Getting multiple keys' values from nested object in JSON (w/out jQuery)

texts:
I'd like to ask if either my JSON data is ill-conceived and whether how I solved it is particularly inefficient/plain stupid/typical.

Given the following JSON data:

{
    "User01": {
        "dates & times": {
            "date 01": "150",
            "date 02": "165",
            "date 03": "180"
        }
    },

    "User02": {
        "dates & times": {
            "date 01": "150",
            "date 02": "165",
            "date 03": "180"
        }
    },

    "User03": {
        "dates & times": {
            "date 01": "150",
            "date 02": "165",
            "date 03": "180"
        }
    }
}

... and wanting to retrieve the dates & times data so it can be rendered, e.g.:

Date 01: Time 01
Date 02: Time 02
Date 03: Time 03

... and which I've achieved thusly:

for (var key in myObj){
    if (key == selUser){
        for (var date in myObj[key]["dates & times"]){
            console.log("Date: " + date + "; " + "weight: " + myObj[key]["dates & times"][date]);
            var dtTag = "
Date: " + date + "
";
            var ddTag = "
Time: " + myObj[key]["dates & times"][date] + "
";
            output.innerHTML += dtTag;
            output.innerHTML += ddTag;
        }
    } // if
} // loop

So, as to the json data: assuming that there could be hundreds of date & time entries, is this even a legit usage of json or should this kind of data be better formatted using arrays, e.g.:

{ "dates & times":
    {
        "dates": [ "date01", "date02", "date03" ],
        "times": [ "150", "165", "180" ]
    }
}

And in such a case where I had no control of the JSON data, how could I improve on my solution to iterate for selected user and iterate again through nested object's data?

By the way, this is in context of studying JavaScript, not jQuery or any other library/framework.


texts:
For practice, I wrote some NASM code that prints out the hailstone sequence of a (unfortunately, hardcoded) number.
This is by far the most complex code I've ever written in NASM. I'd like advice on anything, but specifically:

I'm trying to abide by CDECL. Am I doing anything off?
The multiplication part seems overly complicated. The problem is, mul doesn't take an immediate, and the register that I want to multiply is ebx, not eax, so I need to do a couple movs before I can multiply.
Anything else that's worth mentioning.

hail.asm:
global _start

section .data
    newline: db `\n`
    end_str: db `1\n`

section .text
    print_string:  ; (char* string, int length)
        push ebp
        mov ebp, esp

        push ebx

        mov eax, 4
        mov ebx, 1
        mov ecx, [ebp + 8]
        mov edx, [ebp + 12]
        int 0x80

        pop ebx

        mov esp, ebp
        pop ebp

        ret

    print_int:  ; (int n_to_print)
        push ebp
        mov ebp, esp

        push ebx
        push esi

        mov esi, esp  ; So we can calculate how many were pushed easily

        mov ecx, [ebp + 8]

        .loop:
            mov edx, 0  ; Zeroing out edx for div
            mov eax, ecx  ; Num to be divided
            mov ebx, 10  ; Divide by 10
            div ebx
            mov ecx, eax  ; Quotient

            add edx, '0'
            push edx  ; Remainder

            cmp ecx, 0
            jne .loop

        mov eax, 4  ; Write
        mov ebx, 1  ; STDOUT
        mov ecx, esp  ; The string on the stack
        mov edx, esi
        sub edx, esp  ; Calculate how many bytes were pushed
        int 0x80

        add esp, edx

        pop esi
        pop ebx

        mov esp, ebp
        pop ebp

        ret

    main_loop:  ; (int starting_n)
        push ebp
        mov ebp, esp

        push ebx

        mov ebx, [ebp + 8]  ; ebx is the accumulator
        .loop:
            push ebx
            call print_int
            add esp, 4

            push 1
            push newline
            call print_string
            add esp, 8

            test ebx, 1
            jz .even
            .odd:
                mov eax, ebx
                mov ecx, 3  ; Because multiply needs a memory location
                mul ecx
                inc eax
                mov ebx, eax
                jmp .end

            .even:
                shr ebx, 1

            .end:
                cmp ebx, 1
                jnz .loop

        push 2
        push end_str
        call print_string
        add esp, 8

        pop ebx

        mov esp, ebp
        pop ebp

        ret

    _start:
        push 1000  ; The starting number
        call main_loop
        add esp, 4

        mov eax, 1
        mov ebx, 0
        int 0x80

Makefile:
nasm hail.asm -g -f elf32 -Wall -o hail.o
ld hail.o -m elf_i386 -o hail


texts:
For practice purposes I implemented a function that checks for palindromes:
def palindrom(name):
    name_reversed = ""

    for buchstabe in name[::-1]:
        name_reversed += buchstabe

    return name.lower() == name_reversed.lower()

print(palindrom("Tom"))
print(palindrom("Bob"))

How may I improve this code, especially the for-loop?


texts:
I need to create a sparse Markov chain. It is supposed to receive text, so the number of rows or columns can easily go up to 20000. Besides, if I want to consider higher orders of the Markov chain (creating pairs of consecutive words) the dimension can become much bigger. Hence the need to have something sparse.

I added the constraint to have a "uniform prior" on the transitions (so as to avoid having infinite log likelihood).

I am not sure this is the cleanest way to proceed.

using System.Collections.Generic;
using System;

namespace rossum.Machine.Learning.Markov
{
    public class SparseMarkovChain<T>
    {
        private Dictionary<T, Dictionary<T, int>> _sparseMC = new Dictionary<T, Dictionary<T, int>>();
        private Dictionary<T, int> _countEltLeaving = new Dictionary<T, int>();
        private int _size = 0;

        public double GetTransition(T p1, T p2)
        {
            if (_sparseMC.ContainsKey(p1))
            {
                if (_sparseMC[p1].ContainsKey(p2))
                    return (1f + _sparseMC[p1][p2]) / (_countEltLeaving[p1] + _size);
                else
                    return 1f / (_countEltLeaving[p1] + _size);
            }
            else
                return 1f / _size;
        }

        public void AddTransition(T p1, T p2)
        {
            if (_sparseMC.ContainsKey(p1))
            {
                _countEltLeaving[p1]++;
                if (_sparseMC[p1].ContainsKey(p2))
                    _sparseMC[p1][p2] += 1;
                else
                    _sparseMC[p1].Add(p2, 1);
            }
            else
            {
                _size++;
                if (!_sparseMC.ContainsKey(p2))
                    _size++;
                Dictionary<T, int> nd = new Dictionary<T, int>();
                nd.Add(p2, 1);
                _sparseMC.Add(p1, nd);
                _countEltLeaving.Add(p1, 1);
            }
        }

        public double LogLikelihood(T[] path)
        {
            double res = 0;
            for (int i = 1; i < path.Length; i++)
                res += Math.Log(GetTransition(path[i - 1], path[i]));
            return res;
        }
    }
}