Basic calculator that takes 2 numbers and does an operation with them

The main issue with your code is repetition. The 4 methods calculating the result based on user input are sketched in the same way:

public static void operation() {
    // get numbers
    // perform operation and print result
    // return to main loop
}

As a result, there is copy-pasted code inside those 4 methods.

The first remark is that all of them will need to get numbers from the user. Instead of having each of addition, subtraction, etc. to get the numbers, retrieve them before hand from the user. In the same way, all of them invoke calculator(); to ask the user numbers again.

A first possiblity is therefore to have:

int pick = askScanner.nextInt();

getNumbers();
// perform operation based on input
calculator();

with a sample operation being:

public static void addition() {
    System.out.println("Addition");
    answer = firstNumber + secondNumber;
    System.out.println("This is the sum of the two numbers:  " + answer);
}

That said, this still leaves a design issue:

private static final Scanner askScanner = new Scanner(System.in);
public static double answer;
public static double firstNumber;
public static double secondNumber; //makes variables for the whole class

Having static global variables to keep the numbers input by the user isn't a good idea. What you want instead is to have local variables with the minimum possible scope.

You'll need to drop the method getNumbers() completely: it needs to have global variables (because it only returns one value and not the two). Also, the operation methods won't operate on the global variables anymore; instead, they will be given the two operands as parameter. And, lastly, they won't set the result global variable but return the result.

As such, the code would be:

if (pick == 1) {
    addition(firstNumber, secondNumber);
} else if (pick == 2) {
    subtraction(firstNumber, secondNumber);
} else if (pick == 3) {
    multiplication(firstNumber, secondNumber);
} else if (pick == 4) {
    division(firstNumber, secondNumber);
} else {
    System.out.println("You need to choose 1, 2, 3, or 4");
}

with a sample operation being:

public static double addition(double firstNumber, double secondNumber) {
    System.out.println("Addition");
    double answer = firstNumber + secondNumber;
    System.out.println("This is the sum of the two numbers:  " + answer);
    return answer;
}

You could also consider using a switch instead of the if/else blocks:

switch (pick) {
case 1: addition(firstNumber, secondNumber);
case 2: subtraction(firstNumber, secondNumber);
case 3: multiplication(firstNumber, secondNumber);
case 4: division(firstNumber, secondNumber);
default: System.out.println("You need to choose 1, 2, 3, or 4");
}

which makes the code a bit shorter.

As a final note: your code is an infinite loop right now, the user has no way to exit. It would be nice to introduce an option giving the user the possibility to quit the program.


Since await is effectively a continuation anyway, you could simplify your function to:

private async Task PrepareData()
{
    Task[] FirstTasks = new Task[] { TaskOne(), TaskTwo() };    // Do First group of Tasks
    await Task.WhenAll(FirstTasks); // Wait for First group of Tasks

    Task[] SecondTasks = new Task[] { TaskThree(), TaskFour() }; // Do Second group of Tasks
    await Task.WhenAll(SecondTasks); // Wait for Second group of Tasks

    GuiTaskOne();
    GuiTaskTwo();
}

I also suspect you meant to await the GUI tasks too.


Encapsulation, fields and properties for Asteroid class

Fields vs Properties

As discussed in the comments above, there's a problem with IsVisible:

private bool isVisible;
public bool IsVisible { get; set; }

When this code compiles, you'll basically get something like this "under the hood":

private bool isVisible;

private bool IsVisible;
public bool get_IsVisible() { return this.IsVisible; }
public void set_IsVisible(bool value) { this.IsVisible = value; }

BUG!
You're using isVisible all over your code, but the setter for IsVisible, set_IsVisible, is never called. Hence your clients will not see the right value... literally: the public getter will always return default(bool)... false!

You really have two options.

Either you expose data, or you encapsulate data.

Think of what a class really is: it's a definition for a type. A type can be a class, but in C# you can also have an enum, a struct, an interface... types can also be abstract (like an interface, or an abstract class).

When you instantiate a class, you create an object of the type defined by the class. An object has an interface (do not confuse with interface) that exposes everything that's publicly available. The client code doesn't "see" anything that's private or protected (or internal if the client code is in another assembly). And that's exactly where encapsulation is: it's hidden, encapsulated inside the inner workings, the implementation details of the type - the interface doesn't expose it because client code does not need to know what the implementation details are.

Fields are implementation details. They don't need to be exposed, and doing so breaks encapsulation.

Option One

You could make IsVisible an auto-property:

public bool IsVisible { get; set; }

Or, for a get-only auto-property:

public bool IsVisible { get; private set; }

Remember that under the hood, there is a private field for that auto-property (see "When this code compiles..." above).

Option Two

You could make IsVisible a property that uses a _isVisible private backing field:

private bool _isVisible;

public bool IsVisible
{
    get { return _isVisible; }
    set { _isVisible = value; }
}

The get-only version simply omits the setter.

You'll notice I'm using a naming convention that makes it a no-brainer to tell a field (_isVisible) from a parameter (value - implicit parameter in a property setter).

If you don't like having an underscore prefix on your private fields (it really comes down to personal preference.. or to the naming conventions your team is using), you could alternatively do it like this:

private bool isVisible;

public bool IsVisible
{
    get { return this.isVisible; }
    set { this.isVisible = value; }
}

The this qualifier isn't really needed (it's actually redundant in this case), but then if you had a method like this:

private void DoSomething(bool isVisible)
{
    // "isVisible" in this scope refers to the parameter.
    // use "this.isVisible" to refer to the private field.
}

And this is why I prefer the underscore prefix.

Bottom line: Properties win.

Some useful references:

Member Design Guidelines (Field Design) on MSDN:

  We exclude constant and static read-only fields from this strict restriction, because such fields, almost by definition, are never required to change.

  X DO NOT provide instance fields that are public or protected. You should provide properties for accessing fields instead of making them public or protected.
  √ DO use constant fields for constants that will never change. The compiler burns the values of const fields directly into calling code. Therefore, const values can
  never be changed without the risk of breaking compatibility.
  √ DO use public static readonly fields for predefined object instances. If there are predefined instances of the type, declare them as public read-only static fields of the type itself.
  X DO NOT assign instances of mutable types to readonly fields.

Note that in oop, static, predefined instance is generally just bad wording for don't do that!!

Also while you certainly don't want a mutable readonly struc, but readonly in front of a reference type only means that the reference cannot be reassigned. These are guidelines after all ;)

Member Design Guidelines (Property Design) on MSDN:

  √ DO create get-only properties if the caller should not be able to change the value of the property. Keep in mind that if the type of the property is a mutable reference type, the property value can be changed even if the property is get-only.
  X DO NOT provide set-only properties or properties with the setter having broader accessibility than the getter. For example, do not use properties with a public setter and a protected getter. If the property getter cannot be provided, implement the functionality as a method instead. Consider starting the method name with Set and follow with what you would have named the property. For example, AppDomain has a method called SetCachePath instead of having a set-only property called CachePath.
  √ DO provide sensible default values for all properties, ensuring that the defaults do not result in a security hole or terribly inefficient code.
  √ DO allow properties to be set in any order even if this results in a temporary invalid state of the object. It is common for two or more properties to be interrelated to a point where some values of one property might be invalid given the values of other properties on the same object. In such cases, exceptions resulting from the invalid state should be postponed until the interrelated properties are actually used together by the object.
  √ DO preserve the previous value if a property setter throws an exception.
  X AVOID throwing exceptions from property getters.

Abstraction

If I look at the interface of an Asteroid, I see these members:

Asteroid(Texture2D newTexture, Vector2 newPosition);

Rectangle BoundingBox { get; }
Vector2 Position { get; }
bool IsVisible { get; set; }

void LoadContent(ContentManager content);
void Draw(SpriteBatch spriteBatch);
void Update(GameTime gameTime);

I would think pretty much everything that's drawable in your game has a very similar interface, if not an identical one.

If you defined an abstraction for the methods this interface exposes...

public interface IDrawableContent
{
    void LoadContent(ContentManager Content);
    void Draw(SpriteBatch spriteBatch);
    void Update(GameTime gameTime);
}

Then you could have every drawable game component implement that interface, like this:

public class Asteroid : IDrawableContent

