I found a few issues, here they are (in order in which they were found). The list may seem long, but this does not mean that you did a bad job. Instead, it means that the feedback is detailed ;)

If some issue starts with [major], it means that it would stop me from using your class.

[major] There is zero documentation.
The Thread struct is not really a thread. In fact, it just stores a single std::function member. Why did you name it like that?
The Threadpool has a virtual destructor. This is not necessary, because it does not make sense to inherit from it. I suggest you make it non-virtual.
The prefix get usually indicates that you return something from it. However, getThread does not return anything. Even though t is passed by reference, you do not change it. Maybe addTask is a better name.
[major] If the thread pool is full, getThread blocks until one of the threads is free. This is bad. In addition, you use an active loop to block, which means that waiting takes 100% of one CPU core. This is really bad. The whole point of threads and thread pools is that the user does not need to wait. I suggest that you copy or move the task (your std::function) into the pool and execute it as soon as some thread is free. This way, getThread can return immediately.
[major] The thread pool currently creates one std::thread for each task that is added. However, creating threads has some overhead and this will make a big difference if you have many small tasks. I suggest that you create m_capacity worker threads that grab the tasks from some container. This transforms your problem into a typical producer-consumer problem (adding a task is producing work, which is then consumed by the threads).
[major] You are using std::function<void(Args...)> to store a single task. This means that the thread pool does not support return values. A common pattern is that addTask returns a std::future which will receive the return value after some thread completed the task. Additionally, thread pool users can use the std::future to check whether the task completed and they can use it to wait for completion.
[major] The getThread function uses references of t. This means that problems will occur if t is destroyed while the thread is still running. This is bad, because t is passed by the user, so the pool has no control over its lifetime. The non-existing documentation would have been a good place to mention that t must not be destroyed before the task is finished :) Typically, you would std::move the task, which transfers the control to the pool.
If I understand m_mutex correctly, it guards m_threads against race conditions. This means that you want to lock the mutex whenever you use m_threads. Since reading from a variable while another thread modifies it is undefined behavior, you need to lock the mutex in some more places. There are some usages of m_thread or of its elements where the mutex is not locked (and I do not mean constructor/destructor).
The ThreadPoolElement has a volatile bool. Depending on compiler and platform, volatile may do what you think it does. However, you can not rely on that. You should use std::atomic<bool> instead.
Threadpool has a lower case p, but ThreadPoolElement has an upper case P.

I suggest that you refactor the Threadpool such that you do not need to create a new std::thread object for each task. Typically, a thread pool has a queue with pending tasks and a fixed number of worker threads. The worker threads grab tasks from the queue and complete them. This way, it is possible to add many tasks without the overhead of creating new threads.

You may want to look into the std::packaged_task and std::future classes, since they can simplify your implementation. You can probably get rid of the Thread and ThreadPoolElement classes.


Parsing HTML table into Pandas DataFrame

zip() with a list comprehension to the rescue:

rows_dates = soup.find_all(attrs={'data-bind': 'momentDateText: date'})
rows_category = soup.find_all(attrs={'data-bind': 'text: categoryName'})
rows_comment = soup.find_all(attrs={'data-bind': 'text: comment'})
rows_money = soup.find_all(attrs={'data-bind': 'currencyText: nationalAmount'})

data = [
    {
        "dates": date.get_text(),
        "category": category.get_text(),
        "comment": comment.get_text(),
        "money": money.get_text()
    }
    for date, category, comment, money in zip(rows_dates, rows_category, rows_comment, rows_money)
]

Or, you can do it a bit differently - zipping the lists of texts and specifying the dataframe headers via columns argument:

rows_dates = [item.get_text() for item in soup.find_all(attrs={'data-bind': 'momentDateText: date'})]
rows_category = [item.get_text() for item in soup.find_all(attrs={'data-bind': 'text: categoryName'})]
rows_comment = [item.get_text() for item in soup.find_all(attrs={'data-bind': 'text: comment'})]
rows_money = [item.get_text() for item in soup.find_all(attrs={'data-bind': 'currencyText: nationalAmount'})]

data = list(zip(rows_dates, rows_category, rows_comment, rows_money))

df = pd.DataFrame(data, columns=["dates", "category", "comment", "money"])

df = pd.DataFrame(data)


Convert all CSV files in a given directory to JSON using Python

Looks good to me. It's a perfectly sensible approach.

There's just one line I'm going to criticize:

    csvfile = os.path.splitext(filename)[0]

Picking off element zero is fine, no need to change it. Other idiomatic approaches would be name, ext = ..., or an explicit discard of name, _ = ....

What I really do advocate changing is the identifier csvfile, since the .csv extension has been stripped from it. Better to simply call it name. Then an expression like name + '.csv' can be clearly seen as a csvfile expression.

You could elide the jsonfile assignment, if you like, and similarly rows, replacing each reference with the expression.


First off, there currently is no point in having name = raw_input('Name of employee: '),
as it is never used.

Generally it's safer to never use input. For example:

>>> hello, world = 'goodbye', 'logic'
>>> input()
hello + world
'goodbyelogic'

As you can see, input evaluates the input. Which is not very safe.
Lets say you have some special information that no-one should know about.
But you stored it in a variable.
We with our 'elite haxor skillz', we could find out that information.
for example:

>>> private_key = 'my super private key'
>>> input()
globals()['private_key']
'my super private key'

Bottom line input is bad, so bad that it got removed in Python3.
And so, I would recommend to always use raw_input, in Python2.

float (input('Now enter the hours worked please:'))

First as mentioned above, this should be raw_input,
but it is flimsy, say we input a.
float will error, and the program will exit.

Instead you can use a try except statement.

while True:
    try:
        float(input('Now enter the hours worked please:'))
        break
    except ValueError:
        pass

computePay is really good.
If you are ok with using turnery operators you can re-write it, but your way is probably best.
Except for overtimerate, that should be part of overtime.
If I were to re-write your code then it would be something like:

def computePay (hours,rate):
    normal_hours, overtime_hours = hours, 0 if hours < 40 else 40, hours - 40
    overtime = (hours - 40) * 1.5 * rate if hours > 40 else 0
    return normal_hours, overtime_hours, overtime

preovertime_hours can just be a return statement.
You could even opt for it not to be a function.
I'm more inclined for the latter as it just returns hours * rate, hours * rate.
Also you should add it to computePay as it would fit better there.

In displayPay you may want to use str.format rather than format.
They're very similar, so to change to str.format you would do:

"The amount to be paid to in this pay period is ${:.2f}".format(total_pay)

As for main.
Due to all the changes above I personally would recommend that you change it to 3 function calls.
They are inputData, computePay and displayPay.
Whilst you could merge it all into one function and keep everything simple,
keeping IO away from logic is always good.

Overall your structure is pretty good. There are a lot of nice small functions.

Just to note, you should always have functions declared and used as function().
Note there is no space between the name and the brackets!

Also as some languages allow - in names,
it's always a good idea to put a space either side of operators.

You could 'wrap' your main() in a if __name__ in '__main__':.
This prevents your code running if it's not the main file.
(E.g. if someone imports your file into there code.)

But otherwise your code is good.

Just so you know currently almost all your code is dead code (It does nothing).
And so you could re-write main into:

def main():
    hours, rate = inputData()
    displayPay('', '', '', '', '', hours * rate)

  The ultimate goal is to calculate multiple payrolls before selecting to end the program

If you want this you could make a while loop like the example above to fix float(input()).
A simple way to do this is to ask a question like 'Would you like to add another user? [y/n] '.
And exit on any input that is not 'y' or 'yes'.

As I'm not going to write it for you, the following is half the loop.

if input('Would you like to add another user? [y/n] ').lower() in ['y', 'yes']:
    main()


Adding blank rows for every skipped value in a DataTable

You can have fewer lines of code by creating a the list of missing dates in a single Linq query.

The idea is:

Get the list of all dates in the given time period)
Left-Outer-Join this list with the list of given dates
Add the missing dates to the original DataTable

Dim missingDates = From a in Enumerable.Range(0, Int32.Maxvalue)
                   Let c = startMonth.AddMonths(a)
                   Take While c <= endMonth 'create list of all dates'
                   Group Join d in dtData On c Equals d("MonthDate") Into g = Group
                   Where Not g.Any() 'take only the missing ones'
                   Select c

For Each d in missingDates 'and add them to the DataTable'
    dtData.Rows.Add(d, Nothing)
Next

Using Union is also fine IMHO, but then the GetHashCode method of your comparer should return the hash code of the value you actually want to compare:

Public Function GetHashCode(obj As DataRow) As Integer _
        Implements IEqualityComparer(Of DataRow).GetHashCode
    Return obj("MonthDate").GetHashCode
End Function


Validating a string for a positive number, null/empty string

The code looks very good.

Check your requirements to see if "00", "0x0", etc are supposed to be a valid client ids.  Whatever the answer, write unit tests to capture the requirements and validate that you are meeting them.

As written, you are violating the single responsibility principle: this constructor is acting both as a coordinator (figuring out which checks to run) and as a calculator (computing whether or not the regular expression is a match).  I'd probably leave it, because the pattern is so common.

You are also (possibly) sharing some of the validation code for the "general" string based id (not null, not empty), which the rules specific to ClientId (not '0', not a negative integer).  If so, some refactoring is called for.

String.matches(regex) is just a wrapper around Pattern.matches(regex,input).  Given that you know that the regular expression isn't going to change from one call to the next, you might create a single static instance of the Pattern so that you aren't compiling it multiple times.  It does complicate the logic in the constructor somewhat

checkArgument(! pattern.matcher(clientId).matches(), "clientId must not be negative or zero");

I'd be more likely to do this if I moved the match calculation into a separate function/factory -- the performance gains are not likely to be measurable, and readability is important.

I would suggest that you consider is that your representation of the data, after it has passed all of its validation checks, should probably differ from the representation before the checks have been validated.

public class ClientId {
    // final, because we don't want code to later change the id to
    // something that isn't valid.
    private final String clientId;

    public ClientId(String clientId) {
        checkNotNull(clientId, "clientId cannot be null");
        checkArgument(clientId.length() > 0, "clientId can't be an empty string");
        checkArgument(!clientId.matches("-\\d+|0"), "clientId must not be negative or zero");

        this.clientId = clientId;
    }
}

class Builder {
    public Builder setClientId(String clientId) {
        return setClientId(new ClientId(clientId));
    }

    public Builder setClientId(ClientId clientId) {
        this.clientId = clientId;
        return this;
    }
}

Done this way, all of the code that interacts with a client id knows from the data type that the constraints on the data have already been verified.

