Binary expression tree node with two possible states

This is a perfect situation to introduce an interface. What you want to model is a tree-like structure, with nodes having a left and right subtree and leaf containing an integer value.

Your current code models this by having a single ExpressionTreeNode class, handling both cases of having a node with a left and right operand, and a leaf. What shows that this class has too much responsibility is the overhead you need to have to ensure its consistency:

if (value == null || (!(value instanceof Integer) && !(value instanceof ExpressionTreeNodeOperands))) {
    throw new IllegalArgumentException("Illegal argument: value must be non-null with a type of Integer or ExpressionTreeNodeOperand");
}

if (leftNode == null && rightNode != null || leftNode != null && rightNode == null) {
    throw new IllegalStateException("Illegal state: leftNode and rightNode should both be null or non-null alike");
}

if ((value instanceof Integer) && (leftNode != null && rightNode != null)) {
    throw new IllegalStateException("Illegal state: non-operand non-leaf node");
}

if (!(value instanceof Integer) && leftNode == null && rightNode == null) {
    throw new IllegalStateException("Illegal state: non-integer leaf node");
}

That is a lot of code to make sure that the node has a proper state after its construction. It also makes assumptions on the given arguments (namely, that you cannot pass a value that isn't an Integer or a ExpressionTreeNodeOperands): this is reasonable when well-documented but such constraints, if possible, would be preferable to ensure at compile-time.

For example, it will also compile if the caller gives an integer value along with a node, only to fail at run-time because it is incorrect.

The model you want to have here shows that, in fact, 3 classes need to be introduced:

an ExpressionTree interface, that represents the tree-like structure.
an ExpressionTreeNodeOperands class that would represent a node in the tree. A node would have 2 members: a left and a right subtree, represented as two members of type ExpressionTree.
a Leaf class that would represent a leaf in the tree. This class would just have one member of type int.

A sample code would be the following:

interface ExpressionTree {
    boolean isLeaf();
}

class ExpressionTreeNodeOperands implements ExpressionTree {

    private ExpressionTree left;
    private ExpressionTree right;

    public ExpressionTreeNodeOperands(ExpressionTree left, ExpressionTree right) {
        this.left = Objects.requireNonNull(left);
        this.right = Objects.requireNonNull(right);
    }

    @Override
    public boolean isLeaf() {
        return false;
    }

}

class Leaf implements ExpressionTree {

    private int value;

    public Leaf(int value) {
        this.value = value;
    }

    @Override
    public boolean isLeaf() {
        return true;
    }

}

Notice a couple of things:

Leaf is now constructed directly with an int and you cannot construct it without one. Also, it is not a boxed Integer: null values were not permitted before and are simply not possible now.
ExpressionTreeNodeOperands is constructed with two arguments: the left and right sub-tree, which could be another ExpressionTreeNodeOperands, or a Leaf. It also calls requireNonNull to make sure that the given arguments are non-null.

The concern are now clearly separated: the node handles only its sub-trees, and the leaf handles only its value.

With this base, you can add convenience methods, like isLeaf, that would always return false for a node, and always return true for a leaf.

Then, depending on your actual usage, you may not even need a getLeft() and getRight() getters to retrieve the left and right node sub-trees. Let's take an example usage where we want to perform an infix traversal. You could add a String infix(); method inside the interface ExpressionTree, that would return a String representation:

@Override
public String infix() {
    return "(" + left.infix() + "," + right.infix() + ")";
}

for a node, and

@Override
public String infix() {
    return String.valueOf(value);
}

for a leaf. And then you can have:

ExpressionTree tree = new ExpressionTreeNodeOperands(new ExpressionTreeNodeOperands(new Leaf(2), new Leaf(1)), new Leaf(3));
System.out.println(tree.infix()); // prints ((2,1),3)


Please bare in mind that this is my first review on here :)

I see that you wanted to do the whole sorting yourself and personally I think that's good to understand some basics. However in aspect of perforfmance and readability it's not quite the best.
Why re-invent the wheel when you can use already existing solutions?

 /*
 * File: FindTwoLargest.java
 * ----------------------
 * This program finds the two largest integers in a list.
 *
 */

/* Library packages */
import acm.program.*;

public class FindTwoLargest extends ConsoleProgram {

    /* Private constant */
    private static final int SENTINEL = 0;

    public void run() {
        println("This program finds the two largest integers in a list.");
        println("Enter values, one per line, using a 0 to signal the end of list.");
        List<Integer> userInput = new ArrayList<>();
        while (true) {
            int n = readInt("? ");
            if (n == SENTINEL)
            {
              break;
            }
            userInput.add(n);
        }
        if(!userInput.isEmpty()) {
          java.util.Collections.sort(userInput);
          java.util.Collections.reverse(userInput);
          println("The largest value is " + userInput.get(0));
          println("The second largest value is " + userInput.get(1));
       }
    }
}

So that's a solution I would use. It only uses one while loop which is enough to work and uses less If-Else logic. You can just collect every input given to the list and then use the Collections API from Java to easily sort the list. The call to reverse will change the sorting from ascending to descending meaning the hightest and second highest values are at the beginning.

However if that is not what you wanted or needed I would ask why you used two while loops? It's not necessary for the logic.
You can check everything in the first while and remove duplicate code and unneeded checks, which reduce the readability and maintenance of the code.

Another hint would be that with else if you indicate that the previous condition was checked and didn't comply, meaning no need to check again what you did in the first if. You would only need to check that again if you just used a second if.

Which also improves some maintenance and readability, is moving constants and global variables before the constructor of a class. In case you didn't have contact with that yet, a Constructor is the first method in a class ( used for defining the initialization and so on but that doesn't belong here ) and comes before all custom methods. Meaning it's at the top of a class. And to easily get a grip of what is global or where the constants are you should always move those at the top of the class.

import acm.program.*;

public class FindTwoLargest extends ConsoleProgram {

    /* Private constant */
    private static final int SENTINEL = 0;

    public void run() {
        println("This program finds the two largest integers in a list.");
        println("Enter values, one per line, using a 0 to signal the end of list.");
        int n = readInt("? ");
        if (n == SENTINEL) {
            break;
        }
        int largest = n;
        int secLargest = n;
        while (true) {
            n = readInt("? ");
            if (n == SENTINEL) { // I just personally don't like inline if's
                break;
            }
            if ( n >= largest ) {
                secLargest = largest;
                largest = n;
            } else if ( n > secLargest ) {
                secLargest = n;
            }
        }
        println("The largest value is " + largest);
        println("The second largest value is " + secLargest);
    }
}

Note: I tested a slightly different variant of this in the ideone online compiler here.

So with the answer of Roland in mind here's what you can also do to fix those little bugs:

  1 5 5 0 (only one of the 5s is accepted, the other is ignored)

Just change the first if too if( n >= largest ) if you don't want to ignore the second entry.

  5 0 (there is no second number at all, nevertheless your program says
  that the second-largest number is 5)

Again this depends on what you want to do. If you don't want to display a secondlargest in this case you could do something like this:

int secondLargest = 0;

...
if(secondLargest != 0){
  println("The second largest value is " + secLargest);
}

  0 (basically works, but the output should indicate that there wasn't a
  number at all)

I just did the sentinel check for the first input already. That allows the user to quit the program directly. If that's not what you want to do you can think about something else.


Python class which chains Google translations back and forth between two languages

I think that you should be more explicit about the source language instead of relying exclusively on auto-detection, in both your Translate constructor and when you call translator.translate().  Japanese is easy enough to detect unambiguously in most cases.  However, phrases in other languages could easily be interpreted as several possible languages.

Recursion is rarely the most idiomatic solution in Python.  Rather, generators are often a better idea.  Here's a generator that will translate back and forth between two languages as many times as you want:

from googletrans import Translator

def chained_translations(phrase, target_language='en', source_language=None):
    translator = Translator()
    source_language = source_language or translator.detect(phrase).lang
    while True:
        phrase = translator.translate(phrase, src=source_language, dest=target_language).text
        yield phrase
        source_language, target_language = target_language, source_language

This solution is much simpler, because the state is kept in the execution flow of the generator code itself.

Example usage:

>>> test = chained_translations('は忙しい。彼は多忙な人間だ。勉強をしたい')
>>> print(next(test))
'I am busy. He is a busy man. I want to learn'
>>> print(next(test))
'私は忙しいです。彼は忙しい人だ。学びたい'
>>> from itertools import islice
>>> print(list(islice(test, 3)))
['I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn']


they are all .box class.

I am thinking that you should get rid of the container divs and get rid of the .box class and give it to all divs because after you get rid of the container divs all the divs will be the boxes.

you should do one of those fancy HTML5 Tags for the content section instead of having a container classed div.

check this out, I have removed some tags and some CSS classes to make the code a little cleaner.  the output is slightly different but I think this is a little bit better.  if you need a width on the content you can add that as well.

what happens when the browser window is resized is that the boxes are now hugging the left and right sides of the content,  if you want to keep it to two rows at the max you would just add a width to the content tag

UPDATE

I changed some more things to make this so that you could add more examples with ease, and so that it would be more view-able on mobile devices.

This is the New Version that I came up with

I removed the Left and Right Classes, and moved the float left into the Styling for the Div tags, this way the boxes will wrap the viewport is resized.

I also changed the size of the boxes.

I removed the container classes as they weren't needed.

I added the styling from the box class to the div's themselves.

I am apparently wrong about sizing the content tag that I created, maybe it's not proper HTML5 or I was doing something wrong.

Here is the code that I have after the changes that I made

<!DOCTYPE HTML>

    <title>Box Shadow</title>
    <link rel="stylesheet" type="text/css" href="boxshadow.css">

  <content>

  </content

CSS

