Insert and update SQL entries for posts to be accessed by up to 3 other users

Consider the following table:

CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(6) unsigned NOT NULL,
  `post` varchar(24) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

We've stripped out the ref columns.  Now we add a new table:

CREATE TABLE IF NOT EXISTS `post_refs` (
  `posts_id` int(6) unsigned NOT NULL,
  `ref` varchar(24) NOT NULL,
  `ref_id` varchar(24) NOT NULL,
  PRIMARY KEY (`posts_id`, `ref`)
) DEFAULT CHARSET=utf8;

It's possible that the index should contain ref_id rather than ref.  You don't really provide enough context to tell.

This is basic normalization.  Database tables should not contain columns of duplicate information (e.g. numbered columns).  Such columns should be moved into their own table so that you don't have to modify the database structure every time you change the business rule.

To make this work, you need at least two SQL queries, one for each table.  You have to get the posts_id after the first one.  For updates, you would do so with a SELECT (possibly embedded in the query).  For inserts, you could do $conn->lastInsertId() after inserting the post.  For updates, you might want to delete from the post_refs table and then do an insert.  E.g. something like

SELECT id AS posts_id FROM posts WHERE post = :post

If no rows, do

INSERT INTO posts (post) VALUES (:post)

If there are rows, do

DELETE FROM post_refs WHERE posts_id = :posts_id

Either way, then do

INSERT INTO post_refs (posts_id, ref, ref_id) VALUES (:posts_id, :ref, :ref_id)

or the multi-row equivalent.

That logic becomes simpler if you know beforehand whether you need to do an update or an insert.  Your question implies that you do, but it doesn't show how.

Also consider

CREATE TABLE IF NOT EXISTS `post_read_users` (
  `posts_id` int(6) unsigned NOT NULL,
  `users_id` int(6) unsigned NOT NULL,
  PRIMARY KEY (`posts_id`, `users_id`)
) DEFAULT CHARSET=utf8;

Because it's not normally necessary to describe the people that you want to give access.  You usually just select from a list, connecting existing users to the post.  You seem to be creating the users as you go.  So either the person creating has to remember to give the same information each time, or the person reading has to remember multiple passcodes.  Either would be an uncommon and overly difficult implementation.


Creating an in-memory ViewCounter that commits to database every 10 minutes

This method is broken in two ways. First, multiple threads can access the counter at the same time, and based on ordering, you may lose some updates. Second, if the counter is being created for the first time by multiple threads, you may create the counter multiple times.

public void incrementViewCount(Integer routeId) {
    if (viewCounter.containsKey(routeId)) {
        Integer counter = viewCounter.get(routeId);
        counter++;
        viewCounter.put(routeId, counter);
    } else {
        viewCounter.put(routeId, 1);
    }
}

In addition, you are not clear()ing the map in a thread-safe way. You should strongly consider an existing counter class, like Guava's AtomicLongMap. Writing a thread-safe counter is surprisingly non-trivial.


You can get really far cleaning this up by just creating some private functions and bumping them to the bottom of the file so that they can be hoisted

  this.Sound.masterVolume = function(v){ masterVolume = Math.pow(v,2);};
  this.Sound.instanceVolume = function(name, v){ instanceVolume[name] = Math.pow(v,2);};
  this.Sound.masterStop = function(){ liveSounds.forEach(reset) }
  this.Sound.masterPause = function(){ liveSounds.forEach(pause) }
  this.Sound.instanceStop = function( name ){ liveSoundsExcept(name).forEach(reset) }
  this.Sound.instancePause = function( name ){ liveSoundsExcept(name).forEach(pause) }
  this.Sound.instanceGetLive = function( name ){
    //this seems to be an error - what is match?
    return liveSounds.filter(function(snd){
      return( snd.src === match );
    });
  }
  this.Sound.masterGetLive = function(){
    return liveSounds.slice(0);//slice generates a copy - I don't think splice does
  }

  this.sound = function(name){
    var snd = new Audio(getSound(name)); //reference to `this` removed because it wasn't being used
    snd.volume = instanceVolume[name] || 1;
    snd.play = function(){
      //why use the ambiguous `this` here? It can vary depending on how this is called - you already have an isntance of `snd`!
      snd.volume *= masterVolume;
      //Audio.prototype.play.apply(snd); //Why? you can just use
      snd.play();
      liveSounds.push(snd);
      // This can't be right - you don't need to do any cleanup?
      // this.onended = function(){ liveSounds.splice( liveSounds.indexOf(snd), 1 );};
    };
    return snd;
  };

  function getSound(name) { return sounds[name].src}
  function liveSoundsExcept(name) {
    var match = getSound(name);
    return liveSounds.filter(function(snd){ return snd.src !== match });
  }
  function pause(snd) { snd.pause(); }
  function reset(snd) {
    pause(snd);
    snd.onended();
    snd.currentTime = 0;
  }

I absolutely agree with @Schism that more context is needed for a really good review but I made a few other observations inline.

One that also jumps out at me is this whole relationship between liveSounds and how you're selecting by name. Without more context I can't say for sure, but it seems like maybe you can have liveSounds = {} with the name being the key and that would make everything much simpler.

You do need to think if sounds need to get disposed of or what happens if you invoke a method for something without a name, or if there's two things with the same name.

Also, as always, I'm going to go ahead and say the prodigious use of this here is probably entirely unnecessary and you can just use a factory method instead of a constructor.

Also, it's 2015, can't we just start using es6 already?


Ok, before I set of, there are 3 things to keep in mind here: Code review has to be tough, to be good, so if this hurts your feelings - sorry, but I'm trying to help.
The second thing is: Please, please, please try to adhere to the coding standards as defined by PHP-FIG (google them). Most, if not all, major players adhere to them, and you should, too. Sure, they're not official (yet), but there are no official standards... the more people adhere to a given set of unofficial rules, the more likely it is they become standard.
And finally: Please, document your code... you add some comments here and there, but not nearly as much as required... the main method of your class will bite you in the bum if you leave it be for a couple of months, and then decide to add something or debug it a little...

Now, to business. As I usually do, I'll be going through your code bit by bit, suggesting and commenting along the way

class CSVParser
{//next line, PHP-FIG style