Typically, when implementing a value type this way, you'll also want to replace the default implementations of equals() and hashcode() to make sure that you still have string like semantics available.

Less typically, you will find examples where the standard is to use marker interfaces to denote values.

public ClientId implements ValueObject<ClientId> { ... }

or even

public ClientId implements Id<ClientId> {...}

The marker interfaces will sometimes specify queries that the types must implement

public interface ValueObject<T> {
    boolean sameValueAs(T other);
}

You provide a bit of extra work in the class implementation, and you get some clarity/readability in the consumer code.

In some domains, you may need to worry about the fact that clever attackers can capture a reference to an incompletely constructed value type.  In that case, putting the data validation in the constructor won't suffice, you'll instead want to use a factory method to construct the object.  For instance:

public class ClientId {
    private final String clientId;

    private ClientId(String clientId) {
        this.clientId = clientId;
    }

    public static ClientId create(String clientId) {
        checkNotNull(clientId, "clientId cannot be null");
        checkArgument(clientId.length() > 0, "clientId can't be an empty string");
        checkArgument(!clientId.matches("-\\d+|0"), "clientId must not be negative or zero");

        // with the checks verified, we take advantage of the fact that this
        // method has access to the private constructor that is inaccessible
        // everywhere else.
        return new ClientId(clientId);
    }
}

Written this way, the checks happen before the call to the java.lang.Object constructor exits, which is a critical point in the lifetime of the potential reference.


I need to know that if everything okay in my BTS put and get method

Since the code is not compiling, it will be hard to do a proper code review.

In my opinion, you should rename the variable cmd in both of the methods, since it can be confusing.

BinaryTree#put method

In my opinion, it's a bad choice to use the range operators (<, >, <=, >=) with the compareTo method; since you always get one of those values (-1, 0 & 1).
I suggest that you check if the values are equals before checking if they are inferior / superior; this will alow you to merge some of the logic of the inferior / superior since they are pretty similar.

if (cmd == 0) {
   current.value = newNode.value;
   break;
}

