Overall
Looks good overall.
The design works perfectly for sorting integers. But in C++ we can potentially sort anything. So why not allow your sorting algorithm to work with any sortable type.
To do this learn templates:
 void merge_sort(vector<int> &arr);

 // Change to:

 template<typename T>
 void merge_sort(vector<T>& arr);

The next thing to think about is that vector<> is not the only thing that can be sorted. There are lots of container types that can be sorted. Normally we don't care about the container type and we abstract the container away and specific what what we want to sort in terms of iterators.
So the next subject to learn are iterarators'. Then you can specify what you want to sort in terms of the beginning and end of a range.
template<typename I>
void merge_sort(I begin, I end);

The next thing you should think about is the memory requirements your algorithm uses. Currently your algorithm uses 2 times the current size of the array you want to sort (in addition the vector). You can change this so you only use 1 times the current size of the vector.
To achieve this you want to allocate the memory once outside the recursive sort function then pass in this temporary memory into the merge sort.
// The wrapper
template<typename I>
void merge_sort(I begin, I end)

    // Create a single buffer are to be be re-used.
    std::vector<int>  tmpData(std::distance(begin, end));

    merge_sort_with_buffer(begin, end, std::begin(tmpData) std::end(tmpData));
}

template<typename I1, template I2>
void merge_sort_with_buffer(I1 b , I1 e, I2 tb, I2 te)
{
    std::size_t s = std::distance(begin, end);

    if (s < 2) {
        return;
    }

    I1 m   = std::next(begin, s/2);
    I2 tm  = std::next(tBegin, s/2);

    merge_sort_with_buffer(b, m, tb, tm);
    merge_sort_with_buffer(m, e, tm, te);
    merge(tb, tm, te, b);
}

template<typename I2, template I1>
void merge(I2 tb, I2 tm, I2 te, I1 dst)
{
    // copy tb->tm
    // copy tm->te
    //
    // To the destination
}

Code Review
Not a fan of bad comments:
#include <vector> // will use the vector class  to make things like list slicing very easy

Do you use slicing?

Stop doing this:
using namespace std;

It might be useful in books where space is limited. But in real code it actually causes problems. I recomend you stop using it because it becomes a habit. This is a bad one. When you have a bad habit you will just use it without thinking and accidentally cause on f the problems.
See: Why is “using namespace std;” considered bad practice? Personally I find the second answer the best.

In C++ it is more normal to put the & with the type in the declaration.
void merge_sort(vector<int> &arr);

// Like this:

void merge_sort(vector<int>& arr);

Note: This is the opposite of what is common in C.

Please always add the curly craces '{}'
    for (int i: my_vector)
        cout << i << ',';

    // Like this:

    for (int i: my_vector) {
        cout << i << ',';
    }

The trouble is people still make silly macros that are multiple lines. Not using the braces can put you in funny situations where only part of your code is executed by the loop when you least expect it.
More importantly to me it makes it much simpler to read.

In C++ the last return in main() is not needed.
    return 0;

If you don't provide one the compiler automatically adds a return 0 at the end of main.
It has been common practice to not include a return 0 if main does not ever return anything else. So if I see a return 0 at the end I start looking for other error detection code that would return another value.

This is a subtle one:
        if (left[j] < right[k]) {

If you use the less here then if they are equal you will choose the one from the right. Keep that in mind.
There is an important mathematical principle around sorting called "Stability" (when sorting). If items that are equal retain there original relative order the sort is considered stable otherwise it is not.
If you choose from the right when the items are equal your algorithm is not stable. So by using <= you automatically make your algorithm stable.
        if (left[j] <= right[k]) {

Note this is a copy operation:
        results[i] = left[j];

Now for integers this makes absolutely no different. But when you make this work for other types this mean copying an object. This can be expensive so we would prefer to use move rather than copy.
        results[i] = std::move(left[j]);

Sure these work.
    while (j < L_size) {
        results[i] = left[j];
        j++; i++;
    }
    while (k < R_size) {
        results[i] = right[k];
        k++; i++;
    }

But much easier to use standard algorithms
    std::copy(&left[j],  &left[L_size],  &result[i]);
    std::copy(&right[k], &right[R_size], &result[i]);

But then we remember that we want to use move rather than copy.
    std::move(&left[j],  &left[L_size],  &result[i]);
    std::move(&right[k], &right[R_size], &result[i]);


Calculating the point of intersection of two parabolas

Well it seems as though I SIGNIFICANTLY overcomplicated the equation for some reason. I just did the equation it a second time and I got something much nicer:

For any two parabolas \$ ax^2 + bx + c = 0\$ and \$dx^2 + ex + f = 0\$, we get:

\$
ax^2 - dx^2 + bx - ex + c - f = 0 \\
x^2(a - d) + x(b - e) = f - c
\$

Now it's just a matter of completing the square.

\$
x^2(a - d) + x(b - e) + \frac{(b - e)^2}{4(a - d)} = f - c + \frac{(b - e)^2}{4(a - d)} \\
(x\sqrt{a - d} + \frac{b - e}{2\sqrt{a - d}})^2 = f - c + \frac{(b - e)^2}{4(a - d)} \\
(a - d)(x + \frac{b - e}{2(a - d)})^2 = f - c + \frac{(b - e)^2}{4(a - d)} \\
x + \frac{b - e}{2(a - d)} = \sqrt{\frac{f - c + \frac{(b - e)^2}{a - d}}{a - d}} \\
x = \sqrt{\frac{f - c + \frac{(b - e)^2}{a - d}}{a - d}} - \frac{b - e}{2(a - d)} \\
\$

I don't know how I ended up with the monster I originally posted, but this seems much more reasonable.


splitting and merging Ranges array in javascript

I'll go over some of the basics

let HMID = parseInt(document.getElementById("mySelect").value);

what should HMID be? Aside from being a number, I don't know what it is. And the only reason I know it's a number is because it's the value of parseInt. Looking at how it's used doesn't shed any light. You should name the variable something more descriptive.

Speaking of naming things more descriprive - mySelect is a really bad name, too. Part of why I don't know what HMID is, is because it's the value of something with the non-descriptive ID of mySelect. The myX naming convention is fine when prototyping but you really need to go with descriptive names upon finishing your code.

Echoing the same "descriptive names needed" sentiment for onSelect and onSelectAdd. What do they do? One is executed on select which...doesn't tell me much. The other...adds stuff on select? It's not clear. Somewhat better names would be

onSelect -> removeItemFromRange
onSelectAdd -> addRemovedToRange

I'm not great at naming things but I'd err on the side of verbose but descriptive rather than short but unclear. If you can have something shorter, feel free to use that. As it stands, the names aren't good.

You are better off adding the event listeners via element.addEventListener rather than in the HTML. That way, you keep the HTML clear of logic - it's all contained in your JavaScript. As an added benefit, you can attach more event listeners that do other stuff without changing these functions. Here is an example

let button = document.getElementById("buttonWithMultipleClickListenersExample"); //told you I'm not good at naming things...

button.addEventListener("click", sayFoo);
button.addEventListener("click", sayBar);

function sayFoo() {
  console.log("foo");
}

function sayBar() {
  console.log("bar");
}
<button id="buttonWithMultipleClickListenersExample">Click Me</button>

Two different event listeners are attached for the click event and they can do two completely separate things. If sayBar() is altered or even a sayBaz() is added, we don't need to change anything else, whereas if we define the click handler in the HTML, we have to change that function with every alteration needed.


I would say, that actually sending the email is part of the process of changing the store manager. It's part of the business logic (AFAIK), that when a store changes it's manager, the new manager should be notified, among other things.

Thats why the check if the manager changes is not a job for the email sender at all. The email sender should be a utility, which can be reused.


No, you are re-rendering the application manually.

function ShowSuccessAtDOM(id, name) {
  ReactDOM.unmountComponentAtNode(document.getElementById(id));
  ReactDOM.render(
    <LoginSuccess name={name} />,
    document.getElementById(id)
  );
};

function ShowFailureAtDOM(id) {
  ReactDOM.unmountComponentAtNode(document.getElementById(id));
  ReactDOM.render(
    <LoginFail />,
    document.getElementById(id)
  );
};

Better:

class LoginApp extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (

        {this.props.errors.length > 0 && <LoginFailure {...props} />}
        {this.props.success &&
You are logged in!
}
        {!this.props.success && <LoginForm />}

    );
  }
}

ReactDOM.render(<LoginApp {...props} />,
                document.getElementById('react-root'))

Too pass the props into your application, there are many ways. One of the most popular is using some kind of flux architecture. There is a library called redux. Its really easy to use, you should take a look, then you will understand how easy it is, to implement the example above.


SQL query to select all teachers not in different table

Your query using NOT IN is good, but you can also use LEFT JOIN and keep only the teachers who don't have Groups:

SELECT t.Id, FirstName, MiddleName, LastName
FROM Teachers t LEFT JOIN Groups g ON t.Id=g.TeacherId
WHERE g.TeacherId IS NULL


Performance of stable marriage solution in Python 3

I feel lazy to go through the details of your code, but here are few notes you should think about:

Your code, as it is, is not scalable. You should re-design it in terms of functions (I think functions are enough for your case, even in some other situations OOP may be a better choice). Functions allow also your code to be reused.
In terms of UX, I think you have some more work to do. For instance, when I run your code, I was waiting for something to happen, until I guessed to type in something, but then I had to check your code to see what it expects me to code. That is bad: imagine every software you use, you have to read its code to guess what you have to write or where to click.
You should throw a look to PEP 8 (for example, the naming conventions you use are camelCase, Python developers do not like that and you have to comply to the philosophy of Python)
Interesting if you throw a glance to: What does if __name__ == “__main__”: do?

That is the big picture I want to share with you for the moment ... maybe I can come back later to provide more useful help, or maybe other members may dive deeper into your code.


Find all k points which are closest to origin

This task sounds as if it came directly from an advertisement for the Java 8 streams API:

Sort the points by their distance
Take the minimum k points

This boils down to the following code:

static int[][] kClosest(int[][] points, int k) {
    return Arrays.stream(points)
        .sorted(Comparator.comparing((int[] point) -> point[0] * point[0] + point[1] * point[1]))
        .limit(k)
        .toArray(int[][]::new);
}

That code is written from the top of my head. Since the Java streams API is general-purpose and intended to be highly optimized, it should notice that it only ever needs to remember the \$k\$ smallest elements. You should check this by counting how often the distance function is called. To do that you should extract it to a local method, which is something that your IDE can do for you.

Compared to your code:

