Playing “craps” for the win v0.2 Continued from Playing "craps" for the win

  You roll two dice. Each die has six faces, which contain one, two,
  three, four, five and six spots, respectively. After the dice have
  come to rest, the sum of the spots on the two upward faces is
  calculated. If the sum is 7 or 11 on the first throw, you win. If the
  sum is 2, 3 or 12 on the first throw (called “craps”), you lose (i.e.,
  the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first
  throw, that sum becomes your “point.” To win, you must continue
  rolling the dice until you “make your point” (i.e., roll that same
  point value). You lose by rolling a 7 before making your point.

// Craps.java

package co.vu.xxx.craps;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.Scanner;

public class Craps {
    private int point;
    public static enum possibleResults {UNDEFINED, WIN, LOSE};
    protected possibleResults gameResult;
    private String cause;
    private static SecureRandom randomNumbers = new SecureRandom();

    public Craps() {
        gameResult = possibleResults.UNDEFINED;
    }

    public static int rollDice() {
        int randN = 2 + randomNumbers.nextInt(6) + randomNumbers.nextInt(6);
        System.out.printf("Rolling dice... You got %d%n", randN);
        return randN;
    }

    public void firstRoll() throws IOException {
        waitUser();
        int tmp = rollDice();
        switch (tmp) {
            case 7:case  11:
                gameResult = possibleResults.WIN;
                cause= String.format("you have got a lucky number in the first round: %d.", tmp);
                break;
            case 2:case 3:case 12:
                gameResult = possibleResults.LOSE;
                cause= String.format("you have got an unlucky number in the first round: %d.", tmp);
                break;
            default:
                point = tmp;
        }
    }

    public void declareResult() {
        if(point != 0) {
            System.out.printf("You need to make your point: %d%n", point);
        }
        switch (gameResult) {
            case LOSE:
                System.out.printf("You have lost, because %s%n", cause);
                break;
            case WIN:
                System.out.printf("You have won, because %s%n", cause);
                break;
            case UNDEFINED:
                System.out.println("Game continues...\n");
                break;
        }
        System.out.println();
    }

    public void moreRolls() {
        waitUser();
        int tmp = rollDice();
        if(tmp == point) {
            gameResult = possibleResults.WIN;
            cause = "you have made your point!";
        } else if(tmp == 7) {
            gameResult = possibleResults.LOSE;
            cause = "you have hit 7 before making your point.";
        }
    }

    private void waitUser() {
        Scanner inputScan = new Scanner(System.in);
        System.out.print("Press enter to start rolling: ");
        String input = inputScan.nextLine();
    }
}

// UseCraps.java

package co.vu.xxx.craps;

import java.io.IOException;

public class UseCraps {
    public static void main(String[] args) throws IOException {
        Craps crapObj = new Craps();
        crapObj.firstRoll();
        crapObj.declareResult();
        while(crapObj.gameResult == Craps.possibleResults.UNDEFINED) {
            crapObj.moreRolls();
            crapObj.declareResult();
        }
    }
}

At a glance, the code looks reasonably good.

Either initialize everything in the constructor:

protected possibleResults gameResult;
private static SecureRandom randomNumbers;

public Craps() {
    this.gameResult = possibleResults.UNDEFINED;
    this.randomNumbers = new SecureRandom();
}

… or get rid of the constructor completely (it is implicit):

protected possibleResults gameResult = possibleResults.UNDEFINED;
private static SecureRandom randomNumbers = new SecureRandom();

There is a curious mix of private and protected members.  Why?  I suggest making them all private unless you see a need to expose them.

The gameResult member should be made private; other classes should have to call a public method getResult() to retrieve it.  That prevents other code from setting the gameResult.

As an enum, possibleResults should follow the naming conventions for classes (beginning with a capital letter).  I suggest shortening the name to

public static enum Outcome { UNDEFINED, WIN, LOSE };

Putting it as the first thing in the Craps class would be good, so as to avoid interrupting the class definition with an enum definition.


Better way for securing direct access to php files I don't know if this method uses a lot of time to process, or if it is bad but I wanted to know if there is any better way of actually doing this? I have a few class files that I want to stop users viewing through the browser, and only allowing them to view it if actually load it from the index.php

So I have this nice little piece of code.

In my index.php I have:

define("SECURE", true);

And I check if it has been defined in class files using

defined("SECURE") or exit('Please define variable SECURE to continue.');

So when they visit class files it actually blocks them from viewing it unless they have loaded index.php first.

Any better way?

Your approach seems good to me.

You can find some alternatives here, but most have downsides (not every server parses htaccess files, get_included_files is self-contained but works differently for different PHP versions, etc).

Additionally, you should think about moving everything outside the web-root that should not be accessible directly.

You might also want to rethink how you handle the error. Using an imperative in the error message gives the impression that the user can fix the error, which they can't. This might confuse legitimate users that accidentally accessed the script. So instead of Please do X, something like You can't access X would be better.

Ideally, you would handle the case of accessing an existing but forbidden PHP file exactly like a non-existing PHP file is handled (for example by showing a custom 404 error page).

And lastly, SECURE isn't that great of a name, as it's very generic. Something like IS_INCLUDED, NO_DIRECT_SCRIPT_ACCESS, or similar might be better.


Print 2 double arrrays, the second one should be cumulative totals of the elements of the first array Please tell me how bad is the code...in the book he said it's possible with either nested loop, or 1 loop

The user should provide the 8 double numbers for the program to set the cumulative totals in the second array.

This is the code:

#include <stdio.h>
#define ASIZE 8

int main()

{
    int index = 0, x, index2;
    double cal;
    double array1[ASIZE], array2[ASIZE];

    printf("Please enter 8 numbers:\n");
    for (index = 0; index < ASIZE; index++)//adding the numbers to the first array
    {
        scanf("%lf", &array1[index]);
    }

    for (x = 0,index2 = 0,index = 0; x < ASIZE; x++, index2++)//adding the second array the elements
    {
        cal += array1[index++];
        array2[index2] = cal;
    }

    printf("the first array numbers are:\n");//printing the first array numbers
    for (index = 0; index < ASIZE; index++)
    {
        printf("%.1lf ", array1[index]);
    }
    printf("\n");
    printf("\n");
    printf("the second array numbers are:\n");//printing the second array
    for (index2 = 0; index2 < ASIZE; index2++)
    {
        printf("%.1lf ", array2[index2]);
    }

}

I'm a beginner in C, and its important for me to know how to get better.

About the only thing I would change is this loop

for (x = 0,index2 = 0,index = 0; x < ASIZE; x++, index2++)//adding the second array the elements
{
    cal += array1[index++];
    array2[index2] = cal;
}

You don't need x (its really index1. As all the variables are tracking each other you don't need index2 as index1 is the same value each iteration (and allways do the increment in the for() loop.

The only bug I see is the cal is not initialized to zero and can thus have an indeterminate value.

I would have written it like this:

cal = 0.0;
for (index = 0; index < ASIZE; index++)//adding the second array the elements
{
    cal += array1[index];
    array2[index] = cal;
}

A minor note:

As the code may be changed to have bigger arrays by modifying ASIZE. I would make the user instructions reflect this automaically.

printf("Please enter 8 numbers:\n");

// Try:

printf("Please enter %d numbers:\n", ASIZE);


Matlab any function in C / C++ Due to software constraints, I cannot use the standard libraries, math.h, algorithm, templates, inline, or boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.

I need to duplicate the Matlab any function in C / C++ for an array. I currently have written two any functions with different inputs depending on the array size.

Is it possible to write just one any function without using templates?
How can I improve performance?

I am striving for const correctness, performance/efficiency, and avoiding implicit type casting.

bool any(bool* array, const int N){
    // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
    bool val;
    val = array[0] == true;
    int i = 0;
    while (val == false && i < N){
        val = array[i++] == true;
    }
    return val;
}

bool any(bool** array, const int nRow, const int nCol){
    // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
    bool val;
    val = array[0][0] == true;
    int i = 0;
    while (i < nRow && val == false){
        int j = 0;
        while (j < nCol && val == false){
            val = array[i][j++] == true;
        }
        i++;
    }
    return val;
}

I would suggest having the 2D implementation call the 1D implementation, rather than duplicating the "any" logic in both implementations, e.g.

bool any(bool** array, const int nRow, const int nCol){
    // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
    bool val = false;

    for (int i = 0; i < nRow && val == false; ++i)
    {
        val = any(array[i], nCol); // call 1D version of any
    )
    return val;
}


Returning search results based off checkboxes I use the following code to filter data from SQL and it works fine. However, below code is vulnerable to SQL injection, but all the $post values are checkbox value (it's not user input).  So can I use below code?

Or do I need to use "prepared statement" as per this answer? I can only send number in array.

Conn.php

    try {

    //create PDO connection
    $conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
    //show error
    echo '
' . $e->getMessage() . '
';
    exit;
}

INDEX

     <input type="radio" class="filter_all cate" name="cate" id="car" value="Car">
     Car

script

$(document).ready(function () {
            filter_data();
            function filter_data() {
                $('.filter_data');
                var action = 'fetch_data';
                var cate = get_filter('cate');
                $.ajax({
                    url: "fetch.php",
                    method: "POST",
                    data: {
                        action: action,
                        cate: cate
                    },
                    success: function (data) {
                        $('.filter_data').html(data);
                    }
                });
            }
            function get_filter(class_name) {
                var filter = [];
                $('.' + class_name + ':checked').each(function () {
                    filter.push($(this).val());
                });
                return filter;
            }
            $('.filter_all').click(function () {
                filter_data();
            });
        });

fetch.php

if (isset($_POST["action"])) {

 $query = "SELECT * FROM allpostdata WHERE sts = '1'";

if (isset($_POST["cate"])) {
    $cate = implode("','", $_POST["cate"]);
    $query .= "AND sca IN('" . $cate . "')";
}

$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
    foreach ($result as $row) {
    $output .= '' . $row['link']. '
 }
} else {
    $output = '
No Data Found
';
}
echo $output;
}

Applying YCS's tutorial can't be dumbed down any further, so I suppose I'll write it out.

if (isset($_POST["action"])) {
    $query = "SELECT link FROM allpostdata WHERE sts = '1'";

    if (!empty($_POST["cate"])) {
        $query .= " AND sca IN (" . str_repeat("?,", count($_POST["cate"]) - 1) . "?)";
    } else {
        $_POST["cate"] = []; // in case it is not set
    }

    $stmt = $conn->prepare($query);
    $stmt->execute($_POST["cate"]);
    $result = $stmt->fetchAll();
    if (!$result) {
        exit('
No Data Found
');
    }
    foreach ($result as $row) {
        echo "{$row['link']}";
    }
}

I assume this will display your links side by side.  You may want to style them a bit to position the links in a user friendly fashion.

Additionally, $('.filter_data'); is doing nothing and can be removed.

I'd probably change the filter_data() declaration to something more brief:

function filter_data() {
    $.post(
       "fetch.php",
       {action: 'fetch_data', cate: get_filter('cate')}
    )
    .done(function(data) {
        $('.filter_data').html(data);
    });
}


I want to get rid of unneccessary repetiton of cycles I have a code that should read diameters of barrels from a txt file. If a barrel is smaller than the last one, smaller gets put inside bigger one. One package like that is lied on a stack. at the end, code should give out how many stacks we get and how many barrels were in a file. also sum of diameters.
If one number is repeated 3 times, we get 3 stack, if we have 5 repeating nmbers, then 5.
What can I do that I wouldn´t have to write simillar blocks n times.
using System;
using System.Collections.Generic;
using System.IO;

namespace TaaviSimsonTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TextReader reader = File.OpenText("C:\\temp\\andmed2"))
            {
                int sum = 0;
                string line = string.Empty;
                List<int> numbersList = new List<int>();
                while ((line = reader.ReadLine()) != null)
                {
                    int i = int.Parse(line);
                    sum += i;
                    numbersList.Add(int.Parse(line));
                }
                int[] numbersListArray = numbersList.ToArray();
                int numberOfStacks = numbersListArray.Length;
                //Max number of stacks equals to inital array length

                Array.Sort(numbersListArray);       //Array is ascending orded
                Array.Reverse(numbersListArray);    //Array in descending order

                //Puts smaller barrels inside bigger. Decreases number of stacks.
                List<int> repeatedBrarrelSizes = new List<int>();
                for (int j = 0; j < (numbersListArray.Length - 1); j++)
                {
                    if (numbersListArray[j] > numbersListArray[j + 1])
                    {
                        numberOfStacks--;
                    }
                    else if (numbersListArray[j] == numbersListArray[j + 1])
                    {
                        repeatedBrarrelSizes.Add(numbersListArray[j + 1]);
                    }
                }
                int[] repeatedBarrelSizesArray = repeatedBrarrelSizes.ToArray();

                //Repeats the cycle with repeating numbers
                List<int> repeatedBarrelSizes2 = new List<int>();
                for (int k = 0; k < (repeatedBarrelSizesArray.Length-1); k++)
                {
                    if (repeatedBarrelSizesArray[k] > repeatedBarrelSizesArray[k+1])
                    {
                        numberOfStacks--;
                    }
                    else if (repeatedBarrelSizesArray[k] == repeatedBarrelSizesArray[k + 1])
                    {
                        repeatedBarrelSizes2.Add(repeatedBarrelSizesArray[k + 1]);
                    }
                }
                int[] repeatedBarrelSizes2Array = repeatedBarrelSizes2.ToArray();

                //Repeats the cycle again, until no barrels left
                List<int> repeatedBarrelSizes3 = new List<int>();
                for (int k = 0; k < (repeatedBarrelSizes2Array.Length - 1); k++)
                {
                    if (repeatedBarrelSizes2Array[k] > repeatedBarrelSizes2Array[k + 1])
                    {
                        numberOfStacks--;
                    }
                    else if (repeatedBarrelSizes2Array[k] == repeatedBarrelSizes2Array[k + 1])
                    {
                        repeatedBarrelSizes3.Add(repeatedBarrelSizes2Array[k + 1]);
                    }
                }
                int[] repeatedBarrelSizes3Array = repeatedBarrelSizes3.ToArray();

                foreach (int value in repeatedBarrelSizes3Array)
                {
                    Console.WriteLine(value + " ");
                }

                Console.WriteLine("Sum: " + sum);
                Console.WriteLine("Number of barrels: " + numbersListArray.Length);
                Console.WriteLine("Stacks: " + numberOfStacks);
            }
        }
    }
}

