TreeMap implementation I've just tried to do some code for TreeMap. The TreeMap concept can be found here. As an exercise I've tried to find the solution without reading the article.

Then, I came across this code. The main problem is that I missed the algorithm, my code is not so simple, elegant, short and clean. And I used OOP because I didn't know how to do without it (at university I learned no C, no functional programming, only OOP).

Another issue is that I wanted to make a list of rectangles with no dependencies from the render engine (no matplotlib, maybe I'm writing something for openGL and pyqt), so I need some Rectangle with coordinates normalized between 0 and 1.

This is my code, which I'm no proud of: it is too verbose, redundant and not KISS, and maybe it could also be a bit more readable:

class Rectangle(object):

    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height

    def __repr__(self):
        return "Rect - x:{0}, y:{1}, width:{2}, height:{3}".format(self.x, self.y, self.width, self.height)

class Node(object):
    iter_method = iter
    size_method = int

    def __init__(self, content, depth=0):
        self.depth = depth
        self.childs = []
        try:
            self.value = Node.size_method(content)
        except TypeError:
            self.childs = [Node(x, depth+1) for x in Node.iter_method(content)]
            self.value = sum(child.value for child in self.childs)

    @property
    def leaf(self):
        return len(self.childs)>0

    def __repr__(self):
        s = "{0}Node:{1}".format('\t'*self.depth, self.value)
        if self.leaf:
            s += '\n'+'\n'.join(str(child) for child in self.childs)
        return s

class TreeMap(object):

    def __init__(self, root):
        self.root = root

        self.rects = []
        self.build(self.root, Rectangle(0,0,1,1))

    def build(self, node, rect, horizzontal=True):
        node.rect = rect
        self.rects.append( rect )

        sizes = [child.value for child in node.childs]
        total_size = node.value

        if horizzontal:
            x = 0.0
            for child in node.childs:
                y = rect.y
                w = (child.value*rect.width) / float(total_size)
                h = rect.height
                self.build(child, Rectangle(x,y,w,h), not horizzontal)
                x += w
        else:
            y = 0.0
            for child in node.childs:
                x = rect.x
                h = (child.value*rect.height) / float(total_size)
                w = rect.width
                self.build(child, Rectangle(x,y,w,h), not horizzontal)
                x += w

import unittest

class Test_TreeMap(unittest.TestCase):

    def test_build_depth0(self):
        nodes = (2,1,(2,2))

        known = (1,     1), (2.0/7, 1), (1.0/7, 1), (4.0/7, 1), (4.0/7, 0.5), (4.0/7, 0.5)

        Node.iter_method = iter
        Node.size_method = int
        root = Node(nodes)

        t = TreeMap(root)
        widths = tuple((rect.width, rect.height) for rect in t.rects)
        self.assertEqual(known, widths)
unittest.main()

repr shouldn't be used as a general pretty print method. It should give a short description of an object, preferably one which looks like code.

Its best to use correct english in variable names, i.e. children not childs.

Rather then combining a lot of strings, use StringIO

The TreeMap.build method is mostly concerned with a node. It should really be on the node class. The only interaction it has with TreeMap is the rectangles. But since you store those on the object anyway, we will provide a seperate iteration for those.

Once we've moved build into Node, TreeMap doesn't do anything, so we eliminate it.

There doesn't seem to be a really good reason for a Node to worry about its own depth.

I don't like the Node constructor. I don't think that a constructor should be concerned with conversion from a seperate format like that. Format conversions should be done in other functions. Since iter_method and size_method are only for that conversion, they should be arguments there

The tricky bit is the Node.build function. You have two for loops which look pretty much the same. We can combine them by pulling the bits of logic unique to each direction out.

My results:

from StringIO import StringIO

class Rectangle(object):

    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height

    def __repr__(self):
        return "Rectangle({0},{1},{2},{3})".format(
            self.x, self.y, self.width, self.height)

    def slice(self, horizontal, start, length):
        if horizontal:
            return Rectangle(self.x + start, self.y, length, self.height)
        else:
            return Rectangle(self.x, self.y + start, self.width, length)

class Node(object):

    def __init__(self, children, value):
        self.children = children
        self.value = value

    @classmethod
    def from_nested_tuple(class_, data):
        return class_.from_data(data, iter, int)

    @classmethod
    def from_data(class_, data, iter_method, size_method):
        try:
            iterable = iter_method(data)
        except TypeError:
            value = size_method(data)
            return class_([], value)
        else:
            children = [ class_.from_data(item, iter_method, size_method)
                for item in iterable]
            return Node(children, sum(child.value for child in children))

    def __repr__(self):
        return "Node< {}, {} children>".format( self.value, len(self.children))

    def _pretty_print(self, output, depth):
        output.write('\t' * depth)
        output.write('Node: {}'.format(self.value))
        output.write('\n')
        for child in self.children:
            child.pretty_print(output, depth + 1)

    def pretty_print(self):
        output = StringIO()
        self._pretty_print(output, 0)
        return output.get_value()

    def build(self, rect, horizontal=True):
        self.rect = rect

        sizes = [child.value for child in self.children]
        total_size = self.value

        if horizontal:
            space = rect.width
        else:
            space = rect.height

        position = 0.0
        for child in self.children:
            length = child.value * space
            child.build( rect.slice(horizontal, position, length),
                not horizontal)
            position += length

    def rectangles(self):
        yield self.rect
        for child in self.children:
            for rect in child.rectangles():
                yield rect

import unittest

class Test_TreeMap(unittest.TestCase):

    def test_build_depth0(self):
        nodes = (2,1,(2,2))

        known = (1, 1), (2.0/7, 1), (1.0/7, 1), (4.0/7, 1), (4.0/7, 0.5), (4.0/7, 0.5)

        Node.iter_method = iter
        Node.size_method = int
        root = Node.from_nested_tuple(nodes)
        root.build( Rectangle(0,0,1,1) )

        widths = tuple((rect.width, rect.height) for rect in root.rectangles())
        self.assertEqual(known, widths)
unittest.main()


Python the Dragon's Curve with turtle I'm kind of new to Python, and I'm trying to improve (especially) my object oriented programming, and getting to know Python syntax better.

I'd love to know if there is something to improve, (especially) in the matter of object oriented, or making the code more Pythonic (Syntactic sugar).

import turtle

RIGHT = 'r'
LEFT = 'l'

class Dragon_Curve(turtle.Turtle):
    def __init__(self, iterations, length):
        super(Dragon_Curve, self).__init__()
        self.iterations = iterations
        self.length = length
        self.hideturtle()
        self.speed(50)
        self.sequence = self.create_seq("", iterations)
        self.draw_sequence(self.sequence)

    def draw_sequence(self, dragon_sequence):
        for i in dragon_sequence:
            if i == RIGHT:
                self.right(90)
                self.forward(length)
            elif i == LEFT:
                self.left(90)
                self.forward(length)

    #  Create the dragon's path, depending on the number of iterations.
    def create_seq(self, given_seq, num_iterations):
        self.seq = ""
        if num_iterations == 0:
            print("the dragon's path is {}".format(given_seq))
            return given_seq
        else:
            self.seq += given_seq
            self.seq += 'r'
            self.seq += self.opposite(given_seq)[::-1]
        return self.create_seq(self.seq, num_iterations - 1)

    # flip the given sequence.
    # If the argument is 'rrl', it will return 'llr'
    def opposite(self, str):
        seq = ""
        for i in str:
            if i == 'r':
                seq += 'l'
            elif i == 'l':
                seq += 'r'
        return seq

if __name__ == '__main__':
    iterations = int(input("Enter number of iterations - "))
    length = int(input("Enter length size (recommended 5) - "))
    dragon = Dragon_Curve(iterations, length)
    turtle.Screen().title("The Dragon Curve")
    turtle.done()

Here are some suggestions and remarks, in no particular order:

i is not a great name for a variable in most cases, and especially not when it's not short for "index", as is the case in your draw_sequence function. I would suggest naming it direction.
The official Python PEP8 style guide states that class names should be CamelCased, so your class should be named DragonCurve, without the underscore.
There's no point in making self.seq an instance/member variable, since it's only used by the create_seq function and its value is reset on each call. It can safely be turned into a local variable.
Stick to using the LEFT/RIGHT constants instead of 'l'/'r'.
One small improvement that you could make is replacing your empty strings "" with a constant named EMPTY_SEQUENCE. This would completely hide the fact that sequences are represented as strings from the reader, and would make it easy for you to change the representation if you would ever want to.
Function names should be verbs, so opposite is not a good name for a function. Perhaps something like "flip" or "invert" would be more suitable.
The parameter named str will shadow the built-in function str. This is generally not a good idea, so maybe it should be named seq or sequence, since that is actually the abstraction that the function operates on.


Student information system I have made a small project and I am just wondering if I could add more functionality to the project e.g more classed etc.  Is a better way of displaying my results and what error handling I could do?

I was also wondering what would be the best way to add Inheritance to the this project.I was thinking a EveningCourse class or PostGrad, UnderGrad class. What would be the best way to go about it?

The user enters student name, age, year and student number.

package david;

public class Student
{

    private String name;
    private int age;
    private int year;
    private String studentNum;

    public Student(String name, int age, int year, String studentNum)
    {

        this.name = name;
        this.age = age;
        this.year = year;
        this.studentNum = studentNum;
    }

    // Setters and getters (Name, Age, Year and Student Number)

    public String getName() // name
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge() // age
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public int getYear() // year
    {
        return year;
    }

    public void setYear(int year)
    {
        this.year = year;
    }

    public String getstudentNum() // studentNum
    {
    return studentNum;
    }

    public void setstudentNum(String studentNum)
    {
        this.studentNum = studentNum;
    }

}

package david;

// David Needham - G00263842.
// Student information program.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class TestStudents
{

    public static void main(String[] args) throws IOException
    {

    System.out.println("============" + "=================");
    System.out.println("Students " + "Personal Details");
    System.out.println("============" + "=================");

    String name;
    int age;
    int year;
    String studentNum;

    List<Student> studentsList = new ArrayList<Student>();

    for (int i = 0; i < 2; i++)
    {

    int studentNumber = (i + 1);

    System.out.println("");
    System.out.println("Please enter " + "data for student " + studentNumber);

    InputStreamReader converter = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(converter);

    System.out.println("Enter Student "+ studentNumber + " Name:");
    name = in.readLine();

    System.out.println("Enter Student " + studentNumber + " Age (Integer):");
    age = Integer.valueOf(in.readLine());

    System.out.println("Enter Student " + studentNumber + " Year (Integer):");
    year = Integer.valueOf(in.readLine());

    System.out.println("Enter Student " + studentNumber + " Student Number:");
    studentNum = in.readLine();

    Student student = new Student(name, age, year, studentNum);

    studentsList.add(student); // add student
    }

    for (int j = 0; j < studentsList.size(); j++)
    {

        Student st = studentsList.get(j);

        System.out.println("Student : " + (j + 1));
        System.out.println("Name: " + st.getName() + " - Age: " + st.getAge() + " - Year: " + st.getYear() + " - Student Number: " + st.getstudentNum());
    }

    }
}

Yes, you can add more functionality to your project. You can take this in many different directirons such as adding courses that students and register for.

As for a error handling, you could add a check in your set functions of the Student class to check for formatting or content and return a boolean value based on if they pass the validation or not. For example, since studentnum is a string, you can check to make sure that the format of letters and numbers if correct, if there is a certain format.

You could also use a try-catch block around the code where you read in the values from the user. Or validate that the user enter an acceptable value for each entry such as checking that when the user is asked to enter the age, check to make sure that they did indeed enter a number.


Python program for Jump game II This is a Leetcode problem:

  Given an array of non-negative integers, you are initially positioned at the first index of the array.

  Each element in the array represents your maximum jump length at that
  position.

  Your goal is to reach the last index in the minimum number of jumps.

  Note:

  You can assume that you can always reach the last index.

Here is my first solution to this problem:

def jump(nums):
    n = len(nums)
    curr_far = min(nums[0], n - 1)
    next_far = 0
    step = 0
    for i in range(n):
        if i <= curr_far:
            if next_far < i + nums[i]:
                next_far = min(i + nums[i], n - 1)
            if i == curr_far and curr_far != 0:
                curr_far = next_far
                step += 1

    return step

nums = #Enter a list.
print(jump(nums))

Here is an example of an input/output:

nums = [2,3,1,1,4]
>>> 2

The minimum number of jumps to reach the last index is 2.

Jump 1 step from index 0 to 1, then 3 steps to the last index.

Here is my second solution to this problem:

class Solution:

    def __init__(self, nums):
        self.nums = nums

    def jump(self, nums):
        if not nums or len(nums) == 1:
            return 0

        curr = 0
        count = 0
        while(curr < len(nums)):
            maxReach = -1
            index = 0
            for i in range(1, nums[curr] + 1):
                if curr + i >= len(nums) - 1:
                    return count + 1
                else:
                    if nums[curr + i] + i > maxReach:
                        maxReach = nums[curr + i] + i
                        index = curr + i
            curr = index
            count += 1

nums = #Enter a list.
game = Solution(nums)
print(game.jump(nums))

Input/output - Same as above.

So, I would like to have a code review for the efficiency of both the programs.

Any help would be highly appreciated.

Improving the first solution

I like the first solution better, because I find it easier to understand how it works, and it's shorter.

It can be a bit simpler. The condition if i <= curr_far: is unnecessary and can be safely dropped.

Instead of iterating over a range of indexes, I nice trick is to use enumerate, like this:

for index, value in enumerate(nums):

This way, instead of nums[index] in the loop body, you can use value directly.

Another code smell is the condition if i == curr_far and curr_far != 0 executed in every iteration of the loop, even though curr_far != 0 will only be false for the first iteration, otherwise always true.

I didn't like most of the variable names...

Instead of step, I would find jumps more natural
Instead of curr_far and next_far, I would find reach and next_reach more intuitive

All in all, I would write like this instead:

class Solution(object):
    def jump(self, nums):
        end = len(nums) - 1
        if not end:
            return 0

        reach = 0
        next_reach = 0
        jumps = 0
        for pos, value in enumerate(nums):
            if next_reach < pos + value:
                next_reach = pos + value
                if next_reach >= end:
                    return jumps + 1

            if pos == reach:
                reach = next_reach
                jumps += 1

Issues with the second solution

Looks more complex than the first, and I think unnecessarily so
The __init__ method is completely unnecessary
The outer parentheses are unnecessary in while(curr < len(nums)):
The convention for the naming style of variables in Python is snake_case instead of camelCase


Checking whether the max and min values occur equally frequently An array is defined to be "maxmin equal" if it contains at least two different elements and the number of times the maximum value occur is the same as the number of times the minimum value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and min value 4 both appear two times in the array.

Write a function called isMaxMinEqual that accepts an integer array and returns 1 if the array is maxmin equal; otherwise it returns 0.

Note: Please do not use any string methods. No sorting allowed. No additional data structures including arrays allowed.

If the input array is:

{} | isMaxMinEqual should return 0 (array must have at least two different elements)

{2} | 0 (array must have at least two different elements)

{1, 1, 1, 1, 1, 1} | 0 (array must have at least two different elements)

{2, 4, 6, 8, 11} | 1 (Both max value (11) and min value 2 appear exactly one time)

{-2, -4, -6, -8, -11} | 1 (Both max value (-2) and min value -11 appear exactly one time).

Here is my solution. Is it possible to combine the loops?

    int max;
    int min;
    int maxCount = 0;
    int minCount = 0;
    if (a.length > 2) {
        max = a[0];
        min = a[0];
    } else {
        return 0;
    }
    for (int num : a) {
        if (num > max) {
            max = num;
        }
        if (num < min) {
            min = num;
        }
    }
    for (int num : a) {
        if (max == num) {
            maxCount++;
        }
        if (min == num) {
            minCount++;
        }
    }
    if (maxCount == minCount) {
        return 1;
    }
    return 0;

Reviews:

Nomenclature "a" : Name doesn't reflect the motive.
">2" is incorrect. It should be ">1".
{1, 1, 1, 1, 1, 1} will be incorrect in your case as min and max are same.
a could be null so we should check

if(input == null || input.size <2){
    return 0;
}

Multiple returns, though debatable but advisable.
Coming to reducing the loops:

for (int num : a) {
    if (num > max) {
        max = num;
        maxCount = 1;
    } else if (num == max) {
        maxCount ++;
    }

    if (num < min) {
        min = num;
        minCount = 1;
    } else if (num == min) {
        minCount ++;
    }
}

If you wish to minimize further: return (max != min && maxCount == minCount)


Combine Medical Response Files Prior To Table Load This is a script I wrote to:

Combine multiple text files into one CSV
Append the source file's name to each line of data

This script currently takes about 3 seconds per 10,000 lines read - this is so long in comparison to a working batch/Perl script I have that I'm wondering what I'm doing wrong.

Comments about whether this is even the best approach is welcome - anything that gets me one combined file with the source file name appended to each line is welcome. I chose to use StreamReader because the source files are very large.

Powershell

# Powershell -executionpolicy bypass -file (.ps1 file path)

[System.IO.DirectoryInfo]$ResponsesFolder = (folder path)
[System.IO.DirectoryInfo]$pathCombinedResponsesCSV = ($ResponsesFolder.Parent.FullName + [IO.Path]::DirectorySeparatorChar + $ResponsesFolder.BaseName + "_Combined_Responses.csv")

if (Test-Path $pathCombinedResponsesCSV) {
    Remove-Item $pathCombinedResponsesCSV
}

$streamWriter = New-Object System.IO.StreamWriter $pathCombinedResponsesCSV
Write-Host $pathCombinedResponsesCSV

$files = Get-ChildItem -Path ($ResponsesFolder.ToString() + "*.*") -File
$totalFiles = $files.Count

$fileindex = 0

$files | ForEach-Object {
    $streamReader = New-Object System.IO.StreamReader $_.FullName

    [int]$fileindex = $fileindex + 1
    Write-Host ("File " + $fileindex + " of " + $totalFiles)

    [string]$fileName = $_.Name

    [int]$lineIndex = 0

    while (([string]$line = $streamReader.ReadLine()) -ne $null) {
        $streamWriter.WriteLine($line + "|" + $fileName)
        $lineIndex = $lineIndex + 1

        if ($lineindex % 10000 -eq 0) {
            Write-Host $lineindex "lines of" $fileName "loaded"
        }
    }

    $streamReader.Close(); $streamReader.Dispose()

}

$streamWriter.Close(); $streamWriter.Dispose()

Batch/Perl

pushd (UNC folder path)

copy *.TXT *.csv

REM Add filename to end of each record.
net use b: /delete /y
net use b: (UNC folder path)
for /f %%a IN ('dir /b (UNC folder path)*.csv"') do (perl -i.bak -p -e "s/\n/|$ARGV\n/" %%a )

copy *.csv Consolidated_Magic_File.csv

The Perl approach can be shorter and faster than it already is:

perl -ple"BEGIN { @ARGV=glob shift } s,$,|$ARGV," *.csv > Consolidated_Magic_File.not_an_input
ren *.not_an_input *.csv

The best PowerShell approach is not so different from the fast Perl approach.  Feed a list of filenames, use Get-Content (or gc) to read them, let PS figure out where the line breaks are, loop through those results and collect all the outputs in one place.

ls \\unc\folder -Filter *.txt | %{ $fn=$_.Basename; gc $_.PSPath | %{ $_ + "|$fn" } } | sc out.csv

$_.Basename is the name without path or extension.  You can use $_.Name to get the original name with extension, or $_.Basename + ".csv" to label the output with CSV-filenames even though your input was TXT files.


Implement test which tries function with diferent params and expected results What could I improve in the following code? The goal is to test a function againts a table of input parameters and compare to some expected results with some tolerance (as there are random variables involved in the computations).

This is how I am doing it right now. Note that I cannot use any C++11 features.

void test() throw (const char *) {

    const double TOLERANCE = 0.01;

    const double EXPIRY_TESTS[] = {0.0, more values...};
    const double STRIKE_TESTS[] = { 0.0, more values... };
    const double SPOT_TESTS[] = { 0.0, more values... };
    const double VOL_TESTS[] = { 0.0, more values... };
    const double R_TESTS[] = { 0.0, more values... };
    const unsigned long NPATHS_TESTS[] = { 1, more values... };
    const double EXPECTED_RESULTS[] = { 0.0, more values... };

    int i_result = 0;
    for (int i0 = 0; i0 < sizeof(EXPIRY_TESTS) / sizeof(double); i0++) {
        for (int i1 = 0; i1 < sizeof(STRIKE_TESTS) / sizeof(double); i1++) {
            for (int i2 = 0; i2 < sizeof(SPOT_TESTS) / sizeof(double); i2++) {
                for (int i3 = 0; i3 < sizeof(VOL_TESTS) / sizeof(double); i3++) {
                    for (int i4 = 0; i4 < sizeof(R_TESTS) / sizeof(double); i4++) {
                        for (int i5 = 0; i5 < sizeof(NPATHS_TESTS) / sizeof(long); i5++) {

                            double result = SimpleMonteCarlo1(EXPIRY_TESTS[i0],
                                                              STRIKE_TESTS[i1],
                                                              SPOT_TESTS[i2],
                                                              VOL_TESTS[i3],
                                                              R_TESTS[i4],
                                                              NPATHS_TESTS[i5]);
                            if (abs(EXPECTED_RESULTS[i_result] - result) >= TOLERANCE) {
                                throw "Test failed!";
                            }
                            i_result++;

                        }
                    }
                }
            }
        }
    }

}

A six-fold nesting is not a way to go. Enumerating all possible combinations can be achieved in two loops, no matter how many arrays are contributing:

bool next_combination(int * combination, int * limits, int size) {
    for (int index = 0; index < size; ++index) {
        combination[index] += 1;
        if (combination[index] < limits[index]) {
            return true;
        }
        combination[index] = 0;
    }
    return false;
}

...

int limits[] = { countof(EXPIRY_TEST), countof(STRIKE_TEST), /*etc*/ };
int combination[countof(limits)] = 0;

do {
    result = function(EXPIRY_TEST[combination[0], STRIKE_TEST[combination[1], /*etc*/);
while (next_combination(combination, limits, countof(combination)));

Size of array is better be computed in a type-agnostic way:

#define countof(name) (sizeof(name) / sizeof(name[0]))

The expected results are totally disconnected from the argument sets. It would be very hard to make additional cases.
You must report which test case failed.


Efficient loop over a integer range in Python I want to search for positions inside a range of integers. How to improve the code in terms of efficiency, since both my search list and the ranges are very big:
#Range list with ids
range_lst = [(121000, 122000, 'foo'), (123456, 124557, 'bar'), (156789, 163659, 'egg')]
# Positions which we want to scan
pos = [123456, 369369]
# Neighbouring windows size
window_size = 10000

for p in pos:
    for r in range_lst:
        range_area = range(r[0], r[1])
        range_area_window = range(r[0]-window_size, r[1]+window_size)
        id = r[2]
        if p in range_area:
            print (p, id, 'exact hit!')
        else:
            # If we don't find an exact hit, we check the neighbouring region +- 10000
            if p in range_area_window:
                print (p, id, 'neighbour hit!')

I think that having a range is not necessary here. If you're only comparing against integer ranges, simple \$ \le \$ and \$ \ge \$ comparisons should suffice.
So, the following function is essentially the same:
def search_position(ranges, positions, window_size=10000):
    for low, high, range_id in ranges:
        for pos in positions:
            if low <= pos < high:
                print(pos, range_id, 'exact hit!')
            elif (low - window_size) <= pos < (high + window_size):
                print(pos, range_id, 'neighbour hit!')


Parsing C-like code to extract info I'm reading a file with the following data,

char peer0_3[] = { /* Packet 647 */
0x02, 0x00, 0x04, 0x00, 0x11, 0x01, 0x06, 0x1b,
0x04, 0x01, 0x31, 0x0a, 0x32, 0x30, 0x31, 0x39,
0x2d, 0x30, 0x36, 0x2d, 0x31, 0x30, 0x0a, 0x32,
0x30, 0x31, 0x39, 0x2d, 0x30, 0x36, 0x2d, 0x31,
0x30, 0x01, 0x30 };

with the following code, to get this 'C' text in a python list

f=open(thisFile,'r')
contents=f.read()
tcontents=re.sub('\/\*.*\*\/','',contents).replace('\n', '').strip()      #suppress the comments
xcontents = re.findall("{(.+?)};", tcontents, re.S)                       #find the arrays
frames=[]
for item in xcontents:
    splitData =item.split(',')
    buff=bytes()
    for item in splitData:
        packed =  struct.pack("B", int(item,0) )
        buff+=packed
    frames.append(buff)

That's working fine, but I was wondering if there was not a smarter and more compact method?

I think this can be done a lot more concisely. You need a function to recognize bytes until the end of the array, one to convert them to integers and one to pull it all together:

def get_bytes(f):
    for line in f:
        yield from re.findall(r'0x\d{2}', line)
        if line.rstrip().endswith(";"):
            break

def convert_str_to_bytes(s):
    return int(s, 0).to_bytes(1, 'big')

def convert_arrays(file_name):
    with open(file_name) as f:
        while True:
            arr = b''.join(map(convert_str_to_bytes, get_bytes(f)))
            if arr:
                yield arr
            else:
                return

if __name__ == "__main__":
    print(list(convert_arrays('c_like_code.txt')))
    # [b'\x02\x00\x04\x00\x11\x01\x06\x04\x0112019061020190610\x010']


"Increment" a string of uppercase characters Given a string of uppercase characters, return a string corresponding to the next item in the following series:

A, B, ..., Z, AA, AB, ..., AZ, BA, ..., BZ, ..., ZZ, AAA, ...

My code:

def increment_char(c):
    """
    Increment an uppercase character, returning 'A' if 'Z' is given
    """
    return chr(ord(c) + 1) if c != 'Z' else 'A'

def increment_str(s):
    lpart = s.rstrip('Z')
    if not lpart:  # s contains only 'Z'
        new_s = 'A' * (len(s) + 1)
    else:
        num_replacements = len(s) - len(lpart)
        new_s = lpart[:-1] + increment_char(lpart[-1])
        new_s += 'A' * num_replacements
    return new_s

Proof my code works according to the specification I gave above:

In [4]: increment_str('A')
Out[4]: 'B'

In [5]: increment_str('Z')
Out[5]: 'AA'

In [6]: increment_str('AA')
Out[6]: 'AB'

In [7]: increment_str('AZ')
Out[7]: 'BA'

In [8]: increment_str('ZZ')
Out[8]: 'AAA'

One thing I would ask you ignore is whether or not you think s and new_s (but only those two) are good names for identifiers, because they are not present in the real code (only the trimmed down version for here). All other suggestions, bug reports, etc., are welcome.

A slight simplification of the if else structure is possible:

def increment_str(s):
    lpart = s.rstrip('Z')
    num_replacements = len(s) - len(lpart)
    new_s = lpart[:-1] + increment_char(lpart[-1]) if lpart else 'A'
    new_s += 'A' * num_replacements
    return new_s


Class dedicated to transforming API response to the data I need? I have the following code (in php) that calls the open weather api with my credentials, and returns data for me.
Know I'm returning some data I pick from that response, I'm wondering if it's good practice to create a dedicated class for that? Is this something that's commonly used and does it have a name?
try {
    $request = $this->http->get( 'api.openweathermap.org/data/2.5/weather', $options);
    $response = json_decode($request->getBody());

    return [
        'main' => $response->weather[0]->main,
        'temperature' => $response->main->temp,
    ];

} catch (GuzzleException $e) {
    die(var_dump($e->getMessage()));
}
```

Your might actually take it a step further and create a value object for the data, making it much more type safe. Notice I added PHP 7.4 proeprty typehints. I chosen float for the temperature (maybe it's not appropriate, idk), but i definitely don't know what to choose for the main, but it sure deserves a typehint, if it's nested object, create another class for it or maybe pick the wanted information directly into the WeatherStatus class.
final class WeatherStatus
{
  private ??? $main;
  private float $temperature;

  public function __construct(??? $main, float $temperature)
  {
    $this->main = $main;
    $this->temperature = $temperature;
  }

  public function getMain(): ???
  {
    return $this->main;
  }

  public function getTemperature(): float
  {
    return $this->temperature;
  }
}

You can also define an interface for such a method, including a domain specific exception (because just halting the program with die or exit is not very nice thing to do, in that case it would be better to not catch the exception at all).
class WeatherProviderException extends \Exception
{
}

interface IWeatherProvider
{
  /**
   * @throws WeatherProviderException
   */
  public function getWeather(): WeatherStatus;
}

In the implementation I would accept the api url rather then hardcoding it. You may add a static named constructor for the version 2.5 api.
The credentials for openweathermap.org (whatever they are, let me assume a user name and password) might be also promoted to a class or may be passed to the provider constructor as multiple arguments as well.
final class OpenWeatherCredentials
{
  private string $user;
  private string $password;

  // constructor + getters ...
}

class OpenWeatherProvider implements IWeatherProvider
{
  private ClientInterface $client;
  private string $apiUrl;
  private OpenWeatherCredentials $credentials;

  public function __construct(ClientInterface $client, string $apiUrl, OpenWeatherCredentials $credentials)
  {
    $this->client = $client;
    $this->apiUrl = $apiUrl;
    $this->credentials = $credentials;
  }

  public static function createV2_5(ClientInterface $client, OpenWeatherCredentials $credentials): self
  {
    return new self($client, 'https://api.openweathermap.org/data/2.5/weather', $credentials);
  }

  public function getWeather(): WeatherStatus
  {
    $options = [
      // whatever is needed, $this->credentials->get*
    ];

    try {
      // here you called the object $request, but it really is a $response
      $response = $this->client->get($this->apiUrl, $options);
    } catch (GuzzleException $e) {
      throw new WeatherProviderException($e->getMessage(), $e->getCode(), $e);
    }

    try {
      $json = json_decode($response->getBody(), \JSON_THROW_ON_ERROR);
    } catch (\JsonException $e) {
      throw new WeatherProviderException($e->getMessage(), $e->getCode(), $e);
    }

    return new WeatherStatus(
      $json->weather[0]->main,
      (float) $json->main->temp,
    );
  }
}

Also notice how I wrap each statement in separate try-catch to only catch what can be caught. As long as they are handled the same way you try-catch both together but maybe you should catch their common ancestor exception instead to make it even simpler. And I pulled the instantiation of the WeatherStatus out of the try-catch just because I don't expect it to throw GuzzleException nor \JsonException.


Counting weather events for visualization using Gnuplot I wrote this code to analyze ~800 MB of weather data from the US. I am planning on visualizing the data with Gnuplot and Gimp. I have already made the images and a gif file. This code runs somewhat fast, although I do not suppose it is efficent. How can I improve it?

The idea behind my code is:

find keywords in the lines, such as state names and their weather conditions
save the weather condition in a map according to the state and year
get the yearly weather conditions to a file named after the analyzed state

main code:

int main()
{
    std::string data[18] = {"stormdata_1996.csv",
                            ... // I left out the files from her on purpose
                            "stormdata_2013.csv"};
    for(int j=0;j<18;j++){
        std::string city[36] = {"TEXAS",
                                ... // left out on purpose as well
                                "OREGON",
                                "MISSOURI"};
        for(int i=0;i<36;i++){
            std::map<std::string, int> weather;
            std::ifstream fin(data[j].c_str(),std::ios::in);
            getWeather(weather, fin, city[i]);
            fin.close();
            std::ofstream fout(city[i].c_str(),std::ios::app);
            outPut(weather, fout, city[i],j+1996);
            fout.close();
            weather.clear();
        }
    }
    return 0;
}

functions:

void getWeather(std::map<std::string, int>& weather, std::ifstream& fin, std::string& city){
    std::string line;
    while(!fin.eof()){
        getline(fin, line);
        if(line.find(city) != std::string::npos){
            if(line.find("Drought") != std::string::npos){
                weather["Drought"]++;
            }else if(line.find("Flood") != std::string::npos){
                weather["Flood"]++;
            }else if(line.find("Heavy Snow") != std::string::npos){
                weather["Heavy Snow"]++;
            ... // I left out some else if statements from here to shorten the post
            }else if(line.find("High Surf") != std::string::npos){
                weather["High Surf"]++;
            }
        }
    }
}

void outPut(std::map<std::string, int>& weather, std::ofstream& fout,std::string& city, int date){
    fout << city << "-" << date << std::endl;
    for(auto i:weather){
        fout << i.first << "\t" << i.second << std::endl;
    }
    fout << std::endl;
}

Here's a gif of ALASKA's weather from 1996 to 2013:

I see a number of things that may help you improve your program.

Use the required #includes

The code uses std::map which means that it should #include <map>.  It was not difficult to infer, but it helps reviewers if the code is complete.  I believe that the full set of required includes is:

#include <string>
#include <iostream>
#include <fstream>
#include <map>

Use const where practical

The current getWeather() routine does not (and should not) modify the passed city string, and so it should be declared const:

void getWeather(std::map<std::string, int>& weather, std::ifstream& fin,
        const std::string& city){

For the outPut routine, both city and weather should be const.

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Let the computer do the counting

The main() routine contains this:

std::string city[36] = {"TEXAS",
                        "OREGON",
                        // ... presumably 33 other states
                        "MISSOURI"};
for(int i=0;i<36;i++){

What would make more sense is to omit the 36 and simply iterate directly over the strings, using a "range for" since you're using C++11.  It's a bit peculiar to have 36 states since the United States hasn't had 36 states since 1867, when Nebraska became the 37th state, and even more peculiar that such an array is named city!  I'd write it like this:

std::string states[] = {"TEXAS",
                        "OREGON",
                        // .. maybe 47 other states?
                        "MISSOURI"};
for(const auto &state : states) {

Don't use eof for the loop condition

The code currently contains these lines:

while(!fin.eof()){
    getline(fin, line);

However, that's almost never what you really want.  Instead, write this:

while (std::getline(fin, line)) {

This is not only shorter and more direct, but it actually functions in the way you'd want and expect.

Avoid repeating code

In the getWeather() routine, we have a long list of if statements that looks like this:

if(line.find("Drought") != std::string::npos){
    weather["Drought"]++;
}else if(line.find("Flood") != std::string::npos){
    weather["Flood"]++;

This approach has a few problems.  First, it's needlessly repetitive since it repeats the event type twice in each pair of lines.  Second, it is subject to miscounting because it assumes that, for example, the word "Flood" appearing in the line always means that the event type was "Flood".  Assuming you're using this NOAA data, then it's easy to find a counterexample.  For instance, if you look at the 2014 data, there was an event on 3 August 2014 for which the event code is "Thunderstorm Wind" but the description contains the word "Flood".  This leads to my next suggestion.

Parse the file

An alternative to searching the entirety of each line would be to parse the lines, since it's a CSV file.  There are a number of ways to do so, and a number of third-party libraries for that, but I'd be inclined to use the regex part of the standard library.  In particular, this can be done with a std::regex_token_iterator.

Think carefully about data structures

Right now the code uses a std::map but since maintaining any particular ordering appears to be unimportant for this code, it would likely confer a performance benefit to use a std::unordered_map instead.

Rethink the algorithm

Right now, each input file is scanned once for every state and files are opened and closed with every iteration through the inner loop.  Wouldn't it make more sense just to make a single pass through each input file?  Further, each state's output is probably small enough that all of the data could be generated in memory and then written out when everything is parsed.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.

Results

Here' how I reworked the code to implement all of these suggestions:

#include <string>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <map>
#include <regex>

using StateWeather = std::unordered_map<std::string, std::unordered_map<int, std::map<std::string,int>>>;

std::istream &getWeather (std::istream &in, StateWeather &wx, int year) {
    static const std::regex re{R"x(("([^"]*)"|[^,]*),|$)x"};
    static const std::sregex_token_iterator regend{};
    static constexpr unsigned stateFieldNum{8};
    static constexpr unsigned typeFieldNum{12};
    static constexpr auto maxField{std::max({stateFieldNum, typeFieldNum})};
    std::string line;
    if (std::getline(in, line)) {
        auto it = std::sregex_token_iterator(line.begin(), line.end(), re, 2);
        std::string state;
        std::string type;
        for (unsigned i=0; i <= maxField && it != regend; ++it, ++i) {
            switch (i) {
                case stateFieldNum:
                    state = *it;
                    break;
                case typeFieldNum:
                    type = *it;
                    ++wx[state][year][type];
                    break;
                default:
                    // do nothing
                    ;
            }
        }
    }
    return in;
}

int main()
{
    static constexpr int startyear{1996};
    static constexpr int endyear{2013};
    StateWeather wx{};
    for (auto year = startyear; year <= endyear; ++year) {
        std::ifstream in{"stormdata_"+std::to_string(year)+".csv"};
        while (getWeather(in, wx, year)) {
        }
    }
    for (auto &statedata : wx) {
        std::ofstream out{statedata.first};
        for (auto year = startyear; year <= endyear; ++year) {
            out << statedata.first << '-' << year << '\n';
            auto &events = statedata.second[year];
            for (const auto &event : events) {
                out << event.first << '\t' << event.second << '\n';
            }
            out << '\n';
        }
    }
}

This code runs on the full data set, generating one file per "state" (the data contains "state" designations such as "GUAM" which is a territory, not a state, and "LAKE ERIE" which is a body of water) in 4.4 seconds on my 64-bit Linux machine.  I used gcc version 6.3.1 and -O2 optimization.


Simple Tip Calculator with JavaScript Console App Simple console tip calculator app in JavaScript. I would like to get some feedback on improving my code. Thank you beforehand.

Source code:

//header
const headerMessage = () => {
  console.log('Tip Calculator')
}

//service quality
const serviceQuality = (billEntered, userOption ) => {
  const userInput = Number(userOption);
  switch(userInput){
    case 1:
      return (billEntered * 0.3)
      break;
    case 2:
      return(billEntered * 0.2)
      break;
    case 3:
      return(billEntered * 0.1)
      break;
    case 4:
      return(billEntered * 0.05)
      break;
   }
}

const tipCalulcator = () => {
  headerMessage()
  const enterBill = prompt('Please tell me bill amount: $ ');
  console.log(`Bill amount was $ ${enterBill}`)
  console.log(`How was your service ? Please enter number of the options`)
  const enterOption = prompt(`  1) Outstanding (30%)
  2) Good (20%)
  3) It was ok (10%)
  4) Terrible (5%)`)

  const result = serviceQuality(enterBill, enterOption);
  console.log(`Tip amount ${result}`)
  const total = Number(enterBill) + result;
  console.log(`Overall paycheck ${total}`)
}

tipCalulcator();

A couple of things to consider:

When dealing with a switch statement, if a case utilizes the return keyword then you do not need to also include a break. When the return is hit, no further code in that function will be reached.
You should handle unexpected inputs; for example, serviceQuality should account for non-numeric inputs, or a number that is not 1-5. Look into try/catch statements and using a default case on your switch.
Because you are not reusing headerMessage, this function is not really required.
Your variable names are fairly unintuitive; consider changing them so that it's more obvious what each thing is such as enterBill -> billAmount and enterOption -> serviceOption. It might be worth using those same names as the serviceQuality arguments too.


Using nullable properties in a base class for record selection in Table per Hierarchy I want to be able to list every Transaction associated with a Client in date order.

Transaction has 2 sub-types: PaymentTransaction and ChargeTransaction.

The key difference between them is:

PaymentTransaction should be associated directly with a Client.
ChargeTransaction is associated with a Proposal, which in turn is associated with a Client.

public abstract class Transaction
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public DateTime Time { get; set; }
}

public class PaymentTransaction : Transaction
{
    public int ClientId { get; set; }
    public Client Client { get; set; }
}

public class ChargeTransaction : Transaction
{
    public int ProposalId { get; set; }
    public Proposal Proposal { get; set; }
}

public class Client
{
    public int Id { get; set; }
    public ICollection<Proposal> Proposals { get; set; }
    public ICollection<PaymentTransaction> Payments { get; set; }
}

public class Proposal
{
    public int Id { get; set; }
    public int ClientId { get; set; }
    public Client Client { get; set; }
    public ICollection<ChargeTransaction> Charge { get; set; }
}

There will be 1000s of records for each Client. So I need to page the results.

I don't want to have to blend the results from 2 Db tables, so I have used Table per Hierarchy pattern:

public DbSet<Transaction> Transactions { get; set; }
public DbSet<PaymentTransaction> PaymentTransactions { get; set; }
public DbSet<ChargeTransaction> ChargeTransactions { get; set; }

My problem is retrieving the results for a specific ClientId. For db.ChargeTransactions I would use x => x.Proposal.ClientId. And for db.PaymentTransactions I would use x => x.ClientId. But for db.Transactions I cannot use either of these.

My Solution

I have put the Proposal and Client properties directly on the Transaction model and made them nullable.

I'm not convinced this is a good solution, but I don't know a better way. That is why I'm asking this question.

Can you suggest any improvements on this? Or a better approach?

public abstract class Transaction
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public DateTime Time { get; set; }
    public int? ClientId { get; set; }
    public virtual Client Client { get; set; }
    public int? ProposalId { get; set; }
    public virtual Proposal Proposal { get; set; }
}

public class PaymentTransaction : Transaction
{

}

public class ChargeTransaction : Transaction
{

}

This means I can do:

db.Transactions.Where(x => x.ClientId == clientId || x.Proposal.ClientId == clientId)

It's hard to answer your question with a definitive answer as so much information is missing and a lot, depends also on the other UI screens data that you need to fill or that other may have opened. You’re going to get issues when performing aggregates on the same table that you provide row data on as you might end-up in a deadlock, even with yourself. I'm going to give some basic data that goes through my mind, if you already know this, no harm done, just skip over it.

1 Transaction scope:
Say you have a transaction summing over the charges and payments to get a balance, you also would like to return the last 10 charges as well as the last 10 payments. We all know that there is no guarantee that charges and payments sum-up you will get into partial payments.

Then users will use a invoice reference number in the payments so you need to book a payment to that reference even if there are older charges that would incur late fees (this may actually be a business case for some companies as they charge more).

You're may not be able to guarantee that the table is partitioned in a way that would facilitate transactional isolation levels to that detail so you will likely need to set your connections to allow for a snapshot isolation level (this will hit your tempdb with snapshot data so size for that) as you have no or little control over the TSQL generated by EF. If you can think of the data that you your using as  ViewModel class in MVC that that would help, you do not need take the whole table into memory when you a limited subset. You will have less issues when you’re updating the data that another user might also be updating

public class FooViewConfiguration : EntityTypeConfiguration<FooView>
{
   public FooViewConfiguration()
   {
    this.HasKey(t => t.Id);
    this.ToTable("dbo.myView");
   }
  …
}

You will find that you’re users are getting optimistic concurrency exceptions (you never get them as you’re the only one changing the data in your database) so you’re data scope needs to deal with that. Have a look at

using (var context = new PaymentTransactionContext())
{
    var payment = context.Payments.Find(1);
    payment.PayedByName = "client Name";
    payment.PaymentDate = UTCNow;

    bool saveFailed;
    do
    {
        saveFailed = false;

        try
        {
            context.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            saveFailed = true;

            // Update the values of the entity that failed to save from the store
            ex.Entries.Single().Reload();
        }

    } while (saveFailed);
}

And only save that where you have a change.

using (var context = new MyContext())
{
    context.ChangeTracker.TrackGraph(customer, e =>
    {
        e.Entry.State = EntityState.Unchanged;

        if((e.Entry.Entity as Invoice) != null)
        {
            if (e.Entry.IsKeySet)
            {
                e.Entry.State = EntityState.Modified;
            }
            else
            {
                e.Entry.State = EntityState.Added;
            }
        }
    });

    foreach (var entry in context.ChangeTracker.Entries())
    {
        Console.WriteLine("Entity: {0}, State: {1}", entry.Entity.GetType().Name, entry.State.ToString());
    }
    context.SaveChanges();
}

You limit this by using an (indexed) view and control the locking using TSQL, you can update data in a view either direct if only one table is involved or by using "instead of" triggers when you join several tables.

2 Indexing and locks: You might have some and you might find that your indexes are disabled (they get broken on ETL import errors) or those that you need are missing you will usually end-up with table locks as the dbms has alternative as the only option is a table scan or index scan (yes, both are bad).

Adding to many indexes will really slow down the inserts as they need to be maintained as well. Depending on the size and quantity of an index that might get out of hand. (once worked on a project where I had to drop all indexes, then do a backup and re-create the indexes in order to backup and maintain the recovery time objectives).

Also indexes, and covering indexes will widen the scope of the data as this needs to be locked as well.

What one ends-up doing is design a database that has indexes on join fields first. The way you limit the scope and speed up your table is by "removing unrelated data" as early as possible, the smaller the scope the smaller the lock the less disk I.O. SQL server executes the plan after a given time, might not be the best plan, but you do not want to wait 2 seconds for him to figure it out (that's why you can pre-compile plans and attach them). Usually what I end-up doing is make 2 connections/ contexts. I normally have a database connection with a read-only intend. And one with a read-write intend. This way will save yourself quite a few locking issues and note that this is what makes working with large databases so slow, you quickly end up locking too much and read too much. The read-only will do most of the heavy lifting and cause little or no issues as the intend and transaction levels help.

3 Database are for storing data, they are not OO: Sql server does support graph, and you would get some kick-ass performance however EF doesn’t as far as I know.  So, if getting a bigger database I advice to not use OO design from the class as a mirror on the SQL tables, it’s not going to perform, go to the 6th nominal form and start duplicating data. Or create a physical table for all 3  using a 1-1 optional relationship (a foreign key that is disabled for query plans) and a trigger for data integrity
Also, I think that Proposal is a perhaps a ChargeTrasnaction that has a flag of being accepted… could this be

I think, try having a customer with relationships on "view model"/"unit of work" scoped data using ICollection for all relations and really limit what you load using the above mentioned option.

You can always use EF and SqlCommand and use the best of both worlds when ever you need.


Remove duplication in SELECT statement Say I have the following SQL:

SELECT
    amount,
    amount*.1,
    (amount*1)+3,
    ((amount*1)+3)/2,
    (((amount*1)+3)/2)+37
FROM table

Instead of repeating that identical code every time, I really want to be able to do something like this:

SELECT
    amount,
    amount*.1 AS A,
    A+3 AS B,
    B/2 AS C,
    C+37 AS D,
FROM table

But this code doesn't work.

So, is there another way to avoid duplication in the working query that I have?

You could define intermediate views using common table expressions.  That would eliminate the redundancy of the calculations, but redundantly introduce a different kind of redundancy.

WITH ATable AS (
    SELECT amount, amount*.1 AS A FROM table
), BTable AS (
    SELECT amount, A, A+3 AS B FROM ATable
), CTable AS (
    SELECT amount, A, B, B/2 AS C FROM BTable
)
SELECT amount, A, B, C, C+37 AS D FROM CTable;


Replace radio/checkbox plugin I've just created my first plugin, but I think I've written too much bloated code. Could you point me to the right direction?

$.fn.replaceme = function() {

    function add_essentials(element) {
        var native_btn = element;
        native_type = native_btn.attr('type');

        native_btn.each(function() {
            var n_btn = $(this);
            n_btn.next('label').addClass('label-replacement');
            n_btn.wrap('

');
            n_btn.parent('.input-container').append('
');
        });
    }

    function replace_default_action(element) {
        var input = element;
        group = input.attr('name');

        $('input[name="' + group + '"]').each(function() {

            var input_select = $(this);
            if (input_select.is(':checked')) {
                input_select.siblings('.input-replacement').addClass('selected');
            } else {
                input_select.siblings('.input-replacement').removeClass('selected');
            }
        });
    }

    function label_action(element) {
        element.prevAll('.input-container').children('.styled-input').prop('checked', 'checked').trigger('change');
    }

    function live_check() {
        $('.styled-input:checked').each(function() {
            $(this).siblings('.input-replacement').addClass('selected');
        });
    };

    return this.each(function() {

        var $this = $(this);

        add_essentials($this);
        live_check();

        $('body').on('change', '.styled-input', function() {
            replace_default_action($this);
        });

        $('body').on('click', '.label-replacement', function() {
            label_action($this);
        });
    });
}

$('.styled-input').replaceme();

Scanning your code I have a few recommendations to make. If you update your question with a demo I'll make a few more.

As I mentioned in comments you have a few obvious issues with globals

var native_btn = element;
native_type = native_btn.attr('type');
//should be
var native_btn = element,
    native_type = native_btn.attr('type');

And similarly for group. I don't understand why you're doing this

function replace_default_action(element) {
        var input = element;
        group = input.attr('name');

Why not:

function replace_default_action(input) {
    var group = input.attr('name'); //on another note I'd prefer groupName over group

Throughout your code you make pretty good use of chaining in places it is clear and concise however there are a few spots I would adapt

Obvious one:

$('body').on('change', '.styled-input', function() {
            replace_default_action($this);
        })
        .on('click', '.label-replacement', function() {
            label_action($this);
        });

You can write this code with toggleClass to remove some lines

    var input_select = $(this);
    if (input_select.is(':checked')) {
        input_select.siblings('.input-replacement').addClass('selected');
    } else {
        input_select.siblings('.input-replacement').removeClass('selected');
    }

    //With toggle class
    var input_select = $(this);
    input_select.siblings('.input-replacement').toggleClass('selected', input_select.is(':checked'));

Also I'm pretty sure you have a logic error here:

.append('
')

Finally in javascript, especially with jQuery code (per their style guide), we prefer camelcasing over underscores for names. I'll point you to this discussion from SO.

Update Here's how I would probably write your code and here's your updated fiddle up and running. As you'll notice I removed all your helper functions that were only called once as there was no need for them and I found them confusing to be honest. I added guiding comments to replace them. I corrected the things mentioned in this review, including function names and condensed ways of writing the original. In the future I think you would benefit from trying to write your functions as straightforward and simple as possible (it took me a while to understand your original code cause of all the helper abstractions)!

$.fn.replaceme = function() {
    'use strict';

    return this.each(function() {

        var $this = $(this);
        var native_type = $this.attr('type');

        //setup button for plugin
        $this.each(function() {
            var $btn = $(this);
            $btn.next('label').addClass('label-replacement');
            $btn.wrap('
');
            $btn.parent('.input-container').append('');
        });

        //check if is live
        $('.styled-input:checked').each(function() {
            $(this).siblings('.input-replacement').addClass('selected');
        });

        //handlers
        $('body').on('change', '.styled-input', function() {//set default action, override if already one exists
            var group = $this.attr('name');
            var $cur = $(this);
            $('input[name="' + group + '"]').each(function() {
                $cur.siblings('.input-replacement').toggleClass('selected', $cur.is(':checked'));
            });
        })
        .on('click', '.label-replacement', function() {
            $this.prevAll('.input-container').children('.styled-input').prop('checked', 'checked').trigger('change');
        });
    });
};


Code to create and check a numeric password I am very new to coding and I have created this relatively simple code to do with my basic knowledge of the language. However I have had to do with some unwanted code including shutting it down if password is too long. so could anybody help me with any improvements to this?

import time

passwordx = float(input('create your password'))
def password():
    passwordx
    if passwordx>9999:
        print('password is wrong\n innitiating shutdown')

        x=5
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        quit()

    else:
        print('code saved')
        x=1
        while x <1000:
            print('###############')
            x+=1

def login():
    passwordguess = float(input('please enter password'))

    if passwordguess == passwordx:
        print('access granted')

    else:
        print('wrong')
        print('here\'s a clue', (passwordx-passwordguess)**2)
        login()

password()

login()

A couple of things:

Start using range.

Range is the recommended way to loop in Python.
And you can change your shutdown sequence, and while loop to use it.
This improves the clarity of your code, which is good for when others read it.
And even if no-one else will, it's always good to get good habits.
Reduce the amount of unneeded messages to the end user.
Here less is more.

Seriously, I was used to overly verbose messages when I was on windows.
And then I installed Linux and would most of the time get no feedback.
To change my keyboard layout I use loadkeys dvorak, and I get no message.
I create a file, touch file, and again no message.
The only time I get a message is if that's the intent of the command, ls, or if it's an error.

Honestly you should probably take a leap out of their book.
It's normally best to avoid recursion.

I once made a program that heavily used recursion,
it exceeded the recursion limit and there was no way for me to fix it.
I can assure you I never touched that project again.

Instead I'd use a while loop.
Use getpass.

This removes the need to display a lot of hashes to remove the password from display.
As it never displays in the first place.
Change password to create the password.

This way the method of creating a password is always the same.
Change login to take the password as an argument.

This is as it removes reliance on globals which is always a good thing.
You should check the input is a number, otherwise you program will exit with an error.

from time import sleep
from getpass import getpass # 4

def create_password(): # 5
    password = getpass('Create your password: ') # 4, 5
    try: # 7
        password = float(password)
    except ValueError:
        quit()
    if password > 9999:
        print('Password is invalid, initiating shutdown.')
        for i in range(5, -1, -1): # 1
            time.sleep(1)
            print(i)
        quit()
    return password # 5

def login(password): # 6
    while True: # 3
        password_guess = float(input('Please enter password: '))
        if password_guess == password:
            break # 3
        else:
            print("Wrong. Here's a clue", (password - password_guess) ** 2)

password = create_password()
login(password)

The above shows how I'd change your code if I were to keep the messages you added special code for.
I still think most of your messages are not needed, and so I'd remove more of them.
I also dislike your clue, as it's ridiculously insecure.
And due to floating point inaccuracy I'd store the password as a string.
Resulting in:

from getpass import getpass

def create_password(): # 5
    password = getpass('Create your password: ')
    try:
        float(password)
    except ValueError:
        quit()
    if float(password) > 9999:
        quit()
    return password

def login(password):
    while True:
        password_guess = input('Please enter password: ')
        if password_guess == password:
            break

password = create_password()
login(password)

Finally I'd think about removing the float(password) > 9999.


Checking that a password contains a '$', a digit, and an uppercase letter I have this code, which reads in a string password from the user and checks if it has a dollar sign $, a number, and an upper case letter. If it has all three, it prints:

  Your password is correct

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

#define MAXSIZE 100

void password_read(char password[]);
int password_check(char password[]);

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

    char password[MAXSIZE];
    int sum;

    password_read(password);

    sum = password_check(password);

    if (sum) {
        printf("Your password is correct\n");
    } else {
        printf("Your password sucks\n");
    }

    return 0;
}

void
password_read(char password[]) {
    printf("Enter password:\n");
    scanf("%s", password);
}

int
password_check(char password[]) {
    int upper = 0;
    int digit = 0;
    int dollar = 0;
    int i;

    for (i = 0; i < strlen(password); i++) {

        if (isupper(password[i])) {
            upper = 1;
        }

        else if (isdigit(password[i])) {
            digit = 1;
        }

        else if (password[i] == '$') {
            dollar = 1;
        }
    }
    return (upper && digit && dollar);
}

I'm pretty shabby with C and I was just wondering if there was a way to reduce part of the code. I also just want to check if the pointer/array handling is correct, since I've only just started using it properly.

Design

So the point of this program is to check a password, right?  There are many problems with your approach to verifying a password.  To list a few:

Password could be brute-forced in a matter of milliseconds (on a slow machine) due to small length
Anyone could reverse-engineer your code by de-compiling it and find out how to enter a valid password, even if length was increased to something not as easily brute-forced.
You aren't masking the password when it's entered into the command line in any way; someone looking over your shoulder now knows your password

Your MAXSIZE is 100 when our password could be a length of 3? Or larger?  We should be dynamically allocating the input variable.

Readability & Maintainability

Understandable variable and function names, good
No documentation, despite it being a small and easy to understand program you should still include this
Should have a header for those function prototypes, and perhaps a separate source file for the password handling functions.
You don't use command line arguments, declare main() as such:

int main(void)

You should be using puts() instead of printf() since you are not formatting strings (this also lets us exclude the \n)
You don't have to return 0 at the end of main(). The C standard  knows how frequently this is used, and lets us omit it.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.

Functionality

While the program is only supposed to verify a password, the functionality isn't great.  Why?  Well look at the conditions for our password to be "correct" (quite a large range of strings will fall into this range):

an uppercase letter
a digit
a $ character.

So H8$ is a valid password.  Okay... but what if our password isn't "correct"?  You output "Your password sucks".  But that's actually quite unlikely, my passwords could be MUCH stronger than yours.  Reference this relevent XKCD:

Security

All in all, you shouldn't even be handling passwords by yourself.  You should be relying on external libraries to get and encrypt the password.
To get a password, you could use getpass(), but it is deprecated.  See this answer for an alternative implementation.
To hash a password, I would definitely go with OpenSSL. Please, when it comes to encryption, don't try and roll your own, or just find something someone posted on the Internet. Go with something like OpenSSL that is verified, and trusted by millions every day.


Deleting a node from Binary Tree in OCaml I am currently exploring OCaml and wrote the following implementation of deleting a node from a binary tree

let rec deleteNode tree' value =
  match tree' with
  | Empty -> Empty
  | Node(left, nodeValue, right) ->
      if value < nodeValue then
        Node((deleteNode left value), nodeValue, right)
      else if value > nodeValue then
        Node(left, nodeValue, (deleteNode right value))
      else if left = Empty && right = Empty then
        Empty
      else if left = Empty then
        right
      else if right = Empty then
        left
      else
        let newValue = minValue right in
        Node(left, newValue, (deleteNode right newValue))

Where my tree type is

type tree =
  | Empty
  | Node of tree * int * tree

I am looking for a review of my code so that I can improve my OCaml and functional skills.

Syntax

There are no hard rules on this, but I would change a couple things in your syntax:

avoid ' in identifiers. Especially in that case, you can use tree instead of tree' (there is no collision with the type name).
usually there's a space before constructor arguments, like Node (left, nodeValue, right) (really up to convention, but I'd say it's more common).
parentheses around function application are not necessary, so it's more idiomatic to write Node (deleteNode left value, nodeValue, right). You can also extract a binding: let newLeft = deleteNode left value in Node (newLeft, nodeValue, right)
camel case is rare is ocaml (I know, that's weird!). For example the standard library uses names like print_endline etc. So, I'd use node_value, etc.

Replace conditionals with guards

Every time a if is in a pattern matching branch, you can extract it into a guard. The syntax is | pattern when condition ->.

By applying this to the first ifs, we can arrive to this state:

let rec deleteNode tree' value =
  match tree' with
  | Empty -> Empty
  | Node (left, nodeValue, right) when value < nodeValue ->
        Node((deleteNode left value), nodeValue, right)
  | Node (left, nodeValue, right) when value > nodeValue ->
        Node(left, nodeValue, (deleteNode right value))
  | Node (left, nodeValue, right) ->
      if left = Empty && right = Empty then
        Empty
      else if left = Empty then
        right
      else if right = Empty then
        left
      else
        let newValue = minValue right in
        Node(left, newValue, (deleteNode right newValue))

Use deep pattern matching

You can replace the x = Empty tests by pattern matching. In other words, patterns can contain patterns. By applying this to all the conditionals, we get:

let rec deleteNode tree' value =
  match tree' with
  | Empty -> Empty
  | Node (left, nodeValue, right) when value < nodeValue ->
        Node((deleteNode left value), nodeValue, right)
  | Node (left, nodeValue, right) when value > nodeValue ->
        Node(left, nodeValue, (deleteNode right value))
  | Node (Empty, nodeValue, Empty) ->
        Empty
  | Node (Empty, nodeValue, right) ->
        right
  | Node (left, nodeValue, Empty) ->
        left
  | Node (left, nodeValue, right) ->
        let newValue = minValue right in
        Node(left, newValue, (deleteNode right newValue))

 Remove redundant cases

That's more obvious with pattern matching, but the Node (Empty, nodeValue, right) cases also applies when right = Empty, so we can delete the more specific Node (Empty, nodeValue, Empty) case.

That's about it! Have a nice journey exploring OCaml.


Counting five specific words in a file I'm trying to improve my code and i want to know if this is the best way to write this Switch or if  there are other methods.

for(String word : words) {
        switch(word.toLowerCase()) {
        case "a":
            a++;
            break;
        case "the":
            the++;
            break;
        case "bird":
            bird++;
            break;
        case "animal":
            animal++;
            break;
        case "is":
            is++;
            break;
        }
    }

Here is the complete code if you need it.

public static void main(String[] args) throws IOException {
ArrayList<String> words = new ArrayList<>();
int a = 0, the = 0, bird = 0, animal = 0, is = 0;

    for(String line : Files.readAllLines(Paths.get("C:\\Users\\n\\Desktop\\Text.txt"))) {
        line.split("\\s+");
        line.replaceAll("[!?.,]", "");
        for(String word : line.split("\\s+")) {
            words.add(word);
        }
    }

    for(String word : words) {
        switch(word.toLowerCase()) {
        case "a":
            a++;
            break;
        case "the":
            the++;
            break;
        case "bird":
            bird++;
            break;
        case "animal":
            animal++;
            break;
        case "is":
            is++;
            break;
        }
    }
System.out.println(a + " " + the + " " + bird + " " + animal + " " + is);
}

You can use a Map :

Map<String,Integer> freq = new HashMap<String,Integer>();
for(String word : words) {
    String w = word.toLowerCase();
    if (freq.containsKey(w)) {
        freq.put(w,freq.get(w)+1);
    } else {
        freq.put(w,1);
    }
}


Convert looping statement to linq mode I have a model object class like this

public class EventInterestsResponse
{
  public string id { get; set; }
  public int sortOrder { get; set; }
  public string name { get; set; }
  public string categoryName { get; set; }
  public string categoryId { get; set; }
}

And I am using it to hold some data like this

public List<EventInterestsResponse> GetEventInterests()
{

  _data = _rh.ExecuteGetRequest();
  var yourObject = _data != null ? (List<EventInterestsResponse>)jsonSerializer.Deserialize<List<EventInterestsResponse>>(_data) : null;
  return yourObject;
}

Later I want to preform some operations on this.
For example, I want to check if any of the resulting objects contain a specific categoryId and if yes, I want to print it. I have written this working code:

foreach (var interest  in InterstList)
{
  if (interest.categoryId == "11")
  {

    Branche:@interest.name
  }
  if (interest.categoryId == "22")
  {

    Udviklingsstadie:@interest.name
  }
}

Now I wonder: Is this the most elegant way to do this? Maybe I don't even want to use a foreach loop. Can this be achieved by LINQ and using lambda expressions?

Can any one tell me how I can modify this code so that it uses LINQ and lambda expressions?

I'm not sure if this is any better and it might depend on how many if statements or different categories you have whether it's worth it.  But an alternative could be something like:

var categoryLabelValues = new Dictionary<string, string>()
    {
        {"11", "Branche"},
        {"22", "Udviklingsstadie"}
    };

foreach(var interest in InterstList
                            .Where(p => categoryLabelValues.ContainsKey(p.categoryId)))
{
   <strong>@categoryLabelValues[interest.categoryId]:@interest.name</strong>
}


Showing information about states on a map when clicked I'm using JQVMap, and I have my code to where depending on what state you click, it'll reveal info about that state within a single div below the map. However, I feel there's a simplified, more efficient way to set up this code so there's not a lot of repeat, especially once I start adding more states. Is there?

switch(code){
    case"tx":
        $('#info-children').children(':not(#info-tx)').hide("slow");
        $('#info-children').children('#info-tx').show("slow");
        break;
    case"il":
        $('#info-children').children(':not(#info-il)').hide("slow");
        $('#info-children').children('#info-il').show("slow");
        break;
    case"fl":
        $('#info-children').children(':not(#info-fl)').hide("slow");
        $('#info-children').children('#info-fl').show("slow");
        break;
    case"ga":
        $('#info-children').children(':not(#info-ga)').hide("slow");
        $('#info-children').children('#info-ga').show("slow");
        break;
    case"pa":
        $('#info-children').children(':not(#info-pa)').hide("slow");
        $('#info-children').children('#info-pa').show("slow");
        break;
    default:
        $('#state-name').html(region);
        $('#info-children').children(':not(#info-uhoh)').hide("slow");
        $('#info-children').children('#info-uhoh').show("slow");
}

You could have a single if statement covering all your non-default cases, since all your $('info#children')... sequences are the same, except for the state clicked.

So, you could just say

$('#info-children').children(':not(#info-' + code + ')').hide('slow');

and

$('#info-children').children('#info-' + code + ')').show('slow');

So, you could just have one huge logical statement, checking if the code/state is tx, il, fl, ga, or pa. If that statement is true, run the above code; if not, run the default code.


Hide or show if radio button is checked I was recently working on a project, something jQuery-related for WP-Admin area.

I enable post-formats and create metaboxes for these post-formats, so at the end I tried to hide these metaboxes until the user checks the radio button. I just want to know if there is a better way I can write this code.

// hide the metabox at start
$('#gallery-box').hide();

// fetch the id name of checked post-format
var idName = $('input.post-format:checked').attr('id');

// display the metabox if the fetched value matched
if ( idName === 'post-format-gallery' ) {
    $('#gallery-box').show();
}

// show or hide
$('.post-format').click(function(){
    idName = $(this).attr('id');
    if ( $(this).is(':checked') ) {
        if ( idName === 'post-format-gallery' ) {
            $('#gallery-box').show();
        } else {
            $('#gallery-box').hide();
        }
    }
});

If you know exactly which radio button you are interested in, then you should prefer to select it by ID, for performance.  Presumably, your radio buttons will be part of a group with the same name, so it would be more conventional to select the elements by the name instead of by a class.

If you have to conditionally call .show() and .hide(), you can use .toggle().

Avoid hard-coding hide() as the initial state.  It would be better to have the "Hide" radio button marked as checked in the HTML, then let the JavaScript follow suit.  To bind an event handler and execute it right away, you could use .trigger(), but note that triggering the 'click' event also toggles the radio state, so you'll want to make a separate 'init-post-format' event type.

$(function() {
    $('input[name=post-format]').on('click init-post-format', function() {
        $('#gallery-box').toggle($('#post-format-gallery').prop('checked'));
    }).trigger('init-post-format');
});

<input type="radio" name="post-format" id="post-format-gallery">Show gallery
<input type="radio" name="post-format" checked>Hide gallery

The Gallery


Merging and summing multi-dimensional arrays I've found myself today really struggling with this subject and I'm pretty sure that there must be a better way to do this.

First of all my arrays have the same layout, I need to merge them and sum every value by domain.

Let me give you an example:

$array[0]['X1']['Y1'] = 1;
$array[0]['X1']['Y2'] = 2;
$array[0]['INFO']['DOMAIN'] = 'example1.com';

$array[1]['X1']['Y1'] = 1;
$array[1]['X1']['Y2'] = 2;
$array[1]['INFO']['DOMAIN'] = 'example1.com';

$array[2]['X1']['Y1'] = 2;
$array[2]['X1']['Y2'] = 5;
$array[2]['INFO']['DOMAIN'] = 'example2.com';

$array[3]['X1']['Y1'] = 2;
$array[3]['X1']['Y2'] = 5;
$array[3]['INFO']['DOMAIN'] = 'example2.com';

I need to produce the following new array:

$mergedArray[0]['X1']['Y1'] = 2;
$mergedArray[0]['X1']['Y2'] = 4;
$mergedArray[0]['INFO']['DOMAIN'] = 'example1.com';

$mergedArray[1]['X1']['Y1'] = 4;
$mergedArray[1]['X1']['Y2'] = 10;
$mergedArray[1]['INFO']['DOMAIN'] = 'example2.com';

I'm using the following code to achieve this (forgive me for the bad namings).

foreach($array as $subKey => $subValue) {
    foreach($subValue as $key => $value) {
        foreach($value as $key2 => $value2) {
            if($key2=='DOMAIN' && !isset($merged[$value2])) {
                $merged[$value2] = $subValue;
            } else if ($key2=='DOMAIN' && isset($merged[$value2])) {
                foreach($subValue as $key3=>$value3) {
                    foreach($value3 as $key4=>$value4) {
                        if($key4!='DOMAIN')
                            $merged[$value2][$key3][$key4] += $value4;
                    }
                }
            }
        }
    }
}

How could I improve this piece of code?

Presuming that the format will be consistent, you could remove one foreach loop and extract the domain to use as the key of the merged array, and also only either set the sub array (with keys X1, Y1 and Y2) or add to the sub array items.

foreach($array as $subArray) {
    if (isset($subArray['INFO']) && isset($subArray['INFO']['DOMAIN'])) {
        $domainKey = $subArray['INFO']['DOMAIN'];
        if (!isset($merged[$domainKey])) {
            $merged[$domainKey] = $subArray;
        }
        else { // could add conditionals to ensure X1 is set on $subArray
            foreach($subArray['X1'] as $key => $value) {
                $merged[$domainKey]['X1'][$key] += $value;
            }
        }
    }
}

See it in action in this playground example.

A functional approach could also be employed by using array_reduce():

$merged = array_reduce($array, function($cumulative, $subArray) {
    if (isset($subArray['INFO']) && isset($subArray['INFO']['DOMAIN'])) {
        $domainKey = $subArray['INFO']['DOMAIN'];
        if (!isset($cumulative[$domainKey])) {
            $cumulative[$domainKey] = $subArray;
        }
        else { // could add conditionals to ensure X1 is set on $subArray
            foreach($subArray['X1'] as $key => $value) {
                $cumulative[$domainKey]['X1'][$key] += $value;
            }
        }
    }
    return $cumulative;
}, []);

See it in action in this playground example


Renaming Files and/or Directory I'm quite new to Python and would love to gather feedback on my code. I've written a piece a script that allows me to search all file or directory names within a folder matching a particular pattern. The caller can specify if the function should be recursive or not.

It's only a basic script I would love to know how it could be improved!

import sys
import os
import string

def rename(source, pattern, replacement, dirs = False, recurse = False):
    """
    Rename a file or directory

    source = source directory
    pattern = old string
    replacement = new string
    dirs = apply to directorys
    recurse = move recursivley
    """
    dir = os.path.abspath(source)

    for item in os.listdir(dir):
            # Get the full path
            item = os.path.join(source, item)
            if os.path.isfile(item) and pattern in item:
                 os.rename(item, string.replace(item, pattern, replacement))
            elif os.path.isdir(item):
                if recurse:
                    # Move to the next level, before renaming
                    rename_items(item, pattern, replacement, dirs, recurse)
                if pattern in item and dirs:
                    os.rename(item, string.replace(item, pattern, replacement))

if __name__ == '__main__':

    source = sys.argv[1]
    pattern = sys.argv[2]
    replacement = sys.argv[3]

    rename(source, pattern, replacement, True, True)

What if the script renames file "a.zip" to "b.zip", and both files "a.zip" and "b.zip" exist in the same directory?


Join 5 optional strings with a joiner character I need to append some query parameters to my API URL. The consumer of my API would pass me this optional structure called as APIParameters, which contain 5 optionals, one array of strings and rest strings

Lets assume the following:

let baseURL = "baseURL"
let path = "path"

This is the final URL structure

//assuming since and offset is nil, this would be the URL
result = "baseURL" + "path" + "?"+ "with=some1,some2,some3&limit=100&width=0"

To solve this, I made a struct, and added a method to return me the string that I need to append to my URL.

struct APIParameters {
    var with: [String]?
    var since: NSDate?
    var width: Int?
    var offset: Int?
    var limit: Int?

    func stringToAppendToURL() -> String{
    //started with this approach

        var stringToAppend = ""

        if with != nil {

            var withParamaters = ",".join(with!)
            println("withParamaters = \(withParamaters)")

            stringToAppend += "with=\(withParamaters)"

        }

        if limit != nil {
            println("limit = \(limit)")

        }
    //realized this would be too long so tried using switch

        switch (with, limit, width, offset, since){
        case (nil, nil, nil, nil, nil):
            return ""
        case (.Some(let withParameters), nil, nil, nil, nil):
            return "with=" + ",".join(withParameters)
        case (nil, .Some(let limitParams), nil, nil, nil):
            return "limit=\(limitParams)"
        case (nil, nil, .Some(let widthParams), nil, nil):
            return "width=\(widthParams)"
        case (nil, nil, nil, .Some(let offsetParams), nil):
            return "offset=\(offsetParams)"
        case (nil, nil, nil, nil, .Some(let sinceParams)):
            return "since=\(Int(sinceParams.timeIntervalSince1970))"
        case (.Some(let withParams), .Some(let limitParams), nil, nil, nil):
        return "with=" + ",".join(withParams) + "&" + "limit=\(limitParams)"
    //realized that number of conditions would become too many so decided to ask for help

        default:
            return ""

        }

    }
}

Example:

let apiParams1 = APIParameters(with: ["option", "full"], since: nil, width: nil, offset: nil, limit: 10)
let apiParams2 = APIParameters(with: ["option", "full"], since: nil, width: nil, offset: nil, limit: nil)

println("\(apiParams1.stringToAppendToURL())")
println("\(apiParams2.stringToAppendToURL())")

  Output:

"with=option,full&limit=10"
"with=option,full"

Is there a more elegant way to do this?

I do it a bit more elegantly I believe. First, this extension function is pretty useful.

extension Array {
    static func filterNils(array: [T?]) -> [T] {
        return array.filter { $0 != nil }.map { $0! }
    }
}

An example of my request models.

class PostRequest: BaseRequest {
    var startIndex: Int?
    var fetchCount: Int?
    var programID: String?
    var userID: String?
    let postType: FeedPostType

    var userPostFilter: String? {
        switch postType {
        case .User:
            return "all"
        default:
            return nil
        }
    }

    init(postType: FeedPostType) {
        self.postType = postType
    }

    override var path: String {
        let basePath = "/posts"
        var arguments: [String] = Array.filterNils([basePath,postType.rawValue,programID,userID,userPostFilter,startIndex?.toString(),fetchCount?.toString()])
        return "/".join(arguments)
    }
}

toString is also an extension on Int

extension Int {
    func toString() -> String {
        return String(self)
    }
}


Check if brackets are balanced class EmptyStackError(Exception):
    def __init__(self):
        super().__init__('Stack is empty. Invalid operation')

class FullStackError(Exception):
    def __init__(self):
        super().__init__('Stack is full. Cannot push')

class Stack:
    """ Stack with a specified size """
    def __init__(self, size):
        self.head = None
        self.size = size
        self.current_size = 0

    def push(self, data):
        """ Push data to the top of the stack """
        if self.current_size == self.size:
            raise FullStackError
        node = Node(data)
        if not self.head:
            self.head = node
        else:
            node.next_node = self.head
            self.head = node
        self.current_size += 1

    def pop(self):
        """ Remove data from the top of the stack and return it """
        if not self.head:
            raise EmptyStackError
        data = self.head.data
        self.head = self.head.next_node
        self.current_size -= 1
        return data

    def peek(self):
        """ Take a look at the current item at the top of stack, but do not return it"""
        if not self.head:
            raise EmptyStackError
        data = self.head.data
        return data

    def get_size(self):
        """ Return the current size of the stack """
        return self.current_size

opening_brackets = '([{'
closing_brackets = ')]}'

def check_balance(input_string: str) -> bool:
    answer = True
    stack = Stack(100)
    for char in input_string:
        if char in opening_brackets:
            stack.push(char)
        else:
            try:
                top_item = stack.peek()
            except EmptyStackError as e:
                answer = False # if it's with closing brackets, it's not balanced
                break
            if tuple([top_item, char]) not in zip(opening_brackets, closing_brackets):
                answer = False
                break
            else:
                stack.pop()
    if stack.get_size() != 0:  # there shouldn't be any items remaining in the stack if it's balanced
        answer = False
    return answer

""" Testing """
strings = ['', '[({})]', '[', '}']
[True, True, False, False] == list(map(check_balance, strings))

I have a stack implementation (along with the EmptyStackError).
I didn't want to add to make easier visually, but it might be relevant.
I'm finding the code lacking in grace and elegance.
Any way to improve on this code?
Any bug I cannot see?

Note: I've added the try clause (which I tend to find not that easy on the eyes) to fix a bug when starting with a closing bracket, I get an EmptyStackError which is internal to the stack implementation.

Note: I'm using jupyter lab if that's relevant in any way :)

You should init your Stack with the length of your string. This way, you'd be sure never to hit the FullStackError.

Also, it seems to be on purpose but you don't support other characters in your string? I'd expect "(asdasd)" to return true.

This line : tuple([top_item, char]) not in zip(opening_brackets, closing_brackets): is maybe a little hard to understand at first glance. I'd suggest creating a variable for zip(opening_brackets, closing_brackets). It wouldn't change much but it'd give you an opportunity to have a more meaningful name.

From experience, I'd say that code that parses strings is never elegant and even though it's a generally accepted fact that try/catch(except) are ugly, they are most necessary and I think you should keep it this way.

Two slight nitpicks :

I'd rename answer to isBalanced
You should put your comments on separated lines for readability.


Sums of perfect powers import java.util.ArrayList;

public class SumsOfPerfectPowers {

    ArrayList<Long> numList = new ArrayList<Long>(5000001);
    // status of whether a number is power number
    boolean[] result = new boolean[5000001];

    public SumsOfPerfectPowers() {
        numList.add((long) 0);
        numList.add((long) 1);
        for (int i = 2; i <= 2237; i++) {
            int j = 2;
            double value;
            while ((value = Math.pow(i, j)) <= 5000000) {
                numList.add((long) value);
                j++;
            }
        }

        int len = numList.size();
//      System.out.println(len);
        int value;
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                value = (int) (numList.get(i) + numList.get(j));
                if (value <= 5000001) {
                    result[value] = true;
                }
            }
        }

    }

    static {
    }

    public int howMany(int a, int b) {
        int sum = 0;
        for(int i=a;i<=b;i++) {
            if(result[i]) {
                sum ++;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        SumsOfPerfectPowers test = new SumsOfPerfectPowers();

        System.out.println(test.howMany(0, 1));
        System.out.println(test.howMany(5, 6));
        System.out.println(test.howMany(25, 30));
        System.out.println(test.howMany(103, 103));
        System.out.println(test.howMany(1, 100000));

    }

}

Is this piece of code well-coded?
Are there any bad habits here?
What can be improved?

(long) 0 scructures should be written as 0L.
Access modifiers of numList and result should be private:

private ArrayList<Long> numList = new ArrayList<Long>(5000001);
// status of whether a number is power number
private boolean[] result = new boolean[5000001];

ArrayList<...> reference types should be simply List<...>. See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces

private List<Long> numList = new ArrayList<Long>(5000001);

5000000 is a magic number. Using named constants instead of numbers would make the code more readable and less fragile. If you have to modify it's value it's easy to forget to do it everywhere. 2237 is also a magic number and a computed value. I'd create a MAX constant:

private static final int MAX = 5000000;

and use it everywhere, for example:

private boolean[] result = new boolean[MAX + 1];

then change 2237 to the following:

final int maxSquare = (int) Math.ceil(Math.sqrt(MAX));
for (int i = 2; i <= maxSquare; i++) { ... }

numList only used in the constructor, so it could be a local variable there instead of a field. Try to minimize the scope of variables. See Effective Java, Second Edition, Item 45: Minimize the scope of local variables.
Actually, I'd rename numList to perfectPowers since it stores perfect powers. I'd make the code more readable and easier to maintain.
You set the initial capacity of the list to 5000000 while it contains only about 2500 elements. It's a huge memory wasting. I'd use the default constructor of the ArrayList which use less memory.

final List<Long> perfectPowers = new ArrayList<Long>();

Math.pow uses floating point numbers which are not always precise. For small numbers it's correct, but for big numbers it not:

final long a = 97761243;
final long aa = a * a;
System.out.println("long            " + aa);
System.out.println("Math.pow        " + ((long) Math.pow(a, 2)));
System.out.println("BigInteger.pow: " + BigInteger.valueOf(a).pow(2).longValue());

It prints:

long            9557260632905049
Math.pow        9557260632905048
BigInteger.pow: 9557260632905049

So, I'd change the while loop to the following:

long value;
while ((value = BigInteger.valueOf(i).pow(j).longValue()) <= MAX) {
    perfectPowers.add(value);
    j++;
}

Some additional changes on the same loop would result the following:

while (true) {
    final long value = BigInteger.valueOf(i).pow(j).longValue();
    if (value > MAX) {
        break;
    }
    perfectPowers.add(value);
    j++;
}

It does the same but I think it's easier to read.
In the first for loop I'd rename i to base and j to exponent, and the parameters of the howMany method to lowerBound and upperBound.
The empty static block is unnecessary:

static {
}