I left out the Math.sqrt since the point coordinates are restricted to 10000, which means that the square of the distance can become at most 2e8, which luckily is a bit smaller than Integer.MAX_VALUE.
Calling Math.abs is unnecessary as well.
Making a map of lists may help in pathological cases when the given points all have the same distance. In other cases it can be left out.


A short code review;

Your code does not work, it should return something instead it calls console.log
Your for loop is icky, either update i and check i

for(let i = 0; i < num; i++ ))

or check res.length

while(res.length < num)
solution is too generic for this function name
console.log() is missing a semi-colon
Performance;

Checking whether i is odd every time seems like much, you can avoid that
RememberString.repeat(), you could repeat by calling "AB".repeat(num/2) and add an "A" if num is odd.

Obligatory rewrite

    //repeatAB(5) => "ABABA"
    function repeatAB(n) {
        return "AB".repeat(n/2) + (n%2 ? "A" : "");
    }

    console.log(repeatAB(5)) // returns "ABABA"

I ran this approach against the other approaches for the heck of it, this approach destroys the other approaches (at least visually):

http://jsbench.github.io/#11a2b8507a7f9290c6ef6cda596f8179


Calculating the number of candy bars and gumballs that can be redeemed using coupons

Looking at this statement, it looks as if numberOfGumballs and numberOfCandybars are independently derived from numberOfCoupons:

System.out.println(numberOfCandybars(numberOfCoupons)
        + " candybar(s) and " + numberOfGumballs(numberOfCoupons)
        + " gumball(s).");

But they are not independent, because numberOfGumballs actually depends on numberOfCoupons and numberOfCandybars too. Hiding this fact is not a good thing: one might expect that changing the behavior of numberOfCandybars won't affect the behavior of numberOfGumballs, but it actually will, which is confusing.

If you think about it, it would be best if numberOfCandybars returned 2 values:

The number of candy bars our coupons could buy
and, the number of coupons left

With these two values, we could use the number of coupons left to make another call to numberOfGumballs, and keep the number of candy bars for printing later. That way, the relationships between the functions could be well visible.

Of course, Java can only return a single value. But the single value can be an object, which can contain multiple values.

So let's start over. We have items: Candy bar, Gumball. We have some kind of a vending machine, that you put coupons into, select the item you want, and it gives back a number of items and change (remaining coupons).

Let's model the items with an enum, and give them a price too.

enum Item {
    CandyBar(10),
    Gumball(3);

    final int price;

    Item(int price) {
        this.price = price;
    }
}

And let's model the machine and the output it gives:

class AutomaticCandyMachineOutput {
    final Item item;
    final int itemCount;
    final int change;

    AutomaticCandyMachineOutput(Item item, int itemCount, int change) {
        this.item = item;
        this.itemCount = itemCount;
        this.change = change;
    }
}

class AutomaticCandyMachine {
    AutomaticCandyMachineOutput redeemCouponsForItems(int coupons, Item item) {
        int itemCount = coupons / item.price;
        int change = coupons % item.price;
        return new AutomaticCandyMachineOutput(item, itemCount, change);
    }

    AutomaticCandyMachineOutput redeemCouponsForCandybars(int coupons) {
        return redeemCouponsForItems(coupons, Item.CandyBar);
    }

    AutomaticCandyMachineOutput redeemCouponsForGumballs(int coupons) {
        return redeemCouponsForItems(coupons, Item.Gumball);
    }
}

This seems a more natural, flexible and extensible design. Now we can rewrite the original statement like this:

int coupons = 99;
AutomaticCandyMachine machine = new AutomaticCandyMachine();
AutomaticCandyMachineOutput output1 = machine.redeemCouponsForCandybars(coupons);
AutomaticCandyMachineOutput output2 = machine.redeemCouponsForGumballs(output1.change);

String.format(
    "%d candybar(s) and %d gumball(s)",
    output1.itemCount,
    output2.itemCount);


Function with excessively complex "where" clause

It is a matter of taste but I think reduce will be a bit more cleaner with case.

reduce exp = case exp of
  Literal{}             -> exp
  Variable _ (Just var) -> Literal var
  Variable _ Nothing    -> exp
  FCall f a b
    | isDefined f ma mb -> matchLiterals ma mb
    | otherwise         -> FCall f ra rb
    where ra = reduce a
          rb = reduce b
          ma = eval ra
          mb = eval rb

Literal{} is special pattern syntax that will still work even if you add more arguments to Literal.

To reduce duplication (just a bit) in where, you can use on function from Data.Function

on :: (b -> b -> c) -> (a -> b) -> a -> a -> c

it is like (.) but allows to apply function to both arguments

(ra,rb) = on (,) reduce a b
(ma,mb) = on (,) eval ra rb


Helper function too complex
Your helper function and the fslt function seem too complex for what they do (helper is even recursive!).  All you are really doing is adding roman numerals starting at the highest value first.  So something like this would suffice:
#define DIM(arr)        (sizeof(arr)/sizeof(arr[0]))

void Solution::helper (int num){
    for (int i = DIM(IntVal)-1; i >= 0; i--) {
        while (num >= IntVal[i]) {
            output += roman[i];
            num -= IntVal[i];
        }
    }
}


Most Efficient Solution for USACO: Triangles - Python

An obvious improvement is to not split the strings and convert the parts to int over and over again. Do it once, at the start:
def main(points):
  points = [tuple(map(int, point.split())) for point in points]
  largest = 0

  for cx, cy in points:
    for lx, ly in points:
      for wx, wy in points:
        if lx == cx and wy == cy:
          area = abs(ly-cy) * abs(wx-cx)
          if area > largest:
            largest = area

  return str(largest)

And it can be solved in O(n). For every "corner" as you call it, you go through all point pairs. Instead, just look up the point furthest away on the same y-coordinate and the point furthest away on the same x-coordinate. That can be precomputed in O(n):
with open('triangles.in') as f:
    next(f)
    points = [tuple(map(int, line.split())) for line in f]

xmin, xmax, ymin, ymax = {}, {}, {}, {}
for x, y in points:
    xmin[y] = min(xmin.get(y, x), x)
    xmax[y] = max(xmax.get(y, x), x)
    ymin[x] = min(ymin.get(x, y), y)
    ymax[x] = max(ymax.get(x, y), y)

result = max(max(x - xmin[y], xmax[y] - x) * max(y - ymin[x], ymax[x] - y)
             for x, y in points)

with open('triangles.out', 'w') as f:
    print(result, file=f)

Note that I also did the output a bit differently. No need to close yourself. Getting the file closed for you kinda is the reason you used with in the first place, remember? And I prefer print over write, as I don't have to convert to string then and trust line endings to be done as appropriate for the platform (maybe not an issue here, as the output is just one line and apparently they don't care how it ends).
P.S. Those darn... they kept saying my solution failed due to "Runtime error or memory limit exceeded" and it took me a while to figure out: Instead of tuple(map(...)) I had used my preferred [*map(...)]. But they're inexplicably using Python 3.4 and it didn't exist back then. But that should be a syntax error. Grrrr....


This BYTE* bTmp = new BYTE[4]; could just be put on the stack with BYTE bTmp[4]; (the proper term is actually automatic storage duration which in most cases means it ends up on the stack). This normally avoids a call to malloc and you don't have to delete it explicitly.
I'm not too versed in COM programming but if msr.SODirectIO(0, &data, &bstring); could throw an exception you might want to wrap it into a try {} finally {} in order to ensure the cleanup of the BSTR and COM resource is done regardless.
I know it's just a quick mockup but GetHexBytes could be reduced by using Linq:

string GetHexBytes(string str)
{
    var bytes = System.Text.UnicodeEncoding.Unicode.GetBytes(str);
    var hexBytes = bytes.Select(b => b.ToString("X2")).ToArray();
    return string.Join(":", hexBytes);
}


Is this code is safe or not (img upload) ? [PHP]

Just a few remarks:
I am wondering how that magic value of 6844685465456456 was determined :) I don't think that is equivalent to 2 Mb.

You need to use proper indentation, especially when you have nested control blocks - readability is important. Lack of readability here can result in a greater likelihood of logic errors.

This code is not helpful at all:
 }else{
     echo ':/';
 }

It doesn't tell the user what the problem is. Don't you hate those forms that tell you 'invalid input, try again' but don't actually tell you the problem and leave you guessing ?

This code (borrowed from mickmackusa):
if (!move_uploaded_file($_FILES['avatar']['tmp_name'], "uploads/{$_SESSION['id']}.{$extensionUpload}")) {
    exit("Erreur durant l'importation de votre photo de profil extension");
}

You are showing an error message to the user but it should be treated like an exception. This code could fail for several reasons like:

invalid file name
disk full/not mounted
etc

But at this point it's not the user fault. It's a malfunction in your application or a server issue. There is nothing the user can do. So I would handle the exception and send an alert. If your application is broken you'll want to be notified and fix it asap, before someone reaches out to you.

This code is not foolproof:
$resultat = move_uploaded_file($_FILES['avatar']['tmp_name'], 'uploads/'.$_SESSION['id'].'.'.$extensionUpload);

You are expecting that the session variable ID will be set. It's perfectly possible that the user has the page opened already and the session expires after some time. When submitting the form the session variable could be unset, unless you have more code elsewhere (an include perhaps) that verifies that the session is active. If there is no active session you'll probably redirect the user to the login page.
So the resulting file name could be incorrect and not what you expected (eg: .jpg). It could be one reason why move_uploaded_file would fail in your script. In itself it doesn't present an obvious security risk though but it is a bug.


$("input[name='date_sub01']").prop('checked', false);
 $("input[name='date_sub02']").prop('checked', false);

Can be turned into:

$("input[name='date_sub01'], input[name='date_sub02']").prop('checked', false);

Also if you assign the selectors to a variable your code will be much faster:

var sub_01 = $("input[name='date_sub01']")

You never need to use the method .val().

If you do:

var test = this.value;

You will get the same results without accessing jQuery.

Since you are using background:none alot, you can keep it in an object:

noneBackground: {"background":"none"}

and pass it as an argument

  $("label[for*='date_main']").css(noneBackground);


Return True if num is within 2 of a multiple of 10

You could simplify your code to make it faster and also avoid the 'if-else' construct:

def near_ten(num):
    a = num % 10
    return 8 <= a or 2 >= a

Here's another version: (Thanks to the comment of @mkrieger1)

def near_ten(num):
    return not(2 < (num % 10) < 8)

I think the name of the function is misleading. Maybe you should rename it to something like: near_multiple_of_ten(num)


If you really care about performance you may also give a chance to a branchless version. Note that compiler may optimize code with explicit branches (if and ?:) if target architecture supports CMOV (& similar) instructions, check generated assembly output. In these examples I will use X86 mnemonics but I suppose meaning is clear whichever your architecture is.