DRY = Don't Repeat Yourself.
If you have repeating parts of code, something went wrong then. Also you may use Linq.
Consider this example.
static void Main(string[] args)
{
    string[] lines = File.ReadAllLines(@"C:\temp\andmed2");
    List<int> numbersList = lines.Select(line => int.Parse(line)).OrderByDescending(x => x).ToList();
    int sum = numbersList.Aggregate(0, (x, y) => x + y);
    int numberOfStacks = numbersList.Count;

    List<int> repeatedBarrelSizes = numbersList;
    int count;
    do
    {
        count = 0;
        List<int> result = new List<int>();
        for (int i = 0; i < repeatedBarrelSizes.Count - 1; i++)
        {
            if (repeatedBarrelSizes[i] > repeatedBarrelSizes[i + 1])
                count++;
            else if (repeatedBarrelSizes[i] == repeatedBarrelSizes[i + 1])
                result.Add(repeatedBarrelSizes[i + 1]);
        }
        repeatedBarrelSizes = result;
        numberOfStacks -= count;
    } while (count > 0);

    Console.WriteLine(string.Join(" ", repeatedBarrelSizes));

    Console.WriteLine("Sum: " + sum);
    Console.WriteLine("Number of barrels: " + numbersList.Count);
    Console.WriteLine("Stacks: " + numberOfStacks);
}

I'm sorry but I can't test it because I have no source file with numbers to compare the results.
Total: two loops.


Modified Coupon Collector's Problem in Java What is Coupon Collector's Problem?

  In probability theory, the coupon collector's problem describes the "collect all coupons and win" contests. It asks the following question: Suppose that there is an urn of n different coupons, from which coupons are being collected, equally likely, with replacement. What is the probability that more than t sample trials are needed to collect all n coupons? An alternative statement is: Given n coupons, how many coupons do you expect you need to draw with replacement before having drawn each coupon at least once? from here.

What is my Modified Coupon Collector's Problem?

  Instead of "at least once", I check for "at least 2 times".

I loop for a crore times. I should get \$14.7,24.134\$. My code returns \$14.760683\$ and \$23.83069\$. Fairly correct. Maybe Java is not so randomly accurate?

Here's is my code:

package test;

import java.util.ArrayList;
import java.util.Random;

public class CouponCollector {
private static final int mMaxCouponNumber = 6;
private static final int mMinCouponNumber = 1;
private static final int EXPERIMENT_REPETITIONS = 10000000;
private static final int EACH_COUPONS_ATLEAST_OCCURENCE = 2;

public static void main(String args[]) {
    float mSumOfDraws = 0;
    for (int i = 1; i <= EXPERIMENT_REPETITIONS; i++) {
        ArrayList<Integer> mCouponList = new ArrayList<Integer>();
        int mDrawsRequired = 0;
        do {
            mCouponList.add(new Random()
                    .nextInt((mMaxCouponNumber - mMinCouponNumber) + 1)
                    + mMinCouponNumber);
            // DEBUG System.out.println("Added: " +
            // mCouponList.get(mDrawsRequired));
            ++mDrawsRequired;
            if (allCouponsCollected(mCouponList)) {
                break;
            }
        } while (true);
        if(i%10000==0){
            // Enable this if you are too impatient! :D
            //DEBUG System.out.println("Process: "+(((float)i)*100/EXPERIMENT_REPETITIONS)+"% complete.");
        }
        mSumOfDraws += mDrawsRequired;
        // DEBUG System.out.println("Draws required in " + i
        // + " st/nd/rd/th trial is " + mDrawsRequired);
    }
    System.out.println("Average value of draws required is "
            + (mSumOfDraws / EXPERIMENT_REPETITIONS));
}

private static boolean allCouponsCollected(ArrayList<Integer> pCouponList) {
    int[] mCouponCount = new int[mMaxCouponNumber - mMinCouponNumber + 1];
    for (int i = 0; i < pCouponList.size(); i++) {
        ++mCouponCount[pCouponList.get(i) - 1];
        // DEBUG System.out.println("Count of " + pCouponList.get(i) +
        // " is " + mCouponCount[pCouponList.get(i) - 1]);
    }
    for (int i = 0; i < mCouponCount.length; i++) {
        if (mCouponCount[i] < EACH_COUPONS_ATLEAST_OCCURENCE) {
            return false;
        }
    }
    return true;
}
}

The deviation you see from the expected results is probably in large part due to the poor use of Random. When I time your code, I get:

Average value of draws required is 23.832188
Complete in 23473.917s

If I use Random the way it should be (re)used, and convert this code:

        mCouponList.add(new Random()
                .nextInt((mMaxCouponNumber - mMinCouponNumber) + 1)
                + mMinCouponNumber);

to be:

private static final Random RANDOM = new Random();

....

            mCouponList.add(RANDOM
                    .nextInt((mMaxCouponNumber - mMinCouponNumber) + 1)
                    + mMinCouponNumber);

it completes in half the time:

Average value of draws required is 23.827381
Complete in 11552.228s

Hmm.. I was expecting this to correct the errors in the 'randomness' too, but, now I see the problem there.... you are using float, and not double. Float has relatively low accuracy. If I change this line here:

float mSumOfDraws = 0;

to be:

double mSumOfDraws = 0;

My results become:

Average value of draws required is 24.1312123

That's much closer to the mathematical expectation.

Now, about performance... your code is really slow. There's four prime reasons:

there's no need to record every draw you make in an ArrayList - it will grow large, and require garbage collection. You only need to count how many times you 'pull' each coupon.
there is no need to number the coupons from minimum to maximum - you just need to know how many there are.
You use Integer values instead of int primitives.
You have too much code in your main method - the main method is hard for the compiler to optimize - it is only ever called once.

Additionally, apart from the performance, the code style is... unconventional. You should parameterize a lot of the static values so that you can reuse the code better too.

Here is the results of my simplified code:

Average for 2 sets of 6 coupons is 24.131
Complete in 3.983s

(compared to your results with the improved Random, and double):

Average value of draws required is 24.1291875
Complete in 11.109s

The code I use is:

import java.util.Arrays;
import java.util.Random;

public class CouponClipper {

    private final int[] counts;
    private int remaining;

    public CouponClipper(int couponCount, int sets) {
        this.counts = new int[couponCount];
        Arrays.fill(counts, sets);
        this.remaining = couponCount;
    }

    public boolean pull(int coupon) {
        if (--counts[coupon] == 0) {
            remaining--;
        }
        return remaining == 0;
    }

    private static final Random RANDOM = new Random();

    public static int countRequired(int coupons, int sets) {
        CouponClipper clipper = new CouponClipper(coupons, sets);
        int count = 0;
        do {
            count++;
        } while (!clipper.pull(RANDOM.nextInt(coupons)));
        return count;
    }

    public static double averageCounts(int coupons, int sets, int iterations) {
        long sum = 0;
        for (int i = 0; i < iterations; i++) {
            sum += countRequired(coupons, sets);
        }
        return sum / (double)iterations;
    }

