Approximating π via Monte Carlo simulation

About those arrows

  I’m interested in a general review, but I’m especially curious about my use of arrows: is there a better way to write lengthRatio?

Compare the following two lines. Both do the same, but which one would you rather see if you need to change your code drunk in three months, with only 5% battery left?

lengthRatio = curry (unsplit (/) <<< both genericLength)

lengthRatio xs ys = genericLength xs / genericLength ys

Also, which one has which type, and which one is more general?

Arrows are great if you want to abstract functions. But throughout your small script, you're still just working with (->), not any other instance of Arrow. For a small script like this, Arrow is too much. For example the pointwise definition above is actually a character shorter than the pointfree one. Sure, the pointfree one is clever, but it's also very beginner-unfriendly.

About randomness

randomPoints introduces a dependency between your point coordinates \$x\$ and \$y\$, since both draw from the same sequence. This usually leads to points on hyperplanes (see disadvantages of LCG and spectral test). Your friends variant doesn't have this immediate problem:

randomTuples :: Int -> IO [(Float, Float)]
randomTuples n = do
  seed1 <- newStdGen
  seed2 <- newStdGen
  let xs = randoms seed1 :: [Float] -- two different
      ys = randoms seed2 :: [Float] -- generators being used
  return $ take n $ zipWith (,) xs ys

However, since newStdGen is merely a split, it's more or less hiding the dependency at another place. Still, it's something to keep in mind, if you don't want to end up with something like this.

But how would you check this? Well, you would run tests, over and over. Here's the second design critique on randomPoints, it doesn't take a RandomGen. Truth be told, if I say that Arrow is too much for a small script, then

randomPoints :: RandomGen g => g -> [Point Float]

is too much either.

Also, if you know you're going to generate Points, a newtype Point a together with

instance Random a => Random (Point a) where

is feasible and doesn't introduce a potential error via chunk2. Keep possible problems with Random in mind, though.

About names

The function isInUnitCircle lies. It's not testing whether the point \$(x,y)\$ lies in the circle with radius \$r = 1\$ with center in the origin, e.g.
$$
\sqrt{x^2 + y^2} \le 1^2 \Leftrightarrow x^2 + y^2 \le 1
$$
but in the circle with diameter \$d = 2r = 1\$ with center in \$(0.5, 0.5)\$. In the following picture, the green region is where you generate your random values. In the left one, you see the regular unit circle, in the right one, you see the circle size you're actually testing (after shifting your values from the green square into the red one):

Therefore, you're not calculating the "usual" fourth of a circle, but instead a circle with a fourth of the original size (\$\pi(\frac{1}{2})^2 = \frac{\pi}{4}\$)). Luckily, it doesn't matter for the convergence.

A real test that checks whether a point is in the unit circle is tremendously easier:

isInUnitCircle :: (Num a, Ord a) => Point a -> Bool
isInUnitCircle (x, y) = x ^ 2 + y ^ 2 <= 1

About optimization

Last, but not least, there's an issue with approximatePi, or rather the use of lengthRatio on the same list twice. Actually, taking the length of the list again is a litle bit strange, since you know how large the sample is:

numPoints <- read <$> getLine                -- sample size
points    <- take numPoints <$> randomPoints
print $ approximatePi points                 -- sample size still known (?)

But let's say that you don't actually know how many points you have. Let's assume that someone wants to check a many points. Suddenly, the memory usage of your program explodes:

$ echo 10000000 | ./CalcPi +RTS -s
How many points do you want to generate to approximate π?
3.141744
  33,724,505,920 bytes allocated in the heap
   5,288,250,096 bytes copied during GC
   1,319,621,976 bytes maximum residency (17 sample(s))
       5,554,344 bytes maximum slop
            2587 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0     63626 colls,     0 par    1.606s   3.155s     0.0000s    0.0006s
  Gen  1        17 colls,     0 par    2.732s   3.373s     0.1984s    1.2720s

  INIT    time    0.000s  (  0.000s elapsed)
  MUT     time   17.158s  ( 15.542s elapsed)
  GC      time    4.337s  (  6.528s elapsed)
  EXIT    time    0.019s  (  0.166s elapsed)
  Total   time   21.514s  ( 22.236s elapsed)

  %GC     time      20.2%  (29.4% elapsed)

  Alloc rate    1,965,530,983 bytes per MUT second

  Productivity  79.8% of total user, 77.2% of total elapsed

Even though randoms generates a lazy list, approximatePi needs to hold onto it completely due to lengthRatio. A classic space leak. The altnerative version of lengthRatio won't save you from that. Instead, provide a function to check the ratio of filtered elements:

-- Rational from Data.Ratio
filterRatio :: (a -> Bool) -> [a] -> Rational
filterRatio p xs = -- exercise

That way, you can define a version of approximatePi that works for large lists:

approximatePi :: [Points Float] -> Double
approximatePi points = circleRatio * 4
  where
    circleRatio = fromRational $ filterRatio isInUnitCircle points

$ echo 10000000 | ./GenPIRatio +RTS -s
How many points do you want to generate to approximate π?
3.1421592
  24,445,866,792 bytes allocated in the heap
      15,555,552 bytes copied during GC
          77,896 bytes maximum residency (2 sample(s))
          21,224 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0     46874 colls,     0 par    0.012s   0.113s     0.0000s    0.0001s
  Gen  1         2 colls,     0 par    0.000s   0.000s     0.0001s    0.0001s

  INIT    time    0.000s  (  0.000s elapsed)
  MUT     time   10.809s  ( 10.746s elapsed)
  GC      time    0.012s  (  0.113s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time   10.821s  ( 10.859s elapsed)

  %GC     time       0.1%  (1.0% elapsed)

  Alloc rate    2,261,657,279 bytes per MUT second

  Productivity  99.9% of total user, 99.5% of total elapsed

Summary

Food for thought:

Use the right level of abstraction for your problem. Arrow is an overkill for such a small script, but alright for learning.
Try to decrease the amount of IO wherever possible, but again, that might be too abstract for a small script.

Bad:

Don't lie, give things the right name.
Don't overcomplicate, keep pointfree to a sane minimum.
Major space leak in approximatePi. Read the linked section of RWH and try to define filterRatio or a similar function.

Good:

Type signatures! Yay!
Explicit imports!
Type synonym instead of (a, a) everywhere!

So beside the slight arrow-overkill, well done.


Controller method to manage SMS subscriptions

What I noticed is that there are very few differences between what's happening within the sections that the 'dancers', 'staff', and 'volunteer' messages take you through. Because the only thing that really changed between the three was the word within the message itself, I decided to combine them and use the message variable.

def process_message(message, subscriber)
  if standard_groups.include?(message)
    subscriber.update(subscribed: true)
    subscriber.add_to_group(message)

    "You have been subscribed to the #{message.capitalize} list"
  elsif message == 'tulip' || message == 'stem'
    subscriber.update(subscribed: message == 'tulip')
    subscriber.add_to_group('visitor')

    return 'You are now subscribed for updates.' if subscriber.subscribed
    "You have unsubscribed from notifications. Test 'TULIP' to start receieving updates again"
  else
    "Sorry, we don't recognize that command. Available commands are: 'TULIP' or 'STEM'."
  end
end

def standard_groups
  %w(dancers staff volunteer)
end

I was able to remove the output variable by leaving the string that you want to return as the last line that will run within the method. The exception is the line 'returned' if subscriber.subscribed comes back true.

I moved the common messages to an array so that you can easily add more in the future.

I considered separating the conditional for 'tulip' and 'stem' into 2 individual conditionals, but to me it made more sense to keep the "exceptions" together, especially since they share the 'visitor' group. For increased legibility, you may choose to separate them.


I profiled your code and calling your render function takes 3.1-4.2 ms on my machine (i7 2.1 ghz running chrome/linux). I managed to cut that to only 0.6 ms by removing what is AFAIK the performance killer in this type of drawings using the canvas API. Check it out for yourself http://codepen.io/anon/pen/QbwQmo

The performance killer that I'm talking about is that you're drawing a million separate paths instead of batching them all in a single .beginPath ... .stroke. The catch is however that you can't have multiple colors (alpha levels) in the same path - so changing the color for every segment is not possible anymore. You could instead bucketize the paths - choose 10 shades of grey and add segments to these buckets; then call .stroke for each bucket (that'll amount to max 10 calls - way better than (50*50 which is what you can have)). The only way to overcome this limitation of the canvas API is to not use it in the first place :). Instead use a WebGL renderer (pixi.js, goo.js, three.js).

There's another thing which you can do to increase performance especially if you'll want more than 50 points. Right now you're checking every point against every other point. The number of calls to distance (not the best name btw) grows quadratically with the number of points. You can reduce the number of checks by discarding points that are too far - and you achieve this by splitting the whole space ([0...600] x [0...600]) into smaller buckets of 100 x 100 or something. You'd have to update the buckets every frame such that they contain the points that lie within their bounds. The upside is that you only need to check points in nearby buckets and not in the whole space.

(Disclaimer: I am a dev of goo.js)


Parsing Websites and transferring Data between Objects

For now, I will avoid commenting too much on - (NSArray*) getHourDataForRow:(TFHppleElement*)row Meal:(NSString*)meal as I think the real answer here is to look into NSXMLParser and see if that will work for you.  Other than that, for now I'll simply comment that your spacing is inconsistent and you should work in cleaning that up to make the code more readable.

I will, however, comment on dateFromString:

- (NSDate*) dateFromString:(NSString*)time {

    if ([time isEqualToString:@"CLOSED"])
        return nil;

        NSArray *digits = [time componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];

        int hour = [digits[0] intValue];
        hour+= (([time rangeOfString:@"pm"].location == NSNotFound) ? 0:12) ; //add 12 for pm
        int minutes = [digits[1] intValue];
        //format nsdate
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit ) fromDate:[NSDate date]];
        [components setHour:hour];
        [components setMinute:minutes];
        return [calendar dateFromComponents:components];

}

First of all, you left brackets off of your if statement.  This in combination with the awkward indentation leaves the code quite confusing.  Despite being optional, curly braces should never be omitted.

The rest of the method however.... can be completely replaced.  There's a class called NSDateFormatter which is made specifically for converting NSDate objects to NSString objects and vice versa.

First, we need this link.  This lets us know what our date format string should look like.  We have hours without a leading zero and in 12-hour format, minutes, we have minutes, and we have an am/pm symbol.

So our format string will look like this:

@"h:mma"

Our AM symbol is @"am" and our PM symbol is @"pm".  Now we have all the information we need to create our NSDateFormatter object:

- (NSDate*) dateFromString:(NSString*)time {
    if ([time isEqualToString:@"CLOSED"]) {
        return nil;
    } else {
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"h:mma"];
        [df setAMSymbol:@"am"];
        [df setPMSymbol:@"pm"];

        return [df dateFromString:time];
    }
}