Also you're using non-standard fls() and std::__clz(), they may be implemented with instrinsics or not. If not then performance will greatly decrease because they need a loop or a lookup table instead of BSR (or LZCNT) and BSF (or TZCNT).

uint32_t nextPowerOfTwo(uint32_t n)
{
    --n;

    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;

    return n + 1;
}

Note that 0 gives a wrong result then if you expect 0 as input and you don't want 0 as output you have to handle this special case (just return 1 or add 1 if your compiler will generate a branch for that.) AFAIK also implementation with BSx (or xZCNT) have the same problem (they just set ZF or CF) then special case has to be handled also there (if your implementation specific function does not already do it).

Code is equivalent to 1 << (log2(n - 1) + 1). I don't have a link to original code (algorithm is not mine!) but in my comments authors are W. Lewis and P. Hart) and (thanks Martin) there also is another author who arrived to the same code (with link to their original discussion/implementation!)

Which implementation is faster? It depends (see comments for a discussion with CodeRodde.) Target architecture (possibly revision), compiler vendor, version and settings will all affect results. Exact numbers are meaningless without details about your specific scenario, the point is that CodeRodde's answer is faster than this with MSVC++ but slower with GCC, the absolutely great answers from Jerry and JS1 also add more doubts about which method is best.

The only thing I can suggest is to implement them all and pick the fastest one in your specific case. If this is truly performance critical, because this function is so small, I'd also feel to suggest is to put some raw performance comparison in your unit tests: when current version will be slower than expected (compared to all the others) you will need to inspect again...


It's very fast, but I wonder if hooking into the API (DirectX) and getting the buffer will be faster than this (I don't know how to do that, though).

I don't know either.
What you have here, probably hasn't been reviewed yet, because there's essentially nothing blatantly wrong with it.

What you've done well
Pretty much everything, as far as I can tell:

Every IDisposable is wrapped in a using block and thus, whether it blows up or not, things get disposed correctly.

try...finally is the best thing you could do here; if there's an exception, it will bubble up, and the finally block will run in all cases, ensuring the resources cleanly get released.

You're working everything in a MemoryStream, which is the only logical thing to do (hitting the file system would be utter nonsense).

Question marks

Returning the MemoryStream means closing and disposing the stream isn't the responsibility of the method that created it - that's a potential issue. I would try to Freeze() the bitmap and return a Bitmap object instead, although there might be a performance penalty in doing that.

If the method is called in a tight loop, does the result of NativeMethods.GetWindowRect(hwnd, out rc); change at all between calls? Perhaps the method could take a Rect as a parameter?

It being static scares me a little, but it's private and you're not showing the class it's a member of... You'll want the method wrapped in an object that you can create and pass around, not just a global/static "helper" method that's part of some undefined ambient context.


Generating unique names for things like filenames

Potential infinite loop
If the isValid method is faulty, i.e always returns false, we'd have an infinite loop on our hands. How do we fix it? I'd fix it in coding in some (configurable but not necessary) upper limit, say 255, so if we tried 255 times, and it still fails, just throw an exception. This could either be done using a public property with a default value, or an optional constructor parameter, then all you'd need to do is check whether i is less than that upper bound.

Naming, specifically underscores
Technically, there's nothing wrong with your naming right now, as the Microsoft Naming Guidelines is outdated (from 2008) and not complete at all. And this Stack Overflow Q&A states that you shouldn't use underscores, and instead use this to differentiate between members and parameters (as you are right now). But even that is from 2012, and looking at some of Microsoft's own code, like this line in the ASP.NET Core repository shows that even they use an underscore prefix.

Resulting code:
public class NameGenerator
{
    private readonly string _baseName;

    private readonly Func<string, bool> _isValid;

    public int MaxAttempts {get; set;} = 255;

    public NameGenerator(string baseName, Func<string, bool> isValid)
    {
        _baseName = baseName;
        _isValid = isValid;
    }

    public string Generate()
    {
        // This is just a personal preference, keep it as one line if you want
        if (_isValid(_baseName))
            return _baseName;

        for (var i = 0; i < MaxAttempts; i++)
        {
            var candidate = $"{_baseName} ({i})";
            if (_isValid(candidate))
                return candidate;
        }
    }
}

Instead of a property to set the max attempts, you could also use an optional constructor parameter, like this:
public class NameGenerator
{
    // ...
    private readonly int _maxAttempts;

    public NameGenerator(string baseName, Func<string, bool> isValid, int maxAttempts = 255)
    {
        // ...
        _maxAttempts = maxAttempts;
    }

    // ...
}


Synchronizing two scrollbars to work in unison

This looks perfectly good to me.  Everything has a unique purpose, everything is either clearly explained or self-explanatory.  Unless you have tested this and found a performance issue, and you are sure that it is happening here, do not do any optimization to this.

There is no loop and no recursion, the code itself can't properly be an optimization target.  If you are observing that this is running slowly, the hidden costs of setting the scrollbars must be the cause.  To address this you will need to change your entire strategy to keeping the div contents in the right place using CSS only.  I have to say that while I find using the position of some element (scrollP?) to be a pretty elegant way to duck issues of messing around with coordinates that will be inconsistent otherwise, it is technically the best practice to do all positioning with CSS.


Remove Redundant Parenthesis
In this line:
while (again == 'y'):

The parenthesis are unneeded and can (should) be removed.
Use a dict to drive the stacked if/else
Whenever I see a stacked if/else I look to restructure the code using a dict (mapping) instead.
The net results of the if/else structure in your code can be put into a dict like so:
results = {
    "rock": {
        "rock": "The game is a draw",
        "paper": "Player 2 wins!",
        "scissors": "Player 1 wins!",
    },
    "paper": {
        "rock": "Player 1 wins!",
        "paper": "The game is a draw",
        "scissors": "Player 2 wins!",
    },
    "scissors": {
        "rock": "Player 2 wins!",
        "paper": "Player 1 wins!",
        "scissors": "The game is a draw",
    },
}

If the results are mapped this way, then the interactions with the user becomes more clear and
your loop can simply become:
while again == 'y':

    p1 = input("Player 1 --> Rock, Paper, or Scissors? ").lower()
    print()

    p2 = input("Player 2 --> Rock, Paper, or Scissors? ").lower()
    print()

    result = results.get(p1, {}).get(p2, "Invalid input, try again")
    print(result)

    again = input("Type y to play again, anything else to stop: ")
    print()

This is an example of separating the UI (User Interface) from the Business Logic.


Refining/simplifying jquery for hiding and showing fieldsets

Store selections in variables; don't call $(...) again and again for elements you've already selected
You start out by hiding the fieldset, but it'd be simpler to just hide it with CSS, so it starts out hidden by default. Conversely, if it's visible by default, then add the required attributes in the html, so it actually matches the behavior you want for a visible fieldset.
You're using data-* attributes, but not super effectively (see below).

The way you're using the data-* attributes is basically the same way you'd use a class or ID; as a key to help you find stuff. So you might as well use classes and IDs then, if you're not going to use the data-* attributes to store a value in addition to the key. But for cases like this, where you want a link to refer to an element, I suggest the following:

Foo

...

The link is completely valid syntactically and semantically: It references an element.

Without JS intervening, it'll just scroll the page to element, but with JS, we can intercept the click and do the showing/hiding. Of course, there's no way to distinguish between hide and show links, but I think that should be a toggle-style action anyway.

But to keep to your setup, here's a way to do that (and now data-* attributes come in handy):

Show
Hide

...

For the JS, you can then do something like this:

$(function() {
  var showLinks = $('a[data-shows]'),
      hideLinks = $('a[data-hides]');

  showLinks.on('click', function (event) {
    var target = $(this).addClass('active').data('shows');
    $(target).fadeIn().find(':input').prop('required', true);
    hideLinks.removeClass('active');
    return false;
  });

  hideLinks.on('click', function (event) {
    var target = $(this).addClass('active').data('hides');
    $(target).fadeOut().find(':input').prop('required', false);
    showLinks.removeClass('active');
    return false;
  });
});

There's a bit of repetition there, so you might do:

$(function() {
  var links = $('a[data-shows], a[data-hides]');

  links.on('click', function (event) {
    var link = $(this).addClass('active'),
        type = link.data('shows') ? 'shows' : 'hides',
        target = link.data(type),
        fadeFunc = type === 'shows' ? 'fadeIn' : "fadeOut";
    $(target)[fadeFunc]().find(':input').prop('required', type === 'shows');
    links.not(this).removeClass('active');
    return false;
  });
});

There are many ways of going about this


Program that multiplies numbers over and over

Your program makes inconsistent use of Python 2 and 3. For 3.x you need print('Hello World!'), for 2.x you need print 'Hello World!'. I'm guessing that you are using 2x because you say your program works and print value (as above) only works in 2.x. Note that in 2.x, input(prompt) is equivalent to eval(raw_input(prompt)). In 3.x, input() now means raw_input() and raw_input() has been removed. Given 2.x, your code already eval()s input, no you don't need float(). However, float(raw_input()) is safer so I'll use that below. Also, the use of n3 != '0' never works because n3 is a float not a string. Finally, I've cleaned up the variable names and removed unnecessary assignments.

number1 = float(raw_input('Enter a number: '))
number2 = float(raw_input('Enter a number: '))
result = number1 * number2

print(result)

number3 = float(raw_input('Multiply by: '))

while not number3 == 0:
    result2 = number3 * result
    print result2

    number3 = float(raw_input('Multiply by: '))


I suggest using Joda-Time's LocalDate instead of Java's Date to represent dates without a time zone.

Assuming you only need to traverse the days once, use an Iterator instead of a Stream.

def dayIterator(start: LocalDate, end: LocalDate) = Iterator.iterate(start)(_ plusDays 1) takeWhile (_ isBefore end)

Example usage:

dayIterator(new LocalDate("2013-10-01"), new LocalDate("2014-01-30")).foreach(println)

If you do need a lazily-evaluated list, then Stream is appropriate. I suggest using iterate instead of cons in that case.

def dayStream(start: LocalDate, end: LocalDate) = Stream.iterate(start)(_ plusDays 1) takeWhile (_ isBefore end)


Encoding arbitrary data for stream transmission

Assuming the encoding format itself is not subject to review, it's a pretty good implementation. Things that could be improved (small stuff):

Chaining ?: is not necessary here, compare:

n += dchr[i] == 0x02 ? 2 : dchr[i] == 0x03 ? 2 : dchr[i] == 0x25 ? 2 : 1;

to:

n += (dchr[i] == 0x02 || dchr[i] == 0x03 || dchr[i] == 0x25) ? 2 : 1;