if (cmd == 1) {
   //[...]
}
```


In no particular order:

Create test cases so you can have some confidence while refactoring.

Don't create empty structs (Solution) just to give them functions. next_permutation is perfectly fine as a free function. If you have to create a bad API to satisfy LeetCode or whatever, write the good API first, and then wrap it. If the API required is so bad you can't wrap a good API with it, it's probably a waste of time.

Use rustfmt.

Accept &mut [T] instead of &mut Vec<T> when you don't need to change the size.

let first = 0;
let last = nums.len();

Don't give unnecessary symbolic names to things that aren't used symbolically. 0 is far more obviously the index of the first element in a slice than first. Furthermore, you don't even need to provide the bounds of the slice when indexing with [..]; they're implied. So you need these even less than you perhaps thought.

i, i1, i2 are meaningless. How about some descriptive names?

I prefer to put each loop in a block with its state variables to limit the scope of the mutability.

let i1 = i;

Similar to the note on first and last above, don't make variables that can be trivially calculated from other variables. The relationship between i and i + 1 is way more obvious than i and i1.

if nums[i] < nums[i + 1] { ... }

Why is this body nested in the outer loop? The algorithm breaks fairly easily into four steps:

Get the index of the rightmost ascending pair of values
Get the index of the rightmost value greater than the first element of that pair
Swap the values at these two indices
Reverse the slice starting just after the first index.

You have 2, 3, and 4 nested inside 1, which makes the algorithm look more complicated than it actually is.

let tmp = nums[i];
nums[i] = nums[i2];
nums[i2] = tmp;

Use nums.swap(i, i2) instead.

As mentioned in the reddit comments, there's an iterator method rposition that finds the last item matching some predicate (if the iterator is one that can be iterated from both ends). You can use this to linearize the first (outer) loop, which may be easier to reason about. Don't go overboard, though: iterators are great for certain tasks and not so great for others. If you feel like the logic and flow of the code is better with a loop, just write the loop.

As for the inner loop, since the trailing subslice is by definition monotonically decreasing, you can search for the swap point using binary search. It's not likely to make a big performance difference, though, and the logic might be a little harder to follow, so you might want to use rposition here as well.

Applied
pub fn next_permutation(nums: &mut [i32]) -> bool {
    use std::cmp::Ordering;
    // or use feature(array_windows) on nightly
    let last_ascending = match nums.windows(2).rposition(|w| w[0] < w[1]) {
        Some(i) => i,
        None => {
            nums.reverse();
            return false;
        }
    };

    let swap_with = nums[last_ascending + 1..]
        .binary_search_by(|n| i32::cmp(&nums[last_ascending], n).then(Ordering::Less))
        .unwrap_err(); // cannot fail because the binary search will never succeed
    nums.swap(last_ascending, last_ascending + swap_with);
    nums[last_ascending + 1..].reverse();
    true
}


Using Scrapy/Xpath to scrape ESPN for football (soccer) commentaries

There are no docstrings, so a user of your class is left wondering which methods could be useful to call. In fact, after studying the code, it looks like all the methods are meant to be called by __init__, in a specific order. Makes me wonder if this should be a class at all.
You set very many instance attributes, even a self.dummy, but use very few outside the method where they are set. Most of them should be local variables instead. Again, I'm thinking that you don't need a class -- all the methods could be simple functions that take one or two parameters instead.
The purpose of the class seems to be to initialize six lists, eg. self.corners. So, to get an overview of the game, one has to access six variables. It would be better to use a single data structure that can be easily looped over and queried. Perhaps a dictionary with keys like "corners" could suit you, but I'm thinking that most useful would be to keep the events in a chronological list and provide a function to filter that list by type of event.


Your imports and module structure seems like an incredible mess. Yet your application only contains 3 files. Let's try and improve that.
Value your namespaces
import this

Preferably in an interactive session, will give you an insight of how you should approach problems in Python. In your case, it is the last line Namespaces are one honking great idea -- let's do more of those! which is at issue.
The core idea is to control where symbols can be found without risk of overriding them (or doing so knowingly). As such, from <something> import * is a bad practice and should either be:
import <something>

or
from <something> import <required_name1>, ..., <required_nameN>

This also means that you should removed unnecessary imports.
Avoid circular imports
I'm talking about having from main import * in routes.py and from routes import * in main.py.
One of the major issue with circular import is that one of them might bring an half-loaded module, (mainly) leading to NameErrors.
Why do you need to import routes in the first place? Nothing is used from that in main.py, so you can remove it.
Why do you need to import main in the first place? To be able to use render_template and the app object? Well, you should import render_template in routes.py and create app in there instead.
Don't over-split your code
Modules are good since they allow you to differentiate purposes for pieces of codes. But too much modules makes the code unmanageable.
At this stage of development you could still have all your code in a single file without loosing readability. But I imagine that you'll want to make your application grow and I understand your need to split it into different modules.
You made a good job identifying purposes:

a module to manage your webapp (routes.py);
a module to manage your GUI (in case you'll want to get something better than a QWebView in the future).

But I think you made a mistake making your GUI module "secondary". The GUI is the entry point of the application for your users, I would have made it the main module.
Then you can put routes.py into its own webapp (or whatever name fits its purpose more) folder. This will allow you to keep everything related to the "Web" part of your application in a single place. Try to at least separate your routes from your utilities functions.
You should also try to name your modules relative to what they do overall. main.py is not a good name.
New layout
pyfladesk.py
import sys

from PyQt4.QtCore import QThread, QUrl
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebView

PORT = 5000
ROOT_URL = 'http://localhost:{}'.format(PORT)

class FlaskThread(QThread):
    def __init__(self, application):
        QThread.__init__(self)
        self.application = application

    def __del__(self):
        self.wait()

    def run(self):
        self.application.run(port=PORT)

def provide_GUI_for(application):
    qtapp = QApplication(sys.argv)

    webapp = FlaskThread(application)
    webapp.start()

    qtapp.aboutToQuit.connect(webapp.terminate)

    webview = QWebView()
    webview.load(QUrl(ROOT_URL))
    webview.show()

    return qtapp.exec_()

if __name__ == '__main__':
    from webapp.routes import app
    sys.exit(provide_GUI_for(app))

webapp/routes.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

The few more changes I made contains:

improved naming a bit (not so much, you might come up with better names too);
converting magic values to constants so they can easily be spotted and changed;
used the callable webapp.terminate directly instead of creating a lambda.


Capturing and taking a screenshot of a window in a loop

Well, yes, you're holding on to a bunch of IDisposable objects which should be dealt with by employing the using statement:

IntPtr hwnd;

using (var proc = Process.GetProcessesByName(prcname)[0])
{
    hwnd = proc.MainWindowHandle;
}

RECT rc;
NativeMethods.GetWindowRect(hwnd, out rc);
using (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb))
{
    using (Graphics gfxBmp = Graphics.FromImage(bmp))
    {
        IntPtr hdcBitmap = gfxBmp.GetHdc();
        try
        {
            NativeMethods.PrintWindow(hwnd, hdcBitmap, 0);
        }
        finally
        {
            gfxBmp.ReleaseHdc(hdcBitmap);
        }
    }

    using (MemoryStream ms = new MemoryStream())
    {
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        return new MemoryStream(Lz4.CompressBytes(ms.GetBuffer()));
    }
}

Plus, the MemoryStream you return should be Dispose()'d be the calling code.


The recursion stop condition looks clumsy. First, inside the if clause you already know that jumpTower == 0. Second,

    if (condition)
        return 1;
    else
        return 0;

is a long way to say return condition. Suggested rewrite:

    if (jumpTower == 0) {
        return towers[0] >= targetTower;
    }

The two recursive calls differ only by the last parameter. This strongly hints to make the function tail-recursive:

    if (jumpTower + towers[jumpTower >= targetTower) {
       targetTower = jumpTower;
    }
    jumpTower -= 1;
    return is_hoppable(towers, jumpTower, targetTower);

and mechanically eliminate tail recursion (sorry for another shameless self promotion):

    while (jumpTower > 0) {
        if (jumpTower + towers[jumpTower >= targetTower) {
           targetTower = jumpTower;
        }
        jumpTower -= 1;
    }
    return towers[0] >= targetTower;

Now the problem is reduced to a single loop. It doesn't look right. But don't blame me. It is a mechanical rewrite (much like a C compiler would do), so if there's a problem here, there must be a problem in the original code.

The printf line is too long to my taste. I was almost sure that you print int as %s. Then I scrolled.

Returning bool rather than int would clarify intentions.


I think it is ok to re-use the Connection.

I would not try-catch all the SqlExceptions in the update* methods. Just let them throw. Then you don't need all the boolean logic either. Makes it simpler I guess.


Return the element of collection if the collection contains only one element

I think that, considering the constraints of your situation (Iterable), the implementation is about as good as it's going to get.

However, that does not mean there aren't things that couldn't be improved.

Camel case is standard for method names. I find getOnlyOne to be easier to read than the all lower case version.
It has become more of a standard to declare the result type of methods, especially if the method is part of an API. Unless it's a one-line method whose return type is blindingly obvious.

implicit class GetOnlyOne[A](val coll: Iterable[A]) {
  def getOnlyOne: Option[A] = {
    if (coll.isEmpty) None
    else if (coll.tail.isEmpty) coll.headOption
    else None
  }
}


One suggestion is to make the roles two classes, initialize them based on the role and call the save function.

 class UserRole
    def save(product)
     redirect_to new_product_offer_path(product)
    end
 end
 class AdminRole < UserRole
    def save(product)
     redirect_to krowd_path(product)
    end
 end
 def create_role(r)
    case r
    when :admin
        return AdminRole.new()
    else
        return UserRole.new()
    end
 end

 ....
 role = create_role(current_member.role)

 if @product.save
   role.save(@product)
 else
   render :new
 end


Personally I'd prefer to write this as an explicit fold. IMO that's somewhat cleaner and significantly easier to grasp when skimming

result :: [Char] -> Int
result cs@(c:_) = go $ cs ++ [c]
  where
  go :: [Char] -> Int
  go (c1:chars@(c2:_)) = (if c1 == c2 then digitToInt(c1) else 0) + (go chars)
  go _ = 0
result = 0

This removes a lot of text that I consider pretty confusing to read.


Correctness

Fix build errors

My compiler indicates that your typedef statement is missing typename before std::iterator_traits<BidirIt>::difference_type dt; Additionally, you can replace the typedef with a using statement, which is more modern:

using dt = typename std::iterator_traits<BidirIt>::difference_type;

Adhere to iterator operations

The line:

auto pivot = first + size / dt(2);

Uses the + operator, which bidirectional iterators do not support. Calling your sort on a std::list will fail to compile. You can make your code compliant with bidirectional iterators by changing the above line to:

const auto offset = size / dt(2);
auto pivot = std::next(first, offset);

Squash the bug!

I don't know the cause, but your program appears to loop forever when I give your algorithm the sequence: 1,8,4,6,5,2,0,3. This is almost certainly not desired behavior.

Code Simplicity

Return the new pivot

You can avoid taking the pivot by reference by changing partition() to return the pivot value. The new function signature would be:

template<typename BidirIt,
typename Comparator = std::less<typename std::iterator_traits<BidirIt>::value_type>>
BidirIt partition(BidirIt first,
                  BidirIt last,
                  BidirIt pivot,
                  Comparator cmp = Comparator())

And then simply return pivot; at the end of the function. But then this function signature looks familiar:

Use the standard library, Luke!

There already exists a partition() function in the standard library. You can replace your entire partition function with it, and simplify sort_quick():

    pivot = std::partition(first, last, [&] (auto value)
                           {
                               return cmp(value, *pivot);
                           });

The use of auto in the lambda is a C++14 feature, you will have to write out the correct type if you can only use C++11. Also, using std::partition fixes the loop-forever bug on my "bad" input, but still doesn't quite give correct results.

Minor Issues

Unused comparator

sort_quick() accepts a comparator function argument, but the comparator is never used inside the body of the function.

Restrict Iterator types

Currently you rely on convention that your iterator types are bidirectional. You could produce nicer error messages by using static_assert, possibly like this:

using category = typename std::iterator_traits<BidirIt>::iterator_category;
static_assert(std::is_base_of<std::bidirectional_iterator_tag, category>::value, "This algorithm requires bidirectional iterators.");


Returning a mutable copy of the temporary array makes no sense to me,
perhaps you meant

return [muArrRaw copy];

to return an immutable array (as the return type of the method indicates).

The "proper" data type for array indices is NSUInteger, not int.

In

if (j < ([muArrRaw count] - 1) && [[muArrRaw objectAtIndex:j] intValue] > [[muArrRaw objectAtIndex:(j + 1)] intValue]) {

you can get rid of the extra check j < ([muArrRaw count] - 1) if the
outer loop starts with i = 1.

Also [muArrRaw objectAtIndex:j] can be shortened to muArrRaw[i],

for (NSUInteger i = 1; i < [muArrRaw count]; i++) {
    for (NSUInteger j = 0; j < [muArrRaw count] - i; j++) {
        if ([muArrRaw[j] intValue] > [muArrRaw[j + 1] intValue]) {
            // ...
        }
    }
}

Swapping two elements in the array can be simplified by using
the existing method:

[muArrRaw exchangeObjectAtIndex:j withObjectAtIndex:j+1];

If no elements were swapped at all in some pass then the array is
already sorted and there is no need to continue:

BOOL swapped;
NSUInteger n = [muArrRaw count];
do {
    swapped = NO;
    for (NSUInteger j = 0; j + 1 < n; j++) {
        if ([muArrRaw[j] intValue] > [muArrRaw[j + 1] intValue]) {
            [muArrRaw exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            swapped = YES;
        }
    }
    n--;
} while (swapped);

Your method is limited to arrays of integers. If you compare two
array elements with

if ([muArrRaw[j] compare:muArrRaw[j+1]] == NSOrderedDescending) { ... }

instead then it applies to all element types which have a compare:
method (e.g. NSNumber, NSString, NSDate ...).

Even more general, you can add a comparator argument, as suggested in this
answer:

My own method for sorting numbers in array


Instead of trying to purify the category for the user, which may or may not have unexpected results, you should simply reject everything that does not conform to your level of standard, and let the user fix it:

function isValidCategoryName($string) {
    return preg_match("/^[A-Z][a-z0-9 ]+$/", $string);
}

If it doesn't match, prompt the user with an error message and tell him to try again. Your job isn't to try to extract a good category from a bad one.

At most you could just correct the case with ucfirst if you want.


Get file absolute path from file URL in PHP

This should be the most cross platform way and uses less memory (also doesn't depend on wp)

function get_file_path_from_url( $file_url ){
   return realpath($_SERVER['DOCUMENT_ROOT'] . parse_url( $file_url, PHP_URL_PATH ));
}

It uses the native PHP function realpath().


assorted findings

your code does not document what predict() accomplishes
• I don't even get how the name predict is telling/helpful
• your code documents neither the approach chosen nor alternatives disregarded
comparing a cheaper monotone function of Euclidean distance: nice
• naming the variables without fussing that it's equivalent Euclidean at the end of the day rather than equal to or sum/Manhattan or max: nice, again
camelCase is not pythonic
initial value for minDistances should be height*height+width*width+1
the approach visits each and every element of mask
no mask[x].index(True) (careful with mask[x].reverse().index(True))
the squares get computed time and again
looks especially off with x
code for the four pairs looks repetitive
naming too, come to think of it
the mask example is useless for showing one value, only

context provided is lacking: what is get the corners of [not-exactly-]quadrilateral?

alternative approaches to find closest to the [image] corners

start from the middle
when you find an element set, you still have to inspect all the element closer to the corner, up to the corner itself
just complicates iteration
proceed in order of increasing distance from the corners
+: you find elements set close to the corner early on
  you don't need to look any further for that corner
-: even with at least one element set, there may be more than two visits on average (solitary True in one corner)


The only thing that changes between the first and second half is the query parameters.

<?php

foreach (array('news' => 3, 'reviews' => 4) as $category => $posts_per_page) {
    $wp_query = new WP_Query(
        "category_name=$category&posts_per_page=$posts_per_page"
    );
    while ( $wp_query->have_posts() ) {
        # etc.
    }
}

?>


Webservice class with parser using generics

Turns out I can just use the generic ModelType defined in the ParserType, and I don't need the same generic parameter in WebService;

public class WebService<Parser: ParserType> {
...

The typealias is just for convenience, to not type ParserType.ModelType everywhere but just ModelType.

Results in this call site:

let transport = HTTPTransport(baseURL: URL(string: baseURLString)!)
let parser = JSONParser<CategoryArray>()
let webService: WebService<JSONParser<CategoryArray>> webService = WebService(transport: transport, endpoint: endPoint, parser: parser)

(And because of type inference, the last line can be reduced to let webService = WebService(transport: transport, endpoint: endPoint, parser: parser) which is neat)


Overall
Please fix the formatting.
It's hard to find the public/private sections that way this is formatted.

A fundamental miss of your dynamic array is that objects are not correctly created or destroyed.
You use malloc() and realloc() to allocate memory. But these functions do not call the constructors on class type objects. Thus the memory is not correctly initialized to hold objects of type T, it is undefined behavior to use these objects until they have been correctly initialized (with a constructor).
Conversely you also need to call the destructor when the object is popped or the destructor for your vector is called.
As a result your code is fundamentally broken.

You have not correctly implemented the rule of three.
Please look it up. But basically if your object owns a pointer you need to overide the compiler implementation of several functions correctly.
As a result your code is fundamentally broken.

You have not thought about move semantics.
Since C++11 (9 years ago). C++ has had the concept of move semantics that allow objects to be moved rather than copied. In the worst case this is no worse than a copy but in the best case it is much better than a copy and makes classes a lot more efficient if you start passing them around (eg return values).
This is a nice to have but to be honest expected especially for containers in modern code.

Code Review
This line:
    using size_type = size_t;

means that somewhere (not included) you have the line:
using namespace std;

This is a problem for anything but toy code. Please stop adding this line to your code. Read any other C++ review.
See: Why is “using namespace std;” considered bad practice?

I have no problem you not checking that m_Used is not zero here.
    void pop(void) {
      changeSize(--m_Used);
    }

But it is inconsistent when you do check it here.
    void pop(size_type index) {
      if (!(index < m_Size)) return;
      changeSize(m_Used -= index);
    }

Choose one. Either always check or never check. The std::vector<> does not check. But provides the appropriate functions that allow the user of the vector to validate the state so it can be called safely.

This is not enough:
      changeSize(--m_Used);

If you remove an object from the vector you need to destroy it. This means calling its destructor. Classes of type T may depend on the constructor/destructor being called.
You can call it manually.
      m_Buffer[m_Used].~T();
      changeSize(--m_Used);

Why are you calling changeSize() in the pop?
The whole point of having a m_Used and m_Size members is that you may have unused space in your vector that you can utilize on the next push without having to re-size the vector on every single operation!

Conversely on the push. You can simply call the assignment operator.
        m_Buffer[m_Used - 1] = obj;

Since you allocated the space with malloc() or realloc() this space has not been correctly initialized with the constructor thus calling the assignment operator on this object is not valid.
You can call the constructor by using placement new
        new (m_Buffer + m_Used) T(obj);  // Call the copy constructor
                                         // using placement new
        ++m_Used;

Don't use the inline keyword unless you need to.
    inline size_type used(void) const { return m_Used; }
    inline size_type size(void) const { return m_Size; }

Here you don't need to. It does not force the compiler to actually "inline" the code (it actually does nothing on modern compilers as the compiler engineers realized long ago the programmers are bad and the compiler is much better at making that decision).

Yes perfectly good.
    inline T* begin(void) { return m_Buffer; }
    inline T* end(void) { return begin() + m_Used; }
    inline const T* const begin(void) const { return m_Buffer; }
    inline const T* const end(void) const { return begin() + m_Used; }

Though personally I would have abstracted the iterator.
    using iterator = T*;
    using const_iterator = T const*;

The other thing to think about is that the standard containers contain a couple of additional iterator methods.
    const_iterator cbegin() const;  // Notice the 'c'
    const_iterator cend()   const;

Also reverse iterators are worth using.
    <something>       rbegin();
    <const something> crbeign() const;
    // etc

Using the keyword and seems weird.
      if (m_Buffer and !(m_Size < _size)) return 1;

Yes its valid. But you need to add a special header. Also most engineers are simply used to reading &&.

Constructors at last.
Would be nice to put constructors/destructors/assignment near the top. This the first thing you need to know about a class (also the first thing people in code review want to check).
    // Sure this is fine.
    // But only space for one item?
    // Why not pre-allocate 10 so you don't need to reallocate on each push.
    // You don't need void here.
    myVector(void) {
      m_Buffer = (T*)malloc(sizeof(T));
      m_Used = 0;
      m_Size = 1;
    }

    // Normally the assignment operator is written in terms of the
    // copy constructor. You seem to have done this the complete other
    // way around. But it also mens that you should initialize all the
    // members before you call the assignment operator (it is assuming
    // you are using a fully formed object not one with random values)
    //
    // Go look up the copy and swap idiom.
    myVector(const myVector<T>& other) {
      *this = other;
    }

    // What about self assignment.
    // It is perfectly valid to assign to yourself. Your code
    // needs to work in this situation. If the rhs has a null
    // buffer why does nothing change?
    //
    // See Copy and swap idiom.
    myVector<T>& operator=(const myVector<T>& rhs) {
      if(rhs.m_Buffer){
        m_Used = rhs.m_Used;
        m_Size = rhs.m_Size;

        // This frees your buffer.
        // But what happens to all the objects of type T.
        // You just leaked them all without calling there destructor.
        free(m_Buffer);

        // What happens if this fails?
        // Well with strong exception safety you would not change the
        // current object and throw an exception. But you have lost
        // all the old state so if you throw you are in a bad state.
        m_Buffer = (T*)malloc(sizeof(T) * m_Size);
        memcpy(m_Buffer,rhs.m_Buffer,sizeof(T) * m_Size);
      }
      return *this;
    }

This is how your constructors should look (approximately).
    // Please not the use of initializer list.
    // I am using malloc here because you did (but you can do better).
    myVector()
        : m_buffer(malloc(sizeof(T) * 10))
        , m_Used(0)
        , m_Size(10)
    {}

    // Copy constructor.
    myVector(myVector const& copy)
        : m_buffer(malloc(sizeof (T) * copy.m_Used)
        , m_Used(0)           // We will update this in the code.
        , m_Size(copy.m_Used)
    {
        for(int loop = 0; loop < m_Used; ++loop) {
            push(copy.buffer[loop]);
        }
    }

    // Copy Assignment
    // Use Copy and Swap Idiom (look it up)
    myVector& operator=(myVector const& rhs)
    {
        myVector copy(rhs);   // safely make a copy.
        swap(copy);           // swap the copy and the current object.
        return *this;
    }                         // Note copy destroyed here.
                              // Thus the old array is deleted.

    // Destructor
    ~myVector()
    {
        clear();             // delete all the objects.
        free(m_buffer);
    }

    // Swapping
    void swap(myVector& other) noexcept
    {
         using std::swap;
         swap(m_buffer,    other.m_buffer);
         swap(m_Used,      other.m_used);
         swap(m_Size,      other.m_size);
    }
    friend void swap(myVector& lhs, myVector& rhs)
    {
         lhs.swap(rhs);
    }

    // Move semantics are relatively simple:
    myVector(myVector&& move) noexcept
        : m_buffer(nullptr)
        , m_Used(0)
        , m_Size(0)
    {
        swap(move);
    }
    myVector& operator(myVector&& move) noexcept
    {
        clear();
        swap(move);
        return *this;
    }

    // Now just implement push/clear

Not advisable to do this!!
    template<size_type N>
    myVector(const T (&inputArr)[N]) {
      *this = inputArr;
    }

--
You can't use memcpy() on T if it has a constructor.
      memcpy(m_Buffer,inputArr, N * sizeof(T));

In C++ this is most types. So this is going to fail to correctly construct these objects.

Self Plug
I wrote a couple of articles on how to write a vector. Please have a read. It goes through everything I have said here and then dives into some more detail.
Resource Management Allocation
Resource Management Copy Swap
Resize
Simple Optimizations
The Other Stuff
ReSize Maths


Array manipulation: add a value to each of the array elements between two given indices

Nice implementation, it's already very efficient. Few suggestions:

Expand the variables in the for-loop from for q in queries to for a, b, k in queries. Given the problem description it's easier to read.
A better name for the variable current can be running_sum.
Avoid calling a variable max, since it's a built-in function in Python. An alternative name can be result.
If you change the name of the variable max then you can have result = max(result,running_sum).
As @hjpotter92 said, is better to add a description of your approach in the question, you will likely get more reviews. Few bullet points or some comments in the code is better than nothing.

Applying the suggestions:
def arrayManipulation(n, queries):
    nums = [0] * (n + 1)
    for a, b, k in queries:
        nums[a - 1] += k
        nums[b] -= k
    running_sum = 0
    result = 0
    for i in nums:
        running_sum += i
        result = max(result, running_sum)
    return result

It's already an efficient solution that runs in \$O(n+m)\$, so I wouldn't worry about performances. However, there is an alternative solution running in \$O(m*log(m))\$ in the Editorial of HackerRank.
I implemented it in Python:
def arrayManipulation(n, queries):
    indices = []
    for a, b, k in queries:
        indices.append((a, k))
        indices.append((b + 1, -k))
    indices.sort()
    running_sum = 0
    result = 0
    for _, k in indices:
        running_sum += k
        result = max(result, running_sum)
    return result

It's based on the fact that it's enough finding the running sum on the sorted indices.
FYI in the Editorial (or Discussion) section of HackerRank there are optimal solutions and detailed explanations.
Thanks to @superbrain for the corrections provided in the comments.


Bottom up mergesort - singly linked list

Just some random notes:

l := new(list)
l.head = getNode(arr[0])

This is usually spelled l := &list{head: getNode(arr[0])}.

n := new(node)
n.val = v

Again, can be shortened to n := &node{val: v}.

var head *node
var prev *node
var end *node
var penult *node

Shorten to var head, prev, end, penult *node.

func append

This is a very bad name for a function because it clashes with a built-in. Better change to something like appendList or make it a method.


Functional Programming: int to bignum conversions

num==0 is misleading, use num=0 (although it has the same meaning for integers). Also, fromInt is spread over too many lines for my taste, I'd prefer the following choice of line breaks:

let fromInt (n: int) : bignum =
  let rec aux num : int list =
    if num=0 then []
    else abs (num mod base) :: aux (num/base) in
  {neg=n<0; coeffs=List.rev (aux n)}

This is fine for short lists of coefficients. In general tail recursion is preferred. I drop type annotations below. I add type annotations during debugging if I start getting confusing type errors, other than that I put types of functions in the interface (.mli).

let fromInt n =
  let rec aux acc num =
    if num=0 then acc
    else aux (abs (num mod base) :: acc) (num/base) in
  {neg=n<0; coeffs=aux n}

General note. I use the following kinds of line breaks with if..then..else depending on what fits in 80 columns and looks nice.

if test then blah
else blah

if test
then blah
else blah

if test
then
  blah
else
  blah

Now on to toInt. First, the way I would format it:

let toInt b =
  let rec aux b p =
    match b with
    | [] -> Some 0
    | hd::tl ->
      match aux tl (p*base) with
      | Some c->
        let bint = hd*p in
        if bint < hd then None
        else Some (bint+c)
      | None -> None in
  let c = List.rev b.coeffs in
  match aux c 1 with
  | Some c -> if b.neg then Some (-c) else Some c
  | None -> None

Again, it is interesting to explore the tail-recursive variant. I use my preferred style.

let toInt b =
  let rec aux acc p = function
    | [] -> Some acc
    | hd::tl ->
        let bint = hd*p in
        if bint < hd then None
        else aux (bint + acc) (p*base) tl in
  let c = List.rev b.coeffs in
  match aux 0 1 c with
  | Some c -> if b.neg then Some (-c) else Some c
  | None -> None


A "policy-based" design for a generic CUDA kernel

Is there a good reason against using the thrust library? It seems to come with the nvcc compiler and provides that kind of functionality:

#include <iostream>
#include <thrust/transform.h>

__device__ __managed__ float x[2], y[2];

template <typename T> struct square {
    __host__ __device__ T operator()(const T& x) const {
        return x * x;
    }
};

int main(int argc, char const *argv[]) {
    x[0] = 1; x[1] = 2;
    thrust::transform(x, x + 2, y, square<float>());
    std::cout << x[0] << "**2 = " << y[0] << "\n";
    std::cout << x[1] << "**2 = " << y[1];
    return 0;
}


Controlling permissions in a MVP application

Full disclosure: I haven't done much with windows forms applications, so I may be breaking some otherwise well known winforms programming patterns.

Permissions are better handled by a service, so that you can more easily unit test that layer, plus the permissions logic becomes portable between presenters to promote DRYness of your code (Don't Repeat Yourself).

public class UserPermissionsService
{
    private User _user = null;

    public UserPermissionsService(User user)
    {
        _user = user;
    }

    public bool CanEditAccount { get { return _user.PermissionList.Contains("CanEditAccount"); } }
}

Then to use it:

public partial class BankAccountDetailEntering : Form
{
    UserPermissionsService PermissionsService { get; set; }

    public BankAccountDetailEntering()
    {
        InitializeComponent();
    }

    private void BankAccountDetailEntering_Load(object sender, EventArgs e)
    {
        cmdEditAccount.enabled = PermissionsService.CanEditAccount;
    }
}

The BankAccountDetailEntering form would need to instantiate the user permissions service with the proper user object before the BankAccountDetailEntering_Load method gets called.


Optimising iteration and substitution over large dataset

How to resolve the output size issue (many GB in memory and console) is highly specific to your overall setting, i.e. how you want to use the data further, so I restrict my answer to look into possible performance gains.

Performance baseline

I determine the baseline by restricting you original loop logic to the first 20 pairs:

t0=res.tolist()
t0=[tuple(x) for x in t0]
t1=Pairs
t2=mod

def run_loop_original(limit=20):
    # Make substitions
    result = []
    for i_pair, (v1, v2) in enumerate(zip(t1, t2)):
        if i_pair >= limit:
            break
        out = []
        for i in t0:
            common = set(v1).intersection(i)
            if set(v1) == common:
                out.append(tuple(list(set(i) - common) + [v2]))
            else:
                out.append(tuple(i))
        result.append(out)
    return result

    >>> %timeit run_loop_original(20)
    1 loops, best of 3: 1.33 s per loop

Performance Sinks

As far as I can tell, those are:

type conversion of string arrays
repeated string comparisons to identify the pairs within tuples
large nested list construction by double for-loop

Container Type Conversions

Here I simply leave out the tuple conversion in the nested list construction. Your code does not indicate that order of ingredients matters, so the information is equivalent, whether it is a list, tuple, or set.

t0=res.tolist()
t0=[tuple(x) for x in t0]
t1=Pairs
t2=mod

def run_loop_non_tuple(limit=20):
    # Make substitions
    result = []
    for i_pair, (v1, v2) in enumerate(zip(t1, t2)):
        if i_pair >= limit:
            break
        out = []
        for i in t0:
            common = set(v1).intersection(i)
            if set(v1) == common:
                out.append(set(i) - common)
                out[-1].add(v2)
            else:
                out.append(i)
        result.append(out)
    return result

    >>> %timeit run_loop_non_tuple(20)
    1 loops, best of 3: 1.09 s per loop

This is not all, as the conversion of the individual tuples/lists to sets for the pair finding can be done outside the loop:

t0=[set(i) for i in res.tolist()]
t1=Pairs
t2=mod

def run_loop_sets(limit=20):
    # Make substitions
    result = []
    for i_pair, (v1, v2) in enumerate(zip(t1, t2)):
        if i_pair >= limit:
            break
        v1 = set(v1)
        out = []
        for i in t0:
            common = v1.intersection(i)
            if v1 == common:
                out.append(i - common)
                out[-1].add(v2)
            else:
                out.append(i)
        result.append(out)
    return result

    >>> %timeit run_loop_sets(20)
    1 loops, best of 3: 460 ms per loop

Repeated String Comparisons

Two things might help speeding up:

instead of comparing strings individually, an index can be built to find the relevant entries
there is a very limited amount of words overall, so they can be mapped to integers for faster matching

Let's start with a word mapping:

from itertools import chain
all_words = np.array(list(set(chain(*t0))))
word_mapping = {word: i for i, word in enumerate(all_words)}

    >>> len(all_words)
    381

There is no need to convert everything beforehand. Just go directly for creating an index. This can be realized as a numpy 2D-array, where we have a row per  element of t0 and a column per all_words. The values are just True/False values as uint8 (1 Byte per value).

word_index = np.zeros(shape=(len(t0), len(all_words)), dtype=np.uint8)
for i_row, row in enumerate(t0):
    for word in row:
        word_index[i_row, word_mapping[word]] = 1

    >>> word_index.shape, word_index.sum()
    ((48983, 381), 416041)

You can now lookup which rows have a pair of words by using the & operator:

    >>> word_index[:, word_mapping[Pairs[0][0]]] & word_index[:, word_mapping[Pairs[0][1]]]
    array([0, 0, 0, ..., 0, 0, 0], dtype=uint8)

So we rebuild the loop with this advantage:

t0=[set(i) for i in res.tolist()]
t1=[set(x) for x in Pairs]
t2=mod

def run_loop_indexed(limit=20):
    # Make substitions
    result = []
    for i_pair, (v1, v2) in enumerate(zip(t1, t2)):
        if i_pair >= limit:
            break
        i1 = [word_mapping[x] for x in v1]
        ix_contain_pair = word_index[:, i1[0]] & word_index[:, i1[1]]
        out = []
        for row, contains_pair in zip(t0, ix_contain_pair):
            if contains_pair:
                out.append(row - v1)
                out[-1].add(v2)
            else:
                out.append(row)
        result.append(out)
    return result

    >>> %timeit run_loop_indexed(20)
    1 loops, best of 3: 216 ms per loop

Double for Loop

It would still help to avoid the nested list construction via the double loop. What helps there is, that the nested lists are identical to t0 if the pair is missing, and it is missing in the majority of cases. So we first construct a copy of t0 and then replace the rows that contain the pair.

To get the indices in t0, flatten and use np.nonzero:

    >>> np.ravel(np.nonzero(word_index[:, word_mapping[Pairs[0][0]]] & word_index[:, word_mapping[Pairs[0][1]]]))
    array([ 1915,  1987,  8062, 10593, 10614, 10663, 10879, 11235, 12021,
   12096, 13445, 13805, 14630, 17658, 17701, 18865, 20712, 22560,
   23573, 23840, 25379, 25487, 27338, 27690, 28630, 32266, 33259,
   33884, 34309, 34412, 35430, 35463, 35968, 36326, 36977, 39477,
   40292, 42138], dtype=int64)

t0=[set(i) for i in res.tolist()]
t1=[set(x) for x in Pairs]
t2=mod

def run_loop_indexed_2(limit=20):
    # Make substitions
    result = []
    for i_pair, (v1, v2) in enumerate(zip(t1, t2)):
        if i_pair >= limit:
            break
        i1 = [word_mapping[x] for x in v1]
        ix_contain_pair = np.ravel(np.nonzero(word_index[:, i1[0]] & word_index[:, i1[1]]))
        out = t0[:]
        for i in ix_contain_pair:
            out[i] = out[i] - v1
            out[i].add(v2)
        result.append(out)
    return result

    >>> %timeit run_loop_indexed_2(20)
    10 loops, best of 3: 43.1 ms per loop

I still expect you to run into memory limits on the full set and/or to crash your notebook connection trying to print the results.


I don't think you need to pass $request to the view, because you can access it anyway with Laravel's helper request() function.

For the routes you can use optional parameters, something like.

Route::get('/artigos/{id?}','GlobalController@gestorArtigos');

For the views and repetitive checks you can always use view composers or middlewares depends on the case really.

Eventually you could create trait with function to perform this repetitive task and include it in controller, for instance:

trait RepetitiveTask
{
    public function fireView($output, $id)
    {
        return ($id) ? $output->with('id', $id) : $output;
    }
}

class YourController
{
    use RepetitiveTask;

    public function gestorArtigos(Request $request)
    {
        return $this->fireView(view('artigos.art_gestor_base'), $request->id);
    }
}

However i would use middlewares or view composers instead.

Whatever you do, make sure you keep the logic out of the views.


This is not a review, but an extended comment.
Theoretically you are right, a time complexity of the first approach is \$O(n)\$. However, there is also a space complexity, also \$O(n)\$, due to the Map, and the map is a very heavyweight data structure. Even though it promises a constant time access, it is only an amortized constant time, and the constant could be quite large. You must also take into account its cache unfriendlyness.
Meanwhile, both approaches are suboptimal. There is a way to solve the problem in a linear time in constant space.


You should split your code up into different methods (this increases readability and makes it possible to profile your code and find bottlenecks). I would create listToArray (which transforms your list to an array, although this isn't really needed), parseInput (which parses A 0.53 to an integer of 0.53, and if you need the original string, you can wrap this up in an object), and sortArray (which performs the actual sorting).
your way of transforming a list to an array is not very stable (what if there are , in your strings?) It also doesn't seem very performant. Use the standard solution for this.
although I'm not sure why you are even doing this, it seems to just add needless computing time.
you seem to be using bubble sort, which has a very bad performance of O(n^2). You should look into other sorting algorithms such as quicksort.
you perform split("\\s") multiple times on the same elements. It would be better to perform this once at the beginning to save a lot of computing.
have you tried using Collections.sort? I would guess that it will perform better, and the code will definitely be cleaner.
be consistent with your spacing, and use more spaces to increase readability (around =, +, etc.

Using Collections.sort your code would look like this:

    // create test list
    List<String> list = new ArrayList<>();
    list.add("B 0.56");
    list.add("E 0.33");
    list.add("A 0.53");

    // sort the list
    Collections.sort(list, (a, b) -> a.split("\\s")[1].compareToIgnoreCase(b.split("\\s")[1]));

    // print sorted list
    for (String list1 : list) {
        System.out.println(list1);
    }

Result:

E 0.33
A 0.53
B 0.56


Print tree level by level including Empty node

A few small changes:
Python has a styleguide, PEP8, which programmers are recommended to follow. One of its recommendations is to use lower_case names for both variables and functions. camelCase is also accepted, if applied consistently (which it is in your code).

Your if conditions in the while loop repeatedly check if node exists. Just put all of them in if node:. Additionally, the checks for node.left and node.right are basically identical, they can be combined by looping over for n in [node.left, node.right]:.

Whenever you do a buffer.pop(0) you probably want a collections.deque. While for lists, popping on the left is O(n) and O(1) on the right, both operations are O(1) for a deque.

Python has the nice feature of multiple assignments, allowing things like:

count, nextCount = nextCount, 0

You are always creating an instance of a node and directly afterwards you assign the value. It is better to add a parameter for the value to the class definition:

class Node:
    def __init__(self, value=0):
        self.value = value
        self.left = None
        self.right = None

With these changes I get this code:

from collections import deque

class Node:
    def __init__(self, value=0):
        self.value = value
        self.left = None
        self.right = None

def printTree(root):
    buf = deque()
    output = []
    if not root:
        print '$'
    else:
        buf.append(root)
        count, nextCount = 1, 0
        while count:
            node = buf.popleft()
            if node:
                output.append(node.value)
                count -= 1
                for n in (node.left, node.right):
                    if n:
                        buf.append(n)
                        nextCount += 1
                    else:
                        buf.append(None)
            else:
                output.append('$')
            if not count:
                print output
                output = []
                count, nextCount = nextCount, 0
        # print the remaining all empty leaf node part
        output.extend(['$']*len(buf))
        print output

if __name__ == "__main__":
    root = Node(1)
    leftNode = Node(2)
    root.left = leftNode
    rightNode = Node(3)
    root.right = rightNode
    leftleftNode = Node(4)
    leftNode.left = leftleftNode
    rightleftNode = Node(5)
    rightNode.left = rightleftNode
    rightrightNode = Node(6)
    rightNode.right = rightrightNode

    printTree(newRoot)

This is still not very efficient code. If you give Node a magic method to decide if it is True or False, your code can be greatly simplified. This method is called __nonzero__ in python 2.x and __bool__ in python3.x.

class Node:
    def __init__(self, value='$', left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def __nonzero__(self):
        return self.value != '$'

    def __str__(self):
        buf, out = [self], []
        while buf:
            out.append("{}".format([node.value for node in buf]))
            if any(node for node in buf):
                children = []
                for node in buf:
                    for subnode in (node.left, node.right):
                        children.append(subnode if subnode else Node())
                buf = children
            else:
                break
        return "\n".join(out)

if __name__ == "__main__":
    root = Node(1, Node(2, Node(4)), Node(3, Node(5), Node(6)))
    print root

This gets rid of all the counting and so on. It does, however, not print the last line of all missing nodes (which seemed odd to me anyways). Normally I would use None for an empty Node, not '$', but it also works this way.

I also added left and right, as parameters to the Node, allowing a nested definition, which might be less readable if it becomes too big, but might come handy, when quickly generating a tree like here.

If you also add the magic method __str__ to Node, you can just do print root (or any other node and all its subnodes).

If you insist on having each level printed like a list (to ease copy&pasting it), replace the line

out.append(" ".join(str(node.value) for node in buf))

with

out.append("{}".format([node.value for node in buf]))

If you want to learn more about magic methods, have a look here.


Working out how many hours worked after a certain time

I agree with your summation that it is clumsy.  I see you like to stringly type objects, such as GetTimeOfDayFromDateTime.  It would be neater to just get the time of day as a TimeSpan.  Also, you may have several overloads accepting different input arguments, so you don't need to include the FromDateTime in the name.

public static TimeSpan GetTimeOfDay(DateTime d) => d - d.Date;

Or if you want to simply check AM versus PM, you could use the DateTime.Hour.  If the hour is < 12, it's AM.  Otherwise, it's PM.

Now GetDuration doesn't have to accept string inputs.  They can accept the TimeSpan (i.e. time of day) for start and end, or just better yet, just subtract the 2 DateTime objects.

This just looks clumsy:

double baseMondayHours = 10.00;
baseMondayHours = (baseMondayHours - 0.5);

Cleaner would be either:

double baseMondayHours = 10.0 - 0.5;

or directly

double baseMondayHours = 9.5;

Another tip to keep in mind: Subtracting dates can produce bad results if the Kind of each DateTime is different.  Doesn't seem to be the case here, but be forewarned.


Build clusters from connections (virus propagation)

I always feel odd reviewing code like this, because there is no API. You should really pull out the clustering code into it's own method, with a nice signature, something like:

IEnumerable<IReadOnlyCollection<string>> Cluster(IEnumerable<Person> people);

This will make it reusable (and so testable).

You ask "Am I doing here something potentially dangerous or excessive with the collections?". I'm not entirely sure what you mean... but I think no. Collections are efficient, and it's hard to do anything dangerous in C# by accident. If anything, you should probably be using more powerful collections.

Tuples

What is Tuple<string, List<string>>? What are Item1 and Item2? Give it a meaningful type, with meaningful member names!

public class Person
{
    public Person(string name, IReadOnlyCollection<string> places)
    {
        Name = name;
        Places = places;
    }

    public string Name { get; }
    public IReadOnlyCollection<string> Places { get; }
}

Complexity

Never been much good at complexity... but here's an attempt at answering your second question. Take it with spoonful of salt. Hopefully someone will poke holes in it promptly.

First you need to identify the parameters you care about. Let's say n for the number of people and 'b' number of places. You iterate over pairs of people, which gives you n^2 (just to enumerate the pairs).

Inside that loop you are looking for an intersection between 2 sets of up to b elements, which can be no better than O(b) (that's the case where the hashes turn out perfectly, assuming Intersect converts one of the lists to a HashSet internally). cluster1.AddRange(cluster2.Where(x => !cluster1.Contains(x))) is O(b^2). You ought instead be using HashSets from the outset, which will get the inner working down to something more like O(b) again (i.e. HashSet<T>.UnionWith(HashSet<T>) is kind of just about linear most of the time). ... but then that matching can only happen n times... so it's a separate concern.

Then there is the outer most loop... which I don't want to think about... but in the worst case it will be run n times, giving you a worst-case complexity of O(n*n*n*b + n*n*b*b), or just about O(n*n*n*b) if you use HashSets.

I can't think how the space complexity of your code could be anything other than the input space complexity of O(b + n).

Technically, your printing out at the end has third order time complexity: O(m*k*k) in number of clusters m, and number of places per cluster k. Consider using a StringBuilder or string.Join instead of Aggregate and repeated concatenation (that will make it O(m*k)).

Disjoint Sets

Any problem like this I would solve with disjoint sets, and even a poor implementation should get you O(n*b) time-complexity (max tree-depth is O(n)) on this problem.

The basic idea is that you maintain a table pointers which describe a set of trees, each tree being an independent (disjoint) set. You can follow the pointers from any member of a set to the root member, and by assigning the parent of one root node to the root of another you join the two sets together. You can throw an implementation together in no time, with very little code.

Some very unscientific benchmarking suggests that a somewhat untested disjoint sets implementation I just threw together is a couple of orders of magnitude faster than your implementation (using HashSets and with reduced Pair count, as suggested in Paparazzo's answer) on randomly generated problems. Your implementation is taking over 10seconds on my machine to solve a problem with b=4000, which the disjoint sets solve in a few milliseconds. The disjoint set version seems to be linear in n*b (easier to scale than just b in random problems); yours is taking a while for larger problems larger than n*b=5000, and I wouldn't wish to comment on the experimental time-complexity with these few (noisy) results.

A gist of the disjoint sets implementation and cluster method is provided so that people can find juicy bugs in it: 1 bug fixed so far (2018-06-26)


Throwing a custom error in a stored procedure

I'm not sure I completely understand your logic, but since this is a stored procedure the temp table isn't visible outside it so you don't need to check if it exists (unless you have other code in the same procedure that might have created it already).

And the most obvious way to reduce the number of lines is not to count the number of IDs and then get them, but to just get them and use @@ROWCOUNT to see how many you got:

-- get missing IDs
SELECT sa.Customer_Shipping_ID AS ID
INTO #Missing_Ref
FROM staging.Sale sa
WHERE NOT EXISTS (
        SELECT cu.Customer_Shipping_ID
        FROM staging.Customer cu
        WHERE LTRIM(RTRIM(sa.Customer_Shipping_ID)) = LTRIM(RTRIM(cu.Customer_Shipping_ID)))

-- only continue if we got at least 1 missing ID
if @@rowcount > 0
begin

    DECLARE @Current_ID VARCHAR(50);
    DECLARE @Missing_ID VARCHAR(MAX) = '';
    DECLARE @Output_Error VARCHAR(MAX);

    DECLARE id_cursor CURSOR FOR
    SELECT ID
    FROM #Missing_Ref;

    -- rest of cursor here (presumably)
end

BTW, the title of your question seems to have nothing to do with the actual code, which is concerned with finding a set of rows that may or may not exist.


Reading a collection of strings from the user

Don't forget to check the stream status for errors or EOF.

while (cin >> temp && temp != ".")
{
    params.push_back(temp);
}

EDIT: You do not necessarily need to invent your own break condition. There's one already — end of file. You can just read strings until you reach it. This way, your program will also work with non-interactive input nicely. To generate an end of file on a terminal, type Ctrl+D on Unix/Linux and Ctrl+Z on Windows.

while (cin >> temp)
{
    params.push_back(temp);
}


Nice example of const generics! In general your code is well organized and idiomatic. Some comments:

In your new() function, you are using an argument as a default value. It's more idiomatic to use the Default trait for this:
pub fn new(dim: [usize; N]) -> Self
where
    T: Clone + Default,
{
    let cap = Self::calculate_capacity(&dim);
    NdArray {
        dim,
        data: vec![Default::default(); cap],
    }
}

In some of your unit tests this means you have to use the turbofish to initialize: e.g. NdArray::new becomes NdArray::<usize, 2>::new. However, this only occurs when the user does not access / modify anything in the NdArray, and if they do that then type inference kicks in. So I recommend providing both options to the user, say NdArray::new(dim: ...) for T: Default and NdArray::new_fillwith(dim: ..., default: T) if the user wants to specify their own default value.

Your structure could use some more functionality. For any collection of T, .len() and .iter() would be the minimum:
pub fn len(&self) -> usize {
    self.data.len()
}

pub fn iter(&self) -> impl Iterator<Item = &T> {
    self.data.iter()
}

What about adding two nd-arrays? Multiplying by a constant? Concatenating them along a certain dimension? Generalized matrix multiplication? Some of these will probably require certain utility functions.

For example the following would probably be quite useful and a good exercise to write: iteration along a sub-dimensional slice of the array, like pub fn iter_subarray(&self, coords: &[Option<usize>; N]) -> impl Iterator<Item = &T> where if the coord is None then you iterate along all coordinates in that dimension, but if it's Some(x) then that coordinate is fixed.

You probably want to #[derive(PartialEq, Eq)] in addition to Clone and Debug.

Both the implementation and unit tests could use some handling of edge cases, in particular when the dimension is empty and when any of the dimension lengths is zero. Whether you allow these cases is up to you; I would personally allow the former but not the latter. Here's a unit test:
#[test]
fn nd_array_edgecases() {
    let array_dim0 = NdArray::<usize, 0>::new([]);
    assert_eq!(array_dim0.len(), 1);
    assert_eq!(array_dim0[&[]], 0);
    let array_dim1 = NdArray::<usize, 1>::new([0]);
    assert_eq!(array_dim1.len(), 0);
    assert!(catch_unwind(|| array_dim1[&[0]]).is_err());
}

Great job with the unit tests for vector overflow, that is super useful.

In get_flat_idx, Clippy recommends: for (d, &dlen) in self.dim.iter().enumerate() (then use dlen instead of self.dim[d]). I agree, though in this case we still have to use d to index into idx.

In your implementation, the field .data is not intended to dynamically change size. For this reason, you could initialize with Vec::with_capacity(n) instead of Vec::new() in your new_with() function. You might also consider using a fixed-size or fixed-capacity array implementation, for example the ArrayVec crate.


folder = r'\\my\network\folder'
subfolder_list = [r'\DRAWINGS', r'\DOCUMENTS', r'\VIDEOS']

Don't write the type into the variable name. The type should be able to change without the variable having to be renamed. subfolders already tells you that it is a collection of subfolders. subfolder_names might be better, to make clear that it contains the folders' names, not wrapper objects for the file system.

Removing the backslash from the beginning can prevent you from having to read up the code to make sure where the backslash is, at the beginning or the end. subfolder or subfolder_name implies just the name. So add the backslash wherever you concatenate the strings.

#Delete all records in the table
db_exec = conn.execute('delete from records')

That comment is obsolete, as it adds no information that is not already in the next line of code.

#Loop through the list of subfolders
for i in subfolder_list:
    #loop through the files in the subfolder
    for filename in os.listdir(folder + i):
        #insert the file names into the table
        db_exec = conn.execute('insert into records (file_name) values (' + filename + '\')')

Again, the comments are not needed, and instead impair readability. Instead of explaining with comments what the code does, improve the code to better explain itself. i can be acceptable as a loop variable, but whenever possible, use a more explicit name, like in this case subfolder_name. Then you get this more expressive code:

for subfolder_name in subfolder_names:
    for file_name in os.listdir(folder + r'\' + subfolder_name)
        db_exec = conn.execute('insert into records (file_name) values (' + file_name + '\')')

#Commit the insert statements
db_exec = conn.execute('commit')

Again the comment is not needed.

print "Complete."

What is complete? Give the user more info, e. g. `"42 file names inserted into database."


