Basic Palindrome check comparing chars I've seen variations of this assignment where you reverse a string to match it to the original to find out if it is a palindrome, but this version I made only iterates through half of the string comparing it in reverse and would terminate the loop as soon as it notices a difference between the mirrored char and the current one in the index loop. This causes fewer loops than a reversal of the string.

There is a statement with a ternary operator and a modulus that could be perceived as hard to read.

Is there a better way than comparing chars?
If you saw this in a code test as an answer, what would you assess this as?
Is the more complex line with the ternary operator showing a more advanced knowledge of options or is it only hard to read?

Any other comments are welcome!

public boolean checkPalindrome(String word) {
    boolean palindrome = true;
    int wordLength = word.length() - 1;
    // If the word is dividable by 2 return half else return half including the middle char
    int halfWord = word.length() % 2 == 0? (word.length()/2) : ((int) word.length()/2) + 1 ;
    for(int i = 0; i < halfWord; i++) {
        char first = word.toLowerCase().charAt((wordLength - i));
        char last = word.toLowerCase().charAt(i);
        if(!(first == last)) {
            palindrome = false;
            break;
        }
    }
    return palindrome;
}

Your basic approach looks good.  However I noticed a few things:

You're not checking for strings with 0 characters.

The ternary statement adjusting for odd or even length is unnecessary.  Simply dividing by 2 and adding 1 will work for both odd or even lengths.

Inside the loop, you're calling toLower() twice on each iteration.  This is quite inefficient.  Storing the word converted to lower case in a variable and using that instead of the passed string would be much more efficient.

When testing for inequality it is usually better to use the inequality operator(!=) instead of not(!) and equals(==).  It's more concise and easier to read.


Get the Nth Term in the Fibonacci Sequence I'm trying out a new editor (CLion) and I decided to try an old well known programming problem. I also decided to try out C99 rather than C89.

This program calculates the nth term of the Fibonacci Sequence where the value of the current term is the sum of the 2 previous terms. The first 4 terms are 0, 1, 1, 2. The upper limit applied in the program is the 91st term, on my computer using long long the term value goes negative at 93rd term.

All Comments and observations are appreciated. I'm especially interested in performance, function and variable names and suggestions about how I can increase the range of terms using integers. I know I can use doubles but that may incur floating point errors at some point. As far as performance goes, the program has a nice small memory signature (0.5% of the system memory) speed is where I would be worried.

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

static const int MinimumTerm = 0;
static const int MaximumTerm = 91;
static const int MaxTries = 3;
static const int inputFailure = -1;

static int getTermCount()
{
    char *fmtstr = "Please enter an integer value between %d and %d\n";
    printf(fmtstr, MinimumTerm, MaximumTerm);

    int term = 0;
    int count = 0;
    do
    {
        scanf("%d", &term);
        if (count < MaxTries)
        {
            if (term < MinimumTerm || term > MaximumTerm)
            {
                fprintf(stderr, fmtstr, MinimumTerm, MaximumTerm);
            }
        }
        else
        {
            return inputFailure;
        }
        count++;
    } while (term < MinimumTerm || term > MaximumTerm);

    return term;
}

static long long getNthFibonacciTerm(int term)
{
    int termCount = 2;
    long long prevValue = 0;
    long long nthValue = 1;

    switch  (term)
    {
        case 0: return 0;
        case 1: return 1;
    }

    while  (termCount < term)
    {
        long long newValue = prevValue + nthValue;
        prevValue = nthValue;
        nthValue = newValue;
        termCount++;
    }

    return  nthValue;
}

int main()
{
    int term = getTermCount();
    if (term < MinimumTerm)
    {
        fprintf(stderr, "Invalid Input\n");
        return EXIT_FAILURE;
    }

    printf("The %d term of the Fibonacci Sequence is %lld\n", term, getNthFibonacciTerm(term));

    return EXIT_SUCCESS;
}

A few points about improving code

It seems that your naming convention for constants is to use a capitalized identifier. If so, that should be applied consistently for all constants including inputFailure.
The loop in the function getTermCount can be simplified. A for-loop is clearer IMO.
The output of getNthFibonacciTerm is actually off by one term (assuming the sequence starts with 0 at index 0). It outputs 1 for input 3. The conditional checks before the loop could also be avoided to simplify the code.
Since the Fibonacci sequence is non-negative, the output could use an unsigned integer to allow slightly larger inputs.

About input range: since the output exceeds the limit of unsigned long long when the input is over 93, I do not see how it can be accurately represented unless you try to implement representations of big integers yourself in C.
About performance: there are several \$\Theta(\log n)\$ algorithms for computing Fibonacci numbers for a given input \$n\$. If you want that, here is a list of all algorithms.

Here is an improved version:

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

static const int MinimumTerm = 0;
static const int MaximumTerm = 93;
static const int MaxTries = 3;
static const int InputFailure = -1;

static int getTermCount()
{
    const char *fmtstr = "Please enter an integer value between %d and %d\n";

    for (int count = 0; count < MaxTries; count++)
    {
        int term;

        printf(fmtstr, MinimumTerm, MaximumTerm);    // IMO it is fine to just output to stdout before all attempts fail
        scanf("%d", &term);
        if (term >= MinimumTerm && term <= MaximumTerm)
        {
            return term;
        }
    }

    return InputFailure;
}

static unsigned long long getNthFibonacciTerm(int term)
{
    unsigned long long nthValue = 0;
    unsigned long long nextValue = 1;  // (n+1)th value, you may find a better name for that

    for (int termCount = 0; termCount < term; termCount++)
    {
        unsigned long long newValue = nthValue + nextValue;
        nthValue = nextValue;
        nextValue = newValue;
    }

    return nthValue;
}

int main()
{
    int term = getTermCount();
    if (term == InputFailure)
    {
        fprintf(stderr, "Invalid Input\n");
        return EXIT_FAILURE;
    }

    printf("The %d term of the Fibonacci Sequence is %llu\n", term, getNthFibonacciTerm(term));
    return EXIT_SUCCESS;
}


Calculate work progress in percentage of batches that contain tasks and task contain sub tasks I am trying to calculate work progress in percentage.  I have multiple batches, and each batch contains a set of tasks and each task also contains a set of sub tasks.  Below code is the best I could do.  Is there any more efficient way to do this?

I just edited the code using the Math static method to do help with rounding and getting the next up value.

    double numOfBatches = 3;
    double weightOfEachBatch = (1*100)/numOfBatches;

    double numOfTasksInEachBatch = 1;
    double weightOfEachTask =
        (1*weightOfEachBatch)/numOfTasksInEachBatch;

    double numOfSubTasksInEachTask = 2;
    double weightOfEachSubTask =
        (1*weightOfEachTask)/numOfSubTasksInEachTask;

    System.out.println("Weight of each batch: " + weightOfEachBatch + "%");
    System.out.println("Weight of each task: " + weightOfEachTask + "%");
    System.out.println("Weight of each sub task: " + weightOfEachSubTask + "%");

    double fromBatchWeight = 0;
    for(int i = 1; i <= numOfBatches; i++) {

        double toBatchWeight = weightOfEachBatch * i;
        System.out.println(
                "Batch " + i +
                " from " + Math.floor(fromBatchWeight) +
                "% to " + Math.floor(toBatchWeight) + "%");

        double fromTaskWeight = fromBatchWeight;
        for(int j = 1; j <= numOfTasksInEachBatch; j++) {

            double toTaskWeight = (weightOfEachTask * j) + fromBatchWeight;
            System.out.println(
                    "\tTask " + j +
                    " from " + Math.floor(fromTaskWeight) +
                    "% to " + Math.floor(toTaskWeight) + "%");

            double fromSubTaskWeight = fromTaskWeight;
            for(int k = 1; k <= numOfSubTasksInEachTask; k++) {

                double toSubTaskWeight = (weightOfEachSubTask * k) + fromTaskWeight;
                System.out.println(
                        "\t\tSub Task " + k +
                        " from " + Math.floor(fromSubTaskWeight) +
                        "% to " + Math.floor(toSubTaskWeight) + "%");

                fromSubTaskWeight = Math.nextUp(toSubTaskWeight);
            }

            fromTaskWeight = Math.nextUp(toTaskWeight);
        }

        fromBatchWeight = Math.nextUp(toBatchWeight);
    }

The output looks like this

Weight of each batch: 33.333333333333336%
Weight of each task: 33.333333333333336%
Weight of each sub task: 16.666666666666668%
Batch 1 from 0.0% to 33.0%
    Task 1 from 0.0% to 33.0%
        Sub Task 1 from 0.0% to 16.0%
        Sub Task 2 from 16.0% to 33.0%
Batch 2 from 33.0% to 66.0%
    Task 1 from 33.0% to 66.0%
        Sub Task 1 from 33.0% to 50.0%
        Sub Task 2 from 50.0% to 66.0%
Batch 3 from 66.0% to 100.0%
    Task 1 from 66.0% to 100.0%
        Sub Task 1 from 66.0% to 83.0%
        Sub Task 2 from 83.0% to 100.0%

System.out.println("\t\tSub Task " + k + " from " + Math.floor(fromSubTaskWeight) + "% to "
    + Math.floor(toSubTaskWeight) + "%");

I'd use System.out.format here, it's easier to read than string concatenation:

System.out.format("\t\tSub Task %d from %f%% to %f%%%n",
    k, Math.floor(fromSubTaskWeight), Math.floor(toSubTaskWeight));

With that you can easily format floating numbers.

Weight of each task: 33,333333%
Weight of each sub task: 16,666667%

Could be a readable

Weight of each task: 33,33%
Weight of each sub task: 16,67%

With

System.out.format("Weight of each task: %.2f%%%n", weightOfEachTask);
System.out.format("Weight of each sub task: %.2f%%%n", weightOfEachSubTask);

Having three nested for loops is hard to read. I'd try to extract out a printSubtaskWeights and a printTaskWeights method.
I've seen earlier the numOfSubTasksInEachTask style variables but I've found subTasksInEachTaskNumber more easier to work with. Maybe because if more than one variable starts with numOf it's hard to differentiate them.
i, j, k variables could be more descriptive and could express their purpose. For example,
batchNumber, taskNumber and subtaskNumber.
Batches, tasks and subtasks looks very similar. I'd try to create a common abstraction for them and use that three times instead of duplication.

public class Item {

    private int subItemCount;
    private double weight;

    public Item(final int subItemCount, double weight) {
        super();
        this.subItemCount = subItemCount;
        this.weight = weight;
    }

    public int getSubItemCount() {
        return subItemCount;
    }

    public double getOneSubItemWeight() {
        final double subItemWeight = (1 * weight) / subItemCount;
        return subItemWeight;
    }

    public String getWeightInfo() {
        return String.format("Weight of each %s: %.2f%%",
            name, getOneSubItemWeight());
    }
}