Prefer unsigned char* for work on raw binary sequences, char* means a string of text by convention
0x02, 0x03, and 0x25 all have meanings, so better give them meaningful names, e.g.

const unsigned char ENC_START = 0x02, ENC_END = 0x03, ENC_ESCAPE = 0x25;

In the test:

char* in = "1" "\x02" "%" "\x03" "3";
size_t n = encodedata(&out, in, 6);

it's not clear where 6 came from, so I'd opt for:

char in[] = "1" "\x02" "%" "\x03" "3";
size_t n = encodedata(&out, in, sizeof(in));

Moreover, unless the function signature you proposed is a requirement, I would opt for a buffered design that encodes data in chunks on the fly. It's a little more complicated because you would need to remember the state between calls -- how much input data was processed so far (think of fread). For stream transmission, you probably call encodedata, send the result, and throw it away immediately after. So elliding malloc and relieving the caller from encoding the whole stream at once are both welcome here. One of many possible designs may look like this:

struct encodestate
{
    void* in;
    size_t inlen;
    unsigned char out[256];  // use apprioprate chunk length for your stream
    size_t outlen;
};

/* Writes encoded data into state.out, updates state.outlen
   and for internal use updates state.in and state.inlen.

   Returns whether there's more input data to process (should be called again).
*/
bool encode(struct encodestate* state);

Example of use:

unsigned char in[] = "1" "\x02" "%" "\x03" "3";

for (struct encodestate state = {in, sizeof in}; encode(&state); )
    send(somewhere, state.out, state.outlen);


Copy a directory structure to another, but only copying specific files

Looks ok for a specific task, but the code is not reusable at all. It would be more useful to create a function ignore_except that could be used like this to perform the same task:

shutil.copytree(srcDir, dstDir,
                ignore=ignore_except('*.pyc', '*.ui', '*.txt', '__main__.py', 'dcpp.bat'))

The source code of shutil.ignore_patterns would be a good starting point for such function.


Passing the database connection as a variable is a good technique.
Validate user input as much as possible before considering executing any processes.  If the input is missing or invalid, don't do anything with the submission.

if (empty($_GET["user"])) { // add your validation here if possible
    echo "Missing/Invalid data submitted";
    // halt the script or redirect or whatever
}

Use object-oriented mysqli syntax because it is more brief and IMO cleaner to read.
Do not perform iterated queries.  You can easily condense you iterated queries into one simple query using an INNER JOIN.  Something like this should do (untested):

SELECT *
FROM users u
INNER JOIN posts p USING userid
WHERE u.user_name = ?
  AND p.hostid = p.userid
  AND p.commentid = 0

USING is a convenient shorthand keyword when the two joining columns are identical; otherwise use ON and declare the columns individually. MySQL ON vs USING? You should also replace * in the SELECT clause with the exact columns you need from either table.  (Never ask for more than you need.) With the above query, you will only need to bind $_GET"user"] once since there is now only one placeholder.
I don't typically endorse printing from the same function that does the processing.  If you are going to print nested html elements, you can improve readability by tabbing them.
There is a cleaner way to extract the file extension than picking up post-explosion debris.  How do I get (extract) a file extension in PHP?

$ext = pathinfo($filename, PATHINFO_EXTENSION);

If $row['fileid'] isn't 1 or 2, don't bother printing an empty string.


Naming

CompareStrings() and CompareAllLetters are poorly named. You need a comment to explain what the methods should achieve.

The input parameters string stringToCheck1, string stringToCheck2 are also poorly named using some kind of hungarian style.

The input parameter of the PrintMessage() method is also poorly named. It is just not obvious what result should mean.

The same is true for the local variables string1LettersList and string2LettersList.

Comments

Comments should describe why something is done. The code should describe what is done.
This is especially true if the comment is plain wrong like //check if strings are not the same size. The check in question is not if they have a different size or not, it checks if the difference in length is greater than 2.

Simplifications

Use built in methods to simplify things.

Like this

List<char> string1LettersList = new List<char>();
foreach (var c in stringToCheck1)
{
    string1LettersList.Add(c);
}

can be simplified to

List<char> string1LettersList = stringToCheck1.ToList<char>();

returning booleans

Like already mentioned in vnp's answer you can simplify the returning of booleans. This is true for both of your methods.

The condition in the CompareStrings() method is obviously flawed. If both strings are equal, it  would return true, so better change it to

return (counter == 1);

exit early

You already do a check at the top of the methods (also it is done wrong), you can add another check for checking if both strings are the same.

In the CompareStrings() method you can exit early if before the incremention counter == 1 like

for (int i = 0; i < stringToCheck1.Length; i++)
{
    if (stringToCheck1[i] != stringToCheck2[i])
    {
        if (counter == 1) { return false; }
        counter++;
    }
}

Code duplication

In both methods you have the same (wrong) check about the size difference of the strings. You should extract this check to a separate method in which you also can integreate the check if both strings are the same.

private bool IsComparisonNeeded(String first, String second)
{
    if (first == second) { return false; }
    if (first == null || second == null) { return false; }

    return (Math.Abs(first.Length - second.Length) < 2);
}

Bugs

if strings are same, both methods returns true
if one or both of the strings is null the application crashes
if the difference in CompareAllLetters() is 2 it returns true

Refacoring

Can't be done right now, because

the code isn't producing the expected output
it is not clear for which input which output should be expected.

Suggestion

For a problem like this, you should first write tests defining the expected behaviour.


Prime number calculator using Sieve of Eratosthenes

This is written like C code; there are lots of things you're doing that would be much nicer using the tools C++ gives you.

First, though, I'm not a fan of a global using namespace std, so I removed it.

You're using lots of longs; it's best to replace them with int64_ts for consistency. Perhaps some size_ts would work well, too, but it doesn't seem like an improvement to the API. You should also initialize them in the loops or as late as possible.

Your bool * a should be replaced with a std::vector<bool>; not only is it far easier but it's likely faster and takes less space.

You don't need to return 0.

Your

int64_t c = 0;
for(int64_t i = 2; i < n; i++) {
    if(a[i]) {
        //std::cout << i << " ";
        c++;
    }
}

can be just

int64_t c = std::count(std::begin(a), std::end(a), true);

using the algorithm standard library.

C++ compilers can tell that sqrt(n) is constant, so you don't need to assign it to a variable.

It's standard in C++ to do ++i over i++, although it won't matter in this case.

You can initialize your vector with

std::vector<bool> a(n, true);
a[0] = a[1] = false;

to avoid the first loop.

Your loop

for(int64_t k = 0, j = 0; j <= n; j = (i * i) + (k * i), ++k) {
    a[j] = false;
}

can be simplified to

for(int64_t j = i * i; j < n; j += i) {
    a[j] = false;
}

This does loop over slightly different values (it avoids j=0), but those values were likely unintended anyway.

For your timings, you should use chrono. This is long and verbose, but it's a so much better library that you should just deal with the hassle.

You validate against argc but not whether the input is a valid number. Try using istringstream to do that:

int64_t n;
if (!(std::istringstream(argv[1]) >> n)) {
    std::cout << "Number invalid." << "\n";
    return 1;
}

Note that this allows input like "   6-afsadf" or "  34 2 " which parse as 6 and 34 respectively; a full check is more complicated.

You should probably separate the prime-counting code from the input-output code, although this requires a bit of hassle to return multiple values:

namespace ch = std::chrono;

std::pair<int64_t, ch::steady_clock::duration> primes_count_and_time(int64_t n) {
    ... // code

    auto elapsed = ch::steady_clock::now() - start;
    int64_t count = std::count(std::begin(a), std::end(a), true);
    return {count, elapsed};
}

int main(int argc, const char * argv[]) {
    ... // code

    int64_t count;
    ch::steady_clock::duration elapsed;
    std::tie(count, elapsed) = primes_count_and_time(n);

    ... // code
}

Now we have some simple optimizations to apply; you can start by dropping the odd values from the vector:

for(int64_t i = 1; i <= sqrt(n / 2 + 1); ++i) {
    if(a[i]) {
        // The start is:
        //      compress(uncompress(i)²)
        //          = ((2*i+1)² - 1) / 2
        //          = 2 * i * (i+1)
        for(int64_t j = 2*i*(i+1); j < n / 2 + 1; j += 2*i+1) {
            a[j] = false;
        }
    }
}

This takes 3.3 seconds for \$n = 10^9\$ for me, where the old version took 11.2. All of the changes are below:

#include <algorithm> // count
#include <chrono>    // steady_clock
#include <cmath>     // sqrt
#include <iostream>  // cout
#include <iterator>  // begin/end
#include <sstream>   // istringstream
#include <tuple>     // tee
#include <utility>   // pair
#include <vector>    // vector

namespace ch = std::chrono;

std::pair<int64_t, ch::steady_clock::duration> primes_count_and_time(int64_t n) {
    std::vector<bool> a(n / 2 + 1, true); // 2, 3, 5, 7... might be prime

    auto start = ch::steady_clock::now();

    for(int64_t i = 1; i <= std::sqrt(n / 2 + 1); ++i) {
        if(a[i]) {
            // The start is:
            //      compress(uncompress(i)²)
            //          = ((2*i+1)² - 1) / 2
            //          = 2 * i * (i+1)
            for(int64_t j = 2*i*(i+1); j < n / 2 + 1; j += 2*i+1) {
                a[j] = false;
            }
        }
    }

    auto elapsed = ch::steady_clock::now() - start;
    int64_t count = std::count(std::begin(a), std::end(a), true);
    return {count, elapsed};
}

int main(int argc, const char *argv[]) {
    if(argc == 1) {
        std::cout << "Please enter a number." << "\n";
        return 1;
    }

    int64_t n;
    if (!(std::istringstream(argv[1]) >> n)) {
        std::cout << "Number invalid." << "\n";
        return 1;
    }

    int64_t count;
    ch::steady_clock::duration elapsed;
    std::tie(count, elapsed) = primes_count_and_time(n);

    double seconds = ch::duration_cast<ch::duration<double>>(elapsed).count();
    std::cout << std::fixed
              << "\nCalculated " << count
              << " prime numbers up to " << n
              << " in " << elapsed.count()
              << " clocks (" << seconds << " seconds).\n";
}


Simple animation with Javascript and JQuery

Naming

Use meaningful names.

config sounds better than animInfo.
iter- Although the comment states what the variable contains it's better to name it iterator and remove the comment.
animSoc: What does it do? Animate the width of element to some %. This can be named as animateWidth.
Similarly, animSocp can be renamed to fadeInParagraphThis might need comment to explain its purpose

Globals. Required?