Generating all possible combinations of a string using iteration

Minor changes

As @coderodde already stated, there is not much to improve, nonetheless a few minor things:

You can reduce the scope of the variables x (which has always the same value as k prior entering the inner loop) and k to the inner/outer loop.
for (int i = array.length - 1; i >= 0; --i) can be written as for (int i = array.length; --i >= 0;).
Your inner loop starts at j = 1 but only uses j - 1, you can start the loop at 0 to avoid the subtraction.

Depending on how nulls should be handled, you could use res[k++] = array[i].toString() to throw a NPE if null elements are present. If nulls are permitted, I would prefer that the string "null" is added to the resulting array rather than a null reference.

You could start k and j at -1 and use the (in theory) more efficient preincrement operator instead of the postincrement operator.

Possible implementation (not using preincrement for kand j as I think it makes the code more difficult to read):

public static String[] combinations(String[] array) {
    String[] res = new String[-1 >>> -array.length];
    for (int i = array.length, k = 0; --i >= 0;) {
        String s = res[k] = array[i].toString();
        for (int j = 0, x = k++; j < x;)
            res[k++] = s + res[j++];
    }
    return res;
}

Alternative implementation

Your current implementation supports arrays with a maximum length of 30, you could provide a method #combination(String[] array, long index) to support arrays with up to 64 elements (or a larger datatype than long to support way larger input arrays).

