Applying a currency symbol based on a tested string value My conditional code here seems repetitive and long. Is there a better approach? I want to test for a string value in a NSDictionary object and then depending upon the value prefix a UILabel with $, £, ¥ currency symbols.

I've just shown 2 examples below.  I have more currencies and the code is very long.

if ([[item objectForKey:@"currency"] isEqualToString:@"EUR"]) {

    NSString *priceConvertToStr = [NSString stringWithFormat:@"€%@", [[item objectForKey:@"price"]stringValue]];

    NSString *priceStringFix = [priceConvertToStr
                                stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

    priceLabelText.text = priceStringFix;
    [imgView2 addSubview:priceLabelText];

}

if ([[item objectForKey:@"currency"] isEqualToString:@"GBP"]) {
    NSString *priceConvertToStr = [NSString stringWithFormat:@"€%@", [[item objectForKey:@"price"]stringValue]];

    NSString *priceStringFix = [priceConvertToStr
                                stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

    priceLabelText.text = priceStringFix;
    [imgView2 addSubview:priceLabelText];

}
if ([[item objectForKey:@"currency"] isEqualToString:@"USD"]) {
    NSString *priceConvertToStr = [NSString stringWithFormat:@"$%@", [[item objectForKey:@"price"]stringValue]];

    NSString *priceStringFix = [priceConvertToStr
                                stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

    priceLabelText.text = priceStringFix;
    [imgView2 addSubview:priceLabelText];

}

I'd create an NSDictionary holding those prefixes and wrap that whole thing into its own method, like so:

-(NSString *) prefixForCurrency:(NSString *)currency{
    NSDictionary *currencyPrefixes = @{@"EUR": @"€", @"USD" : @"$", @"GBP" : @"£", @"NOK" : @"kr." };
    NSString *returnString = [currencyPrefixes objectForKey:currency];

    return returnString;
}

Then, instead of your current mass of if-statements you'd have something like the following:

NSString *currency = [item objectForKey:@"currency"];
NSString *currencyPrefix = [self prefixForCurrency: currency];

NSString *price = [item objectForKey:@"price"];
NSString *priceString = [NSString stringWithFormat:@"%@ %@", currencyPrefix, price];

In case you were wondering: the main reason I wrap the prefixDictionary in its own method is in case you'd for instance prefer to fetch this list from a file later on. Then you can just alter the innards of that one method...


"Rotating the string" optimization Below is the code for the problem at Codechef. I have made use of the String method .equals in my solution which is working fine for all the test inputs. However, I am getting a Time Limit Exceeded when I submit to the Judge. I need your ideas on optimizing the code.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{

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

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

        int not=Integer.parseInt(in.readLine());

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

            String s=in.readLine();
            int count=0;

            String inp[]=in.readLine().trim().split(" ");

            int m=Integer.parseInt(inp[0]);
            int p=Integer.parseInt(inp[1]);

            //System.out.println(m+" "+p);

            String temp=s;

            for(int b=0;b<(Integer.MAX_VALUE/2);b++)
            {

                //System.out.println(temp);
                String s1=rotate(m,temp);
                //System.out.println(s1);
                count++;
                if(s1.equals(s))
                    break;

                String  s2=rotate(p,s1);
                //System.out.println(s2);
                count++;
                if(s2.equals(s))
                    break;

                temp=s2;

            }

            if(count>0)
                System.out.println(count);
            else
                System.out.println(-1);

        }

    }   private static String rotate(int m, String s) {

        char sa[]=s.toCharArray();

        int l=sa.length;

        StringBuilder sb=new StringBuilder();

        for(int j=m-1;j>=0;j--)
        {

            sb.append(sa[l-1-j]);

        }

        for(int k=0;k<(l-m);k++)
            sb.append(sa[k]);

        return sb.toString();
    }

}

I would use an entirely different strategy to determine the number of times needed to rotate the string: addition.

Since rotating a string by a and then b yields the same result as rotating it a+b, we do not need to keep track of the string at all, only the equivalent rotation. However, we do need to be able to detect if the string is actually just concantenations of some substring; in that case we can treat it as if its length were the length of the repeated substring.

Here are the steps I would use for each string:

Match the string against the regular expression (.+?)\1+. This uses a backreference to find the iterated portions of the string. (FYI, this regex may need some adjustment.)

static final Pattern iteratedSubstring = Pattern.compile("(.+?)\\1+");
static int reducedLength(String string){
    Matcher m = iteratedSubstring.matcher();
    if(m.matches(input)) return m.group(1).length()

    return string.length()
}

Repeatedly accumulate the two rotations until the rotation is congruent to zero modulo the length.

static int identityRotationCount(final int length, int ... rotations){
    rotations = Arrays.stream(rotations).parallel().flatMap(i->i%length).toArray();

    /* alternately, if you can't use java 8 you can do this, although it's slower:
    for(int idx = 0; idx < rotations.length; idx++)
        rotations[idx] %= length;
    */

    int count = 0, rotation = 0;

    while(true)
        for(int rot: rotations){
            count++;
            rotation += rot;
            if(rotation == length) return count;
            if(rotation > length) rotation -= length;
        }
}

There may be even faster methods to compute this, including variants on algorithms for finding a GCD or other discrete algebra type things.
At least at first, you should be using a Scanner to process the input, because inevitable parsing logic bugs from doing the parsing yourself will make debugging anything else extremely difficult.

try(Scanner in = new Scanner(System.in), PrintWriter out = System.out){
    // ...
}

Finish the program:

in.nextInt(); //discard input entry count, don't need it.

while(true){
    if(!in.hasNextLine()) break;
    String string = in.nextLine();

    if(!in.hasNextInt()) break;
    int monkey = in.nextInt();

    if(!in.hasNextInt()) break;
    int po = in.nextInt();

    out.println(identityRotationCount(reducedLength(string), monkey, po));
}

If you do not want to use a Scanner, try something like this:

try(BufferedReader in = new BufferedReader(System.in), PrintWriter out = System.out){
    int n = Integer.parseInt(in.readLine());

    for(int idx = 0; idx < n; idx++){
        String string = in.readLine();

        String [] rots = in.readLine().split("\\s");

        int monkey = Integer.parseInt(rots[0]),
                  po = Integer.parseInt(rots[1]);

        out.println(identityRotationCount(reducedLength(string), monkey, po));
    }
}


Discern and perform an operation on a list I have some code that's meant to discern certain words in a list and then based on which word is in the list, do a mathematical operation on the numbers also found in the list. Here's my code:

  for (op in operations) {
    if (arrayses.letteros.indexOf(op) !== -1) {
      found = true;
      break;
    }
  }
  if (found) {
    var result = arrayses.numeros[0];
    while (i < arrayses.numeros.length) {
      if (i === 0) {
        result = arrayses.numeros[0];
      } else {
        result = operations[op](result, arrayses.numeros[i]);
      }
      i += 1;
    }

The part of the code I'm having trouble with is the very first line up there. My program has to pass JSLint based on the assumption I'm using a browser and tolerating multiple variables and whitespace mess. JSLint says the for in my for...in statement up there is unexpected; are there any alternatives to using that statement? It's used to look for the operations listed above my function in a global variable.

Here's where operations is defined, it's a global variable:

var operations = {
  add: function(a, b) {
  "use strict";
    return Number(a) + Number(b);
  },
  subtract: function(a, b) {
  "use strict";
    return a - b;
  },
  multiply: function(a, b) {
  "use strict";
    return a * b;
  },
  divide: function(a, b) {
  "use strict";
    return a / b;

  }
};

You could use Object.keys and Array#some to determine if any key in an object fits your criteria:

found = Object.keys(operations).some((op) => arrayses.letteros.indexOf(op) !== -1);

In general, you can use Object.keys and array iteration methods (forEach, map, reduce, some, every, etc.) to replace for..in loops.


Identical linq for different index I am parsing excel data and need to create object based on StartDate-EndDate difference.

Is there a better way to have only one linq perform this task and return two different result sets ? Only difference in both linq is just the variable on which its applied.

private Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] ParseData(ExcelFile file, Dictionary<string, string>[] ConfigMap)
{

    // Extract the information from the excel file
    var excelData = file.GetWorksheetData(sheet: 0, rowStart: 2);

    var monthlyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days > 1);
    var dailyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days == 1);

    var monthlyData = monthlyRows.Where(r => r[KeyCol] != null && ConfigMap[0].ContainsKey((string)r[KeyCol]))
                                   .GroupBy(r => (string)r[KeyCol])
                                   .ToDictionary(g => g.Key,
                                                 g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))
                                                       .ToDictionary(c => c.Key,
                                                                     c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))
                                                                           .ToList()));

    var dailyData = dailyRows.Where(r => r[KeyCol] != null && ConfigMap[1].ContainsKey((string)r[KeyCol]))
                                  .GroupBy(r => (string)r[KeyCol])
                                  .ToDictionary(g => g.Key,
                                                g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))
                                                      .ToDictionary(c => c.Key,
                                                                    c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))
                                                                          .ToList()));

    return new Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] { monthlyData, dailyData };
}

Assuming monthlyRows and dailyRows are both IEnumerable<ExcelDataRow>, a first step could be to extract a method (assuming return type here, I only skimmed through your code):

private Dictionary<DateTime, List<DataPoint>> GetDataDictionary(IEnumerable<ExcelDataRow> data)
{
    var result = data.Where(r => r[KeyCol] != null && ConfigMap[0].ContainsKey((string)r[KeyCol]))
                                   .GroupBy(r => (string)r[KeyCol])
                                   .ToDictionary(g => g.Key,
                                                 g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))
                                                       .ToDictionary(c => c.Key,
                                                                     c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))
                                                                           .ToList()));
    return result;
}

Your ParseData method's body could then look like this:

    // Extract the information from the excel file
    var excelData = file.GetWorksheetData(sheet: 0, rowStart: 2);

    var monthlyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days > 1);
    var monthlyData = GetDataDictionary(monthlyRows);

    var dailyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days == 1);
    var dailyData = GetDataDictionary(dailyRows);

    return new Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] { monthlyData, dailyData };

That solves one issue.