(I'd call it Task but it hasn't already been used.)

I started refactoring the code but I guess I won't finish it. The beginning of the code looked like this:

final Item batches = new Item(3, 100);
final Item tasks = new Item(1, batches.getOneSubItemWeight());
final Item subtasks = new Item(2, tasks.getOneSubItemWeight());

100 is the batches' weight, tasks and subtasks inherit the weight of their parents.

Note that the duplicated Weight of each print statement was also moved to the Item class.

I'd also try to move a loop into the Item class and call subitem printing from that method. I'd reduce the number of loops to one. Something like this:

public class Item {

    private final Item subitems;
    ...

    public void print(double fromWeight) {
        for (int item = 1; item <= itemCount; item++) {

            double toWeight = getItemWeight() * item;
            System.out.format("%s %d from %f%% to %f%%%n",
                name, item, Math.floor(fromBatchWeight),
                Math.floor(toBatchWeight));

            if (subitems != null) {
                subitems.print(fromWeight);
            }
            fromWeight = Math.nextUp(toWeight);
    }
}


Checkout (page) backend I am developing an e-commerce site and am confused about this.

Customers come on the site and add some products to the cart.
Customers click on the checkout link if already logged in, then will go to the "thanks" page (this is your order number, total price, etc.).

I want to insert the total price into Order table.

<?php
session_start();
include('../includes/dbfunctions.php');
if(!isset($_SESSION["id"]))
{
header("location:order_login.php");
}
if(isset($_SESSION['id']))
{
$id=$_SESSION["id"];
$email=$_SESSION["email"];
$name=$_SESSION['name'];
$contact=$_SESSION["contact"];
$mysqli->query("insert into     orders(user_id,user_name,contact_no,email)values('$id','$name','$contact','$email')");

$result=$mysqli->query("select order_id from orders where user_id='$id'   ORDER BY order_id desc limit 1");
$obj=$result->fetch_object();
$order_id=$obj->order_id;
}
?>
<form action="#" method="post" enctype="multipart/form-data">

  <?php
        //Display of cart

        if(isset($_SESSION["products"]))
        {
            $total = 0;
            $qty=0;
            ?>

        <?php
        foreach ($_SESSION["products"] as $cart_itm)
        {
            $product_qty = $cart_itm["qty"];
            $product_code=$cart_itm["product_code"];
            $image=$cart_itm["pic"];
            $product_name=$cart_itm["name"];

            echo '';
            echo 'ucwords($product_name)';
            echo 'ucwords($product_code)';
            echo 'ucwords($product_qty)';
            $subtotal = ($cart_itm["price"]*$product_qty);
            $total = ($total + $subtotal);
            echo '$subtotal';
            $qty=($product_qty+$qty);

            $mysqli->query("insert into order_details(user_id,img,product_name,product_code,qty,sub_total,order_id)values('$id','$image','$product_name','$product_code','$product_qty','$subtotal',$order_id)");

            }
            ?>
</form>

I see two obvious problems:

Your MySQLi queries are vulnerable to sql-injection since you are constructing the queries using string interpolation.  You should use properly parameterized queries with ? placeholders instead.
The business logic is heavily intertwined with the HTML generation.  You would be better off handling the input first (using PHP more like a programming language), writing the order to the database, then when the transaction has successfully completed, proceed to display the output (using PHP as a template language).


Word transformation function My code does what it's suppose to do but the code is failing Pylint checks.
After pasting my code into Pylint checker, it says that Too many branches (15/12) and its failed me on the Pylint checks.

How can this be cleaned up?

"""Docstring"""
import words

def nicer_englishify_word(word):
    """Docstring"""
    wordx = word.lower()
    wordy = ""
    if wordx.endswith('moo'):
        vowel = True
    else:
        vowel = False
    if vowel == True:
        wordy1 = wordx[-3] + wordx[:-3]
        wordy2 = wordx[:-3]
        if wordy1 in words.get_word_list():
            wordy11 = True
        else:
            wordy11 = False
        if wordy2 in words.get_word_list():
            wordy22 = True
        else:
            wordy22 = False
        if wordy11 == wordy22:
            if wordy11 == True:
                wordy = "sametrue"
            else:
                wordy = "samefalse"
        else:
            if wordy22 == False:
                wordy = "[" + wordx[-3] + wordx[:-3] + "]"
            else:
                wordy = "[" + wordx[:-3] + "]"
        if wordy == "sametrue":
            wordy = wordx[-3] + wordx[:-3] + " or " + wordx[:-3]
            wordy = "<" + wordy + ">"
        if wordy == "samefalse":
            wordy = wordx[-3] + wordx[:-3] + " or " + wordx[:-3]
            wordy = "(" + wordy + ")"
    else:
        wordy = wordx[-3] + wordx[:-3]
    return wordy

def nicer_englishify_sentence(sentence):
    """docstring"""
    stringlist = sentence.split()
    result = ""
    for item in stringlist:
        result = result + nicer_englishify_word(item) + " "
    result = result[:-1]
    return result

If true, true. If false, false.

Your code is filled with situations like this:

if someCondition:
    variable = True
else:
    variable = False

You can replace all those occurrences with a simple assignment:

variable = someCondition

If, and if not

Additionally, there's no need to add == True in a comparison. The Python way of x == False is to do not x

Conditional ternary operator

if wordy11:
    wordy = "sametrue"
else:
    wordy = "samefalse"

Can be written as:

wordy = "sametrue" if wordy11 else "samefalse"

Variable names

What on earth is wordy? What type is it? It seems to be one variable used for all kinds of things. I'd recommend making these separate variables and using more descriptive variable names.

Result

This will clean up your code a bit at least, to this point:

"""Docstring"""
import words

def nicer_englishify_word(word):
    """Docstring"""
    wordx = word.lower()
    wordy = ""

    if wordx.endswith('moo'):
        wordy1 = wordx[-3] + wordx[:-3]
        wordy2 = wordx[:-3]
        wordy11 = wordy1 in words.get_word_list()
        wordy22 = wordy2 in words.get_word_list()
        if wordy11 == wordy22:
            wordy = "sametrue" if wordy11 else "samefalse"
        else:
            if not wordy22:
                wordy = "[" + wordx[-3] + wordx[:-3] + "]"
            else:
                wordy = "[" + wordx[:-3] + "]"
        wordy = wordx[-3] + wordx[:-3] + " or " + wordx[:-3]
        wordy = "<" + wordy + ">" if wordy == "sametrue" else "(" + wordy + ")"
    else:
        wordy = wordx[-3] + wordx[:-3]
    return wordy


How to lose plants and aggravate people Courtesy of a few posts around here I've discovered HackerRank. Poisonous Plants is one of their challenges.

Of course, skip the following if you'd like to try it yourself.

Challenge:

  There are \$N\$ plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, it dies.

  Given the initial values of pesticide in each plant, print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left.

Input Format:

  The input consists of an integer \$N\$. The next line consists of N integers describing the array P where P[i] denotes the amount of pesticide in plant i.

Constraints:

  \$1 \le N \le 100000\$
  \$0 \le P[i] \le 10^9\$

Output Format:

  Output a single value equal to the number of days after which no plants die.

Solution:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int[] garden = new int[input.nextInt()];
        for (int i = 0; i < garden.length; i++) {
            garden[i] = input.nextInt();
        }

        int days = 0;
        while(killCommand(garden)) {
            days++;
        }

        System.out.println(days);
    }

    private static boolean killCommand(int[] garden) {
        boolean plantDied = false;
        int lastIndex = garden.length - 1;
        int last = garden[lastIndex];

        for (int i = lastIndex - 1; i >= 0; i--) {
            if (garden[i] == -1) {
                continue;
            }
            int current = garden[i];
            if (current < last) {
                plantDied = true;
                garden[lastIndex] = -1;
            }
            last = current;
            lastIndex = i;
        }

        return plantDied;
    }
}

Sample Input:

  7
  6 5 8 4 7 10 9

Sample Output:

  2

My algorithm works and passes 21 of 23 test cases, but doesn't meet their allotted time for two. How can it be further optimized?

Your code is indeed correct but it is slow: for each day, you are looping over the whole array of numbers to determine if a given plant is killed in that day. You won't be able to optimize your approach further than what you already have. To validate the last 2 test inputs, you need to take another approach.

This problem can be tackled in O(n) complexity by only processing the input array once, from left to right, as was done in this other code review. The idea of the algorithm is to traverse it only once and calculate, for each plant, the number of days it will stay alive.

The observation that can be made is that the number of days plant i will stay alive is the number of days the right-most plant to the left of i that has less pesticide than i, incremented by 1. And if there are none, then the plant never dies. Taking an example:

 6   5   8   4   7   10   9
             |   +--------+
             |   |        |
             |   |        when will this plant die?
             +---|
             |   the day after this one dies and when will this one die?
+------------|
|            the day after this one dies and when will this one die?
|
never
|
+------------0---1--------2

Since we reached the beginning of the array, we know that the plant with pesticide 4 never dies, hence the plant with pesticide 7 dies on day 1 and the plant with pesticide 9 dies on day 2.

We can then improve this first approach. By going from left to right, if we hit a plant i that will never die, we can actually forget all the plants before and stop checking them because any plant waiting for one of those to die will have to wait for i to die first and we know that it will never happen.

In terms of code, this can be implemented by having a stack of a Plant class that would hold its pesticide count and the number of days it stays alive. For each number, we start from the top of the stack and look the closest plant behind having less pesticide; in the mean time, we keep a running daysAlive that is simply the maximum days alive of the encoutered plants and we remove them as we go on. If we reached the end and the stack is empty, it means the plant never dies so we set its daysAlive to 0 and push it to the stack. Otherwise, it means the plant dies the day after that one and we push it to the stack.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    int[] garden = new int[input.nextInt()];
    for (int i = 0; i < garden.length; i++) {
        garden[i] = input.nextInt();
    }

    System.out.println(maxDaysAlive(garden));
}

private static int maxDaysAlive(int[] numbers) {
    Deque<Plant> stack = new ArrayDeque<>();
    int maxDaysAlive = 0;
    for (int pesticide : numbers) {
        int daysAlive = 0;
        while (!stack.isEmpty() && pesticide <= stack.peek().pesticide) {
            daysAlive = Math.max(daysAlive, stack.pop().days);
        }
        if (stack.isEmpty()) {
            daysAlive = 0;
        } else {
            daysAlive++;
        }
        maxDaysAlive = Math.max(maxDaysAlive, daysAlive);
        stack.push(new Plant(pesticide, daysAlive));
    }
    return maxDaysAlive;
}

private static class Plant {

    int pesticide = 0, days = 0;

    public Plant(int pesticide, int days) {
        this.pesticide = pesticide;
        this.days = days;
    }

}