public static String combination(String[] array, long index) {
    // Could iterate twice to determine length (and coder) first
    // to avoid resizing buffer (and could share the resulting
    // byte array), kept this way for simplicity.
    if (array.length > 64 || index == -1 || index + 1 >>> array.length != 0)
        throw new IllegalArgumentException();
    index = index + 1 << -array.length;
    StringBuilder sb = new StringBuilder();
    for (int i = -1; index != 0;) {
        int nlz = numberOfLeadingZeros(index);
        sb.append(array[i += nlz + 1]);
        index = index << nlz << 1;
    }
    return sb.toString();
}


Since you aren't using any of the things that make numpy fast, this code would be about 2x faster if you just used python lists instead. Alternatively, if you vectorized the update function, you would probably be able to make it much faster. That said, this will not be easy. This question has a very good example of what the result would look like.


If your input is already separated correctly by spaces, it seems all you need to do is to convert those into commas and you're good. I'm not sure you need to go to/from arrays.

I would replace the code inside the loop:

{
    String line = subFile.nextLine();
    String[] split = line.split("\\s+");
    StringJoiner joiner = new StringJoiner(",");

    for (String strVal: split)
        joiner.add(strVal);

    line = joiner.toString();
    line = line.startsWith(",") ? line.substring(1) : line;
    fileArray[i++] = line;
}