And since your GameScreen (I'm making this up) also has these methods with the same signature, why not do this as well:

public class GameScreen : IDrawableContent

Your AsteroidZapperGame class (or whatever it's called) also has similar methods (defined by the XNA Game class), but it's pretty much your top-level object, so you don't need it to implement the interface.

What gives?

The GameScreen class might roughly look like this (over-simplified):

public class GameScreen : IDrawableContent
{
    // _items is readonly.
    // its reference may only be assigned in a constructor.
    // items may still be added or removed from the list any time.
    private readonly IList<IDrawableContent> _items;

    public GameScreen(IList<IDrawableContent> items)
    {
        _items = items;
    }

    public void LoadContent(ContentManager content)
    {
        foreach (var item in _items)
        {
            item.LoadContent(content);
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        foreach (var item in _items)
        {
            item.Draw(spriteBatch);
        }
    }

    public void Update(GameTime gameTime)
    {
        foreach (var item in _items)
        {
            item.Update(gameTime);
        }
    }
}

This class has no clue that you're making it draw asteroids. In fact, it could just as well be drawing bubbles in a soda can, or a bunch of zombies hunting the player down. That's what abstractions do: they abstract away the implementation details, and that makes code easier to read, extend, and maintain.


The trick is to lift (:) into the applicative functor using pure thus getting an expression of type f (a -> [a] -> [a]) which you can then apply using (<*>). This gives you: sequenceA (x:xs) = pure (:) <*> x <*> sequenceA xs.

Now, the pattern pure ... <*> is equivalent to ... <$> so we can rewrite the previous equation to the shorter solution:

sequenceA (x:xs) = (:) <$> x <*> sequenceA xs

This pattern can be generalized to other datatypes: see the traversable typeclass. sequenceA can always be implemented for datatypes* by using pure to lift constructors and (<*>) to apply arguments (or induction hypotheses).

* strictly positive ones, at least


It would seem that you are restricting yourself to English alphabet, when there is no need for that. All that Caesar cipher does, is adding some constant (usually called key) to each character. Decoding then may be done by subtracting that very key from each encoded character. All in all, I had this in mind:

public class Encryptor {

    public static String encryptString(String input, int key) {
        StringBuilder sb = new StringBuilder(input.length());

        for (char c : input.toCharArray()) {
            sb.append((char)(c + key));
        }

        return sb.toString();
    }

    public static String decryptString(String input, int key) {
        return encryptString(input, -key);
    }
}

Also, using StringBuilder
will improve the performance of your cipher: when you do

char c = '?';
myString += c;

a new String is created which runs in linear time as it needs to copy the character content. However, appending to a StringBuilder of a known size runs in constant time.

I run your program, and it does not cipher the white-space. This makes breaking your cipher easier as the attacker will see clearly the lengths of words. Instead, cipher any character in the input string.


Let's get cracking ;) Nitpick first:

Indentation / Spacing:
Your indentation and spacing aren't fully consistent. It would be beneficial to use an IDE's autoformatting options.

Okay, now that that's out of the way, let's get to the real beef:

AtomicInteger priorityCounter = new AtomicInteger(-1);

This is only used in your executeMethod. And there it's used "wrongly". You're trying to burden the executeMethod with the additional responsibility of checking whether the task you have at hand should be executed now, or not:

if (task.getPriority() > priorityCounter.get()){
    task.execute();
    priorityCounter.getAndSet(task.getPriority());
}

This is not good especially since you fail your if-condition silently. Enqueueing a lower-priority task to the queue does not execute the task and doesn't tell you about that.

That's a big problem and unnecessary. You can completely remove all the stuff in this method, that's got to do with priorityCounter. What remains is task.execute() and that can stand on it's own.

private ExecutorService executorService = Executors.newFixedThreadPool(10);

I don't like this one for multiple reasons:

It isn't final.
You're not using anything anywhere near 10 threads.

If you want to do it "right" you should move all your executorService.submit()-calls directly around the respective task.execute()-calls. Right now you only ever submit two runnables to this 10-thread pool. That's a waste of threads ;)

private PriorityQueue<Task> taskQueue;

Again this could just as well be made final, you could even initialize this eagerly, since the static PRIORITY_COMPARATOR is available anyways ;)

for (Task task : taskQueue) {
   /* stuff in here */
}

First thing I thought when seeing this: "This doesn't respect priority, right?" While that's not true, I personally find the following much more obvious:

while (taskQueue.peek() != null) {
    Task task = taskQueue.poll();
    /* stuff in here */
}

Moving swiftly on to one of the last points I want to make:

if (task instanceof Interruptible && ((Interruptible) task).isInterrupted()) {

Your requirements nowhere state, that only interrupted Interruptibles are to be executed later. Assuming you didn't have the definition of Interruptible given, I had suspected it to be a marker-interface. I'd shorten the code to:

if (task instanceof Interruptible) {

Almost finished:

executorService.submit(new Runnable() {
    @Override
    public void run() {
       /* real stuff here */
    }
});

If you have java 8 available I highly recommend converting this boilerplate to a lambda-expression:

 executorService.submit(() -> { /*code here */ });

One thing about references and shuting down, if I may:

Overriding finalize to shutdown your executor isn't recommended. This answer on SO gives nice impressions.

What you should do instead is implement AutoCloseable  and shut down the executor when overriding the close-method

And last but not least:

One cannot enqueue new Tasks to your MultiThreadedTaskScheduler. While that was not part of the requirements this is one thing that I'd expect of a TaskScheduler ;)


OpenSSL PBKDF2-HMAC-SHAx proof of concept

Things you did well on:

Looks like you weren't too rusty based on this code.  Looks very nice organizationally.
You return different values for different error conditions.

Things you could improve on:

Standards

Initialize i in your for loops.(C99)

for (unsigned int i = 0; i < sizeof(digest); i++)

Syntax

Don't over-compact your code.

if(argc != 6){printf("Incorrect number of parameters.\n");return 2;};

Let it breathe a bit.

if(argc != 6)
{
    printf("Incorrect number of parameters.\n");
    return 2;
}

Use puts() instead of printf() when you aren't formatting a string.

puts("Incorrect number of parameters.");

You don't follow proper C naming conventions.

 char HexResult[2*outputbytes-1];

Either use camelCase, or snake_case with variable names.
Your indentation is a bit odd.

if (strcmp(argv[1],"SHA-512")==0)
  {
  PBKDF2_HMAC_SHA_512(pass, salt, iterations, outputbytes, HexResult);
  }

But that could be a copy-paste issue.

Commenting:

The only comments I see are a link to a Stack Overflow post, and a commented-out bit of old code.  Use more comments to explain what your code does, and how it accomplishes that/why it works.

Look at it as if a new developer was going to look at your code.  You should try to explain it so that he could understand it's basic function and how it works right away.  You might thank yourself when you return back to this project in the future, forgetting completely how it works. ;)


Is a Timer the best way to achieve recursive in Android?

Timers and TimerTasks appear to be discouraged for Android, especially when interacting with the UI. Each Timer gets a thread on which to do its work, which makes UI updates problematic, and which also presumably causes unnecessary overhead for small tasks.

This could be updated to use the postDelayed() or postAtTime() method of Handler, which takes advantage of the existing message queue.  Note: this code is not tested.

ViewPager mViewPager ;
mViewPager = (ViewPager) findViewById(R.id.viewpager);

private class UpdateTimeTask implements Runnable {
    private static final int TASK_TIME_MS = 5000;

    private int mLength = 0;
    private Handler mHandler;

    public UpdateTimeTask(final int length) {
        this.mLength = length;
        // Get the main thread's Handler. If the task is
        // always on the main thread, we can just do
        // mHandler = new Handler();
        // Otherwise, do:
        mHandler = new Handler(Looper.getMainLooper());

        // Get things started.
        // If this is intended to be done on the UI thread,
        // just call run() directly.
        // run();
        // If this is intended to be done on any thread, use
        // the Handler to execute run()
        mHandler.post(this);
    }

    public void run() {
        if (mViewPager.getCurrentItem()+1 < mLength) {
            Updateviewpager(mViewPager.getCurrentItem() + 1);
        } else {
            Updateviewpager(0);
        }

        // Schedule to repeat
        mHandler.postDelayed(this, TASK_TIME_MS);
    }
}

public void Updateviewpager(int position) {
    mViewPager.setCurrentItem(position);
}

References:
Android Timer Documentation
Updating the UI from a Timer


Placement of jQuery function that toggles p tags

Putting a function inside the jQuery function $(function(){}) is shorthand for $(document).ready(), they are the same thing.

So, the answer is: yes, it will be more efficient.

jQuery's .ready method just waits for the DOM to be ready before firing the code inside but when it comes to setting event handlers, you actually don't have to wait for the DOM to be ready at all. jQuery allows you to attach your events to the document object itself and when those events bubble up, jQuery will call them.

So instead of using

$('#number-of-coins input[type=radio]').change(function () { ... });

You can use

$(document).on("change", '#number-of-coins input[type=radio]', function(){...});

The second one does effectively the samething as the first one, but the first one needs to be inside of a $(function(){..}) or $(document).ready() and the second one does not.

For more info, see Difference between .on('click') vs .click().


First, you should separate the UI logic (with terms like GridView, databinding etc.) from the business and/or data logic (with terms like queries, DbContext etc.). So your second approach with a helper class is the more correct approach. In general this kind of helper classes are called the Repository pattern.

You should not pass the UI controls like GridView to your business and/or data logic layer.

About where to put GridView.DataBind() - there are few approaches each useful in certain cases:

Set the .DataSource and call .DataBind() in your Page_Init() method - this way the controls created will not all go in the ViewState. This is not always possible but should be used whenever possible.
Set the .DataSource and call .DataBind() in GridView_PreRender() event - this event is only called when GridView.Visible == true so if you show/hide the grid, you will not end up going for the data if it is not displayed.

Also always experiment if setting EnableViewState=false works for you - since by default GridView will always store everything in the ViewState. If this does not work, you should only call .DataBind() when the data is initially retrieved or the view changed (such as Page.IsPostBack == false or when clicking a search button etc.


It depends on your app context. If im writting a web app Id create a filter which would getEntityManager(), begin() the transaction, then add it to the request scope, .doFilter() and pass it to the dao in the constructor (at the controller, of course).

When it returns to the filter id commit(), or even rollback() if any exception happens.


Welcome to Code Review. This queue implementation is not truly concurrent-ready.

Arbitrary initial capacity

template <typename Type, std::size_t Capacity = 100>

Why have you decided that the default size should be 100? Different people have different needs; having default values like this isn't a good idea because there is no true advantage to having a default size of 100.

While this is subjective, I suggest you remove that default size and just have users be required to specify the size that they want.

Compare/exchange confusion

There seems to be a misunderstanding in regards to the use of compare/exchange. The compare/exchange operations work as follows:

Let X be the atomic variable
Let E be the expected value of X
Let N be the new value of X

The operations has the following signature:

X.compare_exchange(E, N);

This roughly translates (but is not an implementation of the compare/exchange operation) to:

bool compare_exchange(E, N)
{
    if( X == E )
    {
        X = N;
        return true;
    }
    else
    {
        E = X;
        return false;
    }
}

What this means is that when the comparison fails, E is updated to the current value of X. If the comparison succeeds, X is updated with the value of N. Therefore, you don't need to update X again! That is the whole point of a compare/exchange operation; you're basically saying: "I was the last to modify X."

Issue #1: Unsynchronized access to writer

In your code, you perform a store to the atomic variable with a copy of a value you last obtained from the update performed in the compare/exchange operation, but this is not atomic.

if (next_writer != reader.load())
{
    if (writer.compare_exchange_weak(past_writer, next_writer))
    {
        // thread can be stalled here and try_pop() will access garbage memory
        // since at this point writer != reader
        array[past_writer] = object;
        return true;
    }
}

Imagine a first call to try_push() in thread A makes it inside the if (next_writer != reader.load()) statement and gets stalled just before executing array[past_writer] = object;. Now another thread B calls try_pop() and successfully gets past if (past_reader != writer.load()); the writer now has a value different than reader because of the compare/exchange operation.

However, the store of an element has not happened yet since thread A is still stalled. What is thread B going to pop? It's going to access whatever garbage memory is at that location.

Issue #2: Malfunctioning empty function

The load from reader and the load from writer followed by a comparison is not thread safe.

bool empty() const
{
    return reader.load() == writer.load();
}

Consider what happens if writer.load() returns value A, but before the expression is evaluated, writer is changed to some other value B. This could cause empty() to say that the queue is empty when it isn't or that it isn't when it actually is.

Conclusion

These are two of many issues that are currently in your code. I've decided to stop here since that's a pretty bad problem. This current implementation if not safe at all. I recommend you do some more reading and learning about thread interaction. Good luck.


There are several ways you can save memory, where you’re storing more information than you really need. In some cases, way more information than you need.

If you only save what you need, you’ll reduce memory and get a performance benefit to boot!

Memory improvement #1

These three lines are wasting memory:

strings = []
for i in range(N):
    strings.append(input())

You don’t actually need to gather up all the rocks into a list – you’re only ever looking at one at a time. Although in this case it’s unlikely to matter, creating a list when you don’t need one is a bad antipattern.

You can rewrite your code to make the strings list unnecessary, thus saving memory, like so:

lists = [[False] * 26 for i in range(N)]

for i in range(N):
    rock = input()
    for c in rock:
        # ord() gives the ASCII value of a character
        lists[i][ord(c) - ord('a')] = True

Note that this also only features one for loop of length N, which will likely have a (small) benefit to performance.

Memory improvement #2

The lists variable (that’s not a great name, btw) is a 26 x N-sized matrix. Again, this has the potential to get quite large if you have lots of rocks, or lots of different elements. And you’re storing more data than you need to – all we’re interested in is which elements were present in each rock. A simpler way to store that would be something like:

rock_elements = []

for _ in range(N):
    rock = input()
    rock_elements.append(set(rock))

final_list = reduce(lambda x, y: [i in x and i in y for i in range(26)], lists)

Now the rock_elements list only contains the set of elements in each rock. We’re not provisioning lots of unwanted memory for small rocks.

Memory improvement #3

We’re still storing more information than we need. For example, suppose the first rock omits a, and every other rock contains a. Remembering that those later rocks contain a is pointless, because we know that a isn’t a gem-element.

So an even more efficient solution would be to keep a set of possible gem-elements, and throw elements away whenever we find a rock that doesn’t contain them. Like so:

import string

gem_elements = set(string.ascii_lowercase)

for _ in range(N):
    rock = input()
    gem_elements = gem_elements & set(rock)

print(len(gem_elements))

Now our gem_elements set will never be larger than the number of possible elements, and we’re only storing the data for one rock at a time. Much better!

And as a nice side benefit, we’ve got rid of the two calls to reduce(), which are:

Generally not very Pythonic – idiomatic Python tends towards list comprehensions and similar rather than reduce() and map().
Moderately expensive – I think at least \$O(N)\$ in the number of rocks?


Computing and Populating Excel Table With VBA

First things first - variable naming - help me. I look at your variables and have no idea what they are, what they are meant to do or how they should be used.

Dim SLAbyPrior      As Worksheet
Dim wsAssignedTix   As Worksheet

Dim ctP1            As Integer
Dim ctP1RespSLA     As Integer
Dim ctP1PlanSLA     As Integer
Dim ctP1ResSLA     As Integer
Dim ctP1All3SLA    As Integer
Dim d              As Range

Worksheets have a CodeName property - View Properties window (F4) and the (Name) field (the one at the top) can be used as the worksheet name. This way you can avoid set wsAssignedTix = Sheets("AssignedTickets") and instead just use AssignedTickets.
Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.

Let's try to decipher what your variables are and give them meaningful names

d = priorityValue
ctP1 = countOfCritical?
ctP1RespSLA - countOfCriticalResponseServiceLevelAgreement?

Actually, I can't decipher them. Sorry.

For Each d In wsAssignedTix.Range(wsAssignedTix.Range("H1").End(xlDown), wsAssignedTix.Range("H" & Rows.Count).End(xlUp))

This could be done differently:

Dim lastRow As Long
lastRow = wsAssignedTix.Cells(Rows.Count, 8).End(xlUp).Row
Dim i As Long
For i = 1 To lastRow

Now change your if

Const CRITICAL_PRIORITY As String = "Priority 1 Incident - Critical"
Const CLOSED_OR_RESOLVED As String = "Closed Resolved"
If Cells(i, 8) = CRITICAL_PRIORITY And InStr(1, CLOSED_OR_RESOLVED, Cells(i, 7).Value) > 0 Then

Now do whatever all that adding is, but you can avoid the offset by just using the column number with the current row.

I'd also avoid doing the calculation in the With block by using a variable, personally.

Without really understanding what you're calculating, and assuming your values are either 1 or 0 you can probably just sum as you go rather than testing each offset cell for 1.

And, most likely, you'd benefit from loading the tickets sheet into an array and calculating on the array rather than the sheet.

Actually, what you could probably do is sort the tickets by critical and then just sum the columns for each status based on the count of critical tickets. That would be simpler.


Possibly mixing prototype and module pattern

The commenters pretty much said it all:

publicFunc3 can't see myPrivateFunction <- not good
I would declare function() { /* uses myPrivateFunction() */ } as a private function and then just return a pointer to it:

MyObject.prototype = (function() {
    //private helper functions
    //scoping is a pain, but doable
    function myPrivateFunction() {}
    function myPrivateFunction2() {/* uses myPrivateFunction() */ }
    function myPrivateFunction3() {/* uses myPrivateFunction() */ }

    return {
        publicFunc1: myPrivateFunction2
      , publicFunc2: myPrivateFunction3
    };
})();

I know there is a "comma first" movement out there, but it looks silly to me

Other than that, this code does not look monstrous to me, if it works for you, then why not.


Performance

The recursive function is as fast as I can think of.
The iterative function should enqueue root.left and root.right instead of root and root to gain a cycle (micro-optimisation).

Review

I find it weird that the null node is considered symmetric IsSymmetric(null). I would throw an error for invalid input.
Both algorithms are not able to deal with TreeNode instances that have a cycle (stack overflow exception vs infinite loop respectively). You will lose some performance if you guard against cycles.
Helper is a public method. There is no reason for this. Make it private or local inside the public method, and perhaps rename it to IsSymmetric, which will not be in conflict with the public method because of different signature.
Parameter names t1 and t2 are best avoided. Use full and more clear names like node1 and node2.
Queue<TreeNode> Q = new Queue<TreeNode>(); should be written more concisely and clearly as var queue = new Queue<TreeNode>();.


Here you go, with comments.

Obviously, in production I would have only a handful of comments and not the exhaustive ones I put here. However this is the sort of points I might make during a code review.

When I write code I optimize for it for communicating to a human reader what I intend the code to do. In other words - I want it to read like an essay. Therefore, I extract anything detail-heavy into small helper methods at the bottom of the script. The idea is that someone should open my script and the first thing they see should give them a top-level overview of the general flow of logic.

I didn't comment at all on your solution itself, instead just cleaning up the algorithms that were already there.

transposeString('The quick brown fox jumped over the lazy dog');

//Always comment public apis with usage and your intent when writing it.

//Transpose a string of words into a vertical matrix
//from http://www.reddit.com/r/dailyprogrammer/comments/1m1jam/081313_challenge_137_easy_string_transposition/
function transposeString(str) {
  // the ~ (ones complement) operator makes indexOf work like 'contains'
  // ~(-1) == 0, ~(x != -1) != 0
  // not sure why you need this condition at all however in terms of the problem - seems like everything
  //would just work
  if (!~str.indexOf(' '))
    //definitely don't have two large branches of conditional logic in the same function, put them
    //in separate well-named functions
    //Also always prefer to return early to get the simple paths out of the way in conditional logic.
    //The whole "single point of exit" advice is from back in the day of monolithic functions and gotos all over the place
    return makeVerticalString(str);

  //My preference is to use a single var block with everything aligned and commas preceeding
  //the terms. I have good reasons for this but not anything that I care to get into without
  //being super-pedantic. It's ok to have a different style here.
  var  words            = str.split(' ')         //you were misssing var here
      ,longestWord      = getLongestWord(words)  //give algorithms their own function

      //word matrix - I recommend commenting this so that you know it's a matrix and not a flat array
      //also note that it is much cleaner to use a map than a forEach and explicit push
      //When you see array.push() anywhere it can almost always be cleaned up with a map
      ,transposedMatrix = longestWord.split('').map(function() { return [] })

      //give a name to the thing that you're doing here and extract the algorithm to its own function
      //also rename 'treated' to 'padded' to be more explicit
      ,paddedWords = words.map(padWordsShorterThan(longestWord.length));
      ;
  //again, move the actual algorithm to its own labeled function
  paddedWords.forEach(addEachLetterToARow(transposedMatrix));

  transposedMatrix.forEach(function (arr) {
    console.log(arr.join(''));
  });
  //no need for return if you're not returning anything

  //A line to deliniate private helper functions
  //////////////////////////////////////////////////////////////////////////////////////////////
  function makeVerticalString(str) {
    //You're reducing an array to a single value so really reduce is what you want here
    Array.prototype.reduce.call(str, function(m, c) { return m+c+'\n'}, '')
  }

  function getLongestWord(words) {
    //again going from an array to a single value - we can use reduce here
    return words.reduce(function(longest, thisWord){ return thisWord.length >= longest.length ? thisWord : longest}, '');
  }

  //a function that returns a function can be a good tool for controlling scope while keeping things readable
  //note that the inner function still has a name so that it shows up properly in callstack traces  (rather than "anonymous")
  function padWordsShorterThan(threshold) { return function padWordsShorterThan(word) {
    if (word.length >= threshold)
      return word;
    //no need for else clauses when you return early
    return word + repeatStr(" ", longestWord.length - word.length + 1);
  }}
  function repeatStr(str, times) {
    //you have a neat little way of implementing a character repeat but its difficult to read - drop it in its own method
    return Array(times).join(str)
  }

 //Naming anonymous functions not only helps make clear what they're doing
 //but makes them show up named in a debugging callstack rather than "anonymous"
 //Rule of thumb - name anonymous functions that are doing significant logic
 function addEachLetterToARow(matrix) { return function addEachLetterToARow(word) {
    var n = 0;
    word.split('').forEach(function addToRow(char) {
      matrix[n].push(char); //note that you have a possible error condition here where matrix[n] does not exist. Do you want to check for that explicitly?
      n+=1; //I agree with Doug Crockford that ++ is wierd and error-prone. += reads much better in my opinion
    });
  } }
}


You should cache your selector in a variable:

var $addedColors = $("#colors_added");
$addedColors.html(parseFloat($addedColors.html()) + 1);

Reason: placing selectors in variables is recommended, since overusing selectors can result in poor performance.

Everytime you would call a function on $("#colors_added"), the whole DOM has to be parsed by the browser. This is not the case when you store it in a variable.

Also, it's a general principle to not repeat yourself in code, also called the DRY principle (as mentioned by Peter Rader in the comments).


Is u.setSoldin28(asin, Convert.ToInt16(sold)); writing to the database?

Save up all your changes and make them all under a single connection when the parse is finished. That should save quite a bit of time.

You have alot of other issues with this code though. I strongly urge you to look into proper exception handling techniques.


Using getters and setters to change another variable C#

I don't think it's a bad practice at all. What you did is called encapsulation. It enables you to exchange the underlying configuration provider (currently the Properties.Settings) to something else without breaking your application because it doesn't rely directly on it.

It's also called the Dependency Inversion Principle the higher module (your application) relies on an abstraction (your Settings) and not on the low level module (Properties.Settings). Usually it's build upon abstract types (or interfaces) but a lite version of this could be your settings layer.


Move last node of the linked list to the front

You are only able to access Node's fields data and next from the method moveTailToHead(Node) because this method is declared in the same top level class as Node. I don't know why you chose this design for your code sample, but the fact that you made the method moveTailToHead a static method outside the class Node rather than an instance method of Node makes me think that moveTailToHead is also supposed to work "from the outside" without having access to Node's internal implementation details, so I'm wondering whether your code design in this regard is intentional. If it is, then I won't argue against it, but if it isn't and if moveTailToHead should also work if it were declared in a different top level class, then you need to implement a way for Node to provide some way of accessing the contents of the list it represents. A way to start could be for Node to implement the interface Iterable<Integer>, which would require Node to have an iterator() method. This method could, for instance, look like this:

@Override
public Iterator<Integer> iterator() {
    return new Iterator<Integer>() {
        private Node nextNode = Node.this; //the next node to be returned by next()
        private Node currentNode = null;   //the last node returned by next()
        private Node previousNode = null;  //the node that precedes currentNode

        @Override
        public boolean hasNext() {
            return nextNode != null;
        }

        @Override
        public Integer next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            } else {
                if (currentNode != null) {
                    previousNode = currentNode;
                }
                currentNode = nextNode;
                int nextData = nextNode.data;
                nextNode = nextNode.next;
                return nextData;
            }
        }

        @Override
        public void remove() {
            if (currentNode == null) {
                throw new IllegalStateException();
            } else if (previousNode != null) {
                currentNode.next = null;
                previousNode.next = nextNode;
                currentNode = null;
            } else {
                assert currentNode == Node.this;
                throw new UnsupportedOperationException();
            }
        }
    };
}

That way, you can also get rid of the code duplication whenever you iterate through the list using constructs like while (current.next != null) or similar.

If you look at the method remove(), it becomes apparent that the fact that you are using a Node object to refer to the actual list itself, which Xtreme Biker already criticized in his answer, is problematic. Since the head node also defines the list, it is not possible to remove the head node from the list, which is why I made the method throw an UnsupportedOperationException for the sake of completeness in this demonstration code.

But apart from this issue, with Iterable implemented, adding other methods to add or remove elements should not be very difficult, and then you can move the tail node to the head without having direct access to the private fields Node.data and Node.next.


Displaying information about people from a JSON file

The first step is to shift out duplicate code from the if branch.

def func(x):
  list = data.parseJSON(fileName)
  if x == 1:
    person = [l for l in list if l['worker'] == sys.argv[1]]
    displayPeople(flatten(person))
  elif x == 2:
    person = [l for l in list if sys.argv[1] in set(l['children'])]
    displayPeople(person)
  elif x == 3:
    person = [l for l in list if l['age'] == sys.argv[1]]
    displayPeople(flatten(person))

Secondly, we can flatten the list before putting it into the displayPeople() function.

def func(x):
  list = data.parseJSON(fileName)
  if x == 1:
    person = flatten([l for l in list if l['worker'] == sys.argv[1]])
    displayPeople(person)
  elif x == 2:
    person = [l for l in list if sys.argv[1] in set(l['children'])]
    displayPeople(person)
  elif x == 3:
    person = flatten([l for l in list if l['age'] == sys.argv[1]])
    displayPeople(person)

Thanks to Python's variable scope rules, you can access person outside the branches. We shift the duplicate code out once again:

def func(x):
  list = data.parseJSON(fileName)
  if x == 1:
    person = flatten([l for l in list if l['worker'] == sys.argv[1]])
  elif x == 2:
    person = [l for l in list if sys.argv[1] in set(l['children'])]
  elif x == 3:
    person = flatten([l for l in list if l['age'] == sys.argv[1]])
  displayPeople(person)

Since you mention the possibility that there may be more cases, we can maintain a dictionary of cases.

def func(x):
  def case_1(list):
    return flatten([l for l in list if l['worker'] == sys.argv[1]])
  def case_2(list):
    return [l for l in list if sys.argv[1] in set(l['children'])]
  def case_3(list):
    return flatten([l for l in list if l['age'] == sys.argv[1]])

  list = data.parseJSON(fileName)
  cases = {
    1: case_1,
    2: case_2,
    3: case_3
  }
  if x not in cases:
    raise ValueError
  displayPeople(cases[x](list))

Finally, we can clear up the list comprehensions. Since we're just iterating through the list and filtering everything based on a condition, we can use the function fliter().

def func(x):
  def case_1(list):
    return flatten(filter(lambda l: l['worker'] == sys.argv[1], list))
  def case_2(list):
    return filter(lambda l: sys.argv[1] in set(l['children']), list)
  def case_3(list):
    return flatten(filter(lambda l: l['age'] == sys.argv[1]], list))

  cases = {
    1: case_1,
    2: case_2,
    3: case_3
  }

  list = data.parseJSON(fileName)
  if x not in cases:
    raise ValueError
  displayPeople(cases[x](list))

Certainly much longer than Jaime's answer but personally I find that this is more expressive; having a list of values which need to have the flatten function applied before passing to displayPeople seems hackish to me. It has a few DRY violations but should be adequate.

If flatten can be applied to any list without ill effects (which should be the case), it's alright to waste a few CPU cycles if the list isn't large. In that case, we can reduce the code down to this:

def func(x):
  cases = {
    1: lambda l: l['worker'] == sys.argv[1],
    2: lambda l: sys.argv[1] in set(l['children']),
    3: lambda l: l['age'] == sys.argv[1]
  }

  list = data.parseJSON(fileName)
  if x not in cases:
    raise ValueError
  displayPeople(flatten(filter(list, cases[x])))


If the results are ranked (typically by relevance), you should use an ol instead of a ul.

It’s best practice to use sectioning content elements (article, aside, nav, section) if you use heading elements (h1-h6). In the generel case, go with section. If the results are articles (e.g., blog posts) or pages, go with article.

It’s a usability question, but typically only the title is linked, not everything. This could make it easier for your users to mark the text in the description, and to scroll on touch devices without accidentally opening the links.

The img must have an alt attribute. The value depends on what kind of images you display here. If it’s just an icon representing that it’s a search result, the value should be empty.

Title

notes 1

notes 2

Related: my answer about HTML for search engine result lists


Find pair in array with maximum sum using recursion

Notice that the answer is the sum of the two greatest elements in the array. You only need one pass to find both of them.
The idea is that you go from through the array and keep track of top 2 elements in the array. The code will be simplier if the function requires to be called on a valid input data (an array of length >= 2) and first two elements already compared. The function then takes the next element of the array, updates the top 2 pair and moves onto the next element.
I assume you have to use recursion, but the code could be easily rewritten using a loop.
public static void findSum(int[] a, int greatest, int secondGreatest, int currentIndex) {
    if (currentIndex == a.length) {
        System.out.println("Sum:" + (a[greatest] + a[secondGreatest]) + ", i:"+greatest+",j:"+secondGreatest);
        return;
    }
    if (a[currentIndex] > a[greatest]) {
        // found the new top; the current top becomes the second
        secondGreatest = greatest;
        greatest = currentIndex;
    } else if (a[currentIndex] > a[secondGreatest]) {
        // found the new second-greatest, but so the current top stays the same
        secondGreatest = currentIndex;
    }
    findSum(a, greatest, secondGreatest, currentIndex + 1);
}

And the usage would be:
if (a.length >= 2) {
    // Rank the first two elements in the array and initiate the recursion
    int greatest = a[0] > a[1] ? 0 : 1;
    int secondGreatest = greatest == 0 ? 1 : 0;
    findSum(a, greatest, secondGreatest, 2);
}


I'm doing a couple of assumptions here, but I hope I'm on target.

If you just want the first column of the first row, you should use SqlCommand.ExecuteScalar instead of reading it into a dataset.

For instance:

using (var cn = new SqlConnection("..."))
{
    using (var cmd = new SqlCommand("SELECT statusCode FROM table WHERE whatever", cn)
    {
        cn.Open();
        return (string)cmd.ExecuteScalar();
    }
}

(Notice the using statement if you don't know it. It automatically disposes the connection and command)

You could also look into using SqlCommand.ExecuteReader which returns an SqlDataReader. The latter is cleaner and has better performance than the dataset method too.

using (var reader = cmd.ExecuteReader())
{
    while(reader.Read())
    {
        var value = reader.GetString(0);
    }
}


Suggested interviewing technique

When writing code for an interview, always ask questions to seek clarification from your interviewer.  There are nearly always technical decisions to be made, and you want to make choices that match what they have in mind.  (If you don't have any questions, then you probably haven't thought things through properly.)

For this task, I would ask:

"Can I assume that the the input x is a reasonably small positive integer, not requiring validation?  It doesn't make much sense to print anything larger than 100 × 100 anyway, right?"
"I assume that you want the entries to be aligned nicely in a grid?"
"I assume that we don't need row and column headings, and that we don't need to print grid lines?"
"I assume that you want a reasonable balance of simplicity and speed?"

Before you even write a single line of code, you can score points by showing that you know how to negotiate software requirements.

Here's a solution that I would have written:

public static void printMultTable(int x) {
    int width = (int)Math.floor(Math.log10(x * x)) + 2;
    String fmt = "%" + width + "d";
    StringBuilder b = new StringBuilder(x * width);
    for (int row = 1; row <= x; row++) {
        b.setLength(0);
        for (int col = 1; col <= x; col++) {
            b.append(String.format(fmt, row * col));
        }
        System.out.println(b);
    }
}

After writing it, explain and defend any technical decisions:

"To achieve grid alignment, we need to first determine the width of each entry.  String.valueOf(x * x).length() + 1 would have worked, but I think that the mathematical approach is slightly more efficient."
"I could call System.out.print() for every entry, but printing an entire row at once should have less overhead.  Printing the entire table at once might be even faster, but I figured this was good enough."

Note that other answers are possible.  Your interviewer might have answered, "I don't care about any of those requirements.  I just want to know that you know how to write a nested loop."  In that case, just write the simplest code that prints out the right numbers with sloppy formatting.

Your solution and feedback

My biggest concern is that it is not obvious from inspection what your code does.  There are a lot of variables, and the flow of control is convoluted.

I think number is superfluous.  After each assignment, you use it just once.
Why is rowCounter initialized to 0, but columnCounter initialized to 1?  Why is there a rowCounter = 2 assignment right in the middle of everything?  (I would expect reinitializing to either 0 or 1.)  More alarmingly, you increment rowCounter to count the columns printed, and columnCounter to number the current row.  That's the kind of trap that makes co-workers hate your code.
Three cases is excessive.  All of them have System.out.print(… + " "), which makes it cut-and-paste code.  Couldn't you lump the first if(i < x) case with the last case?  (Hint: setting rowCounter = 0 was a poor move.)

The natural way to write this solution is using a nested for-loop.  If you really wanted to do it in one loop, it should be simpler:

public static void printMultTable(int x)
{
    int row = 1, col = 1;
    int totalEntries = x * x;
    for (int i = 1; i <= totalEntries; i++)
    {
        System.out.print((row * col++) + " ");
        if (i % x == 0)
        {
            System.out.println();
            row++;
            col = 1;
        }
    }
}

Note that the function should be static, since there's no reason for it to have any object state.

  I’d say that a lot of his solutions were pretty inefficient and took a very ‘brute force’ approach to a solution. For example, his solution for question 1 took 30 lines (give or take for some spacing). This is normally done in about 8 lines.  I did like that he documented all of his answers very well, so that’s a positive, …

Comparing your solution against the others posted here, I think you would agree that the logic was unnecessarily convoluted.

  but yeah, just a lot of inefficiency throughout his answers (processing inefficiency, object allocation inefficiency, etc)

For all practical purposes, there isn't going to be much user-visible difference in performance of your printMultTable() and the better implementations.  I don't think that there's much object allocation to speak of in this particular solution; that feedback probably referred to the solutions you wrote for the other tasks.  But judging from the way you used a zoo of variables without any clear purpose, I'm inclined to believe their assessment.


Header and navbar animations on a website

You can condense this a bit by using jQuery's hover method:

$('h1.post').hover(function() {
    $(this).animate({ paddingLeft: 10 }, 300);
}, function() {
    $(this).animate({ paddingLeft: 0 }, 300);
});

$("h1#button").hover(function() {
    $(this).animate({opacity: 0.60}, 100);
}, function() {
    $(this).animate({opacity: 1}, 100);
});


Form involving several models related to each other

This view knows far too much about your data model structure.

One level of nesting is reasonably acceptable, but this many is dangerous : in fact, this view needs knowledge about no less than 4 different business objects, not to mention it has to know the relations between them.

Solution 1 : the facade pattern

Abstract away all those details in another object, which would be the sole source of truth for your view : call it a form object, or a presenter, or a context in DCI idiom, whatever.

The idea is that this object has a simple interface that maps to the complex underlying system. We'd need more details on your business logic to be able to help you on this one.

Solution 2 : cook your own "accepts_nested_attributes" method

on your UserRelation model, create a ratings method that provides direct access to your ratings. Then create another method that allows assignment, like ratings_attributes=. In this method, process the passed parameters to create / update associated ratings ; you can find inspiration for this in the source for the accept_nested_attributes method.


StringBuilder replacing specific characters

It's two consecutive ranges that you want to get replaced with *. So, I'd do two loops like:

    for (int i = 1; i < mp-1; i++) {
        sb.setCharAt(i, '*');
    }
    for (int i = mp+2; i < mp+dp-1; i++) {
        sb.setCharAt(i, '*');
    }

And add some sanity checks that the @ and . characters are present.


Theres nothing particularly unefficient about what you have, but there are a couple of things. instead of storing the variables like

$daysweek=$_POST['daysweek'];

just leave them in $_POST like

if($_POST['daysweek']==7){//..

and then instead of

echo "1. you got the right answer: $daysweek
";

you already know the answer is 7 so just

echo "1. you got the right answer: 7
";

but based on the content of your application you are not yet in a place where you need to be worrying about optimization


In your Match class, I would mark the two private dictionaries as readonly to signify intent and keep them from being assigned to accidentally anywhere else:

private readonly Dictionary<Type, Delegate> funcs =
    new Dictionary<Type, Delegate>();

private readonly Dictionary<TIn, TReturn> values =
    new Dictionary<TIn, TReturn>();

Secondly, I'd design to interfaces and make them IDictionaries as good OO practice:

private readonly IDictionary<Type, Delegate> funcs =
    new Dictionary<Type, Delegate>();

private readonly IDictionary<TIn, TReturn> values =
    new Dictionary<TIn, TReturn>();

In your example classes, you should forego public member data and use properties accessing backing fields (also marked readonly):

abstract class Expression
{
    private readonly double _Value;

    protected Expression(double value)
    {
        this._Value = value;
    }

    public double Value
    {
        get
        {
            return this._Value;
        }
    }
}

abstract class BinaryExpression : Expression
{
    private readonly Expression _Left;

    private readonly Expression _Right;

    public BinaryExpression(Expression left, Expression right) : base(default(double))
    {
        this._Left = left;
        this._Right = right;
    }

    public Expression Left
    {
        get
        {
            return this._Left;
        }
    }

    public Expression Right
    {
        get
        {
            return this._Right;
        }
    }
}

class Add : BinaryExpression
{
    public Add(Expression left, Expression right) : base(left, right)
    {
    }
}

class Mul : BinaryExpression
{
    public Mul(Expression left, Expression right) : base(left, right)
    {
    }
}

class Num : Expression
{
    public Num(double x) : base(x)
    {
    }
}


Speeding up my implementation of Project Euler #3

By inspection, n has no even factors.  You only need to try odd factors.

Whenever you find an i that is a divisor of n, you should factor out all powers of i.  There is also no need for i to start from scratch — your hunt for divisors should proceed monotonically upward.

Your search can end when i reaches or surpasses the square root of n.  At that point, n is the answer to the challenge.

(A reasonable algorithm should obtain the answer within milliseconds.)


First and foremost : your code contains a subtle bug.
Try this input : {"1 2", "4 3", "5 5", "2 3", "1 3"}

As for style;

please respect standard naming conventions.
seperate concerns : parsing the string into a pair should be done in a separate method, this will improve readability.
it's unclear from just looking at your code what the algorithm does exactly. Try finding a better name for the method and certain variables. If that's insufficient, some documentation can also help.
probably this is an exercise, as your algorithm simply prints its result, rather than return it. But generally such methods are useless, plus it mingles concerns again. Make the method return its result, and make a client method print the result. The main method would then call three methods

List<Set<Integer>> pairs = parse(input);
List<Set<Integer>> clusters = calculateClusters(pairs);
print(clusters);


Using a MutationObserver to reformat numbers in the user's locale

One issue I'm seeing is that you're listening to the entire tree. While not an issue in small apps, it might be an issue for huge apps, with deep trees. Consider limiting it to the places where you expect your custom tag will exist.

If you are in control of the process of adding these elements to the DOM, consider doing this transformation there instead of listening to the entire DOM for you to change it. It will be easier to debug since the transformation is involved in the process of generating that element, instead of an indirect side-effect of some other operation.

You know that feeling when someone else's JavaScript re-arranges the HTML you rendered on the backend and you had to hunt it down? Same story.


Comparing a list of messages with a list inside an object

Instead of this:

final List<String> actualErrors = new ArrayList<>()

I believe you can write simply:

final actualErrors = []

I don't really understand the point of this:

assert [ ] == ((actualErrors - expectedErrors) + (expectedErrors - actualErrors))

The only way this will be true is if this is true:

assert actualErrors == expectedErrors

Which is a lot simpler.

Btw, this is not idiomatic in Groovy:

assert [ ] == something

This is the idiomatic way:

assert !something

(because non-empty collections are true)


Formatting
I assume the indentation to be a copy-paste error when removing the
boilerplate struct Solution mandated by LeetCode.
Run cargo fmt on your code to conform to the standard Rust
formatting guidelines.
Interface
LeetCode made a poor choice by using Vec<Vec<i32>> to represent a
two-dimensional array, which is generally inefficient as it stores
elements in multiple segmented allocations, incur double indirection
costs, and fail to maintain proper structure (against jagged arrays).
We can't do anything against this, though, so I'll ignore it for the
rest of the post.
Similarly, i32 is not ideal for color representation — a
dedicated type (e.g., struct Color(i32);) is clearly superior.  At
the very least, we can somehow improve readability by using a type
alias and use it consistently for colors in the code:
type Color = i32;

i32 vs. usize
Generally, it is preferred to store and compute indexes in usize,
which is the natural type for this purpose.  One way you can avoid
subtracting 1 is by using usize::MAX and wrapping_add.
To convert from the i32 values that the function receives,
try_from is preferred over as, since the latter silently
truncates invalid values.  unwrap can be used here since it's for
LeetCode; in real-world code, the error should be handled accordingly.

Is if (0..image.len()).contains(x1) better than if x1>=0 && x1<image.len() for the range check?

I'd say yes.  It indicates the intent more clearly.
Simplifying control flow
Instead of wrapping everything in an if expression, check for
image[sr][sc] == new_color and return early.
while let
This:
while !cells.is_empty() {
    if let Some((sr, sc)) = cells.pop_front() {

is just a convoluted way of saying
while let Some((sr, sc)) = cells.pop_front() {

Here's how I modified your implementation:
type Color = i32;

pub fn flood_fill(
    mut image: Vec<Vec<Color>>,
    sr: i32,
    sc: i32,
    new_color: Color,
) -> Vec<Vec<Color>> {
    use std::collections::VecDeque;
    use std::convert::TryFrom;

    let sr = usize::try_from(sr).unwrap();
    let sc = usize::try_from(sc).unwrap();

    let initial_color = image[sr][sc];

    if initial_color == new_color {
        return image;
    }

    let height = image.len();
    let width = image[0].len();

    let mut cells: VecDeque<(usize, usize)> = VecDeque::new();
    cells.push_back((sr, sc));

    while let Some((sr, sc)) = cells.pop_front() {
        let cell = &mut image[sr][sc];

        if *cell != initial_color {
            continue;
        }

        *cell = new_color;

        const OFFSETS: &[(usize, usize)] = &[(0, usize::MAX), (usize::MAX, 0), (0, 1), (1, 0)];

        for (delta_r, delta_c) in OFFSETS.iter().copied() {
            let new_r = sr.wrapping_add(delta_r);
            let new_c = sc.wrapping_add(delta_c);

            if new_r < height && new_c < width {
                cells.push_back((new_r, new_c));
            }
        }
    }

    image
}


Is there any better way of defining respective data structures to read the sensor data into from driver/application file?

I will give you some tips about defining structs that later are going to be part of a file, of course you can do in other way but this is the way I follow in general. I understand that the following struct is the header of the file.

typedef struct {
    I2C_TypeDef *pI2Cx;
    I2C_Config_t I2C_Config;
    I2C_State I2C_State;
    uint8_t *txBuffer;
    uint8_t *pRxBuffer;
    uint8_t rxStartIndex;
    uint8_t rxBufferSize;
    uint8_t txBufferLength;
    uint8_t rxBufferLength;
} I2C_Handle_t;

In general header files contains some bytes for identification(check libmagic library), the second tip is to have all the types group to avoid misalignment of data. So your struct will be

typedef struct {
    uint32_t magic; // The magic value
    I2C_Config_t I2C_Config;
    I2C_State I2C_State;
    I2C_TypeDef *pI2Cx;
    uint8_t *txBuffer;
    uint8_t *pRxBuffer;
    uint8_t rxStartIndex;
    uint8_t rxBufferSize;
    uint8_t txBufferLength;
    uint8_t rxBufferLength;
} I2C_Handle_t;

Also you can use the attribute packed of the compiler if needed alignment of the data struct.


Calculator that is part of a multipurpose program

I would suggest using a dict as switch-statement like structure.

First some global helper functions/data structures:

math_dict_binary = {'+': lambda a, b: a+b,
                    '-': lambda a, b: a-b,
                    # fill out the rest of you binary functions
                   }
math_dict_uniary = {'sqrt': math.sqrt,
                    # rest of you uniary
                   }

def get_input(str_prompt):
    input = int(input("       * {}:  ".format(str_prompt)))
    blank()
    return input

in your main body:

elif userIn == ("math"):
    op = str(input("    * Enter operation (+, -, *, /, exp, sqrt, log): "))
    blank()
    if op in math_dict_binary:
        input_1 = get_input("Enter first number")
        input_2 = get_input("Enter second number")
        print( "    " + str(math_dict_binary[op](input_1, input_2)))
    elif op in math_dict_uniary:
        input_1 = get_input("Enter number")
        print( "    " + str(math_dict_uniary[op](input_1)))
    else:
        print("Not a vlaid math option")
        # deal with it


Naming. Mostly good. You're making the effort to be descriptive with it, which is awesome. I would change odd_number to odd_numbers since it's a list. Also, prime_number really tells me nothing about what the function is actually doing. Not going to suggest an alternative name, because I'll have more to say about this function later. Warring_Number violates PEP 8. (warring_number instead.)

More, descriptive functions. This can make it easier to get a high-level understanding of what's going on when you're reading it. For example, at the start of warring_number, you could do odd_numbers = get_odd_numbers_in_interval(5, maximum). More importantly though, in your prime_number function, you can just do:

for e in number_list:
    if is_prime(e):
        #etc.

This not only makes it more clear what you're doing. You're also making it so that when you want to speed up checking if a number is prime, you don't have to worry about how that logic will affect anything else. It's all right in one place.

Speaking of...

Avoid brute force. If you finding yourself iterating over every single possibility, it's usually worth it to see if there's a clever way to speed things up. Checking if a number is prime has been researched a lot, so I would just go to Wikipedia or StackOverflow and use an algorithm that I'm not smart enough to come up with myself. For checking if a number is a sum of three primes, let's think about it.

Right now, your check for, say, 13 looks something like this:

2 + 2 + 2 = 6
2 + 2 + 3 = 7
2 + 2 + 5 = 9
2 + 2 + 7 = 11
2 + 2 + 11 = 15
etc.

Let's do it manually, and apply a bit of thought.

for i in list_of_primes:
    for j in list_of_primes:

At this point, there is a unique number x such that i + j + x = e. So let's just check that and move on

        if is_prime(e - (i + j)):

More on prime_numbers: I really don't like that it returns 4 values of each prime. It's not an obvious thing to do, and I would prefer to have the calling code manipulate the return value so it looks like it needs to. In any case, you already have a use for the function where you don't want duplicates of every prime. Additionally, it is a rather expensive function, and you call it twice. Instead, you could do:

prime_number_list = prime_number(maximum)
combination_of_prime_number = combinations(prime_number_list, 3)

Style comments: Spaces around operators, please. if e % divisor == 0 is much easier to read than if e%divisor==0.

Instead of

if boolean:
    return False
else:
    return True

You can just do:

return not boolean

Actually, I believe this is a bug in div_by_two. It should just be

def div_by_two(n):
    if n % 2 == 0:
        return True
    else:
        return False

Which would simplify to

def div_by_two(n):
    return n % 2 == 0


Average calculation issue

The example data happens to be a 3x3 matrix of values, so the calculation of the average appears to be correct. However, try using a 2x3 matrix of values (i.e. remove the 3rd sub-array of values) - it should become clear that the divisor used in the calculation of the average is incorrect.

One should divide the sum by the number of readings corresponding to each key, not the number of keys in each sub-array- i.e. divide by payload.length instead of array.length in the callback to Array.map().

Original Array Modification

le_m is correct with the statement in the comment:

  Above payload.reduce(...) mutates the first element of payload - that is probably unexpected behavior and could cause bugs further on.

This is because the initialValue parameter of Array.reduce() is omitted, which causes payload[0] to be used as accumulator the first time 1. This can be observed by inspecting the values of currentIndex in the callback - for the sample data, it starts with 1 and ends with 2.

In order to not mutate the first element of payload, a deep clone of the first element can be used (e.g. with JSON.parse() and JSON.stringify()).

let initialValue = [];
if (payload.length) {
    initialValue = JSON.parse(JSON.stringify(payload[0]));
}
const result = payload.reduce((accumulator, currentValue, currentIndex) => {
    /*...*/
}, initialValue)).map((currentValue, index, array) => {
    return [currentValue[0], currentValue[1] / array.length]
});

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Parameters


Frankly, it seems unnecessary to have any custom exceptions (and if you keep them, they should all have PEP-8-compliant names). All of the custom exceptions could just be ValueErrors ("when a built-in operation or function receives an argument that has the right type but an inappropriate value") with different messages, e.g.:

if not nums or not fractions: # note empty collections evaluate False in a boolean context
    raise ValueError("Null sample space")


Yes, there is a more elegant way of doing this. (That's all you wanted to know, isn't it?)

First of all, here's some general comments about your code:

Your Scanner should be closed when you are done with it. sc.close();
You use in total six different names for variables. All of these have a variable name of one or two single characters. It is hard to understand their purpose because of the short variable names you have given them. Possible better names could be currentIndex, sign, currentNumber...
Use methods. A method should do one thing and it should do that one thing well. Your main method currently does:

Receive user input and put it into an array
Determine the "final number" according to your rules for this array
Display result to user

At least make a separate method for determining the final number for an array. The method could be something like this: public static int finalNumber(int[] inputArray)

Use an if-statement to check if you are currently processing the last number. This will get rid of the last for-loop in your current code, which only loops through the array and shows the non-zero number it encounters.

There is some things that can be simplified within your algorithm as well.

loop x number of times, where x equals array size
get the value at the current index
get the sign of the current value
modify the current index by + current value
while the value at the current index is zero, modify the current index by the value of sign

When modifying the index, you can use the modulo % operator to make sure that it is within the bounds of the array.

Here is what I would do:

public static int luckyNumber(int[] a, int index) {
    List<Integer> ints = new ArrayList<Integer>(a.length);
    for (int i = 0; i < a.length; i++) {
        // Add the values to a list so that it is easy to remove them later
        ints.add(a[i]);
    }
    int lastValue = 0;
    while (!ints.isEmpty()) {
        // Save the index that should be removed later
        int oldIndex = index;
        int currentNumber = ints.get(index);
        index = index + currentNumber;

        // Make sure that the index is within a valid range
        if (index < 0)
            index += ints.size() * Math.abs(index);
        index = index % ints.size();

        // Remove the old index and adjust the index value if the index removed was before the current index.
        lastValue = ints.remove(oldIndex);
        if (oldIndex <= index) index--;
    }
    // Once the list is empty, return the last value that was removed
    return lastValue;
}

All these tests will print the lovely number 42:

System.out.println(luckyNumber(new int[]{ 1, 2, 42, 4 }, 0));
System.out.println(luckyNumber(new int[]{ 1, -1, 42, 4 }, 0));
System.out.println(luckyNumber(new int[]{ 1, -1, 2, 42, -4 }, 1));


MySQL connection using a static connection

Right now, it does not seem possible to run every type of query. For example: "SHOW FULL PROCESSLIST" or just "SELECT id FROM xyz LIMIT 0,10". Apart from this, there are a lot of things which might possibly go wrong.

What if I call the function with just one argument? arguments[1] would not exist and the query would become CALL (?). This statement is prepared and executed, but there is nothing executed.

I would suggest keeping things more easy instead of trying to merge several things together.

create a single query method which just runs "ADHOC" queries (no prepare)
create a prepare statement where you can bind parameters to the query (and execute)


C# lambda expressions as array extensions in JavaScript

Looks OK to me. I don't know that you could do anything to really squeeze more performance out of this. In the end you're mostly dependent on how $.grep performs.

I set up a jsperf test for your own alternatives and the code below, and constructing a function is by far the fastest (I put the function construction into where, and avoided using reduce since you said you'd need IE7+ support).

But! Constructing a function from text is just tremendously fragile:

Quoting a string is a pain. If the string contains single or double quotes, you can't properly quote it without a lot of parsing and escaping. You just really shouldn't try.
Your 'x.' + prop accessing can easily fail too, if the key isn't a proper "word". Any string can be a property name, including strings with spaces, reserved words, operators, etc.. You end up with code like x.hey look a string key === ...., which won't get you very far.
Using subscripting access, i.e. 'x["' + prop + '"]', will get you a bit further, but you're just back to the issue of quoting strings again.
Only primitive values can be easily compared; you'd still need a custom function for everything else.
You're changing the object that's been passed in; specifically, string values get quoted. I assume that's partly just because it's an example, but still. (I avoided this in the jsperf code.)

So yeah, it's much faster to use a function, but I'd still very much avoid constructing one on the fly. Better to just write one when necessary, or accept the performance hit otherwise.

As for the existing code, I like the iterative way of reducing the matches if the argument is an object. But I wanted to try turning the loops inside out, as I find that more straightforward:

return $.grep(this, function (item) {
  for(var prop in func) {
    if(item[prop] !== func[prop]) {
      return false;
    }
  }
  return true;
});

However, doing so is slower (somewhat to my surprise).

Otherwise, the code's fine, I only have a couple of notes.

The that variable would usually imply that you're dealing with scopes, but that isn't the case here; You can use plain this anywhere in your function. You do need a separate variable for the object-based filtering, but I'd just do something like var filtered = this.
You should throw a TypeError instead of a ReferenceError. And I'd write a slightly nicer and more helpful error message, such as "func must be either a function or an object of properties and values to filter by".
You'll probably want to add a func.hasOwnProperty(prop) check to avoid accidentally looping through a bunch of inherited properties. It's not an issue for object literals, but it can be for other objects.
You'll probably want to ensure that a copy of the original array in returned, even if nothing's been filtered. This isn't a problem if you pass in a function, but could happen if you pass in an empty object.
It's a tad heavy on the whitespace, if you ask me, but to each their own.

In the end, I get this

Array.prototype.where = function (filter) {
    switch(typeof filter) {
        case 'function':
            return $.grep(that, filter);

        case 'object':
            var filtered = this;
            for(var prop in filter) {
              if(!filter.hasOwnProperty(prop)) {
                  continue; // ignore inherited properties
              }
              filtered = $.grep(filtered, function (item) {
                  return item[prop] === filter[prop];
              });
            }
            return filtered.slice(0); // copy the array

        default:
            throw new TypeError("func must be either a function or an object of properties and values to filter by");
    }
};


Closures power and concise style vs readability and maintainability?

Lambda/anonymous functions and closures are not sophisticated enough in PHP to really be reliable at this moment, and probably wont be any time soon, if ever. They are usually too bulky to be worthwhile and typically can be replaced with a normal function or loop and be easier to read and quicker to process.

The most common way to use a lambda function, and about the only way I find acceptable, is as a callback function, which is typically called in line. But that's a matter or preference. There are other cases where they are acceptable, but, as traditional closures as seen in other languages, they fall short.

If you are planning on using a lambda function or closure more than once, then you have just defeated their purpose. As Mahn pointed out, these functions are not compiled at runtime, instead they are compiled on each use. This makes running them costly. At this point you might as well have just created a traditional function. Which, by the way, is essentially what you are doing anyways by defining them as variables before using them, only backwards. The only difference is that you are running that function twice instead of once and defining it for use in the local scope only, which is the same thing as defining a function within another function, which most people consider bad taste.

While these examples can be followed easily enough, I don't think that makes true usages "easy" to read. Sure you can figure out what's going on, but the longer they are the more difficult it becomes.

Would I consider this a nightmare? No. Would I thank you for doing this? No. In my opinion it is much better to follow a sequence of functions than read through a list of lambda functions. And no offense to Mahn, but his I would find a nightmare trying to maintain. Mostly due to his indentations though...

Also, as Mahn pointed out, why are you declaring your foreach loops that way? Traditionally that format is only used in templates.


How can I apply an Optional in which I want to call a method?

This looks mostly correct. IMO, should not use response in the map function, but results. I.e.
final ResultDO response = transformJsonToResponseDO(rawDataResponse, ResultDO.class);

return Optional.ofNullable(response)
            .map(results -> createPOIs(Collections.singletonList(results), providerResponse))
            .orElse(Collections.emptyList());

Even though they are the same in this case, typically this is how you are supposed to use Optional when you're not wrapping in #ofNullable.
Furthermore, this lets you put it all on one line:
return Optional.ofNullable(transformJsonToResponseDO(rawDataResponse, ResultDO.class))
            .map(results -> createPOIs(Collections.singletonList(results), providerResponse))
            .orElse(Collections.emptyList());


Setting up logging

You might be interested in logging.basicConfig, which can setup everything you setup there as well. It's not sufficient if you want for example both a file and a stream logger, but for a small, static configuration like this it's perfectly suitable. Your code up there becomes a simple:

logging.basicConfig(format="[%(levelname)s] %(asctime)s %(message)s", level=logging.DEBUG)
logger = logging.getLogger(__name__)

And you're done. (The default stream is sys.stderr.)

Do note that in no way, shape or form is the long form wrong - it's easier extendable, for one. However, for a quick script it might be easier to use basicConfig.

Module-level logging

I'd recommend you use a different logger for every different file, and have all of them be named the way you did that one. However, if you then also include the %(name) parameter in your format string, your logging messages will each contain the filename of the file they're logging from. This will help in debugging if you don't know exactly where the problems come from. I personally also include %(lineno) for the line number. Personally, I always use the .format method for my logging strings, which makes it look like this:

logging.basicConfig(format="{levelname: <8}:{asctime}:{name: <30}:{lineno: <4}:{message}", level=logging.DEBUG, style="{")
# Or with % formatting:
logging.basicConfig(format="%(levelname)-8s:%(asctime)s:%(name)-30s:%(lineno)-4s:%(message)s", level=logging.DEBUG)

Which tells me exactly where a logging statement was made as well. You won't have to search for your own exact wording anymore when you resume debugging your code for that one weird issue 3 months from now. You can just grab filename and linenumber and you're at the right location.


Code Smells
Remember the DRY and KISS principles of programming.
Here are some other resources with good info on general programming principles.

3 Key Software Principles You Must Understand
The Principles of Good Programming

As a maintainer or reviewer of anyone's code (our own or someone elses), when examining code we look for code smells. These give general indications of programming practices which are less than ideal. When we find code smells, it's a good clue that we need to look more closely and consider why the code smells.
There are a few obvious code smells, mostly pointed out by others already:

Ambiguous Naming Convention
Re-purposing Existing Names
Repetitive Code Patterns
Improper Use of Exceptions
Failure to Release Resources
Lack of Comments

Naming Conventions
Objects and other Variables are nouns. Methods and other functions are verbs. Name them accordingly. Do not use acronyms or abbreviations, but do not use sentences for your names either. There is no need for joining words such as 'The' or 'With'. Most importantly, one should also always strive to maintain consistent naming convention, whatever style you choose. This is more in reference to @Shree's use of executeWithPreparedStatement.
executePreparedStatement is better. It conforms to the naming convention used for the other methods in the library and avoids the use of an unnecessary preposition that doesn't add any meaning to the identifier.
Same for DBUtil. These abbreviations are common enough that there is little risk of confusion but it should still be avoided. DatabaseUtility is best. We can only assume that DB means Database, we can't be sure until we inspect source code or documentation. Forcing the reader of the code to have to guess, or research should be avoided whenever possible.
Re-using names that you are deriving from is OK when you are recreating a function that does the same thing in a different way. It is not OK when you have extended the functionality of the code you are deriving from. Pick a new name that better describes why your method is different than the original.
Repetitive Code Patterns
Next to KISS, DRY should be the most important principle of programming. DRY is why we do programming. To automate things. Failing the DRY principle means you are doing more work than you need to, introducing more potential for error and making it more difficult to maintain.
When you see repetitive code patterns, such as blanket exception handling or methods that look almost identical, consider why is it repetitive and how can you reduce the duplication of those pieces of code. Often it means reconsidering the method of implementation, not just splitting things up more.
Exception Handling
Errors and exceptions should always be handled gracefully.
Never trap exceptions and then not handle them. Printing a stack trace is not handling them. You are merely acknowledging that a problem can happen at that point but you don't care. Why add extra code if you don't care? The only thing accomplished is that the problem is guaranteed to not be fixable from outside of your function, since no caller can know that anything went wrong.
Exceptions that are unhandled should be allowed to flow up the call stack until they are handled, or until the main function is reached and then an unhandled exception error occurs.
You are better off to simply not catch the exceptions at all and just let them get passed on until you get an unhandled exception error.
You can trap them do something with them and then rethrow the exceptions if they are not actually being handled.
Resource Leaks
Make sure that you are not overriding valid handles when you open new connections.
The connect() method needs to make sure that the connection object is not already valid.
As well, in the disconnect() method you should reassign connection=null after it has been closed so that the invalid handle can't accidentally be used.
Make sure to close all open handles when you are done with them. This includes things like PreparedStatement, Statement and ResultSet objects, not just connections. These objects go into object pools just like the connection pool, which can build up and eat RAM if you forget to close things. (TIP: they all derive from the AutoCloseable/Closeable interface)
Lack of Comments
This seems so trivial but it is not. This is the biggest code smell. While we should always strive to create self-documented code, we still need comments to summarize what it is the code is doing and so that formal documentation can be generated with the least effort, written by the people who actually wrote the code. Comments come first, before code. Always. This is one most programmers most often neglect. Me too.
I should mention that I'm mostly speaking of inline documentation, not trying to teach the reader how every bit of code works.
The converse code smell to a lack of comments is too much comments. If you need comments to describe how your code works and not just what it does, then your code is probably too complex.


It does. You directly assign list->elements to the result of realloc which can return NULL, in which case your original array is leaked (but it's okay since you immediately assign a value to a NULL-based array after that, which is UB).

Few more observations.

The list itself can only be operated via its public interface that consists of methods that accept list object by pointer. Perhaps it makes sense to return by pointer from constructor, too; then you can make list's implementation an opaque struct, all its fields will be private.
You should define a destructor to release the array, that otherwise (currently) leaks.
Your current allocation strategy is inefficient. Reallocating the whole array per each new element raises push's complexity to O(N), so creating an array of N elements takes O(N²) time. A traditional approach to deal with it is adding capacity to the list object; capacity equals to the size of allocated space and grows exponentially: when list's size reaches capacity, on next element push capacity doubles, thus reducing push complexity to ammortized O(1).
Elements are stored in a contiguous array, perhaps a better descriptive name? Traditionally, list is associated with linked lists in C family.


Printing out a diamond with a user-inputted size

I see a number of things that could help you improve your code.

Don't disregard readability

Readability of code is always of use and always of interest, even if you're the only one who ever sees the code.  Since, by definition, you're asking for a code review by posting here, even that assumption is clearly faulty, because every reviewer is going to have to read and understand your code to comment usefully on it.  Even if you really were the only person to ever look at the code, if you decide to modify it some time later, readability will be important to you.

Decompose your program into functions

All of the logic here is in main in one rather long and dense chunk of code.  It would be better to decompose this into separate functions.

Don't further clutter trinary operators

The code currently includes this line:

spaces = (lines % 2 == 0) ? spaces = 0 : spaces = 1;

The problem is that the spaces = 0 and spaces = 1 on the right side are wholly uneccesary.  If you must use trinary operators, (and I question that in this case), use them correctly:

spaces = (lines % 2 == 0) ? 0 : 1;

Simpler, and better in my view, would be this:

spaces = lines & 1;

Rethink your algorithm

The biggest improvements are often found in simply rethinking and reimplementing the basic algorithm. In this case, each line is 0 or more spaces, followed by 1 or more stars.  For each increasing line in the first half, the number of spaces decrements by one and the number of stars increments by two.  A little bit of examination with paper and pencil will quickly yield algebraic expressions for the number of spaces and number of stars for each line in the top half of an n-line diamond pattern.  The bottom half is simply the reverse of the top half.  This suggests a simple algorithm.

Putting it all together

Your original program, as posted, was 44 lines long.  Using all of these hints, and with better readability, here it is in exactly half that many lines:

#include <iostream>

void multiprint(unsigned n, char ch) {
    for ( ; n; --n)
        std::cout << ch;
}

void line(unsigned n, unsigned maxline) {
    unsigned half = (maxline-1)/2;
    if (n > half) n = maxline - n - 1;
    multiprint(half - n, ' ');
    multiprint(n*2 + 1, '*');
    std::cout << '\n';
}

int main() {
    int lines;
    std::cin >> lines;

    for (int i =0; i < lines; ++i)
        line(i, lines);
}


Exercise - count binary-tree nodes with 1 leaf and 1 internal node as children

Your comments arn't really helpful, and so I'd remove them. This is as the function names say all that you would want to know.
Using the inverse of 'split the line, change the sign', more commonly know as DeMorgan's laws, you can change isInternal to be much simpler. Rather than using \$\overline{A} \lor \overline{B}\$ your can use \$\overline{A \land B}\$.
Since isInternal is the inverse of isLeaf you can just check that isLeaf(n.left) is not the same as isLeaf(n.right), as if it's not then there is one leaf and one internal.

And so you can change isWantedNode and isLeaf to:

private static boolean isWantedNode(TreeNode n) {
    if (n.left == null || n.right == null)
        return false;
    return isLeaf(n.left) != isLeaf(n.right);
}

private static boolean isLeaf(TreeNode n) {
    return n.left == null && n.right == null;
}

You may also want to change your return statment in strangeCount from a turnery, to addition of result and a turnery.
And so I'd use:

private static int strangeCount(TreeNode h) {
    if (h == null) {
        return 0;
    }
    return strangeCount(h.left) + strangeCount(h.right) + (isWantedNode(h)?1:0);
}


Removing a header and footer from text output with PDFminer

This line performs the same string splitting 3 times:

outfile = pdf.split("_")[4] + "_" + pdf.split("_")[1] + "_" + \
    pdf.split("_")[0] + ".txt"

It would be better to split only once, and also to replace the messy string concatenation:

parts = pdf.split("_")
outfile = '{}_{}_{}.txt'.format(parts[4], parts[1], parts[0])

The variables could have better names.
When I see "pdf",
it makes me think of a PDF object.
But in this code it's just the filename string.
So I'd call it pdf_filename.

I don't have this Python library you're using,
and I'm just wondering if you could rewrite all those resources that you close manually (fp, device, outfp) to use the with syntax instead like you used for txtin and txtout.
If that's not possible with this library, then nevermind.


Getting a substring of a delimited string

Yes, you can definitely simplify this.

public string GetSubstring(string input, int count, char delimiter)
{
    return string.Join(delimiter.ToString(),
                       input.Split(delimiter).Take(count));
}

Calling it is as easy as GetSubstring(input, 2, '_')

What does it do?

Split the input string by the delimiter
Take the amount of substrings you want
Glue the selected substrings together with your delimiter

Very short and sexy!

This doesn't take the substringCount > splitArray.Count() in account but you can easily add that yourself: just split up the oneliner and add the appropriate check.

Now, some comments about your code:

Use .Length instead of .Count() when possible: the former will always be an O(1) operation, the latter sometimes an O(n). It won't make a difference here since an array implements ICollection<T> (and will use this optimization) but it's a good practice to observe.
Returning null is typically avoided for good reasons, consider an empty string or exception instead (don't go for the exception in this case).
I prefer to explicitly use string.Empty rather than an empty string to avoid confusion.
Write your variable names in full -- nobody is helped by abbreviating them.
Use a StringBuilder to concatenate in a loop to avoid unnecessary string object creating.
Leave some space in your code, it will read more fluently.


I personally like the Second option, like you said it is cleaner, easier to read, and looks fairly simple and straight to the point.

I don't see any obvious mistakes in your code.

I can only suggest that you test it vigorously and perhaps check out the option given by @Jignesh Thakker in the comments.

you could reduce the amount of code by merging a variable to your return statement in the second block of code like this.

return query.FirstOrDefault( );

Instead of

var emailAddress = query.FirstOrDefault( );
return emailAddress;


Find all integral coordinates given top left corner and bottom right corner of a rectangle

Since you commented that using numpy is OK for you, you can simplify the whole rectangle computation using its advanced slicing capabilities:

>>> # Let's define a square array
...
>>> a = np.array(range(25)).reshape((5, 5))
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> # Advanced slicing allow us to extract blocks at once
...
>>> a[2:5, 1:3]
array([[11, 12],
       [16, 17],
       [21, 22]])

You just need to encapsulate this behaviour in a class for ease of use:

import numpy as np

class BattleField:
    def __init__(self, size):
        self.field = np.zeros((size, size), dtype=int)

    def receive_missile(self, power, top, left, bottom, right):
        self.field[top-1:bottom, left-1:right] ^= power

    def __str__(self):
        return str(self.field)

if __name__ == '__main__':
    missiles = [
        [3,3,1,3,2],
        [2,2,1,2,2],
        [3,1,1,2,3],
    ]
    field = BattleField(3)
    for missile in missiles:
        field.receive_missile(*missile)
    print(field)

Other points to improve from your code includes:

using more descriptive names than A, B, or C;
using functions instead of code at top-level for ease of testing/reuse;
using the if __name__ == '__main__' guard to avoid running some code when importing the file;
using direct parameters values instead of packing them in a list and unpacking them in the function call (product(*[range(N), range(N)]) => product(range(N), range(N)));
using dict.get with its default value (coords[j] = coords.get(j, 0) ^ Pi) to simplify the code.


Security

It's not safe to execute commands using system.
Try to use one of the execv functions instead (see man execv for the flavors that exist in your system).

Although you wrote that only absolute paths can be executed,
there's nothing in this code to ensure that.
If a malicious user gains access to the rule file,
they can enter a relative path,
and your program will be happy to execute that.
To make this safer using system,
the program should ensure that the paths are absolute paths.

The bottom line is, don't use system, use execv.
The big difference is that the execv commands don't use the shell,
but invoke the specified executables directly,
which frees you from potential vulnerabilities of shells,
such as environment variable command injection, and who knows what else.

Efficiency

After every validated user input,
the program re-reads the rules file.
It would be better to read and parse the rules file once at the start into an array,
and reuse it in the infinite loop of handling user input.

Simplify

This can be written simpler:

if (access(fbuffer, X_OK) == 0) {
    // ...
    // system blocks till finished
    system(fbuffer);
    break;
} else {
    // not executable or does not exist
    break;
}

Since both branches of the if-else will break,
you can move the break outside,
and simply drop the else:

if (access(fbuffer, X_OK) == 0) {
    // ...
    // system blocks till finished
    system(fbuffer);
}
// not executable or does not exist
break;