body{
    background: #ccc;
    margin: 0;
}
content{
    width:1000px;
}
div {
    background-color: #fff;
    width: 500px;
    height: 200px;
    padding:15px;
    margin:15px;
}
.left{
    float: left;
}
.right{
    float: right;
}
/* Basic Shadow */
.shadow1{
    box-shadow: 5px 5px 0 rgba(150,150,150,0.5);
}
/* Inset Shadow and blur radius Variety */
.shadow2{
    box-shadow: inset 0 0 10px black;
}
/* Inset Shadow and blur radius */
.shadow3{
    background: #F2F2F2;
    box-shadow: inset 3px 3px 3px #BFBFBF, inset -3px -3px 3px #8C8C8C;
    border-radius: 10px;
}
/* Spread radius Shadow */
.shadow4{
    box-shadow: 0 20px 10px -10px rgba(150,150,150,0.8);
}
/* Curved Shadows */
.shadow5{
    position: relative;
    overflow:hidden;
}
.shadow5:before{
    content: "";
    position: absolute;
    z-index: 1;
    width: 96%;
    top: -15px;
    height: 15px;
    left: 2%;
    border-radius: 100px / 5px;
    box-shadow: 0 0 39px rgba(0,0,0,0.6);
}
.shadow5:after{
    content: "";
    position: absolute;
    z-index: 1;
    width: 96%;
    bottom: -15px;
    height: 15px;
    left: 2%;
    border-radius: 100px / 5px;
    box-shadow: 0 0 39px rgba(0,0,0,0.6);
}
.shadow6{
    position: relative;
    overflow:hidden;
}
.shadow6:before{
    content: "";
    position:absolute;
    z-index: 1;
    width:10px;
    top: 5%;
    height: 90%;
    left: -10px;
    border-radius: 5px / 100px;
    box-shadow:0 0 13px rgba(0,0,0,0.6);
}
.shadow6:after{
    content: "";
    position:absolute;
    z-index: 1;
    width:15px;
    top: 5%;
    height: 96%;
    right: -15px;
    border-radius: 5px / 100px;
    box-shadow:0 0 13px rgba(0,0,0,0.6);
}

Some other things that I noticed while pasting this new code is that you assign a z-index of 1 to some of your shadow styles and not to the others, I don't think that this is necessary for what you are doing here.  the z-index defaults to 1 or 0 if I remember right, and that should be fine for what you are doing here so you don't even need to add that in there.


Using NSPredicate with NSFetchRequest in a NSFetchedResultsController

The entity and the sort descriptors of NSFetchRequest are defined as "properties"

@property(nonatomic, strong) NSEntityDescription *entity;
@property(nonatomic, strong) NSArray *sortDescriptors;

So while calling the setter methods still works

[fetchRequest setEntity:...];
[fetchRequest setSortDescriptors:...];

you should use the "dot-Syntax" for properties:

fetchRequest.entity = ...;
fetchRequest.sortDescriptors = ...;

and the same applies to the properties of NSFetchedResultsController.

The creation of the fetch request can be simplified with the
factory method

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"KFPSubItem"];

I usually assign the sort descriptors to separate variables first. This may
be a matter of taste, but it avoids too long statements if there is more
than one sort descriptor:

NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
fetchRequest.sortDescriptors = @[sortByName];

The

self.fetchedResultsController = [[NSFetchedResultsController alloc] ...

line is extremely long and should be split into several lines.

The correct way to check for success or failure of Cocoa (Touch) methods is
documented in
"Handling Error Objects Returned From Methods" in the "Error Handling Programming Guide":

  Important: Success or failure is indicated by the return value of the
  method. Although Cocoa methods that indirectly return error objects in
  the Cocoa error domain are guaranteed to return such objects if the
  method indicates failure by directly returning nil or NO, you should
  always check that the return value is nil or NO before attempting to
  do anything with the NSError object.

So instead of

NSError *error = nil;
[self.fetchedResultsController performFetch:&error];
if (error) { ... }

you should do

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) { .... }

Putting it all together:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"KFPSubItem"];

NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
fetchRequest.sortDescriptors = @[sortByName];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item = %@", self.record];
fetchRequest.predicate = predicate;

self.fetchedResultsController = [[NSFetchedResultsController alloc]
                                initWithFetchRequest:fetchRequest
                                managedObjectContext:self.managedObjectContext
                                  sectionNameKeyPath:nil
                                           cacheName:nil];
self.fetchedResultsController.delegate = self;

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
    NSLog(@"Unable to perform fetch");
    NSLog(@"%@, %@", error, error.localizedDescription);
}


This:

var token = NSString(format: "%@", deviceToken)
token = token.stringByReplacingOccurrencesOfString("<", withString: "")
token = token.stringByReplacingOccurrencesOfString(">", withString: "")
token = token.stringByReplacingOccurrencesOfString(" ", withString: "")

is actually a bad method to convert an NSData object to an NSString
(containing the bytes in hexadecimal). It relies on description
having the format

<01020304 05060708 090a0b0c 0d0e0f10>

which is not officially documented. In most cases, the description of
an object is only suitable for debugging purposes, but not for further
processing.

I would convert all data bytes explicitly to create the string. Here is a possible implementation as an NSData extension method:

extension NSData {
    func hexString() -> String {
        // "Array" of all bytes:
        let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
        // Array of hex strings, one for each byte:
        let hexBytes = map(bytes) { String(format: "%02hhx", $0) }
        // Concatenate all hex strings:
        return "".join(hexBytes)
    }
}

which can be used as

let token = deviceToken.hexString()

With

dispatch_async(dispatch_get_main_queue(), { ... }

you dispatch the URL request to the main queue where it blocks the
UI. You can use dispatch_get_global_queue() instead to dispatch
it to a background thread, or simply use sendAsynchronousRequest():

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
    (response, data, error) -> Void in

    if data != nil {
        println("data: \(data)")
    } else {
        println("failed: \(error.localizedDescription)")
    }
}

Now the request is done in the background and then the completion
handler called on the main thread.

In the case of an connection problem, the completion handler is called
with data == nil and error != nil containing information about the
problem.

  shall I use an api key (not sure is the correct word) to "identify" the user

This question is a bit broad and depends on what you are trying to
achieve. Here are some comparisons of the available methods:

CFUUID Vs. advertisingIdentifier Vs. identifierForVendor
The Developer’s Guide to Unique Identifiers

which might serve as a starting point for your further research.


SQL query to order by the difference between FIRST and BEST scores

SELECT ms.uid AS id

No effect on performance, but this seems weird.  You have a column in that table named id, but you are actually returning uid as id.  Why not just keep it as uid?