animSoc and animSocp are global variables. As, these functions are only called from ready they can be moved inside it. See Why are globals bad?

Once, these are moved inside ready the parameters to the function need not to be passed as they will be accessible.

Passing $ as argument to ready

This is done when there are other libraries which uses $ to access it's features or $ is global variable defined. When $ passed as argument to ready, instead of using jQuery each time $ can be used(saves typing). Here, $ is used outside of ready. This means, there are no conflicts on $ and thus using jQuery to refer to jQuery object is not required and passing $ as parameter is not required.

return;

At the end of animSoc, return statement is used but nothing is returned. Also, when this function is called the returned value is never used, so, it can be removed.

Static elementCount

What if tomorrow other developer(or future you) remove/add some elements in the page but forgot to update this value?. I'll suggest to use jQuery to get the number of elements in DOM.

elementCount: $('div.myClass').length,

$('div[class^="soc"]').length can also be used when there is only one class applied to the elements. As, corresponding HTML code is not shown, I'll suggest to add one more class to all elements and use it as selector. In such case eq can be used which works with index.

jslint/jshint

Use JSLint/JSHint regularly to check for errors and potential problems in code.

Here's code with above changes.

$(document).ready(function() {
    'use strict';

    var config = {
        iterator: 1,
        elementCount: $('div[class^="soc"]').length,
        socAnimSpeed: 500, // soc  - Section One Content Animation Speed
        socpAnimSpeed: 1000 // scop - Section One Content <p> Animation Speed
    };

    animateWidth(config);

    function animateWidth() {
        if (config.iterator <= config.elementCount) {
            $(".soc" + config.iterator).animate({
                width: "60%"
            }, config.socAnimSpeed, fadeInParagraph);
        }
    }

    function fadeInParagraph() {
        $(".soc" + config.iterator + " + p").fadeIn(config.socpAnimSpeed,
            function() {
                config.iterator++;
                animateWidth(config);
            });
    }
});


Selects all elements with a specific data attribute and equalizes their heights

data attribute

It's a bit unconventional to use a data attribute to select the affected elements. A class would be the more conventional approach.

Use of template strings

