Simple registration with NodeJS and Mongoose

Well, the code is fairly simple, but you've made it complex due to a bad design. I would encourage the following:

Use Promises. Mongoose implements promises and so does express, so most of the times you can avoid using callbacks. Also implement your own helpers with promises. Further more you can read up on Async/Await too.
Read up on ES6. Use Arrow-functions, const/let variables, etc. It's not just syntactic sugar, but also more consistent overall.
Destructure package variables and arrays. It shortens your code and makes it easier to read.
Use functions. Functions are your friends. Get used to breaking down problems into small pieces and code into small functions. As a rule of thumb no function should have more that two indentations. If you need to nest many if-else clauses, then function them.
Use semicolons. Even though JS accepts code without semicolons, it's a good practice to use them because it makes the code more readable and less error-prone.

Now, getting back to your code... I made a small refactorization so you can see how it should look, but it needs a complete refactor of architecture as well as code because imo there are many anti-patterns and wrong responsibility assignation, i.e. validations should be frontend, the constants should be in the same file they are used, etc. Nonetheless, this last is more opinion-based.

'use strict';

const User = require('../../models/user'),
    { ERROR_MESSAGES, RESPONSE_STATUS } = require('../../models/constant'),
    helper = require('../../helpers/helper'),
    validator = require('validator');

const register = (req, res) => {
    const email = req.body.email;
    const password = req.body.password;
    const errors = [];

    // input validation
    validate(email, password);

    if (errors.length > 0) {
        return res.json(helper.generateResponse(errors, null, RESPONSE_STATUS.REQUEST_DENIED))
    } else {
        User.findOne({email: email})
        .then(user => {
            if (user) {
                res.json(helper.generateResponse([ERROR_MESSAGES.DUPLICATE.EMAIL], null, RESPONSE_STATUS.REQUEST_DENIED))
            } else {
                createUser(email, password);
            }
        })
        .catch(err => {
            res.json(helper.generateResponse([ERROR_MESSAGES.UNKNOW], null, RESPONSE_STATUS.REQUEST_DENIED))
        });
    }
}

const validate =  (email, password) => {
    if (!email || email.trim().length == 0) {
        errors.push(ERROR_MESSAGES.EMPTY.EMAIL)
    } else if (!validator.isEmail(email)) {
        errors.push(ERROR_MESSAGES.INVALID.EMAIL)
    }

    if (!password) {
        errors.push(ERROR_MESSAGES.EMPTY.PASSWORD)
    }
};

const createUser = (email, password) => {
    let user = new User()
    user.email = email
    user.password = user.generateHash(password)

    const errorValidation = user.validateSync();
    if (errorValidation) {
        errors = helper.getMongooseValidationErrors(errorValidation.errors)
        res.json(helper.generateResponse(errors, null, RESPONSE_STATUS.REQUEST_DENIED))
    } else {
        saveUser(user);
    }
};

const saveUser = user => {
    user.save()
        .then(newUser => res.json(helper.generateResponse(errors, newUser, RESPONSE_STATUS.SUCCESS)))
        .catch(error => res.json(helper.generateResponse([error], null, RESPONSE_STATUS.REQUEST_DENIED)));
};

module.exports = { register };

As I said earlier, I'd suggest a complete refactor not just making syntactic changes like the ones I commented, but also architecture changes. If you need to decide how-to structure the project, etc. Ask other questions in Stackoverflow, maybe :)


Find and process duplicates in list of lists

It looks like you could use collections.Counter. Although you may want to use it earlier in your code, when you create the list of pairs you pass to dedupe. As is, you could use the following in your code:

from collections import Counter

def dedupe(data):
    result = Counter()
    for row in data:
        result.update(dict([row]))
    return result.items()

>>> data = [['foo',1], ['bar',3],['foo',4]]
>>> dedupe(data)
[('foo', 5), ('bar', 3)]


I'm asking for rather hard, destructive critics and review.

Sure.

Interface.

I don't see the interface (ie class definition). So it becomes harder to review.

Things I don't see

I don't see any move semantics for your class.

Normally (since C++11) I would expect containers to implement move semantics. i.e. I would expect to see the following methods:

 Vector(Vector&& move) nothrow
 Vector& operator=(Vector&& move) nothrow
 void swap(Vector& other) nothrow

Also I don't see your code implementing the rule of three. This means that your objects will not work correctly if there are any copies made (and C++ makes copies all the time).

To implement the rule of three you need to implement the following three methods:

Vector(Vector const&);
Vector& operator=(Vector const&);
~Vector();

Code Review

This is a dangerous interface. you are asking the user of your class to know and manually set the size. An important thing in C++ is to try and define interfaces that can not be used incorrectly.