    public static void main(String[] args) {
        long nanos = System.nanoTime();
        System.out.printf("Average for 2 sets of 6 coupons is %.3f\n", averageCounts(6, 2, 10000000));
        nanos = System.nanoTime() - nanos;
        System.out.printf("Complete in %.3fs\n", nanos / 1000000000.0);

    }

}


Creating chunks of HTML with jQuery I am working on an online ordering form and am looking for some advice about my jQuery.  I am re-developing the code base for this ordering form and improving what was created by a web design group years ago.  The existing form uses Javascript to dynamically generate a new line of item information when the starts typing in the form.  Reviewing the existing code there is close to 100 lines of JS (many being DOM manipulations) to add the HTML elements and so forth.  I could redo it in JS no problem, but I would like to reduce this amount of code and convert the solution to jQuery. It is already in use for other parts of the site so I may as well utilize it.

I've written a function to facilitate this that I am toying around with to get the functionality down.

function createNewRow() {
    //createNewRow.rc = 1;
    if(typeof createNewRow.rc == 'undefined') {
        createNewRow.rc = 1;
    }
    //Select the existing parent div
    var div = $('div#div');
    //Create a child div (container to the form elements)
    var cell = $('

');
    //Create "cells" (really divs) and form elements

    itemQty = $('

');
    itemQty.append('
Quantity
')
           .append('<input type="text" size="5" class="inputbox" name="ooItem[' + createNewRow.rc + '][qty]" id="' + createNewRow.rc + '" />');

    itemUnit = $('

');
    itemUnit.append('
UOM
');
    unitSlct = $('<select name="ooItem[' + createNewRow.rc + '][unit]"></select>');
    unitSlct.append('<option value="pc">PCS</option>')
            .append('<option value="sq">SQ</option>')
            .append('<option value="lf">LF</option>')
            .append('<option value="ea">EA</option>');
    itemUnit.append(unitSlct);

    itemDesc = $('

');
    itemDesc.append('
Description
')
            .append('<input type="text" class="inputbox" name="ooItem[' + createNewRow.rc +'][description]" />');

    itemColor = $('

');
    itemColor.append('
Color
')
             .append('<input type="text" class="inputbox" name="ooItem[' + createNewRow.rc +'][color]" />');

    itemText = $('
');
    itemText.append('
Texture
');
    textSlct = $('<select class="inputbox" name="ooItem[' + createNewRow.rc +'][texture]"></select>');
    textSlct.append('<option value="rough">Rough</option>')
            .append('<option value="smooth">Smooth</option>');
    itemText.append(textSlct);

    cell.append(itemQty)
        .append(itemUnit)
        .append(itemDesc)
        .append(itemColor)
        .append(itemText);

    //Append child div to the parent div
    div.append(cell);
    //Increase the row count
    createNewRow.rc++;
}

JSFiddle is here: http://jsfiddle.net/McFRV/3/

From a functionality standoint this works fine.  HTML rows are created as I like (minus the presentation layer of course) and the form information passes to the webserver correctly with all the information in the right places.  What is bugging me a bit is how "dirty" this code appears to me.  It seems as if using jQuery to make all that HTML in a bunch of strings is uncanny. Is there a better way to create chunks of HTML other than how I am going about it, or am I simply stressing about nothing?

You could always clean it up using jQuery tmpl

https://github.com/BorisMoore/jquery-tmpl

You would just define the HTML of the templates, and then you could add them to the rows.


Implement a graph in Python Question : Build a graph in python, given its edge representation.

from collections import defaultdict

graph = { '1' : ['2' ,'4','5'],
          '2' : ['3'] ,
          '3' : ['5'] ,
          '4' : ['2']
          }

def generate_edges(graph):
    edges = []

    for node in graph:
        for next_node in graph[node]:
            #if edge exist than append
            edges.append((node,next_node))
    return edges

def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path

        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath:
                    return newpath
        return None

print generate_edges(graph)

print find_path(graph, '1','5')

How can i improve this code?

find_path is very inefficient. Consider the following example, where we try to find a short path (just one edge) in a graph with just eleven nodes:

>>> G = {i: list(range(10)) for i in range(10)}
>>> G[0].append(10)
>>> find_path(G, 0, 10)
[0, 10]

How long does this take?

>>> from timeit import timeit
>>> timeit(lambda:find_path(G, 0, 10), number=1)
1.3475657280068845

It really shouldn't take more than a second to find a path with a single edge in such a small graph. So why does it take so long?

The way that find_path works is that it generates all simple paths (paths with no repeated nodes) in depth-first order. However, in general there can be exponentially many simple paths in a graph. I constructed the graph G so that it looks like this:

The depth-first search starts by finding the path 0–1–2–3–4–5–6–7–8–9 but then it reaches a dead end:

So the search backtracks a couple of steps and then finds the path 0–1–2–3–4–5–6–7–9–8, but again it reaches a dead end:

You can see that the search will have to visit every path starting with 0 and visiting all of 1 to 9, before it will consider the path 0–10. But there are \$9! = 362,880\$ such paths.

To avoid this exponential runtime, you'll have to use a different approach, for example Dijkstra's algorithm.


Determining if integers are sorted I have this task to find whether 5 integers are ordered from the smallest to the largest or not.

Depending on the results, the program output should be "yes" or "no". No loops or arrays supposed to be used (according to the task).
This is my solution, but it's 4 lines longer. Can anyone help me make this better?

int main() {
    int a, b, c, d, e;

    scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);

    if ( a < b && b < c ) {
        if ( c < d && d < e ) {
            printf("yes");
        } else {
            printf("no");
        }
    } else {
        printf("no");
    }

    return 0;
}

Hint: think about whether you can combine the two if statements into one.


Possible redundant code improvement first here is the code:

Part 1
    $('#monhpf').keyup(function()
    {
        /* General variable(s) */
        var monhpf = $('#monhpf').val();

        if(monhpf=="")
        {
            $('#monhpf').css('border-color',red);
            $('.mondayErrors').text(emptyField).show();
        }else
        if(monhpf.length > 0)
        {
            /* Verifies the charset of the zip code */
            $.post('functions/hoursCharset.php',{hoursPHP:monhpf},function(hoursCharset)
            {
                if(hoursCharset==true)
                {
                    /* Charset valid*/
                    $('#monhpf').css('border-color',green);
                    $('.mondayErrors').hide();
                    mondayErrors = false;
                }else
                {
                    /* Charset not valid */
                    $('#monhpf').css('border-color',orange);
                    $('.mondayErrors').text(invalid).show();
                    mondayErrors = true;
                }
            });
        }
    });
Part 2
    $('#monmpf').keyup(function()
    {
        /* General variable(s) */
        var monmpf = $('#monmpf').val();

        if(monmpf=="")
        {
            $('#monmpf').css('border-color',red);
            $('.mondayErrors').text(emptyField).show();
        }else
        if(monmpf.length > 0)
        {
            /* Verifies the charset of the zip code */
            $.post('functions/minutesCharset.php',{minutesPHP:monmpf},function(minutesCharset)
            {
                if(minutesCharset==true)
                {
                    /* Charset valid*/
                    $('#monmpf').css('border-color',green);
                    $('.mondayErrors').hide();
                    mondayErrors = false;
                }else
                {
                    /* Charset not valid */
                    $('#monmpf').css('border-color',orange);
                    $('.mondayErrors').text(invalid).show();
                    mondayErrors = true;
                }
            });
        }
    });

As you can see part 1 and part 2 are pretty much the same except for the #monhpf and #monmpf variables. My question is, how can I improve this code to be smaller? Like in a single function for example.

1)

Take advantage of javascript's truthy and falsey values.

Boolean(undefined); // => false
Boolean(null); // => false
Boolean(false); // => false
Boolean(0); // => false
Boolean(""); // => false
Boolean(NaN); // => false

Boolean(1); // => true
Boolean([1,2,3]); // => true
Boolean(function(){}); // => true

More here: http://james.padolsey.com/javascript/truthy-falsey/

if(monmpf == "") => if(!monmpf).

if(minutesCharset == true) => if(minutesCharset)

if(monhpf.length > 0) => if( monhpf.length )

2)

You can refer to the current element by using $(this).

$('#monmpf').keyup(function () {
// el refers to $("monmpf")
var el = $(this);

3)

if (monhpf.length > 0) is redundant since you already checked the string value with this, if(monmpf == "").

4)

You're using too many global variables, such as emptyField, invalid, green, red, orange, etc.
Try wrapping the variables inside a meaningful namespace, like

var COLORS = { red: "red", green: "green" };
var MESSAGE = { invalid: "Wrong", emptyField: "" };

5)

mondayErrors? I think you should rename this variable.

6)

Break up functions that are longer than 8-12 lines of code into smaller ones.

With all that said, here's what I came up with.

var getRequestObject = function (name, value) {
    var obj = {};
    switch (name) {
        case "monhpf":
            obj.url = 'functions/hoursCharset.php';
            obj.paramObj = {
                hoursPHP : value
            };
            break;
        case "monmpf":
            obj.url = 'functions/minutesCharset.php';
            obj.paramObj = {
                minutesPHP : value
            };
            break;
    }
    return obj;
};
var getPostFunc = function ($el) {
    return function (isCharset) {
        mondayErrors = !isCharset;
        if (isCharset) {
            $el.css('border-color', green);
            $('.mondayErrors').hide();
        } else {
            $el.css('border-color', orange);
            $('.mondayErrors').text(invalid).show();
        }
    };
};
$('#monhpf, #monmpf').keyup(function () {
    var $el = $(this),
        request,
        value = $el.val(),
        id = $el.attr('id');

    if (value) {
        request = getRequestObject(id, value);
        $.post(request.url, request.paramObj, getPostFunc($el));
    } else {
        $el.css('border-color', red);
        $('.mondayErrors').text(emptyField).show();
    }
});


Creating and sending two kinds of notification messages I wish to get rid of using switch case with statuses twice in my code. But create_message function will be bigger in the future, so must stay and I don't want to create messages in send_user_push_notification directly.

Any ideas?

def send_user_push_notification(order, parse_events)
  now = Time.zone.now
  case parse_events
  when 'pending'
    if send_push_notification(order.shopper_id, order, parse_events)
      order.shopper_notified_at = now
    end
  when 'handed_over'
    if send_push_notification(order.deliverer_id, order, parse_events)
      order.deliverer_notified_at = now
    end
  end
end

def send_push_notification(user_id, order, parse_events)
  Parse.publish_order_status(
    user_id,
    *parse_events,
    create_message(order, parse_events)
  )
end

def create_message(order, parse_events)
  case parse_events
  when 'pending'
    I18n.t('orders.shopper.message')
  when 'handed_over'
    I18n.t(
      'orders.deliverer.message',
       order_id: order.order_id,
       store_id: order.store_id
    )
  end
end

You could split the two decisions, for instance:

# Outside your method
EVENT_TO_USERKIND = { pending: 'shopper', handed_over: :'deliverer' }

# Now inside your method
user_kind = EVENT_TO_UID_METHOD[parse_events]
if user_kind && send_push_notification(order.send("#{user_kind}_id"), order, parse_events)
  order.send("#{user_kind}_notified_at=", now)
end

It's more compact and concise, but the usage of send might be considered ugly, and it depends on naming convention (do not dare to rename deliverer_notified_at to delivery_guy_notified_at!), so you have to choose whether or not you like it.


Bash script to truncate subject line of incoming email I'm going to put this script into production in a mail server /etc/aliases file: we have a system that receives email but the subject line must be limited to a certain size. The proposed usage in the aliases file:

alias_name: "| email_filter.sh -s 200 actual.recipient@example.com"

It will be deployed on a gnu/linux system. I'd appreciate any feedback.

#!/bin/bash
shopt -s extglob

usage="$(basename $BASH_SOURCE) [-h] [-s n] recipient"
where="where: -s n == truncate the subject to n characters"
subject_length=''

while getopts :hs: opt; do
    case $opt in
        h) echo "$usage"; echo "$where"; exit ;;
        s) subject_length=$OPTARG ;;
        *) echo "Error: $usage" >&2; exit 1 ;;
    esac
done
shift $((OPTIND - 1))

# validation
if [[ "$#" -eq 1 ]]; then
    recipient=$1
else
    echo "Error: $usage" >&2
    exit 1
fi
if [[ -n $subject_length ]] && [[ $subject_length != +([0-9]) ]]; then
    echo "Error: subject length must be a whole number"
    exit 1
fi

sed_filters=()
if [[ -n $subject_length ]]; then
    sed_filters+=( -e "s/^(Subject: .{1,$subject_length}).*/\1/" )
fi
# other filters can go here

if [[ ${#sed_filters[@]} > 0 ]]; then
    cmd=( sed -E "${sed_filters[@]}" )
else
    # no command line filters given
    cmd=( cat )
fi

# now, filter the incoming email (on stdin) and pass to sendmail
"${cmd[@]}" | /usr/sbin/sendmail -oi "$recipient"

Be sure to read the relevant RFCs that govern e-mail headers!  Specifically:

RFC 2822, Section 1.2.2: Header names are case-insensitive.
RFC 2822, Section 2.2.3: Header fields may be line-folded:

  2.2.3. Long Header Fields

  Each header field is logically a single line of characters
  comprising the field name, the colon, and the field body.  For
  convenience however, and to deal with the 998/78 character
  limitations per line, the field body portion of a header field can
  be split into a multiple line representation; this is called
  "folding".  The general rule is that wherever this standard allows
  for folding white space (not simply WSP characters), a CRLF may be
  inserted before any WSP.  For example, the header field:

Subject: This is a test

  can be represented as:

Subject: This
 is a test

Since your sed operates on the raw representation of the header, you will miss headers that are logically longer than subject_length characters long, but start with a physically short line.

What is your rationale for developing this filter?  Is the application that processes the incoming messages unable to handle long subject texts, or is it unable to handle long physical lines?  If it's the latter, maybe all you need is a filter that performs line folding, rather than truncation.
RFC 2047: Encoding mechanisms for non-ASCII headers.  A logical subject line

Subject: this is some text

… could also be represented physically as

Subject: =?iso-8859-1?q?this=20is=20some=20text?=

… or by many other representations.  Is your limit based on the number of bytes in the raw representation, the number of bytes in the UTF-8 representation, the number of Unicode characters, or something else?  You didn't specify clearly.  If you are truncating the raw representation, you might truncate a MIME-encoded header at a point that makes it syntactically invalid.


Creates a menu and sidebar in Google Spreadsheets In an effort to make my code more testable, I'm trying to make use of constructors and prototypes.

Here is a working Google Apps Script (GAS) for creating a new submenu under the Addon main menu in a Google Spreadsheet. If a user clicks the 'Show' menu item, a sidebar will appear.

var UI = function (menuName, menuFunction, sidebarFile, sidebarTitle) {
    this.menuName = menuName;
    this.menuFunction = menuFunction;
    this.sidebarFile = sidebarFile;
    this.sidebarTitle = sidebarTitle;
};

UI.prototype.createAddonMenu = function () {
    try {
        SpreadsheetApp.getUi()
            .createAddonMenu()
            .addItem(this.menuName, this.menuFunction)
            .addToUi();
        Logger.log('onOpen (success): building menu');

    } catch (e) {
        Logger.log('onOpen (fail): ' +  e);
    }
};

UI.prototype.showSidebar = function () {
    try {
        var ui = HtmlService.createTemplateFromFile(this.sidebarFile)
            .evaluate()
            .setTitle(this.sidebarTitle)
            .setSandboxMode(HtmlService.SandboxMode.IFRAME);

        SpreadsheetApp.getUi()
            .showSidebar(ui);
        Logger.log('showSidebar (success): showing sidebar');

    } catch (e) {
        Logger.log('showSidebar (fail): ' + e);
    }
};

var ui = new UI('Show', 'showSidebar', 'index', 'Awesome Title');

// onOpen is a built-in Google Apps Script function that gets called when the spreadsheet is opened
function onOpen(e) {
    return ui.createAddonMenu();
}

// showSidebar is a standalone function and returns the ui showSidebar method. needs to be this way in order to be called from createAddonMenu
function showSidebar() {
    return ui.showSidebar();
}

Questions:

I'd like to be able to write unit tests for both createAddonMenu and showSidebar, but at this moment I don't believe it's possible as I'm not returning a value from either method; I'm simply just calling Google's third party code for creating a menu and showing a sidebar. Would I need to create a wrapper around any code calling a third party's code, and then call that within my method? I know I'm not supposed to test third party code, so how would I go about testing to make sure it gets called and doesn't return an error?
I'd like a sanity check on when I should create a constructor. I feel like maybe I'm trying to shove too many arguments into it and maybe trying to do too much. Should I create two separate constructors (one for createMenu and one for showSidebar)? Should I even be using constructors at all?
Finally, any other feedback?

1. Testing:

Although your functions don't return a value and they catch any error that is thrown, the functions do log whether the call was successful or not. You could use the Logger to test if they fail like so:

Logger.clear();
ui.showSidebar();
var string = Logger.getLog();
if (string.indeOf("(fail)") === -1) throw "test for 'showSidebar' failed";

Note: If your unit tests are run in the script editor some of the third party functions could throw errors that wouldn't occur when called from the spreadsheet. The ones in your current functions are all fine last I checked, but function calls like SpreadsheetApp.getActive() cannot be made from the script editor.

Writing wrapper classes would be the safest way to ensure that your functions are correct, but that assumes that your wrappers and mocks are perfectly written. You have to consider whether the work it would take to write/debug/test the wrapper and mock classes is worth the value of having unit tests for your functions--especially since there are currently only two and they are rather small.

2. OOP in Google Apps Script

Where to call your constructor

Declaring variables in the global scope is dangerous since Google doesn't offer specifics on the order that it's interpreter/compiler (who knows which) reads the code. Basically things like:

var UI = function () {}

and

UI.prototype.showSidebar = function () {};

and

var ui = new UI();

aren't guaranteed to be executed in the intended order, specifically if they're in separate script files. If you wish to dabble in this dark art (who doesn't?), please note the following:

Functions are hoisted
The rest of the code appears to be executed in the order that your script files were created

I would recommend making one of your script files a sort of "main" file; make this file the only place you preform logic on the global scope to ensure that all the global logic is executed in the intended order.

Note: Global logic is executed every time you execute a script.

Constructor and Prototype in Google Apps Scripts

The way your code creates the UI class depends on global logic. If you declare a UI instance at the global scope in a separate script file, the UI class or it's prototype might not yet be defined.

A way around this would be to use a factory function instead:

function createUI() {
    return {
        createAddonMenu : function () {},
        showSidebar : function () {}

    };
}

The factory function will be hoisted and all is well in the global scope.

To many parameters

Consider passing a single object for your constructor's parameter:

function createUI(settings) {
    var menuName = settings.menu.name;
    var menuFunction = settings.menu.action;
    // ...
}
var ui = createUI({
    menu : {
        name : "Show",
        action : "showSidebar"
    }
    sidebar : {
        // ...
    }
});

This gives names to the parameters at the caller's end, it makes it so the order of the parameters is irrelevant, and it makes optional values easier to work with since the order of other parameters won't be affected if one is omitted. When using this technique you may want to validate that all required parameters exist inside the parameter object.


Find all k-sum paths in a binary tree Description:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Leetcode

Code:

class Solution {
    private List<List<Integer>> paths = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        traverse(root, sum, new ArrayList<Integer>());
        return paths;
    }

    private void traverse(TreeNode root, int sum, ArrayList<Integer> path) {
        if (root != null) {
            path.add(root.val);

            if (root.left == null && root.right == null && sum == root.val) {
                paths.add((ArrayList) path.clone());
            }

            traverse(root.left,  sum - root.val, path);
            traverse(root.right, sum - root.val, path);

            path.remove(path.size() - 1);
        }
    }
}

It's a fine solution. I have a few minor comments.

It's easy to overlook that pathSum doesn't clear the content of paths, which will affect the returned value from subsequent calls, which is likely to be unexpected by callers. In this online puzzle it doesn't seem to matter, but I think it's better to avoid any possible confusion.
The clone with the cast is ugly. The .clone() method except on arrays is a bit controversial, with questionable benefits if any. I suggest to avoid it. You can replace it with a nice clean paths.add(new ArrayList<>(path))
The signature of traverse would be better to use List instead of ArrayList.
I would use an early return in traverse, to have less indented code.


Simple random password generator I decided to write a console program that can generate a random alphanumerical password in the C language. It's quite useful for when I'm making a new account and need to make up a quick password on the spot. I've noticed a lot of the password generators people have shown on this are written in Java and maybe Python or C# so hopefully mine will add some variety.

This is my code, I've aimed to make it as simple as possible:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main()
{
    srand((unsigned int)(time(NULL)));
    int i;
    char pass[12];

    printf("Press enter to get a twelve-character password\n");
    getchar();

    for (i = 0; i < 4; i++) {
        pass[i] = rand() % 9;
        char capLetter = 'A' + (rand() % 26);
        pass[i + 2] = capLetter;
        char letter = 'a' + (rand() % 26);
        pass[i + 3] = letter;
        printf("%d%c%c", pass[i], pass[i + 2], pass[i + 3]);
    }
    printf("\n\n");
}

I can generate decent passwords, such as: 7Qb4Le2Id0Ss, 1Sw0Nb2Ky1Zp, 0Am3Wa4Wo1Tm and 4Rr4My1Mt1Gj. Like I said, I want to make it more efficient if I can, and perhaps add some punctuation, which does not seem that easy, since the ASCII codes are quite spread out.

Does anyone have any ideas?

Though you are getting desired output, here in your code you are not exactly generating characters at all indices/positions of the char pass[12]; array. let me explain

consider the following for loop in your code:

for (i = 0; i < 4; i++) {
    pass[i] = rand() % 10; //10 instead of 9 to produce digits from 0 to 9
    char capLetter = 'A' + (rand() % 26);
    pass[i + 2] = capLetter;
    char letter = 'a' + (rand() % 26);
    pass[i + 3] = letter;
    printf("%d%c%c", pass[i], pass[i + 2], pass[i + 3]);
}

consider the maximum cases i.e, when i = 3 and pass[i + 3], then pass[i + 3] is equivalent to pass[6] so the maximum index value that you can access is 6. So you are not generating random value at all indices of the pass[] array but only within 0 to 6 positions and printing the generated characters in each iteration.

Instead try using for loop this way to generate random character at all the indices:

for (i = 0; i < 4; i++)
{
    pass[ 3 * i ] = rand() % 10;
    char capLetter = 'A' + (rand() % 26);
    pass[(3 * i) + 1] = capLetter;
    char letter = 'a' + (rand() % 26);
    pass[(3 * i) + 2] = letter;
    printf("%d%c%c", pass[3 * i], pass[(3 * i) + 1], pass[(3 * i) + 2]);
}

here you can access all the 12 indices i.e, 0 to 11

further, instead of using pass[i] = rand() % 9; to generate a random character and using %d, you can do pass[i] = '0' + (rand() % 10); (use 10 instead of 9 if not 9 will never be printed) to generate a numeric character and use %c. Since you have a character array, you can append the array with a null terminating character ('\0') and make it a string and print the generated password this way:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>   //not required
#include <time.h>

int main(void) //int main() is not a valid signature in C
{
    srand((unsigned int)(time(NULL)));
    int i;
    char pass[13]; //extra byte for null terminating character

    printf("Press enter to get a twelve-character password\n");
    getchar();

    for (i = 0; i < 4; i++)
    {
        //revised logic to generate random characters at all positions (0 - 11)
        pass[ 3 * i ] = '0' + (rand() % 10); //generating numeric character
        char capLetter = 'A' + (rand() % 26); //generating upper case alpha character
        pass[(3 * i) + 1] = capLetter;
        char letter = 'a' + (rand() % 26); //generating lower case alpha character
        pass[(3 * i) + 2] = letter;
    }
    pass[3 * i] = '\0'; //placing null terminating character at the end
    printf("generated password : %s\n\n",pass); //printing the string

    printf("\n\n");
}

  I want to make it more efficient if I can, and perhaps add some
  punctuation, which does not seem that easy, since the ASCII codes are
  quite spread out.

Here is a way to generate passwords which includes punctuation without caring about ASCII code at all! Right now, you are following a fixed pattern of printing uppercase letter followed by number and then a lowercase letter, and you repeat it for three more times to generate a 12 character password. Instead you could randomly generate the password without any such pattern and not using ASCII codes at all!

create a string of all permissible characters
use the string to print 12 character from any 12 random positions

here's the program which follows the above two steps to generate a password and you can add all the permissible characters in the string which I have not mentioned

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

int main(void)
{
     srand((unsigned int)(time(NULL)));

    int index = 0;

    //step 1
    char characters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/,.-+=~`<>:";
    //I just added a few punctuations characters for explanatory purpose
    //you can add all the additional punctuations which are required

    //step 2
    for(index = 0; index < 12; index++)
    {
        printf("%c", characters[rand() % (sizeof characters - 1)]);
    }

}

I'd say generating the password is much more advantageous as you can only randomly select from the characters that provide in the string. All you need to do is just put in all the permissible characters in the string and you are bound to get a randomly generated password :)


Python program for healthy schedule Please review my program and give some tips . I am a beginner. IT is for those people who sit on computer all day and get unhealthy . This will remind them to do eye exercise , physical exercise and to drink water
import pygame
import time

t = time.ctime(time.time())
# noinspection SpellCheckingInspection
totalbreaks2 = 17
# noinspection SpellCheckingInspection
breakcount2 = 0
# noinspection SpellCheckingInspection
totalbreaks = 16
# noinspection SpellCheckingInspection
breakcount = 0
# noinspection SpellCheckingInspection
totalbreaks1 = 10
# noinspection SpellCheckingInspection
breakcount1 = 0

# noinspection SpellCheckingInspection
def health():
    # global keywords
    global breakcount2
    global breakcount
    global breakcount1
    global totalbreaks1
    global totalbreaks
    global totalbreaks2
    # water program
    if breakcount2 < totalbreaks2:
        pygame.mixer.init()
        pygame.mixer.music.load("water.mp3.mp3")
        pygame.mixer.music.play(-1)
        query = input('Did you drink water (type drank if yes)?')
        if query == 'drank':
            with open('water.txt', 'r+') as o:
                o.write(f'You drank water at {t} ')
            pygame.mixer.music.pause()
            time.sleep(120)
            breakcount2 += 1
    # eye program
    if breakcount < totalbreaks:
        pygame.mixer.init()
        pygame.mixer.music.load("eyes.mp3.mp3")
        pygame.mixer.music.play(-1)
        query = input('Did you do eyes exercise ?(type eydone if yes)')
        if query == 'eydone':
            with open('water.txt', 'r+') as o1:
                o1.write(f'You drank water at {t} ')
            pygame.mixer.music.pause()
            time.sleep(1080)
            breakcount += 1
    # exercise program
    if breakcount1 < totalbreaks1:
        pygame.mixer.init()
        pygame.mixer.music.load("physical.mp3.mp3")
        pygame.mixer.music.play(-1)
        query = input('Did you do physical exercise (type exdone if yes) ?:')
        if query == 'exdone':
            with open('water.txt', 'r+') as o2:
                o2.write(f'You drank water at {t} ')
            pygame.mixer.music.pause()
            time.sleep(2400)
            breakcount1 += 1
            health()

z = input('Do you want to start the program? (y=yes , n=no):')
if z == 'y':
    health()
elif z == 'n':
    print('ok')
else:
    print('type correct input')

Variable naming
Your variables should be named something more telling than breakcount , breakcount1 and breakcount2. I suggest breakcount_water (and _eyes , _physical) instead.
Simpler logic
Instead of two variables for each kind of break (6 total), you can do with just one variable for each, starting at the max, and subtract 1 for each break. Then, you're done when you reach zero.
That lets you do the same thing with half as many (3) variables to keep track of.
Don't repeat yourself
pygame.mixer.init()
pygame.mixer.music.load("water.mp3.mp3")
pygame.mixer.music.play(-1)

These three lines are identical each time you play music.
Create a function instead that takes the file name as input, and you can call play_music("water.mp3.mp3") which then executes these three lines in the function.
def play_music(filename):
    #the three lines from above

Stack abuse
You're calling the health() function from inside itself, which means you never let it exit properly and if you did this a few thousand (maybe more) times, the program would crash due to stack overflow.
Instead, you should use a while loop that checks for the condition to loop again, to start over without calling the function another time. That way, you can also initialise your variables at the start of the function (before the while-loop) and you don't need any global variables, since the function has access to them inside its own scope.


Unique type ID in C++ I need to have an unique ID for any type in C++ for a variant type. Is this code reliable for getting the ID? I don't care to have same ID for same type between multiple runs. Sorry for typos/formatting, I wrote the code on my phone and tested on Ideone.

#include <iostream>

struct Counter
{
    static size_t value;
};

size_t Counter::value = 1;

template<typename T>
struct TypeID : private Counter
{
    static size_t value()
    {
        static size_t value = Counter::value++;
        return value;
    }
};

int main()
{
    std::cout << TypeID<int>::value() << " " << TypeID<int*>::value() << " " << TypeID<Counter>::value() << " " << TypeID<int>::value();

return 0;
}

PS: I use this because std::type_index/std::type_info::hash may have the same value for different types (probably not in practice).

Here is my lightweight solution that involves no operations at run time:

template<typename T>
struct type { static void id() { } };

template<typename T>
size_t type_id() { return reinterpret_cast<size_t>(&type<T>::id); }

struct A { };

int main ()
{
    cout << type_id<int>() << " " << type_id<int*>() << " "
         << type_id<A>() << " " << type_id<int>() << endl;
}

The type id of type T is nothing but the address of function type<T>::id, re-interpreted as a number. Being a static method, there is a unique such function per type. These addresses are assigned by the linker (I think), so they remain constant between different runs. The overhead in executable size is linear in the number of type ids requested (that is, the number of instantiations of type<T>).

This solution has been tested in gcc and clang, and works correctly across different compilation units, i.e. you get the same unique type id for the same type in different compilation units. However, I cannot quite explain why/how this happens.

type_id() is easily inlined, so has no run-time cost. However, since it contains reinterpret_cast (and since the function address is not known to the compiler), it cannot be made constexpr. But I don't see this as a problem: if you want to use something e.g. as a template argument, you can use the type directly instead of its id. The id is for run-time use only.

My original implementation is using const void* as the return type of type_id(), so I know it has the same size as any pointer. I adapted it to size_t to fit the question. I think this is still safe, but I can't see why const void* wouldn't be fair enough.

By the way, because I haven't used it very much, I'd be happy to hear if there may be problems with this approach.


MMO game server brain loop I'm writing up a game server on which thread-safety is very important, basically for this approach I've decided to move my entire server in a single brain loop which handles everything in a single thread, connections are ran separately in their own separate thread, whenever a packet is received, the brain loop is signaled so it doesn't have to wait for the entire interval.

This is truly the best approach I could come up with, given my server is filled with pointers everywhere, and invalidation would kill my player base.

#define GAME_BEAT 50

void Game::brain() {
    int64_t connectionsTimeCounter = 0;
    int64_t decayTimeCounter = 0;
    int64_t releasePointersCounter = 0;
    int64_t creaturesTimeCounter = 0;
    int64_t roundNr = getServerMilliseconds();

    while (isGameRunning() || isGameStarting()) {
        gameSignal.wait(GAME_BEAT);

        int64_t delay = getServerMilliseconds() - roundNr;
        roundNr = getServerMilliseconds();

        // Receive packets from connections with data available to be read (non-blocking)
        // when data is available to be read, the connection which was previously ran in a different thread
        // will be signaled to read packet data and store it in a variable
        // say, a packet for "player talk" was sent, then the function below "moveCreatures" would handle this action
        g_server.receiveData();

        connectionsTimeCounter += delay;
        if (connectionsTimeCounter >= 1000) {
            // This function closes invalid connections/closed connections
            g_server.processConnections();
        }

        decayTimeCounter += delay;
        if (connectionsTimeCounter >= 1500) {
            decayItems(delay);
        }

        releasePointersCounter += delay;
        if (releasePointersCounter >= 1000) {
            // This function simply calls a "delete" to removed objects from the game
            releaseObjects();
        }

        creaturesTimeCounter += delay;
        if (creaturesTimeCounter >= 1000) {
            // Processes creatures idle status
            processCreatures(delay);
        }

        // Moves creatures, players, talking, moving, etc ...
        moveCreatures();

        // Sends all pending packets to be sent to active connections
        g_server.sendAllData();
    }
}

That is pretty much the only way I found for my server to be thread-safe, since I did experienced a few crashes because when connections sent a particular packet (say player move item), it would invalidate other connections from doing so

g_server.receiveData();

Does this actually handle all of the message parsing?

As in: Is it really necessary to handle the full netcode in the main thread?

At least unpacking and sorting all inputs to a thread safe queues (e.g. lockfree queue from boost) with unresolved, symbolic references should be easily possible inside the worker threads handling the connections.

Validation of conflicting inputs, or orphaned references can't be avoided in the main loop. But parsing the packages and preliminary filtering can.

releasePointersCounter += delay;
if (releasePointersCounter >= 1000) {
    // This function simply calls a "delete" to removed objects from the game
    releaseObjects();
}

Not using C++11 shared pointers with builtin reference counting? Respectively, any specific reason (like cyclic references) which would prevent these from working?

// Sends all pending packets to be sent to active connections
g_server.sendAllData();

I must assume the world state, respectively the list of updates is not buffered, so this reads from the live game state?

Writing out all changes to the game state to a transaction log (with all dangling pointers resolved, implemented as a list with a single producer and multiple non-consuming iterators), and then walking the transaction log for each active connection asynchronously removes this load from the main loop as well.

There is no good reason why this should be allowed to stall the main loop.

int64_t connectionsTimeCounter = 0;
int64_t decayTimeCounter = 0;
int64_t releasePointersCounter = 0;
int64_t creaturesTimeCounter = 0;

Why are these variables write-only, apart from the initial check when to run the corresponding logic first? Respectively why does the main loop wait a full second before starting any of the workers at all?


Side effects in functions that find boolean conditions Here's an example of a logic structure I've refactored into something more complex on many occasions because I feel like it's wrong to have a side effect in a function that determines a yes/no answer to a question.

If I were to break this into multiple functions I would add to the main logic to call another function that handles the found conflict.

What is you opinion of logic like this?  Should it be refactored?

(also I welcome any/all code critiques)

namespace DirectAgents.SynchService.Commands
{
    public class CreateCampaign : Command<Campaign, bool>
    {
        private IFactory<DADatabase> eom;
        public CreateCampaign(IFactory<DADatabase> eomDatabase)
        {
            this.eom = eomDatabase;
        }
        public override bool Execute(Campaign input)
        {
            bool result = false;
            using (var db = eom.Create())
            {
                if (this.CanAdd(input))
                {
                    db.Campaigns.AddObject(input);
                    Log("Saving new {0} [{1}].", input.GetType().Name, input.campaign_name);
                    db.SaveChanges();
                    result = true;
                }
            }
            return result;
        }
        private bool CanAdd(Campaign campaign)
        {
            using (var db = eom.Create())
            {
                var conflictingID = from c in db.Campaigns
                                    where (c.pid == campaign.pid) && (c.campaign_name == campaign.campaign_name)
                                    select c.pid;

                bool conflictExists = (conflictingID.FirstOrDefault() == default(int));
                if (conflictExists)
                {
                    this.CampaignConflicts.Add(new CampaignConflict {
                        Campaign = campaign,
                        ConflictingId = conflictingID.First()
                    });
                }
                return (!conflictExists);
            }
        }
        [Dependency("CampaignConflicts")]
        public ICollection<CampaignConflict> CampaignConflicts { get; set; }
    }
}

The method name CanAdd implies that it won't have side effects. Therefore you could mistake the method in the future as a read-only method, while it isn't. Also because the relationship between checking whether it can be added to list A and adding it to another list is not strongly related, I would advice to make CanAdd a method that doesn't make any changes.

A better place to add the campaign to the conflicting list would be in execute or in a separate method called from execute.


Project Euler #42 - Triangle Numbers Here is the Euler problem referenced, it says:

  The n\$^{th}\$ term of the sequence of triangle numbers is given by, t\$_n\$ =
  ½n(n+1); so the first ten triangle numbers are:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  By converting each letter in a word to a number corresponding to its
  alphabetical position and adding these values we form a word value.
  For example, the word value for SKY is 19 + 11 + 25 = 55 = t\$_{10}\$. If the
  word value is a triangle number then we shall call the word a triangle
  word.

  Using words.txt (right click and 'Save Link/Target As...'), a 16K text
  file containing nearly two-thousand common English words, how many are
  triangle words?

My solution is as follows:

import re
import string

#generate a key to map the letters in our strings to
letters = string.ascii_uppercase
letters_map = {letter: idx for idx, letter in enumerate(string.ascii_uppercase, start=1)}

#open the file and parse on quoted values
with open('words.txt') as f:
    words = sorted(re.findall(r'"(.*?)"', f.read()))

#max word score can only be Z*len(n), recall 'Z' : 26 in letters_map
max_word_score = len(max(words, key=len))*26

#generate a list of triangle_numbers to search for using max_score as upper bound
n = 1
triangle_numbers = []
while 1/2.0*n*(n+1) <= max_word_score:
    triangle_numbers.append(1/2.0*n*(n+1))
    n += 1

#finally use a nested for loop to return number of triangle numbers in our now summed words
count = 0
for word in words:
    if sum(letters_map[char] for char in word) in triangle_numbers:
        count += 1

%%timeit
100 loops, best of 3: 3.67 ms per loop

I'm curious if there are any ways I can rewrite this with similar or better performance so that it is more pythonic. I'm curious about a few things more specifically:

1) Is it possible to rewrite this better using itertools.ifilter and itertools.imap using letters_map and the filter being the list of triangle_numbers, to greater affect than simply using a nested for loop and an if statement to filter?

2) Is my while construction extremely not pythonic? It felt awkward writing it the way it was and I wasn't sure what a better way of operating under that framework would be (needing to count up to some arbitrary ceiling, in this case max_word_score.)

3) Should I be getting in the habit of wrapping these items in mini-functions in order to make it more readable/replicable? Would that end up slowing runtime down? What sort of effect would that have in general.

4) Any other pythonizations I can use to better effect?

Your should use csv to read the file.

import csv
with open('words.txt', 'rb') as csvfile:
    words = [
        word
        for line in csv.reader(csvfile, delimiter=',', quotechar='"')
        for word in line
    ]

It's much easier to understand what it is doing. And it's probably safer and faster.

You define letters, however you use string.ascii_uppercase instead.

You can put max_word_score in the same 'block' as the while loop below it.
You can also re-arange 1/2.0*n*(n+1) <= max_word_score to get the max n.

Python also has a style guide called PEP8, which says you should have a space either side of operators. 1 + 1 not 1+1.
The only exception to this is when you want to show precedence. 1 + 2*3.

You can change your for word in words to one large comprehension, and use sum. For better reliability.

max_word_score = len(max(words, key=len)) * 26
triangle_numbers = [
    0.5 * n * (n + 1)
    for n in xrange(int((2 * max_word_score + max_word_score)**0.5))
]

count = sum(
    1
    for word in words
    if sum(letters_map[char] for char in word) in triangle_numbers
)

If you also assume that you are not going to get the longest English word you can change max_word_score = len(max(words, key=len)) * 26 to max_word_score = 1909 * 26, which will allow the second longest English word.
And as they are 'common English words' you could change max_word_score to 27 * 26, which will allow the 9th longest English word.

And if you do use max_word_score = 30 * 26, then you can reduce the memory usage.

You should also change letters_map, max_word_score and triangle_numbers to uppercase variants, e.g. LETTERS_MAP.
This is as they are constants.

If I were to do all the above then I would use the following program:

import csv
import string

MAX_TRIANGLE = 30 * 26
LETTERS_MAP = {letter: idx for idx, letter in enumerate(string.ascii_uppercase, start=1)}
TRIANGLE_NUMBERS = [
    0.5 * n * (n + 1)
    for n in xrange(int((2 * MAX_TRIANGLE) ** 0.5))
]

with open('words.txt', 'rb') as csvfile:
    count = sum(
        1
        for line in csv.reader(csvfile, delimiter=',', quotechar='"')
        for word in line
        if sum(LETTERS_MAP[char] for char in word) in TRIANGLE_NUMBERS
    )

If you want it to be faster than your original, then you can change MAX_TRIANGLE = 30 * 26 to MAX_TRIANGLE = 15 * 26, bit dodgy IMO.
But this uses less memory, (unless csv loads everything into memory) and is more readable.

To answer your questions:

I would only encorage itertools if you use generators. Which you don't. (Well, you have one that is fed into sum...)
It's not 'Pythonic' as the maths you use isn't. However personally I think a greedy for is better, (hence why my maths is an over estimate).
If you wrapped them in a main that would be good. Wrapping them into functions, is always better than having no functions.
But as this can be done with 3 constants, and 1 generator, I would say one function is fine.
I would say following PEP8 is your best bet for that.


Java Implementation of Sieve of Eratosthenes algorithm I previously asked about my implementation of the Sieve of Eratosthenes algorithm here.

After looking at all of the feedback, I have reworked the code to make it significantly more efficient. However, I'd like to know whether it can be made more efficient still.

I have tried to follow pesudocode for my implementation, which I have provided below:

Input: an integer n > 1

Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.

 for i = 2, 3, 4, ..., not exceeding √n:
  if A[i] is true:
    for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n :
      A[j] := false

Output: all i such that A[i] is true.

Pseudocode sourced from here.

My implementation:

import java.util.Arrays;
import java.util.Scanner;
public class sieveOfEratosthenes {
    public static void main (String [] args) {
        int maxPrime;
        try (Scanner sc = new Scanner(System.in);) {
            System.out.print("Enter an integer greater than 1: ");
            maxPrime = sc.nextInt();
            sc.close();
        }
        long start = System.nanoTime();
        boolean [] primeNumbers = new boolean [maxPrime];
        Arrays.fill(primeNumbers, true);
        int maxNumToTest = (int) (Math.floor(Math.sqrt(maxPrime)));
        for(int i = 2; i <= maxNumToTest; i++) {
            if (primeNumbers[i] == true) {
                for (int j = i * i; j < maxPrime; j += i) {
                    primeNumbers[j] = false;
                }
            }
        }
        long stop = System.nanoTime();
        for(int i = 2; i < primeNumbers.length; i++) {
            if(primeNumbers[i] == true) {
                System.out.print((i) + ", ");
            }
        }

        System.out.println("\nExecution time: " + ((stop - start) / 1e+6) + "ms.");
    }
}

I have tested my implementation to find that it is capable of calculating all primes below 10,000,000 in ~110ms on an i5 processor.

My question: Is this as fast as is physically possible in Java, or can I make further improvements?

Using vertical spaces (new line) to group related code will help to easier read your code.
if(primeNumbers[i] == true) the checking with == true is superfluous because the condition of the if is a boolean one, so you can simplify this to if(primeNumbers[i])

- instead of using maxPrime here

    boolean [] primeNumbers = new boolean [maxPrime];
    Arrays.fill(primeNumbers, true)

you should take advantage of the computed int maxNumToTest like you did in the first loop. You should also add this computed value as the end of the inner loop and the result loop like so

    int maxNumToTest = (int) (Math.floor(Math.sqrt(maxPrime)));
    boolean [] primeNumbers = new boolean [maxNumToTest];
    Arrays.fill(primeNumbers, true);

    for(int i = 2; i <= maxNumToTest; i++) {
        if (primeNumbers[i]) {
            for (int j = i * i; j <= maxNumToTest; j += i) {
                primeNumbers[j] = false;
            }
        }
    }
    long stop = System.nanoTime();
    for(int i = 2; i <= maxNumToTest; i++) {
        if(primeNumbers[i]) {
            System.out.print((i) + ", ");
        }
    }

- putting everything int main() should be avoided. The current code could be divided into 3 methods:

reading the input
computing the primes
writing the output

In this way each method has a single responsibility and is easier to read and to maintain.


Parser for CNF formulas I have a parser for CNF formulas in Dimacs format, which is very slow. Any suggestion on how to improve its speed? I did some profiling and I might have to replace Scanner. Is there anything faster?

A possible input for the parser is:

c A sample .cnf file.
p cnf 3 2
1 -3 0
2 3 -1 0

The code:

/**
 * Parses a stream for a CNF instance.
 *
 * @param source input stream
 * @return read skeleton
 * @throws ParseException if stream contains an invalid instance
 */
private static Skeleton parseStream(final InputStream source)
    throws IOException, ParseException {
  Scanner scanner = new Scanner(source);

  // Skip comments
  try {
    String token = scanner.next();
    while (token.equals("c")) {
      scanner.nextLine();
      token = scanner.next();
    }
    if (!token.equals("p")) {
      throw new ParseException(
          "Excepted 'p', but '" + token + "' was found");
    }
  } catch (NoSuchElementException e) {
    throw new ParseException("Header not found");
  }

  // Reads header
  int numVariables, numClauses;
  try {
    String cnf = scanner.next();
    if (!cnf.equals("cnf")) {
      throw new ParseException(
          "Expected 'cnf', but '" + cnf + "' was found");
    }
    numVariables = scanner.nextInt();
    numClauses = scanner.nextInt();
  } catch (NoSuchElementException e) {
    throw new ParseException("Incomplete header");
  }
  logger.debug("p cnf " + numVariables + " " + numClauses);

  // Reads clauses
  Skeleton skeleton = new Skeleton(numVariables);
  try {
    while (numClauses > 0) {
      int literal = scanner.nextInt();
      skeleton.cnf.add(literal);
      if (literal == 0) {
        numClauses--;
      }
    }
  } catch (NoSuchElementException e) {
    throw new ParseException(
        "Incomplete problem: " + numClauses + " clauses are missing");
  }

  return skeleton;
}

Use a BufferedInputStream to speed up the disk access. If that's not enough, you can read the file line-by-line and use split() to break it into individual numbers.


Perl - Splitting a string I've decided to work on my Perl skills. I've written a small subroutine that splits a string based on an optional delimiter. I'd like any feedback on this program so I can kick bad habits to the curb. Written in Perl 5.

sub split_string {
    my $string = @_[0];
    my $delimiter = @_[1] ? @_[1] : " ";
    my @result = ();
    my $temp = "";

    for $i (0..length($string)) {
        my $char = substr($string, $i, 1);
        if (($char eq $delimiter) or $i == length($string)) {
            push(@result, $temp);
            $temp = "";
        } else {
            $temp .= $char;
        }
    }
    return @result;
}

And this is how I test this subroutine.

@test = split_string("This is a test to ensure this works correctly.");
foreach $element (@test) {
    print $element . "\n";
}

- Use the strict and warnings pragmas

This helps catch many errors at an early stage.

- Declare lexical variables with my instead of using package variables

If you define variables without having declared them they will be defined as package variables (which are seen by all code in your package). Note that if you use the strict pragma you need to declare package variables with our.

- use say instead of print

Since perl version 5.10 you can use say to print a line and add the line terminator (newline character) automatically. Just remember to enable the the feature with use feature qw(say).

- Unpack arguments to a function/method from the @_ array for clarity

Prefer my ($str, $delim) = @_ over my $str = $_[0]; my $delim = $_[1]

- Use $array[$N] to refer to the ($N+1)th element of @array.

In you code you used @_[1] to refer to the second element of the @_ array. The correct syntax is to use $_[1].

- Do not use parenthesis around argument for builtin functions if not necessary.

In Perl parenthesis around function arguments is optional. A common style is to avoid parenthesis around builtin function calls. This reduces visual clutter and disambiguates built-in functions from user functions, see also What is the reason to use parenthesis-less subroutine calls in Perl?

- Don't declare empty arrays with empty parenthesis. Simply use my @arr;

- Return a reference to an array and not an array value.

By returning a reference you avoid copying, but see also In perl, when assigning a subroutine's return value to a variable, is the data duplicated in memory?

- Don't reinvent the wheel, use the Perl builtin function split

You tagged your question with [reinventing-the-wheel] so I assume this is for learning purposes only.

Here is a revised version of your code that implements the above comments:

use feature qw(say);
use strict;
use warnings;

{ # <-- create a scope so lexical variable does not "leak" into the subs below

    my $test = split_string("This is a test to ensure this works correctly.");
    foreach my $element (@$test) {
        say $element;
    }
}

sub split_string {
    my ( $string, $delimiter ) = @_;

    $delimiter //= " ";
    my @result;
    my $temp = "";

    for my $i (0..(length $string)) {
        my $char = substr $string, $i, 1;
        if (($char eq $delimiter) or $i == (length $string)) {
            push @result, $temp;
            $temp = "";
        } else {
            $temp .= $char;
        }
    }
    return \@result;
}


5 CPU's Task scheduling N process Question.

  There are 5 CPUs and N number of tasks in the queue. You have to use
  minimum CPUs to process the tasks.

  A task is of format [arrival time, time to process the task].

  Note:

  You can only use at most 5 CPUs. If it is not possible in 5 CPUs, print -1.
  The time to process the task should not be greater than 10     i.e (Time waiting in queue + time to process the task) <= 10.
  If to process the current task, you need more than 10 seconds in current CPU, you can move to a different CPU and check if it is
  possible to process the task in <=10 time.
  If it is not possible to process the task in <=10 or at most 5 CPUs, print -1.

Constraints.

  0 <= Arrival time <= 500

  1 <= time to process the task <= 10

  0 <= N <=500

  You can only use iostream library. No STL's are allowed.

  Time : 3 second for T test cases

Eg:-

  Input

  3

  1 6

  2 7

  3 1

  Output

  2

Explanation:

  3   - N

  1 6 - the first task arrives in CPU0 at time 1, and leaves at time 7 (1+6).
   CPUs used = 1.

  2 7 - the second task arrives in CPU0 at time 2, and wait for 5
  seconds in the queue, so overall processing time is 5+7 > 10. So it is
  moved to CPU1. CPUs used = 2.

  3 1  -  the third task arrives. it can go to CPU0 or CPU1, as
  processing time is 5 ( (7-3) + 1 ) and 7 ( (9-3) + 1 )   seconds respectively. CPUs used = 2.

  CPU1 is a fresh CPU. So task2 will be completed in 9 (2 + 7) seconds without any Time to wait in the queue.

My Approach:

Initially, thought this as a variant of minimum train-platform problem. But that was wrong.
Tried a greedy approach, but it gave -1 for some valid solutions.
Trying memoization approach.

Recursive approach solves the problem, but it gets timed out. (No wonder)

What is the possible way to save the state of int, int, int[]?

I am also open to an iterative solution for the same.

Below is the code.

#include <iostream>
using namespace std;

#define MAXN 500

int min_cpus_used = 6;

int N;
int arr[MAXN];
int len[MAXN];

void recurse( int task_idx, int cpus_used_so_far, int  exit_time_of_task_in_CPUs[] ){

    if( task_idx == N-1){
        min_cpus_used = min( min_cpus_used, cpus_used_so_far);
        return ;
    }

    if( cpus_used_so_far >= min_cpus_used ){
        return ; //optimization
    }

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

        int processing_time = 0;
        int time_in_queue = exit_time_of_task_in_CPUs[i] - arr[task_idx];

        if( time_in_queue < 0 ) // ie processor is free before arrival
            time_in_queue = 0;

        processing_time = time_in_queue + len[task_idx];

        // try with existing CPUs
        if( processing_time <=10){
            int prev =  exit_time_of_task_in_CPUs[i];
            exit_time_of_task_in_CPUs[i] = arr[task_idx] + processing_time;

            recurse( task_idx + 1 , cpus_used_so_far , exit_time_of_task_in_CPUs ); // can we optimize passing array

            exit_time_of_task_in_CPUs[i] = prev;

        }

        // try with new CPU
        if (cpus_used_so_far+1 <= 5){

            int new_cpu_index = cpus_used_so_far + 1 - 1; // converting to zero index

            int prev = exit_time_of_task_in_CPUs[new_cpu_index];

            exit_time_of_task_in_CPUs[new_cpu_index] = arr[task_idx] + len[task_idx] ;

            recurse( task_idx+1 , cpus_used_so_far+1 , exit_time_of_task_in_CPUs );

            exit_time_of_task_in_CPUs[new_cpu_index] = prev;

        }else{
            return ;
        }

    }

}

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    cin>>N;

    for(int i=0;i<N;i++){
        cin>> arr[i] >> len[i];
    }

    int exit_time_of_task_in_CPUs[5]={0};
    recurse(0, 1, exit_time_of_task_in_CPUs);

    if(min_cpus_used==6){
        cout<< -1 <<endl;
    }else{
        cout << min_cpus_used <<endl;
    }

}

Kindly help me with your thoughts on optimizing this solution.

Read through and bookmark the C++ Standard Guidelines.  Numbers I note later are citations from this.

Don’t write using namespace std;.

You can, however, in a CPP file (not H file) or inside a function put individual using std::string; etc.  (See SF.7.)

#define MAXN 500

Don't use #define for constants or "functions" (⧺ES.31).

void recurse( int task_idx, int cpus_used_so_far, int  exit_time_of_task_in_CPUs[] ){

That last parameter is a pointer, with the implication that you are passing a pointer to the first of contiguous elements.  Don’t pass unknown-sized arrays like that.

(Reading ahead…) since it is of fixed size known at compile time, define it as a std::array instead, both the actual array in main and the parameter (by reference).

int min_cpus_used = 6;

int exit_time_of_task_in_CPUs[5]={0};

if (cpus_used_so_far+1 <= 5){

if(min_cpus_used==6){

Hard-coded magic numbers: are these all related?  Define a constant instead of sprinkling these throughout the code.

Let’s see… cpus_used_so_far is not changed within the function, just passed a different value when recursing, right?  It would be helpful for readability and analysis to mark it const in the declaration.

    if (cpus_used_so_far+1 <= 5){
            ⋮
    }else{
        return ;
    }

That took me a moment to figure out what the else return was doing at the end of the function just before the closing braces.  This would be much clearer if you invert the logic:  put the exceptional case first, in the manner of precondition testing.

if (cpus_used_so_far+1 > 5)  return;
⋮

Note that there is no further indenting of the regular code, since it is not nested anymore — it is the main-line of code.

cin.tie(NULL);

Don’t use the C macro NULL.  For a null pointer, it is the keyword nullptr.

    cout<< -1 <<endl;

Don’t use endl.  Just use \n.


Focus next element on keypress It's been a year or two since I last dabbled in jQuery and have attempted to write a simple "on key press move to the next element" script.  However my first attempt has a lot a repetition. I just know there is a more elegant way to write this, probably using a dictionary of elements or such.

$("#DialFirst").keypress(function () {
        $("#DialSecond").focus();
    });

    $("#DialSecond").keypress(function () {
        $("#DialThird").focus();
    });

    $("#DialThird").keypress(function () {
        $("#DialFourth").focus();
    });

    $("#DialFourth").keypress(function () {
        $("#DialFifth").focus();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="DialFirst" name="DialFirst" type="text" value="" />
<input id="DialSecond" name="DialSecond" type="text" value="" />
<input id="DialThird" name="DialThird" type="text" value="" />
<input id="DialFourth" name="DialFourth" type="text" value="" />
<input id="DialFifth" name="DialFifth" type="text" value="" />

Usage: Type in each box, focus should move to the next.

The input elements are all siblings of each other, so you can use $.next() to select the next one that appears after the event target.  There is no need to name each input individually.

$(':input').keypress(function() {
    $(this).next(':input').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input placeholder="1">
<input placeholder="2">
<input placeholder="3">
<input placeholder="4">
<input placeholder="5">


XOR of a list of a numbers In preparing a solution for the CodeChef "Will India Win" challenge, I am trying to find out the xor of list of numbers.

The first line of input contains the number of test cases, 1 ≤ T ≤ 106.
Subsequent lines contain fifteen space-delimited numbers (each between 1 and 231), to be XORed together.

def main():
    t = int(raw_input())
    for i in range(t):

        input_list = [int(j) for j in raw_input().split()]
        res = input_list[0]
        for n in range(len(input_list)-1):
            res = res^input_list[n+1]
        print res

if __name__ == '__main__':
    main()

Here is my second code by implementing a 2D array through a dictionary:

def main():
    t = int(raw_input())
    for i in range(t):
        input_str = [ int(j) for j in raw_input().split()]
        d = {}
        for j in range(15):
            d[j] = bin(input_str[j])[2:].zfill(32)

        l = []#contains the final output
        for j in range(32):
            temp = 0
            for k in range(15):
                if d[k][j] == '1':
                    temp += 1

            if temp%2 == 0:
                l.append(0)
            else:
                l.append(1)
if  __name__ == '__main__':
    name()

But it turns out that both code are not optimal because I am getting time constraint problems. How can I optimize the code?

As the input size is 10**6 and you're using Python 2 the first issue in that you're creating an unnecessary list of 10**6 integers just to do a loop.

Instead of that you should use xrange() which yields integers lazily:

>>> %timeit for _ in range(10**6): pass
10 loops, best of 3: 24.1 ms per loop
>>> %timeit for _ in xrange(10**6): pass
f100 loops, best of 3: 8.92 ms per loop

Another slight micro-optimization that you can do here is to use itertools.repeat with None. None is a singleton, so, only a single None ever exists in memory and it is the smallest object in CPython on the other hand creating 10**6 integers is expensive(well CPython caches some of them, but still they are unnecessary here)

>>> %timeit for _ in repeat(None, 10**6): pass
100 loops, best of 3: 7 ms per loop

As we're using the functions like raw_input, int multiple times in our code it's better to cache them as local variables, because otherwise we're looking for them at least 10**6 times in global dictionary. One way to cache them is to use them as default values to function attributes:

>>> def f_simple(n):
    for _ in xrange(n):
        foo = [int('1') for _ in xrange(15)]
...
>>> def f_cached(n, int=int):
    for _ in xrange(n):
        foo = [int('1') for _ in xrange(15)]
...
>>> %timeit f_simple(10**6)
1 loops, best of 3: 3.7 s per loop
>>> %timeit f_cached(10**6)
1 loops, best of 3: 3.52 s per loop

Instead of starting the result value with input_list[0] we can simply start with 0 and we can also prevent creation of that simple 15 items list:

result = 0
for x in raw_input().split():
    result ^= int(x)

Currently your first solution takes around 7.44 seconds on my system and my solution takes around 5.6 seconds, not a huge improvement.:

from itertools import islice
from functools import partial
import sys

def main5(int=int):
    t = int(raw_input())
    # Take a slice of sys.stdin of size (10**6)*2
    lines = islice(sys.stdin, t*2)
    # Now lines is an iterator which is going to yield one
    # line at a time, but we're also going to read the next line(to get X)
    # with each input, so instead of doing `next(lines)` each time in
    # the loop we can create a partial function.
    next_line = partial(next, lines)

    for line in lines:
        result = 0
        for x in line.split():
            result ^= int(x)
        if format(result, 'b').zfill(32).count('1') > int(next_line()):
            print 'YES'
        else:
            print 'NO'

Note that in the above solution we are writing to the stdout instantly, if we can store the output temporarily in a list(say 1000 items) and them write them at once then the above solution takes 5.52 seconds:

from itertools import islice
from functools import partial
import sys

def main6(int=int, len=len):
    t = int(raw_input())
    # store a reference sys.stdout.write to prevent 2 attribute lookups
    stdout_write = sys.stdout.write
    lines = islice(sys.stdin, t*2)
    next_line = partial(next, lines)
    out = []
    # Cache out.append to prevent attribute lookup
    out_append = out.append
    for line in lines:
        result = 0
        for x in line.split():
            result ^= int(x)
        if format(result, 'b').zfill(32).count('1') > int(next_line()):
            result = 'YES'
        else:
            result = 'NO'

        out_append(result)
        if len(out) == 1000:
            stdout_write('\n'.join(out))
            # empty out list; use list.clear() in Python 3
            del out[:]
    if out:
        stdout_write('\n'.join(out))


Print a command line argument 100 times I am learning Java and this is my solution for a program that will read in a name from the command line and write it out 100 times furthermore words are never split up assuming that the console is 80 characters wide.
Could someone please help me improve its quality?

/**
* Program to print command line argument 100 times
* Words are never split up. Assuming that the console is 80 characters wide.
*
**/
class Hundred {
    private static final int LINE_WIDTH = 80;

    public static void main(String[] args) {
        if(args.length == 0) {
            System.out.println("Argument missing");
        } else {
            String name = args[0];

            int wordsOnOneLine = LINE_WIDTH / (name.length() + 1);
            int i = 0;
            while(i < 100) {
                for(int j = 0; j < wordsOnOneLine && i < 100; j++) {
                    i++;
                    System.out.print(name);
                    System.out.print(" ");
                }
                System.out.println();
            }
        }
    }
}

General Remarks

Well done. While there are some points of improvement, you created a functional program, with proper naming of arguments, and even some basic error handling. Asking for feedback is the best way to learn, so here you get some :). Keep up the good work.

Repeating/LineWidth logic

The repeating of the value 100 is suspicious, there probably is a better solution.

   while(i < 100) {
                for(int j = 0; j < wordsOnOneLine && i < 100; j++) {

If you see this, think more and try to approach the problem differently.

The main idea (that vp_arth already posted) is to keep track of the available space in the line, no need to calculate the wordsOnOneLine

Also, you can count-down the number of words you still have to output.

You will end up with two simple counters repetitions and availableSpace. See below for more detail.

Cleanness of output

While not really enforced, you should not add a space at the end of the line if not needed. Trailing spaces are a general pain in the ass, because you can't see them and might give adverse effects.

Validating arguments

And you need to take care your user does not apply an argument that will break your program (what if the user enters an 1000 character String?), so you need to check for that too.

Java conventions

You already follow most of the java conventions (casing, bracing, etc). But you are missing a package for your class. While not needed, it is good practice.

Exit codes

While not THAT interesting, it is good practice to let you program end with an error code (integer greater than zero) if it could not run succesfully.

Proposed solution

package hundred;

/**
 * Program to print command line argument 100 times Words are never split up. Assuming that the console is 80 characters
 * wide.
 **/
public class Hundred
{
    private static final int LINE_WIDTH = 80;

    public static void main( String[] args )
    {
        if ( args.length == 0 )
        {
            System.err.println( "Argument missing" );
            System.exit( 1 ); //error status
        }
        else
        {
            String word = args[0];
            int availableWidth = LINE_WIDTH;

            if ( word.length() > availableWidth )
            {
                System.err.println( "Argument too long for the line width" );
                System.exit( 1 ); //error status
            }

            int repetitions = 100;

            while ( repetitions > 0 )
            {
                if ( availableWidth < word.length() )
                {
                    System.out.println();
                    availableWidth = LINE_WIDTH;
                }
                System.out.print( word );

                availableWidth -= word.length();

                //We might need a space, but only if the word + space still fits
                if ( availableWidth > word.length() + 1 )
                {
                    System.out.print( " " );
                    availableWidth--;
                }

                repetitions--;
            }
        }
    }
}