with this:

{
    String line = subFile.nextLine();
    line.trim().replaceAll(" +", " "); //check for double spaces
    line.replace(' ', ',');   //replace space with comma
    fileArray[i++] = line;
}

Oh, and check for the array size like someone else mentioned.


Link shortener application - return the "following" string

Consider wrapping getFirst() into getNext(String) - just have it return "A" if it takes in a null or empty string. That might make it a little easier for the client to use.
getFirst(int) can leverage Arrays.fill(), which will make it a little easier to read. Consider throwing an exception if the minLength is less than zero - otherwise you get an empty string returned. Another option would be to return "A".
The core problem can be solved non-recursively. A helper method to return the next character would be, well, helpful, and easier to read than what you're doing now. The math gets done inside the loop, and you prepend an 'A' if appropriate.
You might want to make 'A' a constant, since it's special.

If you make the changes I suggest, your code might look something like:

import java.util.Arrays;
import java.util.regex.Pattern;

public class ProceduralStringCreator {

    private static final Pattern VALID = Pattern.compile("[a-zA-Z0-9]+");
    private static final char FIRST_CHARACTER = 'A';

    public static String next(final int size) {
        if (size < 0) {
            throw new IllegalArgumentException("Size must be greater than or equal to zero, was " + size);
        }
        final char[] value = new char[size];
        Arrays.fill(value, FIRST_CHARACTER);
        return new String(value);
    }