You have two places where you unnecessarily use template strings with backticks (`).

Code

I like the code overall very much. Nice break down into functions. Nice use of modern JS features.

Only one small thing: The return in equalizeHeights is unnecessary.

Timing

The problem with the need for the wait may be due to contents of the divs. If they contain images or use external fonts, then they may lead to resizing of the divs while these are loading. Some points to look out for:

Use the load event instead or additionally to DOMContentLoaded.
Make sure images have a size assigned to them, either in the HTML (height and width attributes) or the CSS.
There a ways to make sure that the text content isn't rendered until the fonts are loaded, but this is not really my area of expertise.

Possible bug/misfeature

There is one problem with the script: It never allows the divs to shrink if the content becomes shorter, for example due to a window resize.

I can think of two possible solutions:

Before checking the size of the divs, remove the min-heights and wait() to allow a re-render.

Or

add a second, inner div inside the equalize divs and use the inner divs client height to determine the largest div.


Project Euler #18 in Python: Maximum sum down a triangle of numbers

In break_pyramid you use list comprehension to split a row into
numbers – why not use list comprehension as well to split the input
into rows?

def break_pyramid(num_pyr):
    '''
    Breaks the number string into an array
    '''
    pyramid = [[int(col) for col in row.split(' ')] for row in num_pyr.split('\n')]
    return pyramid

In add_from_under, this

greater_vals = [max(lower_row[i:i+2]) for i in range(len(upper_row))]

creates many intermediate slices. The alternative

greater_vals = [max(l, r) for l, r in zip(lower_row, lower_row[1:])]

seems to be slightly faster. You can even combine both zip operations
into a single one:

def add_from_under(upper_row, lower_row):
    return [upper + max(lower_left, lower_right)
         for upper, lower_left, lower_right in zip(upper_row, lower_row, lower_row[1:])]

so that no intermediate list is created.

The main loop applies add_from_under cumulatively to the pyramid
rows (in reverse order). That is a "reduce" operation and can be done
with functools.reduce:

from functools import reduce

def main():
    pyramid = break_pyramid(num_pyr)
    final_row = reduce(add_from_under, reversed(pyramid))
    return final_row[0]

if we exchange the parameter order in add_from_under to

def add_from_under(lower_row, upper_row):
    return [upper + max(lower_left, lower_right)
         for upper, lower_left, lower_right in zip(upper_row, lower_row, lower_row[1:])]

Now the pyramid variable is just iterated over, but not modified
anymore.


Project Euler # 36 Double-base palindromes in Python

Code review

The sequence of

    if condition:
        return True
    return False

is a long way to say

    return condition

Consider instead

def is_palindrome(n):
    return to_str == to_str[::-1]:

Generator vs list.

A list takes space. The entire point of a generator is to not take space. Your find_palindrome does yield, that is produces one palindrome at a time. Very well suited to sum them as they are produced. Your code collects them all in a list for no reason.

Even more curious is that your code

builds a dictionary
then yields each entry
to build the list
which is sent to sum to traverse it.

I see at least 4 traversals over the same data. Seems excessive.

Efficiency

Thou shalt not brute force.

There are just 1000 decimal palindromes below 1000000: they are all in form abccba. In fact, we are not interested in all of them: if a is even, the binary representation would have a trailing 0, and to be a palindrome it would have a leading 0 as well. We may immediately disqualify such numbers. What remains, is just 500 candidates.

So, we only need to iterate over 500 numbers, instead of 1000000 your code does. A 2000-fold speedup, immediately. In fact, a bit more, because there is no need to test wether a decimal representation is a palindrome anymore, and such test is quite expensive. There is also no need to test for the parity, but it is peanuts.

The fun part is to design test that the binary representation is palindromic. The usually recommended

        binary = bin(n)
        return binary == binary[-1:1:-1]

works well in general. In this particular setting you know a lot about the numbers and their binary representation (at the very least you know how many bits the number takes), and there are few more performant solutions.

Rant

Please keep in mind that solving Project Euler problems will not make you a better programmer. Project Euler is designed for programmers striving to be better mathematicians.

And no matter what, do not brute force.


They both look like they are \$O(n)\$.

A quick check with timeit show they both take essentially the same amount of time, and the time grows linearly with the length of the input string.

It would be better to iterate over the characters in the string rather use an explicit index over the length of the string (while curr < len(s) is often a smell).

def decoding(s):
    result = []
    repeat = 0

    for c in s:
        if c.isdigit():
            repeat = 10 * repeat + int(c)

        else:
            result.append(repeat * c)
            repeat = 0

    return ''.join(result)

or:

def decoding(s):
    result = []
    prev_index = 0

    for index,c in enumerate(s):
        if not c.isdigit():
            result.append(int(s[prev_index:index]) * c)
            prev_index = index + 1

    return ''.join(result)


I did some testing and research on this, AFAIK your script is safe.

However, you should also be aware of how you retrieve the input. For example, what if the String contained a ", followed by executing PHP code. This would be an even worse vulnerability than malicious client-side code.

This post states old versions of IE may be vulnerable if your char-set is UTF-7, which it probably isn't.

If <div style...> is entered, it will be escaped. Therefore <div> and <span> should be included.

I believe every tag can have an onload=script, (E.G <u onload="script">), so only allowing tags by themselves is a good idea. (As you are already doing)

I suggest adding div, span, b, br and many other tags to the whitelist.

Edit: Since you mentioned you use PHP to echo the output, I also suggest testing using PHP functions or variables  in the input, such as $_SERVER['REMOTE_ADDR'].

Will the output show the result of that variable, or the literal text?


Flash Memory block write counting & thresholding

You can get an immediate speed-up by ditching the defaultdict(int), and using a bytearray(blockCount+1) instead.  Both have roughly \$O(1)\$ lookup time, but the latter has a much smaller constant factor.  In the former, each key must be hashed, then binned, then a linear search through the bin is required to find the correct key entry, if it exists, and creating it if it does not.  In the latter, the key is a direct index to the required memory.

This demonstrates a better than 3x improvement of bytearray over defaultdict:

>>> from collections import defaultdict
>>> from timeit import timeit
>>> def original():
    d = defaultdict(int)
    for i in range(1000000):
        d[i] += 1

>>> def using_bytearray():
    b = bytearray(1000000)
    for i in range(1000000):
        b[i] += 1

>>> timeit(original, number=100)
25.083420443999984
>>> timeit(using_bytearray, number=100)
7.779039941000008

Not only is the bytearray faster, it is also more memory efficient.  The bytearray uses just 57 bytes of overhead to store an array of 1 million bytes.  In contrast, the defaultdict weighs in at over 40x more memory ...

>>> sys.getsizeof(b)
1000057
>>> sys.getsizeof(d)
41943144

... but the real kicker is that is just the size of the dictionary's binning structures.  It excludes the size of all of the keys and values stored in the dictionary; those are harder to total as many small integers are interned and don't use additional storage allocation, and duplicate values may point to the same object.

Note: If threshold can exceed 255, you’d need to use array.array instead, with the appropriate type code for the largest rewrite count you’ll experience.

Of course, this is still the wrong approach.  With writes = [[0, 999999], [1, 1000000]], it should be obvious that block 0 is written once, blocks 1 through 999999 are written twice, and block 1000000 is written once.  There is no need to loop through the million indices; we just need to consider the end-points of each range.

So just store the starting & ending points, and the number of times each has been seen.  With a sorted array of indices of where the transitions occur, you should be able to iterate over these transition points, and construct your diagnostic list.

Implementation left to student.

Bonus: it is possible use one simple Dict[int,int] structure to store both starting and ending counts, if you think about it the right way.


Insert contact information from form fields into MySQL database when button is clicked

Not showing ConnectionString in plaintext. I currently store it in App.Config and I am still trying to figure out how to encrypt it.

Anything you can decrypt locally, a malevolent (and sufficiently skilled) user can too. More information given in the answer here.

There are other ways to avoid this:

Add a webservice backend layer. The frontend only connects to the backend (no connectionstring needed for that), and the backend has the connection string (which is out of reach for the frontend and its users).
Use Integrated Security, i.e. using the current Windows account for logging in to the database; as opposed to providing a username and password in the connection string. But you'd need to provide the needed rights to all of your users' Windows account, and then everyone is working under their own account (some companies do this, most don't).

  catch try finally to deal with exceptions.

Your current implementation seems okay, but I do wonder about the finally.

If there is no error, the textboxes get cleared. That seems okay. But if there is an error, the textboxes still get cleared? That doesn't seem user friendly. I'd expect you'd want to specifically keep the content of the textboxes so the user can retry saving the data.

try
{
    //save the data

    ClearAllTextBoxes();
}
catch (Exception ex)
{
    MessageBox.Show(string.Format("An error occurred {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

If an exception occurs when saving the data; the exception will skip over the ClearAllTextBoxes(); and go straight to the catch. It will never empty the textboxes.
However, if no exception is encountered, then the code will continue with ClearAllTextBoxes(); and therefore clear the textboxes.

  Minor comment
  You may want to put a return; in your catch. Not necessary at the moment, but it will become relevant if there is more code after your try catch.

In general, it's not good to put data handling (the SQL query) inside the UI. You'd want to put at least one layer of separation between the two.

However, you did mention you're a beginner; so I'm not going to hammer this point right now. If this project is a simple test application; you don't have to implement that layer of separation.

But I would advise trying to separate the two in future projects. You don't want a bad habit to form.

This is nitpicking, but

if (TextboxesAreNullorEmpty() == true)

really grinds my gears. == true is redundant, you can simply use

if (TextboxesAreNullorEmpty())

In order to reduce nesting, you can change your code. As it currently stands, you have:

if (TextboxesAreNullorEmpty())
{
     MessageBox.Show("Please fill out all fields!");
     return;
}
else
{
      //Do the work
}

You can omit the else.

if (TextboxesAreNullorEmpty())
{
     MessageBox.Show("Please fill out all fields!");
     return;
}

//Do the work

This works exactly the same way. The only difference is that you have less indentation in your code. While one extra level of indentation may not be an issue; a sufficiently complex algorithm can have several ìnstances of redundant indentation, at which point it does become a relevant consideration.

But since you are a beginner, this isn't really a big issue right now. Just keep it in mind for the future, to avoid a bad habit.

Although you're not yet at the point of abusing it; you should start looking into breaking up the code you have and putting it into multiple smaller methods.

Currently, you have a single method that does many different things:

Handle the button click event
Validate the form (this is already correctly abstracted into a separate method)
Set up the SQL connection and command
Update the data in the database
Handle errors

I would suggest you add two extra methods here:

Instead of putting the logic inside the click event handler, have the click event handler call a StartSave() method which does the work. The benefit of this becomes clear once you can have multiple triggers to save the data (since the act of saving data isn't uniquely connected to a single user control anymore).
Put the entire try catch into a separate method, e.g. UpdateDatabase(). Ideally, you'd want to use method parameters here for all the input variables; which will give you a layer of separation between your form controls and the SQL parameters.


One general way to speed up dynamic algorithms is the "Method of Four Russians" - \$O(\frac{n^2}{\log n})\$. But to implement this method you should use limited alphabet (not like numbers in your implementation).

Although theoretically this method looks awesome, practically the size of a lookup table is growing fast (\$O(3^{2t} \cdot \left|A \right| \cdot t)\$, where \$\left|A \right|\$ is the size of an alphabet, and \$t\$ is a block size). For example, in the case of DNA (4 letters alphabet) it can fit to the modern cash memory just in the case of \$t\$ equals to 3 (\$\sim0.1MB\$) or 4 (\$\sim10MB\$).

Another way to optimize the pairwise alignment is to take advantage of an extended instruction set of modern CPUs (SIMD extension). Up to now there are several such implementations of the Smith-Waterman algorithm (1 or 2).


Bug

This calculation looks suspiciously buggy:

int tzm = ((double) avg * 3 + TEZA) / 4;

Why are you taking avg, which is already a double, and casting it to a double?  Furthermore, why are you taking the right-hand side, which is a double, and coercing it into an int variable?  Note that you had declared double tzm earlier in the code; this int tzm declaration shadows the earlier declaration.  Your compiler should have warned you that the tzm on line 8 is unused.  (You do compile with warnings enabled, right?  It's a good habit.)

In any case, you should write a comment explaining why the tzm formula is the way it is.  I don't understand the calculation.

By the way, you can get floating-point division without explicitly casting, simply by writing / 4.0.

Using the bitwise | operator in tf == "Y" | tf == "y" is not really appropriate; it should be a logical || operator.

Optimization

There is absolutely no point in optimizing this code for performance.  Nearly all of the time is going to be spent waiting for input; the calculations are trivial.

What you should do, though, is to optimize it for elegance and readability.

The key is to identify functionality within main() that can be extracted out into functions, so that main() no longer has any tedious details.  For example, a common pattern is printing a question, and expecting a response from the user.  I'd define three functions, to ask the user for string, integer, and yes/no responses.

I would also define a letterGrade() function so that all of the results can be reported using just one statement.

Avoid cluttering your code with variables that don't mean much.  I'd get rid of sum and tf, for example.  The tzm variable is simply a recalculated average of sorts, so I'd get rid of it too.

Suggested solution

#include <iostream>
#include <string>

std::string ask(const std::string& prompt) {
    std::string answer;
    std::cout << prompt;
    std::cin >> answer;
    return answer;
}

int askInt(const std::string& prompt) {
    int answer;
    std::cout << prompt;
    std::cin >> answer;
    return answer;
}

bool askYN(const std::string& prompt) {
    std::string answer = ask(prompt);
    return answer == "Y" || answer == "y";
}

std::string letterGrade(double grade) {
    return (grade > 10) ? "" :
           (grade >= 9) ? "A" :
           (grade >= 8) ? "B" :
           (grade >= 7) ? "C" :
           (grade >= 6) ? "D" :
           (grade >= 5) ? "E" : "F";
}

int main() {
    std::cout << "SIMPLE AVERAGE CALCULATOR\n\n";
    std::string subject = ask("Subject at hand?: ");

    std::cout << "\nInput the FOUR marks you'd like verified:\n";
    int m1 = askInt("\nM1: "),
        m2 = askInt("\nM2: "),
        m3 = askInt("\nM3: "),
        m4 = askInt("\nM4: ");
    double avg = (m1 + m2 + m3 + m4) / 4.0;

    if (askYN("\nWould you like to include the TEZA grade?(Y/N): ")) {
        int teza = askInt("What is the TEZA grade?: ");
        avg = (3 * avg + teza) / 4.0;
    }

    std::cout << "\nYour average grade at " << subject << " is " << avg << "\n\n"
                 "You got the following mark:" << letterGrade(avg) << "\n"
                 "DO YOU PASS: " << (avg >= 5 ? "Yes." : "No.") << "\n";
}


There are definitely a few things you could improve here.  First, you should create a method to convert a Roman numeral to an Arabic numeral and vice-versa:

def roman_to_arabic(number):

    total = 0

    for i in number:
        if i == 'I':
            total += 1
        elif i == 'V':
            total += 5
        elif i == 'X':
            total += 10
        elif i == 'L':
            total += 50
        elif i == 'C':
            total += 100
    if 'IV' in number:
        total -= 2
    if 'IX' in number:
        total -= 2
    if 'XL' in number:
        total -= 20

    return total

Then, you do not need to write this twice, but can call it like this:

total1 = roman_to_arabic(user1)

Another thing you could do to improve the code is use better names.  You have the inputs named as user1 and user2.  They do not represent users, but Roman numerals as strings, maybe roman_numeral1 would be a better name.  total1 also does not represent a total, but an Arabic numeral converted from a Roman numeral: arabic_numeral1.

Finally, you do not support 'D' (500) or 'M' (1000).  If you support these, you should probably add support for "CM" (900) too.  Otherwise, your code looks pretty good to me.


Most python users would just use sorted(string1) == sorted(string2). That's \$O(n log n)\$, which is not that much worse than your \$O(n)\$ solution.

But the code you've actually written is just a reimplementation of:

collections.Counter(string1) == collections.Counter(string2)

That said, your short-circuit if the lengths mismatch is a good idea no matter which implementation you use.

There are some style issues that jump out with your implementation:

char_count doesn't have a pressing need to be a nested function, I would put it at top level.
Don't have a local variable named char_count inside the same-named function.
Don't cross numbers like chr_count = char_count(string1);chr1_count = char_count(string2). If you need numbered variables, use the same number for all transformed forms also.

For your demonstration code, I would have written:

def test_two_string_anagrams():
    assert are_two_string_anagram("mary", "yram")
    assert are_two_string_anagram("albert", "abelrt")
    assert are_two_string_anagram("something", "anotherus")

Or possibly:

def test_two_string_anagrams():
    for s1, s2 in [
        ("mary", "yram"),
        ("albert", "abelrt"),
        ("something", "anotherus"),

    ]:
        assert are_two_string_anagram(s1, s2)

That way it can be run directly with py.test (and possibly other harnesses, I know the standard unittest requires wrapping them in a dummy class, but I haven't used any others).


Modelling employees in Go as a basic OOP exercise

Using a NewType() constructor-like function is the idiomatic way in Go. See Effective Go: Constructors and composite literals. Also relevant: Effective Go: Package names:

  The importer of a package will use the name to refer to its contents, so exported names in the package can use that fact to avoid stutter. (Don't use the import . notation, which can simplify tests that must run outside the package they are testing, but should otherwise be avoided.) For instance, the buffered reader type in the bufio package is called Reader, not BufReader, because users see it as bufio.Reader, which is a clear, concise name. Moreover, because imported entities are always addressed with their package name, bufio.Reader does not conflict with io.Reader. Similarly, the function to make new instances of ring.Ring—which is the definition of a constructor in Go—would normally be called NewRing, but since Ring is the only type exported by the package, and since the package is called ring, it's called just New, which clients of the package see as ring.New. Use the package structure to help you choose good names.

And if you want to iterate over a whole "collection" (e.g. slice, array, map, channel), the For statements with range clause is the clearest way. "Unfortunately" your People type does not expose such values, so it's not possible to use for range here.

It can still be improved to call People.Count() once:

for i, count := 0, employees.Count(); i < count; i++ {
    f, err := employees.Person(i)
    // ...
}

Other improvements

Your NewPeople() could be simply written as:

func NewPeople(group string) *People {
    return &People{group: group}
}

In People.Person() it's redundant to call errors.New() and fmt.Sprintf(), as the fmt package also has an fmt.Errorf() function doing just that:

func (ppl *People) Person(i int) (*Person, error) {
    if n := len(ppl.list); i < 0 || i >= n {
        return nil, fmt.Errorf("%s index %d is out of range %d-%d.",
            ppl.group, i, 0, n-1)
    }
    return &ppl.list[i], nil
}

Also it's just a matter of taste, but I find it easier to read if you use the max index instead of the length (which is max+1):

if max := len(ppl.list) - 1; i < 0 || i > max {
    return nil, fmt.Errorf("%s index %d is out of range %d-%d.",
        ppl.group, i, 0, max)
}

Also it's a good habit for a specific type to be consistent. Either use pointers in all places, or non-pointers. In case of Person, you mix both: People.Add() expects Person, but People.Person() returns *Person.


Active Directory security groups Search application optimization

Let us first review the code.

Stacking usings will reduce the level of indentation.
The Filter of the DirectorySearcher can be passed to the constructor
If the expected result of the FindAll() call will be huge, you should consider to return only needed properties, by using this overloaded constructor of the DirectorySearcher class.
The SearchResultCollection returned by DirectorySearcher.FindAll() implements the IDisposable interface hence it should be enclosed in a using as well. The remarks section of the documentation states:

  Due to implementation restrictions, the SearchResultCollection class
  cannot release all of its unmanaged resources when it is garbage
  collected. To prevent a memory leak, you must call the Dispose method
  when the SearchResultCollection object is no longer needed.

Implementing some of this changes could look like so

DirectoryEntry root = GetDirectoryEntry();
using (var groups = root.Children.Find("OU=Sample Security Groups"))
using (var directory = groups.Children.Find("OU=Permissions"))
using (var searcher = new DirectorySearcher(directory, "filter condition"))
using (var results = searcher.FindAll())
{
    foreach (SearchResult result in results)
    {
        if (result != null)
        {
            using (var group = result.GetDirectoryEntry())
            {
                items.Add((string)group.Properties["sAMAccountName"].Value);
            }
        }
    }
}

If you only need to get the SamAccountName's of the groups a specific user is a member of you can use UserPrincipal.FindByIdentity() like so

UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, "domain", "username", "password"), IdentityType.SamAccountName, "loginUser");

foreach (GroupPrincipal group in user.GetGroups())
{
    Console.Out.WriteLine(group.SamAccountName);
}


Building Weather Forecast from JSON with optionals

Remember optionals.
Let's start with answering your primary concern: what do I do with the summary field?
You've already appropriately set up a constructor which takes a String? argument for summary.  But your particular code never takes advantage of this fact, does it?

if let summary = curr_dict["summary"] as? String

Let's break down what's going on here piece by piece.

curr_dict["summary"] returns an AnyObject?.  It makes no assumptions about the type, since curr_dict is an NSDictionary.  It either returns whatever value is at that key, or nil if the key doesn't exist.

as? String tries to cast that value as a String.  If the value was nil or if it can't be cast as a string, it returns nil, otherwise it returns String.

let summary = declares the variable called summary, whose type is determined by the return of everything to the right.  Since the top of the right-side's stack is as? String, which can return nil or a String, then the return type is String?.

if let casts an optional type (String?) as a non-optional type (String) if it can, otherwise it enters the else block.

So... we can get rid of the if let part, and just make ourselves an optional string, right?
let summary = curr_dict["summary"] as? String
return WeatherForecast(date: date, summary: summary, latitude: latitude, longitude: longitude)

But wait, there's more!

guard let dict = json as? NSDictionary, // ...

We should prefer to use Swift types over Objective-C types when that makes sense.  And here is a place where it does.  What we want is a [String:Any].
guard let dictionary = json as? [String:Any], // ...

Encapsulate.
We should also prefer encapsulation.  It doesn't make particular sense to have a latitude and longitude property.  What we need is a type that encapsulates these, as they're just two parts of describing one thing: location.
The easiest solution would be simply importing CoreLocation and either using CLLocationCooridinate2D or CLLocation.  The downside to this, however, is that any class that uses our struct has to import CoreLocation in order to use this property, but we can easily get around this with a typealias:
typealias WeatherForecastLocation = CLLocationCoordinate2D

And now we replace our latitude and longitude properties with a property of type WeatherForecastLocation.

Informative Errors
So, JSONErrorType.InvalidJSON... how useful is this?  It's an enum with a single case, just so we have something to throw.  We can be so much more informative.
First of all, two types of valid top-level JSON objects.  Dictionary or array.  So any method we write to parse JSON will expect one of these two types, so the first error will be the JSON not being that type.  That gives use two errors right off the bat (and let's grab some better names here):
enum JSONParseError: ErrorType {
    case ExpectedArrayNotFound
    case ExpectedDictionaryNotFound
}

If we are looking for JSON with a top-level object of dictionary, and we don't find it, we throw ExpectedDictionaryNotFound.  It doesn't matter what it looked like.  But this is already more informative... we couldn't even manage to get past the first level.
Now, what's another sort of JSON parsing error?  Missing keys.  But we don't want to simply be that generic.  Let's specify what key is missing, shall we?  Swift enums can have associated values.  With our MissingKey error, we should use a String associated value to identify the missing key.  Or enum now looks like this:
enum JSONParseError: ErrorType {
    case ExpectedArrayNotFound
    case ExpectedDictionaryNotFound
    case MissingKey(String)
}

We also have an error case for when the type of the value doesn't match what we expect.  For this, we want to specify the key that's problematic and specify the type that we expect it to be, so let's associate a tuple of two strings:
enum JSONParseError: ErrorType {
    case ExpectedArrayNotFound
    case ExpectedDictionaryNotFound
    case MissingKey(String)
    case InvalidTypeForKey(String,String)
}

So, the first string specifies the key, and the second string is a message something like "Expected Int", "Expected Array".
Now... the last thing we can do here that's probably quite helpful... return the JSON that was passed in with error.
enum JSONParseError: ErrorType {
    case ExpectedArrayNotFound(Any)
    case ExpectedDictionaryNotFound(Any)
    case MissingKey(String,Any)
    case InvalidTypeForKey(String,String,Any)
}


Adding data from multiple Excel files to two lists

Your problem is not with 5 (or more) loops. Your problem is that you mixing code of different nature: walking over filesystem and name matching, and processing of files into single chunk of code.

Separate it into different functions calling each other:

def process_worksheet(wb, worksheet_name):
    sheet = wb.sheet_by_name(worksheet_name)
    # ...

def process_xslx(path):
    wb = xlrd.open_workbook(path)
    worksheets = wb.sheet_names()
    for worksheet_name in worksheets:
        if worksheet_name.rfind('7600') != -1 :
            process_worksheet(wb, worksheet_name)

for root,dirs,files in os.walk(src):
    files = [ _ for _ in files if _.endswith('.xlsx') ]
    for file in files:
        process_xslx(os.path.join(root, file))

Another option is to use generators to hide some details on how iteration is performed. For example, instead of walking over filesystem, let generator yield workbooks:

def walk_xlsx(src):
    for root,dirs,files in os.walk(src):
        files = [ _ for _ in files if _.endswith('.xlsx') ]
        for file in files:
            wb = xlrd.open_workbook(os.path.join(root, file))
            yield wb

for wb in walk_xlsx(src):
    # filter() is also a generator which yields only
    # worksheet names that have '7600' in their names
    worksheets = filter(lambda wn: '7600' in wn, wb.sheet_names())
    for worksheet_name in worksheets:
        # ...


I'm not sure why you're handling so many CSS files. If you have one CSS file for your application, which is minified and cached on the user's device, you can reduce HTTP requests and overall loading time.

Anyway. If you need to handle lots of these files and keep this approach, you could simplify your code in terms of readability.

Create an array of default CSS files:

$css = ['a', 'b', 'c'];

Create an array where you store the individual files for each page:

$pageCSS = [
    'page-a' => [
        'add' => ['d', 'e', 'f'],
        'remove' => [],
    ],
    'page-b' => [
        'add' => ['g', 'h', 'i'],
        'remove' => ['a', 'b'],
    ],
];

Now you need to test whether a requested page is in this array. If the key exists, add all new files and remove not-needed default files using array_merge and array_diff:

$page = 'page-a';

if (array_key_exists($page, $pageCSS)) {
    $css = array_diff(array_merge($css, $pageCSS[$page]['add']), $pageCSS[$page]['remove']);
}

Finally create all HTML elements. I find it easier to read, if you use single-quotes. This way you don't need to escape all double quotes with backslashes:

foreach($css as $file) {
    print '<link rel="stylesheet" type="text/css" href="' . $file . '.css">';
}


Deferring command execution with a simple lambda
It is very similar to what you did, but no need to bring in heavier artillery like functools.partial, especially because you have no idea who is going to read your code and they may not understand it :(
I'd go with
def addText(self, x=0):
    if x == 0:
        button = Button(root, command=lambda: self.addText(1))
    else:
        # run other stuff for function

If this still annoys you because of the recursive call, then consider:
def auxiliaryStuff(self, x):
    # run other stuff for function

def addText(self, x=0):
    if x == 0:
        button = Button(root, command=lambda: self.auxiliaryStuff(1))
    else:
        self.auxiliaryStuff(x)

I'm assuming x can take values other than 1 or 0 from other places in your code. If they are always either 1 or 0 and they just represent a flag, consider using True and False instead.


Passing an array of values in Url.Action

I assume you "own" the controller?
If so, I'd serialize and deserialize the list as a comma separated string on each side.
It'd also be nice if criteria.JobTypes is an empty list instead of a possible null, then you don't need the ?? below.

var redirectUrl = Url.Action("search", new {
    // ...
    jobTypes = String.Join(criteria.JobTypes ?? new string[0], ",")
}

And do jobTypes.split(",") in the action.

URL would look a bit nicer too:

/search?q=developer&advanced=false&salaryfrom=20000&salaryto=80000&jobTypes=Full%20Time,Contract


Thread-safe "singleton" that destroys object when not used anymore

The problem with the above code is that it doing two things with one piece of code.

1: Singleton Creation.
2: Singelton LifeSpan.

I would separate these out into two separate classes.

The creation is done via an abstract factory (MySingletonFactory) but lifespan is controlled via explicit factory classes that are defined for the situation (so your code does not define the life span of the singleton).

The other issue of the above code is that I have seen this not working because of the way global variables are created in libraries. When these libraries are linked together it is not required to remove duplicate variables (as all variables were already resolved as much as possible during compilation). The linking phase will only try and resolve unresolved dependencies not all linkers will try and remove duplicated global variables (though I suppose this will depend on how sophisticated the linker is).

Here is how I would resolve the problem (by removing globals (using static storage function scope variables)).

Interfaces

#include <memory>
#include <iostream>
#include <cstdlib>

class MySingleInterface
{
    public:
        virtual ~MySingleInterface() {}

        virtual int doWork() = 0;
};
class MySingleFactoryInterface
{
    public:
        virtual ~MySingleFactoryInterface() {}
        virtual std::shared_ptr<MySingleInterface>  createTheObject() = 0;
};

Abstract Factory (I think?)

class MySingletonFactory
{
    private:
        friend class MySingleInterface;
        static MySingleFactoryInterface& getCurrentFactory(MySingleFactoryInterface* replace)
        {
            // Do not strictly need a default factory.
            // But it is nice to have one for standard (default)
            // operations. Then you only specify one in non standard
            // situations like testing.
            static MyDefaultSingeltonFactory           defaultFactory;

            // The current factory we are using.
            static MySingleFactoryInterface*           currentFactory = &defaultFactory;
            if (replace)
            {
                std::swap(replace, currentFactory);
            }
            else
            {
                replace = currentFactory;
            }
            return *replace;
        }
    public:
        static std::shared_ptr<MySingleInterface> getInstance()
        {
            return getCurrentFactory(nullptr).createTheObject();
        }
        static MySingleFactoryInterface& setFactory(MySingleFactoryInterface& alternativeFactory)
        {
             return getCurrentFactory(&alternativeFactory);
        }
};

Example Default Singleton

class MyDefaultSingeltonFactory;
class MyDefaultSingleton: public MySingleInterface
{
    private:
        friend class MyDefaultSingeltonFactory;
        MyDefaultSingleton(){}
    public:
        virtual int doWork() override {static int value; return value++;}   // Normal operation.
};
class MyDefaultSingeltonFactory: public MySingleFactoryInterface
{
    // A Normal Singleton factory.
    // The singelton lives from creation until the end of the program.
    // Note: This is the behavior of this factory does not need to
    //       to be universal behavior.
    public:
        std::shared_ptr<MySingleInterface>  createTheObject() override
        {
            std::shared_ptr<MySingleInterface>  instance = std::shared_ptr<MySingleInterface>(new MyDefaultSingleton());
            return instance;
        }
};

Example Test Singelton

class MyTestSingleton: public MySingleInterface
{
    int value;
    public:
    MyTestSingleton()
        : value(rand())
    {}
    public:
        virtual int doWork() override {return value;}        // Operation for testing.
};

class MyTestSingletonFactory: public MySingleFactoryInterface
{
    // This factory creates a new instance each time.
    // Can be useful for some types of test.
    public:
        std::shared_ptr<MySingleInterface>  createTheObject() override
        {
            return std::make_shared<MyTestSingleton>();
        }
};

class MyTestPersistantSingletonFactory: public MySingleFactoryInterface
{
    // As long as the code holds a shared pointer it will be re-used.
    // Useful if you want to create the singleton during "setUp()" and
    // destroy it during "tearDown()" you get a brand new singleton for
    // each individual test.
    public:
        std::shared_ptr<MySingleInterface>  createTheObject() override
        {
            // I leave the exercise of locking to you.
            static std::weak_ptr<MySingleInterface>     persist;
            auto result = persist.lock();
            if (!result)
            {
                result = std::make_shared<MyTestSingleton>();
                persist = result;
            }
            return result;
        }
};

Test Harness

int main()
{
    srand(0);

    // Incrementing results.
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";

    // Each result indapendant.
    MyTestSingletonFactory  testFactory;
    MySingletonFactory::setFactory(testFactory);
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";
    std::cout << MySingletonFactory::getInstance()->doWork() << "\n";

    MyTestPersistantSingletonFactory    persistantFactory;
    MySingletonFactory::setFactory(persistantFactory);
    {
        // As long as we hold a reference then
        // we should get the same result.
        std::shared_ptr<MySingleInterface> local = MySingletonFactory::getInstance();
        std::cout << "L: " << local->doWork() << "\n";
        std::cout << "L: " << MySingletonFactory::getInstance()->doWork() << "\n";
        std::cout << "L: " << local->doWork() << "\n";
        std::cout << "L: " << MySingletonFactory::getInstance()->doWork() << "\n";
    }
    // No local reference so we will create a new value.
    std::cout << "N: " << MySingletonFactory::getInstance()->doWork() << "\n";
}

Output

> ./a.out
0
1
2
3
4
5
6
7
8
520932930
28925691
822784415
890459872
L: 145532761
L: 145532761
L: 145532761
L: 145532761
N: 2132723841


Store, retrieve and delete settings in C# Registry

Quick remarks:

When you're copy-pasting code, you should realize you're doing the wrong thing. The first four lines of each of your methods are exactly the same, and thus should become a method that returns a RegistryKey.

Do not needlessly abbreviate. softKey, compKey, appKey and secKey are all unclear.

Do not use Hungarian notation. Even if the type isn't clear from a parameter's name, your IDE will tell you what type it is.

Why doesn't DeleteSetting use GetSetting to retrieve the value?


Forgive me if I misunderstand it, but in the second loop isn't the report and reports[report.rank] refer the same object?

Because if so, then the following simpler code would produce the same result:

function (reports) {
    reports.forEach(function (report, i) {
        report.upPercentage = reports.upTime / reports.totalTime;
    });
    _.sortBy(reports, 'upPercentage').forEach(function (report, i) {
        report.rank = i;
    });
    return reports;
}


Proper parallelism is hard in any language. You should definitely take the time to at least skim through all of the python docs for both the threading module AND the multiprocessing module. (see details below)

Also, in python there's an added wrinkle in that there is a Global Interpreter Lock. The simplified explanation is that Threads from the threading module run asynchronously, but not actually in parallel while multiprocessing Processes run in true parallel. For code like yours where you're querying the web and waiting for IO, threading helps because you can get something else done while waiting. But you might also get a speedup from dividing the load with multiprocessing (and have several threads inside each of those). Mulitprocessing processes take longer to setup so they're not as good when you're waiting on IO (as you are with response.get() ), but they run in true parallel--different processes in the system.

I'm not an expert on tuning between the two yet. I'll just warn you that when there are identically named communication objects like Queue and Event inside both the threading and multiprocessing module, and you have to use the correct one for the boundary your communication is crossing or it won't work.

Usually you want try statements to encapsulate the minimum amount of code possible so you can better predict what to do with the errors. As such response = response.get(... is probably the only line currently inside that actually needs to be in the try statement.

Edit: this section originally used dict keys which are only good for exact matches.

Removing specific responses can be done in one loop instead of going back over the loop many times. Also, the column of if statements can be made into a single statement by looking at a list. Something like:

removelist = ["You are using", "Google Chrome", "Tweet", "wa-com.com"]

for site in sites:
    for x in removelist:
        if x in site:
            sites.remove(site)
            break

Writing to a text file via a command line passed into os.system is not the most efficient method of doing that. First because you're involving the os module as a middle man when you don't need to, and second because you're doing all of this from up to 40M+ threads at once.

Instead write the output from each thread to a python Queue.

for site in sites:
    sitequeue.put(site)

Then have a single thread (or your main thread) read from the Queue and write to the file. Something like

with open('output.txt') as f:
    while not all_done_event.is_set():
        f.write(sitequeue.get())

Next you probably don't want 40M+ threads going at once, but time.sleep(0.5) is not the best way to control the number of threads launched. Instead determine the approximate maximum number of threads you can launch before the first one gets a response, and use a Semaphore object to control when new threads are launched. This keeps you always at the optimal number until you are done rather than using a guess about how long each thread will run. Something like:

maxthreads = 15
threadpool = BoundedSemaphore(value=maxthreads)
for ip in ips:
    threadpool.acquire()
    scan = ip2host(ip)
    scan.start()

and have threadpool.release() at the end of the ip2host.run() function to signal that the next thread can be started. Again, you may also want to split ips groups and wrap the threading objects in a multiprocessing Pool class object to get true parallelism on top of threading.

Hope this helps!


Your code is a little confusing.  You're using names like currWord and passing a word to checkVowel, which is then checking for 'aeiou' etc.  I think of vowels as letters, so on the face of it you appear to be checking whole words against individual vowel letters, which probably shouldn't match.  That said, maybe the file is ordered such that it's actually only reading letters at a time.  Either way, your code is unclear.

As has been said in the comments, whilst you've technically used threads to perform the printing, it's unlikely that this is the strategy that was expected to solve the problem.  There are many approaches that you could take to solving the problem, one of which might be something like this:

start ConThread
start VowelThread

Open File
ForEach word in file
    ForEach letter in word
        if Vowel
            StoreLetter
            Set VowelFlag
        else
            StoreLetter
            Set ConFlag
        while ReadNextLetterFlag not set give up control
        clear ReadNextLetterFlag

Shutdown...

The vowel/Con threads then consist of something like:

While not shutdown
    While ConFlag not set give up control
    clear ConFlag
    Retrieve letter
    Output to console
    Set ReadNextLetterFlag

Giving up control of the running thread could be achieve using yield (although this isn't particularly efficient) and you may want to pair it with sleep.

For flags, you probably want to look at either atomic and/or volatile variables.


Dynamically adding QLineEdits and then copy text from them to vector in right order

Since the MainWindow destructor is empty, you can just omit it.

In lineedit_textChanged, you declare the index variable at the top,
but it's only used if the text has changed.
It would be better to declare it inside the if branch where you actually use it:

if (isTextchanged)
{
    QStringList list = senderobjName.split("lineedit");
    unsigned int index = list[1].toInt();
    users[index] = text;
}

This snippet can be a bit confusing without braces on the outer if:

if(!middlelayout->isEmpty())
    if((child = middlelayout->takeAt(qlist.count()-1)->widget()) != 0) {
        delete child;
        qlist.removeLast();
}

It would be clearer this way:

if (!middlelayout->isEmpty()) {
    if ((child = middlelayout->takeAt(qlist.count()-1)->widget()) != 0) {
        delete child;
        qlist.removeLast();
    }
}


Dynamically change attribute value with split() (JavaScript)

I hope this helps. Made some comments in the snippet.

/* Create <option> tags */
class OptionTime extends HTMLSelectElement {
  constructor() {
    super();
    this.setDateRange();
  }

  setDateRange() {
    const now = new Date();
    const year = now.getFullYear();
    const unit = this.dataset.range.split(' ')[2];
    const startYear = year - 50; // No need to deconstruct start/end and assign years again.
    const endYear = year - 18;

    // `this` give access to HTML element directly.
    this.setAttribute('data-range', `${startYear} ${endYear} ${unit}`);

    for (let i = startYear; i <= endYear; i++) {
      this.add(new Option(`${i}${unit}`, `${i}${unit}`));
    }
  }
};

customElements.define('option-time', OptionTime, {
  extends: 'select'
});

<select is="option-time" name="Year" data-range="%startYear% %endYear% 年">
  <option value="" disabled selected>Year</option>
</select>
<select is="option-time" name="Month" data-range="1 12 月">
  <option value="" disabled selected>Month</option>
</select>
<select is="option-time" name="Day" data-range="1 31 日">
  <option value="" disabled selected>Day</option>
</select>