C program to print input longer than 10 characters The program will read the user's input, if it's longer or equal to 10 characters, it will print it.

It's pretty compact and works fine.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000

int main(void){
    char line[MAX_SIZE];
    int length; /*String length*/

    while((fgets(line, sizeof(line), stdin) != NULL)){
        line[length = (strlen(line)-1)] = '\0'; /*Remove the \n character*/
        if(length >= 10){
            printf("%s\n", line);
        }
    }
    return 0;
}

Not looking for anything specific, method, style, etc..

The magic value 10 is embedded deep in the logic; I would make it an obvious constant (it might one day come from the command-line arguments).

Before overwriting the final \0 with NUL, you will probably want to check that it is actually \n.  If not, then you may have received the start of a line that's more than 1000 characters, and you'll want to print it and all the subsequent inputs until you do receive a \n (note that if you receive 1000 chars and then 5 chars, you can't ignore the 5-char input, because it's actually part of a 1005-char line).  Also, consider when an input line is read as two separate 6-character chunks - your code would discard both, instead of treating them as a single 12-char unit.

Overwriting the final \n with NUL seems to me pointless here, as you add one back on when writing it out.  It's probably better to keep the newline there, and increase your comparison size to take account of it.

Error checking - fgets() can fail, but you treat all failures as end-of-file.  Also, we don't normally write != NULL explicitly; all non-NULL values are true, so reduce the clutter.

The scope of length can be reduced, as it's not used outside the loop.  Except that I'm going to keep track of the length of lines that are split over more than one read, which moves it back again.

Minor style nit: I don't like writing the sizeof operator to look like a function.  It isn't a function, and I prefer it to be distinct.  I know there's a spectrum of opinion on that, so I won't push the point.

It gets surprisingly involved when you take into account partial reads and longer lines:

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

#define MAX_SIZE 1000

const int max_len = 10;

int main(void)
{
    char line[MAX_SIZE];
    int length = 0;
    int is_continuation = 0;

    while (fgets(line + length, (sizeof line) - length, stdin)) {
        length += strlen(line + length);
        /* length includes the final newline */
        if (is_continuation || length >= max_len+1) {
            printf("%s", line);
            is_continuation = line[length-1] != '\n';
            length = 0;
        } else {
            is_continuation = line[length-1] != '\n';
            if (!is_continuation)
                /* reset for next read */
                length = 0;
        }
    }

    /* do we have any remaining input?  It may or may not end in newline */
    if (length) {
        if (is_continuation || length >= max_len + (line[length-1] == '\n')) {
            printf("%s", line);
            length = 0;
            is_continuation = line[length-1] != '\n';
        }
    }

    if (feof(stdin))
        return EXIT_SUCCESS;

    perror("stdin");
    return EXIT_FAILURE;
}


Generate all elements of a power set /*
 * Power set is just set of all subsets for given set.
 * It includes all subsets (with empty set).
 * It's well-known that there are 2N elements in this set, where N is count of elements in original set.

 * To build power set, following thing can be used:

 * Create a loop, which iterates all integers from 0 till 2^N-1
 * Proceed to binary representation for each integer
 * Each binary representation is a set of N bits (for lesser numbers, add leading zeros).
 * Each bit corresponds, if the certain set member is included in current subset.
 */
import java.util.NoSuchElementException;
import java.util.BitSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.List;
import java.util.ArrayList;

public class PowerSet<E> implements Iterator<Set<E>>, Iterable<Set<E>> {
    private final E[] ary;
    private final int subsets;
    private int i;

    public PowerSet(Set<E> set) {
        ary = (E[])set.toArray();
        subsets = (int)Math.pow(2, ary.length) - 1;
    }

    public Iterator<Set<E>> iterator() {
        return this;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Cannot remove()!");
    }

    @Override
    public boolean hasNext() {
        return i <= subsets;
    }

    @Override
    public Set<E> next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        Set<E> subset = new TreeSet<E>();
        BitSet bitSet = BitSet.valueOf(new long[] { i });
        // get the index of truth values.
        for (int e = bitSet.nextSetBit(0); e != -1; e = bitSet.nextSetBit(e + 1)) {
            subset.add(ary[e]);
        }
        i++;
        return subset;
    }

    // Unit Test
    public static void main(String[] args) {
        Set<Integer> numbers = new TreeSet<Integer>();
        for (int i = 1; i < 5; i++) {
            numbers.add(i);
        }
        int count = 0;
        PowerSet<Integer> pSet = new PowerSet<Integer>(numbers);
        for (Set<Integer> subset : pSet) {
            //System.out.println(subset);
            count++;
        }
        assert count ==  (int)Math.pow(2, numbers.size()): "Total number of elements should be 2^N";
    }
}

The code is running fine. I am trying to learn assert for unit testing the code as well. The main issue is the elements seem to come out of order. Is there any way to maintain lexicographical order?

Power of 2
Instead of using:
(int)Math.pow(2, numbers.size())

You can compute a power of two more efficiently like this:
1 << numbers.size()

You can use 1L to compute it as a long if you think that the power may exceed 31.
Manual bit manipulation
Instead of using a BitSet to find the 1 bits in your int, you can use integer arithmetic to check the bits yourself:
    for (int bit = 0; bit < 32; bit++) {
        if ((i & (1 << bit)) != 0) {
            subset.add(ary[bit]);
        }
    }


Simple linked list with two iterators As part of the practice, I created minimalist linked list named SimpleList which can be iterated in two different ways: one element after another or by every second element.

Because I'm beginner I would really appreciate your opinion about my solution. Is it correct? What should I change?

public class SimpleList<T> : IEnumerable<T>
{
    protected class Node
    {
        public T Data { get; set; }
        public Node NextNode { get; set; }

        public Node(T data, Node nextNode)
        {
            Data = data;
            NextNode = nextNode;
        }
    }

    protected Node Head { get; set; } = null;

    public void Add(T data)
    {
        Head = new Node(data, Head);
    }