Vector::Vector(int vector[], int sizeT) {

I prefer the iterator version of the interface. Yes it is still just as dangerous but the utility functions add in C++14 will help you correctly identify the dangers and potentially generate compiler errors.

template<typename T>
Vector::Vector(I begin, I end) {

Now when you use it.

int data[23];
Vector   v(std::begin(data), std::end(data)); // will correctly size the vector
                                              // even if the size is changed.

void test(int* data, std::size_t s)
{
    Vector v(data, data + s); // still works (you just need to add).
}

int*     data = new data[23];
Vector   v(std::begin(data), std::end(data));  // will fail to compile
                                               // For the dangerous
                                               // situations it fails to compile.
                                               // which makes you look.

Use of this-> is discouraged

I consider the use of this-> dangerous as it hides errors. It also shows that you are being lazy in naming your local/member variables.

I know you are going to ask "how does it hide errors?".

The only reason that you need to use this-> is when you have shadowed member variables. You then use this-> to differentiate the member variables from the local variables. But it requires that everybody correctly identify the member/local variable. Any mistake will still silently compile. So this type of error can not be detected by the compiler.

On the other hand if you don't allow shadowed variables (and you can make the compiler detect shadowed variables and fail your compilation) now you have no situation where dropping the this-> (or forgetting) it will NOT cause an error. Since it does not matter whether the this-> is there or not why not just drop it.

This is a funny Constructor.

Not even sure why you would have this interface.

Vector::Vector(Vector* v1) {

You normally have a copy constructor which looks like this:

Vector::Vector(Vector const& v1) {

But an interface that takes pointers is very rare (and for this type of situation is practically never done). You are leaking ownership information. Who ownes the pointer you pass? (Ownership semantics is very important in C++ as the owner of the object is the person responsible for deleting it. A pointer has no ownership information).

Error:

Additionally this interface is broken.

Vector::Vector(Vector* v1) {
    this->array = v1->array;
    this->size = v1->size;
}

Consider this situation:

{
    Vector   a(5);
    Vector   b(&a);   // This is your copy (but the same would apply if
                      // you naively converted it to a standard copy
                      // constructor)
}

In the above case both object point at the same dynamically created object. Not a problem in itself. BUT they both think they own the object and thus will both delete it in there destructor this is illegal.

Const methods

A method that does not change the state of the object should be marked as const.

int Vector::length() {
    return this->size;
}

This is both an indication to the compiler and also allows the object to be used in a context where you only have a const reference (quite common).

Exceptions

Yes you can throw anything. But normally you would throw an exception object that is derived from std::runtime_error.

In your code you are throwing an object of type char const*.

int Vector::getAt(int idx) {
    if(idx >= this->size) {
        throw "out of range";
    }
    return this->array[idx];
}

I would do it like this:

int Vector::getAt(int idx) {
    if(idx >= this->size) {
        throw std::out_of_range("Vector::at()");
    }
    return this->array[idx];
}

Don't do checks for the user.

Don't do uneeded checks for the user. Rather provide methods so that users can perform their own checks to validate there calls. You can provide a checked version of the interface as well.

The std::vector has two techniques for access elemements (just like you). operator[]() and at(). The only difference between the two is that at() validates the index and operator[]() does not.

int& Vector::operator[](const int index){

    // Would not expect this check.
    if(index >= this->size) {
        throw "Vector::out of range";
    }

    return this->array[index];
}

The reason is that in most use cases you don't need to validate the range because you have already validated that your index is within the required range:

for(int loop = 0;loop < v.size(); ++loop) {
    // No need to check the range of `loop`
    // You have guranteed it is correct by the context it is used in.
    // Thus we use the unchecked range operator.
    std::cout << v[loop] << "\n";
}

Do check the range where it is important.

Here I would check the range.

void Vector::deteleAt(int idx) {
    for(int i = idx; i < this->length() - 1; ++i) {
        this->array[i] = this->array[i+1];
    }
    --this->size;
}

The line --this->size; is unchecked. If I delete a non existent element then it still reduces the size. Probably not what you want.

Looks Fishy

This is a very standard pattern for parent and children in a heap.

//HEAP--------PRIORITY QUEUE
int Vector::parent(int idx) {
    if(idx >= 0 && idx <= 2) {
        return this->array[0];
    }

    return this->array[idx/2];
}

The fact that you are special casing 1 and 2 makes me suspicious that there is underlying error you are trying to correct for.

Should not the parent be:

parent = (child-1)/2    //   0   1   2
leftC  = parent*2 + 1   //   1   3   5
rightC = parent*2 + 2   //   2   4   6

Use standard algorithms where you can

void Vector::swap(int firstIdx, int secondIdx) {
    int rotator = this->array[firstIdx];
    this->array[firstIdx] = this->array[secondIdx];
    this->array[secondIdx] = rotator;
}

There is a std::swap() this will swap two elements in the most efficient way possible. For integers your swap is probably the most efficient. But if you change what is held by your vector to some other complex object this may no longer be the most efficient technique (think move semantics).

Printing

When having a printing function, what you are actually doing is writing to a stream. So why not provide the opportunity to use different streams. So add a parameter that allows you to specify the stream (this can default to std::cout.

void Vector::print(){
    for(int i = 0; i < this->size; ++i) {
        std::cout<<this->array[i]<<" ";
    }
    std::cout<<"\n";
}

Also the default way of printing something in C++ is to use the output operator operator<< so you may as welll write that so that it uses your print function.

std::ostream& operator<<(std::ostream& s, Vector const& output)
{
     output.print(s);
     return s;
}


Python rsync to copy the logs from multiple remote servers

Review

Constants should be UPPER_SNAKE_CASE
More (and better) functions!

Lot of this code is in the global namespace, which is bad (not maintainable)
Why is sync doing argument parsing?

You should split up your code into individual instructions

Same goes for the logic of hosts splitting, these really should be part of another function (maybe parse_arguments)

Go with new style formatting or fstrings python3.6+
Simplify the split(',') using join()
Don't do manual path appending but use os.path.join()
Top it off with a if __name__ == '__main__'

Code

#!/usr/bin/python3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import subprocess
import argparse
import os

DEST_DIR = "/infralogs/external_dns_logs"
RSYNC_USER = "root"

EMAIL_SENDER = "dnslogger@udalt.com"
EMAIL_RECIEVER = "gusain@udalt.com"
EMAIL_CC = "gusain@udalt.com"

def parse_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument("-n","--hosts", dest="hosts", help="enter remote host/hosts name, comma seperated", metavar="HOSTS")
    parser.add_argument("-s","--src", dest="source", help="source file/directory", metavar="SOURCE")
    parser.add_argument("-e","--exclude", dest="exclude", help="Exclude files/Directories, comma seperated list", metavar="EXCLUDE")
    args = parser.parse_args()

    if args.exclude is None or args.source is None or args.hosts is None:
        parser.print_help()
        parser.exit()

    args.exclude = " --exclude " + " --exclude".join(args.exclude.split(','))
    args.hosts = args.hosts.split(',')
    return args.hosts, args.source, args.exclude

def sync(hosts, src, exclude):
    for host in hosts:
        host = host.strip()
        dest = os.path.join(DEST_DIR, host)
        cmd = f"rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz {exclude} {RSYNC_USER}@{host}:{src} {dest}/"
        p = subprocess.Popen(cmd, shell=True)
        p.wait()
        yield f"{cmd} Rsync process completed."

def mail(message):
    try:
        Mail = smtplib.SMTP('mailserver.global.udalt.com', 25, 'localhost.udalt.com')
        mail_obj = MIMEMultipart('alternative')
        mail_obj["From"] = EMAIL_SENDER
        mail_obj["To"] = EMAIL_RECIEVER
        mail_obj["Cc"] = EMAIL_CC
        mail_obj["Subject"] = "Rsync process completed Successfully."
        mail_obj.attach(MIMEText(msg, 'plain'))
        Mail.sendmail(from_addr=[EMAIL_SENDER], to_addrs=[EMAIL_RECIEVER],msg=mail_obj.as_string())
        print(f"Mail Sent to {EMAIL_SENDER}")
        print(message)
    except Exception as error:
        print(f"Mail Failed - {error}")

if __name__ == '__main__':
    if not os.path.exists(DEST_DIR):
        os.mkdir(DEST_DIR)

    for msg in sync(*parse_arguments()):
        mail(msg)


Doing multiple imports on the same line from different modules is frowned upon by PEP8, Python's official style-guide.

It also recommends using lower_case for variable names and not camelCase.

You don't need () around variables when assigning, src = 'C:\AEC Work\' + newFolder is enough.

Since you are already using os.path.join, which is a good thing, you should use it throughout.

You can use str.format to get "{:%m%d%Y}".format(datetime.datetime.now()) for the new folder name to make this slightly more compact.

import shutil
import os
import datetime
import time
import sys

os.system('TASKKILL /F /IM FlashRen.exe')

now = datetime.datetime.now()
directory = "{:%m%d%Y}".format(now)

src = os.path.join('C:','AEC Work', directory)
backup_base = os.path.join('\qnap01', 'Data Service', 'AARON')
dst = os.path.join(backup_base, "{:%Y}".format(now),
                   "{:%m. %B}".format(now).upper(), directory)

for file in os.listdir(src):
    src_file = os.path.join(src, file)
    dst_file = os.path.join(dst, file)
    shutil.move(src, dst)


Is it worthy to create a wrapper function like this?

Here's an idea, assuming your logic is really that straightforward:

workflow = []
conf = {}
result = []

steps = ((prepare_A, False),
         (prepare_B, False),
         (prepare_C, False),
         (prepare_D, True),
         (prepare_E, False))

for func, need_results in steps:
    res = func(workflow, conf)
    if need_results:
        result.append(res)

If you don't find that approach suitable, I'd suggest making your wrapper a class that encapsulates workflow and conf, and possibly results too.

class PrepareWrapper(object):
    def __init__(self):
        self.workflow = []
        self.conf = {}

    def __call__(self, prepare_function):
         return prepare_function(self.workflow, self.conf)

prepare_wrapper = PrepareWrapper()
prepare_wrapper(prepare_A)
prepare_wrapper(prepare_B)

Or, why not make all the prepare functions methods of this class?


Print the list of winter bash 2014 hats as a list of checkboxes in GFM format

Don't do this:

#!/usr/bin/env python

Some people make the poor excuse that PEP 394

  recommends that python continue to refer to python2 for the time being

but this doesn't even apply to you since yours only supports Python 3!

Use this instead:

#!/usr/bin/env python3

Your code could do with doc comments; at least load_html_doc could. These don't need to be long.

There's nothing wrong with caching files locally, but I would suggest writing to tempfile.gettempdir().

request.urlopen returns a file-like object. Moments later you use with on a file object but you neglect to do so on request.urlopen's!

I would do an early return in load_html_doc.

Your os.path.isfile(cached_file) check is strange; if it's a directory instead you don't actually deal with the resulting problem. It's not a big deal, but I would use os.path.exists to prevent it looking like you're actually checking.

cached_file would be better as a default argument, and I'd call it cache_file or even cache_path. IMHO fh isn't that great a name either.

Here's the updated code, still writing to the same file:

def load_html_doc(url, cache_file='page.html'):
    if os.path.exists(cache_file) and os.path.getsize(cache_file):
        with open(cache_file) as cache:
            return cache.read()

    with request.urlopen(url) as webpage:
        html_doc = webpage.read()
    with open(cache_file, 'wb') as cache:
        cache.write(html_doc)
    return html_doc

After all of the comments on load_html_doc, I'm sad (happy?) to say there isn't much to talk about with the rest of it. I would remove the # print_pretty(soup) comment, though.


jQuery make DRY two almost identical on click function

You need to have a group selector and just use this context to have the clicked list element:

  $('ul.icons li.size, ul.icons li.color').click(function() {
      $(this).addClass('selected')      // add to clicked li
             .siblings('li')           // get all other lis
             .removeClass('selected');  // remove the class
   });


Speed up code based on map with vectors as values

You can use std::iota for the sequential order vector. If it doesnt increase speed it is prettier:

std::vector<short> order(len);
std::iota(order.begin(), order.end(), 0);

The same obviously goes for indexes
Given that you emplace in sequential order here selected.emplace(lnum, vector<Graphic*>()) you might want to switch to emplace_back
If you do not care about memory you can reserve the memory for your graphics vector with a guess during initialization and then call shrink_to_fit afterwards. That way you avoid possibly costly reallocations. However depending on the size of your guess this might significantly increase the memory burden.


Naming

Give your class a more meaningful name, that begins with a capital letter -as all classes should in Java-, e.g. CaesarCipher.

The operation() method's name doesn't tell us anything about what it actually does. If it weren't for the //Encryption comment, there would be no indication that this class does something even related to encryption/decryption.

The variable shift_String uses snake_case while all the other ones use camelCase; pick one and stick to it (and since this is Java, I'd recommend camelCase as it is the accepted standard).

More generally, try using names that actually describe what the variable/method/class represents or does (what is d? what about test?). You could for example declare one String, say userInput, and reuse it whenever you want to store the user's input, that way you don't need to declare two variables where one has the same name as the other appended with String everytime.

Also, shortened names like out or d don't really have any benefit over slightly longer, clearer ones, other than making the very first time you type the name a tiny bit shorter. Giving them more meaningful names will make the code easier to read later, and you shouldn't be worried about typing a few more characters each time; let your IDE do its job!

final keyword

This recommendation is more based on my own opinions, but I think it's justified here since you've made use of it yourself.

Mark all method arguments as final; this will prevent you from accidentally reassigning them (which you really shouldn't do anyways).

Make all your instance & local variables final when appropriate; this simply indicates that once they are assigned a value, that value should not and will not change in the future. It may seem like you're simply adding more unnecessary fluff to an already very verbose language, but I personally think it helps writing clearer code as well as making it easier to debug.

If you want to read more about Java's use of the final keyword, I recommend this answer : https://softwareengineering.stackexchange.com/questions/98691/excessive-use-final-keyword-in-java.

Code Optimization & Reusability

The text variable is declared but never used.

Redundant checks in main() :

if(decision == 1) {
    boolean test = true;
    out = operation(field, shift, test);
}
else if(decision == 2) {
    boolean test = false;
    out = operation(field, shift, test);
}
else if(decision != 1 && decision != 2) {
    out = "Invalid choice!";
}

Your last else if could be replaced by a simple else, since the only way you'll get there is if decision is neither equal to 1 nor to 2. In this same snippet, you could also get rid of the test variable altogether, or maybe declare it before those conditionals and place the out = operation(field, shift, test); at the end. Additionnaly, what does test mean? What is it testing for?

You may want to implement another cipher later; if that's the case, then creating a simple Cipher interface might be worthwhile. You should also make caesar a separate class from main() and decouple it from all the user interface stuff, that way you can use it whenever you want, wherever you want. The interface might look something like this :

public interface Cipher {
    public String encrypt(final String text);

    public String decrypt(final String cipherText);
}

Use an enum to represent the two choices given to the user. This might be overkill for this case as you'd only have two possible values (ENCRYPT and DECRYPT, for example), but it would certainly make the code even more readable.

There's more that could be said, about user input validation, or using magic numbers in operation(), and more, but I'll leave it to other users.

Exception Handling & User Input

What happens if the user decides to type "oiuahffduht$$$" when you ask them for the shift value? Your program breaks and the user has to manually start it again! Always assume the worst from the user. Ideally, you'd want to handle such cases in your code via exception handling. If you're not familiar with the concept, you can take a look at this link which covers all the basics of EH in Java : https://stackify.com/specify-handle-exceptions-java/.

So what can we do here? If you look at the Java documentation for Integer.parseInt() -or check its signature from your favorite IDE, you'll see that it can throw a NumberFormatException, so let's catch it. Keeping the same logic and syntax as your original code, it might look something like this :

String shift_String = JOptionPane.showInputDialog("Please enter shift to the right:");

try {
    shift = Integer.parseInt(shift_String);
}
catch (NumberFormatException e) {
    // Handle the exception
}

There's lots of different ways you can handle the exception; you could simply show the user the contents of the exception or the stack trace, you could end the program... Personally, I think the best way to handle this case would be to show a new dialog that says something along the lines of "Error, you must enter a number", then show that previous input box and asks for the same thing again. That way the user won't have to close/reopen the program and they'll know what went wrong.

Magic Numbers

In your operation() method, you use a bunch of "magic numbers" (64, 90, 26...). So what's a magic number? It's basically a hardcoded value (not necessarily a 'number') that is present in your code without any explanation of why it's there or what it means.

Imagine if someone who's not familiar with ASCII were to read your code (though maybe they shouldn't be writing code in the first place). They might think you're using some crazy voodo magic to turn numbers into letters, who knows? So give these numbers names!

Or, maybe try a different approach entirely, where you would store all the possible characters in a String, then make use of the wonderful modulo operator like so :

private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

public static String encrypt(final String text, final int shift) {
        final String lowerCaseText = text.toLowerCase();
        String cipherText = "";

        for (int i = 0; i < lowerCaseText.length(); i++) {
            final int charPosition = ALPHABET.indexOf(lowerCaseText.charAt(i));
            final int newCharPosition = (shift + charPosition) % 26;
            final char newChar = ALPHABET.charAt(newCharPosition);

            cipherText += newChar;
        }

        return cipherText;
    }

Now you don't even have to deal with those annoying numbers anymore!

By the way, I haven't tested this, and I don't claim it to be more efficient or readable.


Converting from std::wstring to std::string in Linux

ssize_t is essentially unsigned; that is, the comparison res >= 0 is always true.

The test should be

res != static_cast<std::size_t>(-1)

<cstdlib> and <cwchar> headers are missing
You don't need to WS.copy(wbuf, wlen).

In fact, you don't need wbuf at all:

const wchar_t * wptr = WS.c_str();
std::wcsrtombs(buf, &wptr, sizeof(buf), &st);

works just fine.
I am not sure that calculating buffer length via sizeof(std::wstring::value_type) is a right way. How can you be sure that multibyte sequence will fit? I'd recommend to obtain required size by passing NULL to wcsrtombs.

PS: И тебе привет


All upper and lowercase permutations of a string

1. Review

"Permutations" is not the right word for what this code does. The permutations of a sequence are the different ways the items can be ordered: for example, the permutations of ABC are ABC, ACB, BAC, BCA, CAB and CBA. These can be computed using the built-in itertools.permutations:

>>> from itertools import permutations
>>> list(map(''.join, permutations('ABC')))
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']

What you have here are the different ways to capitalize the letters in a word, so the name ought to be something like capitalizations.
There are no docstrings. What do these functions do and how to I call them?
The Python style guide (PEP8) recommends:

  Avoid extraneous whitespace … immediately inside parentheses, brackets or braces.

The body of permute_first could be written more simply:

return [c.upper(), c.lower()]

In fact this is so simple that there's no real need for this to be a separate function at all.
If str contains non-letters then we get duplicates in the output:

>>> permute('<>')
['<>', '<>', '<>', '<>']

Use sorted(set((c.upper(), c.lower()))) to de-duplicate the output.
If str is the empty string, permute raises IndexError. It should return a list containing the empty string.

2. Revised code

This is a one-liner using itertools.product:

from itertools import product

def capitalizations(s):
    """Return a list of the different ways of capitalizing the letters in
    the string s.

    >>> capitalizations('abc')
    ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
    >>> capitalizations('')
    ['']
    >>> capitalizations('X*Y')
    ['X*Y', 'X*y', 'x*Y', 'x*y']

    """
    return list(map(''.join, product(*(sorted(set((c.upper(), c.lower())))
                                       for c in s))))


Coding - Find a bitwise XOR for a range of numbers in java

First of all the solution you have given is complexity O(n), not O(log(n)). It is possible to do it in O(log(n)) by calculating the result bit by bit. For example, suppose I have a range of four consecutive integers. Then I know that two of those numbers are odd and two of those numbers are even. Since only odd numbers have the first bit set I already know that XOR-ing the four numbers will leave the first bit at 0. For the second bit, I notice that for each set of four consecutive numbers there is always one number 2 mod 4 and one number 3 mod 4. Since all integers which have the second bit set ar either 2 or 3 mod 4, I know that XOR-ing the set of four integers will leave the second bit at 0. In this way I can determine for each bit if it should be set or not by looking at the properties of the numbers in the range. Usually this can be done in O(1) by only using the boundries of the range. Since there are log2(n) rounded up bits in n, this solution will have complexity O(log(n)).

On to the code.

static List<Integer> list;

This list is not needed, it can be removed.

public static int solution(int M, int N)

The name of the method is solution but it doesn't describe what it is doing. Try to give it a name in accordance with it's function, something like computeXorForRange perhaps. Also, all other variables and methods in your code are camelCase so for consistency you should make M and N lower case. Or you can rename them to lowerBound and upperBoundInclusive if you like to tell the reader what they represent.

int lastXOR = M;
currentXOR = 0;
try {
  for (int i = M; i < N; i++) {
    currentXOR = computeXOR(lastXOR, i + 1);
    lastXOR = currentXOR;
  }
} catch (Exception e) {
  System.out.println("Error Found : -" + e);
}

In this part it is not needed to have to different variables, currentXOR and lastXOR. One should be enough. Having the two variables here makes it more complex than it should be. Also, why are you catching exceptions here? What exceptions do you expect to happen? Since the code used in the try does not throw any exception except for the possible standard java runtime exceptions like for example OutOfMemoryException, it is not needed to have a try catch.

System.out.println("Input is not in the range or valid");
return -1;

This part is at the end of the method. Instead you can negate the if statement at the beginning of the method and put this piece in the if. Then it becomes more clear what happens if the conditions are not met. There is also a return -1 which is more of a C style thing. In this case it is perfectly fine to use an Exception, the IllegalArgumentException will fit since the arguments passed are not valid (they are too small or too large).

private static boolean isValidatedInput(int M, int N) {
  if (0 <= M && 0 <= N && M <= Math.pow(10, 9) && N <= Math.pow(10, 9) && M <= N) {
    return true;
  } else
    return false;
}

The name of the method can be changed to isValidInput. The name isValidatedInput suggests that there will be a check if the input is already validated while it seems you are validating the input. There us also no reason to have the return true and return false, you can immediatly return the condition used in the if. Because if that condition is true the method will then return true and if the condition is false the method will then return false. Lastly, the upper bound of 10^9 seems arbitrary. If you want to prevent overflows and underflows you can use Integer.MAX_VALUE as upper bound.

private static Integer computeXOR(Integer m, Integer n) {
  return m ^ n;
}

In the rest of the code you use int yet here you use Integers. Using Integer is not necessary in this case since you don't have to deal with null values so using int would be consistent with the rest of the code. You can also ask if this method is really needed. IMO something like x ^ y is perfectly fine and clear and you don't need a separate method for that, but if it helps you, you can leave it in.

All in all with the above suggestions the code will become

public static void main(String[] args) {
  int bitXORProduct = solution(5,8);
  System.out.println(bitXORProduct);
}

public static int solution(int lowerBound, int upperBoundInclusive) {
  if (!isValidInput(lowerBound, upperBoundInclusive)) {
    throw new IllegalArgumentException("Input is not in the range or valid");
  }

  int currentXOR = lowerBound;
  for (int i = lowerBound; i < upperBoundInclusive; i++) {
    currentXOR = currentXOR ^ (i + 1); // this can also be written as currentXOR ^= i + 1;
  }

  return currentXOR;
}

private static boolean isValidInput(int M, int N) {
  return 0 <= M
      && 0 <= N
      && M <= Math.pow(10, 9)
      && N <= Math.pow(10, 9)
      && M <= N;
}
```


There's several 'special cases' in your code.

String of length 1
String of length 0
'g' at start of String
'g' at end of String

I'd recommend getting rid of these special cases.

To do this, you can check for special conditions inside the for-loop.

Loop through all the positions in the string, and check if there is a 'g' on that position. If it is, then check if the position is more than 0 (i.e. it has a char in front of it) or if the position is less than str.length - 1 (i.e. it has a char after it).

The details about how to write this can be done in oh so many ways, but here is what I would end up with:

for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (ch == 'g') {
        if (i > 0 && str.charAt(i - 1) == ch) {
            continue;
        }
        if (i < str.length() - 1 && str.charAt(i + 1) == ch) {
            continue;
        }
        return false;
    }
}

return true;


Variable declaration keywords
One thing I notice is that the var keyword is used in some functions while others use const. The variables dbo, MongoClient and url are never reassigned so const can be used for those. Using const when re-assignment isn't needed is a good habit because it can help avoid accidental re-assignment and other bugs. Many users also believe var should not be used with ES6 code - refer to the ES lint rule no-var.
nested callbacks
The code is bordering on callback hell. I'd suggest moving anonymous functions out to being named functions. This will also help with automated testing. Let's look at the inner most function:
const insertionCallback = (db, err, res) {
    if (err) throw err;

    db.close();
};

It needs a reference to db. That could be made a parameter:
function (db, err, res) {

Then when making a reference to that function, make a partially applied function with db as the first argument:
dbo.collection("entity").insertMany(result, insertionCallback.bind(null, db))

Or instead of accepting db as a parameter, set the context to it:
dbo.collection("entity").insertMany(result, insertionCallback.bind(db))

after doing that this could be used instead of db within that insertionCallback function.
Then continue pulling out those nested functions - e.g. :
const insertResult = (result, err, db) => {
    if (err) throw err;

    const dbo = db.db("myDb");

    dbo.collection("entity").insertMany(result, insertionCallback.bind(null, db));
};

Then that function can be used in its outer function:
const handleParsedStr = (err, result) => {

    const MongoClient = require('mongodb').MongoClient;
    const url = "mongodb://localhost:27017/";

    MongoClient.connect(url, insertResult.bind(null, result));
});

And that functions can be used as the callback to parser.parseString():
parser.parseString(data, handleParsedStr);

error handling
Some of the callback functions check error arguments like err and conditionally handle such cases, but others don't- e.g. the callback to parser.parseString(). It is advisable to handle such errors, and would also make the code more consistent.
parser declared within forEach callback function
The variable parser is declared within the callback function to the .forEach() method. This means the parser is created once for each file in the directory. If possible, consider declaring it outside the loop to reduce resource requirements.


Well there is multiple solution to this problem ,

Using delegate:

public bool Validate<T1,T2>(T1 value, T2 compareValue, Func<T1,T2,bool> operation)
{
    return operation(value, compareValue);
}
magic.Validate(1, 2, (a, b) => a > b);
magic.Validate("Testing", "Testing", (a, b) => a.Equals(b));

but twp problems with this code is : first your input can be limited , right now you cannot compare more than two values , so you might need to see what can be done to extend this code.

second you can make a switch case to return the right method for comparision.

Using the Expression which could be more compact and will be cleaner code. I have not tried this yet.
Avoid using private variable naming with capital letters.
Avoid giving a name where two capital letters are at start (OMagic), you could write this like OperationMagic.
Avoid boxing and unboxing (if your operations are small dont worry).


Although the answer from Heslacher is a really good one, here's also what you might do. Create two boolean variable to check for null on the model.ValidFrom and model.ValidTo:

bool modelValidFromIsNull = model.ValidFrom == null;
bool modelValidToIsNull = model.ValidTo == null;

Now, like Heslacher mentioned, place a guard to rule out if they are both null.

if (modelValidFromIsNull && modelValidToIsNull) { return null; }

Now you can use these bool variables to do some magic. In the Where() clause of the query, use these flags to check or ignore the condition you want to apply. If the flag is true, the condition will be skipped and if it is false, the condition will be evaluated. A small example:

var numbers = new[] { 1, 2, 3, 4, 5, 6 };
var remaining = numbers.Where(x => false || x > 3);

The variable remaining will now contain 4, 5 and 6. If you were to change that false to true, the variable remaining would contain all the numbers from the original source. [That's why you need the guard :) ]

Now you can apply this logic to your code. When the model.ValidFrom is not null, your variable modelValidFromIsNull will be false. This means that in the where clause the left part is false and the second part will be evaluated. The same goes for model.ValidTo.

This is the resulting code:

bool modelValidFromIsNull = model.ValidFrom == null;
bool modelValidToIsNull = model.ValidTo == null;

if (modelValidFromIsNull && modelValidToIsNull) { return null; }

var result = dalList.Where(s => modelValidFromIsNull || DbFunctions.TruncateTime(s.ValidFrom) >= dateFrom.Date)
                    .Where(s => modelValidToIsNull || DbFunctions.TruncateTime(s.ValidTo) <= dateTo.Date);


A PHP script used on my home server to download YouTube videos

Initial thoughts

I must admit I hadn't heard of the youtube-dl program but it seems quite nifty. Perhaps it was what many of the websites I have seen for downloading YT videos use behind the scenes.

I tried using the script locally and found that the URL must contain an ampersand (i.e. have 2+ query string variables), otherwise the logic to look for a playlist parameter and remove it would lead to an empty string passed to the youtube-dl program. But some URLs I see from Youtube only have zero or one parameters (e.g. https://www.youtube.com/watch?v=DuB6UjEsY_Y and the equivalent sharing link: https://youtu.be/DuB6UjEsY_Y).

Initially I was wondering why $numberToUse couldn't be set to count($directoriesInUse) + 1 but then I realized that some of those directories could be deleted and that might lead to issues. Then I considered that if you could parse out a video id (which seems to have remained the same since 2014)  from the URL then that could be used instead of an integer for the sub-directory name.

Suggestions

Use a mapping instead of a switch

The switch could be simplified:

switch($_GET['format']) {
    case 'bestvideo': case 'worstvideo': $formatExt = "MP4"; break;
    case 'bestaudio': $formatExt = "m4a"; break;
    case 'worstaudio': $formatExt = "webm";
        break;
    default:
        echo("Illegal video format '".$_GET['format']."'!");
        exit(1);
}

A mapping could be defined of formats to extensions:

const FORMAT_MAPPING = [
    'bestvideo' => "MP4",
    'worstvideo' => "MP4",
    'bestaudio' => "m4a",
    'worstaudio' => "webm"
];

Then if the query string is missing that key or that key does not exist in the mapping, show the error and exit early.

if (!isset($_GET['format']) || !array_key_exists($_GET['format'], FORMAT_MAPPING)) {
    echo("Illegal video format '".$_GET['format']."'!");
    exit(1);
}

Otherwise just assign the value to $formatExt:

$formatExt = FORMAT_MAPPING[$_GET['format']];

Control structures not using statement groups

While it may seem unlikely that there would be a need for multiple lines following if, else or for statements, it is best to put the statements to execute in a group (i.e. with curly braces/brackets). Then when you determine that you need to add a line to one of those statement groups, it eliminates any chance of logic error.

if($format === "bestaudio" or $format === "worstaudio" or $format === "worstvideo") {
        $response = exec('mkdir ./workers/'.$numberToUse.' && cd ./workers/'.$numberToUse.'/ && '.$ytcmd.' --no-playlist --format '.$format.' -o \'%(title)s.%(ext)s\' '.$url);
}
else {
        $response = exec('mkdir ./workers/'.$numberToUse.' && cd ./workers/'.$numberToUse.'/ && '.$ytcmd.' --no-playlist -o \'%(title)s.%(ext)s\' '.$url);
}

or has lower precedence than || and others like assignment

Note the operator precedence list and how or is at the end of the list, while logical or i.e. ||, is above assignment and others:

There is a good illustration of the difference in the user contributed notes by fabmlk:

  Watch out for the difference of priority between 'and vs &&' or '|| vs or':

<?php
$bool = true && false;
var_dump($bool); // false, that's expected

$bool = true and false;
var_dump($bool); // true, ouch!
?>

  Because 'and/or' have lower priority than '=' but '||/&&' have higher.

So it is wise to get in the practice of using || unless you know you need or

use foreach instead of for

Instead of this for loop:

for($i = 0; $i < sizeof($directoriesInUse); $i++)
    $integerIDs[$i] = (int)explode("/", $directoriesInUse[$i])[2];

A foreach could be used

foreach ($directoriesInUse as $i => $directory) {
    $integerIDs[$i] = (int)explode("/", $directory)[2];
}

One could also use array_map(). Instead of storing an array of integers, you could just keep track of the maximum number seen - using max(). That would avoid the need to sort the array. This likely wouldn’t be a major optimization unless there were a large number of directories.

Logical flaw when no ampersand exists in URL

As was mentioned above, this line doesn't work well when there is no ampersand in $url

//url may contain & for a playlist, so it will be removed here to prevent other issues.
$url = substr($url, 0, strpos($url, "&"));

This is because strpos() "Returns FALSE if the needle was not found."1. I would update the code to only perform that alteration if the string actually contains an ampersand.

1http://php.net/strpos


Reducing steps for long addition program

1) It seems that you assumed length of a and b are the same. But if a has a bigger length than b you don't process all digits! Your loop should go over maximum of lengths of a and b and whenever one operand has no digit any more, use 0.

2) You can write these lines

i = c+d;
if (carry == 1) {
    i=i+1;
}

like this:

i = c + d + carry

use arithmetic operations when branches are not necessary.

3) The result of addition has always at most one digit more than the bigger operand. So you can allocate a string once and avoid concatenation in each iteration (just put the result digit in its right place).

4) You can reduce number of iterations by using the fact that you can add in higher bases! This way instead of a string, use an integer array and treat the
operands, say in base 10000. Now each digit in this base is a 4 digit number in base 10. Everything will be the same, except for setting the value of carry.
With base 10^4, you reduced number of iteration to one-forth. You can go further till where integer range supports safely (10^8).


You don't need to write this code yourself, there is already a method that does something very similar: Task.Factory.ContinueWhenAll().

ContinueWhenAll() doesn't directly support working with Tasks that return different types, but you can create a helper method that does:

public static Task<R> ContinueWhenBoth<T1, T2, R>(
    this TaskFactory<R> factory, Task<T1> t1, Task<T2> t2, Func<T1, T2, R> f)
{
    return factory.ContinueWhenAll(new Task[] { t1, t2 }, _ => f(t1.Result, t2.Result));
}

If you didn't want to use closure for performance reasons, you could use the array of Tasks and casting:

return factory.ContinueWhenAll(
    new Task[] { t1, t2 }, tasks => f(((Task<T1>)tasks[0]).Result, ((Task<T2>)t2).Result));

t1.ContinueWith(t => { if(t2.IsCompleted) result.TrySetResult(f(t1.Result, t2.Result)); });
t2.ContinueWith(t => { if(t1.IsCompleted) result.TrySetResult(f(t1.Result, t2.Result)); });

This code has a race condition: if t1 and t2 complete at the same time, then f might be executed twice. I don't think that's a good idea, since f might take a long time, or, worse, it might have side-effects.

if(Interlocked.Decrement(ref tasksLeft) == 0 && t2.IsCompleted)

The Decrement() here avoids the race condition from the previous code. But it also means that the check of t2.IsCompleted will always succeed, so you should remove it.

But your code also has a significant issue: if t1 or t2 fail with an exception, your resulting Task will never complete. (And on .Net 4.0, it will also crash the process some time in the future, because there is an uncaught exception in a Task.)


Unwrapping optional properties from an optional array of objects

There are several options, but in any case you can use

public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]

which returns an array containing the non-nil results of applying the
transformation to all sequence elements.

For example

if let unwrappedPeople = people {
    for id in unwrappedPeople.flatMap({ $0.id }) {
        print(id)
    }
}

to iterate over the non-nil ids, or

if let unwrappedPeople = people {
    let ids = unwrappedPeople.flatMap { $0.id }
    print(ids)
}

to get the non-nil ids as an array.

To get rid of the outer unwrapping/optional binding, you can use
optional chaining:

people?.flatMap({ $0.id }).forEach {
    print($0)
}

If people is nil, then flatMap() is not applied. Otherwise
it returns an array of the non-nil ids, which are enumerated with
forEach().

I think that all these methods (as well as your first method) are "Swifty",
you have to decide how compact your code should be.


Elegant way of processing an "options" parameter

You could do something like this to clean things up a little:

options = options || {};

// Set to Default values first
this.weekdayNames = {
  "long": [...],
  "short": [...]
};

// Then check to see if we need to override
if ( options.weekdayNames ){
  for ( var key in options.weekdayNames ){
    this.weekdayNames[ key ] = options.weekdayNames[ key ];
  }
}

Furthermore, something like lodash's defaults function https://lodash.com/docs#defaults may be of use.


You have a bug, if you remove an item in your for loop without breaking you get an IndexError.
Instead use a worse set so that you know what to skip.
What you seem to be doing is performing a sort, and so if you make a cmp function you can use sorted.
To do this you need to use functools.cmp_to_key and then you can itertools.takewhile.

And so I'd use:

import functools
import itertools
from typing import Set, List

class Term(int):
    def is_better_than(self, other):
        return self // 2 > other // 2

def cmp(self: Term, other: Term):
    if self.is_better_than(other):
        return 1
    if other.is_better_than(self):
        return -1
    return 0

def get_best_terms(terms: Set[Term]) -> List[Term]:
    if not terms:
        return []
    terms = sorted(terms, key=functools.cmp_to_key(cmp), reverse=True)
    best = terms[0]
    return list(itertools.takewhile(lambda i: not best.is_better_than(i), terms))

print(get_best_terms(map(Term, [1, 2, 3, 4, 5])))
print(get_best_terms(map(Term, [1, 2, 3, 4])))
print(get_best_terms(map(Term, [5, 1, 2, 4, 3])))
print(get_best_terms(map(Term, [5, 1, 4, 3])))

This can however be simplified if Terms are comparable, as you won't need to use key and can remove the need for a lambda.

@functools.total_ordering
class Term(int):
    def __gt__(self, other: Term) -> bool:
        return self // 2 > other // 2

    def __eq__(self, other: Term) -> bool:
        return self // 2 == other // 2

def get_best_terms(terms: Set[Term]) -> List[Term]:
    if not terms:
        return []
    terms = sorted(terms, reverse=True)
    return list(itertools.takewhile(terms[0].__eq__, terms))


Numeric selfmade CAPTCHA in Windows application

Option Explicit On
From what's an option strict and explicit?

Option Strict "restricts implicit data type conversions to only widening conversions". See here. With this option enabled, you can't accidentally convert one data type to another that is less precise (e.g. from an Integer to a Byte). Again, an option that should be turned on by default.

So after turning Option Strict On you will get 2 errors at these lines
lblfirst.Text = Rand.Next(0, 10) 'first random number
lblsecond.Text = Rand.Next(0, 10) 'second random number

stating "Option Strict On prohibits implicit conversion of Integer to String" (my translation from german).
Now you might think that's a bad thing, but it isn't. It will just show you where you need some work to do.
And for this 2 errors it is also quite easy, you need only to call the ToString() method of the Integer which is returned by calling the Rand.Next() method and there is the next problem.
Variables should use camelCase for their names and also the names should be descriptive so you won't need any comments for these variables anymore, so let us do it right and rename op to operandType and also Rand to randomizer
Dim randomizer As New System.Random
Dim operandType as Integer = 0

operandType = randomizer.Next(0, 3)
lblfirst.Text = randomizer.Next(0, 10).ToString() 'first random number
lblsecond.Text = randomizer.Next(0, 10).ToString() 'second random number

But wait, you are creating Integers convert them to Strings which you assign to the Text property of the labels which you are converting to Integers again inside the check_Click() method. That can be done better. Let declare some variables on class level to do this.
Private firstNumber As Integer = 0
Private secondNumber As Integer = 0

and change the lines above to
firstNumber = randomizer.Next(0, 10)
lblfirst.Text = firstNumber.ToString() 'first random number

secondNumber = randomizer.Next(0, 10)
lblsecond.Text = secondNumber.ToString() 'second random number

now we can use firstNumber and secondNumber in the check_Click method without using the String to Integer conversation (I will later talk about this also).
But wait, we can do better... Why don't we calculate the desired result at the time we generate the captcha ? Let us declare another Integer variable to hold the result
Private internalResult As Integer = 0

and use it
If operandType = 0 Then ' Operator selection
    internalResult = firstNumber + secondNumber
ElseIf operandType = 1 Then
    internalResult = firstNumber - secondNumber
ElseIf operandType = 2 Then
    internalResult = firstNumber * secondNumber
End If

So looking at this If..ElseIf..ElseIf I see 2 things, operandType is in the Range[0..2] which should be expressed as an enum (which I will lend from ckuhn203's answer) and the If..ElseIf.. should be a Select Case . We need also to change
Private operandType As Integer

to
Private operandType As Operand

next we add the enum
Enum Operand
    Add
    Substract
    Multiply
End Enum

and implement the Select..Case
Select Case operandType
    Case Operand.Add
        internalResult = firstNumber + secondNumber
    Case Operand.Substract
        internalResult = firstNumber - secondNumber
    Case Operand.Multiply
        internalResult = firstNumber * secondNumber
End Select

Now let us talk about conversion from String to Integer by taking a look at the last few lines of your check_Click() method
If output = CInt(txtResult.Text) Then
    MsgBox("Successfully varified")
Else
    MsgBox("Varification Faild")
End If

You are calling CInt(txtResult.Text). Assume the user will enter "lala" in the textbox. This will result in an InvalidCastException. A better way would be to use Integer.TryParse() which as the name implies tries to parse a String to an Integer. If this succeeds the method returns true otherwise it will return false. So let us use it
If (Integer.TryParse(txtResult.Text, output) AndAlso output = internalResult) Then
    MsgBox("Successfully verified")
Else
    MsgBox("Verification failed")
End If

Wait, what is this AndAlso ? AndAlso performs a short-circuiting logical conjunction on two expressions. So this means, that the right part of the AndAlso will only be evaluated, if the left part is true.
As we have, putting aside the last part, only code which belongs to the captcha generating and checking, so it would be a good thing to create a class of it
Public Class Captcha

    Private Enum Operand
        Add
        Substract
        Multiply
    End Enum

    Private firstNumber As Integer = 0
    Private secondNumber As Integer = 0
    Private internalResult As Integer = 0
    Private operandType As Operand
    Private result As Integer = 0
    Private randomizer As New Random()

    Public Function IsValid(answer As String) As Boolean
        internalResult = CalculateResult()
        Return (Integer.TryParse(answer, result) AndAlso result = internalResult)
    End Function

    Private Function CalculateResult() As Integer
        Dim result As Integer = 0

        Select Case operandType
            Case Operand.Add
                result = firstNumber + secondNumber
            Case Operand.Substract
                result = firstNumber - secondNumber
            Case Operand.Multiply
                result = firstNumber * secondNumber
        End Select

        Return result
    End Function

    Public Function Generate() As String
        Dim generatedCaptcha As String = String.Empty

        operandType = CType(randomizer.Next(0, 3), Operand)

        Select Case operandType
            Case Operand.Add
                generatedCaptcha = " + "
            Case Operand.Substract
                generatedCaptcha = " - "
            Case Operand.Multiply
                generatedCaptcha = " * "
        End Select

        firstNumber = randomizer.Next(0, 10)
        secondNumber = randomizer.Next(0, 10)

        Return firstNumber.ToString() & generatedCaptcha & secondNumber.ToString()
    End Function
End Class

Now you need only one label to show the captcha which I have named captchaLabel and your code looks fine and tidy
Dim _captcha As New Captcha()

Private Sub Generate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Generate.Click

    captchaLabel.Text = _captcha.Generate()

End Sub

Private Sub check_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles check.Click

    If _captcha.IsValid(txtResult.Text) Then
        MessageBox.Show("Successfully verified")
    Else
        MessageBox.Show("Verification Failed")
    End If

End Sub

Side Note
As I see that you are comming from VB6, I want to encourage you to learn the .NET way of these things. So skip using MsgBox(),CInt(), Mid() etc, as these are only kept to stay backward compatible.


int firstCandidate = 0;
int secondCandidate = 0;
int max = 0;

None of these need as wide a scope as they have. In particular, firstCandidate and secondCandidate are only used inside the nested loop, and are initialised every time they're used. They should be pushed in (if not eliminated...)

        firstCandidate = 0;
        secondCandidate = 0;

        if (j - 1 >= 0)
        {
            firstCandidate = numbers[i][j] + numbers[i - 1][j - 1];
        }

        if (j < numbers[i - 1].Length)
        {
            secondCandidate = numbers[i][j] + numbers[i - 1][j];
        }

        numbers[i][j] = firstCandidate > secondCandidate ? firstCandidate : secondCandidate;

This can be simplified slightly with a simple algebraic rearrangement to factor out the numbers[i][j] from the two candidates, since we know that at least one candidate must exist. (Note that by using int.MinValue we also fix something which could be argued to be a bug, unless the spec clearly states that the triangle will never contain negative numbers).

I agree with TarkaDaal that Math.Max is slightly more readable. And I would also find it more readable with ternary operators. Bearing in mind the scope change mentioned above, I get:

        int firstCandidate = j > 0 ? numbers[i - 1][j - 1] : int.MinValue;
        int secondCandidate = j < numbers[i - 1].Length ? numbers[i - 1][j] : int.MinValue;
        numbers[i][j] += Math.Max(firstCandidate, secondCandidate);

To find the maximum of an array, Linq is more readable and you won't notice any speed difference.

Summarising, I would rewrite the d.p. method as

static int GetMaxSum(int[][] numbers)
{
    for(int i = 1; i < numbers.Length; i++)
    {
        for(int j = 0; j < numbers[i].Length; j++)
        {
            int firstCandidate = j > 0 ? numbers[i - 1][j - 1] : int.MinValue;
            int secondCandidate = j < numbers[i - 1].Length ? numbers[i - 1][j] : int.MinValue;
            numbers[i][j] += Math.Max(firstCandidate, secondCandidate);
        }
    }

    return numbers[numbers.Length - 1].Max();
}


Find the longest line in 2D (MxM) array (vertical, horizontal, or diagonal)

In worst case (array that has only 1, no 0) you are doing M operations for each cell in MxM for a total of M^3 operations. You can reduce it to M^2 if you remember the results for previous row (for vertical, LD, RD) and current(horizontal). If the cell is 1 increment the counters, otherwise reset them to zero.


Checking if two dates are within 15 minutes of each other

Naming:

Method names should contain a verb and describe exactly what they are doing. For example, look at DateComparison. That sounds more like a type name to me, and I have no idea what the method will do by its name alone.

StripMilliseconds and GetTotalSeconds are much better.

I'd suggest this is as an alternate solution:

public static class TokenValidator
{
    private const int aliveDurationMinutes = 15;

    /// <summary>
    /// Checks if the token is still alive with a 1-second tolerance.
    /// </summary>
    public static bool CheckTokenAlive(DateTime created, DateTime timeToCompare)
    {
        TimeSpan elapsedTime = timeToCompare - created;

        return (elapsedTime.TotalSeconds > -1 && elapsedTime.TotalSeconds < 0) // up to 1 second before
               || (elapsedTime.TotalSeconds >= 0 && Math.Floor(elapsedTime.TotalSeconds) <= aliveDurationMinutes * 60); // up to 15 minutes later
    }
}

I use Math.Floor on the TotalSeconds to add the 1-second tolerance. You can be 0.9999 of a second over and still evaluate as true. You could have done a strictly less than with ((aliveDurationMinutes * 60) + 1) instead.


Populate two arrays with two different SQL queries

There are two possible answers to this question, a generalized one and a specific one.

To help with such questions in general, there is one programming concept which is often underestimated by PHP users. It is called user-defined functions

In a nutshell, you can write a code once and then use it any number of times.

function getArrayFromSql($db, $sql)
{
    $db->setQuery($sql);
    $rows = $db->loadRowList();
    $output = array();
    foreach ($rows as $row) {
        array_push($output, $row);
    }
    return $data;
}

Here you created a function which you can use any number of times:

$sql = "Select ranchstyle from information";
$output = getArrayFromSql($db, $sql);
$data = json_encode($output[0]);

$sql = "Select maestro from musicinfo";
$output = getArrayFromSql($db, $sql);
$data1 = json_encode($output[0]);

Whereas for the specific answer we need to review your code more closely. It does unnecessary job all the time.

First, you are making a useless call to $db->getQuery(true);, as with the very next step the $sql variable gets overwritten.

Second, you actually have an array already, as $db->loadRowList(); gives you a first class array. But for some reason you are duplicating it into $data. So your code actually should be

$sql = "Select ranchstyle from information";
$db->setQuery($sql);
$rows = $db->loadRowList();
$data = json_encode($rows[0]);

$sql = "Select maestro from musicinfo";
$db->setQuery($sql);
$rows = $db->loadRowList();
$data1 = json_encode($rows[0]);

Third, given you are encoding only the first item of the array, you seems don't need an array at all, so select and fetch one line only.

$sql = "Select ranchstyle from information limit 1";
$db->setQuery($sql);
$row = $db->loadRow();
$data = json_encode($row);

$sql = "Select maestro from musicinfo limit 1";
$db->setQuery($sql);
$row = $db->loadRow();
$data1 = json_encode($row);


It would be easier to follow the getProductListByUser method if you use two ResponseJSON instance. One for normal execution and one for the exceptional cases:

try {
    ...

    final ResponseJSON responseJSON = new ResponseJSON();
    ...

    responseJSON.setStatus(Constants.SUCCESS);
    responseJSON.add("items", productList);
    return responseJSON.get();
} catch (final Exception e) {
    final ResponseJSON responseJSON = new ResponseJSON();
    responseJSON.setStatus(Constants.FAIL);
    responseJSON.setMessage(e.getMessage());
    logger.error(e.getMessage());
    return responseJSON.get();
}

It also ensures that nobody modifies accidentally the exception case result in the try block and there isn't any incomplete ProductInfo data in the error response.


There are few places you can make this code faster and more efficient.

Most notably, this block (repeated twice):

FileName = location & file
Set wb1 = Workbooks.Open(FileName)
Cells.Copy
wb2.Activate
Sheet7.Activate
Cells.Select
ActiveSheet.Paste
wb1.Close

can be adjusted to this:

Set wb1 = Workbooks.Open(FileName)
Set ws1 = wb1.Worksheets(1) 'make sure to Dim ws1 as Worksheet

With ws1
    'this section will grab the last row and column of actual data on the sheet, instead of copying **every** cell
    'also assumes headers in column A with no data going past left most column in row 1
    Dim lRow as Long, lCol as Long
    lRow = .Range("A" & .Rows.Count).End(xlup).Row
    lCol = .Cells(1,.Columns.Count).End(xlToLeft).Column

    .Range(.Range("A1"),.Cells(lRow,lCol)).Copy wb2.Worksheets("Sheet7").Range("A1") 'change name as needed

    .Close True
End With

I'll try to do a more full review later, but have to leave now.


Well, there's a lott to say:

K and V are the traditional template-arguments for keys and values in C++.
Why do you use J and K respectively KEY and VALUE instead?
List::Node is only instantiated at one place, where all three members are set. Why then does it have a constructor at all, and one setting the last one to nullptr at that?
Default copy- and move- construction and assignment are completely unsuited to your List, as it owns its nodes. Leaving them leads to double-deletes and abandoned nodes. Look at the rule of three.

Also worth a look are inclass-initializers (for head).
deleteNode looks more like reset, and should zero head or be inlined into the destructor. As-is, it leaves head dangling...
The same comments apply to copying / moving / assigning myHash as to List.
The myHash dtor leaks the array of buckets...
contains should return the condition directly, instead of putting it into an if-clause. if(somebool) return true; else return false; is a bit wordy.
Your traverse-functions would be more appropriately named dump or some such... Anyway, why don't you overload operator>>(std::ostream, yourtypehere) instead?
Your hash-function runs afool of the fact that only the type itself can know which parts are relevant and how to hash them. Take a look at the design of std::hash.
Next, I would suggest embracing auto, see Almost Always Auto.


Naming problem or design issue.  The first thing check_hand() does is to re-order the data.  I'd expect check_hand() to not alter hand, base on its name - it is a check.  Alternatively  just re-name it sort_check_hand().   Yet later code make a copy in temp[].  Better to copy into temp[] and then sort temp[], leaving hand[] alone.

//enum poker_hands check_hand(vector *hand) {
//  sort_hand(hand);
enum poker_hands sort_check_hand(vector *hand) {
  sort_hand(hand);

Code to detect a straight is redundant in flush strait and normal straight calculate.  Need only one.
Group detection.  Some poke like games find the best hand out of 5 cards (usual) or more (like 7 in 7 card stud) or betting order based on incomplete hands (1 to 9) cards.  A hand assessment that does not depend on 5 cards is more useful.
Rating.  Returning info as what kind of full house (Jacks over fives) is useful info for many games.  This code only returns fullhouse, three_kind etc, yet only needs a little more code to report the hand details.
Minor: Code for understanding.  By decrementing the smaller group count, group[2] only reports the numbers of pairs, not the sum of numbers of pairs, triples and 4-of-a kind.

// original
for(int i = 0; i < MAXHAND; ++i) {
  int rank = temp[i]->nType;  // Get each card's type
  rankcount[rank]++;      // Increment each rank index
  group[rankcount[rank]]++;   // increment each rank's count index
}

if ( group[3] && group[2] > 1 ) // Found 3 of a kind and found another pair
  return fullhouse;

// suggested revision
for(int i = 0; i < MAXHAND; ++i) {
  int rank = temp[i]->nType;
  group[rankcount[rank]]--;   // add
  rankcount[rank]++;
  group[rankcount[rank]]++;
}

if (group[3] > 0 && group[2] > 0) {
  return fullhouse;


Counting the number of words in a string using C

As has already been said, your code is not very robust and whilst it will work for some happy path scenarios, there is a lot of scope for error.

Variable initialisation

You don't initialise line.  Consequently it has an undefined value.  In local testing this isn't going to be a huge problem because you call fgets and read from stdin into the variable.  However, as indicated by @πάντα-ῥεῖ's example this isn't always the case.  It's very possible for calls to fgets to fail in which case line will contain whatever it is initialised to.

Unless you're really sure you don't need it, err on the side of caution and initialise your variables:

char line[1000]="";

Error Checking

As I've said, fgets can fail.  When it does, it returns NULL.  You're not currently checking the fgets call's return value.  In most cases when you're dealing with stdin, you shouldn't encounter errors so you can avoid the need to check the return value through correct variable initialisation.  However, if you're not going to initialise your variables it's a good idea to check if fgets returns a value to indicate that it has successfully read something.

End of line

fgets will read until the end of either the buffer size supplied or the end of line, whichever comes first.  If it reaches the end of the buffer (sizeof(line)), then the buffer will be NULL terminated.  If on the other hand
it reads to the end of line, the buffer will include an end of line character '\n' before the NULL termination.  At the moment, you're treating this end of line character as part of a word which is probably incorrect.

What's a word?

Currently your method is actually returning the number of spaces in the input string, plus 1.  This works for simple cases where you assume that you start with a word and any space will be followed by a new word.  However, there are lots of edge cases where this isn't going to be true.  I put a double space after a full stop, should that really count as two words?  If I have nothing but spaces in the string I would expect 0, that's not what I get etc.

It may be that for your usage, your definition of a word is enough, however it doesn't feel like the right definition.  It seems like groups of whitespace should be treated as a single word boundary, rather than always being treated as the start of a new word.  You have decided that punctuation on its own is a word, does that really make sense?

Whitespace Vs ' '

Currently, you're only recognising actual space characters as word separators.  This may be correct for you, however as suggested by @Incomputable you could use isspace to check for a wider range of whitespace characters.  This would make your code more robust and able to deal with other whitespace characters like tabs.

Output considerately

puts automatically appends a newline to the end of the string it writes to stdout.  This isn't the case for printf, you need to append it yourself.  You don't currently append a new line, so it's messy for the user.

Naming & Comments

Comments should tell you add useful insight into what's going on in your code.  The comment at the top of the file is good, it contains a description of your specification for a word.  This is useful, although it's in the wrong place.  It's a description of what the word_count method does, why isn't it directly above the method?

You also have this comment:

int count = 0; /*Number of words*/

If you give count a proper name, then you don't need the comment:

int wordCount = 0;

Indentation

Your file indentation seems a bit off.  It may be a copy/paste error, however I'd expect method signatures to start at the extreme left of the line, not floating one indentation in.  If it is a copy/paste error, in future, try to make sure your code in the question looks like it does in your editor.


I assume is_good_response is just checking for a 200 response code.
Merge is_good_response, get_html_content and the insides of your for-loop in your main together.

This makes the main code:

from requests import get
from bs4 import BeautifulSoup

if __name__ == '__main__':
    baseUrl = 'https://www.bikesales.com.au/'
    url = 'https://www.bikesales.com.au/bikes/?q=Service%3D%5BBikesales%5D'

    content = get_html_content(url)
    html = BeautifulSoup(content, 'html.parser')
    BikeList = html.findAll("a", {"class": "item-link-container"})

    for bike in bike_list:
        individualBikeURL = bike.attrs['href']
        bike_content = get_bike(baseUrl+individualBikeURL)

Where we will be focusing on:

def get_bike(url):
    multiplier = 1
    while (BikeContent == None):
        time.sleep(2*multiplier)
        try:
            with closing(get(url)) as resp:
                content_type = resp.headers['Content-Type'].lower()
                if 200 <= resp.status_code < 300:
                    return resp.content
        except RequestException as e:
            print("Error during requests to {0} : {1}".format(url, str(e)))
        if (multiplier < 16):
            multiplier *= 2
    return None

Allow a retry argument. Retry should also act differently on different values:

None - Don't retry.
-1 - Retry infinatly.
n - Retry until \$2^n\$.
iterator - loop through for the delays

We can also add another function to work the same way your previous code did.
You shouldn't need to use contextlib.closing, as Response.close "should not normally need to be called explicitly."
You don't need content_type in get_bike.
You should use *args and **kwargs so you can use requests.gets arguments if you ever need to.
You can allow this to work with post and other request methods if you take the method as a parameter.

import itertools
import collections.abc

import requests.exceptions

def request(method, retry=None, *args, **kwargs):
    if retry is None:
        retry = iter()
    elif retry == -1:
        retry = (2**i for i in itertools.count())
    elif isinstance(retry, int):
        retry = (2**i for i in range(retry))
    elif isinstance(retry, collections.abc.Iterable):
        pass
    else:
        raise ValueError('Unknown retry {retry}'.format(retry=retry))

    for sleep in itertools.chain([0], retry):
        if sleep:
            time.sleep(sleep)
        try:
            resp = method(*args, **kwargs)
            if 200 <= resp.status_code < 300:
                return resp.content
        except requests.exceptions.RequestException as e:
            print('Error during requests to {0} : {1}'.format(url, str(e)))
    return None

def bike_retrys():
    for i in range(5):
        yield 2**i
    while True:
        yield 16

To improve the rest of the code:

Use snake case.
Constants should be in upper snake case.
Use the above code.
Use import requests, rather than from requests import get.
You can make a little helper function to call request, so usage is cleaner.

import requests
from bs4 import BeautifulSoup

def get_bike(*args, **kwargs):
    return request(requests.get, bike_retrys(), *args, **kwargs)

if __name__ == '__main__':
    BASE_URL = 'https://www.bikesales.com.au/'
    url = 'https://www.bikesales.com.au/bikes/?q=Service%3D%5BBikesales%5D'

    content = get_bike(url)
    html = BeautifulSoup(content, 'html.parser')
    bike_list = html.findAll("a", {"class": "item-link-container"})

    for bike in bike_list:
        bike_content = get_bike(BASE_URL + bike.attrs['href'])


Create User profile with separate social media data

public UserProfile AddSocialLink(string userName, UserSocialLink userSocialLink, string socialLinkType)

Shouldn't the socialLinkType be a property of the UserSocialLink class? It seems odd to me that the code has to pass a string along with the object in order to tell the method what type it is. That said, I really do like that you're checking the database to make sure the type is valid. Now that I think of it, why pass the user name as a string? Wouldn't it be a simpler API to pass a UserProfile in? At least, it would be more consistent for the dev using the UserProfileService.

This code is a great example of why we should all use proper indentation and braces around if statements.

var linkType = db.SocialLinkTypes.SingleOrDefault(p => p.LinkType.ToUpper() == socialLinkType.ToUpper());
if (linkType == null)
    throw new Exception("Social Media Type Not Found");
userSocialLink.Created = now;
userSocialLink.Updated = now;
userSocialLink.SocialLinkTypeID = linkType.Id;
db.UserSocialLinks.Add(userSocialLink);
db.SaveChanges();
return userProfile;

At a glance, it looks like the userSocialLink only gets it's properties set if (linkType == null) and after an exception is thrown. Of course, this is ridiculous and not what is actually happening, but braces make that crystal clear to Mr. Maintainer.

var linkType = db.SocialLinkTypes.SingleOrDefault(p => p.LinkType.ToUpper() == socialLinkType.ToUpper());
if (linkType == null)
{
    throw new Exception("Social Media Type Not Found");
}
userSocialLink.Created = now;
userSocialLink.Updated = now;
userSocialLink.SocialLinkTypeID = linkType.Id;
db.UserSocialLinks.Add(userSocialLink);
db.SaveChanges();
return userProfile;


Calculate the difference between the elements in a list

Your implementation is good and easy to understand.

When using List<Double> for input data, be sure to use an efficient implementation. Otherwise you could get really bad read performance. E.g., when you access elements by index, ArrayList<Double> will be much faster than LinkedList<Double> (\$O(n)\$ vs. \$O(n^2)\$ for your getSpeedS).

If you must support arbitrary types of List<Double> you would probably better off when you use Iterators instead of element access by index.

If you use an ArrayList and know its final size in advance, always construct it with the capacity needed (new ArrayList<>(size)). This avoids reallocation and copying of the internal array that holds the elements while adding elements.

If you need maximum performance, then use arrays (double[]) instead of lists. For large data sets they can speed up the creation of the input in-memory objects by factors greater than two. Additionally they may give you a significant advantage in read performance due to better utilization of processor caches compared to list implementations.


From the things I see in your code it looks to me like you are quite new to Object Oriented Programming (OOP), so I will try to keep that in mind during this review.

Basic OOP

The __construct() method of a class is called only once per object of that class, when it is instantiated like so: $db = new Database(). Your class contains a field $db_connection, which default to false. Since the __construct() method is called only when the object is being instantiated, there is no reason to check if ($this->db_connection != false), since $db_connection will always be false for that object.

Static vs non-static

It seems to me like you are misunderstanding how regular class fields and static class fields work. Lets do a quick example based on your code:

$database1 = new Database();
$database2 = new Database();

I now have two instantiated Database objects. Lets assume that when I created $database1, the connection succeeded, so a PDO object will be assigned to $db_connection:

// Will print some stuff about the PDO object
print_r($database1->db_connection);

However, when creating $database2, the $db_connection field will be set to false for $database2, because it is in no way related to the $db_connection field of any other instantiated Database object.

If you were to make $db_connection a static field, then they would be shared between all class instances, because it would be a field on the actual class itself, and not on the instantiated objects.

Using fields

What else is weird is that you assign the global variables DB_HOST, DB_NAME, DB_PASS and DB_USER to some private fields of the class, and then in the constructor you do not use the private fields, but you use the global variables again. This is very unusual and should definitely be removed like so:

$this->db_connection = new PDO('mysql:host='. $this->host .';dbname=' . $this->user .';charset=utf8', $this->name, $this->pass);

Now that we have that out of the way, you should not be setting private fields of a class based on some global variable that might be there. You should change it so they have to be passed to the constructor like so:

public function __construct($host, $user, $password, $name) {
    // Use the variables provided as arguments to the constructor here
}

This makes your class less dependent on your specific setup and global variables and allows for easier reuse and testing of your class. If you for whatever reason need to setup a connection to another database, you can reuse the class with different parameters. You can now use it like this:

$database = new Database(DB_HOST, DB_USER, DB_PASS, DB_NAME);

Furthermore, now that these values are passed as arguments to the constructor, you no longer need the fields to store them in, because you only use them in the constructor!

At this stage into the code review, your class would look something like this:

<?php
class database {
    public $db_connection = false;
    public $logs = array();

    public function __construct($host, $user, $pass, $name) {
        $this->logs[] = "Attempting to connect to the database.";

        try{
            $this->db_connection = new PDO('mysql:host='. $host .';dbname=' . $name .';charset=utf8', $user, $pass);
            $this->logs[] = "A new database connection has been established.";
        }
        catch (PDOException $e) {
                $this->logs[] = "A new database connection could not be established.";
        }
    }
}

One small nitpick, you should get into the habit of not ending PHP files with the ?> closing tag. See this question for an explanation.

Logging with interfaces

One final thing I will just briefly mention: You shouldn't be logging like this. You should be logging to an interface. Consider the interface:

interface Logger {
    public function log($data)
}

Now your Database class could take an optional Logger object in the constructor like so:

public function __construct($host, $user, $pass, $name, Logger $logger = NULL) {
    $this->logger = logger;
}

Now you can replace $this->logs[] = "..."; with $this->logger->log("...");. The beauty of this is that your Database class no longer cares how the data is being logged, only that it is being logged. You could create a ConsoleLogger that logs to the console or a FileLogger, that logs the data to a file. Any of these could be passed to the constructor of a new Database object, as long as they implement the Logger interface.

Edit: The Singleton

Since you verified that you attempted to make a singleton, I will talk about singletons for a bit. By definition, a singleton is a class that can only be instantiated once. What does this mean? This means that you should not be able to do this:

$db1 = new DatabaseSingleton();
$db2 = new DatabaseSingleton();

You have to ensure that only one instance of this class is made. You might get sneaky and attempt to do something like this:

// Don't do this!
class DatabaseSingleton() {
    private static $instance_count = 0;

    public function __construct() {
        if (self::$instance_count > 0) {
            throw new Exception("This singleton has already been instantiated!");
        }

        self::$instance_count += 1;
    }
}

This would technically do the trick, as a second instantiation of the class would throw an exception. Notice how I have used a static variable to achieve this.

The "singleton" above is actually a very bad implementation and should be avoided. The generally accepted way of creating a singleton in PHP looks something like this:

public class DatabaseSingleton {
    private static $instance;

    private __construct() {

    }

    public function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new DatabaseSingleton();
        }

        return self::$instance;
    }
}

A few clever tricks have been used here. First of all, I have made the constructor private! This means that the constructor can only be called from within the class itself, which sounds weird, but is the key to singletons. It means you can no longer do this outside of the DatabaseSingleton class:

// An error occurs because the constructor is private
$db = new DatabaseSingleton();

I have also created a public and static getInstance() method. This method first checks if the static field self::$instance already contains something. If it does not, then it instantiates a new DatabaseSingleton object and stores it in the self::$instance field. Finally it returns the field. The second time this method is called, the if statement will be skipped because self::$intsance is no longer empty.

The instance can now be retrieved as follows from anywhere in the code:

$db = DatabaseSingleton::getInstance();

Tada! There you have your singleton. But notice how I said anywhere. This basically means that you now have a global variable, but enclosed in a class. Singletons can sometimes be useful, but you should think real hard about whether or not you really need/want one before using this design pattern.

I hope this little extra section was informative for you!


I don't know if there is a way to avoid the nested loop in this case because you need to do a calc that involves every inner loop index with every outer loop index.
But I think that is not necessary to calculate row * mapWidth in every iteration in the inner loop, once that both variables are available outside it
for (let row = 0; row < mapHeight; row++) {
    //...
    let cached = row * mapWidth;

    for (let column = 0; column < mapWidth; column++) {
        nodeIndex = column + cached;
        let colorIndex = myNodes[nodeIndex].colorIndex;

        //...
    }
//...
}


I'm concerned that make-suffix is sufficiently general that we'll have name collisions with other packages - or even new Emacs versions.  Perhaps prefix with some tag (I tend to begin names with my initials to disambiguate my own functions, for example; that would give you something like an/make-suffix).

Instead of binding a lambda to the keystroke, prefer to give it a name.  That makes it easier to bind to other keys (perhaps interactively) and for Control+h k to give the best output.

Talking of which, let's have some docstrings, please!

Finally, since the function will work only on writable buffers, we should have (interactive "*") to avoid wasting effort when used in a read-only context.


I will be assuming that you use at least C++11. It also seems that you are coming from C, is that correct?

double (*matrix_a)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));:

There is no reason to use dynamic allocation, ncols and nrows are constant expressions!. Just use double matrix_a[ncols][nrows]; or better std::array<std::array<double,ncols>,nrows> matrix_a;. That said you usually want to have dynamic sizes or your matrix may be larger than the stack limit. Then you should use std::vector<std::vector<double>> matrix_a{nrows, {ncols}}. C-style arrays and dynamic allocation should always be limited as much as possible. Using proper class objects wrapping them is much safer. std::vector will take care of all memory management for you. If you are concerned that std::vector will layout rows non-continuously, then use std::vector<double> matrix_a{nrows*ncols} instead and properly access the elements by ncols*row+col.

Also, in C++, you do not use malloc and free. Instead you use new and delete. The difference is that new not only allocates memory but also constructs the object in that memory. In most cases you would need to manually construct the object in the allocated space (although for double it is technically ok here).
You should not declare a free method, but rather everything freeing memory belongs in the destructor, which is automatically called as soon as the object itself goes out of scope or is destroyed:

~matrix()
{
     free(matrix_a); // should be "delete[] matrix_a;"
     free(matrix_b); // ^^^
     free(matrix_c); // ^^^
}

Note that you would not need a destructor if you were using std::array or std::vector.

If you stick to dynamic memory allocation, you probably also need to implement a custom copy and/or move constructor and assignment operator.
The whole idea of a class is that it represents a certain closed/separate entity. Your class does not follow this, it is merely a wrapper to call the multilication method. If you were following OOP principles, you would create a class matrix holding one of the matrices with an overloaded operator+(const matrix&), operator*(const matrix&) and so on, then create two matrix instances in main and call * on them. Like so:

class Matrix {
private:
    std::size_t ncol;
    std::site_t nrow;
    std::vector<double> storage;
public:
    Matrix() : storage() {}
    Matrix(std::size_t ncol, std::size_t nrow) : ncol(ncol), nrow(nrow), storage(ncol*nrow) {}

    std::size_t getColCount() const { return ncol; }
    std::size_t getRowCount() const { return nrow; }

    double getAt(std::size_t col, std::size_t row) { [implement this] }
    Matrix operator+(const Matrix& other) const { [implement this] }
    Matrix operator*(const Matrix& other) const { [implement this] }
    [other operators...]

    static Matrix randomMatrix(std::size_t ncol, std::size_t nrow) { [ implement this ] }
};

int main() {
    Matrix matrixA = Matrix::randomMatrix();
    Matrix matrixB = Matrix::randomMatrix();
    Matrix matrixC = matrixA*matrixB;
}


Huffman encoding successive-merge function

It's been a while since I've done any Lisp/Scheme, but I'll make one style point and one algorithmic point.

Style point: it's usually more readable if you define structure projection functions with meaningful names rather than using car, cdr, etc.

Algorithmic point: the simplest way of doing this is to include some priority queue structure from the standard library.  Then you simply remove the two least items from the queue, create their combined Huffman tree, and reinsert them into the queue.  You're done when the queue contains only one item.


Rearranging DOM elements using inconsistent criteria

If I were to make any changes then this would be the code, using ES5, and reduce the number of functions a little, and variable assignments.

(function() {
  'use strict';

  var slice = Function.prototype.call.bind(Array.prototype.slice);
  var categoryOrder = {
    fruit: 0,
    vegetable: 1
  };

  function compareCategories(element1, element2) {
    var category1 = element1.getAttribute('data-category-name');
    var category2 = element2.getAttribute('data-category-name');
    if (category1 !== category2) {
      return categoryOrder[category1] - categoryOrder[category2];
    }
    return element1.getAttribute('data-item-id') - element2.getAttribute('data-item-id');
  }

  // dates are ISO-8601
  function compareTimestamps(element1, element2) {
    return element1.getAttribute('data-timestamp')
      .localeCompare(element2.getAttribute('data-timestamp'));
  }

  function makeRearrangeCallback(comparator, reportBody) {
    return function() {
      slice(document.getElementsByClassName('report-section'))
        .sort(comparator)
        .forEach(function(reportBlock) {
          reportBody.appendChild(reportBlock);
        });
    };
  }

  function addRearrangeCallbackToElement(elementId, comparator, reportBody) {
    document.getElementById(elementId)
      .addEventListener('click', makeRearrangeCallback(comparator, reportBody), false);
  }

  function main() {
    var reportBody = document.getElementById('report-body');
    addRearrangeCallbackToElement('sort-by-category', compareCategories, reportBody);
    addRearrangeCallbackToElement('sort-by-timestamp', compareTimestamps, reportBody);
  }

  window.addEventListener('load', main, false);
}());
<button id='sort-by-category'>Category</button>
<button id='sort-by-timestamp'>Timestamp</button>

    ..a

    ..b

    ..c


Pythonic code to convert 3 digit number into all possible letter combinations

First, Python 2 is going to be no longer supported in less than a year. If you are starting to learn Python now, learn Python 3. In your code the only differences are that print is a function now and no longer an expression (so you need ()) and that raw_input was renamed input (and the Python 2 input basically no longer exists).

Your building of the root dictionary can be simplified a bit using a dictionary comprehension:

from string import ascii_lowercase

num_to_letter = {str(i): c for i, c in enumerate(ascii_lowercase, 1)}

For the first three different permutations you can use tuple unpacking:

first, second, third = sequence_to_convert

Note that you are currently not validating if the user entered a valid string. The minimum you probably want is this:

from string import digits
digits = set(digits)

sequence_to_convert = input('Enter three digit number \n')
if len(sequence_to_convert) != 3:
    raise ValueError("Entered sequence not the right length (3)")
if not all(x in digits for x in sequence_to_convert):
    raise ValueError("Invalid characters in input (only digits allowed)")

(A previous version of this answer used str.isdigit, but that unfortunately returns true for digitlike strings such as "¹"...)

Your testing and printing can also be made a bit easier by putting the possible permutations into a list and iterating over it:

permutations = [(first, second, third), (first, fifth), (fourth, third)]
for permutation in permutations:
    if all(x in num_to_letter for x in permutation):
        print("".join(map(num_to_letter.get, permutation)))

However, in the end you would probably want to make this more extendable (especially to strings longer than three). For that you would need a way to get all possible one or two letter combinations, and that is hard. It is probably doable with an algorithm similar to this one, but it might be worth it to ask a question on Stack Overflow about this.


Removing stop words from a Spark Dataframe

In case it helps anybody, I needed to do the following to fix my code:

add import org.apache.spark.sql.DataFrame
Make sure my DataFrame's were capitalized correctly.
add dfNoStop at the end of the function, to stop it returning unit.
make the call val Array(dfNoStop, dfNoStop1)=Array(dfHive, dfHive1).map(RemoveStopwords)


Example using Object lock synchronized blocks

It does look sound to me with one exception that you need to be aware of, as far as I can see:
if (!string.isEmpty()) {
    synchronized (lock) {
        lock.notify();
    }
    string = "";
}

The moment you set string to a new value, the first thread might not have visited the variable at this point. You can see that when outputting string in both threads. This is only important if thread #1 is going to do processing on the value.
Additionally, because of the Thread.sleep(200); you might miss input lines because string value might have changed an unidentified number of times during this period.

I mean, if I don't add the 200ms delay in t2 execution, the thread will consume a lot of processing power, so, how can I create a listener behavior?

The same way you did between #2 and #1, notify #2 from #3.

To fix these issues, you want to use something like a BlockingQueue. Thread #3 pushes the line to the Queue, thread #2 dequeues the next value and notifies #1. Or, #2 pushes it to a second Queue for #1.


Change upper or lowercase vowels to [0,1,2,3,4] respectively and leave the rest the same

Use string.maketrans().

from string import maketrans

input = "aeiouAEIOU"
output = '0123401234'
trans = maketrans(input,output)
str = 'This is a Q&A site, not a discussiOn forUm, so please make sure you answer the question.'
print str.translate(trans)

Output:

Th2s 2s 0 Q&0 s2t1, n3t 0 d2sc4ss23n f3r4m, s3 pl10s1 m0k1 s4r1 y34 0nsw1r th1 q41st23n.


All in all, your code is quite well-structured. Here are a couple of suggestions for improvement:

Consider moving your styles to a resource dictionary:

<Window.Resources>
    <ResourceDictionary Source="Resources.xaml" />
</Window.Resources>

This will de-clutter your file and allow you to re-use the styles in other windows.
Collapse empty tags (use the self-closing syntax):

<Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition />
    <RowDefinition />
    <RowDefinition />
    <RowDefinition />
</Grid.RowDefinitions>

(the same goes for the ColumnDefinitions and any other empty tags)
Declare styles that affect all controls of one type without a key:

<Style TargetType="Button"> ... </Style>
<Style TargetType="Label"> ... </Style>

That way, you don't seperately have to set all the labels to labelStyle and all the  buttons to buttonsStyle, just remove all occurences of the following two attributes:

Style="{StaticResource labelStyle}"
Style="{StaticResource buttonsStyle}"

The default value of Grid.Column and Grid.Row is 0, you can get away without setting it explicitly. And CheckBox.Checked is false by default. So you can remove all occurences of the following:

Grid.Column="0"
Grid.Row="0"
IsChecked="False"

Generally, in WPF, widths and heights are not explicitly stated. You should try to use relative and automatic dimensions where possible (which often requires choosing the correct container).
For instance, you could use relative sizing for your grid columns:

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="0.35*" />
    <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

In other situations, working with Margin can be a replacement for explicit pixel sizes. Remember that hard-coded sizes are an obstacle to localization (where long words in foreign languages are cropped) and less flexible.

These suggestions shrink your Window .xaml file from 54 to 37 lines (Resources.xaml has 14).