    /**
     * @var string
     **/
    protected $fileName = null;//camelCase plz
    /**
     * @var resource <file handle>
     **/
    protected $fileHandle = null;
    /**
     * @var bool
     **/
    protected $hasHeaderRow = false;
    /**
     * @var array<mixed>
     **/
    protected $rowsToIgnore = array();

Now, I'd initialize the properties to null, simply because it's a good habit if you're ever in the situation where you find yourself switching from one language to another.
I'd also add doc-blocks per property to document what types these properties will be assigned
I'd also strongly suggest defining the properties as protected, since a class that reads files should be quite generic, and easy to extend from. If you extend, therefore, private is not always very useful...

Now, the methods:

public function __construct ($FileName, $Mode = "r")
{
    $this->FileName = $FileName;
    if (($this->FileHandle = fopen($this->FileName, $Mode)) === FALSE)
        return false;///????
}

This one is a big problem: At no point are you checking the type of any of the arguments that you're receiving. Is $FileName even a string? is it null?
Worse still: $Mode is the mode in which you want to open the file... fine, there's a limited amount of valid strings that can be passed here. For the ease of the user, and to improve readability of the code that uses your class, I'd create constants for the $Mode parameter.
Then: return false? Seriously? From a constructor? A constructor returns an instance of the given class. All other return statements are pointless, they are ignored. If this were to work, this requires the user to write code like this:

$reader = new CSVParser($file, 'r');
if ($reader === false)
{
    //handle error
}

Which is just messy. If you must, throw an exception, but better yet: allow the user to set the file that needs to be read later on. That way, the user can create the instance, and re-use it throughout his code. Here's what I'd write:

const OPEN_READ = 'r';
const OPEN_WRITE = 'w';
const OPEN_APPEND = 'a';
const OPEN_BIN_READ = 'rb';
const OPEN_BIN_WRITE = 'wb';
//and so on
public function __construct($file = null, $mode = self::OPEN_READ)
{
    if ($file)
    {
        if (is_string($file))
        {
            $this->fileName = $file;
            if (!($this->fileHandle = fopen($file, $mode))
                throw new RuntimeException('Opening file '.$file.' failed');
            return $this;//success
        }
        throw new InvalidArgumentException('File argument is not a string');
    }
    //nothing passed => just fine...
}

But this is far from perfect: you should provide support for the SplFileInfo class (users passing an instance of SplFileInfo should work, too) and perhaps allow them to pass a file handle they opened already.
What you've also failed to do is allow the user to set the hasHeaderRow in the constructor. Now, I'm no big fan of constructors requiring too many arguments, so what I'd probably write is something like:

public function __construct($mixed)
{
    if ($mixed instanceof SplFileInfo) return $this->openSplFile($mixed);
    if (is_resource($mixed)) return $this->useFileHandle($mixed);
    //is string, array, some other instance...
}

But that's what I would do, not what you must do.
Onwards:

public function hasHeaderRow ($flag = false)
{
    $this->hasHeaderRow = (bool) $flag;
    return $this;
}

public function ignoreRows (array $Rows)
{
    $this->rowsToIgnore = $Rows;
    return $this;
}

I've added the return $this; statements simply because I like chainable API's. Now the user can write:

$instance->hasHeaderRow(true)
        ->ignoreRows($someArray);

Other than that, the hasHeaderRow is fine, but the ignoreRows method is, to my eye a tad vague, and I don't like how it doesn't allow me to merge in new rows to the ignore array. Perhaps consider writing

public function ignoreRows(array $rows, $merge = false)
{
    if ($merge){
        $this->rowsToIgnore = array_merge(
            $this->rowsToIgnore,
            $rows
        );
        return $this;
    }
    $this->rowsToIgnore = $rows;
    return $this;
}

Now, I'll skip the groupByColumn method for now, because there's a lot of things I to review there, so first, let's look at this:

public function __destruct()
{
    fclose($this->fileHandle);
}

Nice, that's a sensible use of the constructor method. But what about any of the other magic methods? __sleep and __clone to name just 2? All those methods, if a file-handle is concerned should probably be implemented to close the file, or (__clone for example) should return false, or throw an exception.
I've also hinted at this in the beginning of this answer: what if I were to write some app that had to parse several files? Using your class, I'd have to create a new instance for each file. That's just adding pointless overhead. I'd propose you add a openFile method, that works similarly to the constructor (ideally accepting SplFileInfo and the like, too). This openFile method, then could look like this:

public function openFile($mixed)
{
    if ($this->fileHandle !== null && is_resource($this->fileHandle))
    {
        $this->fileName = null; //<<this is never used throughout your code!
        fclose($this->fileHandle);
        //and so on, re-initialize all properties
    }
    //add same if's and else's as in __constructor here
    return $this;
}

Now, I'll post this answer because it's gotten quite lengthy already. Meanwhile, I'll examing the groupByColumn method to actually get to grips with it... it's short, sure, but would you be able to maintain it 6 months from now? If yes: right... ;-P

Now the main function... not only is it a nightmare to read, it again fails to validate any of the params it received, and it contains bugs!
A line by line once-over:

public function groupByColumn ($groupColumn = 0, $rowLength = 1000, $seperator = ",")
{
    $currentRow = -1;//why, you don't need this
    $classes = array();//what do you mean "classes"
    while ($data = fgetcsv($this->fileHandle, $rowLength, $seperator))
    {//no need for the !== false
        $currentRow++;//
        if ($this->hasHeaderRow)//Why check this on each iteration?
            if ($currentRow < 1) continue;//ouch continue
        if (in_array($currentRow, $this->RowsToIgnore))
                continue;//ouch again
        //maintain this... good luck
        $classes[$data[$groupColumn]][] = array_filter(//should issue notice
            $data,
            function ($var) use ($groupColumn, $data)
            {//think Gloves (you're over-complicating)
                return $var !== $data[$groupColumn];
            }
        );
    }
    return $classes;
}

Now without too many words, I'll just re-write the same code to do what -I think- it is you're trying to acchieve

public function groupByColumn ($groupColumn = 0, $rowLength = 1000, $seperator = ",")
{
    $lines = array();
    if ($this->hasHeaderRow)
        fgetcsv($this->fileHandle,
                $rowLength,
                $separator);
    $count = 0;
    while ($data = fgetcsv($this->fileHandle, $rowLength, $seperator))
    {
        if (!in_array(++$count, $this->rowsToIgnore))
        {
            $idx = $data[$groupByColumn];
            unset($data[$groupByColumn]);
            if (!isset($lines[$idx])) $lines[$idx] = array();
            $lines[$idx][] = $data;
        }
    }
    return $lines;
}

Now not only is this code smaller, it's safer, it is also not producing notices, less resource hungry, and it is, IMO, a lot easier to read. It's not difficult to understand the code, but let me back my claims up:

safer: your array_filter was removing duplicate Values but if I were to group by a "column" that contained a number, and my data looked like this: 123,4364, foobar,123, I could be removing 2 values from the array. You only need to remove 1: the value associated with the group-by column, of which you have the offset. Using unset is faster, and safer
No notices: well, for each new $data[$groupByColumn] value, you need to create a new array. You never do so explicitly. $classes[$data[$groupByColumn]][]<-- the latter just assumes there is an array. If it doesn't exist, PHP will create one for you, but it will produce a notice, too, which slows you down.
less resources required: simply because I'm calling less functions and not using a lambda function (which, in PHP is an instance of the Closure class anyway). You create an instance on each iteration... calling a constructor each time... I use unset + the index of an array, which is a simple HashTable lookup internally.
Sure, PHP will probably optimize this, and create a single instance of Closure but this instance will be GC'ed once this method returns. So you're still creating instances each time this method gets called.

Well, that's my review, hope you find a thing or 2 useful in this verbal diarrhea. I've written this all in one go, off the top of my head, and I didn't check any code I posted here, so there might be some syntax errors (and grammar errors) in here, but hey...


User prompts for entering quiz questions

There are 2 problems that must be addressed first. Where did diff.choice come from, what is that? Second. What is the this.askForCategory() call? It sounds like exactly what addToQuestionToQbank() is doing. addToQuestionToQbank() does not do what it says, so I wonder what the real adding method looks like ....

Anyway, I would expect the calling code to look something like this:

public void newQuestion () {
    Question myQuestion = new Question();

    myQuestion.Question = this.askForQuestion();
    myQuestion.Answer = this.askForAnswer ();

    // here is where we call your code, refactored.
    myQuestion.category = this.multiChoicePrompt("Add Questions[1]Multiple Choice[2] Identification: ", 2);
    myQuestion.Difficulty = this.multiChoicePrompt("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: " ,3);

    this.addQuestionToQbank(myQuestion);
}

By passing the prompt as a parameter we can now refactor as you asked:

// this prompt designed specifically to pick from multiple choices
// note how the method name makes that comment irrelevant.
public int multiChoicePrompt(String askUser, int responseMaxValue) {
    System.out.println(askUser);

    int choice;
    boolean notValid = true;
    do{
        while(!input.hasNextInt()){
            System.out.println("Numbers Only!");
            System.out.print("Try again: ");
            input.nextLine();
        }
            notValid = false;
            choice = input.nextInt();
    }while(notValid);

    // assume numbered choices always start with "1"
    while(choice > responseMaxValue || choice < 1){
        System.out.println("Out of bounds");
        choice = input.nextInt();
        input.nextLine();
    }
    return choice;
}

The easiest way to "extract method" might be to physically move all that code to the new method and then recompile and let the compiler errors tell you what variables it doesn't "know"  - these are what you pass in as parameters.


Using JavaScript-bitwise AND and -bitwise NOT for setting a number to 0

Well, yes, num & (~num) does result in zero. Not much to review there. Seems you've solved the task you were given.

Of course, one might as well return/assign a literal zero, and skip two bitwise operations.

There's one JavaScript-specific caveat to all of this though: JavaScript's bitwise operations only work on 32-bit integers. However, that's not a datatype that usually exists in JavaScript: Numbers in JavaScript are all IEEE 756 64-bit floats.

The moment you use a bitwise operator on them, however, they are converted (with potential loss) to 32-bit ints, and the result then represented as a float again.

Of course, that's all academic, since whatever int representation you get, a & (~a) will result in zero.

But other bitwise operations can give strange results. For instance, OR'ing with zero should just return the number unaltered, but if the number's too large, its most-significant bit will end up being interpreted as the sign bit as the internal 32-bit conversion is always signed. So you get things like this:

2147483647 | 0 // => 2147483647
2147483648 | 0 // => -2147483648

The second number is large enough to flip the high bit, and thus it's interpreted as negative.

Anyway, point is: Yes, a & (~a) will result in zero, for any value of a, despite JS's internal strangeness, because whatever it converts the input to, it also negates. But it's a special case; in other contexts bitwise operations in JS may be treacherous.


Sorting entities by Z in every call to Draw

Not sure about Where

Where method (if applied to IEnumerable<T>) is O(N) operation, and it's a lazy operation so it will do the filtering while consumer reads the result.

  Should I be worrying about this call at all?

The best way to answer this question is to measure the performance and see if it satisfies you. If not - then start thinking about caching results and refreshing them instead of calculating from scratch.

  If so, how can I reduce the runtime complexity, and/or cache the results reliably?

It's hard to suggest good solution based on the information you've provided... Will the number of entities change over time? Can they "loose" SpriteComponent?

Assuming that the number of entities is the same and only Z will slightly change you can cache the sorted list from previous run, and apply TimSort or Insertion sort (you would need to implement it yourselves or grab from Wikipedia) to nearly-sorted list.


Your program is easy to read and does all the necessary input validation. That's good.

The error messages should be more helpful. If the user enters an invalid operator, you should tell them which operators are valid:

print(f'Please enter a valid operator: {' '.join(ops)}\n')

Every use of eval is dangerous. If you pass unvalidated input to it, users might be able to run arbitrary Python code. You currently do the validation in verify and the actual calculation in calc. That's nicely separated, but it can also lead to a situation where you later call calc by accident with unvalidated input. To avoid this, most calculator programs use a dictionary of operators:

binops = {
    '+': lambda a, b: return a + b,
    '-': lambda a, b: return a - b,
    # and so on
}

try:
    return binops[op](x, y)
except KeyError, e:
    print(f'Invalid operator {op!r}, valid operators are {sorted(ops.keys())}')

One unfortunate thing about the above code is that ops.keys() returns the operators in an unspecified order. Therefore I had to add the sorted call.

Each of your functions calls the continuation function at the end. When you try a long session with the calculator (about 5000 calculations), it will raise an exception. Whenever a function is called, Python remembers where it was called from, and it can remember only a few nested function calls. Therefore it is more common to use while loops for representing repetition. See https://stackoverflow.com/q/1359197 for more details.

As a user of the calculator, I don't like to enter the numbers and operators separately. As the next step the calculator should allow inputs like 3+5 and 7 - -9 and +7--9. You can do this by using regular expressions.

The current code asks many questions individually. Instead of asking whether to reuse the result from the last calculation, you could print the result in the form ans1 = 8 and allow the user to write expressions like ans4 * ans5. A calculator session might then look like:

> 123
ans1 = 123

> 456
ans1 = 456

> 3 + ans1
ans3 = 126

> ans3 + ans3
ans4 = 252

> result = ans4
result = 252

> result + result
ans5 = 504

This way the calculator remembers all previous results, and by using the = operator, you can name individual results and refer to them via that name, just like variables in Python. All you need for this is a dictionary and a counter (for the automatic variable names like ans4):

vars = {}
ans = 0

def store_var(name, value):
    vars[name] = value

def store_auto_var(value):
    global ans
    ans += 1
    name = 'ans' + ans
    vars[name] = value

These are the basic building blocks for building a really powerful calculator.


Table printing code using a fluent interface

Which is easier to read? How would you improve either of them? Do either paint us into a corner?

I love A. It is simple, clear, concise and meaningful. B is the same as A but with one major difference: the method addLine was cut into several small pieces.

In my opinion, the issue with B is that it extracts from one meaningful method (adding a line) a lot of small awkward methods, and in the process completely obscuring the real task at play: none of those methods are really reusable and probably none of those methods would make sense in a context other than addLine (think removeLine, withColor, withFont...).

Think back and focus on what you want the code to do. We have addLine and we expect it to add a line to our columns. Clearly, there are several code paths to deal with: notably, the first case is to determine the length of each line, etc. But a method can have 30 lines of code without it doing too much work, because it wouldn't make sense to cut that work in pieces: they are all part of the same unit of work. All of the pieces are needed to make the lot work, and they need to be called and assembled in a specific way that is unique to adding a line. In that sense, having multiple methods may be fragile because they are coupled to each-other.

Of course, if that work would require lots of lines of code, you can move part of in a dedicated method. Additionally, work that requires few lines of code could also be extracted in multiple utility methods.

The point is to find a balance between small, easy to read methods and logical unit of work. Part of it can also rely on opinions — both approaches are correct and none of them are fundamentally bad.

  Any multithreaded concerns?

Both approaches won't work in a multi-threaded environment because Columns isn't thread-safe: it has state, for example with List<List<String>> lines and List<Integer> maxLengths. One possible way to make it thread-safe would be to return a new Columns instance each time addLine is called (for that, we can add a private constructor taking lines, maxLengths and numColumns), and making Columns immutable in the process (do not update the fields of this but use the new values to construct the new instance and return it).

  How could it be made extensible?

It is already extensible enough. The data structures for Columns are kept hidden; I can see a removeLine, withColor (setting a color for each column), withFont (setting a font for each column) added without refactoring the current code.

  Would the getThis() trick help here or is it a bad idea?

Do you really intend to have classes inhering from Columns? Keep it simple, you most likely aren't going to need it.

Other comments on the code, applicable to both examples:

You are throwing an IllegalArgumentException in case a line with a different length is added:

throw new IllegalArgumentException();

That's great, but consider adding a message so that it is clearer for the user what went wrong. IllegalArgumentException with no message is not really helpful.
Both in toString and in pad, you are concatenating String with the += operator. This can lean to serious performance issues. When used inside a loop, you should always use a StringBuilder (or a StringJoiner).


Array-based queue implementation using C

if (isEmpty(&pQueue)) is wrong. It should be pQueue. You also need to have the prototype in scope before you use it. Put int isEmpty(Queue* pQueue) at the top of your file.


I see a few problems, mostly similar to my remarks in a previous answer:

Your definition of head' is unconventional.  Its definition should be

head' :: [a] -> a
head (x:_) = x

Furthermore, your problematic definition of head' is making you define flatten'.  If you fix head' as suggested above, thenflatten' becomes unnecessary.
The definition of tail' is too complicated.  It could just be

tail' :: [a] -> [a]
tail (_:xs) = xs

For clarity, I would rename the parameter to transpose' from ys to rows.
The base case of transpose' is too complicated.  Also, it can be done using pattern matching.

transpose' [[]]    = []
transpose' [[], _] = []

Prefer x:xs to [x] ++ xs.
Scope your helper functions using where.

Here's what I came up with:

transpose' :: [[a]] -> [[a]]
transpose' [[]]    = []
transpose' [[], _] = []
transpose' rows    = (map head' rows) : transpose' (map tail' rows)
  where
    head' (x:_) = x
    tail' (_:xs) = xs