    #region IEnumerable<T> implementation
    public IEnumerator<T> GetEnumerator()
    {
        var current = Head;
        while (current != null)
        {
            yield return current.Data;
            current = current.NextNode;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    #endregion

    #region second iterator implementation
    private class EverySecondElementIterator : IEnumerable<T>
    {
        private readonly Node head;

        public EverySecondElementIterator(Node head)
        {
            this.head = head;
        }

        public IEnumerator<T> GetEnumerator()
        {
            var current = head;
            while (current != null)
            {
                yield return current.Data;
                current = current.NextNode?.NextNode;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public IEnumerable<T> EverySecondElement => new EverySecondElementIterator(Head);
    #endregion
}

Use extension methods
I find you did well by implementing the EverySecondElementIterator as a separate class. However, I also think it would be better to turn it into an extension of IEnumerable<T> and use MoveNext instead of the internal Node.
Otherwise if someone suddenly comes up with the idea to skip every third element, you would need to modify the original SimpleList by creating another private class class and another property. We usually try to avoid modifying code that is tested and is working well. This would also violate the open/closed principle.
It's much safer and extendable to create a new and independent extension that you also can resue with any IEnumerable<T> and skip every-second-element of any collection.
Let the SimpleList be closed for modifications by not implementing anything as specific as that enumerator. It is already opend for extension by implementing the IEnumerable<T> interface. Make use of it.


boost::thread producer consumer I am new toboost::thread and am making a producer-consumer with a Monitor. This is how I've coded it so far:

//{ Declarations in header
private:
  boost::condition_variable    _condition;
  boost::mutex                 _mutex;
  std::deque<RawMatrix*>       _queue;
  boost::detail::atomic_count  _count;
//}

void MatrixMonitor::deposit(RawMatrix* rawMatrix){
    boost::unique_lock<boost::mutex> lock(_mutex);
    _condition.wait(lock, boost::bind(std::less_equal<int>(), boost::ref(_count), max));
    _queue.push_back(rawMatrix);
    ++_count;
    _condition.notify_one();
}

RawMatrix* MatrixMonitor::withdraw(){
    boost::unique_lock<boost::mutex> lock(_mutex);
    _condition.wait(lock, boost::bind(std::greater_equal<int>(), boost::ref(_count), min));
    RawMatrix* elem = _queue.front();
    _queue.pop_front();
    --_count;
    _condition.notify_one();
    return elem;
}

So far I've written the Producer like this:

void MatrixProducer::produce(){
    while(true){
        boost::mutex::scoped_lock lock(_mutex);
        RawMatrix* matrix = rawMatrix();
        _monitor->deposit(matrix);
        boost::this_thread::sleep(boost::posix_time::milliseconds(sleep_msecs));
    }
}
boost::thread& MatrixProducer::start(){
    _thread = boost::thread(boost::bind(&MatrixProducer::produce, this));
    return _thread;
}
RawMatrix* MatrixProducer::rawMatrix(){/*Generates and returns a matrix*/}

The Consumer:

boost::thread& MatrixConsumer::start(){
    _thread = boost::thread(boost::bind(&MatrixConsumer::consume, this));
    return _thread;
}

void MatrixConsumer::consume(){
    while(true){
        boost::mutex::scoped_lock lock(_mutex);
        RawMatrix* matrix = _monitor->withdraw();
        _matrix->deposit(Matrix);
        boost::this_thread::sleep(boost::posix_time::milliseconds(sleep_msecs));
    }
}

Is this okay? Also, who will have the ownership of this: Producer or Consumer and Monitor?

Why do you insist on putting the '' on members. It makes them look so ugly. Also most identifiers beginning with '' are reserved so you need to be careful. If you must use decade old conventions (that have been abandoned) to identify members use 'm_` as the prefix.

The reason I hate them is for this:

--_count;

// That is ugly and harder to read than:

--count; // but that's just an opionon.
         // The bit about being reserved is a problem though.
         // and if you use leading underscores you should understand
         // all the associated rules.

Curious where max/min come from?

_condition.wait(lock, boost::bind(std::less_equal<int>(), boost::ref(_count), max));
                                                                        //   ^^^^^

Passing RAW pointers around is not common in C++ (unlike C).
Normally you wrap a pointer inside a smart pointer object to indicate ownership semantics (and thus who is responsible for deleting the object).

// No indication of ownership is retained or passed the the moniter.
// So we have no idea who should delete rawMatrix?
//
// Have you passed ownership to the moniter or is the caller retaining ownership
// If the owner retains ownership when does he delete it?
void MatrixMonitor::deposit(RawMatrix* rawMatrix){

// I suppose you have to return a pointers as you were passed a pointer.
// but now the caller has no idea weather he should delete the pointer he
// is given or if the pointer is still owned by somebody else.
RawMatrix* MatrixMonitor::withdraw(){

Personally I would change the interface to make sure the ownership symantics are well defined. In this case I would pass ownership to the moniter and pass ownership out to the person withdrawing the item:

void MatrixMonitor::deposit(std::unique_ptr<RawMatrix> rawMatrix){

std::unique_ptr<RawMatrix> MatrixMonitor::withdraw(){

I think you want to separate producer and consumer from the Moniter. These are three different types of object. When you construct the producer/consumer you pass it a monitor object to use when it deposits/withdraws items.

int main()
{
      MatrixMonitor   monitor;
      Producer        farmer(monitor);  // Pass monitor by reference
                                        // So the farmer is adding to this moiter.
      Consumer        shopper(moniter); // shooper uses the same monitor as the
                                        // farmer but because it is a consumer will
                                        // call withdraw() while the
                                        // farmer calles deposit()

      farmer.run();
      shopper.run();

      // don't forget to wait for the threads to exit.
      farmer.join();
      shopper.join();
}

Edit: Based on new code for Producer/Consumer

One would assume that the producer needs to finish at some point.
You may want to change while(true) into while(!finished) or similar.

void MatrixProducer::produce(){
    while(true){

Don't see any need for this mutex.

        boost::mutex::scoped_lock lock(_mutex);

Ownership semantics again. Who owns the generated matrix?

        RawMatrix* matrix = rawMatrix();


Designing posts: state machine In the Object-Oriented Design Pattern Implementation chapter of the second edition of The Rust Programming Language, the basic code structure is given and it suggests trying to add features:

  This implementation is easy to extend to add more functionality. Here
  are some changes you can try making to the code in this section to see
  for yourself what it's like to maintain code using this pattern over
  time:

  Only allow adding text content when a post is in the Draft state
  Add a reject method that changes the post's state from PendingReview back to Draft
  Require two calls to approve before changing the state to Published

Please critique my approach:

struct Post {
    content: String
}

struct DraftPost {
    content: String
}

struct PendingPost {
    content: String,
    approvals: u32

}

impl Post {
    fn new() -> DraftPost {
        DraftPost { content: String::new() }
    }

    fn content(&self) -> &str {
        &self.content
    }
}

impl DraftPost {
    fn req_review(self) -> PendingPost {
        PendingPost {
            content: self.content,
            approvals: 0
        }
    }

    fn add_text(&mut self, content: &str) {
        self.content.push_str(content);
    }
}

enum PublishResult {
    PendingPost(PendingPost),
    Post(Post)
}

impl PendingPost {
    fn approve(&mut self) {
        self.approvals += 1;
    }
    fn reject(self) -> DraftPost {
        DraftPost { content: self.content }
    }
    fn publish(self) -> PublishResult {
        if self.approvals > 1 {
            PublishResult::Post(Post{content: self.content})
        } else {
            PublishResult::PendingPost(self)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn publish_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let mut pending = draft.req_review();
        pending.approve();
        pending.approve();
        let publish = pending.publish();
        match publish {
            PublishResult::Post(p) => assert_eq!(p.content(),
                                                 "ashish first post"),
            _ => assert!(false)
        }
    }

    #[test]
    fn reject_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let pending = draft.req_review();
        let mut again_draft = pending.reject();
        again_draft.add_text(".. after first one..");
    }

    #[test]
    fn two_approvals_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let mut pending = draft.req_review();
        pending.approve();
        match pending.publish() {
            PublishResult::PendingPost(_) => assert!(true),
            _ => assert!(false)
        }
    }
}

Overall, everything seems fine. Some minor nits and suggestions:

Stylistically, you should have:

trailing commas
spaces on struct literals (Post { content: self.content }

PublishResult makes me think it's a type alias of std::result::Result. I'd advocate for picking a different name.
Instead of matching in your tests and having the not-very-useful assert!(true) and assert!(false), add some helper methods to PublishResult to convert to an expected variant. This is a common pattern for this style of enum. Then you can expect with text in your tests
Dnt ndlssly abbr mthds (Don't needlessly abbreviate methods). Call it request_review instead of req_review.
It's strange to have a test (reject_workflow) with no assertions. I don't think anything's wrong with it, as it's testing the methods and types, it's just a bit implicit.

struct Post {
    content: String,
}

struct DraftPost {
    content: String,
}

struct PendingPost {
    content: String,
    approvals: u32,
}

impl Post {
    fn new() -> DraftPost {
        DraftPost { content: String::new() }
    }

    fn content(&self) -> &str {
        &self.content
    }
}

impl DraftPost {
    fn request_review(self) -> PendingPost {
        PendingPost {
            content: self.content,
            approvals: 0,
        }
    }

    fn add_text(&mut self, content: &str) {
        self.content.push_str(content);
    }
}

enum PublishResult {
    PendingPost(PendingPost),
    Post(Post),
}

impl PublishResult {
    fn into_pending_post(self) -> Option<PendingPost> {
        use PublishResult::*;
        match self {
            PendingPost(v) => Some(v),
            _ => None,
        }
    }

    fn into_post(self) -> Option<Post> {
        use PublishResult::*;
        match self {
            Post(v) => Some(v),
            _ => None,
        }
    }
}

impl PendingPost {
    fn approve(&mut self) {
        self.approvals += 1;
    }
    fn reject(self) -> DraftPost {
        DraftPost { content: self.content }
    }
    fn publish(self) -> PublishResult {
        if self.approvals > 1 {
            PublishResult::Post(Post { content: self.content })
        } else {
            PublishResult::PendingPost(self)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn publish_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let mut pending = draft.request_review();
        pending.approve();
        pending.approve();
        let post = pending.publish().into_post().expect("not a post");
        assert_eq!(post.content(), "ashish first post");
    }

    #[test]
    fn reject_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let pending = draft.request_review();
        let mut again_draft = pending.reject();
        again_draft.add_text(".. after first one..");
    }

    #[test]
    fn two_approvals_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let mut pending = draft.request_review();
        pending.approve();
        pending
            .publish()
            .into_pending_post()
            .expect("Not a pending post");
    }
}


CoderCharts puzzle optimization This is my solution to the codercharts problem http://codercharts.com/puzzle/word-swap but if keeps failing when I submit the solution because of the cpu_excess_time. Please suggest possible optimisations for this problem, I believe my solution is correct but not optimal.

#!/usr/bin/python

def swap_words(first_word,second_word,word_dict):
    wd = word_dict
    #if the first word is equal to second ,
    # we have got the target word
    if first_word == second_word:
        return [first_word]
    for word in word_dict:
        if len(word) == len(first_word) and \
           sum([x != y for x,y in zip(list(first_word),list(word))]) == 1:
            wd.remove(word)
            ret = swap_words(word,second_word,wd)
            if ret != False:
                ret.append(first_word)
                return ret
    return False

if __name__ == '__main__':
    import sys
    filename = sys.argv[1]
    first_word = sys.argv[2]
    second_word = sys.argv[3]
    text = open(filename).read()
    word_dict = text.split('\n')
    word_list = swap_words(first_word,second_word,word_dict)
    for word in reversed(word_list):
        print word

Simple optimizations:

By reading the whole file into text, then splitting the text into a word list, you will need enough memory to hold two copies of the file, which might be huge. Look into line-by-line input methods.

Many strings, after a quick check, don't need to be seen ever again.

The off-by-one-letter test does not ALWAYS need to process every letter in the words.

You never actually have to find the target word in the word list to know you have a solution (you know it's in there from the problem description). Some simpler solutions don't even need to consult the word list.

Deeper optimizations:

If you had a way to test which "next" words were more likely to lead to a solution, you might be able to defer other alternatives to explore those first, for a faster average solution time.

It MIGHT make more sense to solve the problem working backwards or both ways at once.

It MIGHT be worthwhile to keep stats on different words you find and/or to place words that seem like they might be useful later in some kind of separate structure.


Search a search button on page and toggle open class and focus on the input I have a jQuery solution as below. I am confident the solution can be made better in terms of OO way using constructor pattern

  var $search = $('.search');

  if ($search.length > 0) {
    $search.removeClass('dropdown radix-dropdown-processed');
    $('.search__button').on('click', function (e) {
      e.preventDefault();
      $search.toggleClass('open');
      $('#site_search_query').focus();
    });
  }

Can someone help in making the code better as in reviewing the code so that it is better in terms of performance

I am confident the solution can be made better in terms of OO way using constructor pattern

Here's the first problem: You assume writing (classical) OO makes everything better. Personally, it's more cumbersome and confusing. You worry what this is, there is state literally everywhere, methods are very side-effect-y, all that unnecessary boilerplate to make a simple operation look fancy but more complicated.

Keep it simple. I'd prefer simple functions over classical OOP.

On the other hand, you are already doing OO. It's just that it's not classical OO, but you're still operating on objects.

Here's a few corrections to the snippet

const $search = $('.search');

A $() function returns an instance of jQuery. It's similar to doing jQuery search = new jQuery('.search') if you're into classical OOP notation.

$search.removeClass('dropdown radix-dropdown-processed');

jQuery objects are array-like objects, containing the matches of your selector. Unless explicitly stated, most methods loop through that array and apply to each item. No items, no loop, therefore method won't run. This makes the length check redundant.

$('.search').on('click', '.search__button', function (e) {
  e.preventDefault();
  e.delegateTarget.toggleClass('open');
});

Now assuming .search__button resides inside .search, you can use delegation. This is where jQuery attaches the handler on an ancestor element to listen for descendant events. The advantage is that it does not rely on the descendant to be there on bind. Also good if you have a lot of descendants to listen. You attach the handler once on the ancestor and not per descendant.

Additionally, you don't need to keep reference of the ancestor you attached the handler to. The event object has a delegateTarget which references the ancestor you attached the event to, in this case .search.

$('#site_search_query').focus();

IDs are brittle. The can only appear once in the page but nothing stops you from putting more than one. The problem appears when you try to grab their reference. document.getElementById as well as jQuery only return the very first one it finds. If your element's id collides with another's and that other comes first, you get the idea.


UVA 10474 - "Where is the marble?" time limit I have a problem from UVA online judge here. I have read it tons of times, and as they said, I have to get the answer really fast.

I have used a binary search and std::sort, but I am still having a time error. I don't know any faster way of searching on an array other than binary search.

Any feedback please?

#include <stdio.h>
#include <string>
#include <algorithm>

int n,q,vec[100000];
int inicio,final,medio,busca;
int cont;
int busquedabinaria()
{

    //busqueda binaria
    std::sort(vec,vec+n);
    inicio=0;
    final=n-1;
    medio=(inicio+final)/2;

    while(inicio<=final)
    {
        if(vec[inicio]==busca)
            return inicio;
        if(vec[medio]==busca)
            return medio;
        if(vec[final]==busca)
            return final;
        medio = (inicio + final) / 2;
        if (vec[medio] > busca)
            final = medio - 1;
        else if (vec[medio] < busca)
            inicio = medio + 1;
        // found

    }
    return -1;

}

int main()
{

    freopen("in.txt", "rt",stdin);
    freopen("out.txt", "wt",stdout);

    while (scanf("%d %d\n",&n,&q)!=EOF && (n!=0 || q!=0)    )
    {
        for (int i=0;i<n;i++)
        {
            scanf("%d\n",&vec[i]);

        }
        printf("CASE# %d:\n",cont+1);
        cont++;
        while(q--)
        {

        scanf("%d\n",&busca);

            int res=busquedabinaria();
            if(res!=-1)
            {
                while (vec[res-1]==busca && res>0)
                {
                    res--;
                }
                printf("%d found at %d\n",busca,res+1);

        }
            else
                printf("%d not found\n",busca);

        }

    }

    return 0;
}

Your solution is slow because it performs the sorting before every binary search! Just move the sorting to the line above the

printf("CASE# %d:\n",cont+1);

and you'll see the difference.

I also add my solution just to see what's possible to optimize (it uses custom int reader, without sort and the binary search):

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

#define SIZE 16*1024
#define N    10001
static unsigned int values[N];
static int  buffer_size = 0;
static int  buffer_pos  = -1;
static char buffer[SIZE];

unsigned int readInt()
{
    unsigned int value  = 0;
    unsigned int digits = 0;
    char b;

    if (buffer_pos == -1)
    {
        buffer_size = fread(buffer, 1, SIZE, stdin);
        buffer_pos  = 0;
    }

    while(buffer_size > 0)
    {

        if (buffer_pos == buffer_size)
        {
            buffer_size = fread(buffer, 1, SIZE, stdin);
            buffer_pos = 0;
        }

        while(buffer_pos < buffer_size)
        {
                b = buffer[buffer_pos++];
                    if (b == '\n' || b == ' ')
            {
                return value;
            }
                    else
            {
                        value = value*10 + (b - '0');
                digits++;
            }
        }
    }
    return value;
}

int main(int argc, char **argv)
{
    long time = clock();

        char buffer[8192];
        setvbuf(stdout, buffer, _IOFBF, sizeof(buffer));
    unsigned int  n, q, num, max, min, c = 0;

    while(1)
    {
        c++;
        n = readInt();
        q = readInt();

        if(n==0 && q==0) break;

        max = 0;
        min = N;
        memset(values, 0, N * sizeof(unsigned int));

        for(unsigned int i=0; i<n; i++)
        {
            num = readInt();
            values[num]++;
            if(num > max) max = num;
            if(num < min) min = num;
        }

        unsigned int pos = 1, temp;
        for(unsigned int i=min; i <= max; i++)
        {
            if(values[i] !=0){
                temp = values[i];
                values[i] = pos;
                pos += temp;
            }

        }

        printf("CASE# %d:\n", c);
        unsigned qval;
        for(unsigned int i=0; i<q; i++)
        {
            qval = readInt();
            int ret = values[qval];
            if(ret == 0)
                printf("%d not found\n", qval);
            else
                printf("%d found at %d\n", qval, ret);
        }
    }
    //printf("Time (ms): %ld\n", clock()-time);
    return 0;
}


Finding capitalized characters and printing their position & ASCII value I was trying to find out if a string contained a capitalized letter and if it did I wanted to know the position of the character and its ASCII code. I might have refactored a little to much.

Given an input such as:

(is-capitalized "Meow mEow kItus kaTus")

My function returns:

((18 . 84) (11 . 73) (6 . 69) (0 . 77))

where the car of each sublist is the position in the string and the CDR of the sublist is the character ASCII code.

Given an input such as:

(is-capitalized "omg my cat attacked my face.")

My function returns: NIL

So I guess it works for what I want but I feel like I reinvented so many things.

How can I improve this code?

(defun string-to-ascii (str)
    "Converts string of characters into a list of ascii character codes
       Returns list of ascii character codes"
      (loop
           :for i
         :in (coerce str 'list)
         :collect (char-code i)
         :into numbers
         :finally (return numbers)))

(defun return-capital-positon (list)
  "Returns list of positions where capitalized characters appear"
  (loop
       :for i
     :in list
     :collect (if (and (> i 65) (< i 90))
                  (position i list)
                  )))

(defun capital-hash (list-1 list-2 &key (test 'eql))
  "Return hash table where key: list-1 :pair list-2"
  (assert (= (length list-1)
              (length list-2)))
  (let ((table (make-hash-table :test test :size (length list-1))))
    (map nil (lambda (k v) (setf (gethash k table) v))
         list-1 list-2)
    table))

(defun do-hash (str)
  "Returns a hash table of key: position in string :pair ascii code character"
  (capital-hash
   (return-capital-positon
    (string-to-ascii str))
   (string-to-ascii str)))

(defun hash-table-alist (table)
  "Returns an association list containing the keys and values of hash table TABLE."
  (let ((alist nil))
    (maphash (lambda (k v)
               (push (cons k v)
                      alist)) table) alist))

(defun is-capitalized (str)
  "Returns a list of sublists in the form:
   ((position in string . ascii code of character)...)
   if string contains capitalized characters
   otherwise returns nil"
  (remove 'nil (hash-table-alist (do-hash str)) :key #'first))

Nits

Check out map:

(def string-to-ascii (str)
  (map 'list 'char-code str))

Note that < takes &rest so you can write (< 65 i 90) instead of (and (> i 65) (< i 90)) (you also want <= instead).

Furthermore, return-capital-positon is quadratic in length of the input string - it can be made linear instead.

do- is a usually used as a prefix for iteration macros.
Also, you call string-to-ascii in do-hash twice; you can use let to remove one call.

Your line breaks in hash-table-alist are very confusing.

You can use delete instead of remove in is-capitalized because hash-table-alist returns a fresh list.

Summary

I think your code is overkill.

(defun is-capitalized (str)
  (loop for char across str for code = (char-code char) for pos upfrom 0
     when (<= 65 code 90)
     collect (cons pos code)))

This has the added benefit that the return value increases in pos (i.e., it returns the reverse of your function).

Alternatively, you can actually avoid constants:

(defun is-capitalized (str)
  (loop for char across str for pos upfrom 0
    when (char= char (char-upcase char))
    collect (cons pos (char-code char))))


Follow-the-cursor eye animation I have code for googly eyes that is too long. Basically I have variables for each element pupils (one for right -other for left), eyesockets (left, right). I wish I could compress my code so I can call a function animateEye (eye).

  function animateEye(eye) {
          console.log(eye);
          var pupille = eye.find("div");

For now this is what I have and I have no idea how to continue.

This is the actual code:

var pupilleLinks = $('#pupilleLinks');
var pupilleRechts = $('#pupilleRechts');

//   var abstandH =  pupille.offset().left- e.pageX + pupille.height()/2;

$(document).on('mousemove', function(e){
    var abstandV1 = pupilleLinks.offset().top- e.pageY +pupilleLinks.height()/2;

    var pupilleL1 = pupilleLinks.position().top - abstandV1 ; // 10 = Breite Pupille / 2
    var augeLinks = $("#augeLinks")
    var distanceX=augeLinks.width()-pupilleLinks.width();
    var distanceY=augeLinks.height()-pupilleLinks.height();
    if(pupilleL1 > distanceY) {
      (pupilleL1 = distanceY);
               }
    if(pupilleL1 < 0) {
      (pupilleL1 = 0);
               }
    var abstandH1 = pupilleLinks.offset().left- e.pageX + pupilleLinks.width()/2;
    var pupilleL2 = pupilleLinks.position().left - abstandH1 ;
    if (pupilleL2 < 0) {
       (pupilleL2 = 0);
               }
    if(pupilleL2 > distanceX) {
      (pupilleL2 =distanceX);
               }
    pupilleLinks.css({
        left: pupilleL2+"px",
        top: pupilleL1+"px"
               });

    var abstandH2 = pupilleRechts.offset().left- e.pageX + pupilleRechts.width()/2;
    var pupilleR1 = pupilleRechts.position().left - abstandH2;
    var augeRechts = $("#augeRechts")
    var distanceX2=augeRechts.width()-pupilleRechts.width();
    var distanceY2=augeRechts.height()-pupilleRechts.height();
    if(pupilleR1 < 0) {
      (pupilleR1 = 0);
               }
    if(pupilleR1 > distanceX2) {
      (pupilleR1 = distanceX2);
               }
    var abstandV2 = pupilleRechts.offset().top- e.pageY + pupilleRechts.width()/2;
    var pupilleR2 = pupilleRechts.position().top - abstandV2;
    if(pupilleR2 < 0) {
      (pupilleR2 = 0);
               }
    if(pupilleR2 > distanceY2) {
      (pupilleR2 =distanceY2);
               }
    pupilleRechts.css({
            left: pupilleR1+"px",
            top: pupilleR2+"px"
               });

    });
.auge {
  position: relative;
  display: inline-block;
  width: 150px;
  height: 150px;
  border: 10px solid black;
}
.pupille {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 30px;
  height: 30px;
  background-color: blue;
  border-radius: 15px;
}

Programming in German results in an awkward mix of English and German identifiers, with conflicting capitalization conventions.  I suggest sticking to English, though I will make an attempt to accommodate your language preference here.

The code is duplicated not only for each eye, but also for each axis, resulting in four copies.  The copy-and-pasted code is hard to follow because you have pasted them in an order that is not quite parallel:

var abstandV1 = …;
var pupilleL1 = …;
var augeLinks = $("#augeLinks")
var distanceX=…;
var distanceY=…;
if …
var abstandH1 = …;
var pupilleL2 = …;
if …

A more logical order would be:

var augeLinks = $("#augeLinks");
var abstandLY = …;
var pupilleLY = …;
var distanceLY = …;
if …
var abstandLX = …;
var pupilleLX = …;
var distanceLX = …;
if …

Instead of using if-statements the enforce the lower and upper bounds, I suggest using Math.min() and Math.max().

Using the same code for the left and right eyes is easy: just make smarter use of jQuery selectors:

$('.pupille').each(function() {
    var $pupille = $(this);
    var $auge = $(this).closest('.auge');
    …
});

Writing one version of the code for both the horizontal and vertical axes is tricker.  I suggest defining a horizontal and a vertikal object to extract the relevant attributes.

var horizontal = {
    groesse:  function($el) { return $el.width(); },
    position: function($el) { return $el.position().left; },
    offset:   function($el) { return $el.offset().left; },
    cursor:   function(event) { return event.pageX; },
};
var vertikal = {
    groesse:  function($el) { return $el.height(); },
    position: function($el) { return $el.position().top; },
    offset:   function($el) { return $el.offset().top; },
    cursor:   function(event) { return event.pageY; },
};

function koordinate($pupille, $auge, cursor, achse) {
    var augeGroesse = achse.groesse($auge) - achse.groesse($pupille);
    var abstand = achse.cursor(cursor) +
                  achse.position($pupille) -
                  achse.offset($pupille) -
                  achse.groesse($pupille) / 2;
    return Math.max(0, Math.min(augeGroesse, abstand));
}

$(document).on('mousemove', function(event) {
    $('.pupille').each(function() {
        var $pupille = $(this);
        var $auge = $(this).closest('.auge');
        $pupille.css({
            left: koordinate($pupille, $auge, event, horizontal) + 'px',
            top:  koordinate($pupille, $auge, event, vertikal) + 'px',
        });
    });
});
.auge {
  position: relative;
  display: inline-block;
  width: 150px;
  height: 150px;
  border: 10px solid black;
}
.pupille {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 30px;
  height: 30px;
  background-color: blue;
  border-radius: 15px;
}


Is there a better way to do this linq sort? I have the following linq statement that is ordering a list of assets by the sort order of a child item:

 Assets.OrderBy(a => a.GalleryItems != null &&
                a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId) != null
                     ? a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId).SortOrder : 1000);

I was wondering if there was a more efficient way to do this as I would have thought having to do 2 a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId) would be pretty poor for performance

You're correct, it can be costly.

You can just expand the lambda expression:

Assets.OrderBy(a => {
    var item = a.GalleryItems != null
               ? a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId)
               : null;
    return item != null ? item.SortOrder : 1000;
});

[Quick edit]

The above will work correctly only for LINQ 2 Objects queries.

If you're using EF or any other LINQ database provider, you should leave the query as-is, because it will probably be translated to ISNULL(..., 1000) or something equivalent.


Implementation of a URL router I was wondering if you could provide some feedback on this Router class I built. Worth noting that it relies on an Apache rewrite rule that always redirects to this file, but passes the path into $_GET['url'] as a string (e.g. A request to http://foo.com/foo/bar) goes into $_GET['url] => 'foo/bar'.

You can then define routes that match against this path string, and the function defined with the route can execute any aribtrary code, like handing off to a controller.

Mainly I would like to know if I should be sanitizing any strings? How could I handle paths that don't match any defined routes?

class Router
{
    private $routes = null;
    private $req_path = null;

    function __construct()
    {
        if (isset($_GET['url']))
            $this->req_path = $_GET['url'];

        // Build the requested path.
        $this->req_path = is_null($this->req_path) ? "/" : "/" . $this->req_path;
    }

    // Create a route with a path and a function associated with that path that we
    // can call.
    function route($path, $handler)
    {
        $this->routes[] = array('path' => $path, 'handler' => $handler);
    }

    // Run the router to compare the request against any defined routes, run the
    // associated function.
    function run()
    {
        if (is_null($this->routes))
            throw new RuntimeException("No routes have been defined");

        foreach($this->routes as $route) {
            if ($route['path'] == $this->req_path) {
                $route['handler']();
                return;
            }
        }
    }
}

$router = new Router();

$router->route("/steve", function() {
    echo "steve";
});

$router->run();

Mainly I would like to know if I should be sanitizing any strings?

Assuming that the only unsafe input is in $_GET['url'],
you're safe: junk that doesn't match a defined route will be ignored.
The routes work effectively like a white list.

  How could I handle paths that don't match any defined routes?

Return a 404 error page (and correctly set status code in the header).

This seems quite redundant:

function __construct()
{
    if (isset($_GET['url']))
        $this->req_path = $_GET['url'];

    // Build the requested path.
    $this->req_path = is_null($this->req_path) ? "/" : "/" . $this->req_path;
}

This should be equivalent and shorter:

function __construct()
{
    // Build the requested path.
    $this->req_path = '/' . @$_GET['url'];
}

Instead of iterating over the list of routes and stop when you find a match,
why not use an associative array instead? Like this:

function route($path, $handler)
{
    $this->routes[$path] = $handler;
}

function run()
{
    if (is_null($this->routes))
        throw new RuntimeException("No routes have been defined");

    if (isset($this->routes[$this->req_path])) {
        $this->routes[$this->req_path]();
        return;
    }
}


Multiple enumerations of IEnumerable I have a snippet of code here that uses C# and Linq. The ganttData variable I have has 12 warnings stating:

  possible multiple enumerations of IENumerable

Should I change it to a List or leave it the way it is?

private IEnumerable<ProductLineDto> FilterAtHighestLevel(IEnumerable<ProductLineDto> ganttData, GanttFilterDto ganttFilterDataModel)
        {
            if (ganttFilterDataModel.ProjectId == null)
                return ganttData;
            //Check if it's a productLine, project, or subproject that was selected from the project filter
            ProductLine productLine = UnitOfWork.ProductLineRepository.GetAll().SingleOrDefault(x => x.ProductLineID == ganttFilterDataModel.ProjectId.Value);
            Project project = UnitOfWork.ProjectRepository.GetAll().SingleOrDefault(x => x.ProjectID == ganttFilterDataModel.ProjectId.Value);
            SubProject subProject = UnitOfWork.SubProjectRepository.GetAll().SingleOrDefault(x => x.SubProjectID == ganttFilterDataModel.ProjectId.Value);

            if (productLine != null)
                ganttData = GetProuctLinesFromDto(ganttData, ganttFilterDataModel.ProjectId.Value);
            else if (project != null)
            {
                ganttData = GetProuctLinesFromDto(ganttData, project.ProductLineID);
                //its always the first one
                ganttData.ElementAt(0).Projects = ganttData.ElementAt(0).Projects.Where(x => x.ProjectId == ganttFilterDataModel.ProjectId.Value);
            }
            else if (subProject != null)
            {
                ganttData = GetProuctLinesFromDto(ganttData, subProject.Project.ProductLineID);

                /// Don't just filter for the subproject get the project and show the entire project tree
                /// What's the point of this filter then?

                var rootProject = SubProjectService.EntityRepo.GetAll().FirstOrDefault(x => x.SubProjectID == ganttFilterDataModel.ProjectId.Value);
                ganttData.ElementAt(0).Projects = ganttData.ElementAt(0).Projects = ganttData.ElementAt(0).Projects.Where(x => x.ProjectId == rootProject.ProjectID);

            }
            return ganttData;
        }

        private IEnumerable<ProductLineDto> GetProuctLinesFromDto(IEnumerable<ProductLineDto> ganttData, Guid id)
        {
            return ganttData.Where(x => x.ProductLineId == id);
        }

possible multiple enumerations of IENuemerable
Should I change it to a List or leave it the way it is?

This depends on the situation. If there is an EF query behind the IEnumerable and you have never called .ToList() on it (not even once), then every time you enumerate it, the query will be executed against the database. If this is your case then you need to call .ToList() so your query can be executed and the results can be stored in a list on the application side. Whenever you want to get a fresh copy from the database, then you can run your query again or run a query which gets you the delta.
If you are doing everything in memory and there are no database calls, then if items are added to the underlying list, you will not get them. Consider this snippet:
IEnumerable<int> list = new List<int> { 1, 2 };
list.Count(); // returns 2

list.ToList().Add(3);
list.ToList().Add(4);

list.Count(); // it still returns 2


Inserting 1 line into my SQL database This is for adding code into my table really easily, however it will be called 2000+ times per second, so I need to know if this is the most efficient code to add a row to the database.

<?php
$site = $_GET['url'];
$con=mysqli_connect("localhost","","","rocket_newsites");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`sites` (`id`, `url`) VALUES (NULL, '$site');");

mysqli_close($con);
exit();
?>

Looking at your code, there are several things that immediately I can tell are issues. Before we even get to performance, there are basic security measures that need to be taken first.

SQL Injection

Like you've seen in the comments, your code is highly susceptible to SQL injection. But, what is it exactly? By definition, it is the

  insertion or "injection" of a SQL query via the input data from the
  client to the application.

Now how is your code affected by this? Well imagine we visit a URL like

http://rocket.com/newsite?url=google.com

That's all fine and dandy. If your connection works, "google.com" will be entered into your database.

However, imagine we visited a URL such as:

http://rocket.com/newsite?url=');

Note: You can't do this straight from the URL bar. I used PHP's get_file_contents() to test this.

Now we have a problem. Why is this such a big deal? Well let's take a look at the query when this happens:

INSERT INTO `rocket_newsites`.`sites` (`id`, `url`) VALUES (NULL, '');', '');

Even StackExchange's syntax highlighter knows this is wrong!

Well now you have a syntax error! Your string was interpreted and we were left with some left-over characters (;', '');). Now the attacker knows you're vulnerable to injection.

Contrary to popular belief, having something such as ?url=');DROP`sites`; will rarely actually delete your table. This is because MySQLi's regular query function does not handle multiple queries in one string. It will however, produce a syntax error. So neither way is a good one!

I was asked in chat:

  how can you have an answer about sql injection without the "bobby
  tables" xkcd comic?

And frankly, I agree. It demonstrates the dangers of SQL injection quite simply and shortly!

Source (CC BY-NC 2.5)

How can you solve this? Well I shouldn't have to do all the work!

Improper Error Handling

This is one many people forget, especially as beginners!

Let's take a look at your error handling:

echo "Failed to connect to MySQL: " . mysqli_connect_error();

Why is this bad? Because even if there's an error connecting, you continue to go through with the query. This means an error will be thrown to the attacker, which gives him incredibly important information. Now anyone with a little bit of intrusion knowledge could brute-force your database credentials.

Give only the information the users needs to get it right the next time. Anything more can compromise the security of your application. This is why forms never tell you if it's your username or your password that is wrong ;)

Be aware that there is also no error handling for your query. Anything that goes wrong, just goes wrong!

Got the security issues out of the way, now for what you asked for!

Performance

Here are some tips for optimizing your queries.

If you don't need the id column, don't have it. It's slowing you down by inserting NULL. And if you don't need it, then maybe you shouldn't be using a RDBMS. Perhaps look into NoSQL.
Don't start a new connection on every page, especially if each user is not unique. Utilize sessions and caching.
You might be able to use transactions, depending on the project.
Look into stored procedures.
Ask yourself why this is being called so often and see if you can change the way the application is designed to better suit such intense querying.
Look into other other server-side languages and their profiled statistics. Perhaps PHP really isn't the most optimized language for the job!


Which is cleaner: a constructor with many parameters or many setters after construction? I'm trying to work out which is cleaner, having a large constructor or having to use many setters on a new object before doing some work with it.

Large constructor:

<?php
class PathGeneratorWithBigConstructor {
  //...

  public function __construct($base_directories, $paths, $filename) {
    $this->base_directories = $base_directories;
    $this->paths = $paths;
    $this->filename = $filename;
  }

  //...
}

// Must pass the parameters in the correct order
$path_generator = new PathGeneratorWithBigConstructor($base_directories, $paths, $filename);

Many setters:

<?php
class PathGeneratorWithSetters {
  //...

  public function set_base_directories($base_directories) {
    $this->base_directories = $base_directories;
  }

  public function set_paths($paths) {
    $this->paths = $paths;
  }

  public function set_filename($filename) {
    $this->filename = $filename;
  }

  //...
}

$path_generator = new PathGeneratorWithSetters;

// These can go in any order
$path_generator->set_paths($paths);
$path_generator->set_filename($filename);
$path_generator->set_base_directories($base_directories);

I'm trying to follow Robert "Uncle Bob" Martin's advice in Clean Code where he recommends against having too many parameters in a method. He states on page 40:

  Function Arguments

  The ideal number of arguments for a function is
  zero (niladic). Next comes one (monadic), followed
  closely by two (dyadic). Three arguments (triadic)
  should be avoided where possible. More than three
  (polyadic) requires very special justification—and
  then shouldn’t be used anyway.

  Arguments are hard. They take a lot of conceptual
  power. …

Obviously, I can't quote the whole section here, and if you disagree with his opinion, I'd advise familiarising yourself with the rest of his argument before posting a reply. He goes into greater detail over the next 3-4 pages which I can't summarise here because he has already written the appropriate amount of text on the subject. I do reference his ideas in the following paragraphs which is again why I recommend being familiar with his full opinion before replying.

In the class with the constructor, it's not obvious what order the parameters should go in (no natural ordering - page 42). You can't give a hint to the programmer with the method's name because it's the constructor, which should succinctly describe the object, not the order of its construction parameters (encode the names of the arguments into the function name - page 43).

With the constructor, an error will occur when the object is created if there are too few parameters. With the setters, an error will still occur later if each property is not set correctly, which is also the case for the constructor, so no clear advantage either way. Some IDEs will warn the programmer if the method signature doesn't match, while they can't warn about missing setters.

The parameters in this case can't be combined into an sensible object, because PathGenerator is the sensible object! $base_directories, $paths & $filename don't have a logical grouping (reduce the number of arguments by creating objects out of them - page 43).

The class with the setters seems like a lot of work. It also seems too easy to miss one of the setters before trying to get it to do some work. However, reading the code that uses the setter class, it's obvious what it does, much more so than the large constructor version!

The third option, passing in a $parameters object/array, as I've seen recommended elsewhere, seems to combine the worst of both styles: extra work is needed to construct the object and it's easy to miss a parameter.

My goal is that the code should be easy to maintain (therefore also easy to understand) and easy to use. Which of the two styles is cleaner?

Where do you want to validate the parameters?

If the parameters are passed inside the constructor (either as multiple parameters or as a structure), the constructor can check all of them and throw an exception if something is missing/off. That way, the other methods of the class can assume they are valid.
If the parameters are passed using setters, then every method needs to check if all the required values are present and valid. If the code runs in a multithreaded context, then there's additional protections needed as a value can change unexpectedly inside a method call if a setter is called from a different thread.


Sieve of Eratosthenes to print prime numbers in a given range This is my implementation for Sieve of Eratosthenes in Java.Please let me know how can I further improve my code:

public static void main(String[] args) {

    ArrayList<Integer> numbers = new ArrayList<Integer>();

    for (int i = 2; i <= 120; i++) {
        numbers.add(i);
    }

    int digit = 2;
    while (digit <= numbers.size()) {
        for (int i = 0; i < numbers.size(); i++) {

            if (numbers.get(i) != digit && numbers.get(i) % digit == 0) {
                numbers.remove(i);
                i--;

            }

        }
        digit++;
    }

    for (int a : numbers)
        System.out.println(a);

}

This is NO Sieve of Eratosthenes. Can you see any division in this algorithm description???

What you're doing is trial division. Worsened by

even checking things like "does 100 divide 2?"
using a list which does not allow efficient removal
using Integer rather than int

The complexity is something like \$O(n^3)\$ as there are 3 nested loops: 2 in your code and 1 in numbers.remove.

The complexity should be \$O(n^\frac32)\$ which comes from using an "indicator array"(*) and iterating up to \$\sqrt n\$ only.

(*) It tracks for each int the information if it's a prime or not. It can be implemented e.g. as a boolean[] or a BitSet. The point is that all you need is an indexed access, no search, no elements shifting....


Is this a safe way of using HTTP query parameters to build a SQL query? Is it? And maybe theres a better way to do this?

$allowed = array("name_desc", "name_asc", "level_desc", "level_asc", "vocation_desc", "vocation_asc");
$order = isset($_GET['order']) ? $_GET['order'] : "name";
$order = in_array($order, $allowed) ? str_replace("_", " ", $order) : "name";

$query = "SELECT * FROM players
          WHERE status = 0 AND group_id < 3 ORDER BY $order";

It is safe. You have a white list of allowed values and ensure that the user provided input is on the list.

But I'd still do the white list checking as the very first thing, and then do the other processing later, so it would be:

$field = 'name';
$direction = 'asc';
if(preg_match('^([a-z]+)_(asc|desc)$', $_GET['order'], $matches)) {
    if(in_array($matches[0], array("name", "level", "vocation"))) {
        $field = $matches[0];
        $direction = $matches[1];
    }
}

What happens here is that the block splits up and validates the input. You can be sure that once you're past this block, $field and $direction can be trusted. An important point is to use $_GET['order'] exactly once, since accessing it multiple times may lead to errors that will leak non-validated data.


C# Multiple ASYNC requests single response (Promise like) I'm no too good with async processes in C#. I need to implement method, that can be called multiple times by async requests, but request data and serve response once. I've created this method, inspired by common JS promise pattern:

private Task<bool> DoSomething(string key)
{
    // generating unique key
    string cacheKey = "do-comething-" + key;
    // searching cache for a Task in progress
    var cachedRequest = MemoryCache.Default.Get(cacheKey, null) as Task<bool>;

    // if found - return old Task
    if (cachedRequest != null)
    {
        return cachedRequest;
    }

    TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

    CacheItemPolicy cip = new CacheItemPolicy()
    {
        AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(60))
    };

    // storing Task object in cache
    MemoryCache.Default.Set(cacheKey, tcs.Task, cip);

    try
    {
        // do something long here
        tcs.TrySetResult(true);
    }
    catch(Exception ex)
    {
        tcs.TrySetResult(false);
    }
    finally
    {
        MemoryCache.Default.Remove(cacheKey);
    }
    return tcs.Task;
}

Is it ok, or I'm totally out of it? Any advice will be highly appreciated. Thanks.

Bug
You have a pretty big multithreading issue in your code. When this method can be called from different threads, the MemoryCache doesn't necessarily contain an already created task. Consider the following execution:
Thread 1                     | Thread 2
string cacheKey = ...        |  -
var cachedRequest = ..       |  -
if (cachedRequest != null)   |  -
if (cachedRequest != null)   |  string cacheKey = ...
if (cachedRequest != null)   |  var cachedRequest = ...
TaskCompletionSource tcs =   |  var cachedRequest = ...
TaskCompletionSource tcs =   |  if (cachedRequest != null)
TaskCompletionSource tcs =   |  TaskCompletionSource tcs =
...                          |  ...

The result should be pretty obvious: This way two tasks for the same key can be started. Depending on how strict you need that semantic, that's a problem.
Fixing this is not trivial, but should be simple enough with a lock (_lock) block onto a private static const Object _lock = new Object();
How to Task
In general I'd expect a method that returns a Task<bool> to not actually do the work, as is suggested by //do something long here. Instead the code should submit the work as an Action or something along these lines. Something like that:
Task<bool> result = new Task<bool>(() =>
{
    try
    {
         // do something long here
         return true;
    }
    catch (Exception e)
    {
         return false;
    }
});

this shows an additional problem. The return value of that Task is basically just a flag for successful completion. But you know what? Task already has that: Task.IsFaulted
This makes for a pretty different return value. Use Task instead of Task<bool>, because it removes redundancy.
Back to the code: We're still not quite there with the lookup and caching mechanics.
CacheItemPolicy cip = new CacheItemPolicy()
...
MemoryCache.Default.Set(cacheKey, result, cip);

This is for the caching, now we just need to clean the cache when we're finished:
result.ContinueWith(() => MemoryCache.Default.Remove(cacheKey));
result.Start(); // actually start doing work
return result;


Selecting folders based on last modified date I am attempting to find folders based on their last modified dates.

import os, shutil, stat, errno, time, datetime
srcFolders = "C:\Users\Test\Desktop\Test"
archiveDate = datetime.datetime.strptime("2016/11/20", '%Y/%m/%d')
os.chdir(srcFolders)

for name in os.listdir('.'):
    if os.path.isdir(name):
        modifiedDate = time.strftime('%Y/%m/%d', time.gmtime(os.path.getmtime(name)))
        strLastModified = datetime.datetime.strptime(modifiedDate, '%Y/%m/%d')
        if  strLastModified > archiveDate:
            print name

This is what I've got and it seems to be right in that they're comparing the same attributes. If there is a better, more Pythonic way for this, please advise.

Do not put all imports on the same line and use snake_case rather than camelCase for variable names.
Read PEP8, the official Python style guide to make your code look like Python code.

Use functions for better reusability. Instead of using hardcoded values like your folder path or archive date, use parameters. You will more easily be able to test various values in the interactive interpreter.
This also means using the if __name__ == '__main__' construct.

return values instead of printing them in the function. Again, better reusability.
For starter you can build a list and return it.

when using datetime objects, you can compare them directly. It is cleaner and probably faster than comparing their string representation. Building dates is also as simple as using the right constructor.

you don't need to move to the desired directory before listing its content. os.listdir can take the absolute path and work from that.

Revised code
import os
import datetime

def filter_by_date(src_folder, archive_date):
    relevant_folders = []
    for name in os.listdir(src_folder):
        full_name = os.path.join(src_folder, name)
        if os.path.isdir(full_name):
            if datetime.fromtimestamp(os.path.getmtime(full_name)) > archive_date:
                 relevant_folders.append(name)
    return relevant_folders

if __name__ == '__main__':
    print filter_by_date("C:\Users\Test\Desktop\Folder", datetime.datetime(2016, 11, 10))

Is a first aproach. But using append in a for loop is deemed unPythonic, better use a generator or a list-comprehension here:
import os
import datetime

def filter_by_date(src_folder, archive_date):
    os.chdir(src_folder)
    return [
        name for name in os.listdir('.')
        if os.path.isdir(name)
        and datetime.fromtimestamp(os.path.getmtime(name)) > archive_date
    ]

if __name__ == '__main__':
    print filter_by_date("C:\Users\Test\Desktop\Folder", datetime.datetime(2016, 11, 10))


A Countdown Timer with reset functionality in pure Javascript This works for me, but is this the right way to create this timer?
I might be naive about this but I think this is close to perfect in pure JS.
What would be the drawbacks of using this Timer compared to creating it in a different way?

Click start and the timer starts to countdown.
Click reset and the timer resets back to the starting time.

HTML:
<button onclick='startStopTimer()'>Start</button>
<button onclick='startStopTimer()'>Reset</button>

00:10

JavaScript:
console.clear()
let timer = document.querySelector('h1')
let startingTime = 9
let startTimer;
let startStopTimer = () => {
  if(startTimer){
    clearInterval(startTimer);
    timer.innerHTML = '00:10'
    startingTime = 9
    return startTimer = undefined
  }else{
    return startTimer = setInterval(()=>{
      timer.innerHTML = `00:0${startingTime--}`
    }, 1000)
  }
}

From a short review;

You use 9 twice, this should be assigned to a nicely named global constant
You hard code both 9 and 00:10, this is not flexible. I would expect to be able to change 9 to 99 and to have the timer start at 01:40
Similarly, 00:0${startingTime--} does not allow for much flexibility in the script
The browser tries to honor the 1000, but it cannot be trusted. You are supposed to keep track of the original start and deduct that from current time to determine how much time has passed. Otherwise the timer is not reliable.
Placing the timer in a h1 element is probably not a good idea semantically
Your entire code should be in a well named (self executing) function
I am not sure why you return anything in startStopTimer? If you are never using the returned value, then just drop the return keyword
since clearInterval returns undefined and because it makes sense, I would go for startTimer = clearInterval(startTimer);
Why console.clear()? Production code should avoid console


Generic mean function It seems useful to have a generic function to calculate the mean of all elements in a container, so I wrote one. By default it calculates the arithmetic mean, but should be able to accommodate other means (like geometric) if passed the appropriate functors.

Assumptions:

value_type can be default-constructed to yield a "zero-value" of its type

I am particularly interested in feedback on:

The validity of my assumptions
The mean() interface
How I validate my iterators
General code style.

mean.hpp

#ifndef MEAN_HPP
#define MEAN_HPP

#include <algorithm>
#include <functional>
#include <iterator>
#include <numeric>
#include <type_traits>

template <class ForwardIt, class DivOp = std::divides<>, class AddOp = std::plus<>,
          class = std::enable_if_t<
                  std::is_base_of<
                  std::forward_iterator_tag,
                  typename std::iterator_traits<ForwardIt>::iterator_category>::value>>
typename std::iterator_traits<ForwardIt>::value_type mean(ForwardIt begin,
                                                          ForwardIt end,
                                                          DivOp div = DivOp(),
                                                          AddOp add = AddOp())
{
    using value_type = typename std::iterator_traits<ForwardIt>::value_type;
    const auto sum = std::accumulate(begin, end, value_type(), add);
    const auto count = std::distance(begin, end);
    return div(sum, count);
}

#endif

Below is included some example code to demonstrate the usage of mean(). I'm less interested in feedback on the example code, but it is of course still welcome.

main.cpp

#include "mean.hpp"
#include <iostream>
#include <vector>

struct Point
{
    Point() : x(0), y(0) {}
    Point(int x, int y) : x(x), y(y) {}

    int x, y;
};

Point operator+ (const Point& lhs, const Point& rhs)
{
    return Point(lhs.x + rhs.x, lhs.y + rhs.y);
}

int main()
{
    // Works on primitives
    const std::vector<float> scalars{1, 2, 3, 4, 5, 6, 7, 8, 9};
    const auto scalarResult = mean(scalars.begin(), scalars.end());
    std::cout << scalarResult << std::endl;

    // Works on class types with appropriate operators
    const std::vector<Point> points{{1,1}, {2,2}, {3,3}};
    const auto pointDivision = [] (const Point& sum, const float count)
    {
        return Point(sum.x / count, sum.y / count);
    };
    const auto pointResult = mean(points.begin(), points.end(), pointDivision);
    std::cout << pointResult.x << " " << pointResult.y << std::endl;
}

The arithmetic mean is not necessarily a closed operation: the mean of integers is, in general, not an integer.  Therefore, you should provide a specialization of the template for integer inputs.


Simulating pod racing over a 2D map : am I implementing OOP in a GO-like fashion? I'm learning Go and I wrote this for a programming challenge. It is working (building and running) but I feel the code is not what Go code should be.

I used an OOP design. Is it correctly implemented in GO ?

In my main, I will call the method pod.playTurn(target, speed)

package main

import (
    "fmt"
    "math"
    "os"
    "strconv"
)
// Dot is king
type Dot struct {
    x, y int
}
// Pod is life
type Pod struct {
    position                Dot
    vx, vy, angle, nextCpID int
    hasShieldOn             bool
}

func squaredDist(a, b Dot) int {
    return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)
}
func distance(a, b Dot) float64 {
    return math.Sqrt(float64(squaredDist(a, b)))
}

func (pod Pod) getAngle(p Dot) float64 {
    d := distance(p, pod.position)
    dx := float64(p.x-pod.position.x) / d
    dy := float64(p.y-pod.position.y) / d
    a := math.Acos(dx) * 180.0 / math.Pi

    // If the point I want is below me, I have to shift the angle for it to be correct
    if dy < 0 {
        a = 360.0 - a
    }
    return a
}

func (pod Pod) diffAngle(p Dot) float64 {
    a := pod.getAngle(p)
    pangle := float64(pod.angle)

    right := 0.0
    if pangle <= a {
        right = a - pangle
    } else {
        right = 360.0 - pangle + a
    }

    left := 0.0
    if pangle >= a {
        left = pangle - a
    } else {
        left = pangle + 360.0 - a
    }

    if right < left {
        return right
    }
    return -left
}

func (pod Pod) rotate(p Dot) int {
    a := pod.diffAngle(p)

    // Can't turn more than 18° in one turn !
    if a > 18.0 {
        a = 18.0
    } else if a < -18.0 {
        a = -18.0
    }

    pod.angle += int(math.Round(a))

    if pod.angle >= 360.0 {
        pod.angle = pod.angle - 360.0
    } else if pod.angle < 0.0 {
        pod.angle += 360.0
    }
    return pod.angle
}

func (pod Pod) boost(t int) (int, int) {
    if pod.hasShieldOn {
        return pod.vx, pod.vy
    }
    pangle := float64(pod.angle)
    pod.vx += int(math.Round(math.Cos(pangle) * float64(t)))
    pod.vy += int(math.Round(math.Sin(pangle) * float64(t)))
    return pod.vx, pod.vy
}

// t shoud become a float later on
func (pod Pod) move(t int) (int, int) {
    pod.position.x += pod.vx * t
    pod.position.y += pod.vy * t
    return pod.position.x, pod.position.y
}

func (pod Pod) endTurn() (int, int) {
    // todo rounding position if needed
    pod.vx = int(float64(pod.vx) * 0.85)
    pod.vy = int(float64(pod.vy) * 0.85)
    return pod.vx, pod.vy
}

func (pod Pod) playTurn(p Dot, t int) {
    pod.angle = pod.rotate(p)
    pod.vx, pod.vy = pod.boost(t)
    pod.position.x, pod.position.y = pod.move(1)
    pod.vx, pod.vy = pod.endTurn()
    fmt.Fprintf(os.Stderr, "\nPredicted Pod position : ")
    fmt.Fprintf(os.Stderr, "\n(%d, %d) speed (%d,%d)", pod.position.x, pod.position.y, pod.vx, pod.vy)
}

Am I using struct correctly ? Is it acceptable object oriented code ?

As per request in the comment, here's an implementation of the rotate function in a more idiomatic golang way (ie using a pointer receiver):

// let's use constants so code becomes self-documenting
const (
    maxRotation float64 = 18 // max rotation as typed constant
    fullCircle  int     = 360 // just like all hard-coded values, let's use constants
    semiCircle  int     = fullCirle/2 // do this for all hard-coded values
)

// note the receiver is a pointer, and there's no return value
func (pod *Pod) rotate(p Dot) {
    a := pod.diffAngle(p)

    if a > maxRotation {
        a = maxRotation
    } else if a < -maxRotation {
        a = -maxRotation
    }

    pod.angle += int(math.Round(a))

    var add int // add this value, defaults to 0
    // you are comparing pod.angle (an int) to a float64 (360.0)
    // that shouldn't be happening. I'd say angle should be a float64
    // but keeping the fields in pod the types they are for now
    if pod.angle >= fullCircle {
        add -= fullCircle
    } else if pod.angle < 0 {
        add = fullCircle
    }
    pod.angle += add // adds 0, 360, or -360 depending on the new value for pod.angle
}

That's all there is to it, really. Instead of calling it like this:

pod.angle = pod.rotate(p)

You simply call it like this:

pod.rotate(p)

The value of pod.angle will be updated. If you start doing this stuff concurrently, you'll need to ensure that pod.rotate() is "thread-safe" (ignoring the fact that goroutines aren't really threads for a second). The easiest way to do this is using a sync.Mutex (or sync.RWMutex), to make sure that you're not accidentally updating pod.angle in 2 routines etc...

I might revisit this stuff to give a more detailed review, so stay tuned for updates.


Generate word list based on Spanish text file I'm a beginner and wrote a program that takes a text file and writes a downcased vocabulary list to another text file. I intend to use it mainly to work with text in Spanish, so I added a line to downcase capitalized-accented words. I'm wondering if there is a more efficient way of reading from the original file, as well as removing non-letters and sorting for unique items.

f = File.open("/.../quijote.txt")
words = f.read.split.map(&:downcase)
f.close

#remove numbers and non-letters
words = words.map {|item| item.tr('0-9.,;:¿¡?!«»\‘\“\”\–\]\[\-\(\)\'\"', '')}

#downcase capitalized accented words
words = words.map {|item| item.tr('ÁÉÍÓÚÑ', 'áéíóúñ')}

words = words.uniq.sort

# write each word on a separate line in the file...
File.open("/.../quijotewords.txt", "w+") do |f|
  words.each { |element| f.puts(element) }
end

Some notes:

open + read + close: Better to use the block form: contents = File.open(path) { |fd| fd.read  } or simply contents = File.read(path)
words = words.something: Don't re-use variable names. New values, new names. For example: sorted_words = words.sort.
Use File.write
Instead of removing chars that you don't want, I'd remove the chars that you do want.
You can apply the processing to the whole file or line and then split.
string.tr(something, '') -> string.delete(something).

I'd write:

words = File.read("quijote.txt").downcase.
  tr("ÁÉÍÓÚÑ", "áéíóúñ").delete("^[a-z]áéíóúüñ \n").
  split.uniq.sort
File.write("quijote-words.txt", words.join("\n"))

If your input file is not UTF8-encoded but, let's say, ISO8859-15, you'd write: File.read("quijote.txt", encoding: "iso8859-15").encode("utf-8").