Functional, but not recursive, tree traversal

Does this help?  In your walk_iter, instead of using pop, grab the first element of the stack. Then do something like this ...

if first_element_has_sub_elements:
    new_stack = stack[0][1]
    new_stack.extend(stack[1:])
    stack = new_stack[:]
else:
    stack = stack[1:]

This was my experiment, in case it's helpful ...

TREE = [
 ("L1A", [("L1A2A",),
          ("L1A2B", [("L1A2B3A", )])]),
 ("L1B", [("L1B2A", [("L1B2A3A", )])]),
 ("L1C",),
 ("L1D", [("L1D2A",),
          ("L1D2B", [("L1D2B3A", ),
                     ("L1D2B3B",)])]),
 ]

EXPECTED = ["L1A", "L1A2A", "L1A2B", "L1A2B3A",
            "L1B", "L1B2A", "L1B2A3A", "L1C",
            "L1D", "L1D2A", "L1D2B", "L1D2B3A", "L1D2B3B"]

def traverse_tree(TREE):
    chopped_tree = TREE[:]
    results = []
    while chopped_tree:
        results.append(chopped_tree[0][0])
        if len(chopped_tree[0]) > 1:
            new_tree = chopped_tree[0][1]
            new_tree.extend(chopped_tree[1:])
            chopped_tree = new_tree[:]
        else:
            chopped_tree = chopped_tree[1:]

    return results

if __name__ == "__main__":
    results = traverse_tree(TREE)
    if results == EXPECTED:
        print "OK"
    else:
        print "MISMATCH"
    print "Expected: "
    print EXPECTED
    print "Results: "
    print results


Returning a collection inside of an IEnumerable method

There is no 0 and 1 answer

X likes to execute an IEnumerable as soon as possible, hence why X is doing it inside of the method.

Whereas

Y is thinking that if you wait until the object is actually needed, using differed execution, you’re eliminating wasted objects in the memory.

They are both wrong. The answer isn't digital, this is, there is no 0 or 1 answer. It depends. Sometimes you must execute a collection and return a non-IEnumerable.
Materialize when working with databases
Such a case would be querying a database. In this scenario you'd open a database connection (or create a context if it's some ORM) and dispose it at the end. If you don't execute it with ToList or ToArray etc. you won't be able to do it later. The runtime would wrap your enumerator with an anonymous type containing the context but when the execution leaves the method, the context gets disposed and it'll throw an excepiton the moment you try to get the data. In this situation you should return a non-IEnumerable type.
The reason the return type shouldn't be an IEnumerable in this case is that IEnumerable tells me that the return type is lazy so if I wanted to use it multiple times I'd call ToList myslef (again) to get the result which would unnecessrily enumerate the collection again.
So, the bottom line is: if you don't have to materialize the result (because you won't be able to get it later when the service/provider is disposed etc), don't do it but be consistent with the API (return types).

When the result value it's materialized I expect you to communicate this fact clearly by using ICollection, IList or anything else but IEnumerable.

Materialize for easier debugging when calling resources
As far as your code is concerned you call a web-service there

RestHelper.PostJsonAsync(..)

So you should ask yourself: Is it ok to be done multiple times if someone else uses Any and then starts enumerating it again or is better to prevent such situations (for whatever reason)?
I would use IList here for one more reason: it's quite difficult to debug lazy code that is calling web-services, databases or other resources. When something goes wrong here you'll be having a lot of fun.

Consider materialized parameters
The same priciples apply to parameters. In your example you execute skus multiple times: with Any and with the foreach loop.
Here, I'd requested an ICollection or an IList to tell the caller: Look out! I'll be using your collection more then once (so you might consider materializing it for better performance before givit it to me).


Find the perfect numbers within the range of 1 and a chosen number

MS Specific

MS specific don't need it here

#include "stdafx.h"

Namespace std

Never do this.

using namespace std;

I know every book you read does this. This is because they are paying for the ink. Its actually very bad style and will cause a huge amount of problems for any program longer than ten lines or for code that lives longer than a year. So it is bad habit you should get out of the habit of doing.

The reason they picked std rather than standard so it is easy to type and use as a prefix. Its not that much harder to type than the normal object or type.

std::cout << "Testing\n"; // Not that hard see.

For details about the problem see: Why is “using namespace std;” considered bad practice?

Comments

Don't add us-less comments.