I realize that you were only supposed to implement the display method, but, the rest of the queue is code that can be significantly improved too.

Your queue is a fixed-capacity queue. There is nothing wrong with that (except that the array should be declared as final ... ), and, it actually makes some things easier.

Like, one of the most complicated things with a circular buffer/queue is to manage whether the queue is full, or empty. at both times, the rear and front cursor are the same. There is a really nice way to solve that problem, which is to not use a rear pointer at all, and to only use the front, and size.

Now, your code has the front, rear, and size variables, and it sometimes uses the rear variable, and other times uses the size... and this leads to confusing code. The thing is, that you can easily calculate the rear from the front and size... or, alternatively, you can calculate any one of those three variables from the other two. Bottom line, is you only need two of them, and keeping the size makes other things easy.

Here's your code, stripping out the entire 'rear' variable.... Other things I did are:

removed the maxSize variable since the queArray's length is the same.
added validation to the insert/remove methods.
some formatting changes
use modulo % operator to 'wrap' indexes nicely in the new adjust() method.

Notice how the display method is now really simple:

public void display() {
    System.out.println("First Inserted Item to Last Inserted Item");

    if (isEmpty()) {
        System.out.println("Queue is Empty!");
    } else {
        for (int i = 0; i < nItems; i++) {
            System.out.println(queArray[adjust(front + i)]);
        }
    }
}

The full code is:

import java.util.NoSuchElementException;

public class Queue {

    private final int[] queArray;
    private int front;
    private int nItems;

    public Queue(int s) {
        queArray = new int[s];
        front = 0;
        nItems = 0;
    }

    /*
     * Simple method converts an un-wrapped index to a wrapped index.
     */
    private final int adjust(int index) {
        // add the array length to make things like adjust(-1) work.
        return (index + queArray.length) % queArray.length;
    }

    public void insert(int j) {
        if (isFull()) {
            throw new IllegalStateException("Queue is full");
        }
        queArray[adjust(front + nItems)] = j;
        nItems++;
    }

    public int remove() {
        if (isEmpty()) {
            throw new NoSuchElementException("Queue is empty");
        }
        int removed = queArray[front];
        // for an object-based queue, this would
        // be the same as setting it to null
        queArray[front] = 0;
        front = adjust(front + 1);
        nItems--;
        return removed;
    }

    public int peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("Queue is empty");
        }
        return queArray[front];
    }

    public boolean isEmpty() {
        return nItems == 0;
    }

    public boolean isFull() {
        return nItems == queArray.length;
    }

    public int size() {
        return nItems;
    }

    public void display() {
        System.out.println("First Inserted Item to Last Inserted Item");

        if (isEmpty()) {
            System.out.println("Queue is Empty!");
        } else {
            for (int i = 0; i < nItems; i++) {
                System.out.println(queArray[adjust(front + i)]);
            }
        }
    }

}


How can I improve the following stored procedure?

Here are some comments in no particular order:

Your CATCH block - including comments - is a copy and paste from the documentation. While it's always good to read the documentation, please remember that the examples are there to illustrate specific features and you shouldn't assume that they're usable as-is in production code
If an error occurs in the TRY block, your CATCH block commits if possible anyway, is this what you intended? XACT_STATE() tells you that the transaction can be committed, not that it should be. See this SO question for more information.
Your CATCH block doesn't examine or log the error message (using ERROR_NUMBER() and similar functions), so if an error does occur you will have no idea what it was
Always list all column names in an INSERT; this gives you some security if the table structure changes
You cannot compare NULL values with the standard comparison operators, you need to write IF @URI IS NULL instead
Always use schema names to reference objects in code
Using BEGIN and END to wrap the entire stored procedure body is not required but usually good practice, otherwise it's easy to forget where the procedure ends and accidentally add some code that you didn't mean to
Most procedures should SET NOCOUNT ON at the beginning

And please always mention your SQL Server version (2005, 2008, 2008R2, 2012) and edition (Standard, Enterprise, Express) because that determines which language features are available.


Your simulation assumes the human is playing randomly. This is not realistic. Consider the case when it's the human's turn at 19. A sensible player will certainly play 1 to force a win, but a random player has only 1/3 probability of doing the same. The simulation teaches the AI that the computer has an advantage in that situation, which is wrong.

If the rules of the game were changed so that every move must be made at random, your algorithm should be able to predict each player's probability of winning at any point. However, that would be a different game: a game of chance.

There's also a simple bug: you generate random moves by randint(0,3). This should of course be randint(1,3) because 0 is not a valid move.


Minimum number of parentheses to be removed to make a string of parentheses balanced

for of not for in

I have noticed that on occasion you use the indexing for in Try to avoid using this loop as it can be problematic if the object you iterate has inherited properties not set as enumerable = false

Use the values iterator for of as it avoids the problems that come with for in. It also has the benefit of not needing to index the object for the value

Use const

When using either for of and for in and you don't intend to change the value or key use a const  eg for(const i in brackets) or for(const char of brackets)

Note That you can not use a const in for(;;) loops but let is allowed. for(let i=0;i<10;i++). The reason is that even though a new instance of i is created each iteration and assigned the value of the previous i, the last loop expression i++ is applied at the bottom of the loop block and thus does not work for constants.

Simplify

Strings are iterable objects so you can avoid the need to use String.split and use the more succinct spread ... operator. eg [...string] is the same as string.split("");

Complexity

Your imperative function is \$O(n)\$ time and \$O(1)\$ space.
Your declarative (you call functional) function is \$O(n)\$ time and \$O(n)\$ space.

Ambiguity

The question does not indicate if the string will contain characters other than "()", yet the example shows only "()" and your solutions count characters other than "()" as ")" so will assume that the input string contains only "()"

Solutions

Imperative

function balanced(str) {
    var open = 0, closed = 0;
    for (const char of str) { char === "(" ? open++ : (open ? open-- : closed++) }
    return open + closed ;
}

Declarative

function balanced(str) {
    const open = counts => (counts[0]++, counts);
    const close = counts => (counts[0] ? counts[0]-- : counts[1]++, counts);
    const counter = (counts, char) => char === "(" ? open(counts) : close(counts);
    const sum = arr => arr[0] + arr[1];
    const chars = str => [...str];
    return sum(chars(str).reduce(counter, [0, 0]));
}

Functional

function balanced(str) {
    const counter = ([open, closed], char) => {
        char === "(" ? open++ : (open ? open-- : closed++);
        return [open, closed];
    }
    const sum = (sum, val) => sum += val;
    return [...str]
       .reduce(counter, [0, 0])
       .reduce(sum, 0);
}

or

function balanced(str) {
    const counter = ([open, closed], char) =>
        (char === "(" ? open++ : (open ? open-- : closed++), [open, closed]);
    const res = [...str].reduce(counter, [0, 0])
    return res[0] + res[1];
}


Making pixels of RGB barcode suitable for scanning

This:
static uint8_t rgb[3];
return rgb;

is a problem. Two different callers assuming to have two different copies of the return array will actually only have one, and that breaks re-entrance. Better off to return by value instead of return by reference in this case - particularly if you make a utility struct. A common pattern is to union over a three-element array and a nested struct of red, green and blue components. To ensure that this is valid, you'll need to tell your compiler to use tight packing, typically with #pragma pack. If you have misgivings on the portability of this approach and you need to support multiple exotic compilers, you'll need to ditch the union and instead write a conversion function.
bind and unbind can both be marked static since they're in the same translation unit.
The only other minor thing I see here is that two-space indentation is somewhat non-standard, and 4-space will be more legible.


Unity3D script for controlling a character

You don't need this directive in the code you have given us.

using System.Collections;

It's conventional to use Pascal casing to name private constants in a file, so

private const float minSpeed = 1f;

private const float maxSpeed = 5f;

private const float minJump = 1f;

private const float maxJump = 10f;

should be:

private const float MinSpeed = 1f;

private const float MaxSpeed = 5f;

private const float MinJump = 1f;

private const float MaxJump = 10f;

In C# it's convention that private instance fields start with an underscore.

[SerializeField]

private float _speedModifier;

[SerializeField]

private float _jumpModifier;

I would also consider writing 'getter' and 'setter' methods for each field instead of serializing them.

I believe public properties also use Pascal case conventionally.

public OnGroundStatus onGroundStatus

{

    get { return _onGroundStatus; }

}

public OnWallStatus onWallStatus

{

    get { return _onWallStatus; }

}

If you preferred you could use auto-properties to set these instead.