Next step would be to break down the LINQ query and make the code self-explanatory as far as why you need to have a dictionary of dictionaries of lists.. and then make that simpler.


Profile with static and input modes (View and Update) I'm a solo developer and a friend told me that my code is not very readable. I always write code trying to keep it DRY while not taking longer than it would take doing it in an "easier" way.
Here is the skeleton for My Profile feature which will initially have read-only values. When the user wants to update it, it turns into an input when clicking on edit.
Is there anything wrong with this way of going about it?
class MyProfileEdit extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            data: {},
            onEdit: ""
        }
        this.displayKey = {
            "first_name": "First name",
            "last_name": "Last name",
            "zipCode": "Zip"
        }
    }
    handleOnChange = key => e => e.persist() || this.setState(prevState => {
        prevState.data[key] = e.target.value;
        return prevState;
    })
    getInputValue = key => this.state.data[key] || this.props.currentUser[key]
    getKeyDisplay = key => this.displayKey[key] || key[0].toUpperCase() + key.slice(1)
    getStatic = key => (

            {this.getKeyDisplay(key)}: {this.getInputValue(key)}  &nbsp;&nbsp;&nbsp;

 this.setState({onEdit: key})}>Edit

    )
    getInput = key => (

            {this.getKeyDisplay(key)}:
            <input value={this.getInputValue(key)} onChange={this.handleOnChange(key)} />

 this.setState({ onEdit: "" })}>Done

    )
    getStaticOrInput = key => this.state.onEdit != key ? this.getStatic(key) : this.getInput(key);
    render(){
        return (
            <React.Fragment>
                My profile:

                { this.getStaticOrInput("first_name") }
                { this.getStaticOrInput("last_name") }

                    Notification option:
                    <select
                        value={this.getInputValue("notification_option")}
                        onChange={this.handleOnChange("notification_option")}
                    >
                        <option value="SMS">SMS</option>
                        <option value="EMAIL">Email</option>
                    </select>

                { this.getStaticOrInput("city") }
                { this.getStaticOrInput("address") }
                { this.getStaticOrInput("zipCode") }
            </React.Fragment>
        )
    }
}

Other than your handleOnChange handler is mutating state, this code seems understandable and readable enough to me, only minor comments about code style.
React-ness
React's synthetic events' persist function is a void return, so I don't think the logical OR between it and the state update necessary.
Mutating-state handler with odd event persisting.
handleOnChange = key => e => e.persist() || this.setState(prevState => {
  prevState.data[key] = e.target.value; // <-- this mutates existing state
  return prevState; // <-- saving previous state object back in state
})

Non-mutating-state handler. React class-based component state updates are merged in, but nested state needs to have their previous state merged manually. Also, instead of persisting the event for use in the "asynchronous" setState, it is more common to grab the event value and let react do what it needs with the event object (i.e. return back to pool).
handleOnChange = key => e => {
  const { value } = e.target;
  this.setState(prevState => ({
    data: {
      ...prevState.data,
      [key]: value,
    },
  }));
}

Readability
All other comments I'd have on the code are more about the readability, i.e. appropriate usage of whitespace, 2-space vs 4-space tabs, etc.. but these are largely dev team driven and tend to be subject to opinion.
Common practices though are