LEFT JOIN (

You know that the user has a score, because you found it in the first query.  Therefore, you don't need a LEFT JOIN.  A regular INNER JOIN is fine and will be considerably faster.

CASE WHEN game_id = 3 THEN date ELSE NULL END

It's not clear to me what this buys you.  Why not just put up.game_id = 3 in the WHERE clause?  This will seriously confuse the optimizer.  Same thing for the max_score query.

Given this query, do you have an index on lesson_id, game_id, uid, score, date?  This query could hit only the index.  It's possible that date should be before score.  I'd try making it both ways and then running EXPLAIN to see which it hits.  Then you can delete the other.  You should put whichever of lesson_id and game_id has more potential values first.  It's possible that uid should go before either, but I'd have to test to see.

You put score and date last in the index because they have inequalities.  This keeps the query from being able to optimize later columns, so they go last.  In regards to the uid IN portion, I believe that it may be able to hold its place on the game_id and lesson_id pair, so I put uid after them.

SELECT ms.uid AS id, ms.max_score - fs.first_score AS progress
FROM (
    SELECT up.uid, MAX(score) AS max_score
    FROM cdu_user_progress up
    WHERE  up.uid IN  ('1671', '1672', '1673', '1674', '1675', '1676', '1679', '1716', '1725',         '1726', '1937', '1964', '1996', '2062', '2065', '2066', '2085', '2086') AND up.lesson_id = '65' AND up.score > '-1' AND up.game_id = 3
    GROUP BY up.uid
) ms
INNER JOIN (
    SELECT up.uid, up.score AS first_score
    FROM cdu_user_progress up
    INNER JOIN (
        SELECT up.uid, MIN(date) AS first_date
        FROM cdu_user_progress up
        WHERE up.uid IN  ('1671', '1672', '1673', '1674', '1675', '1676', '1679', '1716', '1725', '1726', '1937', '1964', '1996', '2062', '2065', '2066', '2085', '2086') AND up.lesson_id = '65' AND up.score > '-1' AND up.game_id = 3
        GROUP BY up.uid
    ) fd ON fd.uid = up.uid AND fd.first_date = up.date
    WHERE up.game_id = 3 AND up.lesson_id = '65'
) fs ON fs.uid = ms.uid
ORDER BY progress DESC

Note that I added WHERE up.game_id = 3 AND up.lesson_id = '65' because I think it will help the optimizer.  You should check the EXPLAIN plan to be sure.


I don't see any rough mistake with your code, but I would refactor some parts of it.

There are a lot of magic string constants like "AddPProc", "VerifyUpload", "FedAuth". They should be defined as named constants:

private const string AddPProc = "AddPProc";

This code

string url = Config.BaseAPIUrl;
url = url + "AddPProc";

can be replaced with

var url = Config.BaseAPIUrl + AddPProc;

The same thing with the second method.

In both methods there are fully qualified types. It is hard to read this code. For example, instead of System.Net.Http.Headers.MediaTypeWithQualityHeaderValue place using System.Net.Http.Headers; at the start of the file and use MediaTypeWithQualityHeaderValue without qualification. Especially it is recommended for this line:

Proj.Repositories.Models.External.ProcResponse procResponse = JsonConvert.DeserializeObject<Proj.Repositories.Models.External.ProcResponse> (await response.Content.ReadAsStringAsync ());

In this code

if (serviceResponse.StatusCode == 200)
    return null;
else
    return serviceResponse.StatusDescription;

you don't need else keyword. You can even replace this if-else with ternary operator and single return:

return serviceResponse.StatusCode == 200
    ? null
    : serviceResponse.StatusDescription;

getUploadFilesCount is bad name according to C# naming guidelines. Method's name should start with uppercase letter.

This code

if (procResponse != null)
    return procResponse.FilesCount;

return 0;

can be replaced with

return procResponse?.FilesCount ?? 0;

Also it is not good to return string to show that something went wrong. Let exceptions be thrown, don't swallow them. Code that calls these methods should take care about exceptions.

And I don't understand why a space is placed before each ( in methods calls.


Passing a DTO into a static domain 'Create' method

If the Playlist is an external dependency then it might make sense to use an extension method like:

public static Playlist Create(this PlaylistDto playlistDto, IUserManager userManager, IPlaylistManager playlistManager)
{
    Playlist playlist = new Playlist
        {
            Id = playlistDto.Id,
            Items = PlaylistItem.Create(playlistDto.Items, playlistManager),
            Sequence = playlistDto.Sequence,
            Title = playlistDto.Title,
            User = userManager.Get(playlistDto.UserId)
        };

    return playlist;
}

other than that, if the code is under your control, why not just make another constructor and do away with the static method


Is this a 100% safe from SQL Injection and will work correctly for any input?

I want to give user ability to search anything.

It looks like you've achieved that, however, I'd use $_POST to reduce the likelihood that your application will be taken offline by users opening multiple tabs or search engine spiders hitting URLs.

  Will it be 100% safe and work as it should do for searching pieces of text in database?

Looks good for SQL injection.

As to whether it "should do" - have you considered generating the query dynamically to allow for tokenized search on inputs like "foo bar"? (i.e. ColB LIKE :token1 OR ColB LIKE :token2)


Rust echo implementation that supports command line options

Thanks to @Shepmaster's comment referring to one of his previous answers, I was able to make the process nicer, by using env::args as an Iterator.

By doing so, it became much easier to switch to using a match statement, and avoids all the string concatenation I mentioned in my question.

I've also managed to add the conversion from hex and octal values to chars by making use of std::u8::from_str_radix in conjunction with std::string::String::trim_start_matches

I therefore now have the following:

// echo in rust - display a line of text
use std::env;
use std::u8;

static HELP: &'static str = "\
echo the STRING(s) to standard output.\n\
-n     do not output the trailing newline\n\
-e     enable intepretation of backslash escapes\n\
-E     disable intepretation of backslash escapes (default)\n\
--help display this help and exit

If -e is in effect, the following sequence are recognized:

  \\\\    backslash
  \\a    alert (BEL)
  \\b    backspace
  \\c    produce no futher output
  \\e    escape
  \\f    form feed
  \\n    new line
  \\r    carriage return
  \\t    horizontal tab
  \\v    vertical tab
  \\0NNN byte with octal value NNN (1 to 3 digits)
  \\xHH  byte with hexadecimal value HH (1 to 2 digits)
";

fn main() {
    let mut nl: bool = true; // the "-n" flag can be used to indicate no new line
    let mut escape: bool = false; // Disable interpretation of backslashes
    let mut args_done = false; // Argument parsing done
    let mut first = true; // Correct the printing spacing

    for arg in env::args().skip(1) {
        if !args_done {
            match arg.as_ref() {
                "-n" => nl = false,
                "-e" => escape = true,
                "-E" => escape = false,
                "--help" => print!("{}", HELP),
                _ => args_done = true,
            }
        }

        if args_done {
            let mut datum: String = arg;
            if escape {
                datum = datum.replace("\\\\", "\\"); // backslash
                datum = datum.replace("\\a", ""); // alert (BEL)
                datum = datum.replace("\\b", ""); // backspace
                datum = datum.replace("\\c", ""); // produce no further output
                datum = datum.replace("\\e", ""); // escape
                datum = datum.replace("\\f", ""); // form feed
                datum = datum.replace("\\n", ""); // new line
                datum = datum.replace("\\r", ""); // carriage return
                datum = datum.replace("\\t", ""); // horizontal tab
                datum = datum.replace("\\v", ""); // vertical tab

                if datum.starts_with("\\x") && 3 <= datum.len() && datum.len() <= 4 {
                    // Hex values with at most 2 digits
                    let value = datum.trim_start_matches("\\x");
                    let chr = u8::from_str_radix(value, 16).unwrap() as char;
                    datum = chr.to_string();
                }

                if datum.starts_with("\\0") && 3 <= datum.len() && datum.len() <= 5 {
                    // Octal values with at most 3 digits
                    let value = datum.trim_start_matches("\\0");

                    let chr = u8::from_str_radix(value, 8);
                    // The maximum octal value for a byte is 377.
                    // Check that this conversion was successful.
                    if chr.is_ok() {
                        let x = chr.unwrap() as char;
                        datum = x.to_string();
                    }
                }
            }
            if first {
                print!("{}", datum);
                first = false;
            } else {
                print!(" {}", datum);
            }
        }
    }
    if nl {
        println!();
    }
}

This now adds an extra first flag for correct formatting, but it's okay for what is done here.


Is there a more efficient way of executing multiple SQL prepared statements at once?

Declaring Variables and other things:

try (Connection con = ds.getConnection()) {
    PreparedStatement updateSex = null;
    PreparedStatement updateAge = null;
    PreparedStatement updateGenre = null;

    String updateSexString = "UPDATE sex SET count=count+1 WHERE name=?";
    String updateAgeString = "UPDATE age SET count=count+1 WHERE id=?";
    String updateGenreString = "";

In your current approach, multiple prepared statements are not helping anyone..
You can just put the new prepared statements you are performing into the same PreparedStatement currentStatement.

This cuts down your declarations by quite a bit. Next are the update*String variables you have here. These things are Constants. Don't declare them on method-level, they can be reasonably expected to not change. Instead these should be classwide constants:

public class ... {
    private static final String UPDATE_SEX_STRING = "UPDATE sex SET count=count+1 WHERE name=?";
    private static final String UPDATE_AGE_STRING = "UPDATE age SET count=count+1 WHERE id=?";
    // you get the gist ;)

The small and the big wtf:

String updateGenreString = "";

for(int i = 0; i < checkboxes.length; i++){

    updateGenreString = "UPDATE genre SET count=count+1 WHERE id=?";
    updateGenre = con.prepareStatement(updateGenreString);
    updateGenre.setString(i+1, checkboxes[i].toString());

Why didn't you move the assignment to the updateGenreString, that doesn't even change to the declaration?

Additionally: Why is the parameter index depending on your loop counter? That makes absolutely no sense, because in case you have more than a single checkbox, things will break with the current statement!
If there's no second parameter, what happens when you try to set it? You get a SQLException, at least per the JavaDoc.

And another one: Why is the id a String? In general using Strings as ID/UID/UUID is strongly advised against. You're losing out on fast searchability and a few other things.

The id in the age-table also seems to be a String, at least according to the method you call.

Bottom line: Your database schema seems skewed.


Split every vector in a sequence into two parts: old elements that were contained in previous vectors and new elements never before seen

Concatenating a sequence of strings

You should use (apply str) instead of (reduce str) As str can take multiple arguments, and apply can take a sequence as a second argument. Intermediate results generated by reduce would cause time and space waste.

Since you are using a separator string, use clojure.string/join instead:

(->> (i :new) (map :name) (clojure.string/join ", "))

Naming loop vars

In the above code i is not a good name, I expect i to be some kind of index. If using meaningful names like user, order is not available; you can user curr for current m for map as temporary variables. Important point is principle of least surprise.

Map destructuring

You can also use map destructuring. It is easiest to show it by example:

> (doseq [{:keys [new old]} [{:new 1 :old 2} {:new 3 :old 4}]] (prn old new old))
2 1 2
4 3 4

So similarly here:

(doseq [{:keys [new old]} (rest precomputed)]
  (println "new: " (->> new (map :name) (clojure.string/join ", "))
           "old: " (->> old (map :name) (clojure.string/join ", "))))

Prefer functions over constants

Prefer functions over data. Functions are the basic unit of re-use in clojure. It will be obvious if you try to test precomputed you provided, with multiple example data (in REPL by hand or with run-tests). Other signs precomputed should be a function is:

it's name: precomputed implies a function by name precompute should exist (also/instead).
data is only referred to once, right at the end; and the rest of the form doesn't depend on it.

Decompose precomputed

See values in precomputed does not depend on the previous values of :new and :old but only those of :seen?.

It can be rewritten thus:

(defn seen-ids [data]
  (reductions
      #(clojure.set/union %1 (->> %2 (map :id) set))
    #{}
    data))

You don't need to put parens around set.

You can then get new and old elements separately:

(defn new-elts [seen-ids data]
  (map (fn [seen? v] (remove #(-> % :id seen?) v)) seen-ids data))

Terse function definition

Sometimes you may want to define a function as combination of other functions instead of using fn. Combinators clojure has for this purpose are comp, partial, and juxt.

For example #(-> % :id seen?) is equivalent to (comp %1 :id), which also allows the fn to be replaced by #. You can sometimes use partial to define functions w/o using parameter names, but I do not recommend it to use in top level functions, as parameter names are important developer documentation; but this style may be useful for shortening inline definitions (in let, for etc).

old-elts can be defined using this style, like this (compare with the definition of new-elts above):

(def old-elts (partial map #(filter (comp %1 :id) %2)))


Not sure of what is the context for your issue, so I will examine the 2 distinct cases I can think to.
Anyway I'm surprised your code doesn't show any data passed along with the POST: this should probably added in both cases below.

1) You said that "the user clicks twice the submit button": may be it means that you have only one button and "a lot of form submission" are successively done through this unique button.
If this is the case, the usually expected advantage of asynchronously processing is of no value here, and the pretty simple solution is to proceed synchronously, like this:

function listItem() {
    $.post( {url: "/post", async: false} )
      .done(function( data ) {
       // data successfully submitted
    });
}

(this way, no further click will have effect, till process done; also note that we had to change the way we are using $.post(), passing it a plain object as argument)

2) At the opposite, since you have written a function rather than a simple piece of code, you may have a lot of buttons, each one submitting a different form through the same listItem() call.
In this case, IMO the simplest way is to pass the button id to your function, that will disable it before launching POST, then enable it when achieved, like this:

function listItem(btnId) {
    button = $('#' . btnId);
    button.attr( {disabled:'disabled'} );
    $.post( "/post" )
    .done(function( data ) {
        // data successfully submitted
    })
    .always(function() {
        button.removeAttr('disabled');
    });
}

(using .always() ensures the button will be enabled even if POST failed or connection breaks)


Alternative to env that accepts arguments

I don't recommend calling your program ex.  That name has a well established meaning in the Unix world as the name of a text-editing tool.


type Direction = (Int -> Int -> Int)

These parentheses are superfluous, though they don't really hurt if they help you to read the code.

upperBound = 127 ; lowerBound = 32

It's not very common to put definitions on the same line with ;, particularly top-level definitions, so this made me double-take a bit. It makes it hard to find a particular definition by scanning the left column of the file.

It's a good idea to give all top-level definitions type signatures, as it helps to catch type errors earlier and makes it easier for someone reading the code.

Also, with numeric types, overloading in the Num class can often give surprising results, so explicitly stating that these are Int is a good idea.

shift :: Char -> Char -> (Int -> Int -> Int) -> Char
shift char charoff dir = fix $ dir (ord char) (ord charoff)

Consider putting the function argument first here. The function is more likely to be useful partially applied as shift dir than as shift char, and it also makes for a more intuitive type signature which correctly gives the sense that a function Int -> Int -> Int is being transformed into a function Char -> Char -> Char.

fix :: Int -> Char

As someone mentioned on your StackOverflow post, fix is a standard library name for something different, so best not to reuse it here.

| charcode > upperBound = chr $ (lowerBound - 1) + excessOf (upperBound + lowerBound)
| charcode < lowerBound = chr $ (upperBound + 1) - excessOf (lowerBound - lowerBound)
    where   excessOf boundry = abs(boundry - charcode)

I find it hard to understand these two cases. You could perhaps add comments to explain what they are doing. Also lowerBound - lowerBound is just 0 so what are you trying to do here? I presume the whole thing is about clamping to within the valid ASCII range but it's quite confusing.

In general I'd have expected a Caesar cipher just to work on letters, rather than the whole ASCII range, but that's a specification question really.

alter :: Message -> Key -> (Int -> Int -> Int) -> Message
alter msg key dir = [(shift c k dir) | (c,k) <- zip msg (cycle key)]

Again I would put the function as the first argument here. I would also put the Key as the second argument, because then you can partially apply it with a key to get a specialised encryption or decryption function. It might also make sense to have the key first and the function second.

enc msg key = alter msg key (+)
dec msg key = alter msg key (-)

As before, type signatures would help here. Also, if you do change the order of the arguments to alter above then this can be abbreviated as enc = alter (+) or enc key = alter key (+), which is perhaps slightly more elegant.


Reverse double linked list in python 2.7

Firstly, the line

new_list.pre_node = None

doesn't do anything and can be removed. Secondly, your code can't handle circular double-linked lists.

Circular lists

When called on a circular double-linked list:

Print_list goes into an endless loop.
Reverse_list terminates late, giving a partially reversed list.

Your code could be easily improved to handle these issues. Preventing an endless loop requires keeping track of the identity of each node. Below, I've done this by incrementing a global variable node_count, but there are more Pythonic ways to keep a count of instances of objects.

The unique id is used to track when the cursor id matches self.id, terminating the while loops in print_list and reverse_list at the appropriate time for circular lists.

Lastly, PEP8 specifies methods within a class should be separated by a single line.

See below:

class DoubleLinkedListNode:

    def __init__(self, value, next_node):
        global node_count                         # added unique node id
        self.id = node_count
        node_count += 1
        self.value = value
        self.pre_node = None                      # removed unnecessary line
        if next_node:
            next_node.pre_node = self
        self.next_node = next_node

    def reverse_list(self):
        new_list = self
        cur = new_list.next_node
        new_list.next_node = None
        while cur:
            node = cur.next_node
            new_list.pre_node = cur
                cur.next_node = new_list
            if cur.id == self.id and not node: break    # for circular lists
            new_list = cur
            cur = node
        return new_list

    def print_list(self):
        cur = self
        result = []
        while cur:
            result.append([cur.value])
            next_id = cur.next_node.id if cur.next_node else None
            if next_id == self.id: break               # for circular lists
            cur = cur.next_node
        return result

if __name__ == "__main__":
    node_count = 0
    head = DoubleLinkedListNode(1, DoubleLinkedListNode(2, DoubleLinkedListNode(3, DoubleLinkedListNode(4, DoubleLinkedListNode(5, None)))))
    print(head.print_list())
    new_head = head.reverse_list()
    print(new_head.print_list())

(Bonus: For simple testing, here's my method to make the lists circular. Add it to the DoubleLinkedListNode class.)

    def circularize(self):
        cur = self
        while cur.next_node:
            cur = cur.next_node
        cur.next_node = self

Complexity

Reversing lists, double-linked or not, scales according to \$\mathcal{O}(n)\$, where n is the length of the list.

The only way to speed it up significantly is to make each list an object, with a Boolean direction flag. Any process moving through the list first refers to the direction flag, which either calls next_node or pre_node depending on how it's set. All that's needed to reverse the list is to reverse the direction flag.

Update:

Below is an example of how \$\mathcal{O}(1)\$ reversal of double-linked lists might be implemented using a direction flag. Points relevant to OP's code are:

A dedicated reverse_list method is not really necessary.
An __iter__ method is more useful than a dedicated print_list method (thanks ChatterOne).
Circular lists are also reversed neatly this way (note that __iter__ cycles endlessly for circular lists).

See below:

class DoubleLinkedListNode:
    def __init__(self, value, plus_node, dir=None):
        self.value = value
        self.minus_node = None
        if plus_node:
            plus_node.minus_node = self
            if dir == None:
                self.dir = plus_node.dir
        if dir != None:
            self.dir = dir
        self.plus_node = plus_node

    def __iter__(self):
        self.cur = self
        return self

    def __next__(self):
        if self.cur:
            current = self.cur
            if self.cur.dir:
                if self.cur.dir[0] > 0:
                    self.cur = self.cur.plus_node
                elif self.cur.dir[0] < 0:
                    self.cur = self.cur.minus_node
            return current
        else:
            raise StopIteration

if __name__ == "__main__":
    tail = DoubleLinkedListNode(5, None, [1]) # [1] sets direction for all nodes in list.
    head = DoubleLinkedListNode(1, DoubleLinkedListNode(2, DoubleLinkedListNode(3, DoubleLinkedListNode(4, tail))))
    for i in head: print(i.value)  # Prints node values forwards from head.
    head.dir[0] = -1               # Reverses direction for all nodes in the list.
    for i in tail: print(i.value)  # Prints node values in reverse from tail.


Processing student scores from the stdin

You should get into the habit of initialising variables whenever possible. It's a little more difficult here, since currentMax, currentMin, and currentEntry may seem not to have a sensible default value. However, all arithmetic values have an upper and a lower bound (these can be found in limits.h). It would make sense to initialise currentMax and currentMin based on these:

int currentMax = INT_MIN;
int currentMin = INT_MAX;

Note that if the user inputs -1 straight away, currentMax and currentMin will now print out predictable values. If you leave them uninitialised, they will print out whatever bits happen to be on the stack at that point in time (effectively, they will print out a random value).

Also, note that because these are now initialised with the min/max integer values respectively, you can remove the check for counter being 1.

I'd also initialise currentEntry and average, 0 and 0.0 seem like relatively reasonable defaults.

The name startValue is accurate at the beginning, but by the end, doesn't really reflect the starting value as you've been adding to it each time. Hence, I'd rather call it something like currentTotal.

Integer division in C can trip beginners up, the line:

average = startValue/counter;

isn't doing quite what you want it to be. Since startValue and counter are both integers, this will do an integer division, and then convert that to a double. Hence this will actually be the floor of the average. To fix this, you need to cast the numerator or denominator to a double:

average = (double)startValue / counter;

In the end, the code is pretty similar, but looks something like:

#include <stdio.h>
#include <limits.h>

int main()
{
    int currentEntry = 0;
    int currentTotal = 0;
    int counter = 0;
    int currentMax = INT_MIN;
    int currentMin = INT_MAX;
    double average = 0.0;

    printf("Enter scores one-by-one, exit by entering -1\n");

    while(currentEntry != -1) {
        if((scanf("%d", &currentEntry) == 1) && (currentEntry != -1)) {
            printf("Current score is %d\n", currentEntry);
            counter++;
            currentTotal += currentEntry;
            average = (double)currentTotal/counter;

            if(currentEntry > currentMax) {
                currentMax = currentEntry;
            }

            if(currentEntry < currentMin) {
                currentMin = currentEntry;
            }
        }
    }

    printf("The average is %lf\n",average);
    printf("The maximum score is %d\n", currentMax);
    printf("The minimum score is %d\n", currentMin);
    return 0;
}


Your main in-effeciency is here:

if(std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), i) != listOfNonPrimes.end())

For every non-prime you are a doing a search through the list of non primes. For both std::vector and std::list this is an O(n) operation.

The usual way of implementing this is to have an array where the removed elements are represented by their index into the array and thus represent a complexity of O(1) to both set and check if an element has already been set to false.

std::vector<bool> sieve(number + 1, true);

Then the following lines can be replaced:

if(std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), i) != listOfNonPrimes.end())
    continue;
listOfNonPrimes.push_back(i);

// Change too
sieve[i] = false;

Other things:

Every time through the loop you do a test:

if (i == current_prime_check) {
    container.push_back(i);
    continue;
}

This is only true the first element.

So hoist it out of the loop. Do the container.push_back(i); outside the loop and start i at the next position:

for (unsigned int i = 2 * current_prime_check; i < number; i += current_prime_check)
             //   ^^^^ Start one place up from where you were.

Replace the other find as well:

++current_prime_check;
while (std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), current_prime_check) != listOfNonPrimes.end()) {
    ++current_prime_check;
}

If you use the sieve this can be replaced by a simple test into the sieve:

++current_prime_check;
while (!sieve[current_prime_check]) {
    ++current_prime_check;
}

After Edit Comments:

We can make it quicker.

Your function that generates the prime:

void CalculateListOfPrimes(std::vector<unsigned int>& container, const unsigned int number)

You pass an array the function fills the array then you processes the array as the next stage. A better solution would be to pass a function that is applied to each prime as you find it. Then you can have a simple version that pushes the values into a container. Or alternatively you can have a function that just sums up the primes (so you do not even need the container or have to iterate over it).

So try:

template<typename Func>
void CalculateListOfPrimes(Func const& action, const unsigned int number);

Then you could use it like this:

struct PB
{
    std::vector<unsigned int>& cont;
    PB(std::vector<unsigned int>& c): cont(c) {}
    void operator()(unsigned int value) const { cont.push_back(value); }
};
…
std::vector<int> data;
CalculateListOfPrimes(PB(data), 2000000);

Or you can have a specific function

struct Sum
{
   unsigned int& sum;
   Sum(unsigned int& s) : sum(s) {}
   void operator()(unsigned int value) const { sum += value; }
};
…
unsigned int total;
CalculateListOfPrimes(Sum(total), 2000000);

Comments:

Don't use system("pause");. It's plainly platform specific. All you are doing is getting the program to wait. So read a line from the standard input.

std::getline(std::cin, line); // If you have other input you may need to flush first.

Hash define not a good move.

Prefer to use a function (there is no performance penalty as it will probably be inlined). If you must use a hash define then define it like this:

#define PAUSE  do { /* Action To Pause */ } while(false)

atoi()

primes = CalculateListOfPrimes(std::atoi(argv[2]));

Not standard. No way to check failures.

I would use boost::lexical_cast(argv[2]) it will throw an exception on failure.

Don't pass pointers around

DisplayResult(&primes, 0);

Change the function so you pass by const reference. This avoids the copy, stops you from accidentally modifying the array, and you can't accidentally pass a NULL so its always valid.

void DisplayResult(std::vector<bool> const& container, const unsigned int sum);

Truth values:

The result of the == operation is a boolean so you don't need to use a ternary operator on-top of that:

bool isSumArg = (std::strcmp("-s", argv[1]) == 0 ? true : false);

is exactly equivalent to the easier-to-read

bool isSumArg = (std::strcmp("-s", argv[1]) == 0);

Prime specific values:

A quick optimization here. You do not need this loop to go all the way to number.

You just need to loop as far as sqrt(number) after that nothing will affect the result.

while (current_prime_check < number) { … }

Make functions do one thing.

This function does lots of different things depending on the inputs that are not related.

void DisplayResult(std::vector<bool>* container, const unsigned int sum) {
    if(container == NULL && sum == 0) {
        return;
    }

    if(sum != 0) {
        std::cout << "Sum of Primes: " << sum << std::endl;
        return;
    } else if(container != NULL) {
        std::cout << "List of Primes:" << std::endl;
        for(unsigned int i = 1; i < container->size(); ++i) {
            if(container->at(i) == true) std::cout << std::setw(15) << std::right << i << std::endl;
        }
    }
}


Simple simulation of animals eating other animals

every time I would need to add a new animal, I would not be able to do it just by extending the existing classes or by adding new ones: I would have to modify the existing classes.

The problem exists in both your approaches. It is because the eating preferences of individual species is mutualy dependent on all other existing animals. If you add new animal, you define what existing animals it likes to eat, but unless you modify existing animals, no existing animal will ever be interested in eating the new animal.

Generally relying on object being of a specific type is not polymorphism, it's a rape.

You need to abstract and centralize the eating preferences somehow.

public enum AnimalKind
{
  Lion,
  Hyena
}

public interface IDinner
{
  public AnimalKind Kind {get;}
  public Size Size {get;}
}

public interface IEater
{
  public bool Likes(IDinner dinner);
}

public interface IAnimal : IEater, IDinner
{
  bool IsDead {get;}
  void Kill();
}

class Animal : IAnimal
{
  public AnimalKind Kind {get;}
  public Size Size {get;}
  public bool IsDead {get;}

  private IDictionary<AnimalKind, Size> Preferences {get;}

  public Animal(AnimalKind kind, Size size, IDictionary<AnimalKind, Size> preferences)
  {
    this.Kind = kind;
    this.Size = size;
    this.Preferences = preferences;
  }

  public bool Likes(IDinner dinner)
  {
     var maxSize = this.Preferences[dinner.Kind];
     return maxSize != null && dinner.Size <= maxSize;
  }

  public void Kill()
  {
    IsDead = true;
  }
}

public interface IAnimalFactory
{
  public IAnimal CreateAnimal(AnimalKind kind, Size size);
}

public class AnimalFactory : IAnimalFactory
{
  // centralized place for all animals and their eating preferences
}

public static class AnimalPark
{
    public static void Process(IList<IAnimal> animals)
    {
        int length = animals.Count;
        for(int i=1; i<length; i++)
        {
            var eater = animals[i - 1];
            var dinner = animals[i];
            if (!dinner.IsDead && !eater.IsDead && eater.Likes(dinner)) {
                dinner.Kill();
            }
        }
    }
}

Adding new animal now means just extending AnimalKind enum and modifying AnimalFactory class to be aware of the new kind.

Although you might object that having the enum is also not nice. And I kinda agree, but I didn't want to invent an abstraction of the dinner description that was not provided by you. Maybe dinner description could instead be something like a description of how big teeth and paws the dinner has, how aggresive and vicious they look, if they have colors that imply being venomous, etc... If you impleent something like this and get rid of the AnimalKind enum, you will need to change the factory to contain a method per existing animal, but I would not consider it a problem, it may actually be so even with the enum existing...

Also notice I have moved the actual killing of the animal to the AnimalPark class, because that would be the same for all animals. An animal is always killed when eaten and stays alive when not eaten, right?


Multiple dispatch with variant and multi visitation in C++

It's a good example of multimethods in C++. But you should be aware that variant takes at least as much space as the biggest of its argument. It's done so to minimize overhead of walking an additional pointer. Probably, you need a variant with another allocation policy, as asteroids and spaceships are quite numerous.

But, to be serious, there's an even bigger problem: extension. You would like to

define new functions that do something with asteroids, spaceships or tuples of them;
define new types of asteroids and spaceships;
modify code only locally.

Your solution needs to have variant<list, of, all, objects, of, the, kind> in several places of your code in addition to defining a new classes for new types of game objects. That's a non-local change.


Modeling a soccer team with substitutions

You naming convention does not follow PEP 8. Try to follow it as much as you can as it helps having same consistent guidelines all over Python code.

I do not quite understand how the on field thingy is supposed to work so I'll skip on that part.

Try to avoid global variables. Try to think how things would be affected if you were trying to handle multiple teams. Most probably things would go wrong.

I guess your different lists should be part of the team class. Also, there is not much point for having a Player class as a player on its own is nothing but a name. As far as I understand soccer, the number is for a given player in a given team. Thus, the team should be some kind of containers of pairs name/number.

Also, it seems like your are doing the same things for different teams of players that could be handled the same way. Instead of write code, it's easier to use smart data structures and make them work for you. In your case, it seems like a dictionnary from position to list of (player name + player number) is good idea. Default composition is to have empty lists and to fill them later on.

Here's what my code looks like :

class Team(object):
    def __init__(self, name):
        self.name = name
        self.composition = {
            'forward' : [],
            'midfield': [],
            'defense': [],
            'goalie': []
        }

    def add_player(self, name, number, position):
        if position not in self.composition:
            print 'Only %s accepted' % ', '.join(self.composition.keys())
        else:
            self.composition[position].append((name,number))
            print 'Added %s to the team!' % name

bcn = Team('Barcelona')
bcn.add_player('Messi', 10, 'forward')
bcn.add_player('Neymar', 11, 'forward')
bcn.add_player('Song', 9, 'midfield')
bcn.add_player('Valdes', 1, 'goalie')
bcn.add_player('Pique', 25, 'defense')
bcn.add_player('Pedro', 8, 'forward')
bcn.add_player('Josay', 10, 'invalid')

# It could be a good idea to create a method to do this :-)
for pos, players in bcn.composition.iteritems():
    print pos
    for p in players:
        print p


About your points:

The interface seems pretty clear.
If you fear about the \arraystretch parameter being abused, you're right: on a double spaced document all tables come out horribly and local remedies are often necessary. Maybe adding a stretch key could help for these cases.
Yes, you're abusing local and global assignments.

Some comments about the code:

There is no point in the key alphabet to set a tl variable, which is then converted to a clist
There's no need to set a .default:n for the font key: the value specified with .default:n would be used if the key is called without assigning a value
\int_step_inline:nnnn can be done more simply using the * feature of tabular
Never use \expandafter in expl3 code
You should not use global assignments on local variables
\clist_gpop:NN should be \clist_gpop_left:NN (but I changed it into \seq_pop_left:NN)
One can do with a simpler loop, using \prg_replicate:nn

I'd also prefer to prepare the table body outside the table, with sequences instead of clists, which are less efficient.

\documentclass{article}
\usepackage[landscape]{geometry}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand { \printvigeneretabular } { O{} }
 {
  \vigenere_tabular:n { #1 }
 }

% keys
\keys_define:nn { vigenere }
 {
  font      .code:n       = { \cs_set_eq:NN \__vigenere_font: #1 },
  font      .initial:n    = { \small },
  tabcolsep .dim_set:N    = \l__vigenere_tabcolsep_dim,
  tabcolsep .initial:n    = { 3pt },
  alphabet  .clist_set:N  = \l__vigenere_alphabet_clist,
  alphabet  .initial:n    = { A, B, C, D, E, F, G, H, I, J, K, L, M,
                              N, O, P, Q, R, S, T, U, V, W, X, Y, Z }
 }

% variables
\tl_new:N \l__vigenere_tablebody_tl
\seq_new:N \l__vigenere_alphabet_seq

% internal function
\cs_new_protected:Nn \vigenere_tabular:n
 {
  \group_begin:
  % set the keys
  \keys_set:nn { vigenere } { #1 }
  % make a sequence from the alphabet
  \seq_set_from_clist:NN \l__vigenere_alphabet_seq \l__vigenere_alphabet_clist
  % set the font and the tabcolsep
  \__vigenere_font:
  \dim_set_eq:NN \tabcolsep \l__vigenere_tabcolsep_dim
  % prepare the table body
  \tl_clear:N \l__vigenere_tablebody_tl
  \prg_replicate:nn { \seq_count:N \l__vigenere_alphabet_seq }
   {
    \tl_put_right:Nx \l__vigenere_tablebody_tl
     {
      \seq_use:Nn \l__vigenere_alphabet_seq { & }
      \exp_not:n { \\ \hline }
     }
    \seq_pop_left:NN \l__vigenere_alphabet_seq \l_tmpa_tl
    \seq_put_right:NV \l__vigenere_alphabet_seq \l_tmpa_tl
   }
  % make the table
  \tabular { | *{\clist_count:N \l__vigenere_alphabet_clist }{ c| } }
  \hline
  \tl_use:N \l__vigenere_tablebody_tl
  \endtabular
  \group_end:
 }
\ExplSyntaxOff

\begin{document}

\printvigeneretabular

\printvigeneretabular[font=\tiny,alphabet={1,2,3,4,5,6,7,8,9,10},tabcolsep=1pt]

\end{document}


Reducing a 2D array to its longest unique series that aren't contained within any other

Bug

Try the following input:

$catLists = array(
                    0 => array('sml', 'med', 'lrg', 'xlg', 'xxl'),
                    1 => array('smlmed', 'lrg', '', '', ''));

I think that this will produce just one row of output, although it should produce two (these arrays are distinct).  To avoid this, you should check the arrays after finding matching strings or use some character that would never appear in the strings to join them.  If you change the join character, note that you may have to trim out the empty portion before generating the string.

For example, the colon (:) would work in your example:

$stringified = ':' . implode(':', $catList) . ':';

but would produce strings like :big::::: when you probably just want :big:.

Avoid unnecessary variables

            $contained = false;
            foreach ($catList_strings as $cl_str) {
                if ( strpos($stringified, $cl_str) ) $contained = true;
            }
            if (!$contained) {
                $catList_strings[] = $stringified;
                $reduced_catLists[] = array_filter($catList);
            }

You can just say

            foreach ($catList_strings as $cl_str) {
                if ( strpos($stringified, $cl_str) ) {
                    $catList_strings[] = $stringified;
                    $reduced_catLists[] = array_filter($catList);
                    break;
                }
            }

This is also more performant, as it stops as soon as it finds a match.  The original code tried to generate more.

Consider using an associative array

You can make this more direct.  Something like:

function array_contains($base, $candidate, $start = 0) {
    if (count($base) < count($candidate) - $start) {
        return false;
    }

    foreach ($base as $v) {
        if ($v != $candidate[$start]) {
            return false;
        }
    }

    return true;
}

$indexesOf = array();
foreach ($catLists as $i => $catList) {
    $trimmedList = array_filter($catList);
    foreach ($trimmedList as $j => $cat) {
        if (isset($indexesOf[$cat]) {
            if (0 == $j) {
                foreach ($indexesOf[$cat] as $index => $start ) {
                    if (array_contains($catList, $catLists[$index], $start)) {
                        break 2;
                    }
                }
            }
        } else {
            $indexesOf[$cat] = array();
        }

        $indexesOf[$cat][$i] = $j;
        $reducedCatLists[] = $trimmedList;
    }
}

This uses a dictionary lookup to search for arrays that could potentially contain the current one.

Bug 2

Perhaps this isn't an issue, but the array order matters here.  You only check arrays that you've already seen.  I do this as well.  Not sure how much it matters, but

$catLists = array(
                    0 => array('500ml', '750ml', '', '', ''),
                    1 => array('300ml', '500ml', '750ml', '1L', ''));

and

$catLists = array(
                    0 => array('300ml', '500ml', '750ml', '1L', ''),
                    1 => array('500ml', '750ml', '', '', ''));

will return different results.

If you want to get the same result from both inputs, then you have to loop through the array twice.  The first time, you build the lookup array.  The second time, you build the reduced list.

Test

If you have historically accurate values for $catList run a test where you time how long it takes to process either way.

Note that if it only changes weekly, it may be reasonable to save $reducedCatList when it first appears.  That would be unlikely to cause significant load to the server, as you can choose to do it at a time when most legitimate users don't use the server.  Something like 3 AM is great, but even a time like 3 PM might work.  I don't know what patterns your customers follow.


As Martin R said, if all strings must match a common prefix, then that prefix is whatever the first and last string in a sorted array have in common.

The code in the SO answer isn't too pretty though. Here's my take (rags-to-riches?):

function findPrefix(strings) {
  if(!strings.length) {
    return ""; // or null or undefined; your choice
  }

  var sorted = strings.slice(0).sort(), // copy the array before sorting!
      string1 = sorted[0],
      string2 = sorted[sorted.length-1],
      i = 0,
      l = Math.min(string1.length, string2.length);

  while(i < l && string1[i] === string2[i]) {
    i++;
  }

  return string1.slice(0, i);
}

Compared to the SO answer, the main point here (besides style and camelCased variables) is that the array is copied, and the copy is sorted. Otherwise, the same array object that was passed to the function will be sorted as a side-effect.

Compared to your code, I've skipped the strings-it-truth'y check at the very start. I prefer to assume that arguments are at least the correct type (i.e. an array) - otherwise it's the caller's problem.

As for your current code:

As mentioned in the comments, you can use string.charAt(i) or simply string[i] (though the latter is a more recent addition to JS) instead of splitting the string into an array.
Your inner loop starts at index 0 - but that's the same string you're already using as your characters array, so you already know that it's going to match.
The moment you hit a non-match, use break to skip the rest of the loop. My bad, you're already returning from the loop, which has the same effect.

As for finding suffixes, your current code seems fine to me if you use the "sort-and-compare" approach above for findPrefix. Otherwise, it'd probably be infinitesimally faster to write a separate findSuffix function that just has its loops reversed. The logic's the same, the indices just run backward.

While nothing beats the sort-and-compare approach (except a better one; see below), here's, just for fun, another way to to use all strings, unsorted, to find the prefix:

function findPrefix(strings) {
  function commonPrefix(a, b) {
    var i = 0,
        l = Math.min(a.length, b.length);

    while(i < l && a[i] === b[i]) {
      i++;
    }
    return a.slice(0, i);
  }

  return strings.reduce(function (prefix, string) {
    // if prefix is empty or matches the string,
    // then just return the prefix immediately
    if(string.indexOf(prefix) === 0) {
      return prefix;
    }

    // otherwise, find the intersection between
    // prefix and the string
    return commonPrefix(prefix, string);
  });
}

Update: As MatinR pointed out in the comments, sort may be a drag on performance, and besides it isn't necessary, as you only need what would be the first and last string in a sorted array. These strings can alternative be found like so:

function extremes(strings) {
  // grab two strings to use as our initial guesses
  var initial = {
    largest: strings[0],
    smallest: strings[strings.length-1]
  };

  // loop through to find the extremes
  return strings.reduce(function (memo, string) {
    // slightly funky syntax, but it's short.
    (memo.largest > string) || (memo.largest = string);
    (memo.smallest < string) || (memo.smallest = string);
    return memo;
  }, initial);
}

The two strings in the returned object may then be used to determine the shared prefix (if any). The entire thing can also be built into findPrefixes, of course, rather than be a separate function as shown below:

function findPrefix(strings) {
  if(!strings.length) {
    return ""; // or null or undefined; your choice
  }

  var string1 = strings[0],
      string2 = strings[strings.length-1],
      i, l;

  // note: a regular for-loop is faster than forEach
  // I'm using forEach because it's prettier
  strings.forEach(function (string) {
    (string1 < string) || (string1 = string);
    (string2 > string) || (string2 = string);
  });

  i = 0;
  l = Math.min(string1.length, string2.length);
  while(i < l && string1[i] === string2[i]) {
    i++;
  }

  return string1.slice(0, i);
}


A barrier can ensure the threads execute in an interleaved fashion.

final CyclicBarrier rendezvous = new CyclicBarrier(2);
final CyclicBarrier conclusion = new CyclicBarrier(3);
Thread a = new Thread() {
    public void run() {
         try {
             rendezvous.await();
             // do your stuff
             // do your stuff
             rendezvous.await(); // if you want to be extra sure the ops are interleaved
             // do your stuff
         } catch (...) {}
         finally { conclusion.await(); }
    }
};

Thread b = new Thread() {
    public void run() {
         try {
             rendezvous.await();
             // do your other stuff
             // do your other stuff
             rendezvous.await(); // if you want to be extra sure the ops are interleaved
             // do your other stuff
         } catch (...) {}
         finally { conclusion.await(); }
    }
};

a.start();
b.start();
conclusion.await();

assertTrue instead of assertEquals(.., true, ..).

cut and paste error has you modifying t2Correct instead of t1Correct


In writing a class model, it can be useful to consider whether a class represents a value (something that doesn't change, but can be useful in multiple contexts), or an entity (something with an identity - a sense of self - that doesn't change even though the values associated with that identity do change).

In your fragment here, I would expect Particle to be an entity (Earth is still Earth even while it moves through its orbit), and PhysicsVector to be a value.

What does this mean for your implementations?

Entities are usually an encapsulation of some rules describing how their current state becomes the next state.  You don't change the state of an entity directly - instead you command it to change, giving it the arguments that it needs to do the work, and the entity determines its own next state.

public class Particle{

    private double mass;
    private PhysicsVector initialPosition = new PhysicsVector();
    private PhysicsVector initialVelocity = new PhysicsVector();

Quick review here - these describe the state of the particle, and you've made them private, which is consistent with the idea that the Particle should control its own state.  mass should probably be final -- you could name it restMass to be more clear.  (It might not be final, depending on how you want to model inelastic collisions).

initialPosition and initialVelocity are probably incorrectly named -- the "initial" state of an object shouldn't change later? so currentPosition/currentVelocity would make things clearer, although since the entity is always holding its current state, position and velocity would probably suffice.

My guess is that your model will want to be able to specify the starting configuration of particles, so you should have a constructor that allows them to do so -- in other words, we are constructing the entity in its initial state.

public class Particle{
    // ...
    public Particle(double restMass, PhysicsVector initialPosition, PhysicsVector initialVelocity) {
        this.mass = restMass;
        this.position = initialPosition;
        this.velocity = initialVelocity;

One constructor can reference another, so if you intend to support the creation of particles in an arbitrary initial state, you create a second contructor that calls this first:

    public Particle(double restMass) {
        this(restMass, new PhysicsVector(), new PhysicsVector());

Now, as we said we send commands to an entity to tell it to change its state.  The entity already knows its own state, so we don't need to pass that in.  So this code doesn't really make sense

public PhysicsVector updatePosition(PhysicsVector initialPosition, PhysicsVector initialVelocity, double timeStep, PhysicsVector aDueToGravity){
    PhysicsVector x = new PhysicsVector(initialVelocity);
    x.scale(timeStep);
    PhysicsVector z = new PhysicsVector(aDueToGravity);
    z.scale(0.5*timeStep*timeStep);

    initialPosition.increaseBy(x);
    initialPosition.increaseBy(z);

    return initialPosition;
}

Either this is a member function (meaning, being run against a specific entity), in which case it should be using the state of the entity at the time it is run:

public void updatePosition(double timeStep, PhysicsVector aDueToGravity){
    PhysicsVector x = new PhysicsVector(velocity);
    x.scale(timeStep);
    PhysicsVector z = new PhysicsVector(aDueToGravity);
    z.scale(0.5*timeStep*timeStep);

    position.increaseBy(x);
    position.increaseBy(z);

    return initialPosition;
}

or instead it's more a convenient calculation service; you can make it clear that it isn't really scoped to the entity by declaring the method to be static (class scope)

public static PhysicsVector updatePosition(PhysicsVector initialPosition, PhysicsVector initialVelocity, double timeStep, PhysicsVector aDueToGravity){
    // ...
}

Or alternatively you can perhaps see in it a time step calculator that is independent of the Particle

public class Accelerator {
    private final double timeStep;
    private final PhysicsVector acceleration;

    public PhysicsVector nextPosition(PhysicsVector currentPosition, PhysicsVector currentVelocity) {
        // ...
    }

public class Particle {
    public void updatePosition(Accelerator accelerator) {
        position = accelerator.nextPosition(position, velocity);

I strongly prefer this approach -- gravity, in non uniform fields, depends on where you are, so you are going to need the position to calculate the force (and then the mass to scale it to the right acceleration).

Your calculator for momentum definitely looks more like a service that should be operating on a collection of particles, than it does a member function of a single particle

public static PhysicsVector[] momentum(Particle [] particles)

ValueTypes are typically immutable - subtracting the position of the earth from the position of the sun doesn't move either particle, but instead gives you a new vector describing the relative position between the two.

We don't send commands to valueTypes, we send them queries, "what do we get if?" kinds of things.  Running the query doesn't change the value (it is immutable), it just returns a result.  So if we want to use vector addition to update the position of the particle, we should expect to use a replace with query result pattern

position = position.increaseBy(x);

Given that what we are doing is vector addition, I'd probably prefer that increaseBy was instead using the spelling add.

Other modeling considerations - PhysicsVector, as a type, is a bit vague; it would be very easy to initialize a particle the wrong way round by ordering your position and velocity incorrectly.  You could make PositionVector distinct from VelocityVector; this would also guard against bugs where you try to add two different vectors that have different units.  Depending on the model, you might also want to distinguish PolarVectors and AxialVectors,


There is a bug in your code for those times when the two input values are not prime.

Consider an instance when the input values are 4 and 6. In this case, your code will output F for multiples of 4, and B for multiples of 6, and FB for multiples of 24.... great... but, is it? No, 12 is a multiple of both, but will only print "F ".

If you want to use the optimized cascading-if-else version of FizzBuzz, then you need to ensure the inputs are both prime, or have no common factors.

It would often still be faster to compute the common factors and then after that do the system you have.


Sharing $scopes across Controllers with ScopeFactory

I've finally refactored out the anti-pattern ScopeFactory out of my apps.
Instead I'm using $broadcast and $emit to accomplish what I'm trying to do, which is the more Angular way of doing this.

Example
Controller 1 (I $emit out the event and send a variable):
$rootScope.$emit("add.ticker.typing", word);
Controller 2 (I listen for the event and pick it up, including variables like objects or strings):
$rootScope.$on(
    "add.ticker.typing",
    function handleSearchTyping(event, word, option) {
        if (option != 'empty') {
            typingSearch(word);
        } else {
            $scope.tickersList       = [];
            $scope.tickersListLoaded = false;
        }
    }
);

Now with this, now only is it a true Angular pattern, but I'm not sending giant Controller $scope objects all around my app.


Remember to close resources
You are opening a file with
Scanner input = new Scanner(new File(args[0]));

but you are never closing the Scanner. This can lead to resource leaks and hard to track down bugs. This is typically solved by using a try-with-resources construct:
try (Scanner input = new Scanner(new File(args[0]))) {
    // ...
}

With this change, the Scanner will be opened at the beginning of the block, and always closed, automatically, at the end. This ensures that, whatever happens in the try block (exception or not), the resource will be properly closed.
Use of methods
Your code makes use of 2 methods:

printLongestLines, which is responsible for printing the top-most lines read.
addLine, which adds a line into a map.

The first method, printLongestLines, is great: its name is descriptive and does the job it is intended to do.
However, the second is awkward: it takes as parameter a map that it will modify. Generally, modifying input parameters inside a method is a bad practice. It means that the code isn't correctly decoupled. In this case, it is because this method is actually part of a bigger responsibility: storing the lines of the file inside a map. Conceptually, you want to break down the program into meaningful methods that perform a task; the task here is reading the file.
As such, consider the following method readLines instead:
private static NavigableMap<Integer, String> readLines(Scanner input) {
    NavigableMap<Integer, String> lineMap = new TreeMap<>();
    while (input.hasNextLine()) {
        String line = input.nextLine();
        lineMap.put(line.length(), line);
    }
    return lineMap;
}

The advantage is that reading from the Scanner and populating the line map is done inside a well defined method, that the main part of the code just invokes.
Iterators
The method printLongestLines is currently using pollLastEntry() to retrieve, and remove, the last entry of the map. This is a side-effect operation: this method is modifying the input map, by removing elements from it.
It would be preferable to use an Iterator to iterate over the map. Consider the following:
private static void printLongestLines(NavigableMap<Integer, String> lineMap, int numberOfLinesToPrint) {
    Iterator<String> iterator = lineMap.descendingMap().values().iterator();
    int i = 0;
    while (i < numberOfLinesToPrint && iterator.hasNext()) {
        System.out.println(iterator.next());
        i++;
    }
}

This gets the reversed map (with descendingMap) and iterates over the values only, since we're not interested in the key. It also highlights a potential bug in your current implementation: if you were to print a number of lines greater than the size of the map, it would fail. This is handled here by checking whether the iterator has a next element.
You don't need a map
You will notice that, in the map that was built, we're only interested in the values, i.e. the lines themselves. This shows that, in fact, we do not need a map. We can directly use a SortedSet where the String are sorted by their length.
private static SortedSet<String> readLines(Scanner input) {
    SortedSet<String> set = new TreeSet<>(Comparator.comparing(String::length, Comparator.reverseOrder()));
    while (input.hasNextLine()) {
        set.add(input.nextLine());
    }
    return set;
}

This creates a set that is sorted in reverse order using a comparator comparing their length. This is using Java 8 specific code (comparing and the method reference String::length) but the same can be done with anonymous classes.
With this change, you can have a very simple printLongestLines method:
private static void printLongestLines(SortedSet<String> set, int numberOfLinesToPrint) {
    set.stream().limit(numberOfLinesToPrint).forEach(System.out::println);
}

This is using the Stream API, but you could keep the same code as before for Java <= 7, using explicitely an iterator.

As oopexpert points out in a comment, you can also directly use a List<String> to store the lines of the file. Depending on the use-case, this also would have the advantage that duplicate lines are kept. The change to do in readLines would simply be to explicitely sort the list once the lines are read, with:
List<String> lines = new ArrayList<>();
// loop over input to add each line
lines.sort(Comparator.comparing(String::length).reversed());


The question is tagged python-3.x; this answer assumes 3.2 or higher.

Threading

You can dramatically simplify the code by using a framework for concurrency and
queueing. Specifically, instead of spawning a fixed number of concurrent
threads and managing a queue, your code will be simpler by using an Executor subclass from concurrent.futures (see
https://docs.python.org/3/library/concurrent.futures.html)

Remove the worker function, the queue management logic (including the poison
kill), and create something like this in your if __name__ == '__main__'
block:

import concurrent.futures as futures
urls = [url['url'] for url in ds.getcollection().find()]
with futures.ThreadPoolExecutor(max_workers=32) as executor:
    executor.map(process, urls)

Note the with statement implicitly calls executor.shutdown(wait=True), so
the block is essentially synchronous. And once the iterable is drained, the
executor manages clean up.

Functional

This pattern is inherently more functional, though I would not say it's "pure"
functional.  The map() method applies your function process to each of the
items in the associated iterable, spreading the load across available threads
(or processes) in the pool.

DEBUG duplication

To address the _DEBUG duplication issue (or generally any selective print() output), in similar situations I use a logger:

log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler(sys.stdout)

if _DEBUG:
    log.setLevel(logging.DEBUG)
else:
    log.setLevel(logging.INFO)

Then, that section becomes:

log.debug("Fetching Urls")
urls = getcollection().find()
log.debug("%d Urls Fetched" % urls.count())
log.debug("pulling urls to the queue")
q = queue.Queue(urls.count())
for url in urls:
    url = url['url']
    q.put(url)
log.debug("pulled urls to the queue")
log.debug("The size of the Queue is %d" % q.qsize())

With no leading if _DEBUG:. Note, though, that if you go with the executor, the queue goes away as well. Play with the levels that work for your needs.

Performance

Honestly, there is not a lot you'll be able to do here above what you are
already doing - your main bottleneck is going to be I/O. For 1m sites in 1
hour, you should be averaging close to 280 requests a second. Play around with
your concurrency (there is a tipping point where too many threads will actually
slow things down) - on an 8 core machine w/ 64 workers, I was only hitting about 100 sites in 1.4 seconds.

Additional notes:

Note that many sites won't return 200 for HEAD requests, so you might consider
a list of "acceptable" codes, which will likely include 301 and 302
You don't need the sleep() calls in the worker function.


Base adder, given base and two numbers of that base, it adds them

The limit of the maximum radix of 26 sounds odd, why not use the full alphabet of characters up to 10 digits, and 26 letters, giving a total of radix-36?

You have not included a reinventing-the-wheel tag, and thus I can suggest the following:

public static String add (String num1, String num2, int base) {
    if (base > 26) {
       // arbitrary limitation to 26... BigInt supports to 36.
    }
    BigInteger bione = new BigInteger(num1, base);
    BigInteger bitwo = new BigInteger(num2, base);
    return bione.add(bitwo).toString(base);
}

I believe that satisfies the review, optimization and best-practices request.


Project Euler 10: Summation of primes in Go

Algorithm : really important

What you want to to is to use the Sieve of Eratosthenes because you already know an upper bound for the biggest number you're going to consider. Getting all the primes smaller than 2 millions is going to be straightforward.  This will solve your process took too long issue.

Other things not as important

You could probably write the following function :

func CheckIfIsNewPrime(number uint64) bool {
    check_if_number_is_new_prime := false
    var remainder uint64 = 0

    for i := range primes {
        remainder = number % primes[i]
        if remainder == 0 {
            check_if_number_is_new_prime = false
            break
        } else {
            check_if_number_is_new_prime = true
        }
    }
    return check_if_number_is_new_prime
}

in a more concise way (no real impact on performance)

func CheckIfIsNewPrime(number uint64) bool {
    for i := range primes {
        if number % primes[i] == 0 {
            return false
        }
    }
    return true
}

I don't know anything about Go, but I guess

if CheckIfIsNewPrime(counter) == true {

could be written as

if CheckIfIsNewPrime(counter) {

As you go further in Project Euler, you'll see that most of the problem is to find the algorithm you want to use and not really to implement it.


Determine if a file is either in JSON or XML format

Well, if you only need to distinguish between JSON and XML formats I'd keep it simple. If the encoding of that string is known to you (or is ASCII or UTF), then looking at the very first char in the file should be enough. Your code looks pythonic to me, but I'd rather do it this way:

def parse_report_file(report_input_file):
    with open(report_input_file) as unknown_file:
        c = unknown_file.read(1)
        if c != '<':
            return 'Is JSON'
        return 'Is XML'

While it is legal for JSON data structures to begin with null, true, false you can avoid those situations if you already know a bit about your data structures.

If you also need to distinguish between JSON, XML and other random file, you should simply strip any whitespace before you look at the "first" char.


So I found a few improvements which solve my problem. First, I used a vector to represent the queue, and a rolling index to store the head of the queue:

type Queue = V.Vector Int
data RollingQ = RollingQ Queue Int

currentVal :: RollingQ -> Int
currentVal (RollingQ v i) = v V.! i

nextVal :: RollingQ -> RollingQ
nextVal (RollingQ v i)
    | i == V.length v = RollingQ v 0
    | otherwise = RollingQ v (i + 1)

This led me to realize that there might be a cycle in the computation: if the number of rides is bigger than the number of groups in the queue, the state of the queue loops. I used a Map to remember information about the computation to detect the loop and compute a shortcut to get the result almost immediately.


Your JS could need improvement in terms of indentation. Other than that, your app is pretty small for a full-blown review. However... we can make improvements.

In the long run, your app will be more than just one controller to display different parts of the site. Most of them will be consuming more or less the same data, just displayed a bit differently. You might want to consider using factories/services as data stores, and have controllers just pull them in as dependencies.

This also means your API calls will live there as well, freeing the controller to only be a means to expose data from the services/factories to the templates as well a communicate from template to services/factories.


Determine if an array of arrays of characters can be concatenated in order, into a substring of haystack

bug

You don't reset the offset when there is a mismatch, so "123 easy as b(" also returns True. Just add:

    else:
        offset = 0

optional parameter offset

The caller of the function should not care about the offset if he wants to check whether a combination is part of the string. I would change the method signature to def find_mutated_string2(combos, search, offset=0). Then your user doesn't need to worry about this

in

Python has the in statement.

Your code says

    for mutant in combos[offset]:
        if mutant == char:

but actually mean: if char in combos[offset]

Since in in a list traverses the list to look for a match, while set uses a lookup, defining the combos as sets helps here

combos = [{"@", "A", "a"}, {"8", "B", "b"}, {"(", "[", "c"}]

def find_mutated_string2(combos, search, offset=0):
    for i, char in enumerate(search):
        if char in combos[offset]:
            if len(combos) == (offset + 1):
                return True
            else:
                return find_mutated_string2(combos, search[i+1:], offset+1)
        else:
            offset = 0
    return False

match substring

You could write a helper function that takes a substring and checks whether this matches the combo's

def matches_combos(substring, combos):
    return len(substring) == len(combos) and all(
        char in combo for char, combo in zip(substring, combos)
    )

This can be easily tested:

test_cases = {
    "abc": True,
    "Ab[": True,
    "abd": False,
    "ab": False,
    "abcd": False,
}
for substring, answer in test_cases.items():
    result = matches_combos(substring, combos)
    assert result == answer

recursion

If your string is long, you will run into the recursion limit.

for i in range(10000):
    try:
        _ = find_mutated_string2(combos, "a"*i)
    except RecursionError:
        print(f"fails for string length: {i}")
        break

fails for string length: 5921

for a recursionlimit of 3000

You can easily rewrite this proble iteratively

def find_mutated_string3(combos, search):
    if len(search) < len(combos):
        return False
    for i in range(len(search) - 2):
        substring = search[i : i + len(combos)]
        if matches_combos(substring, combos):
            return True

or using any

def find_mutated_string4(combos, search):
    if len(search) < len(combos):
        return False
    return any(
        matches_combos(search[i : i + len(combos)], combos)
        for i in range(len(search) - 2)
    )


setup.py with data_files and __author__ parsing

Your use of lambdas and partials makes no sense, and is really hard to understand. If you need them to be functions then just make them functions. Or even better, just write the code out. Some of them are just one-off functions and don't add any value, and should be inlined. The others are just ridiculously hard to read, and should be defined as normal functions.

First let's look at how you get the values from the file. I'm pretty sure I know what the general idea of your algorithm is.

for line in source file
    if the line has one of the values we want
        parse the line, and save the value

This is much easier to implement like this

def extract_values(source_file, desired_vars):
    with open(source_file) as f:
        for line in f:
            if any(line.startswith(var) for var in desired_vars):
                parsed = ast.parse(line).body[0]
                yield parsed.targets[0].id, parsed.value.s

filename = path.join(package_name, '__init__.py')
metadata_names = '__author__', '__version__'
values = dict(extract_values(filename, metadata_names))

Using all of your lambdas and iterables doesn't seem to give much value - I assume you were doing them because this is potentially a big file and you don't want it all in memory? If so don't worry about it - doing the for line in f automatically does buffered-IO and memory management.  Then we can use a generator and construct a dict from it.  This is much more readable, and is unlikely to make much of a difference in performance. More importantly, however, is that unless you're doing something ridiculous in setup.py it shouldn't really matter.

Next let's look at how you get the data files.  I cannot figure out why you did it this way. This line:

data_files=[
    (_data_install_dir(), map(_data_join, listdir(_data_join())))
]

is basically nonsensical.  You map _data_join onto each file inside of calling _data_join()?  What we really have here are two constants - some data install directory, and some data file directory. We want to list all of the files in the data file directory, and pair them with the data install directory.  We can just do something like this

data_files = data_install_folder, [path.join(data_file_source, filename) for filename in listdir(data_file_source)]

Putting this all together, we have something like this

from setuptools import setup, find_packages
import os
import ast

from compatibility import filter, map
from pip import __file__ as pip_loc

def extract_values(source_file, desired_vars):
    with open(source_file) as f:
        for line in f:
            if any(line.startswith(var) for var in desired_vars):
                parsed = ast.parse(line).body[0]
                yield parsed.targets[0].id, parsed.value.s

if __name__ == '__main__':
    package_name = 'foooooo'

    filename = os.path.join(package_name, '__init__.py')
    metadata_names = '__author__', '__version__'
    values = dict(extract_values(filename, metadata_names))

    data_file_source = os.path.join(os.path.dirname(__file__), package_name)
    data_install_folder = os.path.join(os.path.dirname(path.dirname(pip_loc)), package_name)

    all_data_files = os.path.join(data_file_source, filename) for filename in listdir(data_file_source)
    data_files = [(data_install_folder, all_data_files)]

    setup(name=package_name,
        author=values['__author__'],
        version=values['__version__'],
        test_suite=package_name + '.tests',
        packages=find_packages(),
        package_dir={package_name: package_name},
        data_files=data_files
    )

As a quick note, if you want to get things working for both Python 2 and Python 3, imap and ifilter don't exist in Python 3. I usually like to make a file like compatibility.py that I put things like that into, then just import from that.

try:
    from itertools import imap as map, ifilter as filter
except ImportError:
    pass


Design a Tips class that calculates the gratuity on a restaurant meal

Inconsistant layout:

#include<iostream>   // No space
#include <string>    // Space

Be consistent in your code. I prefer the version with the space.

Using namespace std

Arrrrr. Don't do that. see: Why is “using namespace std;” considered bad practice?.

Definately never do it in a header file. You are pulliting the namesapce for anybody that includes your code (which can change behavior) and break other peoples code. Don't do it in source files because of the reasons you read in the linked article.

Default argument

      Tips()
      {
            taxRate = .65;
            cout << "Tax rate is "<<taxRate<<endl;
      }

      Tips(double tax)
      {
                 taxRate = tax;
                 cout << "Tax rate is"<<taxRate<<endl;
      }

When you see code like this you can usually replace it with a single constructor that has a parameter with a default argument (as they are basically doing the same thing).

      Tips(double tax = 0.065) // Corrected you constant.
      {
           taxRate = tax;
           cout << "Tax rate is"<<taxRate<<endl;
      }

Be consistent with spacing (white space is your friend)

           cout << "Tax rate is"<<taxRate<<endl;
                ///            ^^^^^^  ^^^^^        Looking very tight here.

           cout << "Meal cost + tip rate is "<<tip.computeTip(100,20)<<endl;
                ////                        ^^^^^                   ^^^^

Prefer '\n' over std::endl

std::end forces a flush of the stream. This is never what you actually want. The automated flushing of the stream will work much better than manual flushing.

Prefer to use the initializer list.

      Tips(double tax = 0.065) // Corrected you constant.
           :   taxRate(tax)
      {
           cout << "Tax rate is"<< taxRate << endl;
      }

Arithmetic issue

If the billAmount is mealCost * (1 + taxRate) then this is not the formula to calculate meal cost.

            double mealCost = billAmount - billAmount*(taxRate);


I like how you have declared the Fizz and Buzz 'constants'. It makes the code more readable.

The comments are useful too, though, for consistency, the second comment should be changed from:

BTW Froot will run 1 through 100

to

BTW Froot runs 1 through 100

The idea of generating Froot from Frootz is also good, because it reduces the computations later in the code.

I only wish you used a better name than Frootz because it conflicts with Froot. The similarity is.... uncanny.

I would suggest the name Loopz:

I HAS A Loopz ITZ SUM OF Frootz AN 1

This will reduce the ambiguity, and improve the readability and maintainability.

Finally, it is good that you put the Fizz modulo check before the Buzz check because that improves performance. Many people put buzz first, but that means the modulo-5 check happens, and that fails more often than the modulo-3 check, so people who do the Buzz-loop first tend to do about 20% more conditional checks.

All in all, for a first go, I am very impressed with your result. I can't wait until you implement a fim++ interpreter in lolcode. Till then!


Try the following:

function divisible_times($number, $divider) {
  $arr[$number.':'.$divider]['divisions_no'] = floor($number / $divider);
  $arr[$number.':'.$divider]['remainder'] = $number % $divider;
  return $arr;
}