    public static String next(final String current) throws BadFormatException {
        if (current == null || current.isEmpty()) {
            return Character.toString(FIRST_CHARACTER);
        }

        if (!VALID.matcher(current).matches()) {
            throw new BadFormatException("String contains illegal characters.");
        }

        final StringBuilder stringBuilder = new StringBuilder(current);
        int index = stringBuilder.length();

        do {
            index--;
            stringBuilder.setCharAt(index, nextCharacter(stringBuilder.charAt(index)));
        } while ((index >= 1) && (stringBuilder.charAt(index) == FIRST_CHARACTER));

        if ((index == 0) && (stringBuilder.charAt(index) == FIRST_CHARACTER)) {
            stringBuilder.insert(0, FIRST_CHARACTER);
        }

        return stringBuilder.toString();
    }

    private static char nextCharacter(final char character) {
        switch (character) {
        case 'Z':
            return 'a';
        case 'z':
            return '0';
        case '9':
            return 'A';
        default :
            return (char) (character + 1);
        }
    }

}


Python proper abstract class and subclassing with attributes and methods

I don't see much of problems with using properties as abstract attributes e.g:

class Foo(abc.ABC):
    @property
    @abc.abstractmethod
    def bar(self):
        ...

However, if you still don't like it instead of going for your ninja stackoverflow way there is an easy way in python 3.6.

class Foo(abc.ABC):
    def __init_subclass__(cls, **kwargs):
        if not hasattr(cls, 'bar'):
            raise NotImplementedError('damn')
        return super().__init_subclass__(**kwargs)

As for one instance per class just look for python Singleton implementations.


Avoid using namespace std. You just don't know what-all symbols that spews into your global namespace, causing lots of grief when you least suspect it.
Your interface should contain protected default-constructor, copy-constructor, and copy-assignment-operator.
You should use =default when you are explicitly defaulting a special-member-function, so it can stay trivial.
If you use a struct, default-access is public instead of private, which would allow you to dispense with some access-specifiers.
Though that can be controversial for classes which have non-public members, or generally any feature not supported by C.

struct Comparable {
    virtual ~Comparable() = default;
    virtual int compare(const Comparable& other) const = 0;
protected:
    Comparable() = default;
    Comparable(const Comparable&) = default;
    Comparable& operator=(const Comparable&) = default;
};

HighScoreElement should be marked final, prohibiting further derivation and thus allowing some optimizations, unless you redesign it for inheritance. Which you actually shouldn't do.
Don't needlessly create copies of non-trivial types on call / return, use constant references.
Only HighScoreElement::getName fails that now.
Consider marking overrides with override, which in contrast to repeating virtual actually is meaningful.
You should bail out immediately if your dynamic_cast fails.
Consider just changing it to a reference-cast so that's automated.
Avoid useless blocks and concomitant further indentation.
After a return, processing leaves the function immediately.

int compare(const Comparable& other) const override {
    auto&& x = dynamic_cast<const HighScoreElement&>(other);
    if(getScore() < x.getScore())
        return -1;
    else if(getScore() > x.getScore())
        return 1;
    if(getName() < x.getName())
        return -1;
    else if(getName() > x.getName())
        return 1;
    return 0;
}

There's std::swap in <utility> for swapping two items.
Insertion-sort isn't the best algorithm there is, but it will get the job done, as long as the vector isn't too big.
You should use a smart-pointer to manage your elements, best-suited is probably std::unique_ptr from <memory>.
You could use list-initialization to initialize your vector instead of adding the elements afterwards one-by-one:

vector<Comparable*> v {
    new HighScoreElement("Kate Bush", 10),
    new HighScoreElement("Peter Gabriel", 20),
    ...
};

return 0; is implicit in C++ and C99+ for main.


Getting JSON and putting it in a table using jQuery and PHP

There are a few improvements that come to my mind for the given code:

you may want to return an status code for your JSON output instead of checking whether the result is an object. It would allow you to handle error messages and such in a more convenient manner.
as a minor improvement, you can use replaceWith() to replace the table body instead of removing it and then appending a new one to the table.
you don't have an error handler to your script... if you won't ever need it, that's cool, but it's always best to know when a script fails :)
to improve concatenation performance, you might want to use Array's join() method instead of doing += for each table row.
you're now removing all table bodies on the whole page, which could be kind of risky if you have more than one table there. Furthermore, the selector is extensively greedy, as jQuery has to find all table bodies on the whole page. It's better to use ID selectors when possible, as they are the fastest one to execute.
PHP-wise, you don't handle invalid $wtype, so if no condition is met, you won't know what went wrong, since nothing relevant will be returned

Enough of the theory, this is what I have in mind:

$.ajax({
                url: "get_attributes.php",
                type: "post",
                datatype: "json",
                data: {wtype: red_type},
                success: function(data) {
                    if (data["status"] == 200) {
                        var toAppend = [];
                        toAppend.push(
                            "
",
                            "
	Type:	"+data['type']+"
",
                            "
Health:	"+data['health']+"
",
                            "
Attack:	"+data['attack']+"
",
                            "
Defense:	"+data['defense']+"
",
                            "
Speed:	"+data['speed']+"
",
                            "
Evade:	"+data['evade']+"
",
                            "
Special:	"+data['special']+"
",
                            "
"
                        );
                        $("#red_form table tbody").replaceWith(toAppend.join(""));
                    } else {
                        alert('An error has occured. Please try again.');
                        console.log('Status: ' + data["status"] + ', message: ' + data["message"]);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert('An error has occured. Please try again.');
                    console.log('ErrStatus: ' + textStatus + ', error: ' + errorThrown);
                }
            });

And the PHP:

<?php
header("Content-Type: application/json");
$wtype = (isset($_POST['wtype']) ? $_POST['wtype'] : 'unknown');
$attributes = array('status' => 200, 'message' => 'ok', 'type' => $wtype);

switch ($wtype) {
    case 'Ninja':
        $attributes['health'] = '40-60';
        $attributes['attack'] = '60-70';
        $attributes['defense'] = '20-30';
        $attributes['speed'] = '90-100';
        $attributes['evade'] = '0.3-0.5';
        $attributes['special'] = 'There is a 5% chance of 2x attack';
        break;

    case 'Samurai':
        $attributes['health'] = '60-100';
        $attributes['attack'] = '75-80';
        $attributes['defense'] = '35-40';
        $attributes['speed'] = '60-80';
        $attributes['evade'] = '0.3-0.4';
        $attributes['special'] = '10% chance of restoring +10 health when evade is successful';
        break;

    case 'Brawler':
        $attributes['health'] = '90-100';
        $attributes['attack'] = '65-75';
        $attributes['defense'] = '40-50';
        $attributes['speed'] = '40-65';
        $attributes['evade'] = '0.3-0.35';
        $attributes['special'] = 'increased +10 defense when health is below 20%';
        break;

    default: $attributes['status'] = 400;
             $attributes['message'] = 'Invalid class info has been requested.';
}

echo json_encode($attributes);
?>


- Cache your selectors: As a rule of thumb, if you use a selection more than once, you should cache it. What happens when you use $("someElem") is jQuery has to jump into the DOM and look through all elements that would match that selection. So you should really do a search only once, and save your results for future use. This way you can look and play with them whenever you want.  Ex.:

$("a[href=" + hRt + "]").css({
    padding: 10
});

//Should be like this:
var whichLink = $("a[href=" + hRt + "]"); //Saved my search to a variable, which I use later.
whichLink.css({
    padding: 10
});

//...

whichLink.css({
    padding: 0
});

- Save function calls: If you read the jQuery source code you'll see that shortcut methods like .click(), .scroll(), and etc. all reference the .on() method. All they do is basically call the .on() method with some parameters. Well why not just go straight to the meat and potatoes? Check this out:

$("#foo").click(function() {
    //Do your awesomeness
});

//That does the same thing as this:
$("foo").on("click", function() {
    //Do your awesomeness even awesomener.
});

//Or try this:

$(window).on("scroll", function () {
    //Wicked!
});

That just makes the syntax so easy to rememeber as well. If you're going to use jQuery on a regular basis, I recommend that you take some time and read through the source code of the methods you're using. To find them quickly just use CTRL+F and type methodName:. That should jump you straight to what you want to know. This way you can understand what and how you are doing things, and even find better ways to do them on your own. Also if you see something you think should be done better or differently, you know how it works and you can contribute to jQuery.

In your click functions you also might want to prevent the default browser action on a link, which is to direct the page to that link. Since you just want to perform something on your page and don't actually want the browser to leave the page you should prevent that action.
You can do it by passing in e for event and running e.preventDefault();. I see you've used return false; which does that, but if you want to read more on the difference between the two I would suggest [this article by Chris Coyier][1].

-Playing with visible elements: You're if statements from what I can tell are trying to detect scroll position and etc. I highly recommend you check out [this tiny plugin][2]. It basically detects if an element is visible or not at any given time. This may or may not help you out but I just thought I'd throw that out there.

-Performance Wise: Focus on the .scroll() event for now. The way you have it now, the code runs hundreds of times since it is called each time the window scrolls, even if the user isn't done scrolling. That's an increadible ammount of times your code will run for no reason. Not only that but then you run code on each element with the class of .dober - more code that gets run.
Now we don't want to do that since it can really slow down the browser, if not crash it all together. What you'll want to do is wait for when the user stops or is done scrolling, then run the code.

var $window = $(window); //Remember, if you use a selection more than once, you should cache it

$window.on(function() {
    //Here we check if there has been a call already
    //If the check is true that means the code was already called
    //So we cancel any previous calls, this way the code is only called once
    if(this.scrollEnd) clearTimeout(this.scrollEnd);

    //If you've made it here, the code hasn't been called, or the call has been canceled.
    this.scrollEnd = setTimeout(function() {
        $(this).trigger('scrollEnd'); //Call the actual code with a 500ms delay
    }, 500);
});

$window.on('scrollEnd', function() {
//This is a custom event that is triggered after the timeout
//This will only run on the last time the scroll method was called
    $('.dober').each(function () {
        var hRt = $(this).attr('id');
        var paddingAmt = 0; //Here I just slightly optimized your code

        if ($(this).offset().top <= $window.scrollTop()) {
            paddingAmt = 10;
            $('li a').css({ padding: 0 });
        }

        $('a[href=' + hRt + ']').css({
            padding: paddingAmt
        }, function(){ //Callback to set padding back to zero
            paddingAmt = 0;
        });
    });
});

[1]: http://css-tricks.com/return-false-and-prevent-default/
[2]: https://github.com/teamdf/jquery-visible/


Sudoku solution without the use of classes

I see some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std within your program is generally a bad habit that you'd do well to avoid.

The comment in the code seems to indicate you know this and can't change it for some reason, but others who may read this question and answer may benefit

Simplify your code

The current code has this function:

bool is_valid_sdk(const sdk& v)
{
  if (not has_valid_rows(v))   return false;
  if (not has_valid_cols(v))   return false;
  if (not has_valid_blocks(v)) return false;
  return true;
}

However, this could be considerably shorter and easier to read and understand if written like this:

bool is_valid_sdk(const sdk& v)
{
  return has_valid_rows(v) and has_valid_cols(v) and has_valid_blocks(v);
}

Reconsider the design

Although the current code works, it's not very efficient in that it makes a copy of each vector in order to check it.  An alternative approach would be to allow checking in place without making a copy.  One way to do that would be to separate the iteration through the rows/columns/blocks into a separate function that could be passed to the is_permutation function.  For example:

bool is_permutation(const sdk& v, int x, int y,
                    int(*next)(const sdk& v, int& x, int& y))
{
  vector<bool> used(sdk_size, false);
  for (int i = 0; i < sdk_size; ++i) {
    int val = next(v, x, y);
    if (val < 1 or val > sdk_size or used[val-1]) {
      return false;
    }
    used[val-1] = true;
  }
  return true;
}

int next_in_blk(const sdk& v, int &x, int &y)
{
    int val = v[x][y];
    if (++y % sdk_blocks == 0) {
        y -= sdk_blocks;
        ++x;
    }
    return val;
}

bool has_valid_blocks(const sdk& v)
{
  for (int i = 0; i < sdk_size; ++i) {
    int x = sdk_blocks * (i / sdk_blocks);
    int y = sdk_blocks * (i % sdk_blocks);
    if (not is_permutation(v, x, y, next_in_blk)) return false;
  }
  return true;
}

The corresponding functions for row and col are even simpler.


Reading in data from a file and then assigning vals and then creating object

Code Review

You don't check for failures in the read. When you read from a stream it can fail. All the read operations return a stream object as a result. This allows two things. 1) Chaining of read operations 2) Ability to check if it works. When you use a stream object in a boolean context it converts itself to bool that indicates its state. Thus each read operation can be tested to see if it works.

std::ifstream   data('mydata.txt');

int  value;
if (data >> value) {
    // The read worked.
}

std::string line;
while(std::getline(data, line)) {
    // Successfully read a line.
}

Each read operation should be checked to make sure it worked correctly.

int a,b;
if (data >> a >> b) {
    // Both a and b were read correctly.
}

You are not using operator>>. You get everything as a string then convert it. All the built in types have operator>> defined so you can simply read them (If the value read is not the correct type the stream is set bad and your code will automaically stop reading).

Also you can define operator>> fro user defined types so that you can use this simpler technique for nearly any object type (I provide an example below).

In modern C++ code you never see new/delete operations. That's because these return pointers and pointers have no ownership semantics. You should be using smart pointers so that ownership and thus lifetime are well defined.

std::unique_ptr<StockItem>  item(new Transistor(code,count,price,other));

Even better (if you have C++14/C++17)

std::unique_ptr<StockItem>  item  = std::make_unique<Transistor>(code,count,price,other);

How I would do it

Since operator>> for strings reads things that are space separated I would write a helper class for reading comma separated strings. Thus I can use read chaining to read all the things on a line in a single read operation.

struct CommaValueRef
{
    std::string& data;
    CommaValueRef(std::string& data) : data(data) {}
    friend std::istream& operator>>(std::istream& str, CommaValueRef& value) {return std::getline(str, value.data, ",");}
};

Since you are reading a file called "inventory.txt" I am going to assume that each line is a line of inventory. So I would define a class to hold the inventory and an operator>> that knows how to read a line of inventory.

class Inventory
{
    std::string type;
    std::string code;
    int         count;
    int         price;
    std::string other;

    friend std::istream& operator>>(std::istream& str, Inventory& value);
};

Now define the read like this:

    std::istream& operator>>(std::istream& str, Inventory& value)
    {
        std::string line;
        if (std::getline(str, line))
        {
            Inventory         tmp;
            std::stringstream linestream(line);

            char c1, c2;
            linestream >> CommaValueRef(tmp.type)
                       >> CommaValueRef(tmp.code)
                       >> tmp.count >> c1
                       >> tmp.price >> c2
                       >> CommaValueRef(tmp.other);

            // A lot of developers would have combined the above
            // line and this if statement into a single expression
            // I separated them as I though it looked neater.
            if (linestream && c1 == ',' && c2 == ',')
            {
                // All the read's worked so put the data
                // into the actual value.
                value = std::move(tmp);
            }
            else
            {
                 // Something failed to read correctly.
                 // So force the stream into a bad state
                 // So the controlling loop can generate a message
                 // and exit.
                 str.setstate(std::ios::failbit);
            }
        }
        return str;
    }

Now reading the file looks like this:

Inventory   data;
while(inFile >> data)
{
    list.push_back(StockItemFactory::createItemFromInventory(data));
}