public OnGroundStatus OnGroundStatus { get; private set; }

public OnWallStatus OnWallStatus { get; private set; }

I don't see a usage of these properties in your code.

private bool isHorizontalStill

{

    get { return (rigidbody2D.velocity.x == 0); }

}

private bool isVerticalStill

{

    get { return (rigidbody2D.velocity.y == 0); }

}


Using extdebug to display where a function was defined

function where() is not the right syntax and only works in some versions of bash and zsh (and a few others). It is better to write either function where or where().

shopt | grep -q extdebug is expected to always return 0 for the exit code, since extdebug is always in the output of shopt whether it's turned on or off, which is not really your intention when you test for its status. Instead, you should write shopt -q extdebug.

Looking at ! ((extdebug)) && shopt -s extdebug, I don't know if ! ((extdebug)) evaluates to true or false. It turns out it is true when extdebug equals 0 and false otherwise. This runs in counter to how the exit status of a shell command works: 0 for success and non-zero for failure. Both shopt -q extdebug and shopt | grep -q extdebug return 0 (success) if extdebug is, respectively, set and present in the output of shopt, and 1 otherwise. So you'd be setting extdebug when it is already set, and unsetting it when it is already unset. It is better to be explicit and write ! shopt -q extdebug && shopt -s extdebug instead.

It's not clear to me why info=$(command -V "$cmd") does not suffice. You should document cases where this messes up and piping to head -n 1 is needed. Though probably a tiny bit less portable, info=$(type "$cmd") works fine, too, and is shorter to type (no pun intended) and conveys the intent better.

You don't have to limit to processing only the first argument passed to this function, just as command does not process only its first argument. The change required is trivial. I include the whole modified function below, with improved formatting:

function where
{
    while (( $# > 0 ))
    do
        cmd=$1
        info=$(type "$cmd")
        case $info in
            *function*)
                #! shopt -q extdebug && shopt -s extdebug
                shopt -s extdebug
                declare -F "$cmd"
                shopt -u extdebug
                #shopt -q extdebug && shopt -u extdebug
                ;;
            *)
                echo "$info"
                ;;
        esac
        shift
    done
}

The shell option check is superfluous, so I've commented that out. Now the output would look like:

$ where ls l bad where
ls is /bin/ls
l is aliased to `ls -Al --color=auto'
bash: type: bad: not found

where 6 /home/harleypig/projects/dotfiles/.bash_sources.d/tools

The same could probably be done for alias, but this is a much more involving process. You probably need to define a function named alias that calls the builtin alias in a dotfile that is sourced first, utilize caller, do some arithmetic to get the right line number and save the result in an associative array. I'll post an update when I could get it to work.

Addendum

I have a proof of concept to do the same for alias that roughly works though not always 100% accurate:

declare -A alias_info

function alias
{
    builtin alias "$@"
    while (( $# > 0 ))
    do
        case $1 in
            *=*)
                IFS='=' read alias_name alias_command <<< "$1"
                read line_no_in_sub caller_name source_file <<< "$(caller 0)"
                if [[ -n "${source_file}" ]] # alias definition in sourced file
                then
                    # line_no_in_sub is the line number relative to the function/script block,
                    # so we have to add to it the line number of the function.
                    shopt -s extdebug
                    func_line_no=$(awk '{print $2}' <<< "$(declare -F "${func_name}")")
                    shopt -u extdebug
                    alias_info[$alias_name]="$(( line_no_in_sub + func_line_no )) ${source_file} ${alias_name} is aliased to \`${alias_command}'"
                else # alias definition from terminal
                    alias_info[$alias_name]="$(caller) $0 ${alias_name} is aliased to \`${alias_command}'"
                fi
                ;;
            *)
                ;;
        esac
        shift
    done
}


Infinite producer using BlockingCollection

Looks Good To Me.

I was initially confused by this code, so I would want to rename the collection from UniqueStrings to something like UniqueStringBuffer, to make the purpose clear. To me, "buffer" says "I will use this object to hold data temporarily, because the data is consumed at a different rate than it is produced" - which is exactly what you have here.

If you want to take the next step in that direction... I would note that a BlockingCollection can be used for many things, but the only method that should be called on your instance is Take. For that reason, you may want to encapsulate this code inside of a class, with Take (or perhaps something more explicit like GetNext) as its only public method. That would serve the dual purpose of preventing misuse and, again, making the purpose clear. Whether or not you want to go that far is up to you.


What is a better approach for operating on an arbitrary map value in Scala?

myLookup.get(index).orElse(myLookup.get(static_value)).map { doSomeCall(_).makeFooBar }

From the Scala doc of Option.map:

  Returns a scala.Some containing the result of applying f to this scala.Option's value if      this scala.Option is nonempty. Otherwise return None.

This is exactly the type of task functional programming is made for. This simple chaining of Options using map is related to the fact that Option is a monad.


It's kinda hard to make it "more elegant", but it can certainly be made more correct.

Since you use Math.round, you can get a time like "3:60 PM" if you pass it 15.999. And I'm preeeetty sure there's no such thing.

There's also another bug. If you pass a value like 0.5, you should get "12:30 AM". But you don't. You get "0:30 AM".

And some nitpicking: First off, info is not a very descriptive name. It looks like you're trying to format a number of hours, with minutes as the decimals, so hours would be a better name. (Edit: or better yet fractionalHours as rolfl suggests, and which I forgot to credit.)

Also, instead of using parseInt (which is meant to turn a string into an integer), use Math.floor, which is what you actually mean: The number without any decimals. For the minutes, you could use the modulo operator (%) to get the remainder of dividing by 1 (i.e. the decimals) instead of subtracting. But either one works.

By the way, even if your input is a string like "12.3231" JavaScript's type coercion will treat it as a number, so you don't really need Number() anywhere, but it's fine to add it.

You can also do something slightly tricky by using modulo 12 on the hours, and default to 12 if the result it zero. That fixes the 0/12 bug mentioned above.

Also, fewer lines do not make things better/faster/more elegant. In this case, it just hurts readability. So use some linebreaks instead of having a line like if (hrs >12) { hrs = hrs - 12; suffix='PM'; }.

Lastly, use some indentation. It may just be a copy/paste thing when you created the question, but still.

I might do something like this, first converting everything to minutes and rounding that, then breaking it into hours and minutes afterward:

function convertToHHMM(fractionalHours) {
  var totalMinutes = Math.round(fractionalHours * 60) % (24 * 60),
      hours = Math.floor(totalMinutes / 60) % 12 || 12,
      minutes = totalMinutes % 60,
      suffix = totalMinutes >= 12 * 60 ? 'PM' : 'AM';

  if(minutes < 10) minutes = '0' + minutes;

  return hours + ':' + minutes + ' ' + suffix;
}

totalMinutes rolls over after rounding, so passing in 23.999 is equivalent to passing in 0, and 27 becomes 3, etc.
hours also roll over but start at 12 instead of zero, then 1, 2, 3 and so on.
minutes should be straight-forward, and
suffix basically looks at whether the totalMinutes are greater than or equal to noon-in-minutes.

Snippet with some test cases below (format borrowed from rolfl).

function original(info) {
var suffix='AM';
var hrs = parseInt(Number(info));
var min = Math.round((Number(info)-hrs) * 60);
if (hrs >12) { hrs = hrs - 12; suffix='PM'; }
if (min < 10) {min='0'+min;}
return hrs + ':' + min + ' ' + suffix;
}

function reviewed(fractionalHours) {
  var totalMinutes = Math.round(fractionalHours * 60) % (24 * 60),
      hours = Math.floor(totalMinutes / 60) % 12 || 12,
      minutes = totalMinutes % 60,
      suffix = totalMinutes >= 12 * 60 ? 'PM' : 'AM';

  if(minutes < 10) minutes = '0' + minutes;

  return hours + ':' + minutes + ' ' + suffix;
}

var testCases = [
  ["12:00 AM", 0],          // midnight
  ["12:30 AM", 0.5],
  ["1:00 AM",  0.99999999],
  ["11:30 AM", 11.5],
  ["12:00 PM", 11.9999999], // noon
  ["12:00 PM", 12],
  ["11:30 PM", 23.5],
  ["12:00 AM", 23.9999999],
  ["12:00 AM", 24],
  ["1:00 AM",  25]
];

var data = "
";
data += "
Input	Expected	Review func	Original func
";
for(var i = 0, l = testCases.length ; i < l ; i++) {
  data += "
";
  data += "" + testCases[i][1] + "	";
  data += "" + testCases[i][0] + "	";
  data += "" + reviewed(testCases[i][1]) + "	";
  data += "" + original(testCases[i][1]) + "	";
  data += "
";
}
data += "
";

document.body.innerHTML = data;
body { font-family: monospace }
table { border-collapse: collapse }
td, th {
  padding: 0.2em 0.5em;
  border: 1px solid #ccc
}


Direct to another folder with .htaccess file

The line you are using is telling the engine, redirect everything to the following URI. The reason for this is that you are using the pattern matching wildcard (.*).

The parenthesis is used for creating groups, the dot is telling the engine that every character is accepted and the star symbol is telling the engine that it can be of unlimited length. By using the forward slash followed by another wildcard group, you are redirecting every URI request to the following URI "https://google.com/release/theme/5.0.1/$1/$2".

Instead of using

RewriteRule ^(.*)/(.*) "https://google.com/release/theme/5.0.1/$1/$2" [R=302,L]

You should replace it with the following line

RewriteRule ^v5/(.*)$ https://google.com/release/theme/5.0.1/$1 [R=302,L]

Why append the 'v5' before the caret symbol (^)?
The caret symbol matches the start of a string. In our case, the string is the version.

Source : https://www.searchenginepeople.com/blog/htaccess-redirect-rewrite-rules.html


IMO this a strange aproach. One needs to first call GetValue() to be able to set a value by using an eventhandler. I would expect from such an ObjectCache to provide a constructor which takes a value as parameter too.

In addition I would add a property to ObjectCacheEventArgs<T> signaling a state, for instance an enum having the members ChangeValue, KeepAlive and SkipValue to be set by the handler of the event.
If this value is e.g set to ChangeValue then the _value should be changed. If it is set to KeepAlive the LastUpdate should be set to DateTime.Now. And for SkipValue you would need to add another var indicating that the value is skipped and set _value to default(T).

It isn't obvious from a caller side of view that you have to add an eventhandler for that event. IMO this is a bad sign which one would maybe notice first at running the code. Such behaviour shouldn't be wanted and isn't expected. If one does not add an eventhandler he expects that he just don't get notified if this event happens.


ConsoleWorker update console timer with how long application has been open

I think the first thing that you should do is create one more variable for Faze.getServer().getServerInformation().getProjectName() don't type that twice, and please don't make me read it twice.

I would also use String Interpolation (if you can) it makes this look a little cleaner.

You should pull out the stuff that is the same from the if/else statement and then use a single if statement if you want to add seconds onto the console title string, and then you can create the variable in one declaration minimizing the lines of code.

Here is what I have:

if (Faze.getServer().getServerInformation().hasStarted())
{
    if (StaticSettings.advancedLoggingWhenDebugging && Debugger.IsAttached)
        classLogger.Info("ConsoleWorker has elapsed -> " + DateTime.Now.ToLongTimeString());

    TimeSpan serverUptime = DateTime.Now - Faze.getServer().getServerInformation().getStartedTime();

    var projectName = Faze.getServer().getServerInformation().getProjectName();

    var consoleTitleString = $"{projectName} / {serverUptime.Days} " +
                         $"day{(serverUptime.Days != 1 ? "s" : "")}, {serverUptime.Hours} " +
                         $"hour{(serverUptime.Hours != 1 ? "s" : "")}, {serverUptime.Minutes} " +
                         $"minute{(serverUptime.Minutes != 1 ? "s" : "")}";

    if (StaticSettings.includeSecondsInUptimeString)
    {
        consoleTitleString += $" and {serverUptime.Seconds} second{(serverUptime.Seconds != 1 ? "s" : "")}";
    }

    System.Console.Title = consoleTitleString;
}

Another change that I might attempt would be to minimize some typing by creating an object from Faze.getServer().getServerInformation() so that I don't have to type that 3 times in my code,  it might look something like this.

var serverInfo = Faze.getServer().getServerInformation();
if (serverInfo.hasStarted())
{
    if (StaticSettings.advancedLoggingWhenDebugging && Debugger.IsAttached)
        classLogger.Info("ConsoleWorker has elapsed -> " + DateTime.Now.ToLongTimeString());

    TimeSpan serverUptime = DateTime.Now - serverInfo.getStartedTime();

    var projectName = serverInfo.getProjectName();

    var consoleTitleString = $"{projectName} / {serverUptime.Days} " +
                         $"day{(serverUptime.Days != 1 ? "s" : "")}, {serverUptime.Hours} " +
                         $"hour{(serverUptime.Hours != 1 ? "s" : "")}, {serverUptime.Minutes} " +
                         $"minute{(serverUptime.Minutes != 1 ? "s" : "")}";

    if (StaticSettings.includeSecondsInUptimeString)
    {
        consoleTitleString += $" and {serverUptime.Seconds} second{(serverUptime.Seconds != 1 ? "s" : "")}";
    }

    System.Console.Title = consoleTitleString;
}

I don't see anything that would change the private consoleWorkerInterval to anything other than a value of 1000 so I really don't see a need for this

if (StaticSettings.includeSecondsInUptimeString && consoleWorkerInterval < 1000)
            consoleWorkerInterval = 1000;

Resharper also noted that you don't need the Redundant explicit delegate creation on this line of code

consoleWorkerTimer = new Timer(new TimerCallback(timerElapsed), null, TimeSpan.FromMilliseconds(consoleWorkerInterval), TimeSpan.FromMilliseconds(consoleWorkerInterval));

you don't need to create a new TimerCallback because you are creating this Timer and giving it a method to call when the time passes, so this line of code can be shorter as well

consoleWorkerTimer = new Timer(timerElapsed, null, TimeSpan.FromMilliseconds(consoleWorkerInterval), TimeSpan.FromMilliseconds(consoleWorkerInterval));


The statement bit_11 = '{0:b}'.format(T)[-11] actually extracts bit 10, because the convention is to number bits from zero, while indexing from the end of string starts at [-1].
Performing bit manipulations in string format is clunky. Use bitwise operators instead. For example, to extract bit 10: T >> 10 & 1
Opening a file by a with statement ensures it will be closed. You can omit the close calls.
Strings have a zfill method that does the same as for i in range(16 - len(K)): K = '0' + K


C# asynchronous tasks training (turn-based simulation)

The Wait call is tricky.

It throws by default AggregateException not OperationCanceledException.
If you provide the cancellationToken to the Wait then it will throw an OperationCanceledException.
The biggest problem with this approach is that it cancels only the Wait not the underlying task.

Please read this article for more details.

So, if we switch to async main then the application will not stop after user cancellation:
static async Task Main()
{
    var gameTurnsController = new GameTurnsController();
    var userRequestedCancellation = new CancellationTokenSource();

    try
    {
        _ = Task.Run(() =>
        {
            Console.WriteLine("Please press any key to cancel");
            Console.ReadKey(true);
            userRequestedCancellation.Cancel();
        });

        await gameTurnsController.PassTurns(TimeSpan.FromSeconds(1), userRequestedCancellation.Token);
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine(Environment.NewLine + "Cancelled.");
        Environment.ExitCode = 0;
    }

    Console.WriteLine("Execution finished.");
}

Because the underlying LongRunningOperation will not terminate.

(Let me use Thread.Sleep(5000) to simulate complex CPU bound operation)

private async Task<long> LongRunningOperation(CancellationToken cancellationToken)
{
    return await Task.Run(() =>
    {
        long result;
        Thread.Sleep(5000);
        return result;
    }, cancellationToken);
}

If I run this app and I press any key then it will not cancel the LongRunningOperation method that's why the output will be the Execution finished..

How to fix it?
By passing all the way long the cancellationToken:
private async Task<long> LongRunningOperation(CancellationToken cancellationToken)
{
    var job = Task.Run(() => LongRunningOperationInternal(cancellationToken), cancellationToken);
    return await job;
}

private long LongRunningOperationInternal(CancellationToken cancellationToken)
{
    long result = 1;
    for (int i = 0; i < 5; i++)
    {
        cancellationToken.ThrowIfCancellationRequested();
        Thread.Sleep(1000);
    }

    return result;
}

If need to do graceful cancellation then consider to use the following pattern:
if(cancellationToken.IsCancellationRequested)
{
  //TODO: clean up whatever is needed

  cancellationToken.ThrowIfCancellationRequested();
}

TL;DR: You need to check the cancellationToken at milestones/checkpoints to be able to truly cancel the whole application.

Might be an interesting read: How to can non-cancelable async operations


Linked list vs array performance for RemoveAt() function

If you time just removing the item from the list, it probably will be faster.

What you're timing is traversing the list to the correct point, then removing the item. Apparently, traversing the list is slow enough to (more than) make up for the time you're saving on the removal itself.

Although it was written about C++, most of the points Bjarne raises in his video on the subject apply about as well to most other languages.


Return a path between graph nodes using depth-first search redo

Honestly your code is pretty good.

There are however two things that I would change:

self.nodes to be a dictionary rather than a set. This allows you to remove the need for get_node, and changes it to \$O(1)\$ from \$O(n)\$.
In get_path you pop from one stack and append to another. Instead of doing this manually I'd use the built-in list slicing notation, stack[::-1].


First simple program; counting button presses

The first thing that needs to be addressed is the try-catch block.

Without (for now) addressing whether or not you're taking the best approach for this sort of persistent data, the fact of the matter here is that there's not a single exception that your try-catch block is going to catch.

In Objective-C, we don't use try-catch blocks all that much, and they are reserved for behavior that is truly, truly exceptional.  Generally speaking, you should almost never be using them, particularly at such a high level of development.

The last argument of the stringWithContentsOfFile:encoding:error: method is reserved for sending a NSError ** variable.  A pointer to a pointer.

If there's some sort of problem reading the file, no exception is thrown.  Instead, the method returns nil and the error variable, if you've sent a pointer to one, is set to an NSError object that describes the problem in incurred.

Internally, the method quite likely uses try-catch blocks.  And if you're developing some framework code, then you might use a try-catch block within a method if you're trying to catch some truly exception problem, but these cases are extraordinarily rare.  And what should your catch block look like in these cases?  Almost always, the catch block in an Objective-C method should look something like this:

@catch (NSException *exception) {
    // build an NSError object
    // assign the pointer to pointer you took as a method argument to point to this object
    return nil;
}

The only time your @catch block should look differently is if you can continue to execute code despite the exception... but as I said, Objective-C exceptions are reserved for truly exceptional behavior and it's extraordinarily unlikely that one will be thrown and you'll be able to continue with the method.

So instead of the try catch block, your code should instead look something more like this:

NSError *error;

NSString *contents = [NSString stringWithContentsOfFile:filePathCount encoding:NSUTF8StringEncoding error:&error];
self.count = [contents integerValue];
lastPress = [NSString stringWithContentsOfFile:datePath encoding:NSUTF8StringEncoding error:&error];

if (!error) {
    self.buttonCount.text = [NSString stringWithFormat:@"%i", self.count];
    self.buttonDate.text = lastPress;
} else {
    self.count = 0;
    lastPress = @"Never pressed!";
}

The NSError objects will tend to contain extra information about exactly what sort of error was encountered, but in many cases, simply checking whether or not it was set it more than enough.

Now, as for this idea of manually writing to file... I mean ultimately, it's just not going to be the best.  The only time writing plain text to a file is recommended would be we you need to generate a plain .txt file for use outside your app.

Otherwise, there are just generally better options available.

For something as simple as this, persisting a single variable across multiple sessions, we can simply use NSUserDefaults.  At the end of the, NSUserDefaults actually is writing data to a file, however it's an extremely efficient way of doing it and it can be done in a very clean and concise way.  Accessing the data stored in NSUserDefaults is so efficient by the way, that it's not really necessary to have a separate local/instance variable for keeping track of the current count.  We can read/write from/to NSUserDefaults instantly.

First, some groundwork.  Let's define some constants for our NSUserDefaults keys, and write a method that will handle updating our labels:

NSString * const kButtonCounter = @"DefaultsCounterKey";
NSString * const kLastCountDate = @"DefaultsDateKey";

- (void)updateLabels {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSInteger count = [defaults integerForKey:kButtonCounter];
    self.buttonCount.text = [NSString stringWithFormat:@"%l", (long)count];

    NSDate *lastPress = [defaults objectForKey:kLastCountDate];
    NSString *dateString;
    if (lastPress) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm 'on' MM-dd-YYYY"];
        dateString = [dateFormatter stringFromDate:lastPress];
    } else {
        dateString = @"Never pressed!";
    }
    self.buttonDate.text = dateString;
}

In viewDidLoad, we can check whether or not an object exists for the kLastCountDate key.  If it doesn't, the buttons never been pressed before, and we should set up our kButtonCounter so that we can properly display 0 for the counter.  Otherwise, we should have good values for both keys.  Once we've done this, we simply call the updateLabels method we've already written:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![defaults objectForKey:kLastCountDate]) {
        [defaults setInteger:0 forKey:kButtonCounter];
    }

    [self updateLabels];
}

In the method handling the button press, it's as simple as updating the information in NSUserDefaults, and then refreshing the UI:

- (IBAction)pushButtonPressed:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:[NSDate date] forKey:kLastCountDate];

    NSInteger newCount = [defaults integerForKey:kButtonCounter] + 1;
    [defaults setInteger:newCount forKey:kButtonCounter];

    [self updateLabels];
}


The first thing I would do is assign those strings to constants since they will never change throughout the life of the program.
Also, I'm not sure why you have to clear the errors out when you validate this part of the model. When I run valid? on a model, personally I would like to see ALL of the reasons that the model isn't valid.

class InvitationConfirmationValidator < ActiveModel::Validator
  def validate(record)
    invitation = Invitation.find_by_url_suffix(record.id)
    return record.errors[:base] << MISSING_INVITE_MESSAGE unless invitation
    return record.errors[:base] << MATERIALIZED_INVITE_MESSAGE if invitation.materialized?
  end
end


Your connection string is actually a private class member. I would probably put private keyword explicitly to make it clear.

connString is going to be initialized each time the class instance is created. But the connection string is not going to change in run time so it worth to make connStrint a static member.


Your implementation

Your implementation is mostly pretty good.  I'd just make a few minor changes:

int temp should be declared in the tightest scope possible — namely, inside the if block.  Localizing the variable further makes it harder to misuse and easier to understand.  I'd also rename temp to swap to make its purpose clearer.  (Naming a variable temp is usually a bad idea, in my opinion.)
int temp is at the wrong level of indentation.  Maybe you just made an error when pasting the code here?
There is a space after if, but not after for.  Be consistent.  I recommend putting the space there to distinguish those keywords from function calls.
The j < SIZE - 1 - i condition is a bit hard to follow.  You could apply the transformation ii = SIZE - 1 - i, and have the outer loop count backwards instead.

for (int ii = SIZE - 1; ii > 0; ii--)
{
    /* Let the largest element bubble up to the end */
    for (int j = 0; j < ii; j++)
    {
        if (arr[j] > arr[j + 1])
        {
            int swap = arr[j + 1];
            arr[j + 1] = arr[j];
            arr[j] = swap;
        }
    }
}


The vulnerability I see is that only the first two arguments are checked.  You could check all of them:

rm() {
    [[ $- == *i* ]] && for arg
    do
        if [[ $arg = "*" || $arg = "./*" ]]
        then
            # abort
       fi
   done
   # do the rm

This kind of checking will miss other dangerous wildcards like ** or ?*.  You can get safer checking by expanding * yourself, then see if the expanded arguments contain that same list of files:

# alias not needed here; we want globs to be expanded
rm() {
    declare -a star=(*)
    declare -a dotslashstar=(./*)
    if [[ "$@" == *"${star[@]}"*  ||  "$@" == *"${dotslashstar[@]}"* ]]
    then
         # abort

... but then you can't (for example) empty a directory full of temp files with rm *.tmp, if *.tmp and * match the same thing.


Thanks for sharing your code!
These are my thoughts on it:

Naming

Naming Conventions

Please read (and follow) the
Java Naming Conventions

E.g.: you have variables with upper case names like N, M K. In java identifiers with (all) upper case indicate constants. But in your code these are variables and should therefore be (starting with) lower case letters.

You may have chosen this names including the case because they came from the problem statement. Nevertheless you should always stick to good naming. I would add the abbreviation from the problem statement as a comment to the variable:

    int numberOfStudensExpected = sc.nextInt();  // N
    int numberOfRowsInRoom = sc.nextInt(); // M
    int numberOfSeatsInRow = sc.nextInt(); // K

Choose you names from the problem domain, not from the technical solution.

You have identifier names like tree which refers to the type of the variabe. You should give it a name from your problem domain. Since it hols the capacity per row you decrement during processing it might be better named remainingCapacityPerRow.

Avoid single character names / abbreviations

Since the number of characters is quite limited in most languages you will soon run out of names. This means that you either have to choose another character which is not so obviously connected to the purpose of the variable. And/or you have to "reuse" variable names in different contexts. Both makes your code hard to read and understand for other persons. (keep in mind that you are  that other person yourself if you look at your code in a few month!) The same is true for (uncommon) abbreviations. You might find them being obvious today, while you're actively dealing with the problem, but You might have to "relearn" them if you worked on something else for a while.

On the other hand in Java the length of identifier names names is virtually unlimited. There is no penalty in any way for long identifier names. So don't be stingy with letters when choosing names.

So your variable a should better be named preferedRowOfStudent. And
your variable c should be named studentsWithoutSeat.

Along with the previous suggestion your code:

 if (tree.get(a[i]) > 0) {
     tree.put(a[i], tree.get(a[i]) - 1);

would change to:

 if (remainingCapacityPerRow.get(preferedRowOfStudent[i]) > 0) {
     remainingCapacityPerRow.put(preferedRowOfStudent[i], remainingCapacityPerRow.get(preferedRowOfStudent[i]) - 1);

As usual there are some exceptions for this suggestion.
E.g. the running index of loops is usually held in a single letter named variable like i in:

for(int i =0; i<SOME_CONSTANT; i++)

But even there you should use more problem oriented names to support your readers, especially in nested loops like this:

for(int rowInRoom =0; rowInRoom <numberOfRowsInRoom; rowInRoom ++)
   for(int seatInRow =0; seatInRow<numberOfSeatsInRow; seatInRow++)

Use of language

Use temporary variable to simplify the code

within your for loop you access the same element of array a several times. You should assign this element to a temporary variable before the first use.
Some may say you should do this for performance, but at least for Java performance is not affected.

along with the Avoid single character names / abbreviations suggestion your code would change to this:

 int studentsPreferedRow = preferedRowOfStudent[i];
 // ...
 int rowsRemainigCapacity = remainingCapacityPerRow.get(studentsPreferedRow );
 if (rowsRemainigCapacity  > 0) {
     remainingCapacityPerRow.put(studentsPreferedRow , rowsRemainigCapacity--);

doesn't this read much better?

Avoid odd ball solutions

You store the list of students in an array while you store the list of banks and their capacities in a Collection object rather than in an array too. This is called an odd ball solution because you use different approaches for the same thing.

avoid comments

Your solution has some comments which somehow structure your method into "sections". You should better extract these "sections" into methods with names derived from your comments:

public static void main(String[] args) throws Exception {
    Scanner sc = new Scanner(System.in);
    // read NMK
    int[] a = initialiseStudentRowPreferences(sc);
    TreeMap<Integer, Integer> tree = initializeRoom(N,K);
    int c = countStudentThatDidNotGetASeat(tree, a)
    System.out.println(c);
}
// ...
private int countStudentThatDidNotGetASeat(TreeMap<Integer, Integer> tree,int[] a){
   // do method extraction at all levels:
    int c = 0;
    for (int i = 1; i <= N; i++) {
      int studentsPreferedRow =  a[i];
      if(isPreferedRowAvailable(tree, studentsPreferedRow ))
        reduceCapacity(tree, studentsPreferedRow);
      } else {
         c += placeStudentInOtherRow(tree, studentsPreferedRow ))
      }
    }
    return c;
}
// ...

However, Comments should explain why the code is like it is, not what the code does. When ever you feel you need to explain your code try to find better names for your identifiers (variables and methods).

OOP

Your code is a procedural approach to the problem.

There is nothing wrong with procedural approaches in general, but Java is an object oriented (OO) programming language and if you want to become a good Java programmer then you should start solving problems in an OO way.

OOP doesn't mean to "split up" code into random classes.

The ultimate goal of OOP is to reduce code duplication, improve readability and support reuse as well as extending the code.

Doing OOP means that you follow certain principles which are (among others):

information hiding / encapsulation
single responsibility
separation of concerns
KISS (Keep it simple (and) stupid.)
DRY (Don't repeat yourself.)
"Tell! Don't ask."
Law of demeter ("Don't talk to strangers!")


Checking if string contains other strings

I like the ternary operator but in this case I wouldn't use it because a single expression that makes sure both variables are valid and then searching for the strings is easier to understand I think.

The v ?? "" isn't very pretty, especially the "" part which actually should be string.Empty. You could get rid of it by filtering the array and skipping the empty and null elements.

public static bool ContainsAll(this string str, params string[] values)
{
    return
        !string.IsNullOrEmpty(str) &&
        values != null &&
        values
            .Where(x => !string.IsNullOrEmpty(x))
            .All(v => str.Contains(v));
}

If you decorate the second parameter with params keyword then you can just type the values without an array (if you need to):

"text".ContainsAll("t", null);


Is the way I use my pattern good enough?

I would prefer:

function add($left, $right) {
   if (!(isset($left, $right) && is_numeric($left) && is_numeric($right)))
   {
      throw new InvalidArgumentException(
          __METHOD__ . ' Left and Right arguments must be numeric.');
   }

   return $left + $right;
}

The exception can then be caught at a level where you know how to deal with it.

Usage:

try
{
   print add(1, 2) . "\n";
   print add(1, '') . "\n";
}
catch (Exception $e)
{
   echo $e->getMessage();
}

The calls to add are not mixed in with custom error handling, making it easier for other people to understand your code.  It also removes the dependency on your ReturnValue class which makes your code more reusable.  The exception allows you to let the code get back to an appropriate level where you can deal with your problem, rather than passing this information back up stack levels.


Binary search traversal with in/pre/post order and BFS/DFS

There is only one point I can state: in your constructor of Node you don't need to explicitly set left and right to null. The Java runtime system will do that for you. Also, note that DFS and preorder traversal are doing the same thing so you might want to consider removing one. Since your binary tree is not guaranteed to be balanced, I would retain the DFS as it allocates your stack on the heap, and so it is invulnerable to stack overflow as your recursive preorder traversal routine.


Project Euler #1 in Go (counting multiples of 3 or 5 up to 1000)

Closed form solution

The problem is basically a sum over an arithmetic sequence, which has the well defined solution (first + last) * count / 2

func ArithmeticSum(first, step, count int) int {
    var last int = first + step * (count - 1);
    return (first + last) * count / 2;
}

The only difficulty arises from the requirement to sum numbers that are a multiple of both x and y just once. The easiest way to achieve this is to sum x and y independently and subtract the common multiples.

func Problem1(x, y, z int) int {
    var sumX int = ArithmeticSum(0, x, (z - 1) / x + 1);
    var sumY int = ArithmeticSum(0, y, (z - 1) / y + 1);
    var lcm int = Lcm(x, y);
    var sumBoth int = ArithmeticSum(0, lcm, (z - 1) / lcm + 1);
    return sumX + sumY - sumBoth;
}

Luckily, the common multiples also form an arithmetic series. It's step is the least common multiple of x and y.

func Lcm(a, b int) int {
    return a * b  / Gcd(a, b);
}

The least common multiple can be calculated from the greatest common divisor, which itself can be found via Euclid's algorithm.

func Gcd(a, b int) int {
    if b == 0 {
        return a;
    } else {
        return Gcd(b, a % b);
    }
}


Here's are a few things that I noticed.

1

The control and flow of the application needs to be seperated into smaller logical groups.
The customers should be a container and controller for the customers, not the otherway around.
For example, Customer.prototype.addCustomer should be associated with Customers.prototype.addCustomer, since Customers is a container for customer objects.

2

this.id should be a property inside the Customer constructor. Ideally, the id value should be set to null until it is added to the Customers container.

3

Setting an object's prototype to an object over-writes the entire prototype, which means that you lose the reference to the constructor object.
So it's better if you add values and functions to the prototype one at a time like so.

// ok but you lost a few values.
Customer.prototype = {
    method1: function(){
        //...
    }
};

//best
Customer.prototype.method1 = function(){
    //...
};

4

Pass values to the constructor rather than have the constructor go out and find them.

// ok
var Customer = function(el) {
    this.el = document.getElementById(el);
    this.first_name = $("#input_first_name").val();
    this.last_name = $("#input_last_name").val();
    this.name = ""
}

// best
var Customer = function(el, firstName, lastName ) {
    this.el = document.getElementById(el);
    this.first_name = firstName;
    this.last_name = lastName;
    this.name = "";
       this.id;
}

Here's a free online book to help you to understand MVC
http://addyosmani.github.com/backbone-fundamentals/


Comparing rows of a matrix with some row vectors

In Matlab, unlike C, you have to vectorize your code.
A first step would be to understand how to use find like this:

i1=70:2000;
j1=find(D1(B(v,1),i1)==L);

and:

if j1>64
       m_A1(i,j) = all( A(i,j-63:j)==A(B(v,1),j1-63:j1) );
end

You may also find any and all useful. Eventually you should be able to eliminate all the for loops and if statements.


Global variables

I know this isn't part of the module and probably just throwaway code, but you should restructure the module usage to avoid making global variables contactForm and callback:

    window.onload = function () {
      var contactForm = MyModule.createForm('ContactForm');
      contactForm.form.addEventListener("submit", function onSubmit(e) {
        e.preventDefault()
        contactForm.validate();
        console.log(contactForm.errors);
      }, false);  //Modern browsers
    }

Organization of properties between prototypes

I'm not sure why you'd divide up methods and properties between FormHelper and Form, as they seem to perform very similar functionality. I'd combine them into a single Form object; that's the only prototype you need.

This may seem too simple, but your module solves a simple problem. A more complicated module that would benefit from delegation between multiple prototypes would be one that has multiple types of Element prototypes, with some validation functions shared between Elements and some specific to particular types.

form prototype property

I don't think you need/want the form: null property on the prototype object. Even though init is a method of the prototype, it's assigning form to the base object (also named form) that exists in the submit handler, and that's what you want - a shared form property would make multiple Forms impossible.

Also, a subjective point: I'd rename this property to formElement or just element, since there are too many forms and Forms running around this code.

I hope this helps! Kyle Simpson's YDKJS books made me think as well, and with ES6 classes growing more common every day, I often wonder how this explicitly prototype-based JavaScript style can coexist with the classes Simpson discredited.


I can be rather quick with the CSS part, use indentation:

.example{
    oneTab: indented;
}

Round one

Then, you Javascript. Again, indentation. After that, I've removed several blank lines which had no purpose

Result:

 $("#vancouver").ready(function() {
    $(".fillBlank").val("");
});

// vancouver quiz answer one
var one = document.getElementById("one");
one.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
        valone(e);
    }
});

function valone(e) {
    var one = document.getElementById("one").value;
    if (one === "while") {
        document.getElementById("one").style.color = "green";
    }
    else {
        document.getElementById("one").style.color = "red";
    }
}

// vancouver quiz answer two
var two = document.getElementById("two");
two.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
        valtwo(e);
    }
});

/* repeat code for every question */

Round Two

Make use of the short if/else. Example below:

function valone(e) {
    var one = document.getElementById("one").value;
    //                                            Statement    ?  true   : false
    document.getElementById("one").style.color = one==="while" ? "green" : "red";
}
//---------------------------------------------------------------------
// And now save the 'one' element so we dont select it twice
function valone(e) {
    var one = document.getElementById("one");
    //                 Statement          ?  true   : false
    one.style.color = one.value==="while" ? "green" : "red";
}

Round Three

You repeat yourself for every question. This means that when you add one question, you have to update all of that. What if you add 15 questions? Imagine the huge amount of code that that would take!

So, time to fix that. All three of your functions do the same. They check an element for a specific value. They all get triggered on a keydown. Lets try to fix that to a single function:

// First select the elements we want to check the values of, you've allready classed those [fillBlank]:
$('.fillBlank').on('keydown', function(e){
    // At this point we have all the inputs on all keydown event, we only want enter:
    if (e.keyCode === 13) {
        // Now we have all the elements but only execute this on enter.
    }
});

Now comes the fun part. We want to be able to check ALL the inputs in one go, but give every input a UNIQUE value to check. For this we can use objects:

var correctAnswers = {
    one   : 'while',
    two   : 'on',
    three : 'occasion'
}
$('.fillBlank').on('keydown', function(e){ /* ... */ });

Neat little list like that right? Easy to expand aswell, just add one line et voila. We're now gonna add this to our code:

if (e.keyCode === 13) {
    // Now we have all the elements but only excecute this on enter.
    // Start checking the value for the input where the user pressed enter:
    // We can access the value via this.id because we named the input 'one', and there is a key 'one' in correctAnswers
    this.style.color = this.value=== correctAnswers[this.id] ? "green" : "red";
}

Well, thats it really. Now you can add plenty more items without building a million functions. The code below does the same thing as yours, but without hardcoding.

Result:

$("#vancouver").ready(function() {
    $(".fillBlank").val("");
});
// The correct answers:
var correctAnswers = {
    one   : 'while',
    two   : 'on',
    three : 'occasion'
}
// First select the elements we want to check the values of
$('.fillBlank').on('keydown', function(e){
    // At this point we have all the inputs on all keydown event, we only want enter:
    if (e.keyCode === 13) {
        this.style.color = this.value=== correctAnswers[this.id] ? "green" : "red";
    }
});

There are some extra things you can do to improve your code.

What if I type While. If you want to ignore uppercase, you can lowercase the this.value to always check the answers lowercased
You might want to add a check if this.id is an existing value of correctAnswers (hint: it's called .indexOf())
You might want to add/remove a class. CSS is for styling, not JS. This way, when you want to change the style of something correct/incorrect you do it in the stylesheet.
You might want to add the color names (or if you've updated the classnames) to a variable, e.g.: var outcomes = {right:'green', wrong: 'red'}; alert(outcomes.right);


Function to check empty cells found or not in Datagrid

The ByRef simply means that what you feed in here is going to be affected by what you do to it in the function.  You are passing a Variable or object into the function, whereas ByVal you are only passing the value of the Variable into the function/method.

Also, I am not sure what exactly you were meaning to do with this:

Dim d = Trim(cell.Value.ToString())

but it is an orphan, it is not being used for anything.

Another thing that you should keep in mind is that VB is sensitive and you should indent consistently with the VB Standard.

so the entire function should be indented like this:

Public Function IsDataGridViewEmpty(ByRef dataGridView As DataGridView) As Boolean
    Dim isEmpty As Boolean
    isEmpty = False
    For Each row As DataGridViewRow In dataGridView.Rows
        For Each cell As DataGridViewCell In row.Cells
            If Not String.IsNullOrEmpty(cell.Value) Then

                If Not String.IsNullOrEmpty(Trim(cell.Value.ToString())) = True Then
                    Dim d = Trim(cell.Value.ToString())
                    isEmpty = False

                End If
            Else
                isEmpty = True
                Exit For
            End If
        Next
    Next
    Return isEmpty
End Function


Great start for far but you need to work on your overall design.

Here are some tips.

1) Separate the css, html and javascript into their own files.

If you were place all your css into a file called "style.css" and javascript in a file called "main.js", then you could import the files from your html like so.

... more code

    <link rel="stylesheet" type="text/css" href="style.css" />

... more code

2) For your css, try using a creating a class for the box to share common properties.

Old Code:

#a {
    width:400px;
    height:140px;
    background: #FF0000;
    float: left;
}

#b {
    width:400px;
    height:140px;
    background: #FFFF00;
    float: left;
}

#c {
    width:400px;
    height:130px;
    background: #00FFFF;
    float: left;
}

New Code:

#a {
    background: #FF0000;
}
#b {
    background: #FFFF00;
}
#c {
    background: #00FFFF;
}
.box{
    width:400px;
    height:140px;
    float: left;
}

Remember to add the classes.

3) Don't repeat yourself.

The if conditions for firstval and secondval can be combined by using or, ||.

Old Code:

if(firstval == 400){
    StopRun();
    StartTimer()
    return;
}
if(firstval == 800){
    StopRun();
    StartTimer()
    return;
}
runCarousel = setTimeout(Carousel, 10);

New Code:

if(firstval == 400 || firstval == 800){
    StopRun();
    StartTimer()
}else{
    runCarousel = setTimeout(Carousel, 10);
}

4) Declare all variables are the top of a function.

Old Code:

var runCarousel, runTimer;
firstval = 0;
secondval = 0;

New Code:

var runCarousel, runTimer, firstval = 0, secondval = 0;

5) Pass the function name instead of string to setTimeout()

Also it's better to use multiplication when setting the timeout delay.

Old Code:

setTimeout("Carousel()", 10000);

New Code:

setTimeout( Carousel, 10 * 1000);

6) Attach all the global variables to a object literal.

7) Name variables and functions based on their operations.

Rename Carousel() to moveToNextSlide()

8) Cache elements for faster lookup.

Code:

var infoEl = document.getElementById('asas'),
container = document.getElementById('abc-container');

9) There needs to be a limit for firstval inside Carousel()

Add this:

var abc_container = 1200;
firstval += 10;
if( abc_container < firstval ){
    firstval = 0;
}

10) Use variables in place of numeric constants.

It's hard to understand the meaning of 400.
It seems that 400 is the width of each box.

11) secondval isn't needed. Just place everything inside setTimeout() for 10 seconds.

Better yet seconds as a parameter.

Old Code:

function StartTimer() {
    secondval += 1;
    el.innerHTML = "-" + secondval;
    if (secondval == 10 || secondval == 20 ) {
        runTimer = window.setTimeout(StartTimer, 1000);
    }else{
    ...
}

New Code:

function StartTimer( seconds ) {
    setTimeout(function(){
        window.clearTimeout(runTimer);
        moveToNextSlide();
    }, seconds * 1000);
}

12) Read the source code from other image slideshow to find out better techniques.

Here's a place to start. http://www.tripwiremagazine.com/2012/08/jquery-image-slider.html

Final Code:

HTML:

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="style.css" />

Javascript:

var carouselTimer, runTimer, firstval = 0,
    boxWidth = 400, abc_container = 1200,
    infoEl = document.getElementById('asas'),
    container = document.getElementById('abc-container');

function moveToNextSlide() {
    firstval += 10;
    if( abc_container < firstval ){
        firstval = 0;
        return;
    }
    container.style.left = "-" + firstval + "px";
    infoEl.innerHTML = "container.style.left.px = " + firstval;
    if (firstval % boxWidth) {
        carouselTimer = setTimeout(moveToNextSlide, 10);
    }else{
        window.clearTimeout(carouselTimer);
        StartTimer( 2 );
    }
}
function StartTimer( seconds ) {
    setTimeout(function(){
        window.clearTimeout(runTimer);
        moveToNextSlide();
    }, seconds * 1000);
}
StartTimer( 2 );

CSS:

#wrapper {
    width:400px;
    height:140px;
    position:absolute;
    left:50%;
    top:50%;
    margin: -70px 0 0 -200px;
    background: #383838;
    overflow: hidden;
}
#abc-container {
    position: absolute;
    width:1200px;
    height:140px;
}
#a {
    background: #FF0000;
}
#b {
    background: #FFFF00;
}
#c {
    background: #00FFFF;
}
.box{
    width:400px;
    height:140px;
    float: left;
}

Demo: http://jsfiddle.net/vSWmx/2


Function which will fire off a specific template depending on which element is selected

body = doc.getElementsByTagName('body'),

There's a shorter document.body. But then, body isn't even being used in the function. So you probably have to remove it.

console.dir(event.currentTarget);
alert(target.title);

I suggest you don't pepper your code with console.* and alert to view values. Take advantage of the browser's debugger, and use breakpoints. Not only can you view the variable, you can also view surrounding variables, enclosing scopes and more.

switch(target.id){

First, I wouldn't use id. id is supposed to be unique in the page. Use it if you're absolutely sure that the element is the only one in the page with that id. This can get real messy when you discover that your HTML needs to be in multiple places, but contain the same structure and/or content.

But then, I notice you use data-* attributes. Use that instead of id. It's designed for that purpose, carry data in markup.

 case '1':
$.get('../../../templates/index.html',function(template) {
  modal.append(Mustache.render($(template).filter('#templateID').html()))
  modal.listview("refresh");
  });

 break;

 case '2':
 alert(target.title);
 break;

 case '3':
 alert(target.title);
 break;

 case '4':
 alert(target.title);
 break;

 case '5':
 alert(target.title);
 break;

It doesn't have a default. switch is also a bit clunky. And I usually avoid switch because failing to add a break where needed will cause your code to run down an unexpected path.

The following would be a better way to model it:

// An operations object, with key as the id, and function as value
var operations = {
  '1': function(){
    $.get('../../../templates/index.html',function(template) {
      modal.append(Mustache.render($(template).filter('#templateID').html()))
      modal.listview("refresh");
      });
  },
  '2': function(){
    alert(target.title);
  },
  // and so on
}

if(typeof operations[target.id] === 'function') operations[target.id].call(null);


Your code works, but is difficult to understand. Especially it is hard to understand what exactly is stored in b, this list contains both integers and strings. The name b also does not give a clue what it used for.

I would suggest a more straight forward method with more descriptive names for variables:

s = "((a+b*d)*(x/2))*(1+(y+(x-2)/10))"

opening_bracket_pos = []
stack = []

for i in range(0, len(s)):
    if s[i] == '(':
        opening_bracket_pos.append(i)
    elif s[i] == ')':
        start_pos = opening_bracket_pos.pop()
        stack.append(s[start_pos: i+1])

print(s)
print(stack)


Be careful with your inequalities.  You've listed 500 twice: once as if (Score <= 500) and again as else if (Score >= 500).  That's confusing, as the first condition takes precedence.

I think that you would be better off with one state variable representing the current difficulty level.  The code would also be simpler if you determine NewDifficulty using a level-triggered rather than edge-triggered mechanism.

int Difficulty;

void IncreaseScore()
{
    int NewDifficulty = (Score <   100) ? 0
                      : (Score <=  500) ? 1
                      : (Score <= 1500) ? 2
                                        : 3;
    // One-way ratchet: difficulty can only increase, even if the
    // score subsequently drops.
    if (NewDifficulty < Difficulty)
    {
        Difficulty = NewDifficulty;
    }
}

If the score can never decrease in this game, then you can simplify it further:

void IncreaseScore()
{
    Difficulty = (Score <   100) ? 0
               : (Score <=  500) ? 1
               : (Score <= 1500) ? 2
                                 : 3;
}


Incrementing letter-spacing of one line of text

As with all things related to performance, you must measure.  Here's a jsperf with your original code in it and several other iterations: http://jsperf.com/set-text-width

You can do several things to speed it up considerably:

Cache h1.width() since it doesn't change.
Make your comparison be >= because you may never get ==.
Use a larger pixel increment until you get close, then step down to a smaller increment

Per jsperf, this is about 5x faster than your original code.

function matchSize3() {
    var h2,w;
    var x = 1;
    w = $('#header').find('h1').width();
    h2 = $('#header').find('h2');
    h2.css( { 'letter-spacing':'1px' } );

    while(h2.width() < w) {
        if (x++ > 1000) { break; }
        h2.css('letter-spacing', '+=1px');
    }

    for (var i = 0; i < 10; i++) {
        if (h2.width() <= w) break;
        h2.css('letter-spacing', '-=0.1px');
    }
}

And, here's an even faster version that just attempts to calculate the desired pixel spacing and starts with that.  This is 14x faster than your original.  I don't think the last two loops are probably needed at all.

function matchSize4() {
    var h2, w;
    w = $('#header').find('h1').width();
    h2 = $('#header').find('h2');
    h2.css( { 'letter-spacing':'1px' } );

    // try to calculate the best starting point
    var l = h2.text().length;
    var diff = w - h2.width();
    h2.css("letter-spacing", ((diff/l) + 1) + "px");

    // these may not be needed at all
    if (h2.width() < w) {
        for (var i = 0; i < 10; i++) {
            if (h2.width() >= w) break;
            h2.css('letter-spacing', '+=0.1px');
        }
    } else {
        for (var i = 0; i < 10; i++) {
            if (h2.width() <= w) break;
            h2.css('letter-spacing', '-=0.1px');
        }
    }
}

And here's a version that just calculates the desired letter-spacing with no iteration.  This is 27x faster than your original version:

function matchSize5() {
    var h2, w;
    w = $('#header').find('h1').width();
    h2 = $('#header').find('h2');

    // calc the desired spacing
    var len = h2.text().length;
    var diff = w - h2.width();
    h2.css("letter-spacing", (diff/(len - 1)) + "px");
}

For speed reasons, this one assumes the letter-spacing is initially 0.  If it won't reliably be zero, then you have to obtain the initial value and use that in the calculation or set it to zero initially.

And here is a jsFiddle of this one to show that it works: http://jsfiddle.net/jfriend00/trazumeh/


Naming
Your names are... I miss the word to describe your naming overall... Either way let's start.
Some of your names are good. $smtp, $from, $alias, $mailer and so on. Some of your names need improvement. $reader1 for example..
That reader would be better off as $mailReader or $messageReader or even $webReader.
Whenever you number your variables something is wrong..
Then there's your $reader2.. And this is what's breaking my understanding..
You called the Class it has ParamSetter, but you make it implement a InputReaderInterface, and call the variable $reader...
Make up your mind. Is that thing a setter, a reader or something entirely different?
It definitely looks like it's something different. ParameterSetter seems to reflect it's usage. Having it implement InputReaderInterface is definitely the wrong choice.
Concept
Actually your whole concept of OOP seems to be incorrect. I'd expect $message to be a Message and not a "String". That would allow you to restructure your code to something like this, which looks waay more OOP to me:
<?php
    $messageReader = new WebReader($mailUrl);
    $message = new Message(messageReader->getContent());

    $params /* how you get your params at all... */
    $paramReader = new ParamReader($params);
    $mailer = new Mailer($smtp, $from, $alias);

    foreach($rows as $row) {
       $message->applyParameters($paramReader->getParameters($row['email']));
       $mailer->sendMail($row['email'], $subject, $message->getContent());
    }
?>

Of course this means you'd have to change some underlying mechanics. Also I just dropped your InputReaderInterface. In that setup it's not really helpful, as you use your classes differently.
Your ParamSetter was a ParamReader and some Message-functionality. Keep concerns separate, the ParamSetter does not need to know how a message works, and what parameters it wants. He shouldn't even tamper with the message. That would be a violation of the "Principle of Least Knowledge", which is a very important principle for OOP designing.
Instead the only one altering the $message should be the $message itself. Thus your ParamSetter in fact just wants to be a Reader, who is used by the Message.


If you're passing information, pass only information, not markup. Alternatively completely generate the HTML markup on the server-side, and just apply it on the client side. There's no point in combining the two, and if done wrong you could cause double escaping issues.

Second, don't use alert() as a debug function. Use console.log() and use your console.


A few changes I would make:

Follow PEP 8.
Use the modern, high-level pathlib instead of a combination of the os module, glob, and shutil.
Be careful when using a bare except:, or except Exception:, see https://stackoverflow.com/q/54948548.

import pathlib

docs_dir = pathlib.Path('')
target_dir = pathlib.Path('')

for file in docs_dir.glob('*-*'):  # Each file gets moved one by one
    subject_name, file_name = str(file.name).split('-', maxsplit=1)
    subject_dir = target_dir.joinpath(subject_name)

    subject_dir.mkdir(exist_ok=True)
    file.rename(subject_dir.joinpath(file_name))

As an aside, it may be worth considering using a folder just for unsorted school-related files. It would be so easy to add a non-schoolwork file which contains a '-' to your documents folder, and have it moved unintentionally by the program.
You wrote in a comment:

However I aim for that "I saved the file and it directly moved to the targeted folder" approach.

If that's the case, you should look into file system watchers/watchdogs.