Single line space between code blocks (functions and any other logical "chunk" of code
Using curly brackets for functions that are more than simply an implicit return, i.e. they have more than a single expression
Using appropriate line breaks when lines of code get too long, usually around 80 chars

Maintainability/Reusability
The one remaining comment I'd have would be to try and abstract the this.getStaticOrInput logic and utilities into a separate react component, something like EditableInput that handles its toggling state internally.
<EditableInput name="first_name" value={...} etc.. />
<EditableInput name="last_name" value={...} etc.. />
...


Generating a sinusoid sound signal in Java Is there any legroom left for optimization (without switching to C)?

static byte[] generateSound(double frequency, int sampleRate, int samples) {
    byte output[] = new byte[2 * samples];

    int idx = 0;

    double _tone = 2 * Math.PI / (sampleRate / frequency);

    for (int i = 0; i < samples; ++i) {
        double dVal = Math.sin(_tone * i);

        final short val = (short) ((dVal * 32767));

        output[idx++] = (byte) (val & 0x00ff);
        output[idx++] = (byte) ((val & 0xff00) >>> 8);
    }

    return output;
}

There's probably good room for performance gain regarding the Math.sin call itself. You could easily create a lookup-table - there's no faster way than just taking the values straight from an array. (The link's benchmark measures a factor ~6 speed difference.)

It may be problematic because it may cause audible distortions, but that would depend on how much memory you're willing to invest in the lookup-table. Also, you could invest a few more cycles by obtaining both array entries addressed by (_tone*i) and then adding them up, both multiplied by 0.x and respectively (1-0.x), effectively fading over between values.


Resolving the path to a Bash script I wrote a function to resolve the full path to the current Bash script, and I'm wondering if it's SOLID:

#!/usr/bin/env bash

scriptpath()
{
    result=${BASH_SOURCE[0]}

    # unfortunately readlink -f isn't available on Macs,
    # so resolve the symlinks manually
    while [ -h "$result" ]
    do
        symdir=$(dirname "$result")
        cd -P "$symdir"
        result=$(readlink "$result")
    done

    echo "$result"
}

echo "The path to the current script is: $(scriptpath)"

Is there anything I may have looked over in the function? I'm not sure because my answer seems quite different than the solutions listed here or here, and I'm pretty fuzzy on symlinks.

I basically want to know if my function (scriptpath) is any different than this on a Linux system:

readlink -f "${BASH_SOURCE[0]}" | xargs -0 dirname

Let's make this testable

With a small twist, the function can become testable.
Instead of finding the real path of the current script,
it would be better to generalize it to find the real path of any path:

real_path()
{
    result=$1

    # ...
}

Fails to follow relative symlinks correctly

Now that the script is testable, here's a test it will not pass:

mkdir -p /tmp/a
touch /tmp/a/b
(cd /tmp/a; test -L /tmp/a/c || ln -s ../a/b c)

echo $(real_path /tmp/a/c)

The output will be ../a/b instead of the expected /tmp/a/b.
Basically if there are relative links in the chain of links recursively followed, the script will break.

Alternative implementation

This is what I use in production, and I haven't seen a corner case yet where it breaks:

real_path() {
  target=$1

  (
  while true; do
    cd "$(dirname "$target")"
    target=$(basename "$target")
    test -L "$target" || break
    target=$(readlink "$target")
  done

  echo "$(pwd -P)/$target"
  )
}

Notice that the portion where the function changes the working directory is wrapped within a (...) sub-shell.
This is probably overkill,
but I think it's good to eliminate side effects as a general principle.


Binary to Decimal conversion program I am a beginner in Python and I have written a program to convert binary numbers to decimal. It works, but are there any ways to improve the code and make it better?
def binary_to_decimal_converter(binary_value):
    print(f"Binary: {binary_value}")
    decimal_value = 0
    # Treating binary input as a string
    # power is power of number 2
    # power must be less than string length because computer starts counting from 0th index
    power = len(str(binary_value)) - 1
    loop_var = 0
    while loop_var < len(str(binary_value)):
        if str(binary_value)[loop_var] == str(1):
            decimal_value += 2 ** power
        power -= 1
        loop_var += 1
    return print(f"Decimal: {decimal_value}")

# Calling the function
binary_to_decimal_converter(1111101100)

Output:
Binary: 1111101100
Decimal: 1004

```

Do conversions once
As written, with the example input, str(binary_value) will be called 22 times, with the same input value, and returning the same value each time.  This is very inefficient; it is wasted work.  It would be better to call it once, and store the result, and use this stored value:
def binary_to_decimal_converter(binary_value):
    binary_value = str(binary_value)
    # ... rest of function, without any more str(binary_value) calls

But ...
Representing Binary Numbers
As pointed out by harold in the comments, the literal 1111101100 is an integer value slightly larger than one billion in Python.  You should use a string to represent a binary number to be converted.
# Calling the function
binary_to_decimal_converter("1111101100")

Since we're passing a string to the function, all of the calls to str(binary_value) are now completely unnecessary.
String Constants
        if str(binary_value)[loop_var] == str(1):

Again, using the example value, the expression str(1) will be evaluated ten times; once for each digit of the input.  This will convert the numerical value one into the string "1", which will be discarded immediately after use, only to be recreated on the next iteration.  Why not just use the literal "1"?  Not only is it more efficient; it is 3 characters shorter.
Loop like a Native
See "Loop like a Native" by Ned Batchelder on YouTube for more details, motivation, etc.
Part 1
Our modified code now looks like this:
    loop_var = 0
    while loop_var < len(binary_value):
        # ...
        loop_var += 1

len(binary_value) is computed once for each iteration through the loop; 11 times, including the last pass where the condition evaluates to False and the loop terminates.  Since the string doesn't change inside the loop, the length won't change either, so this value is a constant.
    loop_var = 0
    limit = len(binary_value)
    while loop_var < limit:
        # ...
        loop_var += 1

Now that we've recognized that limit is fixed, we can see this is actually a for loop, that starts at zero, counts up by 1, and stops when it reaches limit.  Instead of manually adjusting the loop_var by 1, and manually doing the comparison, we should simply use the for loop, over the required range, which is much more efficient:
    for loop_var in range(len(binary_value)):
        # ...

Part 2
Our loop now looks like:
    for loop_var in range(len(binary_value)):
        if binary_value[loop_var] == "1":
            # ...
        # ...

Indexing is expensive in Python.  Anytime you see a for loop, using a range(len(thing)), and the loop variable is only used as a index into the thing which the range is looping over, thing[loop_var], then we want to let Python do the indexing for us in the for statement:
    for digit in binary_value:
        if digit == "1":
            # ...
        # ...

Return Value
    return print(f"Decimal: {decimal_value}")

Is this function returning a value, or is it printing the result?  Currently, it is taking the value which is returned by the print() function, and returning that.  Ie)
    temporary = print(f"Decimal: {decimal_value}")
    return temporary

But print() returns None, so this is effectively:
    print(f"Decimal: {decimal_value}")
    return None

And if the function ends without a return statement, it automatically returns None anyway.  So the return can simply be omitted.
Note: It is better to return results from a function that does a calculation, without printing anything inside the function, and have the caller do the printing.  This will create more flexible code in the future.  Left to student.
Improved code
def binary_to_decimal_converter(binary_value):
    print(f"Binary: {binary_value}")
    decimal_value = 0

    # power is power of number 2
    # power must be less than string length because computer starts counting from 0th index
    power = len(binary_value) - 1

    for digit in binary_value:
        if digit == "1":
            decimal_value += 2 ** power
        power -= 1

    print(f"Decimal: {decimal_value}")

# Calling the function
binary_to_decimal_converter("1111101100")


Regular Expression Evaluator Task to be accomplished:

Write a function that takes two strings s and p as arguments and returns a boolean denoting whether s matches p.

p is a sequence of any number of the following:

a-z - which stands for itself
. - which matches any character
* - which matches 0 or more occurrences of the previous single character

Code:

#include <iostream>
using namespace std;

bool eval(string s, string p) {
    int j = 0;
    for(int i = 0; i < p.length(); i++) {
        // is next character is wildcard
        if((int)p[i+1] == 42)
        {
            // is it preceded by a dot
            if((int)p[i] == 46)
            {
                char charToMatch = s[j];

                // keep moving forward in string until the repetition of the 'any character' is over
                while(s[j] == charToMatch) j++;
            }
            // it's preceded by a-z
            else
            {
                // keep moving forward in string until repetition of the letter is over
                while(s[j] == p[i]) j++;
            }
        }
        // is current character a dot
        else if((int)p[i] == 46)
        {
            // move forward in string as it'll match no matter what
            j++;
        }
        // it's not '.' || '*'
        else
        {
            // is it a-z
            if((int)p[i] >= 97 && (int)p[i] <= 122) {

                // if current character in string != character mentioned in pattern
                if(s[j] != p[i])
                {
                    // pattern doesnt match
                    return false;
                }
                else
                {
                    // it matches, move forward
                    j++;
                }
            }
        }
    }

    // if pattern is ended but string is still left. pattern didnt match the whole string.
    if(j < s.length()) return false;
    // gone through whole string, pattern also finished. pattern matches.
    else return true;
}

int main() {
    cout << eval("a", "b.*"); // false
}

Constraints: Pattern is always valid and non-empty.

I have just started to learn about time complexity of algos and I believe its complexity should be \$\mathcal{O}(nm)\$ where \$n\$ and \$m\$ are the lengths of  p and the s respectively.

If it's not please correct me. Along with that, what improvements and optimizations could be made to lower the complexity?

Bug

There is a case that requires NFA instead of simple DFA to recognize string (of course it is possible to convert NFA to DFA):

eval("aaab", "a*ab");

Gives false, even though the string matches the regex. Disallowing same character after * fixes the problem too.

Style

why-is-using-namespace-std-considered-bad-practice.

Pass by const reference for read-only access. In the case of eval and availability of C++17, one could use std::string_view. I would advise taking the input range as input iterator, that would allow matching files, input from console, etc.

(int)p[i+1] == 42

I do not see why that is preferred to

p[i + 1] == '*'

more readable version makes comment obsolete.

if(j < s.length()) return false;
    else return true;

Could be rewritten as

return j == s.length();

Note that for this a bug about running over the string should be fixed, the bug is described below. >= will work too.

There are also no checks if string is already fully traversed in conditions with *. Although all implementations that I know of store null terminator at the end, this will not work on arbitrary ranges of characters.

I agree with KonradRudolph that comments do not contribute anything useful.

// is next character is wildcard

This comment is misleading. * is called Kleene star. Without looking at ASCII table one would assume there is a bug.

Runtime complexity

I believe runtime is \$\mathcal{O}(n)\$ in the worst case, where \$n\$ is length of input string. Think about it: the code does a single pass over a string, and doesn't reroll.

Theory

I would advise learning method of transforming NFA to DFA. It's great to learn parsing techniques, but there tools for that like flex, bison, etc exist, if you just want to hammer the nail into it's place.

I would assume .* means match any sequence of characters, as by logic in the question even doing | for all characters in the alphabet will make it impossible to describe just any combination of letters in the alphabet. Note that such a language is in the set of regular languages, as it is possible to construct DFA for it. May be I am wrong though, as my assumption stems from javascript regex.


Maximum Subarray Problem - Recursive O(n log n) algorithm I have implemented a recursive O(n log n) algorithm for solving the maximum sub-array problem. I would like a general review for it.

Here the max_subarray is the main function, and the static one is the auxillary function for it.

#include<stdio.h>

int max_subarray(int array[], int *low, int *high);

static int max_crossing_subarray(int array[], int *low, int mid, int *high);

int main()
{
    //The maximum subarray-sum is 43 for the following
    int array[16] = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
    int low = 0;
    int high = 15;

    printf("%d", max_subarray(array, &low, &high));
    printf("\n%d %d", low, high);

    return 0;
}

int max_subarray(int array[], int *low, int *high)
{
    if (*low == *high) {
        return array[*low];
    } else {
        //Don't change avoids overflow
        int mid = *low + (*high - *low)/2;

        int left_low = *low;
        int left_high = mid;
        int left_sum = max_subarray(array, &left_low, &left_high);

        int right_low = mid + 1;
        int right_high = *high;
        int right_sum = max_subarray(array, &right_low, &right_high);

        int cross_low = *low;
        int cross_high = *high;
        int cross_sum = max_crossing_subarray(array, &cross_low, mid, &cross_high);

        if (left_sum >= right_sum && left_sum >= cross_sum)
        {
            *low = left_low;
            *high = left_high;
            return left_sum;

        } else if (right_sum >= left_sum && right_sum >= cross_sum) {
            *low = right_low;
            *high = right_high;
            return right_sum;

        } else {
            *low = cross_low;
            *high = cross_high;
            return cross_sum;
        }
    }
}

static int max_crossing_subarray(int array[], int *low, int mid, int *high)
{
    int left_sum = 0;
    int max_left = mid;
    for (int i = mid, sum = 0; i >= *low; i--) {
        sum += array[i];
        if (sum > left_sum) {
            left_sum = sum;
            max_left = i;
        }
    }

    int right_sum = 0;
    int max_right = mid;
    for (int i = mid + 1, sum = 0; i <= *high; i++) {
        sum += array[i];
        if (sum > right_sum) {
            right_sum = sum;
            max_right = i;
        }
    }

    *low = max_left;
    *high = max_right;
    return left_sum + right_sum;
}

Your program fails when all of the members of an array are negative, it simply returns 0 instead of the maximum negative number.

Recursion here is slowing you down.  Using Kadane's algorithm, we can make the time complexity linear, or O(n) .

#include<stdio.h>

#define max(a, b) (((a) > (b)) ? (a) : (b))

int maxSubArraySum(int array[], int size)
{
    int maxSoFar = array[0];
    int currentMax = array[0];

    for (int i = 1; i < size; i++)
    {
        currentMax = max(array[i], currentMax + array[i]);
        maxSoFar = max(maxSoFar, currentMax);
    }
    return maxSoFar;
}

int main()
{
    int array[] =  {-2, -3, 4, -1, -2, 1, 5, -3};
    int len = sizeof(array) / sizeof(array[0]);
    int maxSum = maxSubArraySum(array, len);
    printf("Maximum contiguous sum is %d\n", maxSum);
    return 0;
}


Split a char array with NUL terminators and inner delimiters I get as an input a char array in this format:  "key = value\0key = value...\0" (last pair is ended with 2 NUL terminators - one is the pair end + one is the whole string end)

and I want to split it into pairs of {key, value} in order to print them.

This is my approach; is there a better way (strtok-like) to do so?

char str [] =   "line 1 = But I set fire to the rain\0line 2 = Watched it pour as I touched your face\0line 3 = Well, it burned while I cried\0line 4 = 'Cause I heard it screaming out your name, your name!\0";
char * p = str;
char key[10], value[128], * delimiter;

while(*p){
    memset(key,     0, sizeof(key));
    memset(value,   0, sizeof(value));

    delimiter = strchr(p, '=');
    strncpy(key, p, delimiter - p);
    // not sure where the NUL terminator is, so use strcpy
    strcpy(value, 1 + delimiter);

    printf("key: %s\n   value: %s\n", key, value);
    p += strlen(p) + 1;
}

I'm copying the pairs into temp arrays so I could process them later...

// not sure where the NUL terminator is, so use strcpy
strcpy(value, 1 + delimiter);

This is really dangerous. strncpy exists to prevent the possibility of buffer overflows, which are a risk precisely when you don't know how much memory you're throwing around.

If you are copying to an array of fixed size and you don't know how much to allow it to copy, use strncpy and restrict it to copying up to the length of the detination buffer. Note: strncpy(dest, src, length) copies at most length characters, or up to a null terminator if sooner. So that will not guarantee that your program works correctly (and in particular it will not guarantee that your destination is a valid null-terminated C string). It will prevent a buffer overflow if something goes wrong, which would be a much harder problem to handle.

It would still be better if you did know ahead of time how much to expect to copy, because that allows you to handle failure cases. You can do this: just use strlen(delimiter). In fact, you're already doing this! You're just doing it to p and two lines too late.

However, strncpy is not a magic bullet if used incorrectly. strncpy(key, p, delimiter - p); is vulnerable to overflow because it does not consider the capacity of key. If delimiter - p is say 15 then that line says "Copy from here into this array of size 10, but not more than 15 characters."

Take home is always know the sizes of arrays that you're dealing with, and ritually prefer the functions that check sizes such as strncpy(dst, src, sizeof(dst)) as a second line of defence so that if you do have a bug in handling array lengths the bug is less likely to be of the worst case security vulnerability sort.

A second concern I have with this code is that it relies on str being double null terminated. This is an unusual convention, and so requires a lot of conscious effort to get right. If you pack this into a function and it gets called by anyone else, or even by yourself when you're thinking about the logic of the calling component rather than the splitting component, you are going to keep reading through a bunch of junk.

Even worse, because it is not unusual for debug builds to be more generous with initialising stuff to zero than release builds, you stand a very real risk that it will appear to work fine for ages until you push it out to someone else!

The third thing to mention, and a general mindset one, is be careful not to assume that you are on the so called "happy path". Your code should do the right thing if given inputs in a form you expect, and it does. It should also confirm whereever possible that the inputs are in the form you expect.

For example, consider delimiter = strchr(p, '=');
Great, finds the "=" character to split on. If this bit of the string does not contain "=" anywhere, it returns NULL. You should check that this has not happened. Of course delimiter - p where delimiter is NULL is going to have some weird behaviour! You should check that any functions which might fail have not failed before relying on their output.


Formatting a price in Swift using an extension vs. a class I have a price as a Double, which I should format it as a String.

Should I use an extension instead of classical class to encapsulate "formater", "serializers", etc? Or is there an even better alternative?

Using Class

class PriceFormatter{
    let value:Double

    init(_ value:Double){
        self.value = value
    }

    func format()->String{
        let strValue = "\(value)"
        let subStrings = strValue.split(separator: ".")
        let money = subStrings[0]
        var cents = "00"
        if subStrings.count > 1{
            cents = String(subStrings[1])

            if(cents.count == 1){
                cents = "0\(cents)"
            }
        }

        return "$\(money).\(cents)"
    }
}

Using Extension

extension Double {
    var priceFormatted:String{
        let strValue = "\(self)"
        let subStrings = strValue.split(separator: ".")
        let money = subStrings[0]
        var cents = "00"
        if subStrings.count > 1{
            cents = String(subStrings[1])

            if(cents.count == 1){
                cents = "0\(cents)"
            }
        }

        return "$\(money).\(cents)"
    }
}

Implementation

let input:Double = 5.0
let priceFromClass = PriceFormatter(input).format()
let priceFromExtension = input.priceFormatted

Should I use an extension instead of classical class to encapsulate "formatter", "serializers", etc?

No, it should not be an extension to the numeric type.

A couple of observations:

This formatter should really work with a variety of types (Double, Float, Decimal, etc.), so burying it inside a particular numeric type’s definition isn’t right. Theoretically you could consider an extension to a protocol, e.g. Numeric, instead, but attaching it to a particular type is certainly not right.
Formatters often have properties of their own. E.g. for a currency formatter, you’d probably have a locale for number formatting, currency symbol, preferred decimal places for that currency, etc., so that speaks to having the formatter as a type, itself, not just some computed property for the numeric type that is being displayed. It also affords the idea of having a single instance of a formatter that you use repeatedly for every underlying object that needs to be displayed.
Note, once you realize that you’re likely to want to configure a formatter once and use it repeatedly, it no longer makes sense to make the value a property of this formatter type. It should be a parameter that we pass to our method for creating a string representation.
By the way, formatters are not just “represent this object as a string”, but also “parse this string into an object” (and sometimes even “is this a valid substring for this type” which you might use to validate input as the user enters it). Once you consider formatters in this context, the notion of burying this in the underlying numeric types starts to run afoul of the “single responsibility principle”. A formatter is, effectively, an object for translating model objects to and from presentations in the UI.
For all of the aforementioned reasons, Foundation has a long tradition of separating data types and their formatters. See Formatter. And there are a litany of existing formatters. You should have a fairly compelling reason before deviating from this well established pattern.
Needless to say, I wouldn’t advise writing your own currency formatter at all when there are existing formatters that do the job very well. As Apple says:

  Before you decide to create a custom formatter, make sure that you cannot configure the public subclasses to satisfy your requirements.

I’d suggest just using NumberFormatter with a numberStyle of one of the currency types (e.g. .currency, .currencyAccounting, etc.).

But I assume this is for illustrative purposes only.
While your code snippet was a “formatter”, you mention serialization.

That’s a different situation where you are often serializing objects with multiple properties of different types. And the serialization is often being handled by an existing serializer objects (e.g., for encoding, JSONEncoder and PropertyListEncoder, etc.). To support serialization for your custom types, you define your type to conform to the Codable protocol.
While presentation and parsing of values in the UI is often handled by separate formatter objects, it’s worth noting that there are a few string representations that we might add to our custom types for debugging purposes. For example, we might conform to CustomStringConvertible so that we can print our values.  Value types (struct) have a decent default string representation, but especially for reference types (class) it can be nice to customize this.

But don’t be tempted to use description as a backdoor for formatting strings in your UI. As Apple says,

  Accessing a type’s description property directly or using CustomStringConvertible as a generic constraint is discouraged.

But for diagnostic purposes, this can be useful. Also see CustomDebugStringConvertible.


Checking if a Stack is sorted in ascending order Write a method isSorted that accepts a stack of integers as a parameter and returns true if the elements in the stack occur in
  ascending (non-decreasing) order from top to bottom, and false
  otherwise. That is, the smallest element should be on top, growing
  larger toward the bottom. For example, passing the following stack to
  your method should cause it to return true:

  bottom [20, 20, 17, 11, 8, 8, 3, 2] top

  The following stack is not sorted (the 15 is out of place), so passing it to your method should return a result of false:

  bottom [18, 12, 15, 6, 1] top

  An empty or one-element stack is considered to be sorted. When your method returns, the stack should be in the same state as when it
  was passed in. In other words, if your method modifies the stack, you
  must restore it before returning.

Obey the following restrictions in your solution:

You may use one queue or stack (but not both) as auxiliary storage.
You may not use other structures (arrays, lists, etc.), but you can have as many simple variables as you like.
Use the Queue interface and Stack/LinkedList classes discussed in the textbook.
Use stacks/queues in stack/queue-like ways only. Do not call index-based methods such as get, search, or set (or use a for-each loop or iterator) on a stack/queue. You may call only add, remove, push, pop, peek, isEmpty, and size.
Your solution should run in O(N) time, where N is the number of elements of the stack.
You have access to the following two methods and may call them as needed to help you solve the problem:

public static void s2q(Stack s, Queue q) { ... }

public static void q2s(Queue q, Stack s) { ... }

I'm looking for general feedback that will make my future code better. Are there any glaring issues that you can find that make it harder for you to read my code? Is there a better way you can think of to accomplish this task?

public boolean isSorted(Stack<Integer> s) {
    boolean isSorted = true;
    if (s.size() == 1 || s.isEmpty()) {
        return isSorted;
    }

    Queue<Integer> q = new LinkedList<Integer>();
    while(!s.isEmpty()){
        int s1 = s.pop();
        if (!s.isEmpty()) {
            int s2 = s.peek();
            isSorted &= s2 >= s1;
        }
        q.add(s1);
    }

    while (!q.isEmpty()) {
        s.push(q.poll());
    }

    while (!s.isEmpty()) {
        q.offer(s.pop());
    }

    while (!q.isEmpty()) {
        s.push(q.poll());
    }

    return isSorted;
}

Advice 1

if (s.size() == 1 || s.isEmpty()) {
    return isSorted;
}

You can write more succinctly

if (s.size() < 2) {
    return true;
}

Advice 2

boolean isSorted = true;
if (s.size() == 1 || s.isEmpty()) {
    return isSorted;
}

I suggest you write instead:

if (s.size() == 1 || s.isEmpty()) {
    return true;
}
boolean isSorted = true;

This is a micro-optimization.

Advice 3

Making it generic is not hard. You could demand a type parameter E which extends a Comparable<? super E>

Alternative implementation

I had this in mind:

public static <E extends Comparable<? super E>>
    boolean isSortedV2(Stack<E> stack) {
    if (stack.size() < 2) {
        return true;
    }

    Stack<E> aux = new Stack<>();
    aux.push(stack.pop());

    while (!stack.isEmpty() && stack.peek().compareTo(aux.peek()) >= 0) {
        aux.push(stack.pop());
    }

    boolean sorted = stack.isEmpty();

    // Restore the input stack:
    while (!aux.isEmpty()) {
        stack.push(aux.pop());
    }

    return sorted;
}


Replace fifth space with new line I want to replace the fifth space in a sentence with a new line. Sample input:

"Hi this is empty string. This should be in new line!"

Expected output:

"Hi this is empty string.
This should be in new line!"

I'm getting the expected output with this code, but I need to know, is this the optimized solution or there are any better solution than this?
    string s = "Hi this is empty string. This should be in new line!", t = "";
    int countSpaces = s.Count(Char.IsWhiteSpace);
    if (countSpaces > 3)
    {
        int count = 0;
        char n;
        foreach (char c in s)
        {
            if (c == ' ') count++;
            if (count == 5)
            {
                n = '\n';
                count++;
            }
            else n = c;
            t += n;
        }
    }
    else t = s;
    MessageBox.Show(t);

Using += to concatenate strings in a loop scales very badly. Each iteration creates a new string instance by copying the previous string and the new character into a new string, and that string grows for each iteration. Using a StringBuilder (as Dmitry suggests) would be a great improvment.

However, you don't need to build the string character by character. You could use a regular expression to replace the fifth space with a newline:

string t = Regex.Replace(s, "^([^ ]+(?: [^ ]+){4}) ", "$1" + Environment.NewLine);

Explanation of the pattern:

^       mathces the beginning of the string
(       starts a catching group
[^ ]+   matches the first word (a sequence of non-space characters)
(?:     start a non-catching group
space   matches a space
[^ ]+   mathces a word
)       ends the non-catching group
{4}     repeats the group four times
)       ends the catching group
space   matches the fifth space

The $1 in the replacement string gets the value caught by the group.

Another alternative would be to loop through the string and look for spaces, then use Substring to get the parts before and after the fifth space:

int cnt = 0, index = 0;
while (cnt < 5) {
  if (s[index++] == ' ') cnt++;
}
string t = s.Substring(0, index - 1) + Environment.NewLine + s.Substring(index);


Remove excessive recurrent code from store and computed I have three getters in my store:

getActiveTournaments(state) {
  return state.tournaments.data
    ? state.tournaments.data
      .filter(tournament => tournament.state_value === 'in_progress')
    // sort tournaments by date of creation
      .sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
    : [];
},
getFutureTournaments(state) {
  return state.tournaments.data
    ? state.tournaments.data
      .filter(tournament => tournament.state_value === 'promo')
    // sort tournaments by date of creation
      .sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
    : [];
},
getPastTournaments(state) {
  return state.tournaments.data
    ? state.tournaments.data
      .filter(tournament => tournament.state_value === 'finished')
    // sort tournaments by date of creation
      .sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
    : [];
},

In my component I have a slider which accept an array of three items, each first one from an arrays returned by every getters.
So I created a computed property in my component in order to get these items and then pass them to the slider:

<template>
 ...
 <hovering-image-slider v-if="getLatestTournaments.length > 0"
                         :slideData="getLatestTournaments" />
 ...
</template>

<script>
 ...
 getLatestTournaments() {
  return this.getFutureTournaments[0]
  && this.getActiveTournaments[0]
  && this.getPastTournaments[0]
    ? [
      this.getFutureTournaments[0],
      this.getActiveTournaments[0],
      this.getPastTournaments[0]]
    : [];
},
</script>

It works fine but it seems like an ugly solution. Slider component will get an error of undefined data if I will not check the presence of [0] element in the computed property. I thought that by doing some checking at the level of my getters, it will not require checking in the component but apparently it does. Can you please advice how I can improve this existing code?

DRY the code

The 3 store getters are identical apart from the filter value. So first thing is to remove the repeated code. Create a function (either in the store, or within its scope, that you pass the state and the filter string.

You get something like

filterTournaments(state, filter) {
  return state.tournaments.data
    ? state.tournaments.data
      .filter(tournament => tournament.state_value === filter)
      .sort((A, B) => A.created_at - B.created_at)
    : [];
},
getActiveTournaments(state) { return this.filterTournaments(state, "in_progress") },
getFutureTournaments(state) { return this.filterTournaments(state, "promo") },
getPastTournaments(state) { return this.filterTournaments(state, "finished") },

Direct to the array

The current solution on the HTML side is ugly, if you do have data to display, you have to get the data again, filtering and sorting each a second time.

Get the three items and put them directly in an array and test if all truthy, if so return the array, else an empty array.

getLatestTournaments() {
  const tournaments = [
      this.getActiveTournaments[0],
      this.getFutureTournaments[0],
      this.getPastTournaments[0]
  ];
  return tournaments[0] && tournaments[1] && tournaments[2] ? tournaments : [];
}

Do it in the store

Fast and efficient

If you want it done at the store and you can add some smarts to the filter function, that way you can avoid a lot of needless processing and memory use. Using filter and sort to find the min item with a matching state_value is not efficient.

getFilteredTournaments(state) {
    const data = state.tournaments.data;
    if (!data) { return [] }
    const filters = ["in_progress", "promo", "finished"];
    const tournaments = [];
    for (const filter of filters) {
        let min = Infinity, minTournament;
        for (const tournament of data) {
            const {state_value, created_at} = tournament;
            if (state_value === filter && created_at < min) {
               min = created_at;
               minTournament = tournament;
            }
        }
        if (minTournament) { tournaments.push(minTournament) }
        else { return [] }
    }
    return tournaments;
},

Then you need only the one call

:slideData="getFilteredTournaments"

I am not that familiar with VUE so may need the wrapper

:slideData="getLatestTournaments"

<script>
   getLatestTournaments() { return this.getFilteredTournaments }
</script>

But that type of code does not suit everyone.

Keep it simple

Using the existing methodologies you can do the 3 filters in one function in the store as follows

getAllTournaments(state) {
    const data = state.tournaments.data;
    if (data) {
        const filter = filter => data
          .filter(tournament => tournament.state_value === filter)
          .sort((A, B) => A.created_at - B.created_at)[0];
        const result = [
            filter("in_progress"),
            filter("promo"),
            filter("finished"),
        ];
        return result.some(item => !item) ? [] : result;
    }
    return [];
},

and call with

getLatestTournaments() { return this.getAllTournaments }


Logging using function as decorator in Guava I needed to add a logger into my flow based on FluentIterable from the Guava library. I have a lot of functions and in some cases I would like to add logging when in other cases (for the same function) I would not.

Of course the natural solution for this problem is to use the decorator pattern, so I created something like this:

/**
 * Decorator function that add logging into function passed as parameter.
 *
 * @param  input type
 * @param <O> output type.
 */
public class DecoratorLoggerInfoFunc implements Function {

    /**
     * Original function
     */
    private final Function function;

    /**
     * Current logger.
     */
    private final Logger logger;

    /**
     * "Builder" that takes function and return function decorated by logger.
     *
     * @param function function to decorate.
     * @param       input type
     * @param <O>      output type
     * @return function with logger.
     */
    public static  Function of(Function function) {
        checkNotNull(function, "Function to decorate cannot be null");
        return new DecoratorLoggerInfoFunc(function);
    }

    /**
     * Initialize logger!
     *
     * @param function original function.
     */
    private DecoratorLoggerInfoFunc(Function function) {
        this.function = function;
        this.logger = LoggerFactory.getLogger(function.getClass());
    }

    /**
     * Flow:
     *

     *
Call original function

     *
Log input and output

     *
Return output of original function

     *

     *
     * @param input
     * @return
     */
    @Override
    public O apply(I input) {
        O output = function.apply(input);
        logger.info("Input is {} Output is {}", input, output);
        return output;
    }
}

Is this code a good way to solve my problem? Is there a better way to do this?

The concept seems fine to me. The problem is that you will still need to decide whether to decorate, or not decorate the function, and that is done outside the function. That makes it a once-per-create decision, which is OK, but you may still end up with a lot of conditions in your code:

Function f = logFunction() ? new DecoratorLoggerInfoFunc(f) : f;

The actual apply method is not very robust though. I would include logging of any potential exceptions that are not declared to be thrown on the function itself...:

public O apply(I input) {
    try {
        O output = function.apply(input);
        logger.info("Input is {} Output is {}", input, output);
        return output;
    } catch (RuntimeException e) {
        logger.warn("Exception running with input {}", input, e);
        throw e;
    }
}


Wiggle subsequence from leetcode This is the Wiggle Subsequence problem from leetcode.com:

  A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

  For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

  Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

The solution is inspired by an \$O(n\log n)\$ answer to How to determine the longest increasing subsequence using dynamic programming?

class Solution(object):
    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums or len(nums) == 1:
            return len(nums)
        current_num, prev_num = nums[0], nums[0]
        count, trend = 0, None
        for current_num in nums:
            if not trend:
                if current_num > prev_num:
                    trend = "down_to_up"
                    count += 2
                elif current_num < prev_num:
                    trend = "up_to_down"
                    count += 2
            elif trend == "down_to_up":
                if current_num < prev_num:
                    count += 1
                    trend = "up_to_down"
            elif trend == "up_to_down":
                if current_num > prev_num:
                    prev_num = current_num
                    count += 1
                    trend = "down_to_up"
            prev_num = current_num
        if trend == None:
            count = 1
        return count

The special case:

if not nums or len(nums) == 1:

can be simplified to:

if not nums:

because the case len(nums) == 1 is already handled correctly by the main code.
Instead of starting with count = 0, setting count += 2 when a trend is found for the first time, and having an adjustment at the end if no trend was found, you could start with count = 1, set count += 1 when a trend is found for the first time, and remove the adjustment.
There is no need to initialise current_num = nums[0] because this immediately gets overwritten by the for current_num in ... loop.
There is an unnecessary assignment of prev_num = current_num in one of the branches.
Using the strings "down_to_up" and "up_to_down" to represent the current trend is risky: if you made a typo and wrote "up_to_dwon" somewhere, then the code would be broken but Python would not detect this. It would be better to use global constants, for example

_DOWN_TO_UP = "down to up"
_UP_TO_DOWN = "up to down"

and then if you make a typo like _UP_TO_DWON you will get a NameError from Python.
Now the main logic of the function looks like this:

if not trend:
    if current_num > prev_num:
        trend = _DOWN_TO_UP
        count += 1
    elif current_num < prev_num:
        trend = _UP_TO_DOWN
        count += 1
elif trend == _DOWN_TO_UP:
    if current_num < prev_num:
        trend = _UP_TO_DOWN
        count += 1
elif trend == _UP_TO_DOWN:
    if current_num > prev_num:
        trend = _DOWN_TO_UP
        count += 1
prev_num = current_num

There is a lot of repetition here. In particular, on each branch we check to see if the trend has changed direction, and if it has, then we update trend and increment count. So we could refactor it so that we work out the new trend first, and then compare it with the old trend, like this:

# Work out current trend
if current_num > prev_num:
    current_trend = _DOWN_TO_UP
elif current_num < prev_num:
    current_trend = _UP_TO_DOWN
else: # current_num == prev_num
    current_trend = 0

# Compare with previous trend
if current_trend != 0 and current_trend != trend:
    trend = current_trend
    count += 1
prev_num = current_num

In the case current_num == prev_num we know that the trend does not change, and so there can't be a change to trend, so it would make sense to test this first, and so avoid the test current_trend != 0, like this:

if current_num != prev_num:
    # Work out current trend
    if current_num > prev_num:
        current_trend = _DOWN_TO_UP
    else:
        current_trend = _UP_TO_DOWN

    # Compare with previous trend
    if current_trend != trend:
        trend = current_trend
        count += 1
    prev_num = current_num

And now we can make a further simplification by using True instead of _DOWN_TO_UP and False instead of _UP_TO_DOWN:

if current_num != prev_num:
    current_trend = current_num > prev_num
    if current_trend != trend:
        trend = current_trend
        count += 1
    prev_num = current_num

After making this change, it should be clear that prev_trend would be a better name than trend, for parallelism with prev_num.

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    if not nums:
        return 0
    count = 1
    prev_num = nums[0]
    prev_trend = None
    for current_num in nums:
        if current_num != prev_num:
            current_trend = current_num > prev_num
            if current_trend != prev_trend:
                prev_trend = current_trend
                count += 1
            prev_num = current_num
    return count

It would make sense to stop here, as the revised code is already a lot simpler than the original. But if you are comfortable with Python iterators then you might want to read on to see how the functions and recipes in the itertools module can be used to further simplify the code.
First, we can avoid the current_num != prev_num test by using itertools.groupby to group identical numbers together:

from itertools import groupby

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    if not nums:
        return 0
    nums = (n for n, _ in groupby(nums))
    prev_num = next(nums)
    count = 1
    prev_trend = None
    for current_num in nums:
        current_trend = current_num > prev_num
        if current_trend != prev_trend:
            prev_trend = current_trend
            count += 1
        prev_num = current_num
    return count

Now that we have an iterator over groups of identical numbers, we can use the pairwise recipe from the itertools documentation to iterate over adjacent pairs of numbers, avoiding the need to assign to prev_num.

from itertools import groupby, tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    if not nums:
        return 0
    nums = (n for n, _ in groupby(nums))
    count = 1
    prev_trend = None
    for prev_num, current_num in pairwise(nums):
        current_trend = current_num > prev_num
        if current_trend != prev_trend:
            prev_trend = current_trend
            count += 1
    return count

Now we can construct an iterator over the trends:

    trends = (cur > prev for prev, cur in pairwise(nums))

and apply itertools.groupby to this iterator, thus grouping identical trends together and avoiding the need for current_trend and prev_trend. In fact, all we have to do now is count the groups of identical trends.

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    if not nums:
        return 0
    nums = (n for n, _ in groupby(nums))
    trends = (cur > prev for prev, cur in pairwise(nums))
    return 1 + sum(1 for _ in groupby(trends))

This could be written as a single expression:

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    return bool(nums) + sum(1 for _ in groupby(
        a > b for a, b in pairwise(n for n, _ in groupby(nums))))

(But only if you like that kind of code.)


Skew logistic distribution I am trying to program a skew logistic distribution function to return the PDF, the CDF, and (later) the inverse CDF.  Although there are several forms of skew logistic, this is for perhaps the most widely known, a variation of the skew normal distribution introduced by Azzalini and covered by Saralees Nadarajah.  Aside from a formal paper on Springer, it's covered in "Focus on African Diaspora Mathematics By Toka Diagana".  A Google search will turn up the book and the skew logistic portion starts at the bottom of page 41.

I am comfortable with the PDF function (included below), but I am struggling with the CDF, primarily because I am not quite familiar with the math.

Here's the skew logistic CDF taken from the formal paper on Springer (Nadarajah, S. The skew logistic distribution, AStA Adv Stat Anal (2009) 93: 187–203):

$$F(x)=\left\{\begin{array}{lr}1-2\sum_{j=0}^{\infty}\sum_{k=0}^{\infty}\binom{-1}{j}\binom{-2}{k}\frac{1}{1+\lambda j +k}\exp\left[-\frac{(1+\lambda j + k)x}{\beta}\right]&\text{if } x>0,\\
2\sum_{j=0}^{\infty}\sum_{k=0}^{\infty}\binom{-1}{j}\binom{-2}{k}\frac{1}{1+\lambda+\lambda j +k}\exp\left[\frac{(1+\lambda+\lambda j+k)x}{\beta}\right]&\text{if }x<0.\end{array}\right.$$

I understand everything except this portion:

$$\sum_{j=0}^{\infty} \sum_{k=0}^{\infty} \binom{-1}{j}\binom{-2}{k}$$

My current approach is to simply start with the value, step up and down by 0.0001 to sum the PDF in each direction, and then divide the area below the value by the total area.

However, this strikes me as extremely inefficient and inaccurate past five or six decimal places.  I have to believe a better function could be written based off the CDF formula Nadarajah gives.

Once I get the SkewLogisticCDF done properly, I'd like to also have a SkewLogisticCDFInverse as well.

// Skew Logistic PDF
double SkewLogisticPDF(double value, double location, double scale, double shape)
{

double x = exp((-(value - location)) / scale);
double y = exp((-(value - location)) * shape / scale);

x = 2 * x / (scale * pow(1 + x, 2) * (1 + y));

return x;
}

// Skew Logistic CDF
double SkewLogisticCDF(double value, double location, double scale, double shape)
{
const double step = 0.00001;
const double precision = 0.0000001;

double areaBelowValue = 0;
double areaAboveValue = 0;

double currentValue = 0;
double currentPDF = 0;

currentValue = value;
do
{
    currentPDF = SkewLogisticPDF(currentValue, location, scale, shape);
    areaBelowValue += currentPDF;

    currentValue -= step;

} while (currentPDF >= precision);

currentValue = value;
do
{
    currentPDF = SkewLogisticPDF(currentValue, location, scale, shape);
    areaAboveValue += currentPDF;

    currentValue += step;

} while (currentPDF >= precision);

double x = areaBelowValue / (areaBelowValue + areaAboveValue);

return x;
}

OK, after some digging I realized I was actually familiar with the notation below after all:

$$\sum_{j=0}^{\infty} \sum_{k=0}^{\infty} \binom{-1}{j}\binom{-2}{k}$$

However I've only seen it in use for combinations where negative numbers are not allowed.  I initially thought it must represent some other mathematical function, but I found a generalized version that easily allows for negative numbers.  For those interested, it's covered under the Wikipedia article on "Binomial Coefficient" in the section on "Generalization and connection to the binomial series."

Below is the C++ function I came up with.  It essentially starts the CDF off with zero and then adds to the CDF by increasing j and k from zero toward infinity until the change falls below the threshold given in the precision constant.  Here the precision is set to 0.00000001, giving probably at least six decimal places of accuracy, possibly seven, which is good enough for my purposes.  Decreasing the precision further would return even more accurate results at the cost of speed, but that might be necessary for a different application.

Some quick notes:

-- The net result of this function:
$$\sum_{j=0}^{\infty}\binom{-1}{j}$$
is to simply return 1 if j is even and -1 if j is odd.  I've substituted it with a much simpler jMult = ((j % 2) != 1) ? 1 : -1;

-- The net result of this function:
$$\sum_{k=0}^{\infty}\binom{-2}{k}$$
is to simply return k + 1 if k is even and -(k + 1) if k is odd.  I've substituted it with a much simpler kMult = -((k % 2) * 2 - 1)*(k + 1);

-- Although Nadarajah shows two different formulas in his paper, one for value greater than zero and one for value less than zero, I've written this function so that it can accept a positive or negative value and return the correct number with only one formula.

-- Also, Nadarajah doesn't mention this but I realized that when the shape is negative, there are j and k combinations that end up dividing by zero.  However, the correct result is given by finding x using the negative of the shape and value and returning 1 - x as the result.

-- I accomplished both of the above by introducing the distance, distanceMultiplier, shapeTerm, and extraShapeTerm variables and adjusting Nadarajah's formula to use those.

-- I also use kLastSignificant and kPrevious variables to track how far out on k the previous iteration of j went before it fell below the precision threshold.  I found that for larger values of j, the initial k would be below the precision threshold but later values of k would be above the threshold.  Here I wanted to ensure the function captured those later values by going out at least as far on k as the previous iteration of j did.

[EDIT]
-- I've updated the function to use Nadarajah's correct formula for the case of when the value is exactly zero.  The psi function comes from http://people.sc.fsu.edu/~jburkardt/cpp_src/cdflib/cdflib.cpp

There are still two areas of improvement I can identify:

-- The function is extremely fast except when the value is close or equal to zero.  For example, if the value is 0.0001, the j and k tend to stretch out for extremely long periods before they fall below the precision threshold.

-- For very large values, the j and k initially start below the precision threshold and the function results in a one or a zero, which are not possible in the logistic distribution.  To fix this, I've added a portion at the end of the function to simply return either the precision or (1 - precision) in those cases.

In the end, the skew logistic CDF really needs an approximation formula that would easily address each of those issues and provide an even faster function at the cost of a little accuracy.  It's how most other functions like this (i.e., the Normal CDF) are calculated and it would make the inverse much easier to calculate (and more practical to program).

// Skew Logistic CDF
double SkewLogisticCDF(double value, double location, double scale, double shape)
{
const double precision = 0.00000001;

double x = 0;

if (shape == 0)
{
    x = 1 / (1 + exp(-(value - location) / scale));
}
else
{

    // Evaluate the distance and the shape
    // If the shape is negative, then distance *= -1 and shape *= -1
    double shapeTerm = (shape > 0) ? shape : -shape;
    double distance = (shape > 0) ? (value - location) : (location - value);

    double distanceTermMultuplier = (distance < 0) ? 1 : -1;
    double extraShapeTerm = (distance < 0) ? shapeTerm : 0;

    int j = 0;
    int k = 0;

    double result;
    int kPrevious = 0;
    int kLastSignificant = 0;

    // distance != 0
    if (distance != 0)
    {
        // j
        do
        {

            // Returns 1 if j is even, -1 if j is odd
            // This is the ( -1 )
            //             (  j ) of the formula
            // Can also achieve using (j % 2)*-2 + 1;
            // Went with conditional operator to make quicker
            int jMult = ((j % 2) != 1) ? 1 : -1;

            k = 0;
            kLastSignificant = 0;
            // k
            do
            {

                // Returns (k + 1) if k is even, -(k + 1) if k is odd
                // This is the ( -2 )
                //             (  k ) of the formula
                // Can also achieve using -((k % 2) * 2 - 1)*(k + 1);
                // Went with conditional operator to make quicker
                int kMult = -((k % 2) * 2 - 1)*(k + 1);

                result = jMult * kMult * 1 / (1 + extraShapeTerm + shapeTerm * j + k) * exp((1 + extraShapeTerm + shapeTerm * j + k) * distanceTermMultuplier * distance / scale);

                x += result;

                kLastSignificant = (abs(result) >= precision) ? k : kLastSignificant;
                ++k;

            } while (abs(result) >= precision || k <= kPrevious);

            kPrevious = kLastSignificant;

            ++j;

        } while (kLastSignificant > 0);

        x *= 2;
        x = (distance < 0) ? x : 1 - x;

    }

    // distance == 0
    else
    {
        // j
        do
        {

            // Returns 1 if j is even, -1 if j is odd
            // This is the ( -1 )
            //             (  j ) of the formula
            // Can also achieve using (j % 2)*-2 + 1;
            // Went with conditional operator to make quicker
            int jMult = ((j % 2) != 1) ? 1 : -1;

            double psiAlpha = 1 + shapeTerm + shapeTerm * j;
            double psiOne = (1 + psiAlpha) / 2;
            double psiTwo = psiAlpha / 2;

            psiOne = psi(psiOne);
            psiTwo = psi(psiTwo);

            result = jMult * (0.5 - shapeTerm * (1 + j) * 0.5 * (psiOne - psiTwo));

            x += result;

            ++j;

        } while (abs(result) >= precision);

        x *= 2;

    }
}

// Reverse result if shape is negative
x = (shape > 0) ? x : 1 - x;

x = (x == 0) ? precision : x;
x = (x == 1) ? (1 - precision) : x;

return x;

}


Synchronization of an ODBC connection Since I'm venturing more and more into the multithreading, I now need to think about how to protect my precious OdbcConnection from breaking at random times.

The project specifications:

.NET-2.0
ODBC-Connection via MySQL-Connector 3.51 to MySQL 5.0

The main structure of my project in question looks like this:

+ Assembly
+--+> Namespace1
   +--> Data-Layer
+--+> Namespace2
   +--> Data-Layer
...

There's also an abstraction layer in place with interfaces and implementations, but I think that doesn't matter, because my question is about the ODBC implementation. They do also implement IDisposable.

This means I'm passing around an OdbcConnection to different classes and create these Data classes if asked to, like this:

public class MainDataSource
{
    private OdbcConnection _conn = <Yes, It's initialized>;

    public Namespace1.Data CreateNamespace1Data()
    {
        return new Namespace1.Data(_conn);
    }

    public Namespace2.Data CreateNamespace2Data()
    {
        return new Namespace2.Data(_conn);
    }
}

The Data classes itself are containing methods to fetch objects from the database. The only interesting thing here is that every Data class is holding its very own OdbcCommand objects, none of these are shared in any way. The only thing they have in common is the source OdbcConnection.

Since some of these classes (like the Setting class) might be called from multiple threads at the same time, I need to think about the best way to lock and protect these. My first idea was to lock the whole OdbcConnection:

public class Data
{
    private OdbcConnection _conn;
    private OdbcCommand _cmd;

    public Data(OdbcConnection conn)
    {
        _conn = conn;

        _cmd = _conn.CreateCommand();
        _cmd.CommandText = <FromResource>;
        _cmd.Parametersblabla;
    }

    public MyDataObject GetObjects(String searchterm)
    {
        lock(_conn)
        {
            _cmd.Parameters[0].Value = searchterm;
            using(OdbcDataReader reader = _cmd.ExecuteReader())
            {
                // Do stuff here and return MyDataObject
            }
        }
    }
}

This seems a little bit too strict to me, so I also thought about only locking the OdbcCommand:

public class Data
{
    private OdbcCommand _cmd;

    public Data(OdbcConnection conn)
    {
        _cmd = conn.CreateCommand();
        _cmd.CommandText = <FromResource>;
        _cmd.Parametersblabla;
    }

    public MyDataObject GetObjects(String searchterm)
    {
        lock(_cmd)
        {
            _cmd.Parameters[0].Value = searchterm;
            using(OdbcDataReader reader = _cmd.ExecuteReader())
            {
                // Do stuff here and return MyDataObject
            }
        }
    }
}

But I still feel like I've missed something very important here. Do I have other options? Did I miss something important?

The OdbcConnection is not thread-safe in any way, therefor it needs a locking mechanism.

My observation is that the OdbcConnection does send it's received commands down into the Connector. If this is happening in a multi-threaded environment, the sequence of commands is interrupted and you'll receive an exception with this or a similar message:

  ERROR [HY000] [MySQL][ODBC 3.51 Driver]Commands out of sync; you can't run this command now

The driver is confused because the sequence was interrupted. This can not only happen on a OdbcCommand level, but on a OdbcConnection level. The OdbcConnection needs to be locked.

An additional note is that you should lock the OdbcConnection the moment you start to work with a command:

_cmd.Parameters[0].Value = argument;
lock(_conn)
{
    _cmd.ExecuteNonQuery();
}

This is bad, because it could happen in a multi-threaded environment that the parameter gets overridden by another thread before ExecuteNonQuery can be called.

lock(_conn)
{
    _cmd.Parameters[0].Value = argument;
    _cmd.ExecuteNonQuery();
}

This keeps the execution as one atomic operation which can't be interrupted.

Further investigations revealed that the MySQL Odbc-Connector has a locking mechanism...but only on a statement level:

  MySQL ODBC Connector, 5.1.9, execute.c

 39:    SQLRETURN do_query(STMT FAR *stmt,char *query, SQLULEN query_length)
 40:    {
 ...
 55:        MYLOG_QUERY(stmt, query);
 56:        pthread_mutex_lock(&stmt->dbc->lock);
 ...
 96:        exit:
 97:        pthread_mutex_unlock(&stmt->dbc->lock);
 ...
114:   }

And to make it clear: If you have a non-thread-safe connection, lock the whole connection.

And to make it further clear, using an OdbcDataReader counts as using the connection. As long as you work with an OdbcDataReader, you should keep the lock on the connection.

This includes disposing of the resources, f.e. a DataReader. You should always use using inside the locked parts to make sure that the resources are freed again, otherwise it could happen that a DataReader lingers on and is later destroyed by the Garbage Collector and a rather inconvenient moment, like this:

Thread  Action
     1  Lock Connection
     1  Create Statement
     2  Lock Connection -> Wait
     1  Prepare Statement
     1  Execute Statement
     1  Get Reader
     1  Use Reader
     1  Unlock Connection
     2  Lock Connection
     2  Prepare Statement
     2  Execute Statement
    GC  Destroy Statement from thread #1
    GC  Destroy Reader from thread #1

In code it would like this:

lock (connection)
{
    IDbCommand command = connection.CreateCommand();
    command.CommandText = "SQL";
    IDataReader reader = command.ExecuteReader();
    // Do something the reader
    return valuesFromTheReader;
}

This is bad as it allows resources to linger on and the GC will later destroy them, with possible disastrous results. My tests revealed that from the exception

  Attempted to read or write protected memory.

to a simple deadlock of the application on an arbitrary line1 everything is possible if you fail to correctly synchronize database access.

The best pattern is to always destroy everything while in inside the lock:

lock (connection)
{
    using (IDbCommand command = connection.CreateCommand())
    {
        command.CommandText = "SQL";
        using (IDataReader reader = command.ExecuteReader())
        {
            // Do something the reader
            return valuesFromTheReader;
        }
    }
}

1: I'm not kidding, I could reliable reproduce a hang on the following instruction inside the System.Data.Odbc.OdbcDataReader.NextResult(bool, bool)

IL_0099: ldarg.1
00000099 8B F8 mov edi,eax

when I did not properly dispose of a DataReader.


How to better process csv file with pandas and further dealing with set I have below working code with pandas and python, i'm looking if there is an improvement or simplification which can be done.

Can we Just wrap this up into a definition.

$ cat getcbk_srvlist_1.py
#!/python/v3.6.1/bin/python3
from __future__ import print_function
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
import pandas as pd
import os
##### Python pandas, widen output display to see more columns. ####
pd.set_option('display.height', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('expand_frame_repr', True)
##################### END OF THE Display Settings ###################

################# PANDAS Extraction ###########
df_csv = pd.read_csv(input("Please input the CSV File Name: "), usecols=['Platform ID', 'Target system address']).dropna()
hostData = df_csv[df_csv['Platform ID'].str.startswith("CDS-Unix")]['Target system address']
hostData.to_csv('host_file1', header=None, index=None, sep=' ', mode='a')

with open('host_file1') as f1, open('host_file2') as f2:
    dataset1 = set(f1)
    dataset2 = set(f2)

for i, item in enumerate(sorted(dataset2 - dataset1)):
    print(str(item).strip())

os.unlink("host_file1")

The above code just compares the two files one is processed through pandas ie host_file1 and another is already existing host_file2.

main guard

It is common to put the code you want to run behind an if __name__ == "__main__":, so you can later import the functions that might be reused in a different module

naming

You use both snake_case and CamelCase. Try to stick to 1 naming convention. PEP-8 advised snake_case for variables and functions, CamelCase for classes

functions

split the code in logical parts

pandas settings

def settings_pandas():
    pd.set_option("display.height", None)
    pd.set_option("display.max_rows", None)
    pd.set_option("display.max_columns", None)
    pd.set_option("display.width", None)
    pd.set_option("expand_frame_repr", True)

filename input

The way you ask the filename is very fragile. A more robust way would be to ask the filename in a different function, and then validate it

from pathlib import Path
def ask_filename(validate=True):
    """
    Asks the user for a filename.
    If `validate` is True, it checks whether the file exists and it is a file
    """
    while True:
        file = Path(input("Please input the CSV File Name: (CTRL+C to abort)"))
        if validate:
            if not file.exists() and file.is_file():
                print("Filename is invalid")
                continue
        return file

IO

def read_host_data(filename):
    """reads `filename`, filters the unix platforms, and returns the `Target system address`"""
    df = pd.read_csv(filename, usecols=["Platform ID", 'Target system address']).dropna()
    unix_platforms = df['Platform ID'].str.startswith("CDS-Unix")
    return df.loc[unix_platforms, "Target system address"]

There is no need to save the intermediary data to a file. You could use a io.StringIO. An alternative if you need a temporary file is tempfile.

But in this case, where you just need the set of the values of a pd.Series, you can do just set(host_data), without the intermediary file.

putting it together:

if __name__ == "__main__":
    settings_pandas()  # needed?
    filename = ask_filename()
    host_data = set(read_host_data(filename))
    with open("hostfile2") as hostfile2:
        host_data2 = set(hostfile2)
    for item in sorted(host_data2 - host_data):
        print(item.strip())

since the i is not used, I dropped the enumerate. Since host_data2 is directly read from a file, there are no conversions, and it are all strs, so the conversion to str is dropped too.

Since I don't see any printing of pandas data, This part can be dropped apparently.


Django turn ChoiceField into a submit button I have made a ChoiceField into a select and submit button and wondered if this is the correct approach.

forms.py

class PortfolioForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(PortfolioForm, self).__init__(*args, **kwargs)

        portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]

        self.fields['portfolios'] = forms.ChoiceField(
                    widget=forms.Select(),
                    choices=portfolios,
                    required=False,
                    )

views.py

class PortfolioView(View):

    form_class = PortfolioForm
    template_name = 'portfolio.html'

    def get(self, request):
        form = self.form_class()

        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(self.request.POST)

        if form.is_valid():
            selected_portfolio = form.cleaned_data.get('portfolios')
            print(selected_portfolio)
            form = self.form_class(initial={'portfolios': selected_portfolio})

        else:
            form = self.form_class(initial={'portfolio_name': ''})

        return render(self.request, self.template_name, {'form': form})

and most of the trickery in the template. I use elements of form.portfolios to make the buttons, but it seems I have to include form.portfolios in the template to make it all work. In order not to show I put this in a hidden  tag.

{% block content %}
  <form id="id_portfolio" method="post">
    {% csrf_token %}
    {{ form.portfolios }}
    {% for portfolio in form.portfolios %}

      {% if portfolio.data.selected %}
        <button type="button">{{ portfolio.choice_label }}</button>

      {% else %}
        <button type="submit" value="{{ portfolio.data.value }}"
          name="{{ portfolio.data.name }}">{{ portfolio.choice_label }}</button>

      {% endif %}

    {% endfor %}
{% endblock content %}

If you want the options to appear on the page, I would recommend using the RadioSelect widget instead. You will still need to click a separate button to submit however.

class PortfolioForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(PortfolioForm, self).__init__(*args, **kwargs)

        portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]

        self.fields['portfolios'] = forms.ChoiceField(
                    widget=forms.RadioSelect(),
                    choices=portfolios,
                    required=False,
                    )

If you would like your own custom widget instead, you can inherit one of the existing widgets and apply your own template.

# widgets.py
class ButtonSelect(ChoiceWidget):
    template_name = 'widgets/button_select.html'
    option_template_name = 'widgets/button_select_option.html'

# templates/widgets/button_select.html
{% include "django/forms/widgets/multiple_input.html" %}

# templates/widgets/button_select_option.html
""""
Will need custom widget option code here.
Take a look at https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/input_option.html
"""

Then you can use it in your PortfolioForm

from widgets import ButtonSelect

class PortfolioForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(PortfolioForm, self).__init__(*args, **kwargs)

        portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]

        self.fields['portfolios'] = forms.ChoiceField(
                    widget=ButtonSelect(),
                    choices=portfolios,
                    required=False,
                    )


Writing a recursive factorial function in x86-64 The following assembly program works to print the factorial of a number:
SYS_EXIT = 60
.globl _start
_start:
    # run 4! --> 4*3*2*1 = 24
    mov $4,  %edi
    call factorial
    mov %eax, %edi
    mov $SYS_EXIT, %eax
    syscall

.type factorial @function
factorial:

    # if it is the base case, return 1 and exit
    cmp $1, %edi
    jne _factorial
    mov $1, %eax
    ret

_factorial:
    # if not the base case, set up the stack frame
    push %rbp
    mov %rsp, %rbp

    push %rdi    # move the current value or n to the stack,
    dec %rdi     # so we can pop it later and multiple by the factorial(n-1) function
    call factorial
    pop %rbx
    mul %rbx    # multiples eax (return of factorial) by previoud rdi (n)

    # clean up the stack frame
    mov %rbp, %rsp
    pop %rbp
    ret

Here is an example output:

$ as factorial.s -o factorial.o && ld factorial.o -o factorial && ./factorial; echo $?
24

How does the program look? Any feedback would be greatly appreciated!

Input Handling
At least at first glance, it looks like this doesn't handle the factorial of zero correctly. 0! is equal to 1, so fixing it is pretty trivial, by changing jne _factorial to ja _factorial:
# if it is the base case, return 1 and exit
cmp $1, %edi
ja _factorial
mov $1, %eax
ret

Since factorial isn't (at least normally) defined for negative numbers, I've treated the input as unsigned. If you want to treat it as signed, you'd use jg instead of ja.
Register Usage
mul produces a result in edx:eax, not just in eax, so you normally want to clear edx before you start doing your multiplications.
Stack Frame
I would rewrite the function a bit to use an internal function for the recursion. That internal function would use a purely register-based calling convention to avoid setting up a stack frame for every invocation.
Using Intel syntax, I'd write the code something on this general order:
; when first called, input value in edi
; and edx:eax containing 0:1
; result: factorial in edx:eax
;
internal_factorial:
    mul eax, edi
    sub edi, 1
    jz  done
    call internal_factorial
done:
    ret

Then the main routine would be something on this general order:
factorial:
    mov eax, 1    ; prepare our 64-bit result value in edx:eax
    xor edx, edx
    cmp edi, eax  ; check for (either) base case
    jbe do_ret    ; if it's not a base case, compute the factorial
    call internal_factorial
do_ret:
    ret


Guess the number game using jupyter notebook I made a number guessing game in Python 3 using jupyter notebook. I would appreciate it a lot if I could get some feedback on my code.

from random import randint
randnumb = randint(1,100)
guesses = 0
maxGuesses = 5

while guesses < maxGuesses:
    personInput = int(input('What is your guess? '))
    guesses = guesses + 1

    if personInput == randnumb:
        print()
        print('You won! It took you', guesses, 'guess(es)!')
        break

    if personInput > randnumb and guesses != maxGuesses:
        print('Guess lower', '(', maxGuesses - guesses,'guess(es) left)')
        print()

    if personInput < randnumb and guesses != maxGuesses:
        print('Guess higher', '(', maxGuesses - guesses,'guess(es) left)')
        print()

    if guesses == maxGuesses and personInput != randnumb:
        print()
        print('You lost! You ran out of your guesses!')
        print('The answer was', randnumb, '!')

Pretty clean looking code, but let's look at a few ways it could be better or more pythonic:

Use elif statements:

if personInput == randnumb:
    # ...
elif personInput > randnumb:  # You already know they're != at this point
    # ...
elif ...

Use snake case for your variable names. E.g., use person_input instead of personInput (which is camel case), and rand_num instead of randnumb. In that second case, it's also more common to shorten "number" to "num" instead of "numb".
Use format strings instead of print's argument concatenation, e.g.:

print("Guess lower ({} guesses left)".format(max_guesses - guesses))

Check for and handle errors:

try:
    person_input = int(input("What is your guess? "))
except ValueError:
    print("Not sure what you meant by that, please input an integer")
    continue

I prefer to be more safe than sorry when handling my own incrementor, such as guesses, just in case I do something funky that lets it skip over max_guesses:

# Since you "break" on correct answer, we don't need to check that again
if guesses >= max_guesses:
    # ...

EDIT:

One more thing. In Python, to write a script (rather than a module), you should check if __name__ == '__main__': as follows:

from random import randint

def main():
    randnumb = randint(1,100)
    guesses = 0
    maxGuesses = 5

    while guesses < maxGuesses:
        # ...

if __name__ == '__main__':
    main()

This allows for safe code re-use, and makes sure that the code doesn't get run if this file gets imported from another file. It's not technically necessary for a one-file script like you're writing here, but it's a good practice to get into anyway.


Finding columns of a matrix that are the same for combinations of events How I can change this multi-loop to reduce the computation time?

A is a matrix (5 × 10000) where the fifth line contains values between 1 and 50 corresponding to different events of an experiment. My goal is to find the columns of the matrix which are the same for all possible combinations of 7 different events.

data = A(1:4,:);
exptEvents = A(5,:);

% Find repeats
[b,i,j] = unique(data', 'rows');

% Organize the indices of the repeated columns into a cell array
reps = arrayfun(@(x) find(j==x), 1:length(i), 'UniformOutput', false);

% Find events corresponding to these repeats
reps_Events = cellfun(@(x) exptEvents(x), reps, 'UniformOutput', false);

U = cellfun(@unique, reps_Events, 'UniformOutput', false);
repeat_counts = cellfun(@length, U);

kk=1;

for i1=1:50
    for i2=1:50
        for i3=1:50
            for i4=1:50
                for i5=1:50
                    for i6=1:50
                        for i7=1:50
                            if i1~=i2 && i2~=i3 && i3~=i4 && i4~=i5 && i5~=i6 && i6~=i7
                               myEvents = [i1 i2 i3 i4 i5 i6 i7];
                               v= b(cellfun(@(x)all(ismember(myEvents,x)),U),:);
                               intersection(1,kk)=v(1);
                               intersection(2,kk)=v(2);
                               intersection(3,kk)=v(3);
                               intersection(4,kk)=v(4);
                               intersection(5,kk)=i1;
                               intersection(6,kk)=i2;
                               intersection(7,kk)=i3;
                               intersection(8,kk)=i4;
                               intersection(9,kk)=i5;
                               intersection(10,kk)=i6;
                               intersection(11,kk)=i7;
                               kk=kk+1;
                            end
                        end
                    end
                end
            end
        end
    end
end

There's quite a few things that you can do to reduce computation time.

First of all, if you know that an outcome has to be the combination of seven events, you can throw out whatever has fewer of them.

Then, you can preassign the output array (growing in a loop is usually not very fast).

Finally, you want to generate all possible subsets if there are, say, 9 events from which you can choose 7.

So you'd start

%# throw out useless stuff
tooFewIdx = repeat_counts < 7;

b(tooFewIdx,:) = [];
U(tooFewIdx) = [];
repeat_counts(tooFewIdx) = [];

%# estimate how many combinations you will get
nPerms = arrayfun(@(x)nchoosek(x,7),repeat_counts);

intIdx = [0;cumsum(nPerms(:))];

%# pre-assign output
%# If this runs out of memory, try using integer formats
%# instead, e.g. zeros(...,'uint8') if no value is above 255
intersection = zeros(intIdx(end),11);

%# loop to fill intersection
for i=1:length(U)

%# fill in the experiment information
intersection((intIdx(i)+1):intIdx(i+1),1:4) = repmat(b(i,:),nPerms(i),1);

%# add all combinations of events
intersection((intIdx(i)+1):intIdx(i+1),5:11) = combnk(U{i},7);

end