/* Main program*/
int main()
{
    // Declare variable(s)

Comments can do more harm than good when used incorrectly. This is because over time comments fall out of line with the code unless very explicitly maintained. Because the compiler does not check the comments for accuracy this happens a lot.

Thus a maintainer who sees a comment that does not agree with the code then has to try and work out which is wrong. The code or the comment and then has to fix it.

You should restrict your comments to "WHY" comments. Why is the code working like this. "WHY" we need to do something. The code itself should explain "HOW" (as long as you use good variable and function names).

See: What are examples of comments that tell you why instead of how or what?

USless comment: (I can see what it does by reading the code)

    // Display the information
    cout << "\n\nThe perfect numbers between 1 and " << bound << " are: " << endl;

Don't like this comment.

/*
* Function: isPerfect
* -------------------
* Returns the sum of the number(s) within the testing range
*/

In this case the comment says one thing. The name of the function says something else. It does not return the sum it returns bool. Because the function is named  perfectly you don't really need to say anything (the function name is enough).

bool isPerfect(int n)

Don't particularly like the comment.

/*
* Function: int sumOfProperDivisors
* ---------------------------------
* Returns the sum of a number's divisors
*/

It does not tell me anything that the name of the function already tells me.

Validate User Input

You don't validate user input.

    cin >> bound;

Input from many sources can be trusted. Input from a human can not. Validate their input and anticipate that they will either be stupid or malicious in trying to crash your program.

std::endl and flushing

Prefer to use "\n" instead of std::endl.

     cout << "\n\nThe perfect numbers between 1 and " << bound << " are: " << endl;

The reason is that std::endl just puts "\n" then flushes the stream. Stream flushing can make the code very inefficient if done incorrectly. Also the streams flush themselves when they need to without your help.

see: C++: “std::endl” vs “\n”

Prefer Prefix increment

Prefer prefix increment ++i over suffix increment i++.

    for (int i = 1; i <= bound; i++)

Though in this case it does not explicitly matter. If sombody came along and changed the type of you loop (to say BigInt a type that supports 128 bit integers) then it may make a difference. Also you want them to be able to change the type without having to change any code and still get the best performance.

The reason that i++ can be less efficient for types is because of the default way of implementing the operator.

see: Questions about operator overloading

The default method means that the suffix version creates an extra copy of the object that is not required by the prefix version.

System Pause Bad

Don't do this.

    system("PAUSE");

Use a standard happy way of apuing the the code.

cin.ignore(255, '\n'); // ingore input to the end of line (as you did not do that in the previous read).
std::cout << "Hit Enter to continue\n";
cin.get();             // Wait for user input to be flushed.

Return in Main

The function main() is special. If you don't specify a return value the compiler will generate one for you return 0. It is the only function this will happen in.

As a result we use having no return as an indicator to the maintainer that there is no way for this application to fail. If you have an explicit return 0; at the end then I am looking through your code to find a place where you return an error code.

    return 0;


The Question

Could anyone advise a better way to create [cookies]?

Like your code already uses, setcookie() is the traditional way of setting cookies. And yes, since the cookie data is sent in a header, there must be a response, otherwise the browser/user won't really be able to receive the cookie.
General Feedback
Passing instance/member variables to method
Why pass $this->timeout to makeCurlRequest from the checkVote method? If the method was called outside this class (and the scope of the method changed to  protected for sub-classes or public for anywhere else in the code) then it might make sense to accept that parameter.

$result = $this->makeCurlRequest($urlRequest, $this->requestTimeout);

Since that method is not static, it could simply refer to $this->requestTimeout instead of accepting the parameter for it.
Misleading Method Name
The method makeCurlRequest appears to check if the curl function curl_version() exists and then either makes a cURL request or utilizes file_get_contents(). Thus the method might not always make a cURL request and a better name might be makeRequest. The code in the block when the curl_version() function does exist could be moved to a new method called makeCurlRequest.
return from makeCurlRequest()
The method makeCurlRequest has two return statements. One is in the else block, and the other is at the end of the method - i.e. return $requestData;. That variable,$requestData, appears to be the response from the API when the curl_version() function exists (and thus the cURL request is made), yet in the else block, $requestData is assigned a resource from stream_context_create(). While this code likely functions correctly, it could be confusing to a teammate who had to update it. A more appropriate name for the return value from the call to stream_context_create() might be something like $streamContext. Then it might be simpler to either assign the return value from the call to file_get_contents() to $requestData and utilize the return of that variable at the end of the method, or when making the curl request, return the response at the end of that block.
Redundant return false
In isVoteCookieSet() There is an else block to the nested if statement that contains return false;. That could be removed, since the last line of the method does the same thing.
Constants for Response codes
It would be wise to define (class) constants for the response codes, like the ones below. While there currently appears to only be one place in your code where that value appears, there may arise a need to have it appear in other logic and thus it would be useful to reuse the constant(s). Then if the value would ever need to be updated (e.g. if the API ever changes) then it can be updated in your code in one spot.
const RESPONSE_VOTE_PLACED_IN_PAST_24_HOURS = 3;
const RESPONSE_VOTE_NOT_PLACED_IN_PAST_24_HOURS = 2;

That way, the code lines like below:

if ($result == 3) {

Can be updated like this:
if ($result == self::RESPONSE_VOTE_PLACED_IN_PAST_24_HOURS) {

Which would hopefully allow somebody else reading your code to have a better idea of what that logic means. Though if those names are too long, feel free to shorten them.


A clock and a fortune: a full screen clock with random quotes in Tcl/Tk

Nice code. I only see a couple of items

add package require Tk to be explicit you need tk
use uplevel #0 $body instead of eval


Possible combinations of bills that sum to the given amount

You could do some dynamic programming solution.

The basic idea of it in this situation would be you keep track of what you can get with just the 1 dollar bill, then figure out where you can reach with the 2 dollar bill, then the 5 dollar bill.  (For the sake of example, I'll use a 7 dollar bill as well as the one's you have in you example)

So, for example you would start with an array of size 18. Because you can reach 0 dollars, you would have

1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

then with the 1 dollar bill you can reach 0 dollars and 1 dollar

1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

then with the 2 dollar bill and the 1 dollar bill you can reach 0,1,2,or 3 dollars

1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

then with the 5,2, and 1 dollar bill you can reach 0,1,2,3,5,6,7,or 8 dollars

1,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0

then, with the 7 dollar bill: you can reach 7 and 8 in two ways

1,1,1,1,0,1,1,2,2,1,1,0,1,1,1,1,0,0,0

10 dollar bill

1,1,1,1,0,1,1,2,2,1,2,1,2,2,1,2,1,2,2

So, there are two ways to reach 18


Seq[Either[A, B]] => Either[A, Seq[B]] Function

A few points:

Your implementation reverses the order of elements if it succeeds (i.e. if they're all rights). I'm assuming this isn't intentional?
You're taking a list but returning a Seq. This may be what you want, but I find it a little confusing.
The inner curly brackets are unnecessary (and I personally find them kind of noisy).
I'd strongly suggest not shadowing the external acc with the accumulator function argument.

So I'd probably write it like this:

val xs: List[Either[String, Int]] = List(Right(1), Right(55))

xs.foldRight(Right(Nil): Either[String, List[Int]]) { (elem, acc) =>
  acc.right.flatMap(list => elem.right.map(_ :: list))
}

Or:

xs.foldRight(Right(Nil): Either[String, List[Int]]) { (elem, acc) =>
  for {
    t <- acc.right
    h <- elem.right
  } yield h :: t
}

But that's only if I couldn't use cats or Scalaz, both of which provide this operation as sequenceU:

scala> import cats._, cats.syntax.traverse._, cats.std.all._
import cats._
import cats.syntax.traverse._
import cats.std.all._

scala> val xs: List[Either[String, Int]] = List(Right(1), Right(55))
xs: List[Either[String,Int]] = List(Right(1), Right(55))

scala> xs.sequenceU
res0: scala.util.Either[String,List[Int]] = Right(List(1, 55))

Which is much nicer.


Login/registration part of an Android application

Security

You are completely open to SQL injection (in your login as well as registration page). You should always use prepared statements.

Also, md5 is not good enough, use bcrypt.

Misc

class files should not have side effects as it makes it hard to reuse them. Just create a file called user.php and place the class - and nothing else - inside it.


Method for downloading a PDF from a website in Android

Android's method naming convention follows that of Java, so your method name DownloadPDF() will probably be better written as downloadPDF() (or maybe even downloadPdf()).

Your null check for uri comes in after you have toggled your UI elements, wouldn't that mean the state is possibly inconsistent if the method really received a null argument, and then the UL elements already indicated the code is downloading something? You may want to return from your method first in this case...

public void downloadPdf(URL uri) {
    if (uri == null) {
        return;
    }
    // ...
}

DownloadManager.Request methods return the object itself, so you may also consider daisy-chaining the setters together:

request.setTitle(pdf + ".pdf")
    .setDescription("Website: " + pdf)
    .setMimeType("application/pdf");


Do you think this design pattern is good for game portal content management system

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

List<GamePlatform> gamePlatforms;

I'd consider using BigDecimal instead of int price. It can store numbers like $1.99.
I'd rename PCPlatform to PcPlatform. From Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions:

  While uppercase may be more common,
  a strong argument can made in favor of capitalizing only the first
  letter: even if multiple acronyms occur back-to-back, you can still
  tell where one word starts and the next word ends.
  Which class name would you rather see, HTTPURL or HttpUrl?

The PlatformType enum seems as a duplication here and if I'm right it's purpose is to use it in switch-case statements. Consider polymorphism here. I'd put a public abstract String getPlatformName() method in the GamePlatform class and remove PlatformType completely. Two might be useful reading:

Refactoring: Improving the Design of Existing Code by Martin Fowler: Replacing the Conditional Logic on Price Code with Polymorphism
Replace Conditional with Polymorphism

Constructor parameters should be validated. Does it make sense to create a GamePlatform with null or empty string name? If not, check it and throw a NullPointerException or an IllegalArgumentException. (Effective Java, Second Edition, Item 38: Check parameters for validity)


Shell Sort Comparisons/Exchanges Counter

Your counting code seems correct.
comparison increments on each compare operation,
exchanges increments only on exchange.

On reversed array of 2000 elements I have got: comparison = 26416 and exchanges = 10400

\$log_{2000} {26416} \approx 1.34\$
So you have \$O(n^{1.34})\$ complexity.
Which is between \$O(n^{3/2}) = O(n^{1.5})\$ and \$O(n^{5/4}) = O(n^{1.25})\$
So according to wiki it's okay for usual gap sequence.
exchanges = 10400 is less then average move count \$0.41N\ln N (\ln \ln N + 1/6)\$ which in case of N = 2000 is approximately 13500, but it depends on gap sequence. E.g if you start with gap = N / 8 it will be equal to 14400.


Finding an increasing sequence from a given array in a time-efficient manner in Python

I have done this challange before and I quite liked it, now let's dive in teh codez...

Review of your code:

First of all those 2 while loops look kind of silly, and that is what is giving you your TLE's, if you wanted to improve the timing on your code, I would start there.

This should be possible with a 1 loop, now when for instance you look at the last test... one of the last elements needs to be changed. You change it, and it works... but then you loop through the entire array again i = 0 means we start checking from beginning which is not needed. And after that you check the array yet again but this time delete another part and loop through it again! After your second loop finishes you check the outcome and that is a little too late.

I would use 1 loop, to check where the array is not strictly
increasing, afterwards remove at 2 different possitions (with list
comprehension) and check if those are strictly increasing.
Or don't start at position 0 if you found a not increasing bit

Some other PEP8 improvements

Missing whitespace around operator i=0 should be i = 0
if var == False: could be rewritten as if not var:
if var == True and var2 == True: could be rewritten as if var and var2:

A better way of handling this, I explain below

Alternative:

Let's break down the problem statement:

  Given a sequence of integers as an array, we have to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Which means our algorithm should be doing 2 things:

Checking if a list is increasing sequence
Removing item in list and check again

Ok first make a function to check if a list is in a sequence and if not return the first element where it is not strictly increasing

def check_increasing(seq):
    # This will check if it is increasing:
    # If it is return -1 else return the element at which is it not increasing
    for i in range(len(seq)-1):
        if seq[i] >= seq[i+1]:
            return i
    return -1

Well this is part 1 of the problem statement, Part 2 becomes simple if we re-use this function.

def almostIncreasingSequence(sequence):
    check = check_increasing(sequence)
    # List is increasing
    if check == -1:
        return True

We need to remove at most one element from the list, so if it is already strictly increasing we can return true, since no element has to be removed

If it is not we will continou, what are the possibilites from here?

If we delete earlier element, it becomes sctrictly increasing
If we delete later element, it becomes strictly increasing
If both are untrue,  we now that more than 1 element must be changed to form a strictly increasing sequence

Which in code translates to:

# Check if removing an item will make a strictly increasing list
if check_increasing(sequence[check-1:check] + sequence[check+1:]) == -1 or
   check_increasing(sequence[check:check+1] + sequence[check+2:]) == -1:
    return True
# If not return False, since more than 1 element needs to be removed
return False

Making our final code like this

def check_increasing(seq):
    # This will check if it is increasing:
    # If it is return -1 else return the element at which is it not increasing
    for i in range(len(seq)-1):
        if seq[i] >= seq[i+1]:
            return i
    return -1

def almostIncreasingSequence(sequence):
    check = check_increasing(sequence)
    # List is increasing
    if check == -1:
        return True
    # Check if removing an item will make a strictly increasing list
    if check_increasing(sequence[check-1:check] + sequence[check+1:]) == -1 or check_increasing(sequence[check:check+1] + sequence[check+2:]) == -1:
        return True
    # If not return False, since more than 1 element needs to be removed
    return False

Edit

Sorry but that test keeps breaking my IDLE,
But here proof... no TLE on CodeFights:


Is there still a way to upload a malicious file?

I think not, due to these elements:

The check of $image['type'] against an array of various image/* mime types prevents uploading a script instead of an image
The hashing of the filename with makeHash prevents uploading a script with a malicious path to get the file placed somewhere unintended
The check of $image['size'] against a defined maximum prevents uploading an oversized file

  What is your opinion of this code?

Instead of this:

    if ($in == '')
    {
        return false;
    }

It would be better to add a default statement in the switch above it:

    switch ($image['type'])
    {
        // ...
        case 'image/wbmp':
            $in = 'imagecreatefromwbmp';
            break;
        default:
            return false;
    }

This seems pointless to me:

    if ($fileName == '')
    {
        return false;
    }

It seems to me that $fileName will always be set.


Finding the most common DNA patterns of some given length

You can optimize a bit by pre-calculating s.length() - k

for (int i = 0, max = s.length() - k; i < max; i++) {
    ...
}

Furthermore, you can cut a bit of execution time by replacing the auto boxing and unboxing you do by using a mutable value class, something like this:

private static class MutableInt {
    public int value;

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

public static void mostCommonKmer3(String s, int k) {
    HashMap<String, MutableInt> m = new HashMap<>();
    int l = 0;
    MutableInt g;
    String n = "", ss;
    for (int i = 0, max = s.length() - k; i < max; i++) {
        ss = s.substring(i, i+k);

        // note: computeIfAbsent over getOrDefault in this case, so that
        // creation will only take place when necessary
        g = m.computeIfAbsent(ss, key -> new MutableInt(1));
        g.value++;
        if (l < g.value) {
            l = g.value;
            n = ss;
        }
    }
    //System.out.println("Most Frequent " + k + "-mer = " + n);
    //System.out.println("frequency = " + l);
}

Raw execution time for 1000 repetitions (with proper ramp-up) using 100000 chars and k = 150 went from 3308 ms for the original code to 3190 using both changes on my machine.

And as you are on codereview, one additional remark: longer variable names (longest, subsequence, n?) do not hurt execution time, but have the potential to make the code more readable.... ;-)


Macros
Most of your code is in a macro. This makes it harder to write, read and debug.
Why not place the logic in normal functions and only use macros to pass __FILE__ and __LINE__?
That is until you can switch to C++20 which provides std::source_location
Naming
Why is the mutex called stream?


I would recommend making a main game loop. Running a loop in a constructor breaks the fundamental contract of a constructor: to construct something. This change will also allow you to easily restart the game and keep track of score if you wish. With that said, adding a StartGame, RestartGame and EndGame functionality may help organize things.

I tend to shy away from enums. If I find myself needing an enum, I always end up realizing I actually want a class. This follows the S in SOLID: single responsibility.

There is a line of code in check_winner that goes well over 100 columns. I would wrap the line after every few boolean operators in an if statement like this.

if((table_board[i][0] & table_board[i][1] & table_board[i][2])!=0
  || (table_board[0][i] & table_board[1][i] & table_board[2][i])!=0
  || (table_board[i][0] & table_board[i+1][1] & table_board[i+2][2])!=0
  || (table_board[i][2] & table_board[i+1][1] & table_board[i+2][0])!=0)
{
...
}

You seem to be using the new operator where you don't need to. All of this can be done on the stack with less lines of code and less work for the processor. Every time you call new, the CPU has to find new space on the heap, construct the datatype and return the pointer to the memory address. Considering how small this program is, it's likely all your data could fit in the registry directly on the CPU.

void read_move()
{
    int moveX = 0;
    int moveY = 0;
    std::cout << "\nChoose a field (Player " << which_player << "): ";
    std::cin >> moveX >> moveY;
    write_move(moveX, moveY, which_player);
}

check_winner also has a similar problem.

draw_board does not need to take in a table_board because it is already accessible as a member, also I would avoid giving function parameter the same names as members. I'd recommend putting a lowercase 'm' before your member variables and using pascal case.

After the appropriate code changes, you shouldn't have any pointers in your code, but just as a side note:

nullptr is now the standard for assigning pointers to null in C++11. nullptr is of type std::nullptr_t where NULL is an int.


Returning elements in a list also found in another list

First, let's get this out of the way:

The reason the OP version is slow is that, to decide whether to insert elements into c, it checks each one of them against b—a list, rather than a set. That means it's quadratic when it could be linear.

You could fix that by making another set, call it mark2 = set(b), then using if -i in mark2 instead of if -i in b.

That means your code is no longer quadratic, it's linear. Which is probably all you cared about.

However, it's looping twice as much as it needs to, and it's doing all of the looping in Python rather than finding ways to push it into C. That add_mark = mark.add optimization implies that you might be looking for more such tricks, and you should be able to cut the time to about a third.

But just fixing that isn't good enough once you get the community going, so a number of variations have been suggested both here and on a previous SO question. Which one is actually
fastest?

Instead of just guessing, let's actually write and test some implementations and see. Of course for real answers we need your real data, but I'll make up some data, and that should be enough to show you how to do it yourself.

# my answer on the earlier question, and my comment above
def negated_0(a):
    a = set(a)
    return [i for i in a if -i in a]

# Peter DeGlopper's comment, and hcwhsa's on the earlier question
def negated_1(a):
    s = set(a)
    return [i for i in a if -i in s]

# one suggestion I made on the earlier question
def negated_2(a):
    return set(a) & {-i for i in a}

# another suggestion I thought my be a little faster but not worth it
def negated_3(a):
    return {-i for i in a}.intersection(a)

# a possibly-improved version of #3 that I just thought of
def negated_4(a):
    a = set(a)
    return a & {-i for i in a}

# kojiro's posted answer
def negated_kojiro(a):
    '''Take a list a and returns another list which only contains the elements x such that -x is also in a'''
    neg, pos = set(), set()
    for i in a:
        if i < 0:
            neg.add(-1*i)
        else:
            pos.add(i)
    return [i for i in a if abs(i) in pos & neg]

import timeit
import random

a = [random.randint(-10000,10000) for _ in range(1000)]
for func in dir(sys.modules('__main__')):
    if func.startswith('negated_'):
        f = getattr(sys.modules('__main__'), func)
        print('{}: {}'.format(func, timeit.timeit(lambda: f(a), number=10000))

Here's the output on one laptop with Apple's Python 2.7.2:

negated_0: 1.50614500046
negated_1: 1.45001101494
negated_2: 1.79172492027
negated_3: 1.29876303673
negated_4: 1.92844605446
negated_kojiro: 84.5585548878

… and with a default-configured local build of Python 3.4 trunk:

negated_0: 1.5246370710083283
negated_1: 1.420855167991249
negated_2: 1.7558801580162253
negated_3: 1.297387560014613
negated_4: 1.8665565319824964
negated_kojiro: 72.18082603899529

… and with PyPy 2.1.0/2.7.3:

negated_0: 0.595048904419
negated_1: 0.405268907547
negated_2: 0.815263032913
negated_3: 0.878368139267
negated_4: 0.910092115402
negated_kojiro: 49.3969540596

Comparing the fixed version of the OP's implementation:

negated_op: 4.76454496384
negated_op: 3.3227077620103955
negated_op: 0.87509393692

(The original, unfixed version took over 79 seconds before I killed it in 2.7.2.)

We've improved it by 3x in CPython 2.7.2, but only 2x in the other implementations. Not quite what I'd hoped, but not bad.

It looks like negated_3 actually is a decent-sized win over the obvious implementation, but nothing else is. (And #4 actually makes things worse.)

Wrapping #2-#4 in list(…) so they return the same type as the others shows virtually no difference:

negated_0: 1.54194092751
negated_1: 1.44428801537
negated_2: 1.78255009651
negated_3: 1.29559803009
negated_4: 1.90534591675

Fixing the most serious problem with kojiro's answer, by evaluating pos & neg once outside the listcomp instead of for each element, gives me:

negated_kojiro_fix: 2.11841907501
negated_kojiro_fix: 3.84713697433
negated_kojiro_1: 0.739408969879

So, it's still significantly slower than negated_1 (which, like it, preserves duplicates and order) everywhere. Why?

It could be that it's doing twice as much setup work and not getting a comparable amount of savings in the actual comprehension. It may be simpler work, but still, adding O(N) loops in Python to speed up an O(N) list comprehension might be costly.

But there's also the fact that the listcomp filter is more complicated: abs(i) in mark instead of the -i in mark. So, if we could make it even simpler, would that make the listcomp even faster? Just keep the negated set around, and do i in mark. Which means you can replace the listcomp with a filter by using mark.__contains__ as the argument:

def negated_3b(a):
    mark = {-i for i in a}
    return filter(mark.__contains__, a)

(For Python 3, you have to make that list(filter(…)) of course, or it'll return almost instantly, having built an iterable but not iterated it.)

The results with the same three Python implementations are:

negated_3b: 1.39607014656
negated_3b: 1.8215457699843682
negated_3b: 0.51006603241

So… it beats all of the other order-and-dups-preserving methods in 2.x, CPython or PyPy, but not the set-returning negated_3 (which is obvious, when you think about it).

However, it's slower in 3.x. Maybe that's just because of the necessity of calling list? If you don't actually need a list, let's see how long it takes to iterate it, by just feeding the iterator into deque(maxlen=0):

negated_3b: 1.6808519120211713

Better, but still not as good as negated_1 in Python 3. Maybe it's just that 3.x's filter hasn't been improved since the original version was written as 2.x's itertools.ifilter, but listcomps have been improved multiple times over the years?

So, conclusions—if your data are very similar to mine (which is very unlikely!):

Unless this is such a bottleneck in your code that a few microseconds one way or the other actually make a difference, use whichever one is most readable.
If you don't need to preserve order and duplicates, use negated_3.
If you're using Python 2.x, use negated_3b.
Otherwise, use negated_1.


Making a reservation using Selenium/PhantomJS

You can try approaching the problem without using an actual browser and sending HTTP requests using requests and parsing HTML using, say, BeautifulSoup. This though would involve diving into how the page is formed, is more error-prone and would be far more suspicious and easier to detect in general. Of course, with no browser overhead, this would be much faster.

There are some other relevant tools like the Scrapy web-scraping framework. Which, if needed, can be combined with a JavaScript engine - see scrapy-splash.

There are though some things you can try to speed things up in your current approach:

remove time.sleep() hardcoded delays and switch to using Explicit Waits based on WebDriverWait and Expected Conditions
avoid using XPaths as it is generally the slowest element location technique (of course, that's not a bottleneck here)
you can pass certain flags to PhantomJS to help it load pages faster - like --load-images
you can try switching to headless Chrome instead of PhantomJS - I've seen benchmarks showing that the headless Chrome beats PhantomJS in terms of both speed and memory usage


Find if one list is a subsequence of another

Review

Testing

  (I haven't rigorously tested it).

Well you should write some test to ensure validity of the function. So even after changes you can be sure it will still work. doctest is a pretty nice module to use, and is a nice extension of your docstring
Naming

Variables should have descriptive names!

lst1, lst2 if it wasn't for that docstring I would not have known what is the subseq and the parent, so instead I propose to rename them to needle and haystack here the intent is more clear

Same goes for d1, d2... I can see that they are the remaining length of the list, but it is hard to tell from the variable name.
for is considered more Pythonic vs while

For loops are Pythons greatest feature IMHO, they are easy to read and short to write

You should start writing for loops instead of a while, "Loop like a native" might be an interesting talk to view
Too many assignments in a line

Might be preference, but I find this line hard to read:

i, j, d1, d2 = i+1, j+1, d1-1, d2-1

There are too many values with not enough descriptive names on this line

Alternative

We can instead loop over the haystack and use slicing to compare the sliced haystack with the needle, lastly top it off with the any keyword and write some tests with the doctest module

import doctest

def is_subsequence(needle, haystack):
    """
    Finds if a list is a subsequence of another.

    * args
        needle: the candidate subsequence
        haystack: the parent list

    * returns
        boolean

    >>> is_subsequence([1, 2, 3, 4], [1, 2, 3, 4, 5, 6])
    True
    >>> is_subsequence([1, 2, 3, 4], [1, 2, 3, 5, 6])
    False
    >>> is_subsequence([6], [1, 2, 3, 5, 6])
    True
    >>> is_subsequence([5, 6], [1, 2, 3, 5, 6])
    True
    >>> is_subsequence([[5, 6], 7], [1, 2, 3, [5, 6], 7])
    True
    >>> is_subsequence([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, [5, 6], 7])
    False
    """
    return any(
        haystack[i:i+len(needle)] == needle
        for i in range(len(haystack) - len(needle) + 1)
    )

if __name__ == '__main__':
    doctest.testmod()


Help with refactoring my Tic Tac Toe game

For someone new to coding, there's a lot here that is good. Naming of classes, functions and variables are generally good. Comments follow convention, with simple, concise Docstrings for everything. Methods are generally simple and do only one thing, which is nice.

Let's go through a few things that I think can be improved:

In the winner function, every time this is called, winning_rows is recreated. However, this will be the same for any Board, and won't change. Hence, we can make this a class attribute:

class Board(object):

    winning_rows = [[0,1,2],[3,4,5],[6,7,8], # up and down
                    [0,3,6],[1,4,7],[2,5,8], # across
                    [0,4,8],[2,4,6]]         # diagonal

In winner, we simply call it as follows:

def winner(self):
    """Wining combinations. Returns Player or None"""
    for row in Board.winning_rows:
        #Code as before

In fact, the user of Board probably shouldn't change this. Other object-oriented language have the notion of private variables: variables that aren't visible and can't be accessed outside their own class. Python doesn't have this restriction, but it does have a convention that anything prefixed by an underscore should probably be treated as such, hence it should be _winning_rows.

Naming is generally good, but just watch out for the few inconsistencies that are lurking around: self.move_names or self.Free_move? It's nice to keep things uniform, either start everything with lower case, or start everything with upper case. Starting everything with lowercase would be "more pythonic" in my eyes, but consistency is key. The same thing applies to method names, e.g. gameOver vs startover.

Using Player as a base class and PlayerX, PlayerY as subclasses isn't really the way to go here. Note that xmove and ymove are almost exactly the same. This sort of code duplication is a definite sign that you should reconsider your design. Instead of subclassing for each type of Player, it would be far better to simply create difference instances of Player, each one with perhaps an attribute like self.piece. Hence, it would look something like:

class Player(object):

    """ Represents player and his/her moves"""
    def __init__(self, piece, moves):
        self.moves = moves
        self.piece = piece

    def getMove(self):
        print("Move Player %s" % self.piece)
        #...

    def makeMove(self, move):
        #...

    def __str__(self):
        return "Player " + self.piece

I've modified the names and shuffled things around a bit here, but hopefully you can see what's going on. This cuts down on the repeated code. Note we've also directly created a __str__ method that will be called whenever we call str() on a Player.

There are a few bits of leaky abstraction. self.whoseturn = 1 shouldn't live in Player - this doesn't really encapsulate anything about the player themselves, it's instead information about the state of the game - hence it's in the wrong spot. It likely shouldn't be a simple int either. In fact, I think the part of the code that needs the most work is the tictac() function. Instead of simply having a function, there should be another class that encapsulates the idea of a game. This will hold a Board, both the Players, and will co-ordinate whose turn it is, whether the game is finished, and perform cleanup and reset functions for a new game:

class Game(object):

    _welcome_mes = """Welcome to Tic Tac Toe!

The Game board is as follows:

    _0_|_1_|_2_
    _3_|_4_|_5_
     6 | 7 | 8   """

    def __init__(self):
        self.board = Board()
        self.playerX = Player('x', self.board.moves)
        self.playerO = Player('o', self.board.moves)
        self._currentTurn = self.playerX

    def _swapCurrentTurn(self):
        if self._currentTurn == self.playerX:
            self._currentTurn = self.playerO
        else: self._currentTurn = self.playerX

    def start(self):
        print(Game._welcome_mes)
        while not self.isGameOver():
            print("Turn: " + str(self._currentTurn))
            if self._currentTurn.move():
                self._swapCurrentTurn()
        self._atGameEnd()

    def _atGameEnd(self):
        print(self.board.winner() + " has won the game")
        print("Would you like to play again?")
        answer = input()
        if str(answer).lower() in ["yes", "y", "yeah"]:
            self._restart()

    def _restart(self):
        self.board.clear()
        self.playerX = Player('x', self.board.moves)
        self.playerO = Player('o', self.board.moves)
        self._currentTurn = self.playerX

    def isGameOver(self):
        return self.board.gameOver()

To play the game, all you need to do is make a Game object and call start() on it. This cleans up the logic a bit (and was done a bit hastily, so can probably be further improved. However, it should give you a general idea at least). I've left out any docstrings, which you should add if you decide to go this route.

I've also cleaned up the string checking to see if the user wants to play again: firstly, we convert it to lowercase, so we don't need to worry about dealing with the difference between "yes" and "YES", and then we simply check if it is in a few different options with in.

There's another minor thing I would think about fixing/adding: having the board print out in rows of 3, instead of a single flat list. This should be fairly simple.


How to fill an ArrayList of ArrayLists with a Left Join?

A standard way to do this is through break-processing, where you track one value, and when it changes, you do something special.... but you may find it easier to do a more unstructured system:

Map<Integer, List<Project>> employeeProjects = new HashMap<>();
Map<Integer, Employee> employees = new TreeMap<>(); // Treeset ... sorted by employeeID

// join the tables.
String select = " select e.employee_id, e.employee_name, p.project_id, p.project_name "
              + " from employees e
                      left outer join projects p on e.employee_id = p.employee_id"
              + " order by e.employee_id, p.project_name";

// do the select.....

while (rs.next()) {
    Integer employeeID = rs.get("employee_id");
    Employee emp = employees.get(employeeID);
    if (emp == null) {
        emp = new Employee();
        emp.setName(rs.get("employee_name");
        emp.setEmployeeID(employeeID);
        employees.put(employeeID, emp);
        // create a new list for this employee
        employeeProject.put(employeeID, new ArrayList<Project>());
    }

    String projectName = rs.getString("project_name");

    if (!rs.wasNull()) {
        List<Project> projects = employeeProject.get(employeeID);
        Project proj = new Project();
        proj.setID(rs.getInt("project_id"));
        proj.setName(projectName);
        projects.add(proj);
    }

}
rs.close();

Then, once you have the data structured the way you want, you can:

List<Employee> result = new ArrayList<>();
for (Employee emp : employees.values()) {
    emp.setProjects(employeeProjects.get(emp.getEmployeeID());
    result.add(emp);
}
return result;


Wouldn't this give you the desired output:

$result = '
' . preg_replace('/^- (.*)$/m', '
$1
', $subject) . '
';

Update:

$output = preg_replace_callback(
    "((^- (.*)$\r*\n*)+)m",
    function($m) {
        return '
' . preg_replace('/^- (.*)$/m', '
$1
', $m) . '
';
    },
    $input
);


Counting all substrings with exactly k distinct characters

Consider

public static void findSubstringsWithKDistinctCharacters(String s, int k) {
    char[] letters = s.toCharArray();

    for (int i = 0, n = letters.length - k; i <= n; i++) {
        Set<Character> uniques = new LinkedHashSet<Character>();

        for (int j = i, m = i + k; j < m; j++) {
            uniques.add(letters[j]);
        }

        if (uniques.size() == k) {
            System.out.println("substring : " + uniques);
        }
    }
}

This is a simpler version of what you wrote.  It gets rid of your r variable entirely, as it is unnecessary.

I also changed the names of sArr and set to things that I find more descriptive.

I moved the code into its own method so that it can be called multiple times.

There are two reasons to move the declaration of uniques into the loop.  One, this is less code.  Two, if you changed this code to produce a list of results rather than print the results, the other version doesn't work.  You'd have multiple copies of whatever the last set was rather than unique copies.  I'd only use the clear version if I knew that performance of this method was a bottleneck.

Bug

Unfortunately, both this version and your original do not match the linked problem statement:

  Input: aba, k = 2
  Output: 3
  Possible substrings are {"ab", "ba", "aba"}

  Input: aa, k = 1
  Output: 3
  Possible substrings are {"a", "a", "aa"}

They only find two solutions for each of these, as they stop counting once there are k characters (distinct or not) in the substring.  They should keep going until they've verified that the next character isn't a duplicate of a character already in the substring.

Complexity

Calling the time complexity \$\mathcal{O}(n\cdot k)\$ is reasonable.  It's slightly more accurate to say that it is \$\mathcal{O}(n\cdot k - k^2)\$, but \$k\$ is never larger than \$n\$ so it's reasonable to view this as \$\mathcal{O}(n\cdot k)\$.  Note that if you fix the algorithm, it would be \$\mathcal{O}(n^2)\$, as the worst case is an input of all the same character.  That gives substrings up to length \$n\$ where this is limited to length \$k\$.


How can I avoid all this code duplication?

You could refactor out your tagging into a helper method, as below:

[Authorize]
public ActionResult Create()
{
   var model = new CreateArticleViewModel {};
   TagModel (model, _ => false);
   return View(model);
}
[HttpPost, Authorize]
public ActionResult Create(CreateArticleViewModel model)
{
   if (ModelState.IsValid)
   {
      try
      {
         var currentUser = _userService.GetByUserName(User.Identity.Name);
         var tagIds = model.TagIds.Select(int.Parse);
         var article = _articleService.Create(currentUser, model.Title, model.Body, tagIds);
         return RedirectToAction("ViewArticle", new { id = article.ID });
      }
      catch (Exception ex)
      {
         ModelState.AddModelError("Error", ex.Message);
      }
   }
   TagModel (model, _ => false);
   return View(model);
}

[Authorize]
public ActionResult Edit(int id)
{
   var article = _articleService.GetById(id);
   var model = new CreateArticleViewModel {Title=article.Title, Body = article.Body};
   TagModel (model, tag => article.HasTag (tag));

   return View(model);
}

[HttpPost, Authorize]
public ActionResult Edit(CreateArticleViewModel model)
{
   if (ModelState.IsValid)
   {
      try
      {
            //handle article update
      }
      catch (Exception ex)
      {
            //Add ModelState error
      }
   }
   TagModel (model, tag => article.HasTag (tag));
   return View(model);
}

private void TagModel (CreateArgicleViewModel model, Predicate<Tag> isSelected)
{
   var tags = from tag in _articleService.GetAllTags()
              select new SelectListItem { Text = tag.Name, Value = tag.ID.ToString(), Selected = isSelected(tag)};
   model.Tags= tags;
}


Yes, you could put that into a separate file and include_once('header_file.php');.

You try something such as:

function loadFile($name, $isInterface = false) {
    $type = ($isInterface == true) ? 'interface' : 'class'
    $path = sprintf('./classes/%s.%s.php',$name,$type);
    if (file_exists($path)) {
        require_once($path);
    }
}


Rust shortest way to find the maximum product of a fixed length substring

General observations:

An indentation of two spaces is quite small.  The standard formatting uses four spaces.

Names like Map and Chars read better with their modules: iter::Map, str::Chars.

str: &str — don't do that.

When str is not entirely made of decimal digits, your function panics by unwrapping.  Reporting an error via Result is generally preferred.  Magic also happens when str contains zeros.

Using fold here makes the semantics harder to understand.  A simple for loop might be more suitable.

Now, my intuition tells me floating point calculations are less efficient than just doing the operations on integers, so I wrote a benchmark.  Here's the result that I got:
running 4 tests
test l_f::tests::test ... ignored
test simonzack::tests::test ... ignored
test l_f::tests::bench       ... bench:  10,189,230 ns/iter (+/- 278,958)
test simonzack::tests::bench ... bench:  16,865,990 ns/iter (+/- 440,350)

test result: ok. 0 passed; 0 failed; 2 ignored; 2 measured; 0 filtered out

Using integers resulted in a ~1.7x speedup.  Do note that this benchmark is very crude, and you might want to measure your own use cases.

For reference, here's the code for the benchmark.  (Error checking is omitted for simplicity.)
#![feature(test)]

extern crate test;

mod l_f {
    fn to_digits(digits: &str) -> impl Iterator<Item = u64> + '_ {
        digits.chars().map(|c| c.to_digit(10).unwrap().into())
    }

    pub fn max_product_no_zeros(digits: &str, length: usize) -> u64 {
        if digits.len() < length {
            return 0;
        }

        let mut current_product: u64 = to_digits(&digits[..length]).product();
        let mut max_product = current_product;

        for (left, right) in to_digits(digits).zip(to_digits(&digits[length..])) {
            current_product = current_product / left * right;
            max_product = max_product.max(current_product);
        }

        max_product
    }

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

        #[test]
        fn test() {
            assert_eq!(super::max_product_no_zeros("31415926", 3), 108);
        }

        #[bench]
        fn bench(b: &mut Bencher) {
            let digits = test::black_box("9".repeat(1_000_000));

            b.iter(|| super::max_product_no_zeros(&digits, 10));
        }
    }
}

mod simonzack {
    use std::iter::Map;
    use std::str::Chars;

    fn iter_log_digits(str: &str) -> Map<Chars<'_>, fn(char) -> f64> {
        str.chars()
            .map(|c: char| (c.to_digit(10).unwrap() as f64).ln())
    }

    /// Returns the maximum log sum of adjacent digit characters.
    /// # Arguments
    /// - `str`: Assumes there are no 0s.
    /// - `adj_count`: The number of adjacent digit characters.
    fn max_adj_log_sum_no_zeros(str: &str, adj_count: usize) -> f64 {
        if str.len() < adj_count {
            return 0.;
        }
        let log_first: f64 = iter_log_digits(&str[..adj_count]).sum();
        iter_log_digits(&str)
            .zip(iter_log_digits(&str[adj_count..]))
            .fold(
                (log_first, log_first), // `(log_cur, log_max)`
                |(log_cur, log_max), (x_left, x_right)| {
                    let log_next = log_cur - x_left + x_right;
                    (log_next, log_max.max(log_next))
                },
            )
            .1
    }

    pub fn max_product_no_zeros(str: &str, adj_count: usize) -> u64 {
        max_adj_log_sum_no_zeros(str, adj_count).exp().round() as u64
    }

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

        #[test]
        fn test() {
            assert_eq!(super::max_product_no_zeros("31415926", 3), 108);
        }

        #[bench]
        fn bench(b: &mut Bencher) {
            let digits = test::black_box("9".repeat(1_000_000));

            b.iter(|| super::max_product_no_zeros(&digits, 10));
        }
    }
}


First of all, you shouldn't use $('.submit').click() but $('#myForm').submit() as you will be able to submit forms by pressing enter too.
To check if a string is a number, use !isNan(string) (see this answer for more information).
Email regex are difficult things. Just check if there is someting before the @ (with .+?) and if there is something after the @ (again with .+?) and if that last part contains a . and a couple of characters (from 2 to 6)
It would make the function a lot easier if you put all specific code outside it. E.g:

    validateForm({
        '#nameInput': {
            'valid': function (value) {
                return /^[a-z]+$/i.test(value);
            },
            'label': '#nameLabel',
            'messages': {
                'empty': 'Please enter your name',
                'invalid': 'Letters only',
            },
        },
        '#companyInput': {
            'label': '#companyLabel',
            'messages': {
                'empty': 'Please enter your company',
            },
        },
        // ...
    });


Changing a sprite depending on variables

I suggest writing it as

currentSprite = playerSprites[4 * (gunUpgrade + 1) + (moveUpgrade - 1)];

Consider laying out the elements of playerSprites so as to require fewer ±1 operations.

Note that you must ensure that gunUpgrade never exceeds 3, and moveUpgrade never exceeds 4.


Vectorization for temperature simulation

Besides the hints in comments, I would like to add the following:

Replace the abbreviated variables by useful names. This will increase the performance of your code reviewer.
Try to keep all your comments in English (see 1.).
Preallocate variables if you really want to write their value inside a loop. Even in C++ you would not write Ta(i,t)=Tinitial;.
Do you really need all N*M*num_t values? If not, you should only store the current and the last iteration.
Now try to begin to replace the repetitive statements like Ta(i,t)=T(i,t0); and the sourounding for-loop with a single statement. You don't need to replace all at once.
Split your code into a main function and one or more subfunctions. A recent Matlab itself may then increase execution speed of the loops.
You calculate c=k/Inc_x1; very often but neither k nor Inc_x1 changes. Try to identify lines which can be computed outside of the loop. Maybe you need to introduce more variables (with good names!).
Replace the while-loop by a for-loop. It will be more readable.
Correct the indentation of your code. Press Ctrl-A and Ctrl-I.
If you have a 2D object, then why not use a 2D array for this. If you really need the results for all times, then you should have a 3D-array. You may then initialize it with temperature = zeros(M, N, T_max);

If you made all this changes, feel free to present your new readable and beautiful code.


Using strings (in your case: "o" and "x") to identify the two
players is inflexible and error-prone:

If you mistype "o" as "O" or "0" then the program will not work
properly or crash, and the compiler cannot warn you about that.
If you decide to use different player names or different names for the image resources then you have to change it at many places.
The actual display of a player's name as uppercase letter is "hidden"
at

winner = row[0].uppercaseString

in checkForWinner().

Defining string constants

let playerO = "o"
let playerX = "x"

would be one possible solution, but the better way is to use an
enumeration which can take exactly two values:

enum Player : String {
    case X = "x"
    case O = "o"
}

Methods to get the "other" player, the display image, and to select
a random player can be added directly to the enum definition:

enum Player : String {
    case X = "x"
    case O = "o"

    func other() -> Player {
        switch (self) {
        case .O: return .X
        case .X: return .O
        }
    }

    func image() -> UIImage {
        return UIImage(named: self.rawValue + ".png")!
    }

    static func random() -> Player {
        return arc4random_uniform(2) == 0 ? .O : .X
    }
}

This makes the pickFirstPlayer and toggleNextPlayer() methods
in the view controller obsolete, and viewDidLoad() becomes

override func viewDidLoad() {
    super.viewDidLoad()
    currentPlayer = Player.random()
}

where currentPlayer is defined as

var currentPlayer: Player!

To print a player's name, implement the CustomStringConvertible
protocol:

extension Player : CustomStringConvertible {
    var description: String {
        return self.rawValue.uppercaseString
    }
}

If winner is value of type Player then

gameResult.text = "\(winner) is the winner!"

prints the winner's name using the description method, and you
can adopt that to your needs without affecting the rest of the code or the image resource names.

Your gameState variable describes the contents of the game board,
so I would call it board instead. Each field can be empty, or be
occupied by one of the players. This can be modeled by

var board : [Player?] = [nil, nil, nil,
    nil, nil, nil,
    nil, nil, nil,
]

i.e. an array of optional players.

I would separate the determination of a possible winner from the
display of the outcome, e.g. by defining the method as

func checkForWinner() -> Player? { ... }

which either returns the winner or nil. In that method,

       var row: [String] = []
        for space in combo {
            row.append(gameState[space])
        }

can be simplified using map(). Using the new Player type and return type it  would look this:

func checkForWinner() -> Player? {
    for combo in winningCombos {
        let row = combo.map { board[$0] }
        if (row[0] != nil && row[0] == row[1] && row[1] == row[2]) {
            return row[0]
        }
    }
    return nil
}

It would suffice to check only the rows which are changed by the
last move. On the other hand, with 8 winning combinations, that
does not make a big performance difference.

Assuming that the makeMove() action is connected to buttons
only, you should declare it as

@IBAction func makeMove(sender: UIButton) { ... }

this allows better error checking than sender : AnyObject.
(When you create the action in interface builder, there is an option
for that.)

Using all the above stuff, the makeMove() method becomes

@IBAction func makeMove(sender: UIButton) {
    let space = sender.tag
    if (board[space] == nil && !gameOver) {

        sender.setImage(currentPlayer.image(), forState: .Normal)
        board[space] = currentPlayer
        turnCount++

        if let winner = checkForWinner() {
            gameOver = true
            gameResult.text = "\(winner) is the winner!"
        } else if (turnCount == 9) {
            gameOver = true
            gameResult.text = "It's a tie!"
        } else {
            currentPlayer = currentPlayer.other()
        }
    }
}

You use the UIView's tag property to identify from which button
the action method is called. This is OK, but note that 0 (zero)
is the default tag for all views. It is therefore better to tag the
buttons with 1 ... 9 instead of 0 ... 8, and adjust that in

    let space = sender.tag - 1

A final note about using self: You can access properties and
methods of the current class without using self (unless there
is an ambiguity, e.g. due to a local variable or function parameter with the name name, or if self is captured implicitly in a block.)

Whether you use self or not to access properties is
a matter of taste and programming style,
but in any case it should be consistent in your code, which it
currently isn't:

self.turnCount++
// ...
gameOver = true

(Remark: There was a language proposal to require self for accessing instance members, which
was rejected recently.
Also ++ and -- will be deprecated soon and removed in Swift 3.)


PHP array return array vs passing as reference

Just never return an argument by reference. It is nearly as bad as using global. And even a memory management is not an excuse. In case your array is big, create a function that does the calculations, and then apply it to each element inside of an explicit loop.


Naming

Field babushka should be named wearingBabushka, since that is what the field describes. The method accessing it becomes isWearingBabushka(). For some reason Java-people like exceptions in naming standards and are adamant that it's vital to have a non-standard getter name for boolean typed methods (yes I'm bitter about this, no need to go into it any deeper).

Final modifiers

The fields should be final, as they are not meant to be changed. Non-final fields always increase the cognitive load on the reader as they have to figure out where the fields are modified.

Constructors vs. static factory methods

In this application it could be useful to instantiate the objects with static factory methods.

public abstract class Matryoshka {

    public static Matryoshka of(String name, ...) {
        return new RootMatryoshka(name, ...);
    }

    public static Matryoshka of(String name, ..., Matryoshka innerMatryoshka) {
        Objects.requireNonNull(innerMatryoshka);
        return new OuterMatryoshka(name, ..., innerMatryoshka);
    }
}

Static factory methods allow you to return a different implementations when needed. The root matryoshka would return static values from the methods that calculate weight etc. The outer matryoshkas would simply perform recursion and addition with no need for null checks (as the factory method prevents null values). There are rules on how classe that use static factory methods should be written, I won't replicate them here.

But that's pretty much a matter of taste. The current implementation is just fine too.

Bugs

If the root matryoshka wears a babushka, the calculation returns an incorrect answer.

Style

I find the unnecessary use of this distracting. In my opinion it should be used only when there is a naming conflict. When done so, the number of references to this can be used as a metric for bad naming or problematic structure.

Tail recursion

Since you asked about efficiency, I have to talk about tail recursion. But be aware that this all is total and complete premature optimization. Each of the recursive methods could be replaced with a loop, which would eliminate the need for populating the stack on each recursion:

public int howManyDolls() {
    int dollCount = 0;

    Matryoshka currentDoll = this;
    while (currentDoll != null) {
        dollCount++;
        currentDoll = getInnerDoll();
    }
    return count;
}

It probably won't affect running time, but at least you're not limited by the stack size. You can have millions of matryoshkas! But you will fail the recursion task, since now this has none.


You should take a look at Symfony's HttpFoundation component.

They've written various Request/Response objects similar to what you're attempting to do and they are extremely well done. Either I'd use them directly(save your own time). Or if this is an exploratory exercise then take a look at their code base to see how you can improve on your own solution.

It's not as sexy as writing your own objects, but it'll save you a lot of time and effort in the long run.


Getting the KML color code from colordialog box more efficiently

In the System.Drawing namespace lives the ColorTranslator class which has an ToHtml() method which can be used here. A good way would be to create extension methods for this task. The first extension method will be named ToKMLColor and will expect a String parameter.

By using dec.TryParse() and Math.Min() we assure that the given parameter is a valid representation of a decimal/number with a maximum of 100. If the TryParse won't succeed, we assume that the opacity will be 0.
After we have got the computed (/100*255) opacity value we pass it

public static string ToKMLColor(this Color color, String percentageOpacity)
{
    decimal opacity = 0;
    decimal.TryParse(percentageOpacity, out opacity);

    opacity = Math.Min(opacity, 100);
    opacity = Math.Floor(opacity / 100 * 255);

    return color.ToKMLColor(opacity);
}

to the overloaded ToKMLColor() method, which takes a decimal parameter. After converting the decimal to an int we pass it

public static string ToKMLColor(this Color color, decimal opacity)
{
    return color.ToKMLColor(Convert.ToInt32(opacity));
}

to the overloaded ToKMLColor() method, which takes an integer parameter. Here we call the ToString() method with the X2 format to get the hex representation of the integer parameter and concat the return value of the ToHex() by using the Substring() method to remove the leading #.

public static string ToKMLColor(this Color color, int opacity)
{
    return opacity.ToString("X2") + color.ToHex().Substring(1);
}
public static String ToHex(this Color color)
{
    return System.Drawing.ColorTranslator.ToHtml(Color.FromArgb(0, color));
}

Now we can call

polyColor = colorDialog1.Color.ToKMLColor(txtOpacity.Text);


Detecting capturing moves that pawns can make, in both directions

In other words, I can surely re-factor this by creating another function that contains the common parts, but I am afraid of creating a few more if blocks inside that function and making the code dirtier.

Au contraire. If your refactoring is increasing the code complexity, you're not doing it right.

The refactoring I did in this answer has reduced maximum nesting to a single level.

Maybe some quick-fire observations about why your code was so complex:

You were pushing all your calculations into your array index, which caused you to have to repeat the same value+1 and value-1 statements over and over.
As you already acknowledged, you had copy/pasted code and only made minor alterations (turning a +1 into a -1 due to the different player teams).
Your variables names weren't really all that clear, nor clearly used. Even after having refactored it, I still have no clue what endX and endY were used for.

There are two "types" of refactoring:

Simplifying code by changing it while not making any functional difference.

A simple example would be seeing if(myBool == true) and changing it to if(myBool). It makes no functional difference, and therefore can be safely refactored.

Revisiting the code and redesigning it, so you can optimize it with knowledge you have now (but didn't have at the time).

This often happens when a problem is complex at the beginning, but after developing a solution, it looks so much easier in hindsight.

We're going to be doing the second type of refactoring here. Which means we'll start from scratch and build the requirements as they come.

Assumptions:

Arrays are 0-indexed (it's been a while since I did Java, I think that's the case?)
We're using screen coordinates:

Method signature

We want:

A boolean that tells us whether the pawn can capture an enemy.

We need to supply:

The specific pawn
Access to the game board for retrieving information.

Your code:

public boolean hasCapturableEnemy(Piece[][] board, int startX, int startY, int endX, int endY)

I've been looking at it for a while, and I genuinely have no idea why you are supplying endX and endY. My suggestion:

public boolean hasCapturableEnemy(Piece[][] board, int pawnX, int pawnY)

1 - Input validation

Let's store the pawn in its own variable, for ease of use:

Piece pawn = board[pawnX][pawnY];

Does the referenced position actually contain a pawn? As it stands, you're only really checking for null, so I'll do the same:

if (pawn == null)
    return false;

Notice that I inverted the logic. If the pawn does not exist, then we immediately return false. This helps reduce nesting, and you won't need to indent the subsequent code.

2 - Defining the possible capture regions

To help you simplify this, let's look at the row calculation and the column calculation separately:

Columns are easy: given that a pawn is standing in column X, the capture regions can be found in columns X-1 and X+1.
Importantly, this is true for both the UP and DOWN players!

int captureColumnLeft = pawnX - 1;
int captureColumnRight = pawnX + 1;

When the pawn is on column 0 or 7, it will only have one capture region. But we'll get to that later.

Rows, however, are a bit more complex. This is the first time we need to observe the team that this pawn belongs to. Given that a pawn is standing on row Y, its capture regions are found in row Y+1 for the UP player, but in row Y-1 for the DOWN player.

int captureRow;

if(pawn.getTeam() == Player.UP)
    captureRow = pawnY + 1;
else
    captureRow = pawnY - 1;

We don't need to exclude fringe cases. A pawn can never be at the end of the board (for either player), since it would then turn into another piece.

Now we've very easily defined a given pawn's capture regions:

Piece captureRegionLeft = board[captureColumnLeft][captureRow];
Piece captureRegionRight = board[captureColumnRight][captureRow];

The next step is checking to see if there is a capturable piece on any of the capture regions. As the logic is exactly the same for both regions, we'll put this in a new method.

Before we get to that, let's close our current method:

return CanCaptureAt(captureRegionLeft, pawn)
       || CanCaptureAt(captureRegionRight, pawn);

3 - Checking if a possible capture region contains a capturable piece

public boolean CanCaptureAt(Piece captureRegion, Piece pawn)
{

    // ...

}

The logic isn't all that hard:

If there is no piece in the capture region, we cannot capture anything in that region.

if(captureRegion == null)
    return false;
If there is a piece in the capture region, it must be of the opposing team. In other words, a piece is capturable if the teams are different:

return captureRegion.getTeam() != pawn.getTeam();

Combined:

public boolean hasCapturableEnemy(Piece[][] board, int pawnX, int pawnY)
{
    Piece pawn = board[pawnX][pawnY];

    if (pawn == null)
        return false;

    int captureColumnLeft = pawnX - 1;
    int captureColumnRight = pawnX + 1;

    int captureRow;

    if(pawn.getTeam() == Player.UP)
        captureRow = pawnY + 1;
    else
        captureRow = pawnY - 1;

    Piece captureRegionLeft = board[captureColumnLeft][captureRow];
    Piece captureRegionRight = board[captureColumnRight][captureRow];

    return CanCaptureAt(captureRegionLeft, pawn)
        || CanCaptureAt(captureRegionRight, pawn);
}

public boolean CanCaptureAt(Piece captureRegion, Piece pawn)
{
    if(captureRegion == null)
        return false;

    return captureRegion.getTeam() != pawn.getTeam();
}

Additionally

I said we still needed to exclude two fringe cases: if the pawn is on the leftmost column, it doesn't have a left capture region; and when it is on the rightmost column, it's doesn't have a right capture region.

This can be achieved by slightly reshuffling the code:

public boolean hasCapturableEnemy(Piece[][] board, int pawnX, int pawnY)
{
    Piece pawn = board[pawnX][pawnY];

    if (pawn == null)
        return false;

    int captureRow;

    if(pawn.getTeam() == Player.UP)
        captureRow = pawnY + 1;
    else
        captureRow = pawnY - 1;

    if(pawnX > 0) // == NOT in the leftmost column
    {
        int captureColumnLeft = pawnX - 1;
        Piece captureRegionLeft = board[captureColumnLeft][captureRow];

        if(CanCaptureAt(captureRegionLeft, pawn))
            return true;
    }

    if(pawnX < 7) // == NOT in the rightmost column
    {
        int captureColumnRight = pawnX + 1;
        Piece captureRegionRight = board[captureColumnRight][captureRow];

        if(CanCaptureAt(captureRegionRight, pawn))
            return true;
    }

    //Neither caption region registered a hit,
    //Therefore we cannot capture anything
    return false;
}

Footnotes

There is currently no check to see if the provided X/Y values are within the bounds of the board.
There is currently no check to see if the Piece at the provided X/Y coordinates is actually a pawn.


One improvement would be to simplify this:

    if not out:
        for items in Hero.get_inventory():
            if items.name == "Door1Key":
                print("CLICK!")
                time.sleep(1)
                print("*Door opened*")
                time.sleep(1)
                out = True
                door1key=True
    if not door1key:
        print("Door Could not be opened")
        time.sleep(1)

into this:

    if "Door1Key" in [_.name for _ in Hero.get_inventory()]:
        print("CLICK!")
        time.sleep(1)
        print("*Door opened*")
        time.sleep(1)
        break
    else:
        print("Door could not be opened")
        time.sleep(1)

You don't need "if not out:" at the top of this -- you're in a "while not out" loop and out hasn't had a chance to change since the top of the loop.

The "for items" loop just scans through the inventory looking to see if you have the door key. That can be done in a single statement, as I show.

Once you've opened the door, you're out, so we can just break out of the "while not out" loop and carry on from there.

Several of your descriptions are hard-coded:

print("You look around and find a door, a window, and a box")
print("You open the chest and find a staff(2 damage) and a key, you take them")
print("You see an infected cat in front of you, with death in his eyes.")

For the room, you could do something like

room = {'entrances': ['door', 'window'],
        'contents': ['box']}
print("You look around and find " +
      ', '.join(['a ' + _ for _ in room.entrances] +
      'and ' + ', '.join(room.contents))

The idea is that rather than embedding your data in the code, you should structure it in a meaningful way, then use generic code to present the data from the structures in the way you want the player to see it.

I think you're on the right track with your Creature and Item classes. I think maybe you want more classes like Place (or Room), Container (to represent boxes, chests, hidey holes, etc.). If you have to write specific logic for each step in the story, your game is going to be very linear and you'll be limited in how much branching and looping you can manage.

On the other hand, if your game is just a network of Places connected to each other with Items, Containers, other Creatures and such scattered throughout for the Hero to encounter and either fight or befriend, and the Hero is free to wander from Place to Place backward and forward and in loops, then the game becomes much less predictable and more interesting.

What would the code look like to process such a network of Places, Items, Containers, Creatures, and whatever else you can dream up?


Here few suggestion:

in the function  you have :

if($i == 1)
{

    var $el = $theWidth;
}else{
    var $el = $theWidth * $i;
}

could be replaced by a single line:

var $el = $theWidth * $i;

and you could modify the following if :

if($i < totalImg)
{
    $('.home-featured-bg .absolute').animate({'margin-left':'-'+$el+'px'},2000);
    $i++;
    $('.events-links a').eq($i - 1).css('display','block');
}else{
    $('.home-featured-bg .absolute').animate({'margin-left':'0px'},2000);
    $i = 1;
    $('.events-links a').eq($i - 1).css('display','block');
}

by extract the $('.events-links a').eq($i - 1).css('display','block');   like this:

if($i < totalImg)
{
    $('.home-featured-bg .absolute').animate({'margin-left':'-'+$el+'px'},2000);
    $i++;
}else{
    $('.home-featured-bg .absolute').animate({'margin-left':'0px'},2000);
    $i = 1;
}
$('.events-links a').eq($i - 1).css('display','block');


Repetitive replacement for expressing fractions in LaTeX

You can use a recursive function with the pattern %b() as follows:

function ToFrac( sInput )
    local tStack = {}
    for sOperand in sInput:gmatch "%b()" do
        table.insert( tStack, sOperand:sub(2, -2) )
    end
    while true do
        if #tStack <= 1 then break end
        local sNumerator = table.remove( tStack, 1 )
        if sNumerator:find '/' then sNumerator = ToFrac( sNumerator ) end
        local sDenominator = table.remove( tStack, 1 )
        if sDenominator:find '/' then sDenominator = ToFrac( sDenominator ) end
        table.insert( tStack, 1, ([[\dfrac{%s}{%s}]]):format(sNumerator, sDenominator) )
    end
    return tStack[1]
end

Here, I'm storing the operands as nodes in a stack. I tested the above function for the inputs:

local s = {
    "((a)/(b))/(c)",
    "(a)/((b)/(c))",
    "(a)/((b)/(c))/(d)",
    "(a)/(b)/(c)/(d)",
    "((a)/(b))/((c)/(d))",
}

for k, v in pairs(s) do
    print( v, ToFrac(v) )
end

The final results were:

((a)/(b))/(c)   \dfrac{\dfrac{a}{b}}{c}
(a)/((b)/(c))   \dfrac{a}{\dfrac{b}{c}}
(a)/((b)/(c))/(d)   \dfrac{\dfrac{a}{\dfrac{b}{c}}}{d}
(a)/(b)/(c)/(d) \dfrac{\dfrac{\dfrac{a}{b}}{c}}{d}
((a)/(b))/((c)/(d)) \dfrac{\dfrac{a}{b}}{\dfrac{c}{d}}


Solution to Google Code Jam 2008 round 1C problem B

M = 2*3*5*7
uglies = list(filter(lambda n: (int(n)%2 == 0 or
                                int(n)%3 == 0 or
                                int(n)%5 == 0 or
                                int(n)%7 == 0),
                     range(M)))

Why the int(...) calls? Surely range returns integers?

@lru_cache(maxsize=None)
def f(line, k=None):
    if k == None:
        return sum([f(line, k) for k in uglies])

I'm not really a Python programmer so I'm not sure how Pythonic it is, but to me this overloading is a code smell. I would prefer to split out one function which takes just the line and another which does the real work.

Also, what is k? I managed to figure it out by reverse engineering, but a short comment would have helped a lot.

    return sum([
        (1 if (int(line) % M) == k else 0),

        sum([f(line[:p],
               (k-int(line[p:])) % M)
             for p in range(1, len(line))]),

        sum([f(line[:p],
               (k+int(line[p:])) % M)
             for p in range(1, len(line))]),
        ])

Again, it would be nice to have a short comment explaining why the recursion works on suffixes (and proving that it's correct, which isn't obvious, because it would seem to allow inserting a - before the first digit of the line in contradiction to the spec).

It would also be nice to see a justification for working on string slices rather than using integers with div/mod by powers of 10.


There is a better way.

That's a very good function, but you can make it 100 times more useful by returning the statement.

function pdoQuery($con, $query, $values = array()) {
    if($values) {
        $stmt = $con->prepare($query);
        $stmt->execute($values);
    } else {
        $stmt = $con->query($query);
    }
    return $stmt;
}

Given there are two excellent things,

"method chaining" (if some statement returns an object, you can call this object's method directly by adding -> )
different fetch methods supported by PDOStatement

So in the end your current code will be changed a little, but you will get a lot of other neat ways for getting your data.

To get a row

$row = pdoQuery($pdo, "SELECT name FROM table WHERE id=?", [$id])->fetch();

to get a name

$name = pdoQuery($pdo, "SELECT name FROM table WHERE id=?", [$id])->fetchColumn();

But beside these two use cases there are many others!

you can run a DML query as well:

pdoQuery($pdo, "DELETE FROM table WHERE id=?", [$id]);

fetch a list of records

$data = pdoQuery($pdo, "SELECT * FROM table")->fetchAll();

use all the formats supported by fetchAll()
even get a row count

$deleted = pdoQuery($pdo, "DELETE FROM table WHERE id=?", [$id])->rowCount();

As you can see, this new function is much more flexible and can be used to ease a lot more tasks


If you look at your naming schema, you have emptyX and guessX, where X is an index. This is an indicator that you should be using an array or a list:

EmptyType empties[5] = { empty1, empty2, ... };
GuessType guesses[5] = { guess1, guess2, ... };

yellow.setOnClickListener(new View.OnClickListener() {
    public void onClick (View v) {
        assert buttonCount < 5;
        empties[buttonCount - 1].setImageResource(R.drawable.yellow);
        buttonCount++;
        guesses[buttonCount - 1] = Colour.YELLOW;
    }
})

If you have to do the same thing for three colours, either copy&paste this small snippet, or extract it into another method, which you can call with appropriate colours:

private void doStuff(EventSource source, Color color, ImageResource resource) {
  source.setOnClickListener(new View.OnClickListener() {
    public void onClick (View v) {
        assert buttonCount < 5;
        empties[buttonCount - 1].setImageResource(resource);
        buttonCount++;
        guesses[buttonCount - 1] = color;
    }
  });
}

  doStuff(yellow, Color.YELLOW, R.drawable.yellow);
  doStuff(blue,   Color.BLUE,   R.drawable.blue  );
  doStuff(green,  Color.GREEN,  R.drawable.green );

This still looks like you could choose better data structures, so that the Color and the corresponding ImageResource and EventSource are explicitly connected.


No big issues that I can see, but here are a few tips.

When using for-in loops, add a hasOwnProperty check, like this:

for (var i in obj) {
    if (obj.hasOwnProperty(i) {
        // do stuff
    }
 }

Otherwise the loop will also iterate over properties of Object.prototype.

data can more simply and efficiently be declared like this:

data = localStorage[USERID + '.forumhistory'] ?
    JSON.parse(localStorage[USERID+'.forumhistory']) :
    {forum:{},thread:{}};

The switch statement might be more legibly written as a series of if else-if statements (with nesting), but that's mostly a stylistic choice.

data is, actually, the worst variable name there is. It is impossible to create a less specific name. I would suggest renaming it.

In loops where you iterate over an array, like this:

var i, l = forums.length;
for (i = 0; i < l; i++) {
    // use `forums[i]`
}

If you know every element in forums is truthy (not 0, null, undefined, false, or ""), you can use this loop, which is shorter and more efficient, and in my opinion more legible.

var i, forum;
for (i = 0; forum = forums[i]; i++) {
    // use `forum`
}


There are several ways to improve the code.
Let's start with the constructor.

You should not make any assumptions about the place of a file in the current file system, because that makes later changes very hard and it hurts reusability.
So get rid of the __DIR__ constant and send the directory of the classes as an argument to the constructor instead.

Registering callbacks and finding a file are two very different tasks. They don't belong to the same class. So register a method of an instance of the autoloader from the outside instead, and remove the call to spl_autoload_register() from your class.

You should use namespaces for all of your classes, interfaces and traits. This prevents collisions in case that you want to use other peoples code in your project later. Add a $namespace argument to your constructor.

In the end, your constructor shouldn't do more than setting up private members, maybe add some preparation for these. Example:
/**
 * Autoload constructor.
 *
 * @param string $namespace Pass the namespace unescaped.
 * @param string $dir
 */
public function __construct( $namespace, $dir )
{
    // Make sure it ends with a '\'.
    $namespace       = rtrim( $namespace, '\\' ) . '\\';
    $this->namespace = $namespace;
    $this->length    = strlen( $namespace );
    $this->dir       = rtrim( $dir, '/' ) . '/';
}

Now, to the actual class loader classLoader().

I wouldn't call it classLoader, because it will load traits and interfaces too. Just call it load(), that's clear enought for a class named Autoload. :) And because you will register and test it directly, make it public.

Do not return a value in that method. If you find a matching file, just include it and stop, return nothing otherwise. PHP will figure the rest out for you.

class_exists() is pointless here, because that method will be called only if the class/trait/interface doesn't exist yet. Just remove it.

The private methods called from that "parent" method don't deal with namespaces, and they are too slow. You don't need glob() here. (On a side note GLOB_ONLYDIR is not available on Solaris/Sun OS, use that constant only if portability is not a concern for your code.)
Figure out the correct complete file path first, then check if that file exists and is readable! The latter is important, because you cannot rely on the fact that you can actually include all existing files.

So that method may be reduced to something like this:
/**
 * @param string $search
 * @return void
 */
public function load( $search )
{
    if ( strncmp( $this->namespace, $search, $this->length ) !== 0 ) {
        return;
    }

    $name = substr( $search, $this->length );
    $path = $this->dir . str_replace( '\\', '/', $name ) . '.php';

    if ( is_readable( $path ) ) {
        require $path;
    }
}

Finally to the registration. As you can see, you can reuse the class now to find files in different directories mapped to a namespace. Let's say all of your own files are living under the namespace CodeReview in the directory src/ (this is a convention in PHP).
In the main file of your application, you can include the Autoloader and register its load() method now like this:
require __DIR__ . '/src/Autoload.php';
spl_autoload_register( [ new Autoload( 'CodeReview', __DIR__ . '/src/' ), 'load' ] );

Now let's say, you have a class Response living under namespace CodeReview\Http.
namespace CodeReview\Http;

class Response {}

It should be placed under /src/CodeReview/Http/Response.php.
You can create a new instance now either with:
new CodeReview\Http\Response;

… or you put a use statement at the top of the file that is creating that instance:
use CodeReview\Http;

new Response;

Your class is much simpler now, you can test it, map it to different directories and namespaces, use it in different projects, and put it in any place you like.


This will make your example work in the same way you intended to.

patterns = []
patterns.append(lambda x: 'A' if x.isalpha() else x)
patterns.append(lambda x: '0' if x.isdigit() else x)

def get_pattern(name):
    for pattern in patterns:
        name = map(pattern, name)
    return ''.join(name)

Additionally you can register new patterns. Here is an example:

>>> get_pattern('Mario Cesar 2013')
'AAAAA AAAAA 0000'

About your objective, if you want just to sanitize the file names, will be the best to use a different approach, look at https://github.com/ksze/sanitize